pax_global_header00006660000000000000000000000064125041300730014505gustar00rootroot0000000000000052 comment=a21567d28f3fc08cfcdd71048352c7c21ac8b09b pygments.rb-0.6.3/000077500000000000000000000000001250413007300137635ustar00rootroot00000000000000pygments.rb-0.6.3/.gitignore000066400000000000000000000000731250413007300157530ustar00rootroot00000000000000Gemfile.lock ext/Makefile lib/pygments_ext.* tmp pkg *.pyc pygments.rb-0.6.3/CHANGELOG.md000066400000000000000000000027451250413007300156040ustar00rootroot00000000000000changelog =========== Version 0.5.4 (Nov 3, 2013) ----------------------------- * Update lexers file Version 0.5.3 (Sep 17, 2013) ----------------------------- * Fixes for Slash lexer * Improve highlighting for Slash lexer * Upgrade to latest pygments (1.7, changes summary follows. See pygments changelog for details) * Add Clay lexer * Add Perl 6 lexer * Add Swig lexer * Add nesC lexer * Add BlitzBasic lexer * Add EBNF lexer * Add Igor Pro lexer * Add Rexx lexer * Add Agda lexer * Recognize vim modelines * Improve Python 3 lexer * Improve Opa lexer * Improve Julia lexer * Improve Lasso lexer * Improve Objective C/C++ lexer * Improve Ruby lexer * Improve Stan lexer * Improve JavaScript lexer * Improve HTTP lexer * Improve Koka lexer * Improve Haxe lexer * Improve Prolog lexer * Improve F# lexer Version 0.5.2 (July 17, 2013) ----------------------------- * Add Slash lexer Version 0.5.1 (June 25, 2013) ----------------------------- * Ensure compatability across distros by detecting if `python2` is available Version 0.5.0 (Apr 13, 2013) ----------------------------- * Use #rstrip to fix table mode bug Version 0.4.2 (Feb 25, 2013) ----------------------------- * Add new lexers, including custom lexers Version 0.3.7 (Jan 2, 2013) ----------------------------- * Fixed missing custom lexers * Added syntax highlighting for Hxml Version 0.3.4 (Dec 28, 2012) ----------------------------- * Add support for Windows * Add MIT license pygments.rb-0.6.3/Gemfile000066400000000000000000000000461250413007300152560ustar00rootroot00000000000000source "https://rubygems.org" gemspec pygments.rb-0.6.3/LICENSE000066400000000000000000000021211250413007300147640ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) Ted Nyman and Aman Gupta, 2012-2013 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pygments.rb-0.6.3/README.md000066400000000000000000000101461250413007300152440ustar00rootroot00000000000000# pygments.rb A Ruby wrapper for the Python [pygments syntax highlighter](http://pygments.org/). pygments.rb works by talking over a simple pipe to a long-lived Python child process. This library replaces [github/albino](https://github.com/github/albino), as well as a version of pygments.rb that used an embedded Python interpreter. Each Ruby process that runs has its own 'personal Python'; for example, 4 Unicorn workers will have one Python process each. If a Python process dies, a new one will be spawned on the next pygments.rb request. ## system requirements - Python 2.5, Python 2.6, or Python 2.7. You can always use Python 2.x from a `virtualenv` if your default Python install is 3.x. ## usage ``` ruby require 'pygments' ``` ``` ruby Pygments.highlight(File.read(__FILE__), :lexer => 'ruby') ``` Encoding and other lexer/formatter options can be passed in via an options hash: ``` ruby Pygments.highlight('code', :options => {:encoding => 'utf-8'}) ``` pygments.rb defaults to using an HTML formatter. To use a formatter other than `html`, specify it explicitly like so: ``` ruby Pygments.highlight('code', :formatter => 'bbcode') Pygments.highlight('code', :formatter => 'terminal') ``` To generate CSS for HTML formatted code, use the `#css` method: ``` ruby Pygments.css Pygments.css('.highlight') ``` To use a specific pygments style, pass the `:style` option to the `#css` method: ``` ruby Pygments.css(:style => "monokai") ``` Other Pygments high-level API methods are also available. These methods return arrays detailing all the available lexers, formatters, and styles. ``` ruby Pygments.lexers Pygments.formatters Pygments.styles ``` To use a custom pygments installation, specify the path to `Pygments#start`: ``` ruby Pygments.start("/path/to/pygments") ``` If you'd like logging, set the environmental variable `MENTOS_LOG` to a file path for your logfile. By default pygments.rb will timeout calls to pygments that take over 8 seconds. You can change this by setting the environmental variable `MENTOS_TIMEOUT` to a different positive integer value. ## benchmarks $ ruby bench.rb 50 Benchmarking.... Size: 698 bytes Iterations: 50 user system total real pygments popen 0.010000 0.010000 0.020000 ( 0.460370) pygments popen (process already started) 0.010000 0.000000 0.010000 ( 0.272975) pygments popen (process already started 2) 0.000000 0.000000 0.000000 ( 0.273589) $ ruby bench.rb 10 Benchmarking.... Size: 15523 bytes Iterations: 10 user system total real pygments popen 0.000000 0.000000 0.000000 ( 0.819419) pygments popen (process already started) 0.010000 0.000000 0.010000 ( 0.676515) pygments popen (process already started 2) 0.000000 0.010000 0.010000 ( 0.674189) ## license The MIT License (MIT) Copyright (c) Ted Nyman and Aman Gupta, 2012-2013 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pygments.rb-0.6.3/Rakefile000066400000000000000000000034641250413007300154370ustar00rootroot00000000000000#!/usr/bin/env rake require "bundler/gem_tasks" task :default => :test # ========================================================== # Packaging # ========================================================== GEMSPEC = eval(File.read('pygments.rb.gemspec')) require 'rubygems/package_task' # ========================================================== # Testing # ========================================================== require 'rake/testtask' Rake::TestTask.new 'test' do |t| t.test_files = FileList['test/test_*.rb'] t.ruby_opts = ['-rubygems'] end # ========================================================== # Benchmarking # ========================================================== task :bench do sh "ruby bench.rb" end # ========================================================== # Cache lexers # ========================================================== # Write all the lexers to a file for easy lookup task :lexers do sh "ruby cache-lexers.rb" end # ========================================================== # Vendor # ========================================================== namespace :vendor do file 'vendor/pygments-main' do |f| sh "hg clone https://bitbucket.org/birkenfeld/pygments-main #{f.name}" sh "hg --repository #{f.name} identify --id > #{f.name}/REVISION" rm_rf Dir["#{f.name}/.hg*"] end task :clobber do rm_rf 'vendor/pygments-main' end # Load all the custom lexers in the `vendor/custom_lexers` folder # and stick them in our custom Pygments vendor task :load_lexers do LEXERS_DIR = 'vendor/pygments-main/pygments/lexers' lexers = FileList['vendor/custom_lexers/*.py'] lexers.each { |l| FileUtils.copy l, LEXERS_DIR } FileUtils.cd(LEXERS_DIR) { sh "python _mapping.py" } end task :update => [:clobber, 'vendor/pygments-main', :load_lexers] end pygments.rb-0.6.3/bench.rb000066400000000000000000000014711250413007300153720ustar00rootroot00000000000000require File.join(File.dirname(__FILE__), '/lib/pygments.rb') require 'benchmark' include Benchmark # number of iterations num = ARGV[0] ? ARGV[0].to_i : 10 # we can also repeat the code itself repeats = ARGV[1] ? ARGV[1].to_i : 1 code = File.open('test/test_data.py').read.to_s * repeats puts "Benchmarking....\n" puts "Size: " + code.bytesize.to_s + " bytes\n" puts "Iterations: " + num.to_s + "\n" Benchmark.bm(40) do |x| x.report("pygments popen ") { for i in 1..num; Pygments.highlight(code, :lexer => 'python'); end } x.report("pygments popen (process already started) ") { for i in 1..num; Pygments.highlight(code, :lexer => 'python'); end } x.report("pygments popen (process already started 2) ") { for i in 1..num; Pygments.highlight(code, :lexer => 'python'); end } end pygments.rb-0.6.3/cache-lexers.rb000066400000000000000000000003351250413007300166540ustar00rootroot00000000000000require File.join(File.dirname(__FILE__), '/lib/pygments.rb') # Simple marshalling serialized_lexers = Marshal.dump(Pygments.lexers!) # Write to a file File.open("lexers", 'w') { |file| file.write(serialized_lexers) } pygments.rb-0.6.3/lexers000066400000000000000000001142571250413007300152220ustar00rootroot00000000000000{YI"Brainfuck:ET{ : nameI"Brainfuck;T: aliases[I"brainfuck;TI"bf;T:filenames[I" *.bf;TI"*.b;T:mimetypes[I"application/x-brainfuck;TI" dasm16;T{ ;I" dasm16;T;[I" DASM16;T;[I" *.dasm16;TI" *.dasm;T; [I"text/x-dasm16;TI" Puppet;T{ ;I" Puppet;T;[I" puppet;T;[I" *.pp;T; [I" Augeas;T{ ;I" Augeas;T;[I" augeas;T;[I" *.aug;T; [I" TOML;T{ ;I" TOML;T;[I" toml;T;[I" *.toml;T; [I" Slash;T{ ;I" Slash;T;[I" slash;T;[I" *.sl;T; [I" Cirru;T{ ;I" Cirru;T;[I" cirru;T;[I" *.cirru;TI" *.cr;T; [I"text/x-cirru;TI" Nimrod;T{ ;I" Nimrod;T;[I" nimrod;TI"nim;T;[I" *.nim;TI" *.nimrod;T; [I"text/x-nimrod;TI" Bash;T{ ;I" Bash;T;[I" bash;TI"sh;TI"ksh;T;[I" *.sh;TI" *.ksh;TI" *.bash;TI" *.ebuild;TI" *.eclass;TI" .bashrc;TI" bashrc;TI" .bash_*;TI" bash_*;TI" PKGBUILD;T; [I"application/x-sh;TI"application/x-shellscript;TI" Golo;T{ ;I" Golo;T;[I" golo;T;[I" *.golo;T; [I"CSS+Django/Jinja;T{ ;I"CSS+Django/Jinja;T;[I"css+django;TI"css+jinja;T;[; [I"text/css+django;TI"text/css+jinja;TI"Coldfusion HTML;T{ ;I"Coldfusion HTML;T;[I"cfm;T;[I" *.cfm;TI" *.cfml;T; [I"application/x-coldfusion;TI"Literate Agda;T{ ;I"Literate Agda;T;[I" lagda;TI"literate-agda;T;[I" *.lagda;T; [I"text/x-literate-agda;TI" Xtend;T{ ;I" Xtend;T;[I" xtend;T;[I" *.xtend;T; [I"text/x-xtend;TI"PowerShell;T{ ;I"PowerShell;T;[ I"powershell;TI" posh;TI"ps1;TI" psm1;T;[I" *.ps1;TI" *.psm1;T; [I"text/x-powershell;TI" Limbo;T{ ;I" Limbo;T;[I" limbo;T;[I"*.b;T; [I"text/limbo;TI" JAGS;T{ ;I" JAGS;T;[I" jags;T;[I" *.jag;TI" *.bug;T; [I"Kal;T{ ;I"Kal;T;[I"kal;T;[I" *.kal;T; [I" text/kal;TI"application/kal;TI"Dylan session;T{ ;I"Dylan session;T;[I"dylan-console;TI"dylan-repl;T;[I"*.dylan-console;T; [I"text/x-dylan-console;TI" Java;T{ ;I" Java;T;[I" java;T;[I" *.java;T; [I"text/x-java;TI" Nemerle;T{ ;I" Nemerle;T;[I" nemerle;T;[I"*.n;T; [I"text/x-nemerle;TI" CSS+Ruby;T{ ;I" CSS+Ruby;T;[I" css+erb;TI" css+ruby;T;[; [I"text/css+ruby;TI" MySQL;T{ ;I" MySQL;T;[I" mysql;T;[; [I"text/x-mysql;TI"C++;T{ ;I"C++;T;[I"cpp;TI"c++;T;[I" *.cpp;TI" *.hpp;TI" *.c++;TI" *.h++;TI" *.cc;TI" *.hh;TI" *.cxx;TI" *.hxx;TI"*.C;TI"*.H;TI" *.cp;TI" *.CPP;T; [I"text/x-c++hdr;TI"text/x-c++src;TI"CBM BASIC V2;T{ ;I"CBM BASIC V2;T;[I" cbmbas;T;[I" *.bas;T; [I"XML+Smarty;T{ ;I"XML+Smarty;T;[I"xml+smarty;T;[; [I"application/xml+smarty;TI"autohotkey;T{ ;I"autohotkey;T;[I"ahk;TI"autohotkey;T;[I" *.ahk;TI" *.ahkl;T; [I"text/x-autohotkey;TI"OpenEdge ABL;T{ ;I"OpenEdge ABL;T;[I" openedge;TI"abl;TI" progress;T;[I"*.p;TI" *.cls;T; [I"text/x-openedge;TI"application/x-openedge;TI" CMake;T{ ;I" CMake;T;[I" cmake;T;[I" *.cmake;TI"CMakeLists.txt;T; [I"text/x-cmake;TI"SourcePawn;T{ ;I"SourcePawn;T;[I"sp;T;[I" *.sp;T; [I"text/x-sourcepawn;TI" Mako;T{ ;I" Mako;T;[I" mako;T;[I" *.mao;T; [I"application/x-mako;TI"JavaScript+Myghty;T{ ;I"JavaScript+Myghty;T;[I"js+myghty;TI"javascript+myghty;T;[; [I"$application/x-javascript+myghty;TI"text/x-javascript+myghty;TI"text/javascript+mygthy;TI"RSL;T{ ;I"RSL;T;[I"rsl;T;[I" *.rsl;T; [I" text/rsl;TI" Scaml;T{ ;I" Scaml;T;[I" scaml;T;[I" *.scaml;T; [I"text/x-scaml;TI" MAQL;T{ ;I" MAQL;T;[I" maql;T;[I" *.maql;T; [I"text/x-gooddata-maql;TI" application/x-gooddata-maql;TI"ActionScript;T{ ;I"ActionScript;T;[I"as;TI"actionscript;T;[I" *.as;T; [I"application/x-actionscript;TI"text/x-actionscript;TI"text/actionscript;TI"SquidConf;T{ ;I"SquidConf;T;[I"squidconf;TI"squid.conf;TI" squid;T;[I"squid.conf;T; [I"text/x-squidconf;TI" Fantom;T{ ;I" Fantom;T;[I"fan;T;[I" *.fan;T; [I"application/x-fantom;TI" BBCode;T{ ;I" BBCode;T;[I" bbcode;T;[; [I"text/x-bbcode;TI"CSS+Myghty;T{ ;I"CSS+Myghty;T;[I"css+myghty;T;[; [I"text/css+myghty;TI" MuPAD;T{ ;I" MuPAD;T;[I" mupad;T;[I" *.mu;T; [I" XML+Ruby;T{ ;I" XML+Ruby;T;[I" xml+erb;TI" xml+ruby;T;[; [I"application/xml+ruby;TI" Kconfig;T{ ;I" Kconfig;T;[ I" kconfig;TI"menuconfig;TI"linux-config;TI"kernel-config;T;[ I" Kconfig;TI"*Config.in*;TI"external.in*;TI"standard-modules.in;T; [I"text/x-kconfig;TI"Python Traceback;T{ ;I"Python Traceback;T;[I" pytb;T;[I" *.pytb;T; [I"text/x-python-traceback;TI"cfstatement;T{ ;I"cfstatement;T;[I"cfs;T;[; [I"Ada;T{ ;I"Ada;T;[I"ada;TI"ada95ada2005;T;[I" *.adb;TI" *.ads;TI" *.ada;T; [I"text/x-ada;TI" CSS+Mako;T{ ;I" CSS+Mako;T;[I" css+mako;T;[; [I"text/css+mako;TI" Gherkin;T{ ;I" Gherkin;T;[I" cucumber;TI" gherkin;T;[I"*.feature;T; [I"text/x-gherkin;TI"Io;T{ ;I"Io;T;[I"io;T;[I" *.io;T; [I"text/x-iosrc;TI"UrbiScript;T{ ;I"UrbiScript;T;[I"urbiscript;T;[I"*.u;T; [I"application/x-urbiscript;TI" PL/pgSQL;T{ ;I" PL/pgSQL;T;[I" plpgsql;T;[; [I"text/x-plpgsql;TI" Inform 6;T{ ;I" Inform 6;T;[I" inform6;TI"i6;T;[I" *.inf;T; [I"Bro;T{ ;I"Bro;T;[I"bro;T;[I" *.bro;T; [I"!ANTLR With ObjectiveC Target;T{ ;I"!ANTLR With ObjectiveC Target;T;[I"antlr-objc;T;[I"*.G;TI"*.g;T; [I"XML;T{ ;I"XML;T;[I"xml;T;[ I" *.xml;TI" *.xsl;TI" *.rss;TI" *.xslt;TI" *.xsd;TI" *.wsdl;TI" *.wsf;T; [ I" text/xml;TI"application/xml;TI"image/svg+xml;TI"application/rss+xml;TI"application/atom+xml;TI"Genshi Text;T{ ;I"Genshi Text;T;[I"genshitext;T;[; [I"application/x-genshi-text;TI"text/x-genshi;TI" Pike;T{ ;I" Pike;T;[I" pike;T;[I" *.pike;TI" *.pmod;T; [I"text/x-pike;TI"Objective-J;T{ ;I"Objective-J;T;[ I"objective-j;TI"objectivej;TI" obj-j;TI" objj;T;[I"*.j;T; [I"text/x-objective-j;TI"Python console session;T{ ;I"Python console session;T;[I" pycon;T;[; [I"text/x-python-doctest;TI"Ragel in C Host;T{ ;I"Ragel in C Host;T;[I" ragel-c;T;[I" *.rl;T; [I"IDL;T{ ;I"IDL;T;[I"idl;T;[I" *.pro;T; [I" text/idl;TI" aspx-cs;T{ ;I" aspx-cs;T;[I" aspx-cs;T;[ I" *.aspx;TI" *.asax;TI" *.ascx;TI" *.ashx;TI" *.asmx;TI" *.axd;T; [I"Ragel in Ruby Host;T{ ;I"Ragel in Ruby Host;T;[I"ragel-ruby;TI" ragel-rb;T;[I" *.rl;T; [I"HTML+Genshi;T{ ;I"HTML+Genshi;T;[I"html+genshi;TI" html+kid;T;[; [I"text/html+genshi;TI" RPMSpec;T{ ;I" RPMSpec;T;[I" spec;T;[I" *.spec;T; [I"text/x-rpm-spec;TI"CSS+Smarty;T{ ;I"CSS+Smarty;T;[I"css+smarty;T;[; [I"text/css+smarty;TI"ANTLR With C# Target;T{ ;I"ANTLR With C# Target;T;[I"antlr-csharp;TI" antlr-c#;T;[I"*.G;TI"*.g;T; [I" LLVM;T{ ;I" LLVM;T;[I" llvm;T;[I" *.ll;T; [I"text/x-llvm;TI"Python 3.0 Traceback;T{ ;I"Python 3.0 Traceback;T;[I" py3tb;T;[I" *.py3tb;T; [I"text/x-python3-traceback;TI"TypeScript;T{ ;I"TypeScript;T;[I"ts;T;[I" *.ts;T; [I"text/x-typescript;TI" MiniD;T{ ;I" MiniD;T;[I" minid;T;[I" *.md;T; [I"text/x-minidsrc;TI"SQL;T{ ;I"SQL;T;[I"sql;T;[I" *.sql;T; [I"text/x-sql;TI" JSON;T{ ;I" JSON;T;[I" json;T;[I" *.json;T; [I"application/json;TI" NASM;T{ ;I" NASM;T;[I" nasm;T;[I" *.asm;TI" *.ASM;T; [I"text/x-nasm;TI" Idris;T{ ;I" Idris;T;[I" idris;TI"idr;T;[I" *.idr;T; [I"text/x-idris;TI" AutoIt;T{ ;I" AutoIt;T;[I" autoit;T;[I" *.au3;T; [I"text/x-autoit;TI" Sass;T{ ;I" Sass;T;[I" sass;T;[I" *.sass;T; [I"text/x-sass;TI" aspx-vb;T{ ;I" aspx-vb;T;[I" aspx-vb;T;[ I" *.aspx;TI" *.asax;TI" *.ascx;TI" *.ashx;TI" *.asmx;TI" *.axd;T; [I" Ceylon;T{ ;I" Ceylon;T;[I" ceylon;T;[I" *.ceylon;T; [I"text/x-ceylon;TI"HTML+Evoque;T{ ;I"HTML+Evoque;T;[I"html+evoque;T;[I" *.html;T; [I"text/html+evoque;TI" NumPy;T{ ;I" NumPy;T;[I" numpy;T;[; [I"CoffeeScript;T{ ;I"CoffeeScript;T;[I"coffee-script;TI"coffeescript;TI" coffee;T;[I" *.coffee;T; [I"text/coffeescript;TI" XML+Mako;T{ ;I" XML+Mako;T;[I" xml+mako;T;[; [I"application/xml+mako;TI" CSS+PHP;T{ ;I" CSS+PHP;T;[I" css+php;T;[; [I"text/css+php;TI" VimL;T{ ;I" VimL;T;[I"vim;T;[I" *.vim;TI" .vimrc;TI" .exrc;TI" .gvimrc;TI" _vimrc;TI" _exrc;TI" _gvimrc;TI" vimrc;TI" gvimrc;T; [I"text/x-vim;TI"CSS+Genshi Text;T{ ;I"CSS+Genshi Text;T;[I"css+genshitext;TI"css+genshi;T;[; [I"text/css+genshi;TI" Fancy;T{ ;I" Fancy;T;[I" fancy;TI"fy;T;[I" *.fy;TI"*.fancypack;T; [I"text/x-fancysrc;TI" Ragel;T{ ;I" Ragel;T;[I" ragel;T;[; [I"Scalate Server Page;T{ ;I"Scalate Server Page;T;[I"ssp;T;[I" *.ssp;T; [I"application/x-ssp;TI"AmbientTalk;T{ ;I"AmbientTalk;T;[I"at;TI"ambienttalk;TI"ambienttalk/2;T;[I" *.at;T; [I"text/x-ambienttalk;TI"XML+Evoque;T{ ;I"XML+Evoque;T;[I"xml+evoque;T;[I" *.xml;T; [I"application/xml+evoque;TI" Redcode;T{ ;I" Redcode;T;[I" redcode;T;[I" *.cw;T; [I"RobotFramework;T{ ;I"RobotFramework;T;[I"robotframework;T;[I" *.txt;TI" *.robot;T; [I"text/x-robotframework;TI" Scala;T{ ;I" Scala;T;[I" scala;T;[I" *.scala;T; [I"text/x-scala;TI" Lighttpd configuration file;T{ ;I" Lighttpd configuration file;T;[I" lighty;TI" lighttpd;T;[; [I"text/x-lighttpd-conf;TI"RQL;T{ ;I"RQL;T;[I"rql;T;[I" *.rql;T; [I"text/x-rql;TI" Chapel;T{ ;I" Chapel;T;[I" chapel;TI" chpl;T;[I" *.chpl;T; [I"HTML+Velocity;T{ ;I"HTML+Velocity;T;[I"html+velocity;T;[; [I"text/html+velocity;TI"Ruby irb session;T{ ;I"Ruby irb session;T;[I" rbcon;TI"irb;T;[; [I"text/x-ruby-shellsession;TI"CSS;T{ ;I"CSS;T;[I"css;T;[I" *.css;T; [I" text/css;TI"Ragel in D Host;T{ ;I"Ragel in D Host;T;[I" ragel-d;T;[I" *.rl;T; [I"Asymptote;T{ ;I"Asymptote;T;[I"asy;TI"asymptote;T;[I" *.asy;T; [I"text/x-asymptote;TI" XML+PHP;T{ ;I" XML+PHP;T;[I" xml+php;T;[; [I"application/xml+php;TI" Gnuplot;T{ ;I" Gnuplot;T;[I" gnuplot;T;[I" *.plot;TI" *.plt;T; [I"text/x-gnuplot;TI"Gettext Catalog;T{ ;I"Gettext Catalog;T;[I"pot;TI"po;T;[I" *.pot;TI" *.po;T; [I"application/x-gettext;TI"text/x-gettext;TI"text/gettext;TI" Matlab;T{ ;I" Matlab;T;[I" matlab;T;[I"*.m;T; [I"text/matlab;TI"C;T{ ;I"C;T;[I"c;T;[I"*.c;TI"*.h;TI" *.idc;T; [I"text/x-chdr;TI"text/x-csrc;TI" Eiffel;T{ ;I" Eiffel;T;[I" eiffel;T;[I"*.e;T; [I"text/x-eiffel;TI" Genshi;T{ ;I" Genshi;T;[ I" genshi;TI"kid;TI"xml+genshi;TI" xml+kid;T;[I" *.kid;T; [I"application/x-genshi;TI"application/x-kid;TI"VGL;T{ ;I"VGL;T;[I"vgl;T;[I" *.rpf;T; [I" Velocity;T{ ;I" Velocity;T;[I" velocity;T;[I" *.vm;TI" *.fhtml;T; [I" Koka;T{ ;I" Koka;T;[I" koka;T;[I" *.kk;TI" *.kki;T; [I"text/x-koka;TI" Alloy;T{ ;I" Alloy;T;[I" alloy;T;[I" *.als;T; [I"text/x-alloy;TI" IRC logs;T{ ;I" IRC logs;T;[I"irc;T;[I"*.weechatlog;T; [I"text/x-irclog;TI" SWIG;T{ ;I" SWIG;T;[I" swig;T;[I" *.swg;TI"*.i;T; [I"text/swig;TI" Prolog;T{ ;I" Prolog;T;[I" prolog;T;[I" *.prolog;TI" *.pro;TI" *.pl;T; [I"text/x-prolog;TI"XML+Lasso;T{ ;I"XML+Lasso;T;[I"xml+lasso;T;[; [I"application/xml+lasso;TI"Smalltalk;T{ ;I"Smalltalk;T;[I"smalltalk;TI" squeak;TI"st;T;[I" *.st;T; [I"text/x-smalltalk;TI" YAML;T{ ;I" YAML;T;[I" yaml;T;[I" *.yaml;TI" *.yml;T; [I"text/x-yaml;TI"#ANTLR With ActionScript Target;T{ ;I"#ANTLR With ActionScript Target;T;[I" antlr-as;TI"antlr-actionscript;T;[I"*.G;TI"*.g;T; [I" Cypher;T{ ;I" Cypher;T;[I" cypher;T;[I" *.cyp;TI" *.cypher;T; [I" XSLT;T{ ;I" XSLT;T;[I" xslt;T;[I" *.xsl;TI" *.xslt;TI" *.xpl;T; [I"application/xsl+xml;TI"application/xslt+xml;TI"S;T{ ;I"S;T;[I" splus;TI"s;TI"r;T;[ I"*.S;TI"*.R;TI".Rhistory;TI".Rprofile;TI".Renviron;T; [ I"text/S-plus;TI" text/S;TI"text/x-r-source;TI" text/x-r;TI" text/x-R;TI"text/x-r-history;TI"text/x-r-profile;TI" DylanLID;T{ ;I" DylanLID;T;[I"dylan-lid;TI"lid;T;[I" *.lid;TI" *.hdp;T; [I"text/x-dylan-lid;TI"eC;T{ ;I"eC;T;[I"ec;T;[I" *.ec;TI" *.eh;T; [I"text/x-echdr;TI"text/x-ecsrc;TI" Perl6;T{ ;I" Perl6;T;[I" perl6;TI"pl6;T;[I" *.pl;TI" *.pm;TI" *.nqp;TI" *.p6;TI" *.6pl;TI" *.p6l;TI" *.pl6;TI" *.6pm;TI" *.p6m;TI" *.pm6;TI"*.t;T; [I"text/x-perl6;TI"application/x-perl6;TI" Logos;T{ ;I" Logos;T;[I" logos;T;[ I"*.x;TI" *.xi;TI" *.xm;TI" *.xmi;T; [I"text/x-logos;TI" Racket;T{ ;I" Racket;T;[I" racket;TI"rkt;T;[I" *.rkt;TI" *.rktd;TI" *.rktl;T; [I"text/x-racket;TI"application/x-racket;TI"Text only;T{ ;I"Text only;T;[I" text;T;[I" *.txt;T; [I"text/plain;TI" Dart;T{ ;I" Dart;T;[I" dart;T;[I" *.dart;T; [I"text/x-dart;TI"Ragel in CPP Host;T{ ;I"Ragel in CPP Host;T;[I"ragel-cpp;T;[I" *.rl;T; [I" Scilab;T{ ;I" Scilab;T;[I" scilab;T;[I" *.sci;TI" *.sce;TI" *.tst;T; [I"text/scilab;TI"Java Server Page;T{ ;I"Java Server Page;T;[I"jsp;T;[I" *.jsp;T; [I"application/x-jsp;TI" ABAP;T{ ;I" ABAP;T;[I" abap;T;[I" *.abap;T; [I"text/x-abap;TI" Rust;T{ ;I" Rust;T;[I" rust;T;[I" *.rs;T; [I"text/x-rustsrc;TI" Diff;T{ ;I" Diff;T;[I" diff;TI" udiff;T;[I" *.diff;TI" *.patch;T; [I"text/x-diff;TI"text/x-patch;TI" liquid;T{ ;I" liquid;T;[I" liquid;T;[I" *.liquid;T; [I"Matlab session;T{ ;I"Matlab session;T;[I"matlabsession;T;[; [I" Slim;T{ ;I" Slim;T;[I" slim;T;[I" *.slim;T; [I"text/x-slim;TI" HTML+PHP;T{ ;I" HTML+PHP;T;[I" html+php;T;[I" *.phtml;T; [ I"application/x-php;TI"application/x-httpd-php;TI"application/x-httpd-php3;TI"application/x-httpd-php4;TI"application/x-httpd-php5;TI"Objective-C++;T{ ;I"Objective-C++;T;[ I"objective-c++;TI"objectivec++;TI" obj-c++;TI" objc++;T;[I" *.mm;TI" *.hh;T; [I"text/x-objective-c++;TI"PostScript;T{ ;I"PostScript;T;[I"postscript;TI" postscr;T;[I" *.ps;TI" *.eps;T; [I"application/postscript;TI" verilog;T{ ;I" verilog;T;[I" verilog;TI"v;T;[I"*.v;T; [I"text/x-verilog;TI"JavaScript+Ruby;T{ ;I"JavaScript+Ruby;T;[ I" js+erb;TI"javascript+erb;TI" js+ruby;TI"javascript+ruby;T;[; [I""application/x-javascript+ruby;TI"text/x-javascript+ruby;TI"text/javascript+ruby;TI"COBOLFree;T{ ;I"COBOLFree;T;[I"cobolfree;T;[I" *.cbl;TI" *.CBL;T; [I"Base Makefile;T{ ;I"Base Makefile;T;[I" basemake;T;[; [I" Ioke;T{ ;I" Ioke;T;[I" ioke;TI"ik;T;[I" *.ik;T; [I"text/x-iokesrc;TI" PyPy Log;T{ ;I" PyPy Log;T;[I" pypylog;TI" pypy;T;[I"*.pypylog;T; [I"application/x-pypylog;TI" Python 3;T{ ;I" Python 3;T;[I" python3;TI"py3;T;[; [I"text/x-python3;TI"application/x-python3;TI" Swift;T{ ;I" Swift;T;[I" swift;T;[I" *.swift;T; [I"text/x-swift;TI" ANTLR;T{ ;I" ANTLR;T;[I" antlr;T;[; [I"PostgreSQL console (psql);T{ ;I"PostgreSQL console (psql);T;[I" psql;TI"postgresql-console;TI"postgres-console;T;[; [I"text/x-postgresql-psql;TI"JavaScript+Django/Jinja;T{ ;I"JavaScript+Django/Jinja;T;[ I"js+django;TI"javascript+django;TI" js+jinja;TI"javascript+jinja;T;[; [ I"$application/x-javascript+django;TI"#application/x-javascript+jinja;TI"text/x-javascript+django;TI"text/x-javascript+jinja;TI"text/javascript+django;TI"text/javascript+jinja;TI"LSL;T{ ;I"LSL;T;[I"lsl;T;[I" *.lsl;T; [I"text/x-lsl;TI"Mathematica;T{ ;I"Mathematica;T;[I"mathematica;TI"mma;TI"nb;T;[ I" *.nb;TI" *.cdf;TI" *.nbp;TI" *.ma;T; [ I"application/mathematica;TI"(application/vnd.wolfram.mathematica;TI"0application/vnd.wolfram.mathematica.package;TI" application/vnd.wolfram.cdf;TI"Erlang erl session;T{ ;I"Erlang erl session;T;[I"erl;T;[I" *.erl-sh;T; [I"text/x-erl-shellsession;TI" Modelica;T{ ;I" Modelica;T;[I" modelica;T;[I" *.mo;T; [I"text/x-modelica;TI" Treetop;T{ ;I" Treetop;T;[I" treetop;T;[I"*.treetop;TI" *.tt;T; [I"Tcl;T{ ;I"Tcl;T;[I"tcl;T;[I" *.tcl;T; [I"text/x-tcl;TI"text/x-script.tcl;TI"application/x-tcl;TI" FSharp;T{ ;I" FSharp;T;[I" fsharp;T;[I" *.fs;TI" *.fsi;T; [I"text/x-fsharp;TI" NewLisp;T{ ;I" NewLisp;T;[I" newlisp;T;[I" *.lsp;TI" *.nl;T; [I"text/x-newlisp;TI"application/x-newlisp;TI"CSS+Lasso;T{ ;I"CSS+Lasso;T;[I"css+lasso;T;[; [I"text/css+lasso;TI" Todotxt;T{ ;I" Todotxt;T;[I" todotxt;T;[I" todo.txt;TI"*.todotxt;T; [I"text/x-todo;TI"Shell Session;T{ ;I"Shell Session;T;[I"shell-session;T;[I"*.shell-session;T; [I"application/x-sh-session;TI" Newspeak;T{ ;I" Newspeak;T;[I" newspeak;T;[I" *.ns2;T; [I"text/x-newspeak;TI"Bash Session;T{ ;I"Bash Session;T;[I" console;T;[I"*.sh-session;T; [I" application/x-shell-session;TI"Gosu Template;T{ ;I"Gosu Template;T;[I"gst;T;[I" *.gst;T; [I"text/x-gosu-template;TI"Rd;T{ ;I"Rd;T;[I"rd;T;[I" *.Rd;T; [I"text/x-r-doc;TI"JavaScript;T{ ;I"JavaScript;T;[I"js;TI"javascript;T;[I" *.js;T; [ I"application/javascript;TI"application/x-javascript;TI"text/x-javascript;TI"text/javascript;TI"Common Lisp;T{ ;I"Common Lisp;T;[ I"common-lisp;TI"cl;TI" lisp;TI" elisp;TI" emacs;TI"emacs-lisp;T;[I" *.cl;TI" *.lisp;TI" *.el;T; [I"text/x-common-lisp;TI"APL;T{ ;I"APL;T;[I"apl;T;[I" *.apl;T; [I"GAP;T{ ;I"GAP;T;[I"gap;T;[ I"*.g;TI" *.gd;TI" *.gi;TI" *.gap;T; [I" Factor;T{ ;I" Factor;T;[I" factor;T;[I" *.factor;T; [I"text/x-factor;TI"Awk;T{ ;I"Awk;T;[ I"awk;TI" gawk;TI" mawk;TI" nawk;T;[I" *.awk;T; [I"application/x-awk;TI"systemverilog;T{ ;I"systemverilog;T;[I"systemverilog;TI"sv;T;[I" *.sv;TI" *.svh;T; [I"text/x-systemverilog;TI"JavaScript+Mako;T{ ;I"JavaScript+Mako;T;[I" js+mako;TI"javascript+mako;T;[; [I""application/x-javascript+mako;TI"text/x-javascript+mako;TI"text/javascript+mako;TI"Elixir iex session;T{ ;I"Elixir iex session;T;[I"iex;T;[; [I"text/x-elixir-shellsession;TI"HTML+Cheetah;T{ ;I"HTML+Cheetah;T;[I"html+cheetah;TI"html+spitfire;TI"htmlcheetah;T;[; [I"text/html+cheetah;TI"text/html+spitfire;TI"Inform 6 template;T{ ;I"Inform 6 template;T;[I"i6t;T;[I" *.i6t;T; [I" Julia;T{ ;I" Julia;T;[I" julia;TI"jl;T;[I" *.jl;T; [I"text/x-julia;TI"application/x-julia;TI" Smarty;T{ ;I" Smarty;T;[I" smarty;T;[I" *.tpl;T; [I"application/x-smarty;TI"Protocol Buffer;T{ ;I"Protocol Buffer;T;[I" protobuf;TI" proto;T;[I" *.proto;T; [I"Tea;T{ ;I"Tea;T;[I"tea;T;[I" *.tea;T; [I"text/x-tea;TI" Jasmin;T{ ;I" Jasmin;T;[I" jasmin;TI" jasminxt;T;[I"*.j;T; [I"ApacheConf;T{ ;I"ApacheConf;T;[I"apacheconf;TI" aconf;TI" apache;T;[I".htaccess;TI"apache.conf;TI"apache2.conf;T; [I"text/x-apacheconf;TI"JavaScript+Genshi Text;T{ ;I"JavaScript+Genshi Text;T;[ I"js+genshitext;TI"js+genshi;TI"javascript+genshitext;TI"javascript+genshi;T;[; [I"$application/x-javascript+genshi;TI"text/x-javascript+genshi;TI"text/javascript+genshi;TI" Scheme;T{ ;I" Scheme;T;[I" scheme;TI"scm;T;[I" *.scm;TI" *.ss;T; [I"text/x-scheme;TI"application/x-scheme;TI" Octave;T{ ;I" Octave;T;[I" octave;T;[I"*.m;T; [I"text/octave;TI"LiveScript;T{ ;I"LiveScript;T;[I"live-script;TI"livescript;T;[I" *.ls;T; [I"text/livescript;TI" Monkey;T{ ;I" Monkey;T;[I" monkey;T;[I" *.monkey;T; [I"text/x-monkey;TI"Red;T{ ;I"Red;T;[I"red;TI"red/system;T;[I" *.red;TI" *.reds;T; [I"text/x-red;TI"text/x-red-system;TI"Coldfusion CFC;T{ ;I"Coldfusion CFC;T;[I"cfc;T;[I" *.cfc;T; [I"d-objdump;T{ ;I"d-objdump;T;[I"d-objdump;T;[I"*.d-objdump;T; [I"text/x-d-objdump;TI" Hxml;T{ ;I" Hxml;T;[I" haxeml;TI" hxml;T;[I" *.hxml;T; [I" Groovy;T{ ;I" Groovy;T;[I" groovy;T;[I" *.groovy;T; [I"text/x-groovy;TI"Pig;T{ ;I"Pig;T;[I"pig;T;[I" *.pig;T; [I"text/x-pig;TI" CUDA;T{ ;I" CUDA;T;[I" cuda;TI"cu;T;[I" *.cu;TI" *.cuh;T; [I"text/x-cuda;TI"Handlebars;T{ ;I"Handlebars;T;[I"handlebars;T;[; [I" HTTP;T{ ;I" HTTP;T;[I" http;T;[; [I" Python;T{ ;I" Python;T;[I" python;TI"py;TI" sage;T;[ I" *.py;TI" *.pyw;TI" *.sc;TI"SConstruct;TI"SConscript;TI" *.tac;TI" *.sage;T; [I"text/x-python;TI"application/x-python;TI"Boo;T{ ;I"Boo;T;[I"boo;T;[I" *.boo;T; [I"text/x-boo;TI" Logtalk;T{ ;I" Logtalk;T;[I" logtalk;T;[I" *.lgt;T; [I"text/x-logtalk;TI" VB.net;T{ ;I" VB.net;T;[I" vb.net;TI" vbnet;T;[I" *.vb;TI" *.bas;T; [I"text/x-vbnet;TI"text/x-vba;TI"D;T{ ;I"D;T;[I"d;T;[I"*.d;TI" *.di;T; [I"text/x-dsrc;TI"BlitzBasic;T{ ;I"BlitzBasic;T;[I"blitzbasic;TI"b3d;TI" bplus;T;[I" *.bb;TI" *.decls;T; [I"text/x-bb;TI" SCSS;T{ ;I" SCSS;T;[I" scss;T;[I" *.scss;T; [I"text/x-scss;TI" Haml;T{ ;I" Haml;T;[I" haml;T;[I" *.haml;T; [I"text/x-haml;TI" FoxPro;T{ ;I" FoxPro;T;[ I" foxpro;TI"vfp;TI" clipper;TI" xbase;T;[I" *.PRG;TI" *.prg;T; [I"Debian Control file;T{ ;I"Debian Control file;T;[I" control;TI"debcontrol;T;[I" control;T; [I" Jade;T{ ;I" Jade;T;[I" jade;T;[I" *.jade;T; [I"text/x-jade;TI"c-objdump;T{ ;I"c-objdump;T;[I"c-objdump;T;[I"*.c-objdump;T; [I"text/x-c-objdump;TI"XML+Velocity;T{ ;I"XML+Velocity;T;[I"xml+velocity;T;[; [I"application/xml+velocity;TI"JavaScript+Cheetah;T{ ;I"JavaScript+Cheetah;T;[ I"js+cheetah;TI"javascript+cheetah;TI"js+spitfire;TI"javascript+spitfire;T;[; [ I"%application/x-javascript+cheetah;TI"text/x-javascript+cheetah;TI"text/javascript+cheetah;TI"&application/x-javascript+spitfire;TI"text/x-javascript+spitfire;TI"text/javascript+spitfire;TI" COBOL;T{ ;I" COBOL;T;[I" cobol;T;[ I" *.cob;TI" *.COB;TI" *.cpy;TI" *.CPY;T; [I"text/x-cobol;TI" objdump;T{ ;I" objdump;T;[I" objdump;T;[I"*.objdump;T; [I"text/x-objdump;TI" ca65;T{ ;I" ca65;T;[I" ca65;T;[I"*.s;T; [I" SPARQL;T{ ;I" SPARQL;T;[I" sparql;T;[I" *.rq;TI" *.sparql;T; [I"application/sparql-query;TI" Lasso;T{ ;I" Lasso;T;[I" lasso;TI"lassoscript;T;[I" *.lasso;TI"*.lasso[89];T; [I"text/x-lasso;TI"Ragel in Java Host;T{ ;I"Ragel in Java Host;T;[I"ragel-java;T;[I" *.rl;T; [I" Vala;T{ ;I" Vala;T;[I" vala;TI" vapi;T;[I" *.vala;TI" *.vapi;T; [I"text/x-vala;TI" Haskell;T{ ;I" Haskell;T;[I" haskell;TI"hs;T;[I" *.hs;T; [I"text/x-haskell;TI"Lua;T{ ;I"Lua;T;[I"lua;T;[I" *.lua;TI" *.wlua;T; [I"text/x-lua;TI"application/x-lua;TI" AspectJ;T{ ;I" AspectJ;T;[I" aspectj;T;[I" *.aj;T; [I"text/x-aspectj;TI" Groff;T{ ;I" Groff;T;[I" groff;TI" nroff;TI"man;T;[I"*.[1234567];TI" *.man;T; [I"application/x-troff;TI"text/troff;TI"JavaScript+Lasso;T{ ;I"JavaScript+Lasso;T;[I" js+lasso;TI"javascript+lasso;T;[; [I"#application/x-javascript+lasso;TI"text/x-javascript+lasso;TI"text/javascript+lasso;TI" GLSL;T{ ;I" GLSL;T;[I" glsl;T;[I" *.vert;TI" *.frag;TI" *.geo;T; [I"text/x-glslsrc;TI"GAS;T{ ;I"GAS;T;[I"gas;TI"asm;T;[I"*.s;TI"*.S;T; [I"text/x-gas;TI" MXML;T{ ;I" MXML;T;[I" mxml;T;[I" *.mxml;T; [I"XML+Cheetah;T{ ;I"XML+Cheetah;T;[I"xml+cheetah;TI"xml+spitfire;T;[; [I"application/xml+cheetah;TI"application/xml+spitfire;TI"Go;T{ ;I"Go;T;[I"go;T;[I" *.go;T; [I"text/x-gosrc;TI"Pan;T{ ;I"Pan;T;[I"pan;T;[I" *.pan;T; [I"MQL;T{ ;I"MQL;T;[ I"mql;TI"mq4;TI"mq5;TI" mql4;TI" mql5;T;[I" *.mq4;TI" *.mq5;TI" *.mqh;T; [I"text/x-mql;TI" Felix;T{ ;I" Felix;T;[I" felix;TI"flx;T;[I" *.flx;TI" *.flxh;T; [I"text/x-felix;TI"Properties;T{ ;I"Properties;T;[I"properties;TI"jproperties;T;[I"*.properties;T; [I"text/x-java-properties;TI" Igor;T{ ;I" Igor;T;[I" igor;TI" igorpro;T;[I" *.ipf;T; [I" text/ipf;TI" BlitzMax;T{ ;I" BlitzMax;T;[I" blitzmax;TI" bmax;T;[I" *.bmx;T; [I"text/x-bmx;TI" Perl;T{ ;I" Perl;T;[I" perl;TI"pl;T;[I" *.pl;TI" *.pm;TI"*.t;T; [I"text/x-perl;TI"application/x-perl;TI" Stan;T{ ;I" Stan;T;[I" stan;T;[I" *.stan;T; [I"INI;T{ ;I"INI;T;[I"ini;TI"cfg;TI" dosini;T;[I" *.ini;TI" *.cfg;T; [I"text/x-ini;TI" RHTML;T{ ;I" RHTML;T;[I" rhtml;TI" html+erb;TI"html+ruby;T;[I" *.rhtml;T; [I"text/html+ruby;TI"Coq;T{ ;I"Coq;T;[I"coq;T;[I"*.v;T; [I"text/x-coq;TI" Tcsh;T{ ;I" Tcsh;T;[I" tcsh;TI"csh;T;[I" *.tcsh;TI" *.csh;T; [I"application/x-csh;TI"Darcs Patch;T{ ;I"Darcs Patch;T;[I" dpatch;T;[I" *.dpatch;TI"*.darcspatch;T; [I"Nginx configuration file;T{ ;I"Nginx configuration file;T;[I" nginx;T;[; [I"text/x-nginx-conf;TI" Agda;T{ ;I" Agda;T;[I" agda;T;[I" *.agda;T; [I"text/x-agda;TI"AppleScript;T{ ;I"AppleScript;T;[I"applescript;T;[I"*.applescript;T; [I"HTML+Smarty;T{ ;I"HTML+Smarty;T;[I"html+smarty;T;[; [I"text/html+smarty;TI" Inform 7;T{ ;I" Inform 7;T;[I" inform7;TI"i7;T;[I" *.ni;TI" *.i7x;T; [I"Literate Haskell;T{ ;I"Literate Haskell;T;[I"lhs;TI"literate-haskell;TI" lhaskell;T;[I" *.lhs;T; [I"text/x-literate-haskell;TI"PHP;T{ ;I"PHP;T;[ I"php;TI" php3;TI" php4;TI" php5;T;[I" *.php;TI"*.php[345];TI" *.inc;T; [I"text/x-php;TI" Mscgen;T{ ;I" Mscgen;T;[I" mscgen;TI"msc;T;[I" *.msc;T; [I"Ooc;T{ ;I"Ooc;T;[I"ooc;T;[I" *.ooc;T; [I"text/x-ooc;TI"Debian Sourcelist;T{ ;I"Debian Sourcelist;T;[I"sourceslist;TI"sources.list;TI"debsources;T;[I"sources.list;T; [I" Delphi;T{ ;I" Delphi;T;[ I" delphi;TI"pas;TI" pascal;TI"objectpascal;T;[I" *.pas;T; [I"text/x-pascal;TI" Modula-2;T{ ;I" Modula-2;T;[I" modula2;TI"m2;T;[I" *.def;TI" *.mod;T; [I"text/x-modula2;TI"PostgreSQL SQL dialect;T{ ;I"PostgreSQL SQL dialect;T;[I"postgresql;TI" postgres;T;[; [I"text/x-postgresql;TI" Rexx;T{ ;I" Rexx;T;[I" rexx;TI" arexx;T;[ I" *.rexx;TI" *.rex;TI" *.rx;TI" *.arexx;T; [I"text/x-rexx;TI"HTML+Django/Jinja;T{ ;I"HTML+Django/Jinja;T;[I"html+django;TI"html+jinja;TI"htmldjango;T;[; [I"text/html+django;TI"text/html+jinja;TI" Haxe;T{ ;I" Haxe;T;[I"hx;TI" haxe;TI" hxsl;T;[I" *.hx;TI" *.hxsl;T; [I"text/haxe;TI"text/x-haxe;TI"text/x-hx;TI"Django/Jinja;T{ ;I"Django/Jinja;T;[I" django;TI" jinja;T;[; [I"$application/x-django-templating;TI"application/x-jinja;TI"DTD;T{ ;I"DTD;T;[I"dtd;T;[I" *.dtd;T; [I"application/xml-dtd;TI"Nix;T{ ;I"Nix;T;[I" nixos;TI"nix;T;[I" *.nix;T; [I"text/x-nix;TI" vhdl;T{ ;I" vhdl;T;[I" vhdl;T;[I" *.vhdl;TI" *.vhd;T; [I"text/x-vhdl;TI" Mask;T{ ;I" Mask;T;[I" mask;T;[I" *.mask;T; [I"text/x-mask;TI" Zephir;T{ ;I" Zephir;T;[I" zephir;T;[I" *.zep;T; [I" Pawn;T{ ;I" Pawn;T;[I" pawn;T;[I"*.p;TI" *.pwn;TI" *.inc;T; [I"text/x-pawn;TI"JavaScript+Smarty;T{ ;I"JavaScript+Smarty;T;[I"js+smarty;TI"javascript+smarty;T;[; [I"$application/x-javascript+smarty;TI"text/x-javascript+smarty;TI"text/javascript+smarty;TI" Fortran;T{ ;I" Fortran;T;[I" fortran;T;[ I"*.f;TI" *.f90;TI"*.F;TI" *.F90;T; [I"text/x-fortran;TI" Cryptol;T{ ;I" Cryptol;T;[I" cryptol;TI"cry;T;[I" *.cry;T; [I"text/x-cryptol;TI" REBOL;T{ ;I" REBOL;T;[I" rebol;T;[I"*.r;TI" *.r3;TI" *.reb;T; [I"text/x-rebol;TI"ERB;T{ ;I"ERB;T;[I"erb;T;[; [I""application/x-ruby-templating;TI" Befunge;T{ ;I" Befunge;T;[I" befunge;T;[I"*.befunge;T; [I"application/x-befunge;TI"MoonScript;T{ ;I"MoonScript;T;[I" moon;TI"moonscript;T;[I" *.moon;T; [I"text/x-moonscript;TI"application/x-moonscript;TI" Dylan;T{ ;I" Dylan;T;[I" dylan;T;[I" *.dylan;TI" *.dyl;TI" *.intr;T; [I"text/x-dylan;TI"MoinMoin/Trac Wiki markup;T{ ;I"MoinMoin/Trac Wiki markup;T;[I"trac-wiki;TI" moin;T;[; [I"text/x-trac-wiki;TI" Croc;T{ ;I" Croc;T;[I" croc;T;[I" *.croc;T; [I"text/x-crocsrc;TI" HTML;T{ ;I" HTML;T;[I" html;T;[ I" *.html;TI" *.htm;TI" *.xhtml;TI" *.xslt;T; [I"text/html;TI"application/xhtml+xml;TI"reStructuredText;T{ ;I"reStructuredText;T;[I"rst;TI" rest;TI"restructuredtext;T;[I" *.rst;TI" *.rest;T; [I"text/x-rst;TI"text/prs.fallenstein.rst;TI" NSIS;T{ ;I" NSIS;T;[I" nsis;TI"nsi;TI"nsh;T;[I" *.nsi;TI" *.nsh;T; [I"text/x-nsis;TI" Elixir;T{ ;I" Elixir;T;[I" elixir;TI"ex;TI"exs;T;[I" *.ex;TI" *.exs;T; [I"text/x-elixir;TI"HTML+Myghty;T{ ;I"HTML+Myghty;T;[I"html+myghty;T;[; [I"text/html+myghty;TI" Makefile;T{ ;I" Makefile;T;[ I" make;TI" makefile;TI"mf;TI" bsdmake;T;[ I" *.mak;TI" *.mk;TI" Makefile;TI" makefile;TI"Makefile.*;TI"GNUmakefile;T; [I"text/x-makefile;TI"sqlite3con;T{ ;I"sqlite3con;T;[I" sqlite3;T;[I"*.sqlite3-console;T; [I"text/x-sqlite3-console;TI" OCaml;T{ ;I" OCaml;T;[I" ocaml;T;[ I" *.ml;TI" *.mli;TI" *.mll;TI" *.mly;T; [I"text/x-ocaml;TI" Clay;T{ ;I" Clay;T;[I" clay;T;[I" *.clay;T; [I"text/x-clay;TI"Julia console;T{ ;I"Julia console;T;[I" jlcon;T;[; [I" Ruby;T{ ;I" Ruby;T;[I"rb;TI" ruby;TI" duby;T;[ I" *.rb;TI" *.rbw;TI" Rakefile;TI" *.rake;TI"*.gemspec;TI" *.rbx;TI" *.duby;T; [I"text/x-ruby;TI"application/x-ruby;TI" POVRay;T{ ;I" POVRay;T;[I"pov;T;[I" *.pov;TI" *.inc;T; [I"text/x-povray;TI"dg;T{ ;I"dg;T;[I"dg;T;[I" *.dg;T; [I"text/x-dg;TI" Evoque;T{ ;I" Evoque;T;[I" evoque;T;[I" *.evoque;T; [I"application/x-evoque;TI" Docker;T{ ;I" Docker;T;[I" docker;TI"dockerfile;T;[I"Dockerfile;TI" *.docker;T; [I"text/x-dockerfile-config;TI"reg;T{ ;I"reg;T;[I" registry;T;[I" *.reg;T; [I"text/x-windows-registry;TI"HTML+Mako;T{ ;I"HTML+Mako;T;[I"html+mako;T;[; [I"text/html+mako;TI"CFEngine3;T{ ;I"CFEngine3;T;[I"cfengine3;TI"cf3;T;[I" *.cf;T; [I" Mason;T{ ;I" Mason;T;[I" mason;T;[ I"*.m;TI" *.mhtml;TI" *.mc;TI" *.mi;TI"autohandler;TI" dhandler;T; [I"application/x-mason;TI"Literate Cryptol;T{ ;I"Literate Cryptol;T;[I" lcry;TI"literate-cryptol;TI" lcryptol;T;[I" *.lcry;T; [I"text/x-literate-cryptol;TI"ActionScript 3;T{ ;I"ActionScript 3;T;[I"as3;TI"actionscript3;T;[I" *.as;T; [I" application/x-actionscript3;TI"text/x-actionscript3;TI"text/actionscript3;TI" Kotlin;T{ ;I" Kotlin;T;[I" kotlin;T;[I" *.kt;T; [I"text/x-kotlin;TI"ANTLR With Java Target;T{ ;I"ANTLR With Java Target;T;[I"antlr-java;T;[I"*.G;TI"*.g;T; [I" BUGS;T{ ;I" BUGS;T;[I" bugs;TI" winbugs;TI" openbugs;T;[I" *.bug;T; [I"ANTLR With Python Target;T{ ;I"ANTLR With Python Target;T;[I"antlr-python;T;[I"*.G;TI"*.g;T; [I"YAML+Jinja;T{ ;I"YAML+Jinja;T;[I"yaml+jinja;TI" salt;TI"sls;T;[I" *.sls;T; [I"text/x-yaml+jinja;TI"text/x-sls;TI"cpp-objdump;T{ ;I"cpp-objdump;T;[I"cpp-objdump;TI"c++-objdumb;TI"cxx-objdump;T;[I"*.cpp-objdump;TI"*.c++-objdump;TI"*.cxx-objdump;T; [I"text/x-cpp-objdump;TI"Batchfile;T{ ;I"Batchfile;T;[ I"bat;TI" batch;TI" dosbatch;TI" winbatch;T;[I" *.bat;TI" *.cmd;T; [I"application/x-dos-batch;TI" Hybris;T{ ;I" Hybris;T;[I" hybris;TI"hy;T;[I" *.hy;TI" *.hyb;T; [I"text/x-hybris;TI"application/x-hybris;TI"Opa;T{ ;I"Opa;T;[I"opa;T;[I" *.opa;T; [I"text/x-opa;TI"Hy;T{ ;I"Hy;T;[I" hylang;T;[I" *.hy;T; [I"text/x-hy;TI"application/x-hy;TI" Cython;T{ ;I" Cython;T;[I" cython;TI"pyx;TI" pyrex;T;[I" *.pyx;TI" *.pxd;TI" *.pxi;T; [I"text/x-cython;TI"application/x-cython;TI" Erlang;T{ ;I" Erlang;T;[I" erlang;T;[ I" *.erl;TI" *.hrl;TI" *.es;TI"*.escript;T; [I"text/x-erlang;TI"VCTreeStatus;T{ ;I"VCTreeStatus;T;[I"vctreestatus;T;[; [I" Clojure;T{ ;I" Clojure;T;[I" clojure;TI"clj;T;[I" *.clj;T; [I"text/x-clojure;TI"application/x-clojure;TI"ANTLR With Perl Target;T{ ;I"ANTLR With Perl Target;T;[I"antlr-perl;T;[I"*.G;TI"*.g;T; [I" Myghty;T{ ;I" Myghty;T;[I" myghty;T;[I" *.myt;TI"autodelegate;T; [I"application/x-myghty;TI"ClojureScript;T{ ;I"ClojureScript;T;[I"clojurescript;TI" cljs;T;[I" *.cljs;T; [I"text/x-clojurescript;TI" application/x-clojurescript;TI"QML;T{ ;I"QML;T;[I"qml;T;[I" *.qml;T; [I"application/x-qml;TI" MOOCode;T{ ;I" MOOCode;T;[I" moocode;TI"moo;T;[I" *.moo;T; [I"text/x-moocode;TI" RConsole;T{ ;I" RConsole;T;[I" rconsole;TI" rout;T;[I" *.Rout;T; [I"Raw token data;T{ ;I"Raw token data;T;[I"raw;T;[; [I""application/x-pygments-tokens;TI"HTML+Lasso;T{ ;I"HTML+Lasso;T;[I"html+lasso;T;[; [I"text/html+lasso;TI"application/x-httpd-lasso;TI""application/x-httpd-lasso[89];TI"C#;T{ ;I"C#;T;[I" csharp;TI"c#;T;[I" *.cs;T; [I"text/x-csharp;TI"TeX;T{ ;I"TeX;T;[I"tex;TI" latex;T;[I" *.tex;TI" *.aux;TI" *.toc;T; [I"text/x-tex;TI"text/x-latex;TI"ChaiScript;T{ ;I"ChaiScript;T;[I" chai;TI"chaiscript;T;[I" *.chai;T; [I"text/x-chaiscript;TI"application/x-chaiscript;TI" Cheetah;T{ ;I" Cheetah;T;[I" cheetah;TI" spitfire;T;[I" *.tmpl;TI" *.spt;T; [I"application/x-cheetah;TI"application/x-spitfire;TI" Smali;T{ ;I" Smali;T;[I" smali;T;[I" *.smali;T; [I"text/smali;TI" QBasic;T{ ;I" QBasic;T;[I" qbasic;TI" basic;T;[I" *.BAS;TI" *.bas;T; [I"text/basic;TI"GoodData-CL;T{ ;I"GoodData-CL;T;[I"gooddata-cl;T;[I" *.gdc;T; [I"text/x-gooddata-cl;TI"HTML+Handlebars;T{ ;I"HTML+Handlebars;T;[I"html+handlebars;T;[I"*.handlebars;TI" *.hbs;T; [I"text/html+handlebars;TI"text/x-handlebars-template;TI"Objective-C;T{ ;I"Objective-C;T;[ I"objective-c;TI"objectivec;TI" obj-c;TI" objc;T;[I"*.m;TI"*.h;T; [I"text/x-objective-c;TI"Literate Idris;T{ ;I"Literate Idris;T;[I" lidr;TI"literate-idris;TI" lidris;T;[I" *.lidr;T; [I"text/x-literate-idris;TI"Embedded Ragel;T{ ;I"Embedded Ragel;T;[I" ragel-em;T;[I" *.rl;T; [I"objdump-nasm;T{ ;I"objdump-nasm;T;[I"objdump-nasm;T;[I"*.objdump-intel;T; [I"text/x-nasm-objdump;TI"ANTLR With CPP Target;T{ ;I"ANTLR With CPP Target;T;[I"antlr-cpp;T;[I"*.G;TI"*.g;T; [I" EBNF;T{ ;I" EBNF;T;[I" ebnf;T;[I" *.ebnf;T; [I"text/x-ebnf;TI" Gosu;T{ ;I" Gosu;T;[I" gosu;T;[ I" *.gs;TI" *.gsx;TI" *.gsp;TI" *.vark;T; [I"text/x-gosu;TI" Snobol;T{ ;I" Snobol;T;[I" snobol;T;[I" *.snobol;T; [I"text/x-snobol;TI"JavaScript+PHP;T{ ;I"JavaScript+PHP;T;[I" js+php;TI"javascript+php;T;[; [I"!application/x-javascript+php;TI"text/x-javascript+php;TI"text/javascript+php;TI" XQuery;T{ ;I" XQuery;T;[ I" xquery;TI"xqy;TI"xq;TI"xql;TI"xqm;T;[ I" *.xqy;TI" *.xquery;TI" *.xq;TI" *.xql;TI" *.xqm;T; [I"text/xquery;TI"application/xquery;TI" nesC;T{ ;I" nesC;T;[I" nesc;T;[I" *.nc;T; [I"text/x-nescsrc;TI"ECL;T{ ;I"ECL;T;[I"ecl;T;[I" *.ecl;T; [I"application/x-ecl;TI"Ragel in Objective C Host;T{ ;I"Ragel in Objective C Host;T;[I"ragel-objc;T;[I" *.rl;T; [I"XML+Django/Jinja;T{ ;I"XML+Django/Jinja;T;[I"xml+django;TI"xml+jinja;T;[; [I"application/xml+django;TI"application/xml+jinja;TI"Standard ML;T{ ;I"Standard ML;T;[I"sml;T;[I" *.sml;TI" *.sig;TI" *.fun;T; [I"text/x-standardml;TI"application/x-standardml;TI"ANTLR With Ruby Target;T{ ;I"ANTLR With Ruby Target;T;[I"antlr-ruby;TI" antlr-rb;T;[I"*.G;TI"*.g;T; [I" Duel;T{ ;I" Duel;T;[I" duel;TI" jbst;TI"jsonml+bst;T;[I" *.duel;TI" *.jbst;T; [I"text/x-duel;TI"text/x-jbst;TI"XML+Myghty;T{ ;I"XML+Myghty;T;[I"xml+myghty;T;[; [I"application/xml+myghty;Tpygments.rb-0.6.3/lib/000077500000000000000000000000001250413007300145315ustar00rootroot00000000000000pygments.rb-0.6.3/lib/pygments.rb000066400000000000000000000002201250413007300167160ustar00rootroot00000000000000require File.join(File.dirname(__FILE__), 'pygments/popen') module Pygments extend Pygments::Popen autoload :Lexer, 'pygments/lexer' end pygments.rb-0.6.3/lib/pygments/000077500000000000000000000000001250413007300163775ustar00rootroot00000000000000pygments.rb-0.6.3/lib/pygments/lexer.rb000066400000000000000000000065631250413007300200550ustar00rootroot00000000000000module Pygments class Lexer < Struct.new(:name, :aliases, :filenames, :mimetypes) @lexers = [] @index = {} @name_index = {} @alias_index = {} @extname_index = {} @mimetypes_index = {} # Internal: Create a new Lexer object # # hash - A hash of attributes # # Returns a Lexer object def self.create(hash) lexer = new(hash[:name], hash[:aliases], hash[:filenames], hash[:mimetypes]) @lexers << lexer @index[lexer.name.downcase] = @name_index[lexer.name] = lexer lexer.aliases.each do |name| @alias_index[name] = lexer @index[name.downcase] ||= lexer end lexer.filenames.each do |filename| extnames = [] extname = File.extname(filename) if m = extname.match(/\[(.+)\]/) m[1].scan(/./).each do |s| extnames << extname.sub(m[0], s) end elsif extname != "" extnames << extname end extnames.each do |extname| @extname_index[extname] = lexer @index[extname.downcase.sub(/^\./, "")] ||= lexer end end lexer.mimetypes.each do |type| @mimetypes_index[type] = lexer end lexer end # Public: Get all Lexers # # Returns an Array of Lexers def self.all @lexers end # Public: Look up Lexer by name or alias. # # name - A String name or alias # # Lexer.find('Ruby') # => # # # Returns the Lexer or nil if none was found. def self.find(name) @index[name.to_s.downcase] end # Public: Alias for find. def self.[](name) find(name) end # Public: Look up Lexer by its proper name. # # name - The String name of the Lexer # # Examples # # Lexer.find_by_name('Ruby') # # => # # # Returns the Lexer or nil if none was found. def self.find_by_name(name) @name_index[name] end # Public: Look up Lexer by one of its aliases. # # name - A String alias of the Lexer # # Examples # # Lexer.find_by_alias('rb') # # => # # # Returns the Lexer or nil if none was found. def self.find_by_alias(name) @alias_index[name] end # Public: Look up Lexer by one of it's file extensions. # # extname - A String file extension. # # Examples # # Lexer.find_by_extname('.rb') # # => # # # Returns the Lexer or nil if none was found. def self.find_by_extname(extname) @extname_index[extname] end # Public: Look up Lexer by one of it's mime types. # # type - A mime type String. # # Examples # # Lexer.find_by_mimetype('application/x-ruby') # # => # # # Returns the Lexer or nil if none was found. def self.find_by_mimetype(type) @mimetypes_index[type] end # Public: Highlight syntax of text # # text - String of code to be highlighted # options - Hash of options (defaults to {}) # # Returns html String def highlight(text, options = {}) options[:lexer] = aliases.first Pygments.highlight(text, options) end alias_method :==, :equal? alias_method :eql?, :equal? end lexers.values.each { |h| Lexer.create(h) } end pygments.rb-0.6.3/lib/pygments/mentos.py000077500000000000000000000254301250413007300202650ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, re, os, signal import traceback if 'PYGMENTS_PATH' in os.environ: sys.path.insert(0, os.environ['PYGMENTS_PATH']) dirname = os.path.dirname base_dir = dirname(dirname(dirname(os.path.abspath(__file__)))) sys.path.append(base_dir + "/vendor") sys.path.append(base_dir + "/vendor/pygments-main") sys.path.append(base_dir + "/vendor/simplejson") import pygments from pygments import lexers, formatters, styles, filters from threading import Lock try: import json except ImportError: import simplejson as json def _convert_keys(dictionary): if not isinstance(dictionary, dict): return dictionary return dict((str(k), _convert_keys(v)) for k, v in dictionary.items()) def _write_error(error): res = {"error": error} out_header = json.dumps(res).encode('utf-8') bits = _get_fixed_bits_from_header(out_header) sys.stdout.write(bits + "\n") sys.stdout.flush() sys.stdout.write(out_header + "\n") sys.stdout.flush() return def _get_fixed_bits_from_header(out_header): size = len(out_header) return "".join(map(lambda y:str((size>>y)&1), range(32-1, -1, -1))) def _signal_handler(signal, frame): """ Handle the signal given in the first argument, exiting gracefully """ sys.exit(0) class Mentos(object): """ Interacts with pygments.rb to provide access to pygments functionality """ def __init__(self): pass def return_lexer(self, lexer, args, inputs, code=None): """ Accepting a variety of possible inputs, return a Lexer object. The inputs argument should be a hash with at least one of the following keys: - 'lexer' ("python") - 'mimetype' ("text/x-ruby") - 'filename' ("yeaaah.py") The code argument should be a string, such as "import derp". The code guessing method is not especially great. It is advised that clients pass in a literal lexer name whenever possible, which provides the best probability of match (100 percent). """ if lexer: if inputs: return lexers.get_lexer_by_name(lexer, **inputs) else: return lexers.get_lexer_by_name(lexer) if inputs: if 'lexer' in inputs: return lexers.get_lexer_by_name(inputs['lexer'], **inputs) elif 'mimetype' in inputs: return lexers.get_lexer_for_mimetype(inputs['mimetype'], **inputs) elif 'filename' in inputs: name = inputs['filename'] # If we have code and a filename, pygments allows us to guess # with both. This is better than just guessing with code. if code: return lexers.guess_lexer_for_filename(name, code, **inputs) else: return lexers.get_lexer_for_filename(name, **inputs) # If all we got is code, try anyway. if code: return lexers.guess_lexer(code, **inputs) else: return None def highlight_text(self, code, lexer, formatter_name, args, kwargs): """ Highlight the relevant code, and return a result string. The default formatter is html, but alternate formatters can be passed in via the formatter_name argument. Additional paramters can be passed as args or kwargs. """ # Default to html if we don't have the formatter name. if formatter_name: _format_name = str(formatter_name) else: _format_name = "html" # Return a lexer object lexer = self.return_lexer(lexer, args, kwargs, code) # Make sure we sucessfuly got a lexer if lexer: formatter = pygments.formatters.get_formatter_by_name(str.lower(_format_name), **kwargs) # Do the damn thing. res = pygments.highlight(code, lexer, formatter) return res else: _write_error("No lexer") def get_data(self, method, lexer, args, kwargs, text=None): """ Based on the method argument, determine the action we'd like pygments to do. Then return the data generated from pygments. """ if kwargs: formatter_name = kwargs.get("formatter", None) opts = kwargs.get("options", {}) # Ensure there's a 'method' key before proceeeding if method: res = None # Now check what that method is. For the get methods, pygments # itself returns generators, so we make them lists so we can serialize # easier. if method == 'get_all_styles': res = json.dumps(list(pygments.styles.get_all_styles())) elif method == 'get_all_filters': res = json.dumps(list(pygments.filters.get_all_filters())) elif method == 'get_all_lexers': res = json.dumps(list(pygments.lexers.get_all_lexers())) elif method == 'get_all_formatters': res = [ [ft.__name__, ft.name, ft.aliases] for ft in pygments.formatters.get_all_formatters() ] res = json.dumps(res) elif method == 'highlight': try: text = text.decode('utf-8') except UnicodeDecodeError: # The text may already be encoded text = text res = self.highlight_text(text, lexer, formatter_name, args, _convert_keys(opts)) elif method == 'css': kwargs = _convert_keys(kwargs) fmt = pygments.formatters.get_formatter_by_name(args[0], **kwargs) res = fmt.get_style_defs(args[1]) elif method == 'lexer_name_for': lexer = self.return_lexer(None, args, kwargs, text) if lexer: # We don't want the Lexer itself, just the name. # Take the first alias. res = lexer.aliases[0] else: _write_error("No lexer") else: _write_error("Invalid method " + method) return res def _send_data(self, res, method): # Base header. We'll build on this, adding keys as necessary. base_header = {"method": method} res_bytes = len(res) + 1 base_header["bytes"] = res_bytes out_header = json.dumps(base_header).encode('utf-8') # Following the protocol, send over a fixed size represenation of the # size of the JSON header bits = _get_fixed_bits_from_header(out_header) # Send it to Rubyland sys.stdout.write(bits + "\n") sys.stdout.flush() # Send the header. sys.stdout.write(out_header + "\n") sys.stdout.flush() # Finally, send the result sys.stdout.write(res + "\n") sys.stdout.flush() def _get_ids(self, text): start_id = text[:8] end_id = text[-8:] return start_id, end_id def _check_and_return_text(self, text, start_id, end_id): # Sanity check. id_regex = re.compile('[A-Z]{8}') if not id_regex.match(start_id) and not id_regex.match(end_id): _write_error("ID check failed. Not an ID.") if not start_id == end_id: _write_error("ID check failed. ID's did not match.") # Passed the sanity check. Remove the id's and return text = text[10:-10] return text def _parse_header(self, header): method = header["method"] args = header.get("args", []) kwargs = header.get("kwargs", {}) lexer = kwargs.get("lexer", None) return (method, args, kwargs, lexer) def start(self): """ Main loop, waiting for inputs on stdin. When it gets some data, it goes to work. mentos exposes most of the "High-level API" of pygments. It always expects and requires a JSON header of metadata. If there is data to be pygmentized, this header will be followed by the text to be pygmentized. The header is of form: { "method": "highlight", "args": [], "kwargs": {"arg1": "v"}, "bytes": 128, "fd": "8"} """ lock = Lock() while True: # The loop begins by reading off a simple 32-arity string # representing an integer of 32 bits. This is the length of # our JSON header. size = sys.stdin.read(32) lock.acquire() try: # Read from stdin the amount of bytes we were told to expect. header_bytes = int(size, 2) # Sanity check the size size_regex = re.compile('[0-1]{32}') if not size_regex.match(size): _write_error("Size received is not valid.") line = sys.stdin.read(header_bytes) header = json.loads(line) method, args, kwargs, lexer = self._parse_header(header) _bytes = 0 if lexer: lexer = str(lexer) # Read more bytes if necessary if kwargs: _bytes = kwargs.get("bytes", 0) # Read up to the given number bytes (possibly 0) text = sys.stdin.read(_bytes) # Sanity check the return. if _bytes: start_id, end_id = self._get_ids(text) text = self._check_and_return_text(text, start_id, end_id) # Get the actual data from pygments. res = self.get_data(method, lexer, args, kwargs, text) # Put back the sanity check values. if method == "highlight": res = start_id + " " + res + " " + end_id self._send_data(res, method) except: tb = traceback.format_exc() _write_error(tb) finally: lock.release() def main(): # Signal handlers to trap signals. signal.signal(signal.SIGINT, _signal_handler) signal.signal(signal.SIGTERM, _signal_handler) if sys.platform != "win32": signal.signal(signal.SIGHUP, _signal_handler) mentos = Mentos() if sys.platform == "win32": # disable CRLF import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) else: # close fd's inherited from the ruby parent import resource maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if maxfd == resource.RLIM_INFINITY: maxfd = 65536 for fd in range(3, maxfd): try: os.close(fd) except: pass mentos.start() if __name__ == "__main__": main() pygments.rb-0.6.3/lib/pygments/popen.rb000066400000000000000000000331531250413007300200520ustar00rootroot00000000000000# coding: utf-8 require 'posix/spawn' require 'yajl' require 'timeout' require 'logger' require 'time' # Error class class MentosError < IOError end # Pygments provides access to the Pygments library via a pipe and a long-running # Python process. module Pygments module Popen include POSIX::Spawn extend self # Get things started by opening a pipe to mentos (the freshmaker), a # Python process that talks to the Pygments library. We'll talk back and # forth across this pipe. def start(pygments_path = File.expand_path('../../../vendor/pygments-main/', __FILE__)) is_windows = RUBY_PLATFORM =~ /mswin|mingw/ begin @log = Logger.new(ENV['MENTOS_LOG'] ||= is_windows ? 'NUL:' : '/dev/null') @log.level = Logger::INFO @log.datetime_format = "%Y-%m-%d %H:%M " rescue @log = Logger.new(is_windows ? 'NUL:' : '/dev/null') end ENV['PYGMENTS_PATH'] = pygments_path # Make sure we kill off the child when we're done at_exit { stop "Exiting" } # A pipe to the mentos python process. #popen4 gives us # the pid and three IO objects to write and read. python_path = python_binary(is_windows) script = "#{python_path} #{File.expand_path('../mentos.py', __FILE__)}" @pid, @in, @out, @err = popen4(script) @log.info "[#{Time.now.iso8601}] Starting pid #{@pid.to_s} with fd #{@out.to_i.to_s}." end # Detect a suitable Python binary to use. def python_binary(is_windows) if is_windows && which('py') return 'py -2' end return which('python2') || 'python' end # Cross platform which command # from http://stackoverflow.com/a/5471032/284795 def which(command) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |dir| exts.each { |ext| path = File.join(dir, "#{command}#{ext}") return path if File.executable?(path) && !File.directory?(path) } end return nil end # Stop the child process by issuing a kill -9. # # We then call waitpid() with the pid, which waits for that particular # child and reaps it. # # kill() can set errno to ESRCH if, for some reason, the file # is gone; regardless the final outcome of this method # will be to set our @pid variable to nil. # # Technically, kill() can also fail with EPERM or EINVAL (wherein # the signal isn't sent); but we have permissions, and # we're not doing anything invalid here. def stop(reason) if @pid begin Process.kill('KILL', @pid) Process.waitpid(@pid) rescue Errno::ESRCH, Errno::ECHILD end end @log.info "[#{Time.now.iso8601}] Killing pid: #{@pid.to_s}. Reason: #{reason}" @pid = nil end # Check for a @pid variable, and then hit `kill -0` with the pid to # check if the pid is still in the process table. If this function # gives us an ENOENT or ESRCH, we can also safely return false (no process # to worry about). Defensively, if EPERM is raised, in a odd/rare # dying process situation (e.g., mentos is checking on the pid of a dead # process and the pid has already been re-used) we'll want to raise # that as a more informative Mentos exception. # # Returns true if the child is alive. def alive? return true if @pid && Process.kill(0, @pid) false rescue Errno::ENOENT, Errno::ESRCH false rescue Errno::EPERM raise MentosError, "EPERM checking if child process is alive." end # Public: Get an array of available Pygments formatters # # Returns an array of formatters. def formatters mentos(:get_all_formatters).inject(Hash.new) do | hash, (name, desc, aliases) | # Remove the long-winded and repetitive 'Formatter' suffix name.sub!(/Formatter$/, '') hash[name] = { :name => name, :description => desc, :aliases => aliases } hash end end # Public: Get all lexers from a serialized array. This avoids needing to spawn # mentos when it's not really needed (e.g,. one-off jobs, loading the Rails env, etc). # # Should be preferred to #lexers! # # Returns an array of lexers def lexers begin lexer_file = File.expand_path('../../../lexers', __FILE__) raw = File.open(lexer_file, "rb").read Marshal.load(raw) rescue Errno::ENOENT raise MentosError, "Error loading lexer file. Was it created and vendored?" end end # Public: Get back all available lexers from mentos itself # # Returns an array of lexers def lexers! mentos(:get_all_lexers).inject(Hash.new) do |hash, lxr| name = lxr[0] hash[name] = { :name => name, :aliases => lxr[1], :filenames => lxr[2], :mimetypes => lxr[3] } hash["dasm16"] = {:name=>"dasm16", :aliases=>["DASM16"], :filenames=>["*.dasm16", "*.dasm"], :mimetypes=>['text/x-dasm16']} hash["Puppet"] = {:name=>"Puppet", :aliases=>["puppet"], :filenames=>["*.pp"], :mimetypes=>[]} hash["Augeas"] = {:name=>"Augeas", :aliases=>["augeas"], :filenames=>["*.aug"], :mimetypes=>[]} hash["TOML"] = {:name=>"TOML", :aliases=>["toml"], :filenames=>["*.toml"], :mimetypes=>[]} hash["Slash"] = {:name=>"Slash", :aliases=>["slash"], :filenames=>["*.sl"], :mimetypes=>[]} hash end end # Public: Return an array of all available filters def filters mentos(:get_all_filters) end # Public: Return an array of all available styles def styles mentos(:get_all_styles) end # Public: Return css for highlighted code def css(klass='', opts={}) if klass.is_a?(Hash) opts = klass klass = '' end mentos(:css, ['html', klass], opts) end # Public: Return the name of a lexer. def lexer_name_for(*args) # Pop off the last arg if it's a hash, which becomes our opts if args.last.is_a?(Hash) opts = args.pop else opts = {} end if args.last.is_a?(String) code = args.pop else code = nil end mentos(:lexer_name_for, args, opts, code) end # Public: Highlight code. # # Takes a first-position argument of the code to be highlighted, and a # second-position hash of various arguments specifiying highlighting properties. def highlight(code, opts={}) # If the caller didn't give us any code, we have nothing to do, # so return right away. return code if code.nil? || code.empty? # Callers pass along options in the hash opts[:options] ||= {} # Default to utf-8 for the output encoding, if not given. opts[:options][:outencoding] ||= 'utf-8' # Get back the string from mentos and force encoding if we can str = mentos(:highlight, nil, opts, code) str.force_encoding(opts[:options][:outencoding]) if str.respond_to?(:force_encoding) str end private # Our 'rpc'-ish request to mentos. Requires a method name, and then optional # args, kwargs, code. def mentos(method, args=[], kwargs={}, original_code=nil) # Open the pipe if necessary start unless alive? begin # Timeout requests that take too long. # Invalid MENTOS_TIMEOUT results in just using default. timeout_time = Integer(ENV["MENTOS_TIMEOUT"]) rescue 8 Timeout::timeout(timeout_time) do # For sanity checking on both sides of the pipe when highlighting, we prepend and # append an id. mentos checks that these are 8 character ids and that they match. # It then returns the id's back to Rubyland. id = (0...8).map{65.+(rand(25)).chr}.join code = add_ids(original_code, id) if original_code # Add metadata to the header and generate it. if code bytesize = code.bytesize else bytesize = 0 end kwargs.freeze kwargs = kwargs.merge("fd" => @out.to_i, "id" => id, "bytes" => bytesize) out_header = Yajl.dump(:method => method, :args => args, :kwargs => kwargs) # Get the size of the header itself and write that. bits = get_fixed_bits_from_header(out_header) @in.write(bits) # mentos is now waiting for the header, and, potentially, code. write_data(out_header, code) # mentos will now return data to us. First it sends the header. header = get_header # Now handle the header, any read any more data required. res = handle_header_and_return(header, id) # Finally, return what we got. return_result(res, method) end rescue Timeout::Error # If we timeout, we need to clear out the pipe and start over. @log.error "[#{Time.now.iso8601}] Timeout on a mentos #{method} call" stop "Timeout on mentos #{method} call." end rescue Errno::EPIPE, EOFError stop "EPIPE" raise MentosError, "EPIPE" end # Based on the header we receive, determine if we need # to read more bytes, and read those bytes if necessary. # # Then, do a sanity check wih the ids. # # Returns a result — either highlighted text or metadata. def handle_header_and_return(header, id) if header header = header_to_json(header) bytes = header["bytes"] # Read more bytes (the actual response body) res = @out.read(bytes.to_i) if header["method"] == "highlight" # Make sure we have a result back; else consider this an error. if res.nil? @log.warn "[#{Time.now.iso8601}] No highlight result back from mentos." stop "No highlight result back from mentos." raise MentosError, "No highlight result back from mentos." end # Remove the newline from Python res = res[0..-2] @log.info "[#{Time.now.iso8601}] Highlight in process." # Get the id's start_id = res[0..7] end_id = res[-8..-1] # Sanity check. if not (start_id == id and end_id == id) @log.error "[#{Time.now.iso8601}] ID's did not match. Aborting." stop "ID's did not match. Aborting." raise MentosError, "ID's did not match. Aborting." else # We're good. Remove the padding res = res[10..-11] @log.info "[#{Time.now.iso8601}] Highlighting complete." res end end res else @log.error "[#{Time.now.iso8601}] No header data back." stop "No header data back." raise MentosError, "No header received back." end end # With the code, prepend the id (with two spaces to avoid escaping weirdness if # the following text starts with a slash (like terminal code), and append the # id, with two padding also. This means we are sending over the 8 characters + # code + 8 characters. def add_ids(code, id) code.freeze code = id + " #{code} #{id}" code end # Write data to mentos, the Python Process. # # Returns nothing. def write_data(out_header, code=nil) @in.write(out_header) @log.info "[#{Time.now.iso8601}] Out header: #{out_header.to_s}" @in.write(code) if code end # Sanity check for size (32-arity of 0's and 1's) def size_check(size) size_regex = /[0-1]{32}/ if size_regex.match(size) true else false end end # Read the header via the pipe. # # Returns a header. def get_header begin size = @out.read(33) size = size[0..-2] # Sanity check the size if not size_check(size) @log.error "[#{Time.now.iso8601}] Size returned from mentos.py invalid." stop "Size returned from mentos.py invalid." raise MentosError, "Size returned from mentos.py invalid." end # Read the amount of bytes we should be expecting. We first # convert the string of bits into an integer. header_bytes = size.to_s.to_i(2) + 1 @log.info "[#{Time.now.iso8601}] Size in: #{size.to_s} (#{header_bytes.to_s})" @out.read(header_bytes) rescue @log.error "[#{Time.now.iso8601}] Failed to get header." stop "Failed to get header." raise MentosError, "Failed to get header." end end # Return the final result for the API. Return Ruby objects for the methods that # want them, text otherwise. def return_result(res, method) unless method == :lexer_name_for || method == :highlight || method == :css res = Yajl.load(res, :symbolize_keys => true) end res = res.rstrip if res.class == String res end # Convert a text header into JSON for easy access. def header_to_json(header) @log.info "[#{Time.now.iso8601}] In header: #{header.to_s} " header = Yajl.load(header) if header["error"] # Raise this as a Ruby exception of the MentosError class. # Stop so we don't leave the pipe in an inconsistent state. @log.error "[#{Time.now.iso8601}] Failed to convert header to JSON." stop header["error"] raise MentosError, header["error"] else header end end def get_fixed_bits_from_header(out_header) size = out_header.bytesize # Fixed 32 bits to represent the int. We return a string # represenation: e.g, "00000000000000000000000000011110" Array.new(32) { |i| size[i] }.reverse!.join end end end pygments.rb-0.6.3/lib/pygments/version.rb000066400000000000000000000000501250413007300204040ustar00rootroot00000000000000module Pygments VERSION = '0.6.3' end pygments.rb-0.6.3/pygments.rb.gemspec000066400000000000000000000012761250413007300176060ustar00rootroot00000000000000require File.expand_path('../lib/pygments/version', __FILE__) Gem::Specification.new do |s| s.name = 'pygments.rb' s.version = Pygments::VERSION s.summary = 'pygments wrapper for ruby' s.description = 'pygments.rb exposes the pygments syntax highlighter to Ruby' s.homepage = 'https://github.com/tmm1/pygments.rb' s.has_rdoc = false s.authors = ['Aman Gupta', 'Ted Nyman'] s.email = ['aman@tmm1.net'] s.license = 'MIT' s.add_dependency 'yajl-ruby', '~> 1.2.0' s.add_dependency 'posix-spawn', '~> 0.3.6' s.add_development_dependency 'rake-compiler', '~> 0.7.6' # s.extensions = ['ext/extconf.rb'] s.require_paths = ['lib'] s.files = `git ls-files`.split("\n") end pygments.rb-0.6.3/test/000077500000000000000000000000001250413007300147425ustar00rootroot00000000000000pygments.rb-0.6.3/test/test_data.c000066400000000000000000003023031250413007300170570ustar00rootroot00000000000000/* * Copyright (c) 2009-2010, Salvatore Sanfilippo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "redis.h" #include "slowlog.h" #include "bio.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* Our shared "common" objects */ struct sharedObjectsStruct shared; /* Global vars that are actually used as constants. The following double * values are used for double on-disk serialization, and are initialized * at runtime to avoid strange compiler optimizations. */ double R_Zero, R_PosInf, R_NegInf, R_Nan; /*================================= Globals ================================= */ /* Global vars */ struct redisServer server; /* server global state */ struct redisCommand *commandTable; /* Our command table. * * Every entry is composed of the following fields: * * name: a string representing the command name. * function: pointer to the C function implementing the command. * arity: number of arguments, it is possible to use -N to say >= N * sflags: command flags as string. See below for a table of flags. * flags: flags as bitmask. Computed by Redis using the 'sflags' field. * get_keys_proc: an optional function to get key arguments from a command. * This is only used when the following three fields are not * enough to specify what arguments are keys. * first_key_index: first argument that is a key * last_key_index: last argument that is a key * key_step: step to get all the keys from first to last argument. For instance * in MSET the step is two since arguments are key,val,key,val,... * microseconds: microseconds of total execution time for this command. * calls: total number of calls of this command. * * The flags, microseconds and calls fields are computed by Redis and should * always be set to zero. * * Command flags are expressed using strings where every character represents * a flag. Later the populateCommandTable() function will take care of * populating the real 'flags' field using this characters. * * This is the meaning of the flags: * * w: write command (may modify the key space). * r: read command (will never modify the key space). * m: may increase memory usage once called. Don't allow if out of memory. * a: admin command, like SAVE or SHUTDOWN. * p: Pub/Sub related command. * f: force replication of this command, regarless of server.dirty. * s: command not allowed in scripts. * R: random command. Command is not deterministic, that is, the same command * with the same arguments, with the same key space, may have different * results. For instance SPOP and RANDOMKEY are two random commands. * S: Sort command output array if called from script, so that the output * is deterministic. */ struct redisCommand redisCommandTable[] = { {"get",getCommand,2,"r",0,NULL,1,1,1,0,0}, {"set",setCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0}, {"setnx",setnxCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0}, {"setex",setexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0}, {"psetex",psetexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0}, {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0}, {"strlen",strlenCommand,2,"r",0,NULL,1,1,1,0,0}, {"del",delCommand,-2,"w",0,noPreloadGetKeys,1,-1,1,0,0}, {"exists",existsCommand,2,"r",0,NULL,1,1,1,0,0}, {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getbit",getbitCommand,3,"r",0,NULL,1,1,1,0,0}, {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"incr",incrCommand,2,"wm",0,NULL,1,1,1,0,0}, {"decr",decrCommand,2,"wm",0,NULL,1,1,1,0,0}, {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"rpush",rpushCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"lpush",lpushCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"rpushx",rpushxCommand,3,"wm",0,NULL,1,1,1,0,0}, {"lpushx",lpushxCommand,3,"wm",0,NULL,1,1,1,0,0}, {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0}, {"rpop",rpopCommand,2,"w",0,NULL,1,1,1,0,0}, {"lpop",lpopCommand,2,"w",0,NULL,1,1,1,0,0}, {"brpop",brpopCommand,-3,"ws",0,NULL,1,1,1,0,0}, {"brpoplpush",brpoplpushCommand,4,"wms",0,NULL,1,2,1,0,0}, {"blpop",blpopCommand,-3,"ws",0,NULL,1,-2,1,0,0}, {"llen",llenCommand,2,"r",0,NULL,1,1,1,0,0}, {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0}, {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0}, {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0}, {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0}, {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0}, {"sadd",saddCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"srem",sremCommand,-3,"w",0,NULL,1,1,1,0,0}, {"smove",smoveCommand,4,"w",0,NULL,1,2,1,0,0}, {"sismember",sismemberCommand,3,"r",0,NULL,1,1,1,0,0}, {"scard",scardCommand,2,"r",0,NULL,1,1,1,0,0}, {"spop",spopCommand,2,"wRs",0,NULL,1,1,1,0,0}, {"srandmember",srandmemberCommand,2,"rR",0,NULL,1,1,1,0,0}, {"sinter",sinterCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sunion",sunionCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sdiff",sdiffCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"smembers",sinterCommand,2,"rS",0,NULL,1,1,1,0,0}, {"zadd",zaddCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"zincrby",zincrbyCommand,4,"wm",0,NULL,1,1,1,0,0}, {"zrem",zremCommand,-3,"w",0,NULL,1,1,1,0,0}, {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0}, {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcount",zcountCommand,4,"r",0,NULL,1,1,1,0,0}, {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcard",zcardCommand,2,"r",0,NULL,1,1,1,0,0}, {"zscore",zscoreCommand,3,"r",0,NULL,1,1,1,0,0}, {"zrank",zrankCommand,3,"r",0,NULL,1,1,1,0,0}, {"zrevrank",zrevrankCommand,3,"r",0,NULL,1,1,1,0,0}, {"hset",hsetCommand,4,"wm",0,NULL,1,1,1,0,0}, {"hsetnx",hsetnxCommand,4,"wm",0,NULL,1,1,1,0,0}, {"hget",hgetCommand,3,"r",0,NULL,1,1,1,0,0}, {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0}, {"hincrby",hincrbyCommand,4,"wm",0,NULL,1,1,1,0,0}, {"hincrbyfloat",hincrbyfloatCommand,4,"wm",0,NULL,1,1,1,0,0}, {"hdel",hdelCommand,-3,"w",0,NULL,1,1,1,0,0}, {"hlen",hlenCommand,2,"r",0,NULL,1,1,1,0,0}, {"hkeys",hkeysCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hvals",hvalsCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0}, {"hexists",hexistsCommand,3,"r",0,NULL,1,1,1,0,0}, {"incrby",incrbyCommand,3,"wm",0,NULL,1,1,1,0,0}, {"decrby",decrbyCommand,3,"wm",0,NULL,1,1,1,0,0}, {"incrbyfloat",incrbyfloatCommand,3,"wm",0,NULL,1,1,1,0,0}, {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0}, {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0}, {"select",selectCommand,2,"r",0,NULL,0,0,0,0,0}, {"move",moveCommand,3,"w",0,NULL,1,1,1,0,0}, {"rename",renameCommand,3,"w",0,renameGetKeys,1,2,1,0,0}, {"renamenx",renamenxCommand,3,"w",0,renameGetKeys,1,2,1,0,0}, {"expire",expireCommand,3,"w",0,NULL,1,1,1,0,0}, {"expireat",expireatCommand,3,"w",0,NULL,1,1,1,0,0}, {"pexpire",pexpireCommand,3,"w",0,NULL,1,1,1,0,0}, {"pexpireat",pexpireatCommand,3,"w",0,NULL,1,1,1,0,0}, {"keys",keysCommand,2,"rS",0,NULL,0,0,0,0,0}, {"dbsize",dbsizeCommand,1,"r",0,NULL,0,0,0,0,0}, {"auth",authCommand,2,"rs",0,NULL,0,0,0,0,0}, {"ping",pingCommand,1,"r",0,NULL,0,0,0,0,0}, {"echo",echoCommand,2,"r",0,NULL,0,0,0,0,0}, {"save",saveCommand,1,"ars",0,NULL,0,0,0,0,0}, {"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0}, {"bgrewriteaof",bgrewriteaofCommand,1,"ar",0,NULL,0,0,0,0,0}, {"shutdown",shutdownCommand,-1,"ar",0,NULL,0,0,0,0,0}, {"lastsave",lastsaveCommand,1,"r",0,NULL,0,0,0,0,0}, {"type",typeCommand,2,"r",0,NULL,1,1,1,0,0}, {"multi",multiCommand,1,"rs",0,NULL,0,0,0,0,0}, {"exec",execCommand,1,"s",0,NULL,0,0,0,0,0}, {"discard",discardCommand,1,"rs",0,NULL,0,0,0,0,0}, {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0}, {"replconf",replconfCommand,-1,"ars",0,NULL,0,0,0,0,0}, {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0}, {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0}, {"sort",sortCommand,-2,"wmS",0,NULL,1,1,1,0,0}, {"info",infoCommand,-1,"r",0,NULL,0,0,0,0,0}, {"monitor",monitorCommand,1,"ars",0,NULL,0,0,0,0,0}, {"ttl",ttlCommand,2,"r",0,NULL,1,1,1,0,0}, {"pttl",pttlCommand,2,"r",0,NULL,1,1,1,0,0}, {"persist",persistCommand,2,"w",0,NULL,1,1,1,0,0}, {"slaveof",slaveofCommand,3,"as",0,NULL,0,0,0,0,0}, {"debug",debugCommand,-2,"as",0,NULL,0,0,0,0,0}, {"config",configCommand,-2,"ar",0,NULL,0,0,0,0,0}, {"subscribe",subscribeCommand,-2,"rps",0,NULL,0,0,0,0,0}, {"unsubscribe",unsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0}, {"psubscribe",psubscribeCommand,-2,"rps",0,NULL,0,0,0,0,0}, {"punsubscribe",punsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0}, {"publish",publishCommand,3,"pf",0,NULL,0,0,0,0,0}, {"watch",watchCommand,-2,"rs",0,noPreloadGetKeys,1,-1,1,0,0}, {"unwatch",unwatchCommand,1,"rs",0,NULL,0,0,0,0,0}, {"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0}, {"restore",restoreCommand,4,"awm",0,NULL,1,1,1,0,0}, {"migrate",migrateCommand,6,"aw",0,NULL,0,0,0,0,0}, {"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0}, {"dump",dumpCommand,2,"ar",0,NULL,1,1,1,0,0}, {"object",objectCommand,-2,"r",0,NULL,2,2,2,0,0}, {"client",clientCommand,-2,"ar",0,NULL,0,0,0,0,0}, {"eval",evalCommand,-3,"s",0,zunionInterGetKeys,0,0,0,0,0}, {"evalsha",evalShaCommand,-3,"s",0,zunionInterGetKeys,0,0,0,0,0}, {"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0}, {"script",scriptCommand,-2,"ras",0,NULL,0,0,0,0,0}, {"time",timeCommand,1,"rR",0,NULL,0,0,0,0,0}, {"bitop",bitopCommand,-4,"wm",0,NULL,2,-1,1,0,0}, {"bitcount",bitcountCommand,-2,"r",0,NULL,1,1,1,0,0} }; /*============================ Utility functions ============================ */ /* Low level logging. To use only for very big messages, otherwise * redisLog() is to prefer. */ void redisLogRaw(int level, const char *msg) { const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; const char *c = ".-*#"; FILE *fp; char buf[64]; int rawmode = (level & REDIS_LOG_RAW); level &= 0xff; /* clear flags */ if (level < server.verbosity) return; fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a"); if (!fp) return; if (rawmode) { fprintf(fp,"%s",msg); } else { int off; struct timeval tv; gettimeofday(&tv,NULL); off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg); } fflush(fp); if (server.logfile) fclose(fp); if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg); } /* Like redisLogRaw() but with printf-alike support. This is the funciton that * is used across the code. The raw version is only used in order to dump * the INFO output on crash. */ void redisLog(int level, const char *fmt, ...) { va_list ap; char msg[REDIS_MAX_LOGMSG_LEN]; if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); redisLogRaw(level,msg); } /* Log a fixed message without printf-alike capabilities, in a way that is * safe to call from a signal handler. * * We actually use this only for signals that are not fatal from the point * of view of Redis. Signals that are going to kill the server anyway and * where we need printf-alike features are served by redisLog(). */ void redisLogFromHandler(int level, const char *msg) { int fd; char buf[64]; if ((level&0xff) < server.verbosity || (server.logfile == NULL && server.daemonize)) return; fd = server.logfile ? open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644) : STDOUT_FILENO; if (fd == -1) return; ll2string(buf,sizeof(buf),getpid()); if (write(fd,"[",1) == -1) goto err; if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd," | signal handler] (",20) == -1) goto err; ll2string(buf,sizeof(buf),time(NULL)); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,") ",2) == -1) goto err; if (write(fd,msg,strlen(msg)) == -1) goto err; if (write(fd,"\n",1) == -1) goto err; err: if (server.logfile) close(fd); } /* Redis generally does not try to recover from out of memory conditions * when allocating objects or strings, it is not clear if it will be possible * to report this condition to the client since the networking layer itself * is based on heap allocation for send buffers, so we simply abort. * At least the code will be simpler to read... */ void oom(const char *msg) { redisLog(REDIS_WARNING, "%s: Out of memory\n",msg); sleep(1); abort(); } /* Return the UNIX time in microseconds */ long long ustime(void) { struct timeval tv; long long ust; gettimeofday(&tv, NULL); ust = ((long long)tv.tv_sec)*1000000; ust += tv.tv_usec; return ust; } /* Return the UNIX time in milliseconds */ long long mstime(void) { return ustime()/1000; } /* After an RDB dump or AOF rewrite we exit from children using _exit() instead of * exit(), because the latter may interact with the same file objects used by * the parent process. However if we are testing the coverage normal exit() is * used in order to obtain the right coverage information. */ void exitFromChild(int retcode) { #ifdef COVERAGE_TEST exit(retcode); #else _exit(retcode); #endif } /*====================== Hash table type implementation ==================== */ /* This is an hash table type that uses the SDS dynamic strings libary as * keys and radis objects as values (objects can hold SDS strings, * lists, sets). */ void dictVanillaFree(void *privdata, void *val) { DICT_NOTUSED(privdata); zfree(val); } void dictListDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); listRelease((list*)val); } int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2) { int l1,l2; DICT_NOTUSED(privdata); l1 = sdslen((sds)key1); l2 = sdslen((sds)key2); if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } /* A case insensitive version used for the command lookup table. */ int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2) { DICT_NOTUSED(privdata); return strcasecmp(key1, key2) == 0; } void dictRedisObjectDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); if (val == NULL) return; /* Values of swapped out keys as set to NULL */ decrRefCount(val); } void dictSdsDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); sdsfree(val); } int dictObjKeyCompare(void *privdata, const void *key1, const void *key2) { const robj *o1 = key1, *o2 = key2; return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); } unsigned int dictObjHash(const void *key) { const robj *o = key; return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } unsigned int dictSdsHash(const void *key) { return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); } unsigned int dictSdsCaseHash(const void *key) { return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key)); } int dictEncObjKeyCompare(void *privdata, const void *key1, const void *key2) { robj *o1 = (robj*) key1, *o2 = (robj*) key2; int cmp; if (o1->encoding == REDIS_ENCODING_INT && o2->encoding == REDIS_ENCODING_INT) return o1->ptr == o2->ptr; o1 = getDecodedObject(o1); o2 = getDecodedObject(o2); cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); decrRefCount(o1); decrRefCount(o2); return cmp; } unsigned int dictEncObjHash(const void *key) { robj *o = (robj*) key; if (o->encoding == REDIS_ENCODING_RAW) { return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } else { if (o->encoding == REDIS_ENCODING_INT) { char buf[32]; int len; len = ll2string(buf,32,(long)o->ptr); return dictGenHashFunction((unsigned char*)buf, len); } else { unsigned int hash; o = getDecodedObject(o); hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); decrRefCount(o); return hash; } } } /* Sets type hash table */ dictType setDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ dictType zsetDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Db->dict, keys are sds strings, vals are Redis objects. */ dictType dbDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictRedisObjectDestructor /* val destructor */ }; /* Db->expires */ dictType keyptrDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ NULL, /* key destructor */ NULL /* val destructor */ }; /* Command table. sds string -> command struct pointer. */ dictType commandTableDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Hash type hash table (note that small hashes are represented with zimpaps) */ dictType hashDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ dictRedisObjectDestructor /* val destructor */ }; /* Keylist hash table type has unencoded redis objects as keys and * lists as values. It's used for blocking operations (BLPOP) and to * map swapped keys to a list of clients waiting for this keys to be loaded. */ dictType keylistDictType = { dictObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictObjKeyCompare, /* key compare */ dictRedisObjectDestructor, /* key destructor */ dictListDestructor /* val destructor */ }; /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to * clusterNode structures. */ dictType clusterNodesDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; int htNeedsResize(dict *dict) { long long size, used; size = dictSlots(dict); used = dictSize(dict); return (size && used && size > DICT_HT_INITIAL_SIZE && (used*100/size < REDIS_HT_MINFILL)); } /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL * we resize the hash table to save memory */ void tryResizeHashTables(void) { int j; for (j = 0; j < server.dbnum; j++) { if (htNeedsResize(server.db[j].dict)) dictResize(server.db[j].dict); if (htNeedsResize(server.db[j].expires)) dictResize(server.db[j].expires); } } /* Our hash table implementation performs rehashing incrementally while * we write/read from the hash table. Still if the server is idle, the hash * table will use two tables for a long time. So we try to use 1 millisecond * of CPU time at every serverCron() loop in order to rehash some key. */ void incrementallyRehash(void) { int j; for (j = 0; j < server.dbnum; j++) { /* Keys dictionary */ if (dictIsRehashing(server.db[j].dict)) { dictRehashMilliseconds(server.db[j].dict,1); break; /* already used our millisecond for this loop... */ } /* Expires */ if (dictIsRehashing(server.db[j].expires)) { dictRehashMilliseconds(server.db[j].expires,1); break; /* already used our millisecond for this loop... */ } } } /* This function is called once a background process of some kind terminates, * as we want to avoid resizing the hash tables when there is a child in order * to play well with copy-on-write (otherwise when a resize happens lots of * memory pages are copied). The goal of this function is to update the ability * for dict.c to resize the hash tables accordingly to the fact we have o not * running childs. */ void updateDictResizePolicy(void) { if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) dictEnableResize(); else dictDisableResize(); } /* ======================= Cron: called every 100 ms ======================== */ /* Try to expire a few timed out keys. The algorithm used is adaptive and * will use few CPU cycles if there are few expiring keys, otherwise * it will get more aggressive to avoid that too much memory is used by * keys that can be removed from the keyspace. */ void activeExpireCycle(void) { int j, iteration = 0; long long start = ustime(), timelimit; /* We can use at max REDIS_EXPIRELOOKUPS_TIME_PERC percentage of CPU time * per iteration. Since this function gets called with a frequency of * REDIS_HZ times per second, the following is the max amount of * microseconds we can spend in this function. */ timelimit = 1000000*REDIS_EXPIRELOOKUPS_TIME_PERC/REDIS_HZ/100; if (timelimit <= 0) timelimit = 1; for (j = 0; j < server.dbnum; j++) { int expired; redisDb *db = server.db+j; /* Continue to expire if at the end of the cycle more than 25% * of the keys were expired. */ do { unsigned long num = dictSize(db->expires); unsigned long slots = dictSlots(db->expires); long long now = mstime(); /* When there are less than 1% filled slots getting random * keys is expensive, so stop here waiting for better times... * The dictionary will be resized asap. */ if (num && slots > DICT_HT_INITIAL_SIZE && (num*100/slots < 1)) break; /* The main collection cycle. Sample random keys among keys * with an expire set, checking for expired ones. */ expired = 0; if (num > REDIS_EXPIRELOOKUPS_PER_CRON) num = REDIS_EXPIRELOOKUPS_PER_CRON; while (num--) { dictEntry *de; long long t; if ((de = dictGetRandomKey(db->expires)) == NULL) break; t = dictGetSignedIntegerVal(de); if (now > t) { sds key = dictGetKey(de); robj *keyobj = createStringObject(key,sdslen(key)); propagateExpire(db,keyobj); dbDelete(db,keyobj); decrRefCount(keyobj); expired++; server.stat_expiredkeys++; } } /* We can't block forever here even if there are many keys to * expire. So after a given amount of milliseconds return to the * caller waiting for the other active expire cycle. */ iteration++; if ((iteration & 0xf) == 0 && /* check once every 16 cycles. */ (ustime()-start) > timelimit) return; } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4); } } void updateLRUClock(void) { server.lruclock = (server.unixtime/REDIS_LRU_CLOCK_RESOLUTION) & REDIS_LRU_CLOCK_MAX; } /* Add a sample to the operations per second array of samples. */ void trackOperationsPerSecond(void) { long long t = mstime() - server.ops_sec_last_sample_time; long long ops = server.stat_numcommands - server.ops_sec_last_sample_ops; long long ops_sec; ops_sec = t > 0 ? (ops*1000/t) : 0; server.ops_sec_samples[server.ops_sec_idx] = ops_sec; server.ops_sec_idx = (server.ops_sec_idx+1) % REDIS_OPS_SEC_SAMPLES; server.ops_sec_last_sample_time = mstime(); server.ops_sec_last_sample_ops = server.stat_numcommands; } /* Return the mean of all the samples. */ long long getOperationsPerSecond(void) { int j; long long sum = 0; for (j = 0; j < REDIS_OPS_SEC_SAMPLES; j++) sum += server.ops_sec_samples[j]; return sum / REDIS_OPS_SEC_SAMPLES; } /* Check for timeouts. Returns non-zero if the client was terminated */ int clientsCronHandleTimeout(redisClient *c) { time_t now = server.unixtime; if (server.maxidletime && !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */ !(c->flags & REDIS_MASTER) && /* no timeout for masters */ !(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */ dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */ listLength(c->pubsub_patterns) == 0 && (now - c->lastinteraction > server.maxidletime)) { redisLog(REDIS_VERBOSE,"Closing idle client"); freeClient(c); return 1; } else if (c->flags & REDIS_BLOCKED) { if (c->bpop.timeout != 0 && c->bpop.timeout < now) { addReply(c,shared.nullmultibulk); unblockClientWaitingData(c); } } return 0; } /* The client query buffer is an sds.c string that can end with a lot of * free space not used, this function reclaims space if needed. * * The funciton always returns 0 as it never terminates the client. */ int clientsCronResizeQueryBuffer(redisClient *c) { size_t querybuf_size = sdsAllocSize(c->querybuf); time_t idletime = server.unixtime - c->lastinteraction; /* There are two conditions to resize the query buffer: * 1) Query buffer is > BIG_ARG and too big for latest peak. * 2) Client is inactive and the buffer is bigger than 1k. */ if (((querybuf_size > REDIS_MBULK_BIG_ARG) && (querybuf_size/(c->querybuf_peak+1)) > 2) || (querybuf_size > 1024 && idletime > 2)) { /* Only resize the query buffer if it is actually wasting space. */ if (sdsavail(c->querybuf) > 1024) { c->querybuf = sdsRemoveFreeSpace(c->querybuf); } } /* Reset the peak again to capture the peak memory usage in the next * cycle. */ c->querybuf_peak = 0; return 0; } void clientsCron(void) { /* Make sure to process at least 1/(REDIS_HZ*10) of clients per call. * Since this function is called REDIS_HZ times per second we are sure that * in the worst case we process all the clients in 10 seconds. * In normal conditions (a reasonable number of clients) we process * all the clients in a shorter time. */ int numclients = listLength(server.clients); int iterations = numclients/(REDIS_HZ*10); if (iterations < 50) iterations = (numclients < 50) ? numclients : 50; while(listLength(server.clients) && iterations--) { redisClient *c; listNode *head; /* Rotate the list, take the current head, process. * This way if the client must be removed from the list it's the * first element and we don't incur into O(N) computation. */ listRotate(server.clients); head = listFirst(server.clients); c = listNodeValue(head); /* The following functions do different service checks on the client. * The protocol is that they return non-zero if the client was * terminated. */ if (clientsCronHandleTimeout(c)) continue; if (clientsCronResizeQueryBuffer(c)) continue; } } /* This is our timer interrupt, called REDIS_HZ times per second. * Here is where we do a number of things that need to be done asynchronously. * For instance: * * - Active expired keys collection (it is also performed in a lazy way on * lookup). * - Software watchdong. * - Update some statistic. * - Incremental rehashing of the DBs hash tables. * - Triggering BGSAVE / AOF rewrite, and handling of terminated children. * - Clients timeout of differnet kinds. * - Replication reconnection. * - Many more... * * Everything directly called here will be called REDIS_HZ times per second, * so in order to throttle execution of things we want to do less frequently * a macro is used: run_with_period(milliseconds) { .... } */ /* Using the following macro you can run code inside serverCron() with the * specified period, specified in milliseconds. * The actual resolution depends on REDIS_HZ. */ #define run_with_period(_ms_) if (!(loops % ((_ms_)/(1000/REDIS_HZ)))) int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { int j, loops = server.cronloops; REDIS_NOTUSED(eventLoop); REDIS_NOTUSED(id); REDIS_NOTUSED(clientData); /* Software watchdog: deliver the SIGALRM that will reach the signal * handler if we don't return here fast enough. */ if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period); /* We take a cached value of the unix time in the global state because * with virtual memory and aging there is to store the current time * in objects at every object access, and accuracy is not needed. * To access a global var is faster than calling time(NULL) */ server.unixtime = time(NULL); run_with_period(100) trackOperationsPerSecond(); /* We have just 22 bits per object for LRU information. * So we use an (eventually wrapping) LRU clock with 10 seconds resolution. * 2^22 bits with 10 seconds resoluton is more or less 1.5 years. * * Note that even if this will wrap after 1.5 years it's not a problem, * everything will still work but just some object will appear younger * to Redis. But for this to happen a given object should never be touched * for 1.5 years. * * Note that you can change the resolution altering the * REDIS_LRU_CLOCK_RESOLUTION define. */ updateLRUClock(); /* Record the max memory used since the server was started. */ if (zmalloc_used_memory() > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used_memory(); /* We received a SIGTERM, shutting down here in a safe way, as it is * not ok doing so inside the signal handler. */ if (server.shutdown_asap) { if (prepareForShutdown(0) == REDIS_OK) exit(0); redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); } /* Show some info about non-empty databases */ run_with_period(5000) { for (j = 0; j < server.dbnum; j++) { long long size, used, vkeys; size = dictSlots(server.db[j].dict); used = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (used || vkeys) { redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); /* dictPrintStats(server.dict); */ } } } /* We don't want to resize the hash tables while a bacground saving * is in progress: the saving child is created using fork() that is * implemented with a copy-on-write semantic in most modern systems, so * if we resize the HT while there is the saving child at work actually * a lot of memory movements in the parent will cause a lot of pages * copied. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) { tryResizeHashTables(); if (server.activerehashing) incrementallyRehash(); } /* Show information about connected clients */ run_with_period(5000) { redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use", listLength(server.clients)-listLength(server.slaves), listLength(server.slaves), zmalloc_used_memory()); } /* We need to do a few operations on clients asynchronously. */ clientsCron(); /* Start a scheduled AOF rewrite if this was requested by the user while * a BGSAVE was in progress. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_scheduled) { rewriteAppendOnlyFileBackground(); } /* Check if a background saving or AOF rewrite in progress terminated. */ if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) { int statloc; pid_t pid; if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { int exitcode = WEXITSTATUS(statloc); int bysignal = 0; if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); if (pid == server.rdb_child_pid) { backgroundSaveDoneHandler(exitcode,bysignal); } else { backgroundRewriteDoneHandler(exitcode,bysignal); } updateDictResizePolicy(); } } else { /* If there is not a background saving/rewrite in progress check if * we have to save/rewrite now */ for (j = 0; j < server.saveparamslen; j++) { struct saveparam *sp = server.saveparams+j; if (server.dirty >= sp->changes && server.unixtime-server.lastsave > sp->seconds) { redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...", sp->changes, sp->seconds); rdbSaveBackground(server.rdb_filename); break; } } /* Trigger an AOF rewrite if needed */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_perc && server.aof_current_size > server.aof_rewrite_min_size) { long long base = server.aof_rewrite_base_size ? server.aof_rewrite_base_size : 1; long long growth = (server.aof_current_size*100/base) - 100; if (growth >= server.aof_rewrite_perc) { redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth); rewriteAppendOnlyFileBackground(); } } } /* If we postponed an AOF buffer flush, let's try to do it every time the * cron function is called. */ if (server.aof_flush_postponed_start) flushAppendOnlyFile(0); /* Expire a few keys per cycle, only if this is a master. * On slaves we wait for DEL operations synthesized by the master * in order to guarantee a strict consistency. */ if (server.masterhost == NULL) activeExpireCycle(); /* Close clients that need to be closed asynchronous */ freeClientsInAsyncFreeQueue(); /* Replication cron function -- used to reconnect to master and * to detect transfer failures. */ run_with_period(1000) replicationCron(); /* Run other sub-systems specific cron jobs */ run_with_period(1000) { if (server.cluster_enabled) clusterCron(); } server.cronloops++; return 1000/REDIS_HZ; } /* This function gets called every time Redis is entering the * main loop of the event driven library, that is, before to sleep * for ready file descriptors. */ void beforeSleep(struct aeEventLoop *eventLoop) { REDIS_NOTUSED(eventLoop); listNode *ln; redisClient *c; /* Try to process pending commands for clients that were just unblocked. */ while (listLength(server.unblocked_clients)) { ln = listFirst(server.unblocked_clients); redisAssert(ln != NULL); c = ln->value; listDelNode(server.unblocked_clients,ln); c->flags &= ~REDIS_UNBLOCKED; /* Process remaining data in the input buffer. */ if (c->querybuf && sdslen(c->querybuf) > 0) { server.current_client = c; processInputBuffer(c); server.current_client = NULL; } } /* Write the AOF buffer on disk */ flushAppendOnlyFile(0); } /* =========================== Server initialization ======================== */ void createSharedObjects(void) { int j; shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n")); shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n")); shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n")); shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n")); shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n")); shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n")); shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n")); shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n")); shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n")); shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n")); shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n")); shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n")); shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew( "-ERR Operation against a key holding the wrong kind of value\r\n")); shared.nokeyerr = createObject(REDIS_STRING,sdsnew( "-ERR no such key\r\n")); shared.syntaxerr = createObject(REDIS_STRING,sdsnew( "-ERR syntax error\r\n")); shared.sameobjecterr = createObject(REDIS_STRING,sdsnew( "-ERR source and destination objects are the same\r\n")); shared.outofrangeerr = createObject(REDIS_STRING,sdsnew( "-ERR index out of range\r\n")); shared.noscripterr = createObject(REDIS_STRING,sdsnew( "-NOSCRIPT No matching script. Please use EVAL.\r\n")); shared.loadingerr = createObject(REDIS_STRING,sdsnew( "-LOADING Redis is loading the dataset in memory\r\n")); shared.slowscripterr = createObject(REDIS_STRING,sdsnew( "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); shared.masterdownerr = createObject(REDIS_STRING,sdsnew( "-MASTERDOWN Link with MASTER is down and slave-serve-stale-data is set to 'no'.\r\n")); shared.bgsaveerr = createObject(REDIS_STRING,sdsnew( "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.\r\n")); shared.roslaveerr = createObject(REDIS_STRING,sdsnew( "-READONLY You can't write against a read only slave.\r\n")); shared.oomerr = createObject(REDIS_STRING,sdsnew( "-OOM command not allowed when used memory > 'maxmemory'.\r\n")); shared.space = createObject(REDIS_STRING,sdsnew(" ")); shared.colon = createObject(REDIS_STRING,sdsnew(":")); shared.plus = createObject(REDIS_STRING,sdsnew("+")); for (j = 0; j < REDIS_SHARED_SELECT_CMDS; j++) { shared.select[j] = createObject(REDIS_STRING, sdscatprintf(sdsempty(),"select %d\r\n", j)); } shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); shared.del = createStringObject("DEL",3); shared.rpop = createStringObject("RPOP",4); shared.lpop = createStringObject("LPOP",4); for (j = 0; j < REDIS_SHARED_INTEGERS; j++) { shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j); shared.integers[j]->encoding = REDIS_ENCODING_INT; } for (j = 0; j < REDIS_SHARED_BULKHDR_LEN; j++) { shared.mbulkhdr[j] = createObject(REDIS_STRING, sdscatprintf(sdsempty(),"*%d\r\n",j)); shared.bulkhdr[j] = createObject(REDIS_STRING, sdscatprintf(sdsempty(),"$%d\r\n",j)); } } void initServerConfig() { getRandomHexChars(server.runid,REDIS_RUN_ID_SIZE); server.runid[REDIS_RUN_ID_SIZE] = '\0'; server.arch_bits = (sizeof(long) == 8) ? 64 : 32; server.port = REDIS_SERVERPORT; server.bindaddr = NULL; server.unixsocket = NULL; server.unixsocketperm = 0; server.ipfd = -1; server.sofd = -1; server.dbnum = REDIS_DEFAULT_DBNUM; server.verbosity = REDIS_NOTICE; server.maxidletime = REDIS_MAXIDLETIME; server.client_max_querybuf_len = REDIS_MAX_QUERYBUF_LEN; server.saveparams = NULL; server.loading = 0; server.logfile = NULL; /* NULL = log on standard output */ server.syslog_enabled = 0; server.syslog_ident = zstrdup("redis"); server.syslog_facility = LOG_LOCAL0; server.daemonize = 0; server.aof_state = REDIS_AOF_OFF; server.aof_fsync = AOF_FSYNC_EVERYSEC; server.aof_no_fsync_on_rewrite = 0; server.aof_rewrite_perc = REDIS_AOF_REWRITE_PERC; server.aof_rewrite_min_size = REDIS_AOF_REWRITE_MIN_SIZE; server.aof_rewrite_base_size = 0; server.aof_rewrite_scheduled = 0; server.aof_last_fsync = time(NULL); server.aof_rewrite_time_last = -1; server.aof_rewrite_time_start = -1; server.aof_delayed_fsync = 0; server.aof_fd = -1; server.aof_selected_db = -1; /* Make sure the first time will not match */ server.aof_flush_postponed_start = 0; server.pidfile = zstrdup("/var/run/redis.pid"); server.rdb_filename = zstrdup("dump.rdb"); server.aof_filename = zstrdup("appendonly.aof"); server.requirepass = NULL; server.rdb_compression = 1; server.rdb_checksum = 1; server.activerehashing = 1; server.maxclients = REDIS_MAX_CLIENTS; server.bpop_blocked_clients = 0; server.maxmemory = 0; server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU; server.maxmemory_samples = 3; server.hash_max_ziplist_entries = REDIS_HASH_MAX_ZIPLIST_ENTRIES; server.hash_max_ziplist_value = REDIS_HASH_MAX_ZIPLIST_VALUE; server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES; server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE; server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES; server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES; server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE; server.shutdown_asap = 0; server.repl_ping_slave_period = REDIS_REPL_PING_SLAVE_PERIOD; server.repl_timeout = REDIS_REPL_TIMEOUT; server.cluster_enabled = 0; server.cluster.configfile = zstrdup("nodes.conf"); server.lua_caller = NULL; server.lua_time_limit = REDIS_LUA_TIME_LIMIT; server.lua_client = NULL; server.lua_timedout = 0; updateLRUClock(); resetServerSaveParams(); appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ /* Replication related */ server.masterauth = NULL; server.masterhost = NULL; server.masterport = 6379; server.master = NULL; server.repl_state = REDIS_REPL_NONE; server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT; server.repl_serve_stale_data = 1; server.repl_slave_ro = 1; server.repl_down_since = time(NULL); /* Client output buffer limits */ server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].hard_limit_bytes = 0; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_bytes = 0; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_seconds = 0; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].hard_limit_bytes = 1024*1024*256; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_bytes = 1024*1024*64; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_seconds = 60; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].hard_limit_bytes = 1024*1024*32; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_bytes = 1024*1024*8; server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_seconds = 60; /* Double constants initialization */ R_Zero = 0.0; R_PosInf = 1.0/R_Zero; R_NegInf = -1.0/R_Zero; R_Nan = R_Zero/R_Zero; /* Command table -- we intiialize it here as it is part of the * initial configuration, since command names may be changed via * redis.conf using the rename-command directive. */ server.commands = dictCreate(&commandTableDictType,NULL); populateCommandTable(); server.delCommand = lookupCommandByCString("del"); server.multiCommand = lookupCommandByCString("multi"); server.lpushCommand = lookupCommandByCString("lpush"); /* Slow log */ server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN; server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN; /* Debugging */ server.assert_failed = ""; server.assert_file = ""; server.assert_line = 0; server.bug_report_start = 0; server.watchdog_period = 0; } /* This function will try to raise the max number of open files accordingly to * the configured max number of clients. It will also account for 32 additional * file descriptors as we need a few more for persistence, listening * sockets, log files and so forth. * * If it will not be possible to set the limit accordingly to the configured * max number of clients, the function will do the reverse setting * server.maxclients to the value that we can actually handle. */ void adjustOpenFilesLimit(void) { rlim_t maxfiles = server.maxclients+32; struct rlimit limit; if (getrlimit(RLIMIT_NOFILE,&limit) == -1) { redisLog(REDIS_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", strerror(errno)); server.maxclients = 1024-32; } else { rlim_t oldlimit = limit.rlim_cur; /* Set the max number of files if the current limit is not enough * for our needs. */ if (oldlimit < maxfiles) { rlim_t f; f = maxfiles; while(f > oldlimit) { limit.rlim_cur = f; limit.rlim_max = f; if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break; f -= 128; } if (f < oldlimit) f = oldlimit; if (f != maxfiles) { server.maxclients = f-32; redisLog(REDIS_WARNING,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.", (int) maxfiles, strerror(errno), (int) server.maxclients); } else { redisLog(REDIS_NOTICE,"Max number of open files set to %d", (int) maxfiles); } } } } void initServer() { int j; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); setupSignalHandlers(); if (server.syslog_enabled) { openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, server.syslog_facility); } server.current_client = NULL; server.clients = listCreate(); server.clients_to_close = listCreate(); server.slaves = listCreate(); server.monitors = listCreate(); server.unblocked_clients = listCreate(); createSharedObjects(); adjustOpenFilesLimit(); server.el = aeCreateEventLoop(server.maxclients+1024); server.db = zmalloc(sizeof(redisDb)*server.dbnum); if (server.port != 0) { server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr); if (server.ipfd == ANET_ERR) { redisLog(REDIS_WARNING, "Opening port %d: %s", server.port, server.neterr); exit(1); } } if (server.unixsocket != NULL) { unlink(server.unixsocket); /* don't care if this fails */ server.sofd = anetUnixServer(server.neterr,server.unixsocket,server.unixsocketperm); if (server.sofd == ANET_ERR) { redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr); exit(1); } } if (server.ipfd < 0 && server.sofd < 0) { redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting."); exit(1); } for (j = 0; j < server.dbnum; j++) { server.db[j].dict = dictCreate(&dbDictType,NULL); server.db[j].expires = dictCreate(&keyptrDictType,NULL); server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); server.db[j].id = j; } server.pubsub_channels = dictCreate(&keylistDictType,NULL); server.pubsub_patterns = listCreate(); listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); server.cronloops = 0; server.rdb_child_pid = -1; server.aof_child_pid = -1; aofRewriteBufferReset(); server.aof_buf = sdsempty(); server.lastsave = time(NULL); server.rdb_save_time_last = -1; server.rdb_save_time_start = -1; server.dirty = 0; server.stat_numcommands = 0; server.stat_numconnections = 0; server.stat_expiredkeys = 0; server.stat_evictedkeys = 0; server.stat_starttime = time(NULL); server.stat_keyspace_misses = 0; server.stat_keyspace_hits = 0; server.stat_peak_memory = 0; server.stat_fork_time = 0; server.stat_rejected_conn = 0; memset(server.ops_sec_samples,0,sizeof(server.ops_sec_samples)); server.ops_sec_idx = 0; server.ops_sec_last_sample_time = mstime(); server.ops_sec_last_sample_ops = 0; server.unixtime = time(NULL); server.lastbgsave_status = REDIS_OK; server.stop_writes_on_bgsave_err = 1; aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL); if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE, acceptTcpHandler,NULL) == AE_ERR) oom("creating file event"); if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE, acceptUnixHandler,NULL) == AE_ERR) oom("creating file event"); if (server.aof_state == REDIS_AOF_ON) { server.aof_fd = open(server.aof_filename, O_WRONLY|O_APPEND|O_CREAT,0644); if (server.aof_fd == -1) { redisLog(REDIS_WARNING, "Can't open the append-only file: %s", strerror(errno)); exit(1); } } /* 32 bit instances are limited to 4GB of address space, so if there is * no explicit limit in the user provided configuration we set a limit * at 3.5GB using maxmemory with 'noeviction' policy'. This saves * useless crashes of the Redis instance. */ if (server.arch_bits == 32 && server.maxmemory == 0) { redisLog(REDIS_WARNING,"Warning: 32 bit instance detected but no memory limit set. Setting 3.5 GB maxmemory limit with 'noeviction' policy now."); server.maxmemory = 3584LL*(1024*1024); /* 3584 MB = 3.5 GB */ server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION; } if (server.cluster_enabled) clusterInit(); scriptingInit(); slowlogInit(); bioInit(); } /* Populates the Redis Command Table starting from the hard coded list * we have on top of redis.c file. */ void populateCommandTable(void) { int j; int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; char *f = c->sflags; int retval; while(*f != '\0') { switch(*f) { case 'w': c->flags |= REDIS_CMD_WRITE; break; case 'r': c->flags |= REDIS_CMD_READONLY; break; case 'm': c->flags |= REDIS_CMD_DENYOOM; break; case 'a': c->flags |= REDIS_CMD_ADMIN; break; case 'p': c->flags |= REDIS_CMD_PUBSUB; break; case 'f': c->flags |= REDIS_CMD_FORCE_REPLICATION; break; case 's': c->flags |= REDIS_CMD_NOSCRIPT; break; case 'R': c->flags |= REDIS_CMD_RANDOM; break; case 'S': c->flags |= REDIS_CMD_SORT_FOR_SCRIPT; break; default: redisPanic("Unsupported command flag"); break; } f++; } retval = dictAdd(server.commands, sdsnew(c->name), c); assert(retval == DICT_OK); } } void resetCommandTableStats(void) { int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); int j; for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; c->microseconds = 0; c->calls = 0; } } /* ========================== Redis OP Array API ============================ */ void redisOpArrayInit(redisOpArray *oa) { oa->ops = NULL; oa->numops = 0; } int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { redisOp *op; oa->ops = zrealloc(oa->ops,sizeof(redisOp)*(oa->numops+1)); op = oa->ops+oa->numops; op->cmd = cmd; op->dbid = dbid; op->argv = argv; op->argc = argc; op->target = target; oa->numops++; return oa->numops; } void redisOpArrayFree(redisOpArray *oa) { while(oa->numops) { int j; redisOp *op; oa->numops--; op = oa->ops+oa->numops; for (j = 0; j < op->argc; j++) decrRefCount(op->argv[j]); zfree(op->argv); } zfree(oa->ops); } /* ====================== Commands lookup and execution ===================== */ struct redisCommand *lookupCommand(sds name) { return dictFetchValue(server.commands, name); } struct redisCommand *lookupCommandByCString(char *s) { struct redisCommand *cmd; sds name = sdsnew(s); cmd = dictFetchValue(server.commands, name); sdsfree(name); return cmd; } /* Propagate the specified command (in the context of the specified database id) * to AOF, Slaves and Monitors. * * flags are an xor between: * + REDIS_PROPAGATE_NONE (no propagation of command at all) * + REDIS_PROPAGATE_AOF (propagate into the AOF file if is enabled) * + REDIS_PROPAGATE_REPL (propagate into the replication link) */ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags) { if (server.aof_state != REDIS_AOF_OFF && flags & REDIS_PROPAGATE_AOF) feedAppendOnlyFile(cmd,dbid,argv,argc); if (flags & REDIS_PROPAGATE_REPL && listLength(server.slaves)) replicationFeedSlaves(server.slaves,dbid,argv,argc); } /* Used inside commands to schedule the propagation of additional commands * after the current command is propagated to AOF / Replication. */ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { redisOpArrayAppend(&server.also_propagate,cmd,dbid,argv,argc,target); } /* Call() is the core of Redis execution of a command */ void call(redisClient *c, int flags) { long long dirty, start = ustime(), duration; /* Sent the command to clients in MONITOR mode, only if the commands are * not geneated from reading an AOF. */ if (listLength(server.monitors) && !server.loading) replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc); /* Call the command. */ redisOpArrayInit(&server.also_propagate); dirty = server.dirty; c->cmd->proc(c); dirty = server.dirty-dirty; duration = ustime()-start; /* When EVAL is called loading the AOF we don't want commands called * from Lua to go into the slowlog or to populate statistics. */ if (server.loading && c->flags & REDIS_LUA_CLIENT) flags &= ~(REDIS_CALL_SLOWLOG | REDIS_CALL_STATS); /* Log the command into the Slow log if needed, and populate the * per-command statistics that we show in INFO commandstats. */ if (flags & REDIS_CALL_SLOWLOG) slowlogPushEntryIfNeeded(c->argv,c->argc,duration); if (flags & REDIS_CALL_STATS) { c->cmd->microseconds += duration; c->cmd->calls++; } /* Propagate the command into the AOF and replication link */ if (flags & REDIS_CALL_PROPAGATE) { int flags = REDIS_PROPAGATE_NONE; if (c->cmd->flags & REDIS_CMD_FORCE_REPLICATION) flags |= REDIS_PROPAGATE_REPL; if (dirty) flags |= (REDIS_PROPAGATE_REPL | REDIS_PROPAGATE_AOF); if (flags != REDIS_PROPAGATE_NONE) propagate(c->cmd,c->db->id,c->argv,c->argc,flags); } /* Commands such as LPUSH or BRPOPLPUSH may propagate an additional * PUSH command. */ if (server.also_propagate.numops) { int j; redisOp *rop; for (j = 0; j < server.also_propagate.numops; j++) { rop = &server.also_propagate.ops[j]; propagate(rop->cmd, rop->dbid, rop->argv, rop->argc, rop->target); } redisOpArrayFree(&server.also_propagate); } server.stat_numcommands++; } /* If this function gets called we already read a whole * command, argments are in the client argv/argc fields. * processCommand() execute the command or prepare the * server for a bulk read from the client. * * If 1 is returned the client is still alive and valid and * and other operations can be performed by the caller. Otherwise * if 0 is returned the client was destroied (i.e. after QUIT). */ int processCommand(redisClient *c) { /* The QUIT command is handled separately. Normal command procs will * go through checking for replication and QUIT will cause trouble * when FORCE_REPLICATION is enabled and would be implemented in * a regular command proc. */ if (!strcasecmp(c->argv[0]->ptr,"quit")) { addReply(c,shared.ok); c->flags |= REDIS_CLOSE_AFTER_REPLY; return REDIS_ERR; } /* Now lookup the command and check ASAP about trivial error conditions * such as wrong arity, bad command name and so forth. */ c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr); if (!c->cmd) { addReplyErrorFormat(c,"unknown command '%s'", (char*)c->argv[0]->ptr); return REDIS_OK; } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || (c->argc < -c->cmd->arity)) { addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return REDIS_OK; } /* Check if the user is authenticated */ if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand) { addReplyError(c,"operation not permitted"); return REDIS_OK; } /* If cluster is enabled, redirect here */ if (server.cluster_enabled && !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) { int hashslot; if (server.cluster.state != REDIS_CLUSTER_OK) { addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information"); return REDIS_OK; } else { int ask; clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&ask); if (n == NULL) { addReplyError(c,"Multi keys request invalid in cluster"); return REDIS_OK; } else if (n != server.cluster.myself) { addReplySds(c,sdscatprintf(sdsempty(), "-%s %d %s:%d\r\n", ask ? "ASK" : "MOVED", hashslot,n->ip,n->port)); return REDIS_OK; } } } /* Handle the maxmemory directive. * * First we try to free some memory if possible (if there are volatile * keys in the dataset). If there are not the only thing we can do * is returning an error. */ if (server.maxmemory) { int retval = freeMemoryIfNeeded(); if ((c->cmd->flags & REDIS_CMD_DENYOOM) && retval == REDIS_ERR) { addReply(c, shared.oomerr); return REDIS_OK; } } /* Don't accept write commands if there are problems persisting on disk. */ if (server.stop_writes_on_bgsave_err && server.saveparamslen > 0 && server.lastbgsave_status == REDIS_ERR && c->cmd->flags & REDIS_CMD_WRITE) { addReply(c, shared.bgsaveerr); return REDIS_OK; } /* Don't accept wirte commands if this is a read only slave. But * accept write commands if this is our master. */ if (server.masterhost && server.repl_slave_ro && !(c->flags & REDIS_MASTER) && c->cmd->flags & REDIS_CMD_WRITE) { addReply(c, shared.roslaveerr); return REDIS_OK; } /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0) && c->cmd->proc != subscribeCommand && c->cmd->proc != unsubscribeCommand && c->cmd->proc != psubscribeCommand && c->cmd->proc != punsubscribeCommand) { addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context"); return REDIS_OK; } /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and * we are a slave with a broken link with master. */ if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED && server.repl_serve_stale_data == 0 && c->cmd->proc != infoCommand && c->cmd->proc != slaveofCommand) { addReply(c, shared.masterdownerr); return REDIS_OK; } /* Loading DB? Return an error if the command is not INFO */ if (server.loading && c->cmd->proc != infoCommand) { addReply(c, shared.loadingerr); return REDIS_OK; } /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */ if (server.lua_timedout && !(c->cmd->proc == shutdownCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'n') && !(c->cmd->proc == scriptCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'k')) { addReply(c, shared.slowscripterr); return REDIS_OK; } /* Exec the command */ if (c->flags & REDIS_MULTI && c->cmd->proc != execCommand && c->cmd->proc != discardCommand && c->cmd->proc != multiCommand && c->cmd->proc != watchCommand) { queueMultiCommand(c); addReply(c,shared.queued); } else { call(c,REDIS_CALL_FULL); } return REDIS_OK; } /*================================== Shutdown =============================== */ int prepareForShutdown(int flags) { int save = flags & REDIS_SHUTDOWN_SAVE; int nosave = flags & REDIS_SHUTDOWN_NOSAVE; redisLog(REDIS_WARNING,"User requested shutdown..."); /* Kill the saving child if there is a background saving in progress. We want to avoid race conditions, for instance our saving child may overwrite the synchronous saving did by SHUTDOWN. */ if (server.rdb_child_pid != -1) { redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!"); kill(server.rdb_child_pid,SIGKILL); rdbRemoveTempFile(server.rdb_child_pid); } if (server.aof_state != REDIS_AOF_OFF) { /* Kill the AOF saving child as the AOF we already have may be longer * but contains the full dataset anyway. */ if (server.aof_child_pid != -1) { redisLog(REDIS_WARNING, "There is a child rewriting the AOF. Killing it!"); kill(server.aof_child_pid,SIGKILL); } /* Append only file: fsync() the AOF and exit */ redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file."); aof_fsync(server.aof_fd); } if ((server.saveparamslen > 0 && !nosave) || save) { redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting."); /* Snapshotting. Perform a SYNC SAVE and exit */ if (rdbSave(server.rdb_filename) != REDIS_OK) { /* Ooops.. error saving! The best we can do is to continue * operating. Note that if there was a background saving process, * in the next cron() Redis will be notified that the background * saving aborted, handling special stuff like slaves pending for * synchronization... */ redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit."); return REDIS_ERR; } } if (server.daemonize) { redisLog(REDIS_NOTICE,"Removing the pid file."); unlink(server.pidfile); } /* Close the listening sockets. Apparently this allows faster restarts. */ if (server.ipfd != -1) close(server.ipfd); if (server.sofd != -1) close(server.sofd); if (server.unixsocket) { redisLog(REDIS_NOTICE,"Removing the unix socket file."); unlink(server.unixsocket); /* don't care if this fails */ } redisLog(REDIS_WARNING,"Redis is now ready to exit, bye bye..."); return REDIS_OK; } /*================================== Commands =============================== */ /* Return zero if strings are the same, non-zero if they are not. * The comparison is performed in a way that prevents an attacker to obtain * information about the nature of the strings just monitoring the execution * time of the function. * * Note that limiting the comparison length to strings up to 512 bytes we * can avoid leaking any information about the password length and any * possible branch misprediction related leak. */ int time_independent_strcmp(char *a, char *b) { char bufa[REDIS_AUTHPASS_MAX_LEN], bufb[REDIS_AUTHPASS_MAX_LEN]; /* The above two strlen perform len(a) + len(b) operations where either * a or b are fixed (our password) length, and the difference is only * relative to the length of the user provided string, so no information * leak is possible in the following two lines of code. */ int alen = strlen(a); int blen = strlen(b); int j; int diff = 0; /* We can't compare strings longer than our static buffers. * Note that this will never pass the first test in practical circumstances * so there is no info leak. */ if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1; memset(bufa,0,sizeof(bufa)); /* Constant time. */ memset(bufb,0,sizeof(bufb)); /* Constant time. */ /* Again the time of the following two copies is proportional to * len(a) + len(b) so no info is leaked. */ memcpy(bufa,a,alen); memcpy(bufb,b,blen); /* Always compare all the chars in the two buffers without * conditional expressions. */ for (j = 0; j < sizeof(bufa); j++) { diff |= (bufa[j] ^ bufb[j]); } /* Length must be equal as well. */ diff |= alen ^ blen; return diff; /* If zero strings are the same. */ } void authCommand(redisClient *c) { if (!server.requirepass) { addReplyError(c,"Client sent AUTH, but no password is set"); } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) { c->authenticated = 1; addReply(c,shared.ok); } else { c->authenticated = 0; addReplyError(c,"invalid password"); } } void pingCommand(redisClient *c) { addReply(c,shared.pong); } void echoCommand(redisClient *c) { addReplyBulk(c,c->argv[1]); } void timeCommand(redisClient *c) { struct timeval tv; /* gettimeofday() can only fail if &tv is a bad addresss so we * don't check for errors. */ gettimeofday(&tv,NULL); addReplyMultiBulkLen(c,2); addReplyBulkLongLong(c,tv.tv_sec); addReplyBulkLongLong(c,tv.tv_usec); } /* Convert an amount of bytes into a human readable string in the form * of 100B, 2G, 100M, 4K, and so forth. */ void bytesToHuman(char *s, unsigned long long n) { double d; if (n < 1024) { /* Bytes */ sprintf(s,"%lluB",n); return; } else if (n < (1024*1024)) { d = (double)n/(1024); sprintf(s,"%.2fK",d); } else if (n < (1024LL*1024*1024)) { d = (double)n/(1024*1024); sprintf(s,"%.2fM",d); } else if (n < (1024LL*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024); sprintf(s,"%.2fG",d); } } /* Create the string returned by the INFO command. This is decoupled * by the INFO command itself as we need to report the same information * on memory corruption problems. */ sds genRedisInfoString(char *section) { sds info = sdsempty(); time_t uptime = server.unixtime-server.stat_starttime; int j, numcommands; struct rusage self_ru, c_ru; unsigned long lol, bib; int allsections = 0, defsections = 0; int sections = 0; if (section) { allsections = strcasecmp(section,"all") == 0; defsections = strcasecmp(section,"default") == 0; } getrusage(RUSAGE_SELF, &self_ru); getrusage(RUSAGE_CHILDREN, &c_ru); getClientsMaxBuffers(&lol,&bib); /* Server */ if (allsections || defsections || !strcasecmp(section,"server")) { struct utsname name; if (sections++) info = sdscat(info,"\r\n"); uname(&name); info = sdscatprintf(info, "# Server\r\n" "redis_version:%s\r\n" "redis_git_sha1:%s\r\n" "redis_git_dirty:%d\r\n" "os:%s %s %s\r\n" "arch_bits:%d\r\n" "multiplexing_api:%s\r\n" "gcc_version:%d.%d.%d\r\n" "process_id:%ld\r\n" "run_id:%s\r\n" "tcp_port:%d\r\n" "uptime_in_seconds:%ld\r\n" "uptime_in_days:%ld\r\n" "lru_clock:%ld\r\n", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, name.sysname, name.release, name.machine, server.arch_bits, aeGetApiName(), #ifdef __GNUC__ __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__, #else 0,0,0, #endif (long) getpid(), server.runid, server.port, uptime, uptime/(3600*24), (unsigned long) server.lruclock); } /* Clients */ if (allsections || defsections || !strcasecmp(section,"clients")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Clients\r\n" "connected_clients:%lu\r\n" "client_longest_output_list:%lu\r\n" "client_biggest_input_buf:%lu\r\n" "blocked_clients:%d\r\n", listLength(server.clients)-listLength(server.slaves), lol, bib, server.bpop_blocked_clients); } /* Memory */ if (allsections || defsections || !strcasecmp(section,"memory")) { char hmem[64]; char peak_hmem[64]; bytesToHuman(hmem,zmalloc_used_memory()); bytesToHuman(peak_hmem,server.stat_peak_memory); if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Memory\r\n" "used_memory:%zu\r\n" "used_memory_human:%s\r\n" "used_memory_rss:%zu\r\n" "used_memory_peak:%zu\r\n" "used_memory_peak_human:%s\r\n" "used_memory_lua:%lld\r\n" "mem_fragmentation_ratio:%.2f\r\n" "mem_allocator:%s\r\n", zmalloc_used_memory(), hmem, zmalloc_get_rss(), server.stat_peak_memory, peak_hmem, ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL, zmalloc_get_fragmentation_ratio(), ZMALLOC_LIB ); } /* Persistence */ if (allsections || defsections || !strcasecmp(section,"persistence")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Persistence\r\n" "loading:%d\r\n" "rdb_changes_since_last_save:%lld\r\n" "rdb_bgsave_in_progress:%d\r\n" "rdb_last_save_time:%ld\r\n" "rdb_last_bgsave_status:%s\r\n" "rdb_last_bgsave_time_sec:%ld\r\n" "rdb_current_bgsave_time_sec:%ld\r\n" "aof_enabled:%d\r\n" "aof_rewrite_in_progress:%d\r\n" "aof_rewrite_scheduled:%d\r\n" "aof_last_rewrite_time_sec:%ld\r\n" "aof_current_rewrite_time_sec:%ld\r\n", server.loading, server.dirty, server.rdb_child_pid != -1, server.lastsave, server.lastbgsave_status == REDIS_OK ? "ok" : "err", server.rdb_save_time_last, (server.rdb_child_pid == -1) ? -1 : time(NULL)-server.rdb_save_time_start, server.aof_state != REDIS_AOF_OFF, server.aof_child_pid != -1, server.aof_rewrite_scheduled, server.aof_rewrite_time_last, (server.aof_child_pid == -1) ? -1 : time(NULL)-server.aof_rewrite_time_start); if (server.aof_state != REDIS_AOF_OFF) { info = sdscatprintf(info, "aof_current_size:%lld\r\n" "aof_base_size:%lld\r\n" "aof_pending_rewrite:%d\r\n" "aof_buffer_length:%zu\r\n" "aof_rewrite_buffer_length:%zu\r\n" "aof_pending_bio_fsync:%llu\r\n" "aof_delayed_fsync:%lu\r\n", (long long) server.aof_current_size, (long long) server.aof_rewrite_base_size, server.aof_rewrite_scheduled, sdslen(server.aof_buf), aofRewriteBufferSize(), bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC), server.aof_delayed_fsync); } if (server.loading) { double perc; time_t eta, elapsed; off_t remaining_bytes = server.loading_total_bytes- server.loading_loaded_bytes; perc = ((double)server.loading_loaded_bytes / server.loading_total_bytes) * 100; elapsed = server.unixtime-server.loading_start_time; if (elapsed == 0) { eta = 1; /* A fake 1 second figure if we don't have enough info */ } else { eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes; } info = sdscatprintf(info, "loading_start_time:%ld\r\n" "loading_total_bytes:%llu\r\n" "loading_loaded_bytes:%llu\r\n" "loading_loaded_perc:%.2f\r\n" "loading_eta_seconds:%ld\r\n" ,(unsigned long) server.loading_start_time, (unsigned long long) server.loading_total_bytes, (unsigned long long) server.loading_loaded_bytes, perc, eta ); } } /* Stats */ if (allsections || defsections || !strcasecmp(section,"stats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Stats\r\n" "total_connections_received:%lld\r\n" "total_commands_processed:%lld\r\n" "instantaneous_ops_per_sec:%lld\r\n" "rejected_connections:%lld\r\n" "expired_keys:%lld\r\n" "evicted_keys:%lld\r\n" "keyspace_hits:%lld\r\n" "keyspace_misses:%lld\r\n" "pubsub_channels:%ld\r\n" "pubsub_patterns:%lu\r\n" "latest_fork_usec:%lld\r\n", server.stat_numconnections, server.stat_numcommands, getOperationsPerSecond(), server.stat_rejected_conn, server.stat_expiredkeys, server.stat_evictedkeys, server.stat_keyspace_hits, server.stat_keyspace_misses, dictSize(server.pubsub_channels), listLength(server.pubsub_patterns), server.stat_fork_time); } /* Replication */ if (allsections || defsections || !strcasecmp(section,"replication")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Replication\r\n" "role:%s\r\n", server.masterhost == NULL ? "master" : "slave"); if (server.masterhost) { info = sdscatprintf(info, "master_host:%s\r\n" "master_port:%d\r\n" "master_link_status:%s\r\n" "master_last_io_seconds_ago:%d\r\n" "master_sync_in_progress:%d\r\n" ,server.masterhost, server.masterport, (server.repl_state == REDIS_REPL_CONNECTED) ? "up" : "down", server.master ? ((int)(server.unixtime-server.master->lastinteraction)) : -1, server.repl_state == REDIS_REPL_TRANSFER ); if (server.repl_state == REDIS_REPL_TRANSFER) { info = sdscatprintf(info, "master_sync_left_bytes:%ld\r\n" "master_sync_last_io_seconds_ago:%d\r\n" ,(long)server.repl_transfer_left, (int)(server.unixtime-server.repl_transfer_lastio) ); } if (server.repl_state != REDIS_REPL_CONNECTED) { info = sdscatprintf(info, "master_link_down_since_seconds:%ld\r\n", (long)server.unixtime-server.repl_down_since); } } info = sdscatprintf(info, "connected_slaves:%lu\r\n", listLength(server.slaves)); if (listLength(server.slaves)) { int slaveid = 0; listNode *ln; listIter li; listRewind(server.slaves,&li); while((ln = listNext(&li))) { redisClient *slave = listNodeValue(ln); char *state = NULL; char ip[32]; int port; if (anetPeerToString(slave->fd,ip,&port) == -1) continue; switch(slave->replstate) { case REDIS_REPL_WAIT_BGSAVE_START: case REDIS_REPL_WAIT_BGSAVE_END: state = "wait_bgsave"; break; case REDIS_REPL_SEND_BULK: state = "send_bulk"; break; case REDIS_REPL_ONLINE: state = "online"; break; } if (state == NULL) continue; info = sdscatprintf(info,"slave%d:%s,%d,%s\r\n", slaveid,ip,slave->slave_listening_port,state); slaveid++; } } } /* CPU */ if (allsections || defsections || !strcasecmp(section,"cpu")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# CPU\r\n" "used_cpu_sys:%.2f\r\n" "used_cpu_user:%.2f\r\n" "used_cpu_sys_children:%.2f\r\n" "used_cpu_user_children:%.2f\r\n", (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000); } /* cmdtime */ if (allsections || !strcasecmp(section,"commandstats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Commandstats\r\n"); numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; if (!c->calls) continue; info = sdscatprintf(info, "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", c->name, c->calls, c->microseconds, (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls)); } } /* Cluster */ if (allsections || defsections || !strcasecmp(section,"cluster")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Cluster\r\n" "cluster_enabled:%d\r\n", server.cluster_enabled); } /* Key space */ if (allsections || defsections || !strcasecmp(section,"keyspace")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Keyspace\r\n"); for (j = 0; j < server.dbnum; j++) { long long keys, vkeys; keys = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (keys || vkeys) { info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n", j, keys, vkeys); } } } return info; } void infoCommand(redisClient *c) { char *section = c->argc == 2 ? c->argv[1]->ptr : "default"; if (c->argc > 2) { addReply(c,shared.syntaxerr); return; } sds info = genRedisInfoString(section); addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n", (unsigned long)sdslen(info))); addReplySds(c,info); addReply(c,shared.crlf); } void monitorCommand(redisClient *c) { /* ignore MONITOR if aleady slave or in monitor mode */ if (c->flags & REDIS_SLAVE) return; c->flags |= (REDIS_SLAVE|REDIS_MONITOR); c->slaveseldb = 0; listAddNodeTail(server.monitors,c); addReply(c,shared.ok); } /* ============================ Maxmemory directive ======================== */ /* This function gets called when 'maxmemory' is set on the config file to limit * the max memory used by the server, before processing a command. * * The goal of the function is to free enough memory to keep Redis under the * configured memory limit. * * The function starts calculating how many bytes should be freed to keep * Redis under the limit, and enters a loop selecting the best keys to * evict accordingly to the configured policy. * * If all the bytes needed to return back under the limit were freed the * function returns REDIS_OK, otherwise REDIS_ERR is returned, and the caller * should block the execution of commands that will result in more memory * used by the server. */ int freeMemoryIfNeeded(void) { size_t mem_used, mem_tofree, mem_freed; int slaves = listLength(server.slaves); /* Remove the size of slaves output buffers and AOF buffer from the * count of used memory. */ mem_used = zmalloc_used_memory(); if (slaves) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { redisClient *slave = listNodeValue(ln); unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave); if (obuf_bytes > mem_used) mem_used = 0; else mem_used -= obuf_bytes; } } if (server.aof_state != REDIS_AOF_OFF) { mem_used -= sdslen(server.aof_buf); mem_used -= aofRewriteBufferSize(); } /* Check if we are over the memory limit. */ if (mem_used <= server.maxmemory) return REDIS_OK; if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return REDIS_ERR; /* We need to free memory, but policy forbids. */ /* Compute how much memory we need to free. */ mem_tofree = mem_used - server.maxmemory; mem_freed = 0; while (mem_freed < mem_tofree) { int j, k, keys_freed = 0; for (j = 0; j < server.dbnum; j++) { long bestval = 0; /* just to prevent warning */ sds bestkey = NULL; struct dictEntry *de; redisDb *db = server.db+j; dict *dict; if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM) { dict = server.db[j].dict; } else { dict = server.db[j].expires; } if (dictSize(dict) == 0) continue; /* volatile-random and allkeys-random policy */ if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM || server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM) { de = dictGetRandomKey(dict); bestkey = dictGetKey(de); } /* volatile-lru and allkeys-lru policy */ else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) { for (k = 0; k < server.maxmemory_samples; k++) { sds thiskey; long thisval; robj *o; de = dictGetRandomKey(dict); thiskey = dictGetKey(de); /* When policy is volatile-lru we need an additonal lookup * to locate the real key, as dict is set to db->expires. */ if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU) de = dictFind(db->dict, thiskey); o = dictGetVal(de); thisval = estimateObjectIdleTime(o); /* Higher idle time is better candidate for deletion */ if (bestkey == NULL || thisval > bestval) { bestkey = thiskey; bestval = thisval; } } } /* volatile-ttl */ else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) { for (k = 0; k < server.maxmemory_samples; k++) { sds thiskey; long thisval; de = dictGetRandomKey(dict); thiskey = dictGetKey(de); thisval = (long) dictGetVal(de); /* Expire sooner (minor expire unix timestamp) is better * candidate for deletion */ if (bestkey == NULL || thisval < bestval) { bestkey = thiskey; bestval = thisval; } } } /* Finally remove the selected key. */ if (bestkey) { long long delta; robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); propagateExpire(db,keyobj); /* We compute the amount of memory freed by dbDelete() alone. * It is possible that actually the memory needed to propagate * the DEL in AOF and replication link is greater than the one * we are freeing removing the key, but we can't account for * that otherwise we would never exit the loop. * * AOF and Output buffer memory will be freed eventually so * we only care about memory used by the key space. */ delta = (long long) zmalloc_used_memory(); dbDelete(db,keyobj); delta -= (long long) zmalloc_used_memory(); mem_freed += delta; server.stat_evictedkeys++; decrRefCount(keyobj); keys_freed++; /* When the memory to free starts to be big enough, we may * start spending so much time here that is impossible to * deliver data to the slaves fast enough, so we force the * transmission here inside the loop. */ if (slaves) flushSlavesOutputBuffers(); } } if (!keys_freed) return REDIS_ERR; /* nothing to free... */ } return REDIS_OK; } /* =================================== Main! ================================ */ #ifdef __linux__ int linuxOvercommitMemoryValue(void) { FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); char buf[64]; if (!fp) return -1; if (fgets(buf,64,fp) == NULL) { fclose(fp); return -1; } fclose(fp); return atoi(buf); } void linuxOvercommitMemoryWarning(void) { if (linuxOvercommitMemoryValue() == 0) { redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); } } #endif /* __linux__ */ void createPidFile(void) { /* Try to write the pid file in a best-effort way. */ FILE *fp = fopen(server.pidfile,"w"); if (fp) { fprintf(fp,"%d\n",(int)getpid()); fclose(fp); } } void daemonize(void) { int fd; if (fork() != 0) exit(0); /* parent exits */ setsid(); /* create a new session */ /* Every output goes to /dev/null. If Redis is daemonized but * the 'logfile' is set to 'stdout' in the configuration file * it will not log at all. */ if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); } } void version() { printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d\n", REDIS_VERSION, redisGitSHA1(), atoi(redisGitDirty()) > 0, ZMALLOC_LIB, sizeof(long) == 4 ? 32 : 64); exit(0); } void usage() { fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n"); fprintf(stderr," ./redis-server - (read config from stdin)\n"); fprintf(stderr," ./redis-server -v or --version\n"); fprintf(stderr," ./redis-server -h or --help\n"); fprintf(stderr," ./redis-server --test-memory \n\n"); fprintf(stderr,"Examples:\n"); fprintf(stderr," ./redis-server (run the server with default conf)\n"); fprintf(stderr," ./redis-server /etc/redis/6379.conf\n"); fprintf(stderr," ./redis-server --port 7777\n"); fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n"); exit(1); } void redisAsciiArt(void) { #include "asciilogo.h" char *buf = zmalloc(1024*16); snprintf(buf,1024*16,ascii_logo, REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", server.cluster_enabled ? "cluster" : "stand alone", server.port, (long) getpid() ); redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf); zfree(buf); } static void sigtermHandler(int sig) { REDIS_NOTUSED(sig); redisLogFromHandler(REDIS_WARNING,"Received SIGTERM, scheduling shutdown..."); server.shutdown_asap = 1; } void setupSignalHandlers(void) { struct sigaction act; /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. * Otherwise, sa_handler is used. */ sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = sigtermHandler; sigaction(SIGTERM, &act, NULL); #ifdef HAVE_BACKTRACE sigemptyset(&act.sa_mask); act.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO; act.sa_sigaction = sigsegvHandler; sigaction(SIGSEGV, &act, NULL); sigaction(SIGBUS, &act, NULL); sigaction(SIGFPE, &act, NULL); sigaction(SIGILL, &act, NULL); #endif return; } void memtest(size_t megabytes, int passes); int main(int argc, char **argv) { long long start; struct timeval tv; /* We need to initialize our libraries, and the server configuration. */ zmalloc_enable_thread_safeness(); srand(time(NULL)^getpid()); gettimeofday(&tv,NULL); dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid()); initServerConfig(); if (argc >= 2) { int j = 1; /* First option to parse in argv[] */ sds options = sdsempty(); char *configfile = NULL; /* Handle special options --help and --version */ if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) version(); if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) usage(); if (strcmp(argv[1], "--test-memory") == 0) { if (argc == 3) { memtest(atoi(argv[2]),50); exit(0); } else { fprintf(stderr,"Please specify the amount of memory to test in megabytes.\n"); fprintf(stderr,"Example: ./redis-server --test-memory 4096\n\n"); exit(1); } } /* First argument is the config file name? */ if (argv[j][0] != '-' || argv[j][1] != '-') configfile = argv[j++]; /* All the other options are parsed and conceptually appended to the * configuration file. For instance --port 6380 will generate the * string "port 6380\n" to be parsed after the actual file name * is parsed, if any. */ while(j != argc) { if (argv[j][0] == '-' && argv[j][1] == '-') { /* Option name */ if (sdslen(options)) options = sdscat(options,"\n"); options = sdscat(options,argv[j]+2); options = sdscat(options," "); } else { /* Option argument */ options = sdscatrepr(options,argv[j],strlen(argv[j])); options = sdscat(options," "); } j++; } resetServerSaveParams(); loadServerConfig(configfile,options); sdsfree(options); } else { redisLog(REDIS_WARNING,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'"); } if (server.daemonize) daemonize(); initServer(); if (server.daemonize) createPidFile(); redisAsciiArt(); redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION); #ifdef __linux__ linuxOvercommitMemoryWarning(); #endif start = ustime(); if (server.aof_state == REDIS_AOF_ON) { if (loadAppendOnlyFile(server.aof_filename) == REDIS_OK) redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000); } else { if (rdbLoad(server.rdb_filename) == REDIS_OK) { redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds", (float)(ustime()-start)/1000000); } else if (errno != ENOENT) { redisLog(REDIS_WARNING,"Fatal error loading the DB. Exiting."); exit(1); } } if (server.ipfd > 0) redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port); if (server.sofd > 0) redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket); aeSetBeforeSleepProc(server.el,beforeSleep); aeMain(server.el); aeDeleteEventLoop(server.el); return 0; } /* The End */ pygments.rb-0.6.3/test/test_data.py000066400000000000000000000362431250413007300172740ustar00rootroot00000000000000# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. from __future__ import with_statement import errno import os import select import signal import sys import time import traceback from gunicorn.errors import HaltServer from gunicorn.pidfile import Pidfile from gunicorn.sock import create_socket from gunicorn import util from gunicorn import __version__, SERVER_SOFTWARE class Arbiter(object): """ Arbiter maintain the workers processes alive. It launches or kills them if needed. It also manages application reloading via SIGHUP/USR2. """ # A flag indicating if a worker failed to # to boot. If a worker process exist with # this error code, the arbiter will terminate. WORKER_BOOT_ERROR = 3 START_CTX = {} LISTENER = None WORKERS = {} PIPE = [] # I love dynamic languages SIG_QUEUE = [] SIGNALS = map( lambda x: getattr(signal, "SIG%s" % x), "HUP QUIT INT TERM TTIN TTOU USR1 USR2 WINCH".split() ) SIG_NAMES = dict( (getattr(signal, name), name[3:].lower()) for name in dir(signal) if name[:3] == "SIG" and name[3] != "_" ) def __init__(self, app): os.environ["SERVER_SOFTWARE"] = SERVER_SOFTWARE self.setup(app) self.pidfile = None self.worker_age = 0 self.reexec_pid = 0 self.master_name = "Master" # get current path, try to use PWD env first try: a = os.stat(os.environ['PWD']) b = os.stat(os.getcwd()) if a.ino == b.ino and a.dev == b.dev: cwd = os.environ['PWD'] else: cwd = os.getcwd() except: cwd = os.getcwd() args = sys.argv[:] args.insert(0, sys.executable) # init start context self.START_CTX = { "args": args, "cwd": cwd, 0: sys.executable } def setup(self, app): self.app = app self.cfg = app.cfg self.log = self.cfg.logger_class(app.cfg) # reopen files if 'GUNICORN_FD' in os.environ: self.log.reopen_files() self.address = self.cfg.address self.num_workers = self.cfg.workers self.debug = self.cfg.debug self.timeout = self.cfg.timeout self.proc_name = self.cfg.proc_name self.worker_class = self.cfg.worker_class if self.cfg.debug: self.log.debug("Current configuration:") for config, value in sorted(self.cfg.settings.iteritems()): self.log.debug(" %s: %s", config, value.value) if self.cfg.preload_app: if not self.cfg.debug: self.app.wsgi() else: self.log.warning("debug mode: app isn't preloaded.") def start(self): """\ Initialize the arbiter. Start listening and set pidfile if needed. """ self.log.info("Starting gunicorn %s", __version__) self.cfg.on_starting(self) self.pid = os.getpid() self.init_signals() if not self.LISTENER: self.LISTENER = create_socket(self.cfg, self.log) if self.cfg.pidfile is not None: self.pidfile = Pidfile(self.cfg.pidfile) self.pidfile.create(self.pid) self.log.debug("Arbiter booted") self.log.info("Listening at: %s (%s)", self.LISTENER, self.pid) self.log.info("Using worker: %s", self.cfg.settings['worker_class'].get()) self.cfg.when_ready(self) def init_signals(self): """\ Initialize master signal handling. Most of the signals are queued. Child signals only wake up the master. """ if self.PIPE: map(os.close, self.PIPE) self.PIPE = pair = os.pipe() map(util.set_non_blocking, pair) map(util.close_on_exec, pair) self.log.close_on_exec() map(lambda s: signal.signal(s, self.signal), self.SIGNALS) signal.signal(signal.SIGCHLD, self.handle_chld) def signal(self, sig, frame): if len(self.SIG_QUEUE) < 5: self.SIG_QUEUE.append(sig) self.wakeup() def run(self): "Main master loop." self.start() util._setproctitle("master [%s]" % self.proc_name) self.manage_workers() while True: try: self.reap_workers() sig = self.SIG_QUEUE.pop(0) if len(self.SIG_QUEUE) else None if sig is None: self.sleep() self.murder_workers() self.manage_workers() continue if sig not in self.SIG_NAMES: self.log.info("Ignoring unknown signal: %s", sig) continue signame = self.SIG_NAMES.get(sig) handler = getattr(self, "handle_%s" % signame, None) if not handler: self.log.error("Unhandled signal: %s", signame) continue self.log.info("Handling signal: %s", signame) handler() self.wakeup() except StopIteration: self.halt() except KeyboardInterrupt: self.halt() except HaltServer, inst: self.halt(reason=inst.reason, exit_status=inst.exit_status) except SystemExit: raise except Exception: self.log.info("Unhandled exception in main loop:\n%s", traceback.format_exc()) self.stop(False) if self.pidfile is not None: self.pidfile.unlink() sys.exit(-1) def handle_chld(self, sig, frame): "SIGCHLD handling" self.wakeup() def handle_hup(self): """\ HUP handling. - Reload configuration - Start the new worker processes with a new configuration - Gracefully shutdown the old worker processes """ self.log.info("Hang up: %s", self.master_name) self.reload() def handle_quit(self): "SIGQUIT handling" raise StopIteration def handle_int(self): "SIGINT handling" self.stop(False) raise StopIteration def handle_term(self): "SIGTERM handling" self.stop(False) raise StopIteration def handle_ttin(self): """\ SIGTTIN handling. Increases the number of workers by one. """ self.num_workers += 1 self.manage_workers() def handle_ttou(self): """\ SIGTTOU handling. Decreases the number of workers by one. """ if self.num_workers <= 1: return self.num_workers -= 1 self.manage_workers() def handle_usr1(self): """\ SIGUSR1 handling. Kill all workers by sending them a SIGUSR1 """ self.kill_workers(signal.SIGUSR1) self.log.reopen_files() def handle_usr2(self): """\ SIGUSR2 handling. Creates a new master/worker set as a slave of the current master without affecting old workers. Use this to do live deployment with the ability to backout a change. """ self.reexec() def handle_winch(self): "SIGWINCH handling" if os.getppid() == 1 or os.getpgrp() != os.getpid(): self.log.info("graceful stop of workers") self.num_workers = 0 self.kill_workers(signal.SIGQUIT) else: self.log.info("SIGWINCH ignored. Not daemonized") def wakeup(self): """\ Wake up the arbiter by writing to the PIPE """ try: os.write(self.PIPE[1], '.') except IOError, e: if e.errno not in [errno.EAGAIN, errno.EINTR]: raise def halt(self, reason=None, exit_status=0): """ halt arbiter """ self.stop() self.log.info("Shutting down: %s", self.master_name) if reason is not None: self.log.info("Reason: %s", reason) if self.pidfile is not None: self.pidfile.unlink() sys.exit(exit_status) def sleep(self): """\ Sleep until PIPE is readable or we timeout. A readable PIPE means a signal occurred. """ try: ready = select.select([self.PIPE[0]], [], [], 1.0) if not ready[0]: return while os.read(self.PIPE[0], 1): pass except select.error, e: if e[0] not in [errno.EAGAIN, errno.EINTR]: raise except OSError, e: if e.errno not in [errno.EAGAIN, errno.EINTR]: raise except KeyboardInterrupt: sys.exit() def stop(self, graceful=True): """\ Stop workers :attr graceful: boolean, If True (the default) workers will be killed gracefully (ie. trying to wait for the current connection) """ try: self.LISTENER.close() except Exception: pass self.LISTENER = None sig = signal.SIGQUIT if not graceful: sig = signal.SIGTERM limit = time.time() + self.cfg.graceful_timeout while self.WORKERS and time.time() < limit: self.kill_workers(sig) time.sleep(0.1) self.reap_workers() self.kill_workers(signal.SIGKILL) def reexec(self): """\ Relaunch the master and workers. """ if self.pidfile is not None: self.pidfile.rename("%s.oldbin" % self.pidfile.fname) self.reexec_pid = os.fork() if self.reexec_pid != 0: self.master_name = "Old Master" return os.environ['GUNICORN_FD'] = str(self.LISTENER.fileno()) os.chdir(self.START_CTX['cwd']) self.cfg.pre_exec(self) util.closerange(3, self.LISTENER.fileno()) util.closerange(self.LISTENER.fileno()+1, util.get_maxfd()) os.execvpe(self.START_CTX[0], self.START_CTX['args'], os.environ) def reload(self): old_address = self.cfg.address # reload conf self.app.reload() self.setup(self.app) # reopen log files self.log.reopen_files() # do we need to change listener ? if old_address != self.cfg.address: self.LISTENER.close() self.LISTENER = create_socket(self.cfg, self.log) self.log.info("Listening at: %s", self.LISTENER) # do some actions on reload self.cfg.on_reload(self) # unlink pidfile if self.pidfile is not None: self.pidfile.unlink() # create new pidfile if self.cfg.pidfile is not None: self.pidfile = Pidfile(self.cfg.pidfile) self.pidfile.create(self.pid) # set new proc_name util._setproctitle("master [%s]" % self.proc_name) # spawn new workers for i in range(self.cfg.workers): self.spawn_worker() # manage workers self.manage_workers() def murder_workers(self): """\ Kill unused/idle workers """ for (pid, worker) in self.WORKERS.items(): try: if time.time() - worker.tmp.last_update() <= self.timeout: continue except ValueError: continue self.log.critical("WORKER TIMEOUT (pid:%s)", pid) self.kill_worker(pid, signal.SIGKILL) def reap_workers(self): """\ Reap workers to avoid zombie processes """ try: while True: wpid, status = os.waitpid(-1, os.WNOHANG) if not wpid: break if self.reexec_pid == wpid: self.reexec_pid = 0 else: # A worker said it cannot boot. We'll shutdown # to avoid infinite start/stop cycles. exitcode = status >> 8 if exitcode == self.WORKER_BOOT_ERROR: reason = "Worker failed to boot." raise HaltServer(reason, self.WORKER_BOOT_ERROR) worker = self.WORKERS.pop(wpid, None) if not worker: continue worker.tmp.close() except OSError, e: if e.errno == errno.ECHILD: pass def manage_workers(self): """\ Maintain the number of workers by spawning or killing as required. """ if len(self.WORKERS.keys()) < self.num_workers: self.spawn_workers() workers = self.WORKERS.items() workers.sort(key=lambda w: w[1].age) while len(workers) > self.num_workers: (pid, _) = workers.pop(0) self.kill_worker(pid, signal.SIGQUIT) def spawn_worker(self): self.worker_age += 1 worker = self.worker_class(self.worker_age, self.pid, self.LISTENER, self.app, self.timeout/2.0, self.cfg, self.log) self.cfg.pre_fork(self, worker) pid = os.fork() if pid != 0: self.WORKERS[pid] = worker return pid # Process Child worker_pid = os.getpid() try: util._setproctitle("worker [%s]" % self.proc_name) self.log.info("Booting worker with pid: %s", worker_pid) self.cfg.post_fork(self, worker) worker.init_process() sys.exit(0) except SystemExit: raise except: self.log.debug("Exception in worker process:\n%s", traceback.format_exc()) if not worker.booted: sys.exit(self.WORKER_BOOT_ERROR) sys.exit(-1) finally: self.log.info("Worker exiting (pid: %s)", worker_pid) try: worker.tmp.close() self.cfg.worker_exit(self, worker) except: pass def spawn_workers(self): """\ Spawn new workers as needed. This is where a worker process leaves the main loop of the master process. """ for i in range(self.num_workers - len(self.WORKERS.keys())): self.spawn_worker() def kill_workers(self, sig): """\ Kill all workers with the signal `sig` :attr sig: `signal.SIG*` value """ for pid in self.WORKERS.keys(): self.kill_worker(pid, sig) def kill_worker(self, pid, sig): """\ Kill a worker :attr pid: int, worker pid :attr sig: `signal.SIG*` value """ try: os.kill(pid, sig) except OSError, e: if e.errno == errno.ESRCH: try: worker = self.WORKERS.pop(pid) worker.tmp.close() self.cfg.worker_exit(self, worker) return except (KeyError, OSError): return raise pygments.rb-0.6.3/test/test_data_generated000066400000000000000000015622011250413007300206620ustar00rootroot00000000000000
/*
 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "redis.h"
#include "slowlog.h"
#include "bio.h"

#include <time.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <sys/resource.h>
#include <sys/utsname.h>

/* Our shared "common" objects */

struct sharedObjectsStruct shared;

/* Global vars that are actually used as constants. The following double
 * values are used for double on-disk serialization, and are initialized
 * at runtime to avoid strange compiler optimizations. */

double R_Zero, R_PosInf, R_NegInf, R_Nan;

/*================================= Globals ================================= */

/* Global vars */
struct redisServer server; /* server global state */
struct redisCommand *commandTable;

/* Our command table.
 *
 * Every entry is composed of the following fields:
 *
 * name: a string representing the command name.
 * function: pointer to the C function implementing the command.
 * arity: number of arguments, it is possible to use -N to say >= N
 * sflags: command flags as string. See below for a table of flags.
 * flags: flags as bitmask. Computed by Redis using the 'sflags' field.
 * get_keys_proc: an optional function to get key arguments from a command.
 *                This is only used when the following three fields are not
 *                enough to specify what arguments are keys.
 * first_key_index: first argument that is a key
 * last_key_index: last argument that is a key
 * key_step: step to get all the keys from first to last argument. For instance
 *           in MSET the step is two since arguments are key,val,key,val,...
 * microseconds: microseconds of total execution time for this command.
 * calls: total number of calls of this command.
 *
 * The flags, microseconds and calls fields are computed by Redis and should
 * always be set to zero.
 *
 * Command flags are expressed using strings where every character represents
 * a flag. Later the populateCommandTable() function will take care of
 * populating the real 'flags' field using this characters.
 *
 * This is the meaning of the flags:
 *
 * w: write command (may modify the key space).
 * r: read command  (will never modify the key space).
 * m: may increase memory usage once called. Don't allow if out of memory.
 * a: admin command, like SAVE or SHUTDOWN.
 * p: Pub/Sub related command.
 * f: force replication of this command, regarless of server.dirty.
 * s: command not allowed in scripts.
 * R: random command. Command is not deterministic, that is, the same command
 *    with the same arguments, with the same key space, may have different
 *    results. For instance SPOP and RANDOMKEY are two random commands.
 * S: Sort command output array if called from script, so that the output
 *    is deterministic.
 */
struct redisCommand redisCommandTable[] = {
    {"get",getCommand,2,"r",0,NULL,1,1,1,0,0},
    {"set",setCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0},
    {"setnx",setnxCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0},
    {"setex",setexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0},
    {"psetex",psetexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0},
    {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"strlen",strlenCommand,2,"r",0,NULL,1,1,1,0,0},
    {"del",delCommand,-2,"w",0,noPreloadGetKeys,1,-1,1,0,0},
    {"exists",existsCommand,2,"r",0,NULL,1,1,1,0,0},
    {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"getbit",getbitCommand,3,"r",0,NULL,1,1,1,0,0},
    {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0},
    {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0},
    {"incr",incrCommand,2,"wm",0,NULL,1,1,1,0,0},
    {"decr",decrCommand,2,"wm",0,NULL,1,1,1,0,0},
    {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0},
    {"rpush",rpushCommand,-3,"wm",0,NULL,1,1,1,0,0},
    {"lpush",lpushCommand,-3,"wm",0,NULL,1,1,1,0,0},
    {"rpushx",rpushxCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"lpushx",lpushxCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0},
    {"rpop",rpopCommand,2,"w",0,NULL,1,1,1,0,0},
    {"lpop",lpopCommand,2,"w",0,NULL,1,1,1,0,0},
    {"brpop",brpopCommand,-3,"ws",0,NULL,1,1,1,0,0},
    {"brpoplpush",brpoplpushCommand,4,"wms",0,NULL,1,2,1,0,0},
    {"blpop",blpopCommand,-3,"ws",0,NULL,1,-2,1,0,0},
    {"llen",llenCommand,2,"r",0,NULL,1,1,1,0,0},
    {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0},
    {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0},
    {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0},
    {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0},
    {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0},
    {"sadd",saddCommand,-3,"wm",0,NULL,1,1,1,0,0},
    {"srem",sremCommand,-3,"w",0,NULL,1,1,1,0,0},
    {"smove",smoveCommand,4,"w",0,NULL,1,2,1,0,0},
    {"sismember",sismemberCommand,3,"r",0,NULL,1,1,1,0,0},
    {"scard",scardCommand,2,"r",0,NULL,1,1,1,0,0},
    {"spop",spopCommand,2,"wRs",0,NULL,1,1,1,0,0},
    {"srandmember",srandmemberCommand,2,"rR",0,NULL,1,1,1,0,0},
    {"sinter",sinterCommand,-2,"rS",0,NULL,1,-1,1,0,0},
    {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
    {"sunion",sunionCommand,-2,"rS",0,NULL,1,-1,1,0,0},
    {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
    {"sdiff",sdiffCommand,-2,"rS",0,NULL,1,-1,1,0,0},
    {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
    {"smembers",sinterCommand,2,"rS",0,NULL,1,1,1,0,0},
    {"zadd",zaddCommand,-4,"wm",0,NULL,1,1,1,0,0},
    {"zincrby",zincrbyCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"zrem",zremCommand,-3,"w",0,NULL,1,1,1,0,0},
    {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0},
    {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0},
    {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0},
    {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0},
    {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0},
    {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0},
    {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0},
    {"zcount",zcountCommand,4,"r",0,NULL,1,1,1,0,0},
    {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0},
    {"zcard",zcardCommand,2,"r",0,NULL,1,1,1,0,0},
    {"zscore",zscoreCommand,3,"r",0,NULL,1,1,1,0,0},
    {"zrank",zrankCommand,3,"r",0,NULL,1,1,1,0,0},
    {"zrevrank",zrevrankCommand,3,"r",0,NULL,1,1,1,0,0},
    {"hset",hsetCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"hsetnx",hsetnxCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"hget",hgetCommand,3,"r",0,NULL,1,1,1,0,0},
    {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0},
    {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0},
    {"hincrby",hincrbyCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"hincrbyfloat",hincrbyfloatCommand,4,"wm",0,NULL,1,1,1,0,0},
    {"hdel",hdelCommand,-3,"w",0,NULL,1,1,1,0,0},
    {"hlen",hlenCommand,2,"r",0,NULL,1,1,1,0,0},
    {"hkeys",hkeysCommand,2,"rS",0,NULL,1,1,1,0,0},
    {"hvals",hvalsCommand,2,"rS",0,NULL,1,1,1,0,0},
    {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0},
    {"hexists",hexistsCommand,3,"r",0,NULL,1,1,1,0,0},
    {"incrby",incrbyCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"decrby",decrbyCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"incrbyfloat",incrbyfloatCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0},
    {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0},
    {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0},
    {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0},
    {"select",selectCommand,2,"r",0,NULL,0,0,0,0,0},
    {"move",moveCommand,3,"w",0,NULL,1,1,1,0,0},
    {"rename",renameCommand,3,"w",0,renameGetKeys,1,2,1,0,0},
    {"renamenx",renamenxCommand,3,"w",0,renameGetKeys,1,2,1,0,0},
    {"expire",expireCommand,3,"w",0,NULL,1,1,1,0,0},
    {"expireat",expireatCommand,3,"w",0,NULL,1,1,1,0,0},
    {"pexpire",pexpireCommand,3,"w",0,NULL,1,1,1,0,0},
    {"pexpireat",pexpireatCommand,3,"w",0,NULL,1,1,1,0,0},
    {"keys",keysCommand,2,"rS",0,NULL,0,0,0,0,0},
    {"dbsize",dbsizeCommand,1,"r",0,NULL,0,0,0,0,0},
    {"auth",authCommand,2,"rs",0,NULL,0,0,0,0,0},
    {"ping",pingCommand,1,"r",0,NULL,0,0,0,0,0},
    {"echo",echoCommand,2,"r",0,NULL,0,0,0,0,0},
    {"save",saveCommand,1,"ars",0,NULL,0,0,0,0,0},
    {"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0},
    {"bgrewriteaof",bgrewriteaofCommand,1,"ar",0,NULL,0,0,0,0,0},
    {"shutdown",shutdownCommand,-1,"ar",0,NULL,0,0,0,0,0},
    {"lastsave",lastsaveCommand,1,"r",0,NULL,0,0,0,0,0},
    {"type",typeCommand,2,"r",0,NULL,1,1,1,0,0},
    {"multi",multiCommand,1,"rs",0,NULL,0,0,0,0,0},
    {"exec",execCommand,1,"s",0,NULL,0,0,0,0,0},
    {"discard",discardCommand,1,"rs",0,NULL,0,0,0,0,0},
    {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0},
    {"replconf",replconfCommand,-1,"ars",0,NULL,0,0,0,0,0},
    {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0},
    {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0},
    {"sort",sortCommand,-2,"wmS",0,NULL,1,1,1,0,0},
    {"info",infoCommand,-1,"r",0,NULL,0,0,0,0,0},
    {"monitor",monitorCommand,1,"ars",0,NULL,0,0,0,0,0},
    {"ttl",ttlCommand,2,"r",0,NULL,1,1,1,0,0},
    {"pttl",pttlCommand,2,"r",0,NULL,1,1,1,0,0},
    {"persist",persistCommand,2,"w",0,NULL,1,1,1,0,0},
    {"slaveof",slaveofCommand,3,"as",0,NULL,0,0,0,0,0},
    {"debug",debugCommand,-2,"as",0,NULL,0,0,0,0,0},
    {"config",configCommand,-2,"ar",0,NULL,0,0,0,0,0},
    {"subscribe",subscribeCommand,-2,"rps",0,NULL,0,0,0,0,0},
    {"unsubscribe",unsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0},
    {"psubscribe",psubscribeCommand,-2,"rps",0,NULL,0,0,0,0,0},
    {"punsubscribe",punsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0},
    {"publish",publishCommand,3,"pf",0,NULL,0,0,0,0,0},
    {"watch",watchCommand,-2,"rs",0,noPreloadGetKeys,1,-1,1,0,0},
    {"unwatch",unwatchCommand,1,"rs",0,NULL,0,0,0,0,0},
    {"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0},
    {"restore",restoreCommand,4,"awm",0,NULL,1,1,1,0,0},
    {"migrate",migrateCommand,6,"aw",0,NULL,0,0,0,0,0},
    {"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0},
    {"dump",dumpCommand,2,"ar",0,NULL,1,1,1,0,0},
    {"object",objectCommand,-2,"r",0,NULL,2,2,2,0,0},
    {"client",clientCommand,-2,"ar",0,NULL,0,0,0,0,0},
    {"eval",evalCommand,-3,"s",0,zunionInterGetKeys,0,0,0,0,0},
    {"evalsha",evalShaCommand,-3,"s",0,zunionInterGetKeys,0,0,0,0,0},
    {"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0},
    {"script",scriptCommand,-2,"ras",0,NULL,0,0,0,0,0},
    {"time",timeCommand,1,"rR",0,NULL,0,0,0,0,0},
    {"bitop",bitopCommand,-4,"wm",0,NULL,2,-1,1,0,0},
    {"bitcount",bitcountCommand,-2,"r",0,NULL,1,1,1,0,0}
};

/*============================ Utility functions ============================ */

/* Low level logging. To use only for very big messages, otherwise
 * redisLog() is to prefer. */
void redisLogRaw(int level, const char *msg) {
    const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING };
    const char *c = ".-*#";
    FILE *fp;
    char buf[64];
    int rawmode = (level & REDIS_LOG_RAW);

    level &= 0xff; /* clear flags */
    if (level < server.verbosity) return;

    fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
    if (!fp) return;

    if (rawmode) {
        fprintf(fp,"%s",msg);
    } else {
        int off;
        struct timeval tv;

        gettimeofday(&tv,NULL);
        off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec));
        snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000);
        fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg);
    }
    fflush(fp);

    if (server.logfile) fclose(fp);

    if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg);
}

/* Like redisLogRaw() but with printf-alike support. This is the funciton that
 * is used across the code. The raw version is only used in order to dump
 * the INFO output on crash. */
void redisLog(int level, const char *fmt, ...) {
    va_list ap;
    char msg[REDIS_MAX_LOGMSG_LEN];

    if ((level&0xff) < server.verbosity) return;

    va_start(ap, fmt);
    vsnprintf(msg, sizeof(msg), fmt, ap);
    va_end(ap);

    redisLogRaw(level,msg);
}

/* Log a fixed message without printf-alike capabilities, in a way that is
 * safe to call from a signal handler.
 *
 * We actually use this only for signals that are not fatal from the point
 * of view of Redis. Signals that are going to kill the server anyway and
 * where we need printf-alike features are served by redisLog(). */
void redisLogFromHandler(int level, const char *msg) {
    int fd;
    char buf[64];

    if ((level&0xff) < server.verbosity ||
        (server.logfile == NULL && server.daemonize)) return;
    fd = server.logfile ?
        open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644) :
        STDOUT_FILENO;
    if (fd == -1) return;
    ll2string(buf,sizeof(buf),getpid());
    if (write(fd,"[",1) == -1) goto err;
    if (write(fd,buf,strlen(buf)) == -1) goto err;
    if (write(fd," | signal handler] (",20) == -1) goto err;
    ll2string(buf,sizeof(buf),time(NULL));
    if (write(fd,buf,strlen(buf)) == -1) goto err;
    if (write(fd,") ",2) == -1) goto err;
    if (write(fd,msg,strlen(msg)) == -1) goto err;
    if (write(fd,"\n",1) == -1) goto err;
err:
    if (server.logfile) close(fd);
}

/* Redis generally does not try to recover from out of memory conditions
 * when allocating objects or strings, it is not clear if it will be possible
 * to report this condition to the client since the networking layer itself
 * is based on heap allocation for send buffers, so we simply abort.
 * At least the code will be simpler to read... */
void oom(const char *msg) {
    redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
    sleep(1);
    abort();
}

/* Return the UNIX time in microseconds */
long long ustime(void) {
    struct timeval tv;
    long long ust;

    gettimeofday(&tv, NULL);
    ust = ((long long)tv.tv_sec)*1000000;
    ust += tv.tv_usec;
    return ust;
}

/* Return the UNIX time in milliseconds */
long long mstime(void) {
    return ustime()/1000;
}

/* After an RDB dump or AOF rewrite we exit from children using _exit() instead of
 * exit(), because the latter may interact with the same file objects used by
 * the parent process. However if we are testing the coverage normal exit() is
 * used in order to obtain the right coverage information. */
void exitFromChild(int retcode) {
#ifdef COVERAGE_TEST
    exit(retcode);
#else
    _exit(retcode);
#endif
}

/*====================== Hash table type implementation  ==================== */

/* This is an hash table type that uses the SDS dynamic strings libary as
 * keys and radis objects as values (objects can hold SDS strings,
 * lists, sets). */

void dictVanillaFree(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);
    zfree(val);
}

void dictListDestructor(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);
    listRelease((list*)val);
}

int dictSdsKeyCompare(void *privdata, const void *key1,
        const void *key2)
{
    int l1,l2;
    DICT_NOTUSED(privdata);

    l1 = sdslen((sds)key1);
    l2 = sdslen((sds)key2);
    if (l1 != l2) return 0;
    return memcmp(key1, key2, l1) == 0;
}

/* A case insensitive version used for the command lookup table. */
int dictSdsKeyCaseCompare(void *privdata, const void *key1,
        const void *key2)
{
    DICT_NOTUSED(privdata);

    return strcasecmp(key1, key2) == 0;
}

void dictRedisObjectDestructor(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);

    if (val == NULL) return; /* Values of swapped out keys as set to NULL */
    decrRefCount(val);
}

void dictSdsDestructor(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);

    sdsfree(val);
}

int dictObjKeyCompare(void *privdata, const void *key1,
        const void *key2)
{
    const robj *o1 = key1, *o2 = key2;
    return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
}

unsigned int dictObjHash(const void *key) {
    const robj *o = key;
    return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
}

unsigned int dictSdsHash(const void *key) {
    return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
}

unsigned int dictSdsCaseHash(const void *key) {
    return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));
}

int dictEncObjKeyCompare(void *privdata, const void *key1,
        const void *key2)
{
    robj *o1 = (robj*) key1, *o2 = (robj*) key2;
    int cmp;

    if (o1->encoding == REDIS_ENCODING_INT &&
        o2->encoding == REDIS_ENCODING_INT)
            return o1->ptr == o2->ptr;

    o1 = getDecodedObject(o1);
    o2 = getDecodedObject(o2);
    cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
    decrRefCount(o1);
    decrRefCount(o2);
    return cmp;
}

unsigned int dictEncObjHash(const void *key) {
    robj *o = (robj*) key;

    if (o->encoding == REDIS_ENCODING_RAW) {
        return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
    } else {
        if (o->encoding == REDIS_ENCODING_INT) {
            char buf[32];
            int len;

            len = ll2string(buf,32,(long)o->ptr);
            return dictGenHashFunction((unsigned char*)buf, len);
        } else {
            unsigned int hash;

            o = getDecodedObject(o);
            hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
            decrRefCount(o);
            return hash;
        }
    }
}

/* Sets type hash table */
dictType setDictType = {
    dictEncObjHash,            /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictEncObjKeyCompare,      /* key compare */
    dictRedisObjectDestructor, /* key destructor */
    NULL                       /* val destructor */
};

/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
dictType zsetDictType = {
    dictEncObjHash,            /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictEncObjKeyCompare,      /* key compare */
    dictRedisObjectDestructor, /* key destructor */
    NULL                       /* val destructor */
};

/* Db->dict, keys are sds strings, vals are Redis objects. */
dictType dbDictType = {
    dictSdsHash,                /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictSdsKeyCompare,          /* key compare */
    dictSdsDestructor,          /* key destructor */
    dictRedisObjectDestructor   /* val destructor */
};

/* Db->expires */
dictType keyptrDictType = {
    dictSdsHash,               /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictSdsKeyCompare,         /* key compare */
    NULL,                      /* key destructor */
    NULL                       /* val destructor */
};

/* Command table. sds string -> command struct pointer. */
dictType commandTableDictType = {
    dictSdsCaseHash,           /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictSdsKeyCaseCompare,     /* key compare */
    dictSdsDestructor,         /* key destructor */
    NULL                       /* val destructor */
};

/* Hash type hash table (note that small hashes are represented with zimpaps) */
dictType hashDictType = {
    dictEncObjHash,             /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictEncObjKeyCompare,       /* key compare */
    dictRedisObjectDestructor,  /* key destructor */
    dictRedisObjectDestructor   /* val destructor */
};

/* Keylist hash table type has unencoded redis objects as keys and
 * lists as values. It's used for blocking operations (BLPOP) and to
 * map swapped keys to a list of clients waiting for this keys to be loaded. */
dictType keylistDictType = {
    dictObjHash,                /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictObjKeyCompare,          /* key compare */
    dictRedisObjectDestructor,  /* key destructor */
    dictListDestructor          /* val destructor */
};

/* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
 * clusterNode structures. */
dictType clusterNodesDictType = {
    dictSdsHash,                /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictSdsKeyCompare,          /* key compare */
    dictSdsDestructor,          /* key destructor */
    NULL                        /* val destructor */
};

int htNeedsResize(dict *dict) {
    long long size, used;

    size = dictSlots(dict);
    used = dictSize(dict);
    return (size && used && size > DICT_HT_INITIAL_SIZE &&
            (used*100/size < REDIS_HT_MINFILL));
}

/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
 * we resize the hash table to save memory */
void tryResizeHashTables(void) {
    int j;

    for (j = 0; j < server.dbnum; j++) {
        if (htNeedsResize(server.db[j].dict))
            dictResize(server.db[j].dict);
        if (htNeedsResize(server.db[j].expires))
            dictResize(server.db[j].expires);
    }
}

/* Our hash table implementation performs rehashing incrementally while
 * we write/read from the hash table. Still if the server is idle, the hash
 * table will use two tables for a long time. So we try to use 1 millisecond
 * of CPU time at every serverCron() loop in order to rehash some key. */
void incrementallyRehash(void) {
    int j;

    for (j = 0; j < server.dbnum; j++) {
        /* Keys dictionary */
        if (dictIsRehashing(server.db[j].dict)) {
            dictRehashMilliseconds(server.db[j].dict,1);
            break; /* already used our millisecond for this loop... */
        }
        /* Expires */
        if (dictIsRehashing(server.db[j].expires)) {
            dictRehashMilliseconds(server.db[j].expires,1);
            break; /* already used our millisecond for this loop... */
        }
    }
}

/* This function is called once a background process of some kind terminates,
 * as we want to avoid resizing the hash tables when there is a child in order
 * to play well with copy-on-write (otherwise when a resize happens lots of
 * memory pages are copied). The goal of this function is to update the ability
 * for dict.c to resize the hash tables accordingly to the fact we have o not
 * running childs. */
void updateDictResizePolicy(void) {
    if (server.rdb_child_pid == -1 && server.aof_child_pid == -1)
        dictEnableResize();
    else
        dictDisableResize();
}

/* ======================= Cron: called every 100 ms ======================== */

/* Try to expire a few timed out keys. The algorithm used is adaptive and
 * will use few CPU cycles if there are few expiring keys, otherwise
 * it will get more aggressive to avoid that too much memory is used by
 * keys that can be removed from the keyspace. */
void activeExpireCycle(void) {
    int j, iteration = 0;
    long long start = ustime(), timelimit;

    /* We can use at max REDIS_EXPIRELOOKUPS_TIME_PERC percentage of CPU time
     * per iteration. Since this function gets called with a frequency of
     * REDIS_HZ times per second, the following is the max amount of
     * microseconds we can spend in this function. */
    timelimit = 1000000*REDIS_EXPIRELOOKUPS_TIME_PERC/REDIS_HZ/100;
    if (timelimit <= 0) timelimit = 1;

    for (j = 0; j < server.dbnum; j++) {
        int expired;
        redisDb *db = server.db+j;

        /* Continue to expire if at the end of the cycle more than 25%
         * of the keys were expired. */
        do {
            unsigned long num = dictSize(db->expires);
            unsigned long slots = dictSlots(db->expires);
            long long now = mstime();

            /* When there are less than 1% filled slots getting random
             * keys is expensive, so stop here waiting for better times...
             * The dictionary will be resized asap. */
            if (num && slots > DICT_HT_INITIAL_SIZE &&
                (num*100/slots < 1)) break;

            /* The main collection cycle. Sample random keys among keys
             * with an expire set, checking for expired ones. */
            expired = 0;
            if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
                num = REDIS_EXPIRELOOKUPS_PER_CRON;
            while (num--) {
                dictEntry *de;
                long long t;

                if ((de = dictGetRandomKey(db->expires)) == NULL) break;
                t = dictGetSignedIntegerVal(de);
                if (now > t) {
                    sds key = dictGetKey(de);
                    robj *keyobj = createStringObject(key,sdslen(key));

                    propagateExpire(db,keyobj);
                    dbDelete(db,keyobj);
                    decrRefCount(keyobj);
                    expired++;
                    server.stat_expiredkeys++;
                }
            }
            /* We can't block forever here even if there are many keys to
             * expire. So after a given amount of milliseconds return to the
             * caller waiting for the other active expire cycle. */
            iteration++;
            if ((iteration & 0xf) == 0 && /* check once every 16 cycles. */
                (ustime()-start) > timelimit) return;
        } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
    }
}

void updateLRUClock(void) {
    server.lruclock = (server.unixtime/REDIS_LRU_CLOCK_RESOLUTION) &
                                                REDIS_LRU_CLOCK_MAX;
}


/* Add a sample to the operations per second array of samples. */
void trackOperationsPerSecond(void) {
    long long t = mstime() - server.ops_sec_last_sample_time;
    long long ops = server.stat_numcommands - server.ops_sec_last_sample_ops;
    long long ops_sec;

    ops_sec = t > 0 ? (ops*1000/t) : 0;

    server.ops_sec_samples[server.ops_sec_idx] = ops_sec;
    server.ops_sec_idx = (server.ops_sec_idx+1) % REDIS_OPS_SEC_SAMPLES;
    server.ops_sec_last_sample_time = mstime();
    server.ops_sec_last_sample_ops = server.stat_numcommands;
}

/* Return the mean of all the samples. */
long long getOperationsPerSecond(void) {
    int j;
    long long sum = 0;

    for (j = 0; j < REDIS_OPS_SEC_SAMPLES; j++)
        sum += server.ops_sec_samples[j];
    return sum / REDIS_OPS_SEC_SAMPLES;
}

/* Check for timeouts. Returns non-zero if the client was terminated */
int clientsCronHandleTimeout(redisClient *c) {
    time_t now = server.unixtime;

    if (server.maxidletime &&
        !(c->flags & REDIS_SLAVE) &&    /* no timeout for slaves */
        !(c->flags & REDIS_MASTER) &&   /* no timeout for masters */
        !(c->flags & REDIS_BLOCKED) &&  /* no timeout for BLPOP */
        dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
        listLength(c->pubsub_patterns) == 0 &&
        (now - c->lastinteraction > server.maxidletime))
    {
        redisLog(REDIS_VERBOSE,"Closing idle client");
        freeClient(c);
        return 1;
    } else if (c->flags & REDIS_BLOCKED) {
        if (c->bpop.timeout != 0 && c->bpop.timeout < now) {
            addReply(c,shared.nullmultibulk);
            unblockClientWaitingData(c);
        }
    }
    return 0;
}

/* The client query buffer is an sds.c string that can end with a lot of
 * free space not used, this function reclaims space if needed.
 *
 * The funciton always returns 0 as it never terminates the client. */
int clientsCronResizeQueryBuffer(redisClient *c) {
    size_t querybuf_size = sdsAllocSize(c->querybuf);
    time_t idletime = server.unixtime - c->lastinteraction;

    /* There are two conditions to resize the query buffer:
     * 1) Query buffer is > BIG_ARG and too big for latest peak.
     * 2) Client is inactive and the buffer is bigger than 1k. */
    if (((querybuf_size > REDIS_MBULK_BIG_ARG) &&
         (querybuf_size/(c->querybuf_peak+1)) > 2) ||
         (querybuf_size > 1024 && idletime > 2))
    {
        /* Only resize the query buffer if it is actually wasting space. */
        if (sdsavail(c->querybuf) > 1024) {
            c->querybuf = sdsRemoveFreeSpace(c->querybuf);
        }
    }
    /* Reset the peak again to capture the peak memory usage in the next
     * cycle. */
    c->querybuf_peak = 0;
    return 0;
}

void clientsCron(void) {
    /* Make sure to process at least 1/(REDIS_HZ*10) of clients per call.
     * Since this function is called REDIS_HZ times per second we are sure that
     * in the worst case we process all the clients in 10 seconds.
     * In normal conditions (a reasonable number of clients) we process
     * all the clients in a shorter time. */
    int numclients = listLength(server.clients);
    int iterations = numclients/(REDIS_HZ*10);

    if (iterations < 50)
        iterations = (numclients < 50) ? numclients : 50;
    while(listLength(server.clients) && iterations--) {
        redisClient *c;
        listNode *head;

        /* Rotate the list, take the current head, process.
         * This way if the client must be removed from the list it's the
         * first element and we don't incur into O(N) computation. */
        listRotate(server.clients);
        head = listFirst(server.clients);
        c = listNodeValue(head);
        /* The following functions do different service checks on the client.
         * The protocol is that they return non-zero if the client was
         * terminated. */
        if (clientsCronHandleTimeout(c)) continue;
        if (clientsCronResizeQueryBuffer(c)) continue;
    }
}

/* This is our timer interrupt, called REDIS_HZ times per second.
 * Here is where we do a number of things that need to be done asynchronously.
 * For instance:
 *
 * - Active expired keys collection (it is also performed in a lazy way on
 *   lookup).
 * - Software watchdong.
 * - Update some statistic.
 * - Incremental rehashing of the DBs hash tables.
 * - Triggering BGSAVE / AOF rewrite, and handling of terminated children.
 * - Clients timeout of differnet kinds.
 * - Replication reconnection.
 * - Many more...
 *
 * Everything directly called here will be called REDIS_HZ times per second,
 * so in order to throttle execution of things we want to do less frequently
 * a macro is used: run_with_period(milliseconds) { .... }
 */

/* Using the following macro you can run code inside serverCron() with the
 * specified period, specified in milliseconds.
 * The actual resolution depends on REDIS_HZ. */
#define run_with_period(_ms_) if (!(loops % ((_ms_)/(1000/REDIS_HZ))))

int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
    int j, loops = server.cronloops;
    REDIS_NOTUSED(eventLoop);
    REDIS_NOTUSED(id);
    REDIS_NOTUSED(clientData);

    /* Software watchdog: deliver the SIGALRM that will reach the signal
     * handler if we don't return here fast enough. */
    if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period);

    /* We take a cached value of the unix time in the global state because
     * with virtual memory and aging there is to store the current time
     * in objects at every object access, and accuracy is not needed.
     * To access a global var is faster than calling time(NULL) */
    server.unixtime = time(NULL);

    run_with_period(100) trackOperationsPerSecond();

    /* We have just 22 bits per object for LRU information.
     * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
     * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
     *
     * Note that even if this will wrap after 1.5 years it's not a problem,
     * everything will still work but just some object will appear younger
     * to Redis. But for this to happen a given object should never be touched
     * for 1.5 years.
     *
     * Note that you can change the resolution altering the
     * REDIS_LRU_CLOCK_RESOLUTION define.
     */
    updateLRUClock();

    /* Record the max memory used since the server was started. */
    if (zmalloc_used_memory() > server.stat_peak_memory)
        server.stat_peak_memory = zmalloc_used_memory();

    /* We received a SIGTERM, shutting down here in a safe way, as it is
     * not ok doing so inside the signal handler. */
    if (server.shutdown_asap) {
        if (prepareForShutdown(0) == REDIS_OK) exit(0);
        redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
    }

    /* Show some info about non-empty databases */
    run_with_period(5000) {
        for (j = 0; j < server.dbnum; j++) {
            long long size, used, vkeys;

            size = dictSlots(server.db[j].dict);
            used = dictSize(server.db[j].dict);
            vkeys = dictSize(server.db[j].expires);
            if (used || vkeys) {
                redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
                /* dictPrintStats(server.dict); */
            }
        }
    }

    /* We don't want to resize the hash tables while a bacground saving
     * is in progress: the saving child is created using fork() that is
     * implemented with a copy-on-write semantic in most modern systems, so
     * if we resize the HT while there is the saving child at work actually
     * a lot of memory movements in the parent will cause a lot of pages
     * copied. */
    if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) {
        tryResizeHashTables();
        if (server.activerehashing) incrementallyRehash();
    }

    /* Show information about connected clients */
    run_with_period(5000) {
        redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
            listLength(server.clients)-listLength(server.slaves),
            listLength(server.slaves),
            zmalloc_used_memory());
    }

    /* We need to do a few operations on clients asynchronously. */
    clientsCron();

    /* Start a scheduled AOF rewrite if this was requested by the user while
     * a BGSAVE was in progress. */
    if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 &&
        server.aof_rewrite_scheduled)
    {
        rewriteAppendOnlyFileBackground();
    }

    /* Check if a background saving or AOF rewrite in progress terminated. */
    if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) {
        int statloc;
        pid_t pid;

        if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
            int exitcode = WEXITSTATUS(statloc);
            int bysignal = 0;

            if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);

            if (pid == server.rdb_child_pid) {
                backgroundSaveDoneHandler(exitcode,bysignal);
            } else {
                backgroundRewriteDoneHandler(exitcode,bysignal);
            }
            updateDictResizePolicy();
        }
    } else {
        /* If there is not a background saving/rewrite in progress check if
         * we have to save/rewrite now */
         for (j = 0; j < server.saveparamslen; j++) {
            struct saveparam *sp = server.saveparams+j;

            if (server.dirty >= sp->changes &&
                server.unixtime-server.lastsave > sp->seconds) {
                redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
                    sp->changes, sp->seconds);
                rdbSaveBackground(server.rdb_filename);
                break;
            }
         }

         /* Trigger an AOF rewrite if needed */
         if (server.rdb_child_pid == -1 &&
             server.aof_child_pid == -1 &&
             server.aof_rewrite_perc &&
             server.aof_current_size > server.aof_rewrite_min_size)
         {
            long long base = server.aof_rewrite_base_size ?
                            server.aof_rewrite_base_size : 1;
            long long growth = (server.aof_current_size*100/base) - 100;
            if (growth >= server.aof_rewrite_perc) {
                redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth);
                rewriteAppendOnlyFileBackground();
            }
         }
    }


    /* If we postponed an AOF buffer flush, let's try to do it every time the
     * cron function is called. */
    if (server.aof_flush_postponed_start) flushAppendOnlyFile(0);

    /* Expire a few keys per cycle, only if this is a master.
     * On slaves we wait for DEL operations synthesized by the master
     * in order to guarantee a strict consistency. */
    if (server.masterhost == NULL) activeExpireCycle();

    /* Close clients that need to be closed asynchronous */
    freeClientsInAsyncFreeQueue();

    /* Replication cron function -- used to reconnect to master and
     * to detect transfer failures. */
    run_with_period(1000) replicationCron();

    /* Run other sub-systems specific cron jobs */
    run_with_period(1000) {
        if (server.cluster_enabled) clusterCron();
    }

    server.cronloops++;
    return 1000/REDIS_HZ;
}

/* This function gets called every time Redis is entering the
 * main loop of the event driven library, that is, before to sleep
 * for ready file descriptors. */
void beforeSleep(struct aeEventLoop *eventLoop) {
    REDIS_NOTUSED(eventLoop);
    listNode *ln;
    redisClient *c;

    /* Try to process pending commands for clients that were just unblocked. */
    while (listLength(server.unblocked_clients)) {
        ln = listFirst(server.unblocked_clients);
        redisAssert(ln != NULL);
        c = ln->value;
        listDelNode(server.unblocked_clients,ln);
        c->flags &= ~REDIS_UNBLOCKED;

        /* Process remaining data in the input buffer. */
        if (c->querybuf && sdslen(c->querybuf) > 0) {
            server.current_client = c;
            processInputBuffer(c);
            server.current_client = NULL;
        }
    }

    /* Write the AOF buffer on disk */
    flushAppendOnlyFile(0);
}

/* =========================== Server initialization ======================== */

void createSharedObjects(void) {
    int j;

    shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
    shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
    shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
    shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
    shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
    shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
    shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
    shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
    shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
    shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
    shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
    shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
    shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
        "-ERR Operation against a key holding the wrong kind of value\r\n"));
    shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
        "-ERR no such key\r\n"));
    shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
        "-ERR syntax error\r\n"));
    shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
        "-ERR source and destination objects are the same\r\n"));
    shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
        "-ERR index out of range\r\n"));
    shared.noscripterr = createObject(REDIS_STRING,sdsnew(
        "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
    shared.loadingerr = createObject(REDIS_STRING,sdsnew(
        "-LOADING Redis is loading the dataset in memory\r\n"));
    shared.slowscripterr = createObject(REDIS_STRING,sdsnew(
        "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
    shared.masterdownerr = createObject(REDIS_STRING,sdsnew(
        "-MASTERDOWN Link with MASTER is down and slave-serve-stale-data is set to 'no'.\r\n"));
    shared.bgsaveerr = createObject(REDIS_STRING,sdsnew(
        "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.\r\n"));
    shared.roslaveerr = createObject(REDIS_STRING,sdsnew(
        "-READONLY You can't write against a read only slave.\r\n"));
    shared.oomerr = createObject(REDIS_STRING,sdsnew(
        "-OOM command not allowed when used memory > 'maxmemory'.\r\n"));
    shared.space = createObject(REDIS_STRING,sdsnew(" "));
    shared.colon = createObject(REDIS_STRING,sdsnew(":"));
    shared.plus = createObject(REDIS_STRING,sdsnew("+"));

    for (j = 0; j < REDIS_SHARED_SELECT_CMDS; j++) {
        shared.select[j] = createObject(REDIS_STRING,
            sdscatprintf(sdsempty(),"select %d\r\n", j));
    }
    shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
    shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
    shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
    shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
    shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
    shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
    shared.del = createStringObject("DEL",3);
    shared.rpop = createStringObject("RPOP",4);
    shared.lpop = createStringObject("LPOP",4);
    for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
        shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
        shared.integers[j]->encoding = REDIS_ENCODING_INT;
    }
    for (j = 0; j < REDIS_SHARED_BULKHDR_LEN; j++) {
        shared.mbulkhdr[j] = createObject(REDIS_STRING,
            sdscatprintf(sdsempty(),"*%d\r\n",j));
        shared.bulkhdr[j] = createObject(REDIS_STRING,
            sdscatprintf(sdsempty(),"$%d\r\n",j));
    }
}

void initServerConfig() {
    getRandomHexChars(server.runid,REDIS_RUN_ID_SIZE);
    server.runid[REDIS_RUN_ID_SIZE] = '\0';
    server.arch_bits = (sizeof(long) == 8) ? 64 : 32;
    server.port = REDIS_SERVERPORT;
    server.bindaddr = NULL;
    server.unixsocket = NULL;
    server.unixsocketperm = 0;
    server.ipfd = -1;
    server.sofd = -1;
    server.dbnum = REDIS_DEFAULT_DBNUM;
    server.verbosity = REDIS_NOTICE;
    server.maxidletime = REDIS_MAXIDLETIME;
    server.client_max_querybuf_len = REDIS_MAX_QUERYBUF_LEN;
    server.saveparams = NULL;
    server.loading = 0;
    server.logfile = NULL; /* NULL = log on standard output */
    server.syslog_enabled = 0;
    server.syslog_ident = zstrdup("redis");
    server.syslog_facility = LOG_LOCAL0;
    server.daemonize = 0;
    server.aof_state = REDIS_AOF_OFF;
    server.aof_fsync = AOF_FSYNC_EVERYSEC;
    server.aof_no_fsync_on_rewrite = 0;
    server.aof_rewrite_perc = REDIS_AOF_REWRITE_PERC;
    server.aof_rewrite_min_size = REDIS_AOF_REWRITE_MIN_SIZE;
    server.aof_rewrite_base_size = 0;
    server.aof_rewrite_scheduled = 0;
    server.aof_last_fsync = time(NULL);
    server.aof_rewrite_time_last = -1;
    server.aof_rewrite_time_start = -1;
    server.aof_delayed_fsync = 0;
    server.aof_fd = -1;
    server.aof_selected_db = -1; /* Make sure the first time will not match */
    server.aof_flush_postponed_start = 0;
    server.pidfile = zstrdup("/var/run/redis.pid");
    server.rdb_filename = zstrdup("dump.rdb");
    server.aof_filename = zstrdup("appendonly.aof");
    server.requirepass = NULL;
    server.rdb_compression = 1;
    server.rdb_checksum = 1;
    server.activerehashing = 1;
    server.maxclients = REDIS_MAX_CLIENTS;
    server.bpop_blocked_clients = 0;
    server.maxmemory = 0;
    server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
    server.maxmemory_samples = 3;
    server.hash_max_ziplist_entries = REDIS_HASH_MAX_ZIPLIST_ENTRIES;
    server.hash_max_ziplist_value = REDIS_HASH_MAX_ZIPLIST_VALUE;
    server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
    server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
    server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
    server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES;
    server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE;
    server.shutdown_asap = 0;
    server.repl_ping_slave_period = REDIS_REPL_PING_SLAVE_PERIOD;
    server.repl_timeout = REDIS_REPL_TIMEOUT;
    server.cluster_enabled = 0;
    server.cluster.configfile = zstrdup("nodes.conf");
    server.lua_caller = NULL;
    server.lua_time_limit = REDIS_LUA_TIME_LIMIT;
    server.lua_client = NULL;
    server.lua_timedout = 0;

    updateLRUClock();
    resetServerSaveParams();

    appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */
    appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */
    appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
    /* Replication related */
    server.masterauth = NULL;
    server.masterhost = NULL;
    server.masterport = 6379;
    server.master = NULL;
    server.repl_state = REDIS_REPL_NONE;
    server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT;
    server.repl_serve_stale_data = 1;
    server.repl_slave_ro = 1;
    server.repl_down_since = time(NULL);

    /* Client output buffer limits */
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].hard_limit_bytes = 0;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_bytes = 0;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_NORMAL].soft_limit_seconds = 0;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].hard_limit_bytes = 1024*1024*256;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_bytes = 1024*1024*64;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_SLAVE].soft_limit_seconds = 60;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].hard_limit_bytes = 1024*1024*32;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_bytes = 1024*1024*8;
    server.client_obuf_limits[REDIS_CLIENT_LIMIT_CLASS_PUBSUB].soft_limit_seconds = 60;

    /* Double constants initialization */
    R_Zero = 0.0;
    R_PosInf = 1.0/R_Zero;
    R_NegInf = -1.0/R_Zero;
    R_Nan = R_Zero/R_Zero;

    /* Command table -- we intiialize it here as it is part of the
     * initial configuration, since command names may be changed via
     * redis.conf using the rename-command directive. */
    server.commands = dictCreate(&commandTableDictType,NULL);
    populateCommandTable();
    server.delCommand = lookupCommandByCString("del");
    server.multiCommand = lookupCommandByCString("multi");
    server.lpushCommand = lookupCommandByCString("lpush");

    /* Slow log */
    server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN;
    server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN;

    /* Debugging */
    server.assert_failed = "<no assertion failed>";
    server.assert_file = "<no file>";
    server.assert_line = 0;
    server.bug_report_start = 0;
    server.watchdog_period = 0;
}

/* This function will try to raise the max number of open files accordingly to
 * the configured max number of clients. It will also account for 32 additional
 * file descriptors as we need a few more for persistence, listening
 * sockets, log files and so forth.
 *
 * If it will not be possible to set the limit accordingly to the configured
 * max number of clients, the function will do the reverse setting
 * server.maxclients to the value that we can actually handle. */
void adjustOpenFilesLimit(void) {
    rlim_t maxfiles = server.maxclients+32;
    struct rlimit limit;

    if (getrlimit(RLIMIT_NOFILE,&limit) == -1) {
        redisLog(REDIS_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
            strerror(errno));
        server.maxclients = 1024-32;
    } else {
        rlim_t oldlimit = limit.rlim_cur;

        /* Set the max number of files if the current limit is not enough
         * for our needs. */
        if (oldlimit < maxfiles) {
            rlim_t f;

            f = maxfiles;
            while(f > oldlimit) {
                limit.rlim_cur = f;
                limit.rlim_max = f;
                if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break;
                f -= 128;
            }
            if (f < oldlimit) f = oldlimit;
            if (f != maxfiles) {
                server.maxclients = f-32;
                redisLog(REDIS_WARNING,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
                    (int) maxfiles, strerror(errno), (int) server.maxclients);
            } else {
                redisLog(REDIS_NOTICE,"Max number of open files set to %d",
                    (int) maxfiles);
            }
        }
    }
}

void initServer() {
    int j;

    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    setupSignalHandlers();

    if (server.syslog_enabled) {
        openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
            server.syslog_facility);
    }

    server.current_client = NULL;
    server.clients = listCreate();
    server.clients_to_close = listCreate();
    server.slaves = listCreate();
    server.monitors = listCreate();
    server.unblocked_clients = listCreate();

    createSharedObjects();
    adjustOpenFilesLimit();
    server.el = aeCreateEventLoop(server.maxclients+1024);
    server.db = zmalloc(sizeof(redisDb)*server.dbnum);

    if (server.port != 0) {
        server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
        if (server.ipfd == ANET_ERR) {
            redisLog(REDIS_WARNING, "Opening port %d: %s",
                server.port, server.neterr);
            exit(1);
        }
    }
    if (server.unixsocket != NULL) {
        unlink(server.unixsocket); /* don't care if this fails */
        server.sofd = anetUnixServer(server.neterr,server.unixsocket,server.unixsocketperm);
        if (server.sofd == ANET_ERR) {
            redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
            exit(1);
        }
    }
    if (server.ipfd < 0 && server.sofd < 0) {
        redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
        exit(1);
    }
    for (j = 0; j < server.dbnum; j++) {
        server.db[j].dict = dictCreate(&dbDictType,NULL);
        server.db[j].expires = dictCreate(&keyptrDictType,NULL);
        server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
        server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
        server.db[j].id = j;
    }
    server.pubsub_channels = dictCreate(&keylistDictType,NULL);
    server.pubsub_patterns = listCreate();
    listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
    listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
    server.cronloops = 0;
    server.rdb_child_pid = -1;
    server.aof_child_pid = -1;
    aofRewriteBufferReset();
    server.aof_buf = sdsempty();
    server.lastsave = time(NULL);
    server.rdb_save_time_last = -1;
    server.rdb_save_time_start = -1;
    server.dirty = 0;
    server.stat_numcommands = 0;
    server.stat_numconnections = 0;
    server.stat_expiredkeys = 0;
    server.stat_evictedkeys = 0;
    server.stat_starttime = time(NULL);
    server.stat_keyspace_misses = 0;
    server.stat_keyspace_hits = 0;
    server.stat_peak_memory = 0;
    server.stat_fork_time = 0;
    server.stat_rejected_conn = 0;
    memset(server.ops_sec_samples,0,sizeof(server.ops_sec_samples));
    server.ops_sec_idx = 0;
    server.ops_sec_last_sample_time = mstime();
    server.ops_sec_last_sample_ops = 0;
    server.unixtime = time(NULL);
    server.lastbgsave_status = REDIS_OK;
    server.stop_writes_on_bgsave_err = 1;
    aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
    if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
        acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
    if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
        acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");

    if (server.aof_state == REDIS_AOF_ON) {
        server.aof_fd = open(server.aof_filename,
                               O_WRONLY|O_APPEND|O_CREAT,0644);
        if (server.aof_fd == -1) {
            redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
                strerror(errno));
            exit(1);
        }
    }

    /* 32 bit instances are limited to 4GB of address space, so if there is
     * no explicit limit in the user provided configuration we set a limit
     * at 3.5GB using maxmemory with 'noeviction' policy'. This saves
     * useless crashes of the Redis instance. */
    if (server.arch_bits == 32 && server.maxmemory == 0) {
        redisLog(REDIS_WARNING,"Warning: 32 bit instance detected but no memory limit set. Setting 3.5 GB maxmemory limit with 'noeviction' policy now.");
        server.maxmemory = 3584LL*(1024*1024); /* 3584 MB = 3.5 GB */
        server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION;
    }

    if (server.cluster_enabled) clusterInit();
    scriptingInit();
    slowlogInit();
    bioInit();
}

/* Populates the Redis Command Table starting from the hard coded list
 * we have on top of redis.c file. */
void populateCommandTable(void) {
    int j;
    int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);

    for (j = 0; j < numcommands; j++) {
        struct redisCommand *c = redisCommandTable+j;
        char *f = c->sflags;
        int retval;

        while(*f != '\0') {
            switch(*f) {
            case 'w': c->flags |= REDIS_CMD_WRITE; break;
            case 'r': c->flags |= REDIS_CMD_READONLY; break;
            case 'm': c->flags |= REDIS_CMD_DENYOOM; break;
            case 'a': c->flags |= REDIS_CMD_ADMIN; break;
            case 'p': c->flags |= REDIS_CMD_PUBSUB; break;
            case 'f': c->flags |= REDIS_CMD_FORCE_REPLICATION; break;
            case 's': c->flags |= REDIS_CMD_NOSCRIPT; break;
            case 'R': c->flags |= REDIS_CMD_RANDOM; break;
            case 'S': c->flags |= REDIS_CMD_SORT_FOR_SCRIPT; break;
            default: redisPanic("Unsupported command flag"); break;
            }
            f++;
        }

        retval = dictAdd(server.commands, sdsnew(c->name), c);
        assert(retval == DICT_OK);
    }
}

void resetCommandTableStats(void) {
    int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
    int j;

    for (j = 0; j < numcommands; j++) {
        struct redisCommand *c = redisCommandTable+j;

        c->microseconds = 0;
        c->calls = 0;
    }
}

/* ========================== Redis OP Array API ============================ */

void redisOpArrayInit(redisOpArray *oa) {
    oa->ops = NULL;
    oa->numops = 0;
}

int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid,
                       robj **argv, int argc, int target)
{
    redisOp *op;

    oa->ops = zrealloc(oa->ops,sizeof(redisOp)*(oa->numops+1));
    op = oa->ops+oa->numops;
    op->cmd = cmd;
    op->dbid = dbid;
    op->argv = argv;
    op->argc = argc;
    op->target = target;
    oa->numops++;
    return oa->numops;
}

void redisOpArrayFree(redisOpArray *oa) {
    while(oa->numops) {
        int j;
        redisOp *op;

        oa->numops--;
        op = oa->ops+oa->numops;
        for (j = 0; j < op->argc; j++)
            decrRefCount(op->argv[j]);
        zfree(op->argv);
    }
    zfree(oa->ops);
}

/* ====================== Commands lookup and execution ===================== */

struct redisCommand *lookupCommand(sds name) {
    return dictFetchValue(server.commands, name);
}

struct redisCommand *lookupCommandByCString(char *s) {
    struct redisCommand *cmd;
    sds name = sdsnew(s);

    cmd = dictFetchValue(server.commands, name);
    sdsfree(name);
    return cmd;
}

/* Propagate the specified command (in the context of the specified database id)
 * to AOF, Slaves and Monitors.
 *
 * flags are an xor between:
 * + REDIS_PROPAGATE_NONE (no propagation of command at all)
 * + REDIS_PROPAGATE_AOF (propagate into the AOF file if is enabled)
 * + REDIS_PROPAGATE_REPL (propagate into the replication link)
 */
void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
               int flags)
{
    if (server.aof_state != REDIS_AOF_OFF && flags & REDIS_PROPAGATE_AOF)
        feedAppendOnlyFile(cmd,dbid,argv,argc);
    if (flags & REDIS_PROPAGATE_REPL && listLength(server.slaves))
        replicationFeedSlaves(server.slaves,dbid,argv,argc);
}

/* Used inside commands to schedule the propagation of additional commands
 * after the current command is propagated to AOF / Replication. */
void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
                   int target)
{
    redisOpArrayAppend(&server.also_propagate,cmd,dbid,argv,argc,target);
}

/* Call() is the core of Redis execution of a command */
void call(redisClient *c, int flags) {
    long long dirty, start = ustime(), duration;

    /* Sent the command to clients in MONITOR mode, only if the commands are
     * not geneated from reading an AOF. */
    if (listLength(server.monitors) && !server.loading)
        replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc);

    /* Call the command. */
    redisOpArrayInit(&server.also_propagate);
    dirty = server.dirty;
    c->cmd->proc(c);
    dirty = server.dirty-dirty;
    duration = ustime()-start;

    /* When EVAL is called loading the AOF we don't want commands called
     * from Lua to go into the slowlog or to populate statistics. */
    if (server.loading && c->flags & REDIS_LUA_CLIENT)
        flags &= ~(REDIS_CALL_SLOWLOG | REDIS_CALL_STATS);

    /* Log the command into the Slow log if needed, and populate the
     * per-command statistics that we show in INFO commandstats. */
    if (flags & REDIS_CALL_SLOWLOG)
        slowlogPushEntryIfNeeded(c->argv,c->argc,duration);
    if (flags & REDIS_CALL_STATS) {
        c->cmd->microseconds += duration;
        c->cmd->calls++;
    }

    /* Propagate the command into the AOF and replication link */
    if (flags & REDIS_CALL_PROPAGATE) {
        int flags = REDIS_PROPAGATE_NONE;

        if (c->cmd->flags & REDIS_CMD_FORCE_REPLICATION)
            flags |= REDIS_PROPAGATE_REPL;
        if (dirty)
            flags |= (REDIS_PROPAGATE_REPL | REDIS_PROPAGATE_AOF);
        if (flags != REDIS_PROPAGATE_NONE)
            propagate(c->cmd,c->db->id,c->argv,c->argc,flags);
    }
    /* Commands such as LPUSH or BRPOPLPUSH may propagate an additional
     * PUSH command. */
    if (server.also_propagate.numops) {
        int j;
        redisOp *rop;

        for (j = 0; j < server.also_propagate.numops; j++) {
            rop = &server.also_propagate.ops[j];
            propagate(rop->cmd, rop->dbid, rop->argv, rop->argc, rop->target);
        }
        redisOpArrayFree(&server.also_propagate);
    }
    server.stat_numcommands++;
}

/* If this function gets called we already read a whole
 * command, argments are in the client argv/argc fields.
 * processCommand() execute the command or prepare the
 * server for a bulk read from the client.
 *
 * If 1 is returned the client is still alive and valid and
 * and other operations can be performed by the caller. Otherwise
 * if 0 is returned the client was destroied (i.e. after QUIT). */
int processCommand(redisClient *c) {
    /* The QUIT command is handled separately. Normal command procs will
     * go through checking for replication and QUIT will cause trouble
     * when FORCE_REPLICATION is enabled and would be implemented in
     * a regular command proc. */
    if (!strcasecmp(c->argv[0]->ptr,"quit")) {
        addReply(c,shared.ok);
        c->flags |= REDIS_CLOSE_AFTER_REPLY;
        return REDIS_ERR;
    }

    /* Now lookup the command and check ASAP about trivial error conditions
     * such as wrong arity, bad command name and so forth. */
    c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr);
    if (!c->cmd) {
        addReplyErrorFormat(c,"unknown command '%s'",
            (char*)c->argv[0]->ptr);
        return REDIS_OK;
    } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) ||
               (c->argc < -c->cmd->arity)) {
        addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
            c->cmd->name);
        return REDIS_OK;
    }

    /* Check if the user is authenticated */
    if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand)
    {
        addReplyError(c,"operation not permitted");
        return REDIS_OK;
    }

    /* If cluster is enabled, redirect here */
    if (server.cluster_enabled &&
                !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) {
        int hashslot;

        if (server.cluster.state != REDIS_CLUSTER_OK) {
            addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information");
            return REDIS_OK;
        } else {
            int ask;
            clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&ask);
            if (n == NULL) {
                addReplyError(c,"Multi keys request invalid in cluster");
                return REDIS_OK;
            } else if (n != server.cluster.myself) {
                addReplySds(c,sdscatprintf(sdsempty(),
                    "-%s %d %s:%d\r\n", ask ? "ASK" : "MOVED",
                    hashslot,n->ip,n->port));
                return REDIS_OK;
            }
        }
    }

    /* Handle the maxmemory directive.
     *
     * First we try to free some memory if possible (if there are volatile
     * keys in the dataset). If there are not the only thing we can do
     * is returning an error. */
    if (server.maxmemory) {
        int retval = freeMemoryIfNeeded();
        if ((c->cmd->flags & REDIS_CMD_DENYOOM) && retval == REDIS_ERR) {
            addReply(c, shared.oomerr);
            return REDIS_OK;
        }
    }

    /* Don't accept write commands if there are problems persisting on disk. */
    if (server.stop_writes_on_bgsave_err &&
        server.saveparamslen > 0
        && server.lastbgsave_status == REDIS_ERR &&
        c->cmd->flags & REDIS_CMD_WRITE)
    {
        addReply(c, shared.bgsaveerr);
        return REDIS_OK;
    }

    /* Don't accept wirte commands if this is a read only slave. But
     * accept write commands if this is our master. */
    if (server.masterhost && server.repl_slave_ro &&
        !(c->flags & REDIS_MASTER) &&
        c->cmd->flags & REDIS_CMD_WRITE)
    {
        addReply(c, shared.roslaveerr);
        return REDIS_OK;
    }

    /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
    if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
        &&
        c->cmd->proc != subscribeCommand &&
        c->cmd->proc != unsubscribeCommand &&
        c->cmd->proc != psubscribeCommand &&
        c->cmd->proc != punsubscribeCommand) {
        addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
        return REDIS_OK;
    }

    /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
     * we are a slave with a broken link with master. */
    if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED &&
        server.repl_serve_stale_data == 0 &&
        c->cmd->proc != infoCommand && c->cmd->proc != slaveofCommand)
    {
        addReply(c, shared.masterdownerr);
        return REDIS_OK;
    }

    /* Loading DB? Return an error if the command is not INFO */
    if (server.loading && c->cmd->proc != infoCommand) {
        addReply(c, shared.loadingerr);
        return REDIS_OK;
    }

    /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */
    if (server.lua_timedout &&
        !(c->cmd->proc == shutdownCommand &&
          c->argc == 2 &&
          tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&
        !(c->cmd->proc == scriptCommand &&
          c->argc == 2 &&
          tolower(((char*)c->argv[1]->ptr)[0]) == 'k'))
    {
        addReply(c, shared.slowscripterr);
        return REDIS_OK;
    }

    /* Exec the command */
    if (c->flags & REDIS_MULTI &&
        c->cmd->proc != execCommand && c->cmd->proc != discardCommand &&
        c->cmd->proc != multiCommand && c->cmd->proc != watchCommand)
    {
        queueMultiCommand(c);
        addReply(c,shared.queued);
    } else {
        call(c,REDIS_CALL_FULL);
    }
    return REDIS_OK;
}

/*================================== Shutdown =============================== */

int prepareForShutdown(int flags) {
    int save = flags & REDIS_SHUTDOWN_SAVE;
    int nosave = flags & REDIS_SHUTDOWN_NOSAVE;

    redisLog(REDIS_WARNING,"User requested shutdown...");
    /* Kill the saving child if there is a background saving in progress.
       We want to avoid race conditions, for instance our saving child may
       overwrite the synchronous saving did by SHUTDOWN. */
    if (server.rdb_child_pid != -1) {
        redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!");
        kill(server.rdb_child_pid,SIGKILL);
        rdbRemoveTempFile(server.rdb_child_pid);
    }
    if (server.aof_state != REDIS_AOF_OFF) {
        /* Kill the AOF saving child as the AOF we already have may be longer
         * but contains the full dataset anyway. */
        if (server.aof_child_pid != -1) {
            redisLog(REDIS_WARNING,
                "There is a child rewriting the AOF. Killing it!");
            kill(server.aof_child_pid,SIGKILL);
        }
        /* Append only file: fsync() the AOF and exit */
        redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file.");
        aof_fsync(server.aof_fd);
    }
    if ((server.saveparamslen > 0 && !nosave) || save) {
        redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting.");
        /* Snapshotting. Perform a SYNC SAVE and exit */
        if (rdbSave(server.rdb_filename) != REDIS_OK) {
            /* Ooops.. error saving! The best we can do is to continue
             * operating. Note that if there was a background saving process,
             * in the next cron() Redis will be notified that the background
             * saving aborted, handling special stuff like slaves pending for
             * synchronization... */
            redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit.");
            return REDIS_ERR;
        }
    }
    if (server.daemonize) {
        redisLog(REDIS_NOTICE,"Removing the pid file.");
        unlink(server.pidfile);
    }
    /* Close the listening sockets. Apparently this allows faster restarts. */
    if (server.ipfd != -1) close(server.ipfd);
    if (server.sofd != -1) close(server.sofd);
    if (server.unixsocket) {
        redisLog(REDIS_NOTICE,"Removing the unix socket file.");
        unlink(server.unixsocket); /* don't care if this fails */
    }

    redisLog(REDIS_WARNING,"Redis is now ready to exit, bye bye...");
    return REDIS_OK;
}

/*================================== Commands =============================== */

/* Return zero if strings are the same, non-zero if they are not.
 * The comparison is performed in a way that prevents an attacker to obtain
 * information about the nature of the strings just monitoring the execution
 * time of the function.
 *
 * Note that limiting the comparison length to strings up to 512 bytes we
 * can avoid leaking any information about the password length and any
 * possible branch misprediction related leak.
 */
int time_independent_strcmp(char *a, char *b) {
    char bufa[REDIS_AUTHPASS_MAX_LEN], bufb[REDIS_AUTHPASS_MAX_LEN];
    /* The above two strlen perform len(a) + len(b) operations where either
     * a or b are fixed (our password) length, and the difference is only
     * relative to the length of the user provided string, so no information
     * leak is possible in the following two lines of code. */
    int alen = strlen(a);
    int blen = strlen(b);
    int j;
    int diff = 0;

    /* We can't compare strings longer than our static buffers.
     * Note that this will never pass the first test in practical circumstances
     * so there is no info leak. */
    if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1;

    memset(bufa,0,sizeof(bufa));        /* Constant time. */
    memset(bufb,0,sizeof(bufb));        /* Constant time. */
    /* Again the time of the following two copies is proportional to
     * len(a) + len(b) so no info is leaked. */
    memcpy(bufa,a,alen);
    memcpy(bufb,b,blen);

    /* Always compare all the chars in the two buffers without
     * conditional expressions. */
    for (j = 0; j < sizeof(bufa); j++) {
        diff |= (bufa[j] ^ bufb[j]);
    }
    /* Length must be equal as well. */
    diff |= alen ^ blen;
    return diff; /* If zero strings are the same. */
}

void authCommand(redisClient *c) {
    if (!server.requirepass) {
        addReplyError(c,"Client sent AUTH, but no password is set");
    } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) {
      c->authenticated = 1;
      addReply(c,shared.ok);
    } else {
      c->authenticated = 0;
      addReplyError(c,"invalid password");
    }
}

void pingCommand(redisClient *c) {
    addReply(c,shared.pong);
}

void echoCommand(redisClient *c) {
    addReplyBulk(c,c->argv[1]);
}

void timeCommand(redisClient *c) {
    struct timeval tv;

    /* gettimeofday() can only fail if &tv is a bad addresss so we
     * don't check for errors. */
    gettimeofday(&tv,NULL);
    addReplyMultiBulkLen(c,2);
    addReplyBulkLongLong(c,tv.tv_sec);
    addReplyBulkLongLong(c,tv.tv_usec);
}

/* Convert an amount of bytes into a human readable string in the form
 * of 100B, 2G, 100M, 4K, and so forth. */
void bytesToHuman(char *s, unsigned long long n) {
    double d;

    if (n < 1024) {
        /* Bytes */
        sprintf(s,"%lluB",n);
        return;
    } else if (n < (1024*1024)) {
        d = (double)n/(1024);
        sprintf(s,"%.2fK",d);
    } else if (n < (1024LL*1024*1024)) {
        d = (double)n/(1024*1024);
        sprintf(s,"%.2fM",d);
    } else if (n < (1024LL*1024*1024*1024)) {
        d = (double)n/(1024LL*1024*1024);
        sprintf(s,"%.2fG",d);
    }
}

/* Create the string returned by the INFO command. This is decoupled
 * by the INFO command itself as we need to report the same information
 * on memory corruption problems. */
sds genRedisInfoString(char *section) {
    sds info = sdsempty();
    time_t uptime = server.unixtime-server.stat_starttime;
    int j, numcommands;
    struct rusage self_ru, c_ru;
    unsigned long lol, bib;
    int allsections = 0, defsections = 0;
    int sections = 0;

    if (section) {
        allsections = strcasecmp(section,"all") == 0;
        defsections = strcasecmp(section,"default") == 0;
    }

    getrusage(RUSAGE_SELF, &self_ru);
    getrusage(RUSAGE_CHILDREN, &c_ru);
    getClientsMaxBuffers(&lol,&bib);

    /* Server */
    if (allsections || defsections || !strcasecmp(section,"server")) {
        struct utsname name;

        if (sections++) info = sdscat(info,"\r\n");
        uname(&name);
        info = sdscatprintf(info,
            "# Server\r\n"
            "redis_version:%s\r\n"
            "redis_git_sha1:%s\r\n"
            "redis_git_dirty:%d\r\n"
            "os:%s %s %s\r\n"
            "arch_bits:%d\r\n"
            "multiplexing_api:%s\r\n"
            "gcc_version:%d.%d.%d\r\n"
            "process_id:%ld\r\n"
            "run_id:%s\r\n"
            "tcp_port:%d\r\n"
            "uptime_in_seconds:%ld\r\n"
            "uptime_in_days:%ld\r\n"
            "lru_clock:%ld\r\n",
            REDIS_VERSION,
            redisGitSHA1(),
            strtol(redisGitDirty(),NULL,10) > 0,
            name.sysname, name.release, name.machine,
            server.arch_bits,
            aeGetApiName(),
#ifdef __GNUC__
            __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__,
#else
            0,0,0,
#endif
            (long) getpid(),
            server.runid,
            server.port,
            uptime,
            uptime/(3600*24),
            (unsigned long) server.lruclock);
    }

    /* Clients */
    if (allsections || defsections || !strcasecmp(section,"clients")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
            "# Clients\r\n"
            "connected_clients:%lu\r\n"
            "client_longest_output_list:%lu\r\n"
            "client_biggest_input_buf:%lu\r\n"
            "blocked_clients:%d\r\n",
            listLength(server.clients)-listLength(server.slaves),
            lol, bib,
            server.bpop_blocked_clients);
    }

    /* Memory */
    if (allsections || defsections || !strcasecmp(section,"memory")) {
        char hmem[64];
        char peak_hmem[64];

        bytesToHuman(hmem,zmalloc_used_memory());
        bytesToHuman(peak_hmem,server.stat_peak_memory);
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
            "# Memory\r\n"
            "used_memory:%zu\r\n"
            "used_memory_human:%s\r\n"
            "used_memory_rss:%zu\r\n"
            "used_memory_peak:%zu\r\n"
            "used_memory_peak_human:%s\r\n"
            "used_memory_lua:%lld\r\n"
            "mem_fragmentation_ratio:%.2f\r\n"
            "mem_allocator:%s\r\n",
            zmalloc_used_memory(),
            hmem,
            zmalloc_get_rss(),
            server.stat_peak_memory,
            peak_hmem,
            ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL,
            zmalloc_get_fragmentation_ratio(),
            ZMALLOC_LIB
            );
    }

    /* Persistence */
    if (allsections || defsections || !strcasecmp(section,"persistence")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
            "# Persistence\r\n"
            "loading:%d\r\n"
            "rdb_changes_since_last_save:%lld\r\n"
            "rdb_bgsave_in_progress:%d\r\n"
            "rdb_last_save_time:%ld\r\n"
            "rdb_last_bgsave_status:%s\r\n"
            "rdb_last_bgsave_time_sec:%ld\r\n"
            "rdb_current_bgsave_time_sec:%ld\r\n"
            "aof_enabled:%d\r\n"
            "aof_rewrite_in_progress:%d\r\n"
            "aof_rewrite_scheduled:%d\r\n"
            "aof_last_rewrite_time_sec:%ld\r\n"
            "aof_current_rewrite_time_sec:%ld\r\n",
            server.loading,
            server.dirty,
            server.rdb_child_pid != -1,
            server.lastsave,
            server.lastbgsave_status == REDIS_OK ? "ok" : "err",
            server.rdb_save_time_last,
            (server.rdb_child_pid == -1) ?
                -1 : time(NULL)-server.rdb_save_time_start,
            server.aof_state != REDIS_AOF_OFF,
            server.aof_child_pid != -1,
            server.aof_rewrite_scheduled,
            server.aof_rewrite_time_last,
            (server.aof_child_pid == -1) ?
                -1 : time(NULL)-server.aof_rewrite_time_start);

        if (server.aof_state != REDIS_AOF_OFF) {
            info = sdscatprintf(info,
                "aof_current_size:%lld\r\n"
                "aof_base_size:%lld\r\n"
                "aof_pending_rewrite:%d\r\n"
                "aof_buffer_length:%zu\r\n"
                "aof_rewrite_buffer_length:%zu\r\n"
                "aof_pending_bio_fsync:%llu\r\n"
                "aof_delayed_fsync:%lu\r\n",
                (long long) server.aof_current_size,
                (long long) server.aof_rewrite_base_size,
                server.aof_rewrite_scheduled,
                sdslen(server.aof_buf),
                aofRewriteBufferSize(),
                bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC),
                server.aof_delayed_fsync);
        }

        if (server.loading) {
            double perc;
            time_t eta, elapsed;
            off_t remaining_bytes = server.loading_total_bytes-
                                    server.loading_loaded_bytes;

            perc = ((double)server.loading_loaded_bytes /
                   server.loading_total_bytes) * 100;

            elapsed = server.unixtime-server.loading_start_time;
            if (elapsed == 0) {
                eta = 1; /* A fake 1 second figure if we don't have
                            enough info */
            } else {
                eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
            }

            info = sdscatprintf(info,
                "loading_start_time:%ld\r\n"
                "loading_total_bytes:%llu\r\n"
                "loading_loaded_bytes:%llu\r\n"
                "loading_loaded_perc:%.2f\r\n"
                "loading_eta_seconds:%ld\r\n"
                ,(unsigned long) server.loading_start_time,
                (unsigned long long) server.loading_total_bytes,
                (unsigned long long) server.loading_loaded_bytes,
                perc,
                eta
            );
        }
    }

    /* Stats */
    if (allsections || defsections || !strcasecmp(section,"stats")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
            "# Stats\r\n"
            "total_connections_received:%lld\r\n"
            "total_commands_processed:%lld\r\n"
            "instantaneous_ops_per_sec:%lld\r\n"
            "rejected_connections:%lld\r\n"
            "expired_keys:%lld\r\n"
            "evicted_keys:%lld\r\n"
            "keyspace_hits:%lld\r\n"
            "keyspace_misses:%lld\r\n"
            "pubsub_channels:%ld\r\n"
            "pubsub_patterns:%lu\r\n"
            "latest_fork_usec:%lld\r\n",
            server.stat_numconnections,
            server.stat_numcommands,
            getOperationsPerSecond(),
            server.stat_rejected_conn,
            server.stat_expiredkeys,
            server.stat_evictedkeys,
            server.stat_keyspace_hits,
            server.stat_keyspace_misses,
            dictSize(server.pubsub_channels),
            listLength(server.pubsub_patterns),
            server.stat_fork_time);
    }

    /* Replication */
    if (allsections || defsections || !strcasecmp(section,"replication")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
            "# Replication\r\n"
            "role:%s\r\n",
            server.masterhost == NULL ? "master" : "slave");
        if (server.masterhost) {
            info = sdscatprintf(info,
                "master_host:%s\r\n"
                "master_port:%d\r\n"
                "master_link_status:%s\r\n"
                "master_last_io_seconds_ago:%d\r\n"
                "master_sync_in_progress:%d\r\n"
                ,server.masterhost,
                server.masterport,
                (server.repl_state == REDIS_REPL_CONNECTED) ?
                    "up" : "down",
                server.master ?
                ((int)(server.unixtime-server.master->lastinteraction)) : -1,
                server.repl_state == REDIS_REPL_TRANSFER
            );

            if (server.repl_state == REDIS_REPL_TRANSFER) {
                info = sdscatprintf(info,
                    "master_sync_left_bytes:%ld\r\n"
                    "master_sync_last_io_seconds_ago:%d\r\n"
                    ,(long)server.repl_transfer_left,
                    (int)(server.unixtime-server.repl_transfer_lastio)
                );
            }

            if (server.repl_state != REDIS_REPL_CONNECTED) {
                info = sdscatprintf(info,
                    "master_link_down_since_seconds:%ld\r\n",
                    (long)server.unixtime-server.repl_down_since);
            }
        }
        info = sdscatprintf(info,
            "connected_slaves:%lu\r\n",
            listLength(server.slaves));
        if (listLength(server.slaves)) {
            int slaveid = 0;
            listNode *ln;
            listIter li;

            listRewind(server.slaves,&li);
            while((ln = listNext(&li))) {
                redisClient *slave = listNodeValue(ln);
                char *state = NULL;
                char ip[32];
                int port;

                if (anetPeerToString(slave->fd,ip,&port) == -1) continue;
                switch(slave->replstate) {
                case REDIS_REPL_WAIT_BGSAVE_START:
                case REDIS_REPL_WAIT_BGSAVE_END:
                    state = "wait_bgsave";
                    break;
                case REDIS_REPL_SEND_BULK:
                    state = "send_bulk";
                    break;
                case REDIS_REPL_ONLINE:
                    state = "online";
                    break;
                }
                if (state == NULL) continue;
                info = sdscatprintf(info,"slave%d:%s,%d,%s\r\n",
                    slaveid,ip,slave->slave_listening_port,state);
                slaveid++;
            }
        }
    }

    /* CPU */
    if (allsections || defsections || !strcasecmp(section,"cpu")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
        "# CPU\r\n"
        "used_cpu_sys:%.2f\r\n"
        "used_cpu_user:%.2f\r\n"
        "used_cpu_sys_children:%.2f\r\n"
        "used_cpu_user_children:%.2f\r\n",
        (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
        (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
        (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000,
        (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000);
    }

    /* cmdtime */
    if (allsections || !strcasecmp(section,"commandstats")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info, "# Commandstats\r\n");
        numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
        for (j = 0; j < numcommands; j++) {
            struct redisCommand *c = redisCommandTable+j;

            if (!c->calls) continue;
            info = sdscatprintf(info,
                "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
                c->name, c->calls, c->microseconds,
                (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls));
        }
    }

    /* Cluster */
    if (allsections || defsections || !strcasecmp(section,"cluster")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info,
        "# Cluster\r\n"
        "cluster_enabled:%d\r\n",
        server.cluster_enabled);
    }

    /* Key space */
    if (allsections || defsections || !strcasecmp(section,"keyspace")) {
        if (sections++) info = sdscat(info,"\r\n");
        info = sdscatprintf(info, "# Keyspace\r\n");
        for (j = 0; j < server.dbnum; j++) {
            long long keys, vkeys;

            keys = dictSize(server.db[j].dict);
            vkeys = dictSize(server.db[j].expires);
            if (keys || vkeys) {
                info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
                    j, keys, vkeys);
            }
        }
    }
    return info;
}

void infoCommand(redisClient *c) {
    char *section = c->argc == 2 ? c->argv[1]->ptr : "default";

    if (c->argc > 2) {
        addReply(c,shared.syntaxerr);
        return;
    }
    sds info = genRedisInfoString(section);
    addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
        (unsigned long)sdslen(info)));
    addReplySds(c,info);
    addReply(c,shared.crlf);
}

void monitorCommand(redisClient *c) {
    /* ignore MONITOR if aleady slave or in monitor mode */
    if (c->flags & REDIS_SLAVE) return;

    c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
    c->slaveseldb = 0;
    listAddNodeTail(server.monitors,c);
    addReply(c,shared.ok);
}

/* ============================ Maxmemory directive  ======================== */

/* This function gets called when 'maxmemory' is set on the config file to limit
 * the max memory used by the server, before processing a command.
 *
 * The goal of the function is to free enough memory to keep Redis under the
 * configured memory limit.
 *
 * The function starts calculating how many bytes should be freed to keep
 * Redis under the limit, and enters a loop selecting the best keys to
 * evict accordingly to the configured policy.
 *
 * If all the bytes needed to return back under the limit were freed the
 * function returns REDIS_OK, otherwise REDIS_ERR is returned, and the caller
 * should block the execution of commands that will result in more memory
 * used by the server.
 */
int freeMemoryIfNeeded(void) {
    size_t mem_used, mem_tofree, mem_freed;
    int slaves = listLength(server.slaves);

    /* Remove the size of slaves output buffers and AOF buffer from the
     * count of used memory. */
    mem_used = zmalloc_used_memory();
    if (slaves) {
        listIter li;
        listNode *ln;

        listRewind(server.slaves,&li);
        while((ln = listNext(&li))) {
            redisClient *slave = listNodeValue(ln);
            unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave);
            if (obuf_bytes > mem_used)
                mem_used = 0;
            else
                mem_used -= obuf_bytes;
        }
    }
    if (server.aof_state != REDIS_AOF_OFF) {
        mem_used -= sdslen(server.aof_buf);
        mem_used -= aofRewriteBufferSize();
    }

    /* Check if we are over the memory limit. */
    if (mem_used <= server.maxmemory) return REDIS_OK;

    if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION)
        return REDIS_ERR; /* We need to free memory, but policy forbids. */

    /* Compute how much memory we need to free. */
    mem_tofree = mem_used - server.maxmemory;
    mem_freed = 0;
    while (mem_freed < mem_tofree) {
        int j, k, keys_freed = 0;

        for (j = 0; j < server.dbnum; j++) {
            long bestval = 0; /* just to prevent warning */
            sds bestkey = NULL;
            struct dictEntry *de;
            redisDb *db = server.db+j;
            dict *dict;

            if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
                server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
            {
                dict = server.db[j].dict;
            } else {
                dict = server.db[j].expires;
            }
            if (dictSize(dict) == 0) continue;

            /* volatile-random and allkeys-random policy */
            if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
                server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
            {
                de = dictGetRandomKey(dict);
                bestkey = dictGetKey(de);
            }

            /* volatile-lru and allkeys-lru policy */
            else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
                server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
            {
                for (k = 0; k < server.maxmemory_samples; k++) {
                    sds thiskey;
                    long thisval;
                    robj *o;

                    de = dictGetRandomKey(dict);
                    thiskey = dictGetKey(de);
                    /* When policy is volatile-lru we need an additonal lookup
                     * to locate the real key, as dict is set to db->expires. */
                    if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
                        de = dictFind(db->dict, thiskey);
                    o = dictGetVal(de);
                    thisval = estimateObjectIdleTime(o);

                    /* Higher idle time is better candidate for deletion */
                    if (bestkey == NULL || thisval > bestval) {
                        bestkey = thiskey;
                        bestval = thisval;
                    }
                }
            }

            /* volatile-ttl */
            else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
                for (k = 0; k < server.maxmemory_samples; k++) {
                    sds thiskey;
                    long thisval;

                    de = dictGetRandomKey(dict);
                    thiskey = dictGetKey(de);
                    thisval = (long) dictGetVal(de);

                    /* Expire sooner (minor expire unix timestamp) is better
                     * candidate for deletion */
                    if (bestkey == NULL || thisval < bestval) {
                        bestkey = thiskey;
                        bestval = thisval;
                    }
                }
            }

            /* Finally remove the selected key. */
            if (bestkey) {
                long long delta;

                robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
                propagateExpire(db,keyobj);
                /* We compute the amount of memory freed by dbDelete() alone.
                 * It is possible that actually the memory needed to propagate
                 * the DEL in AOF and replication link is greater than the one
                 * we are freeing removing the key, but we can't account for
                 * that otherwise we would never exit the loop.
                 *
                 * AOF and Output buffer memory will be freed eventually so
                 * we only care about memory used by the key space. */
                delta = (long long) zmalloc_used_memory();
                dbDelete(db,keyobj);
                delta -= (long long) zmalloc_used_memory();
                mem_freed += delta;
                server.stat_evictedkeys++;
                decrRefCount(keyobj);
                keys_freed++;

                /* When the memory to free starts to be big enough, we may
                 * start spending so much time here that is impossible to
                 * deliver data to the slaves fast enough, so we force the
                 * transmission here inside the loop. */
                if (slaves) flushSlavesOutputBuffers();
            }
        }
        if (!keys_freed) return REDIS_ERR; /* nothing to free... */
    }
    return REDIS_OK;
}

/* =================================== Main! ================================ */

#ifdef __linux__
int linuxOvercommitMemoryValue(void) {
    FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
    char buf[64];

    if (!fp) return -1;
    if (fgets(buf,64,fp) == NULL) {
        fclose(fp);
        return -1;
    }
    fclose(fp);

    return atoi(buf);
}

void linuxOvercommitMemoryWarning(void) {
    if (linuxOvercommitMemoryValue() == 0) {
        redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
    }
}
#endif /* __linux__ */

void createPidFile(void) {
    /* Try to write the pid file in a best-effort way. */
    FILE *fp = fopen(server.pidfile,"w");
    if (fp) {
        fprintf(fp,"%d\n",(int)getpid());
        fclose(fp);
    }
}

void daemonize(void) {
    int fd;

    if (fork() != 0) exit(0); /* parent exits */
    setsid(); /* create a new session */

    /* Every output goes to /dev/null. If Redis is daemonized but
     * the 'logfile' is set to 'stdout' in the configuration file
     * it will not log at all. */
    if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
        dup2(fd, STDIN_FILENO);
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        if (fd > STDERR_FILENO) close(fd);
    }
}

void version() {
    printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d\n",
        REDIS_VERSION,
        redisGitSHA1(),
        atoi(redisGitDirty()) > 0,
        ZMALLOC_LIB,
        sizeof(long) == 4 ? 32 : 64);
    exit(0);
}

void usage() {
    fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
    fprintf(stderr,"       ./redis-server - (read config from stdin)\n");
    fprintf(stderr,"       ./redis-server -v or --version\n");
    fprintf(stderr,"       ./redis-server -h or --help\n");
    fprintf(stderr,"       ./redis-server --test-memory <megabytes>\n\n");
    fprintf(stderr,"Examples:\n");
    fprintf(stderr,"       ./redis-server (run the server with default conf)\n");
    fprintf(stderr,"       ./redis-server /etc/redis/6379.conf\n");
    fprintf(stderr,"       ./redis-server --port 7777\n");
    fprintf(stderr,"       ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n");
    fprintf(stderr,"       ./redis-server /etc/myredis.conf --loglevel verbose\n");
    exit(1);
}

void redisAsciiArt(void) {
#include "asciilogo.h"
    char *buf = zmalloc(1024*16);

    snprintf(buf,1024*16,ascii_logo,
        REDIS_VERSION,
        redisGitSHA1(),
        strtol(redisGitDirty(),NULL,10) > 0,
        (sizeof(long) == 8) ? "64" : "32",
        server.cluster_enabled ? "cluster" : "stand alone",
        server.port,
        (long) getpid()
    );
    redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
    zfree(buf);
}

static void sigtermHandler(int sig) {
    REDIS_NOTUSED(sig);

    redisLogFromHandler(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
    server.shutdown_asap = 1;
}

void setupSignalHandlers(void) {
    struct sigaction act;

    /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
     * Otherwise, sa_handler is used. */
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    act.sa_handler = sigtermHandler;
    sigaction(SIGTERM, &act, NULL);

#ifdef HAVE_BACKTRACE
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
    act.sa_sigaction = sigsegvHandler;
    sigaction(SIGSEGV, &act, NULL);
    sigaction(SIGBUS, &act, NULL);
    sigaction(SIGFPE, &act, NULL);
    sigaction(SIGILL, &act, NULL);
#endif
    return;
}

void memtest(size_t megabytes, int passes);

int main(int argc, char **argv) {
    long long start;
    struct timeval tv;

    /* We need to initialize our libraries, and the server configuration. */
    zmalloc_enable_thread_safeness();
    srand(time(NULL)^getpid());
    gettimeofday(&tv,NULL);
    dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid());
    initServerConfig();

    if (argc >= 2) {
        int j = 1; /* First option to parse in argv[] */
        sds options = sdsempty();
        char *configfile = NULL;

        /* Handle special options --help and --version */
        if (strcmp(argv[1], "-v") == 0 ||
            strcmp(argv[1], "--version") == 0) version();
        if (strcmp(argv[1], "--help") == 0 ||
            strcmp(argv[1], "-h") == 0) usage();
        if (strcmp(argv[1], "--test-memory") == 0) {
            if (argc == 3) {
                memtest(atoi(argv[2]),50);
                exit(0);
            } else {
                fprintf(stderr,"Please specify the amount of memory to test in megabytes.\n");
                fprintf(stderr,"Example: ./redis-server --test-memory 4096\n\n");
                exit(1);
            }
        }

        /* First argument is the config file name? */
        if (argv[j][0] != '-' || argv[j][1] != '-')
            configfile = argv[j++];
        /* All the other options are parsed and conceptually appended to the
         * configuration file. For instance --port 6380 will generate the
         * string "port 6380\n" to be parsed after the actual file name
         * is parsed, if any. */
        while(j != argc) {
            if (argv[j][0] == '-' && argv[j][1] == '-') {
                /* Option name */
                if (sdslen(options)) options = sdscat(options,"\n");
                options = sdscat(options,argv[j]+2);
                options = sdscat(options," ");
            } else {
                /* Option argument */
                options = sdscatrepr(options,argv[j],strlen(argv[j]));
                options = sdscat(options," ");
            }
            j++;
        }
        resetServerSaveParams();
        loadServerConfig(configfile,options);
        sdsfree(options);
    } else {
        redisLog(REDIS_WARNING,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'");
    }
    if (server.daemonize) daemonize();
    initServer();
    if (server.daemonize) createPidFile();
    redisAsciiArt();
    redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION);
#ifdef __linux__
    linuxOvercommitMemoryWarning();
#endif
    start = ustime();
    if (server.aof_state == REDIS_AOF_ON) {
        if (loadAppendOnlyFile(server.aof_filename) == REDIS_OK)
            redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000);
    } else {
        if (rdbLoad(server.rdb_filename) == REDIS_OK) {
            redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds",
                (float)(ustime()-start)/1000000);
        } else if (errno != ENOENT) {
            redisLog(REDIS_WARNING,"Fatal error loading the DB. Exiting.");
            exit(1);
        }
    }
    if (server.ipfd > 0)
        redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
    if (server.sofd > 0)
        redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
    aeSetBeforeSleepProc(server.el,beforeSleep);
    aeMain(server.el);
    aeDeleteEventLoop(server.el);
    return 0;
}

/* The End */
pygments.rb-0.6.3/test/test_pygments.rb000066400000000000000000000217621250413007300202040ustar00rootroot00000000000000#coding: utf-8 require 'test/unit' require File.join(File.dirname(__FILE__), '..', '/lib/pygments.rb') ENV['mentos-test'] = "yes" P = Pygments class PygmentsHighlightTest < Test::Unit::TestCase RUBY_CODE = "#!/usr/bin/ruby\nputs 'foo'" RUBY_CODE_TRAILING_NEWLINE = "#!/usr/bin/ruby\nputs 'foo'\n" REDIS_CODE = File.read(File.join(File.dirname(__FILE__), '..', '/test/test_data.c')) def test_highlight_defaults_to_html code = P.highlight(RUBY_CODE) assert_match '#!/usr/bin/ruby', code assert_equal '
#!/usr/bin/ruby', code assert_equal "
#!/usr/bin/ruby\nputs 'foo'\n
", code end def test_full_table_highlight code = P.highlight(RUBY_CODE, :options => {:linenos => true}) assert_match '#!/usr/bin/ruby', code assert_equal "
1\n2
#!/usr/bin/ruby\nputs 'foo'\n
\n
", code end def test_highlight_works_with_larger_files code = P.highlight(REDIS_CODE) assert_match 'used_memory_peak_human', code assert_equal 455203, code.bytesize.to_i end def test_returns_nil_on_timeout large_code = REDIS_CODE * 300 code = P.highlight(large_code) # a 30 mb highlight request will timeout assert_equal nil, code end def test_highlight_works_with_null_bytes code = P.highlight("\0hello", :lexer => 'rb') assert_match "hello", code end def test_highlight_works_on_utf8 code = P.highlight('# ø', :lexer => 'rb', :options => {:encoding => 'utf-8'}) assert_match "# ø", code end def test_highlight_works_on_utf8_automatically code = P.highlight('# ø', :lexer => 'rb') assert_match "# ø", code end def test_highlight_works_on_utf8_all_chars_automatically code = P.highlight('def foo: # ø', :lexer => 'py') assert_equal '
 'rb', :options => {:encoding => 'utf-8'})
    assert_match "# ø ø ø", code
  end

  def test_highlight_works_with_multiple_utf8_and_trailing_newline
    code = P.highlight("#!/usr/bin/ruby\nputs 'ø..ø'\n", :lexer => 'rb')
    assert_match "ø..ø", code
  end

  def test_highlight_formatter_bbcode
    code = P.highlight(RUBY_CODE, :formatter => 'bbcode')
    assert_match 'color=#408080][i]#!/usr/bin/ruby[/i]', code
  end

  def test_highlight_formatter_terminal
    code = P.highlight(RUBY_CODE, :formatter => 'terminal')
    assert_match '39;49;00m', code
  end

  def test_highlight_options
    code = P.highlight(RUBY_CODE, :options => {:full => true, :title => 'test'})
    assert_match 'test', code
  end

  def test_highlight_works_with_single_character_input
    code = P.highlight("a")
    assert_match 'a', code
  end

  def test_highlight_works_with_trailing_newline
    code = P.highlight(RUBY_CODE_TRAILING_NEWLINE)
    assert_match '#!/usr/bin/ruby', code
  end

  def test_highlight_works_with_multiple_newlines
    code = P.highlight(RUBY_CODE_TRAILING_NEWLINE + "derp\n\n")
    assert_match '#!/usr/bin/ruby', code
  end

  def test_highlight_works_with_trailing_cr
    code = P.highlight(RUBY_CODE_TRAILING_NEWLINE + "\r")
    assert_match '#!/usr/bin/ruby', code
  end

  def test_highlight_still_works_with_invalid_code
    code = P.highlight("importr python;    wat?", :lexer => 'py')
    assert_match ">importr", code
  end
end

# Philosophically, I'm not the biggest fan of testing private
# methods, but given the relative delicacy of validity checking
# over the pipe I think it's necessary and informative.
class PygmentsValidityTest < Test::Unit::TestCase
  def test_add_ids_with_padding
    res = P.send(:add_ids, "herp derp baz boo foo", "ABCDEFGH")
    assert_equal "ABCDEFGH  herp derp baz boo foo  ABCDEFGH", res
  end

  def test_add_ids_on_empty_string
    res = P.send(:add_ids, "", "ABCDEFGH")
    assert_equal "ABCDEFGH    ABCDEFGH", res
  end

  def test_add_ids_with_unicode_data
    res = P.send(:add_ids, "# ø ø ø", "ABCDEFGH")
    assert_equal "ABCDEFGH  # ø ø ø  ABCDEFGH", res
  end

  def test_add_ids_with_starting_slashes
    res = P.send(:add_ids, '\\# ø ø ø..//', "ABCDEFGH")
    assert_equal "ABCDEFGH  \\# ø ø ø..//  ABCDEFGH", res
  end

  def test_get_fixed_bits_from_header
    bits = P.send(:get_fixed_bits_from_header, '{"herp": "derp"}')
    assert_equal "00000000000000000000000000010000", bits
  end

  def test_get_fixed_bits_from_header_works_with_large_headers
    bits = P.send(:get_fixed_bits_from_header, '{"herp": "derp"}' * 10000)
    assert_equal "00000000000000100111000100000000", bits
  end

  def test_size_check
    size = "00000000000000000000000000100110"
    res = P.send(:size_check, size)
    assert_equal res, true
  end

  def test_size_check_bad
    size = "some random thing"
    res = P.send(:size_check, size)
    assert_equal res, false
  end
end

class PygmentsLexerTest < Test::Unit::TestCase
  RUBY_CODE = "#!/usr/bin/ruby\nputs 'foo'"

  def test_lexer_by_mimetype
    assert_equal 'rb', P.lexer_name_for(:mimetype => 'text/x-ruby')
    assert_equal 'json', P.lexer_name_for(:mimetype => 'application/json')
  end

  def test_lexer_by_filename
    assert_equal 'rb', P.lexer_name_for(:filename => 'test.rb')
    assert_equal 'scala', P.lexer_name_for(:filename => 'test.scala')
  end

  def test_lexer_by_name
    assert_equal 'rb', P.lexer_name_for(:lexer => 'ruby')
    assert_equal 'python', P.lexer_name_for(:lexer => 'python')
    assert_equal 'c', P.lexer_name_for(:lexer => 'c')
  end

  def test_lexer_by_filename_and_content
    assert_equal 'rb', P.lexer_name_for(RUBY_CODE, :filename => 'test.rb')
  end

  def test_lexer_by_content
    assert_equal 'rb', P.lexer_name_for(RUBY_CODE)
  end

  def test_lexer_by_nothing
    assert_raise MentosError do
      P.lexer_name_for(:invalid => true)
    end
  end
end

class PygmentsLexerClassTest < Test::Unit::TestCase
  def test_find
    assert_equal 'Ruby', P::Lexer['Ruby'].name
    assert_equal 'Ruby', P::Lexer['ruby'].name
    assert_equal 'Ruby', P::Lexer['rb'].name
    assert_equal 'Ruby', P::Lexer['rake'].name
    assert_equal 'Ruby', P::Lexer['gemspec'].name
  end

  def test_find_by_name
    assert_equal P::Lexer['Ruby'], P::Lexer.find_by_name('Ruby')
    assert_equal P::Lexer['C'], P::Lexer.find_by_name('C')
  end

  def test_find_by_alias
    assert_equal P::Lexer['Ruby'], P::Lexer.find_by_alias('rb')
    assert_equal P::Lexer['Ruby'], P::Lexer.find_by_alias('ruby')
    assert_equal P::Lexer['Scala'], P::Lexer.find_by_alias('scala')
    assert_equal P::Lexer['Go'], P::Lexer.find_by_alias('go')
  end

  def test_find_lexer_by_extname
    assert_equal P::Lexer['Ruby'], P::Lexer.find_by_extname('.rb')
    assert_equal P::Lexer['PHP'], P::Lexer.find_by_extname('.php4')
    assert_equal P::Lexer['PHP'], P::Lexer.find_by_extname('.php5')
    assert_equal P::Lexer['Groff'], P::Lexer.find_by_extname('.1')
    assert_equal P::Lexer['Groff'], P::Lexer.find_by_extname('.3')
    assert_equal P::Lexer['C'], P::Lexer.find_by_extname('.c')
    assert_equal P::Lexer['Python'], P::Lexer.find_by_extname('.py')
    assert_equal P::Lexer['Java'], P::Lexer.find_by_extname('.java')
  end

 def test_find_lexer_by_mimetype
    assert_equal P::Lexer['Ruby'], P::Lexer.find_by_mimetype('text/x-ruby')
    assert_equal P::Lexer['JSON'], P::Lexer.find_by_mimetype('application/json')
    assert_equal P::Lexer['Python'], P::Lexer.find_by_mimetype('text/x-python')
  end
end


class PygmentsCssTest < Test::Unit::TestCase
  include Pygments

  def test_css
    assert_match /^\.err \{/, P.css
  end

  def test_css_prefix
    assert_match /^\.highlight \.err \{/, P.css('.highlight')
  end

  def test_css_options
    assert_match /^\.codeerr \{/, P.css(:classprefix => 'code')
  end

  def test_css_prefix_and_options
    assert_match /^\.mycode \.codeerr \{/, P.css('.mycode', :classprefix => 'code')
  end

  def test_css_default
    assert_match '.c { color: #408080; font-style: italic }', P.css
  end

  def test_css_colorful
    assert_match '.c { color: #888888 }', P.css(:style => 'colorful')
  end
end

class PygmentsConfigTest < Test::Unit::TestCase
  def test_styles
    assert P.styles.include?('colorful')
  end

  def test_filters
    assert P.filters.include?('codetagify')
  end

  def test_lexers
    list = P.lexers
    assert list.has_key?('Ruby')
    assert list['Ruby'][:aliases].include?('duby')
  end

  def test_formatters
    list = P.formatters
    assert list.has_key?('Html')
    assert list['Html'][:aliases].include?('html')
  end
end


pygments.rb-0.6.3/vendor/000077500000000000000000000000001250413007300152605ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/custom_lexers/000077500000000000000000000000001250413007300201545ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/custom_lexers/github.py000066400000000000000000000510201250413007300220060ustar00rootroot00000000000000# -*- coding: utf-8 -*-
"""
    pygments.lexers.github
    ~~~~~~~~~~~~~~~~~~~

    Custom lexers for GitHub.com

    :copyright: Copyright 2012 by GitHub, Inc
    :license: BSD, see LICENSE for details.
"""
import re

from pygments.lexer import RegexLexer, ExtendedRegexLexer, include, bygroups, \
    using, DelegatingLexer
from pygments.token import Text, Name, Number, String, Comment, Punctuation, \
     Other, Keyword, Operator, Literal, Whitespace

__all__ = ['Dasm16Lexer', 'PuppetLexer', 'AugeasLexer', "TOMLLexer", "SlashLexer"]

class Dasm16Lexer(RegexLexer):
    """
    Simple lexer for DCPU-16 Assembly

    Check http://0x10c.com/doc/dcpu-16.txt
    """
    name = 'dasm16'
    aliases = ['DASM16']
    filenames = ['*.dasm16', '*.dasm']
    mimetypes = ['text/x-dasm16']

    INSTRUCTIONS = [
        'SET',
        'ADD', 'SUB',
        'MUL', 'MLI',
        'DIV', 'DVI',
        'MOD', 'MDI',
        'AND', 'BOR', 'XOR',
        'SHR', 'ASR', 'SHL',
        'IFB', 'IFC', 'IFE', 'IFN', 'IFG', 'IFA', 'IFL', 'IFU',
        'ADX', 'SBX',
        'STI', 'STD',
        'JSR',
        'INT', 'IAG', 'IAS', 'RFI', 'IAQ', 'HWN', 'HWQ', 'HWI',
    ]

    REGISTERS = [
        'A', 'B', 'C',
        'X', 'Y', 'Z',
        'I', 'J',
        'SP', 'PC', 'EX',
        'POP', 'PEEK', 'PUSH'
    ]

    # Regexes yo
    char = r'[a-zA-Z$._0-9@]'
    identifier = r'(?:[a-zA-Z$_]' + char + '*|\.' + char + '+)'
    number = r'[+-]?(?:0[xX][a-zA-Z0-9]+|\d+)'
    binary_number = r'0b[01_]+'
    instruction = r'(?i)(' + '|'.join(INSTRUCTIONS) + ')'
    single_char = r"'\\?" + char + "'"
    string = r'"(\\"|[^"])*"'

    def guess_identifier(lexer, match):
        ident = match.group(0)
        klass = Name.Variable if ident.upper() in lexer.REGISTERS else Name.Label
        yield match.start(), klass, ident

    tokens = {
        'root': [
            include('whitespace'),
            (':' + identifier, Name.Label),
            (identifier + ':', Name.Label),
            (instruction, Name.Function, 'instruction-args'),
            (r'\.' + identifier, Name.Function, 'data-args'),
            (r'[\r\n]+', Text)
        ],

        'numeric' : [
            (binary_number, Number.Integer),
            (number, Number.Integer),
            (single_char, String),
        ],

        'arg' : [
            (identifier, guess_identifier),
            include('numeric')
        ],

        'deref' : [
            (r'\+', Punctuation),
            (r'\]', Punctuation, '#pop'),
            include('arg'),
            include('whitespace')
        ],

        'instruction-line' : [
            (r'[\r\n]+', Text, '#pop'),
            (r';.*?$', Comment, '#pop'),
            include('whitespace')
        ],

        'instruction-args': [
            (r',', Punctuation),
            (r'\[', Punctuation, 'deref'),
            include('arg'),
            include('instruction-line')
        ],

        'data-args' : [
            (r',', Punctuation),
            include('numeric'),
            (string, String),
            include('instruction-line')
        ],

        'whitespace': [
            (r'\n', Text),
            (r'\s+', Text),
            (r';.*?\n', Comment)
        ],
    }

class PuppetLexer(RegexLexer):
    name = 'Puppet'
    aliases = ['puppet']
    filenames = ['*.pp']

    tokens = {
        'root': [
            include('puppet'),
        ],
        'puppet': [
            include('comments'),
            (r'(class)(\s*)(\{)', bygroups(Name.Class, Text, Punctuation), ('type', 'namevar')),
            (r'(class|define)', Keyword.Declaration, ('block','class_name')),
            (r'node', Keyword.Declaration, ('block', 'node_name')),
            (r'elsif', Keyword.Reserved, ('block', 'conditional')),
            (r'if', Keyword.Reserved, ('block', 'conditional')),
            (r'unless', Keyword.Reserved, ('block', 'conditional')),
            (r'(else)(\s*)(\{)', bygroups(Keyword.Reserved, Text, Punctuation), 'block'),
            (r'case', Keyword.Reserved, ('case', 'conditional')),
            (r'(::)?([A-Z][\w:]+)+(\s*)(<{1,2}\|)', bygroups(Name.Class, Name.Class, Text, Punctuation), 'spaceinvader'),
            (r'(::)?([A-Z][\w:]+)+(\s*)(\{)', bygroups(Name.Class, Name.Class, Text, Punctuation), 'type'),
            (r'(::)?([A-Z][\w:]+)+(\s*)(\[)', bygroups(Name.Class, Name.Class, Text, Punctuation), ('type', 'override_name')),
            (r'(@{0,2}[\w:]+)(\s*)(\{)(\s*)', bygroups(Name.Class, Text, Punctuation, Text), ('type', 'namevar')),
            (r'\$(::)?(\w+::)*\w+', Name.Variable, 'var_assign'),
            (r'(include|require)', Keyword.Namespace, 'include'),
            (r'import', Keyword.Namespace, 'import'),
            (r'(\w+)(\()', bygroups(Name.Function, Punctuation), 'function'),
            (r'\s', Text),
        ],
        'block': [
            include('puppet'),
            (r'\}', Text, '#pop'),
        ],
        'override_name': [
            include('strings'),
            include('variables'),
            (r'\]', Punctuation),
            (r'\s', Text),
            (r'\{', Punctuation, '#pop'),
        ],
        'node_name': [
            (r'inherits', Keyword.Declaration),
            (r'[\w\.]+', String),
            include('strings'),
            include('variables'),
            (r',', Punctuation),
            (r'\s', Text),
            (r'\{', Punctuation, '#pop'),
        ],
        'class_name': [
            (r'inherits', Keyword.Declaration),
            (r'[\w:]+', Name.Class),
            (r'\s', Text),
            (r'\{', Punctuation, '#pop'),
            (r'\(', Punctuation, 'paramlist'),
        ],
        'include': [
            (r'\n', Text, '#pop'),
            (r'[\w:-]+', Name.Class),
            include('value'),
            (r'\s', Text),
        ],
        'import': [
            (r'\n', Text, '#pop'),
            (r'[\/\w\.]+', String),
            include('value'),
            (r'\s', Text),
        ],
        'case': [
            (r'(default)(:)(\s*)(\{)', bygroups(Keyword.Reserved, Punctuation, Text, Punctuation), 'block'),
            include('case_values'),
            (r'(:)(\s*)(\{)', bygroups(Punctuation, Text, Punctuation), 'block'),
            (r'\s', Text),
            (r'\}', Punctuation, '#pop'),
        ],
        'case_values': [
            include('value'),
            (r',', Punctuation),
        ],
        'comments': [
            (r'\s*#.*\n', Comment.Singleline),
        ],
        'strings': [
            (r"'.*?'", String.Single),
            (r'\w+', String.Symbol),
            (r'"', String.Double, 'dblstring'),
            (r'\/.+?\/', String.Regex),
        ],
        'dblstring': [
            (r'\$\{.+?\}', String.Interpol),
            (r'(?:\\(?:[bdefnrstv\'"\$\\/]|[0-7][0-7]?[0-7]?|\^[a-zA-Z]))', String.Escape),
            (r'[^"\\\$]+', String.Double),
            (r'\$', String.Double),
            (r'"', String.Double, '#pop'),
        ],
        'variables': [
            (r'\$(::)?(\w+::)*\w+', Name.Variable),
        ],
        'var_assign': [
            (r'\[', Punctuation, ('#pop', 'array')),
            (r'\{', Punctuation, ('#pop', 'hash')),
            (r'(\s*)(=)(\s*)', bygroups(Text, Operator, Text)),
            (r'(\(|\))', Punctuation),
            include('operators'),
            include('value'),
            (r'\s', Text, '#pop'),
        ],
        'booleans': [
            (r'(true|false)', Literal),
        ],
        'operators': [
            (r'(\s*)(==|=~|\*|-|\+|<<|>>|!=|!~|!|>=|<=|<|>|and|or|in)(\s*)', bygroups(Text, Operator, Text)),
        ],
        'conditional': [
            include('operators'),
            include('strings'),
            include('variables'),
            (r'\[', Punctuation, 'array'),
            (r'\(', Punctuation, 'conditional'),
            (r'\{', Punctuation, '#pop'),
            (r'\)', Punctuation, '#pop'),
            (r'\s', Text),
        ],
        'spaceinvader': [
            include('operators'),
            include('strings'),
            include('variables'),
            (r'\[', Punctuation, 'array'),
            (r'\(', Punctuation, 'conditional'),
            (r'\s', Text),
            (r'\|>{1,2}', Punctuation, '#pop'),
        ],
        'namevar': [
            include('value'),
            (r'\[', Punctuation, 'array'),
            (r'\s', Text),
            (r':', Punctuation, '#pop'),
            (r'\}', Punctuation, '#pop'),
        ],
        'function': [
            (r'\[', Punctuation, 'array'),
            include('value'),
            (r',', Punctuation),
            (r'\s', Text),
            (r'\)', Punctuation, '#pop'),
        ],
        'paramlist': [
            include('value'),
            (r'=', Punctuation),
            (r',', Punctuation),
            (r'\s', Text),
            (r'\[', Punctuation, 'array'),
            (r'\)', Punctuation, '#pop'),
        ],
        'type': [
            (r'(\w+)(\s*)(=>)(\s*)', bygroups(Name.Tag, Text, Punctuation, Text), 'param_value'),
            (r'\}', Punctuation, '#pop'),
            (r'\s', Text),
            include('comments'),
            (r'', Text, 'namevar'),
        ],
        'value': [
            (r'[\d\.]', Number),
            (r'([A-Z][\w:]+)+(\[)', bygroups(Name.Class, Punctuation), 'array'),
            (r'(\w+)(\()', bygroups(Name.Function, Punctuation), 'function'),
            include('strings'),
            include('variables'),
            include('comments'),
            include('booleans'),
            (r'(\s*)(\?)(\s*)(\{)', bygroups(Text, Punctuation, Text, Punctuation), 'selector'),
            (r'\{', Punctuation, 'hash'),
        ],
        'selector': [
            (r'default', Keyword.Reserved),
            include('value'),
            (r'=>', Punctuation),
            (r',', Punctuation),
            (r'\s', Text),
            (r'\}', Punctuation, '#pop'),
        ],
        'param_value': [
            include('value'),
            (r'\[', Punctuation, 'array'),
            (r',', Punctuation, '#pop'),
            (r';', Punctuation, '#pop'),
            (r'\s', Text, '#pop'),
            (r'', Text, '#pop'),
        ],
        'array': [
            include('value'),
            (r'\[', Punctuation, 'array'),
            (r',', Punctuation),
            (r'\s', Text),
            (r'\]', Punctuation, '#pop'),
        ],
        'hash': [
            include('value'),
            (r'\s', Text),
            (r'=>', Punctuation),
            (r',', Punctuation),
            (r'\}', Punctuation, '#pop'),
        ],
    }

class AugeasLexer(RegexLexer):
    name = 'Augeas'
    aliases = ['augeas']
    filenames = ['*.aug']

    tokens = {
        'root': [
            (r'(module)(\s*)([^\s=]+)', bygroups(Keyword.Namespace, Text, Name.Namespace)),
            (r'(let)(\s*)([^\s=]+)', bygroups(Keyword.Declaration, Text, Name.Variable)),
            (r'(del|store|value|counter|seq|key|label|autoload|incl|excl|transform|test|get|put)(\s+)', bygroups(Name.Builtin, Text)),
            (r'(\()([^\:]+)(\:)(unit|string|regexp|lens|tree|filter)(\))', bygroups(Punctuation, Name.Variable, Punctuation, Keyword.Type, Punctuation)),
            (r'\(\*', Comment.Multiline, 'comment'),
            (r'[\+=\|\.\*\;\?-]', Operator),
            (r'[\[\]\(\)\{\}]', Operator),
            (r'"', String.Double, 'string'),
            (r'\/', String.Regex, 'regex'),
            (r'([A-Z]\w*)(\.)(\w+)', bygroups(Name.Namespace, Punctuation, Name.Variable)),
            (r'.', Name.Variable),
            (r'\s', Text),
        ],
        'string': [
            (r'\\.', String.Escape),
            (r'[^"]', String.Double),
            (r'"', String.Double, '#pop'),
        ],
        'regex': [
            (r'\\.', String.Escape),
            (r'[^\/]', String.Regex),
            (r'\/', String.Regex, '#pop'),
        ],
        'comment': [
            (r'[^*\)]', Comment.Multiline),
            (r'\(\*', Comment.Multiline, '#push'),
            (r'\*\)', Comment.Multiline, '#pop'),
            (r'[\*\)]', Comment.Multiline)
        ],
    }

class TOMLLexer(RegexLexer):
    """
    Lexer for TOML, a simple language for config files
    """

    name = 'TOML'
    aliases = ['toml']
    filenames = ['*.toml']

    tokens = {
        'root': [

            # Basics, comments, strings
            (r'\s+', Text),
            (r'#.*?$', Comment.Single),
            (r'"(\\\\|\\"|[^"])*"', String),
            (r'(true|false)$', Keyword.Constant),
            ('[a-zA-Z_][a-zA-Z0-9_\-]*', Name),

            # Datetime
            (r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z', Number.Integer),

            # Numbers
            (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float),
            (r'\d+[eE][+-]?[0-9]+j?', Number.Float),
            (r'\-?\d+', Number.Integer),

            # Punctuation
            (r'[]{}:(),;[]', Punctuation),
            (r'\.', Punctuation),

            # Operators
            (r'=', Operator)

        ]
    }

class SlashLanguageLexer(ExtendedRegexLexer):
    _nkw = r'(?=[^a-zA-Z_0-9])'

    def move_state(new_state):
        return ("#pop", new_state)

    def right_angle_bracket(lexer, match, ctx):
        if len(ctx.stack) > 1 and ctx.stack[-2] == "string":
            ctx.stack.pop()
        yield match.start(), String.Interpol, u"}"
        ctx.pos = match.end()
        pass

    tokens = {
        "root": [
            (r"<%=",        Comment.Preproc,    move_state("slash")),
            (r"<%!!",       Comment.Preproc,    move_state("slash")),
            (r"<%#.*?%>",   Comment.Multiline),
            (r"<%",         Comment.Preproc,    move_state("slash")),
            (r".|\n",       Other),
        ],
        "string": [
            (r"\\",         String.Escape,      move_state("string_e")),
            (r"\"",         String,             move_state("slash")),
            (r"#\{",        String.Interpol,    "slash"),
            (r'.|\n',       String),
        ],
        "string_e": [
            (r'n',                  String.Escape,      move_state("string")),
            (r't',                  String.Escape,      move_state("string")),
            (r'r',                  String.Escape,      move_state("string")),
            (r'e',                  String.Escape,      move_state("string")),
            (r'x[a-fA-F0-9]{2}',    String.Escape,      move_state("string")),
            (r'.',                  String.Escape,      move_state("string")),
        ],
        "regexp": [
            (r'}[a-z]*',            String.Regex,       move_state("slash")),
            (r'\\(.|\n)',           String.Regex),
            (r'{',                  String.Regex,       "regexp_r"),
            (r'.|\n',               String.Regex),
        ],
        "regexp_r": [
            (r'}[a-z]*',            String.Regex,       "#pop"),
            (r'\\(.|\n)',           String.Regex),
            (r'{',                  String.Regex,       "regexp_r"),
        ],
        "slash": [
            (r"%>",                     Comment.Preproc,    move_state("root")),
            (r"\"",                     String,             move_state("string")),
            (r"'[a-zA-Z0-9_]+",         String),
            (r'%r{',                    String.Regex,       move_state("regexp")),
            (r'/\*.*?\*/',              Comment.Multiline),
            (r"(#|//).*?\n",            Comment.Single),
            (r'-?[0-9]+e[+-]?[0-9]+',   Number.Float),
            (r'-?[0-9]+\.[0-9]+(e[+-]?[0-9]+)?', Number.Float),
            (r'-?[0-9]+',               Number.Integer),
            (r'nil'+_nkw,               Name.Builtin),
            (r'true'+_nkw,              Name.Builtin),
            (r'false'+_nkw,             Name.Builtin),
            (r'self'+_nkw,              Name.Builtin),
            (r'(class)(\s+)([A-Z][a-zA-Z0-9_\']*)',
                bygroups(Keyword, Whitespace, Name.Class)),
            (r'class'+_nkw,             Keyword),
            (r'extends'+_nkw,           Keyword),
            (r'(def)(\s+)(self)(\s*)(\.)(\s*)([a-z_][a-zA-Z0-9_\']*=?|<<|>>|==|<=>|<=|<|>=|>|\+|-(self)?|~(self)?|\*|/|%|^|&&|&|\||\[\]=?)',
                bygroups(Keyword, Whitespace, Name.Builtin, Whitespace, Punctuation, Whitespace, Name.Function)),
            (r'(def)(\s+)([a-z_][a-zA-Z0-9_\']*=?|<<|>>|==|<=>|<=|<|>=|>|\+|-(self)?|~(self)?|\*|/|%|^|&&|&|\||\[\]=?)',
                bygroups(Keyword, Whitespace, Name.Function)),
            (r'def'+_nkw,               Keyword),
            (r'if'+_nkw,                Keyword),
            (r'elsif'+_nkw,             Keyword),
            (r'else'+_nkw,              Keyword),
            (r'unless'+_nkw,            Keyword),
            (r'for'+_nkw,               Keyword),
            (r'in'+_nkw,                Keyword),
            (r'while'+_nkw,             Keyword),
            (r'until'+_nkw,             Keyword),
            (r'and'+_nkw,               Keyword),
            (r'or'+_nkw,                Keyword),
            (r'not'+_nkw,               Keyword),
            (r'lambda'+_nkw,            Keyword),
            (r'try'+_nkw,               Keyword),
            (r'catch'+_nkw,             Keyword),
            (r'return'+_nkw,            Keyword),
            (r'next'+_nkw,              Keyword),
            (r'last'+_nkw,              Keyword),
            (r'throw'+_nkw,             Keyword),
            (r'use'+_nkw,               Keyword),
            (r'switch'+_nkw,            Keyword),
            (r'\\',                     Keyword),
            (r'λ',                      Keyword),
            (r'__FILE__'+_nkw,          Name.Builtin.Pseudo),
            (r'__LINE__'+_nkw,          Name.Builtin.Pseudo),
            (r'[A-Z][a-zA-Z0-9_\']*'+_nkw, Name.Constant),
            (r'[a-z_][a-zA-Z0-9_\']*'+_nkw, Name),
            (r'@[a-z_][a-zA-Z0-9_\']*'+_nkw, Name.Variable.Instance),
            (r'@@[a-z_][a-zA-Z0-9_\']*'+_nkw, Name.Variable.Class),
            (r'\(',                     Punctuation),
            (r'\)',                     Punctuation),
            (r'\[',                     Punctuation),
            (r'\]',                     Punctuation),
            (r'\{',                     Punctuation),
            (r'\}',                     right_angle_bracket),
            (r';',                      Punctuation),
            (r',',                      Punctuation),
            (r'<<=',                    Operator),
            (r'>>=',                    Operator),
            (r'<<',                     Operator),
            (r'>>',                     Operator),
            (r'==',                     Operator),
            (r'!=',                     Operator),
            (r'=>',                     Operator),
            (r'=',                      Operator),
            (r'<=>',                    Operator),
            (r'<=',                     Operator),
            (r'>=',                     Operator),
            (r'<',                      Operator),
            (r'>',                      Operator),
            (r'\+\+',                   Operator),
            (r'\+=',                    Operator),
            (r'-=',                     Operator),
            (r'\*\*=',                  Operator),
            (r'\*=',                    Operator),
            (r'\*\*',                   Operator),
            (r'\*',                     Operator),
            (r'/=',                     Operator),
            (r'\+',                     Operator),
            (r'-',                      Operator),
            (r'/',                      Operator),
            (r'%=',                     Operator),
            (r'%',                      Operator),
            (r'^=',                     Operator),
            (r'&&=',                    Operator),
            (r'&=',                     Operator),
            (r'&&',                     Operator),
            (r'&',                      Operator),
            (r'\|\|=',                  Operator),
            (r'\|=',                    Operator),
            (r'\|\|',                   Operator),
            (r'\|',                     Operator),
            (r'!',                      Operator),
            (r'\.\.\.',                 Operator),
            (r'\.\.',                   Operator),
            (r'\.',                     Operator),
            (r'::',                     Operator),
            (r':',                      Operator),
            (r'(\s|\n)+',               Whitespace),
            (r'[a-z_][a-zA-Z0-9_\']*',  Name.Variable),
        ],
    }

class SlashLexer(DelegatingLexer):
    """
    Lexer for the Slash programming language.
    """

    name = 'Slash'
    aliases = ['slash']
    filenames = ['*.sl']

    def __init__(self, **options):
        from pygments.lexers.web import HtmlLexer
        super(SlashLexer, self).__init__(HtmlLexer, SlashLanguageLexer, **options)

pygments.rb-0.6.3/vendor/pygments-main/000077500000000000000000000000001250413007300200505ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/AUTHORS000066400000000000000000000137261250413007300211310ustar00rootroot00000000000000Pygments is written and maintained by Georg Brandl .

Major developers are Tim Hatch  and Armin Ronacher
.

Other contributors, listed alphabetically, are:

* Sam Aaron -- Ioke lexer
* Ali Afshar -- image formatter
* Thomas Aglassinger -- Rexx lexer
* Kumar Appaiah -- Debian control lexer
* Andreas Amann -- AppleScript lexer
* Timothy Armstrong -- Dart lexer fixes
* Jeffrey Arnold -- R/S, Rd, BUGS, Jags, and Stan lexers
* Jeremy Ashkenas -- CoffeeScript lexer
* Stefan Matthias Aust -- Smalltalk lexer
* Ben Bangert -- Mako lexers
* Max Battcher -- Darcs patch lexer
* Thomas Baruchel -- APL lexer
* Tim Baumann -- (Literate) Agda lexer
* Paul Baumgart, 280 North, Inc. -- Objective-J lexer
* Michael Bayer -- Myghty lexers
* John Benediktsson -- Factor lexer
* Christopher Bertels -- Fancy lexer
* Jarrett Billingsley -- MiniD lexer
* Adam Blinkinsop -- Haskell, Redcode lexers
* Frits van Bommel -- assembler lexers
* Pierre Bourdon -- bugfixes
* Hiram Chirino -- Scaml and Jade lexers
* Ian Cooper -- VGL lexer
* David Corbett -- Inform and Jasmin lexers
* Leaf Corcoran -- MoonScript lexer
* Christopher Creutzig -- MuPAD lexer
* Daniël W. Crompton - Pike lexer
* Pete Curry -- bugfixes
* Bryan Davis -- EBNF lexer
* Owen Durni -- Haxe lexer
* Alexander Dutton, Oxford University Computing Services -- SPARQL lexer
* Nick Efford -- Python 3 lexer
* Sven Efftinge -- Xtend lexer
* Artem Egorkine -- terminal256 formatter
* James H. Fisher -- PostScript lexer
* William S. Fulton -- SWIG lexer
* Carlos Galdino -- Elixir and Elixir Console lexers
* Michael Galloy -- IDL lexer
* Naveen Garg -- Autohotkey lexer
* Laurent Gautier -- R/S lexer
* Alex Gaynor -- PyPy log lexer
* Richard Gerkin -- Igor Pro lexer
* Alain Gilbert -- TypeScript lexer
* Alex Gilding -- BlitzBasic lexer
* Bertrand Goetzmann -- Groovy lexer
* Krzysiek Goj -- Scala lexer
* Matt Good -- Genshi, Cheetah lexers
* Michał Górny -- vim modeline support
* Patrick Gotthardt -- PHP namespaces support
* Olivier Guibe -- Asymptote lexer
* Jordi Gutiérrez Hermoso -- Octave lexer
* Martin Harriman -- SNOBOL lexer
* Matthew Harrison -- SVG formatter
* Steven Hazel -- Tcl lexer
* Aslak Hellesøy -- Gherkin lexer
* Greg Hendershott -- Racket lexer
* David Hess, Fish Software, Inc. -- Objective-J lexer
* Varun Hiremath -- Debian control lexer
* Rob Hoelz -- Perl 6 lexer
* Doug Hogan -- Mscgen lexer
* Ben Hollis -- Mason lexer
* Max Horn -- GAP lexer
* Dustin Howett -- Logos lexer
* Alastair Houghton -- Lexer inheritance facility
* Tim Howard -- BlitzMax lexer
* Ivan Inozemtsev -- Fantom lexer
* Brian R. Jackson -- Tea lexer
* Christian Jann -- ShellSession lexer
* Dennis Kaarsemaker -- sources.list lexer
* Dmitri Kabak - Inferno Limbo lexer
* Igor Kalnitsky -- vhdl lexer
* Alexander Kit -- MaskJS lexer
* Pekka Klärck -- Robot Framework lexer
* Eric Knibbe -- Lasso lexer
* Stepan Koltsov -- Clay lexer
* Adam Koprowski -- Opa lexer
* Benjamin Kowarsch -- Modula-2 lexer
* Domen Kožar -- Nix lexer
* Alexander Kriegisch -- Kconfig and AspectJ lexers
* Marek Kubica -- Scheme lexer
* Jochen Kupperschmidt -- Markdown processor
* Gerd Kurzbach -- Modelica lexer
* Jon Larimer, Google Inc. -- Smali lexer
* Olov Lassus -- Dart lexer
* Sylvestre Ledru -- Scilab lexer
* Mark Lee -- Vala lexer
* Ben Mabey -- Gherkin lexer
* Angus MacArthur -- QML lexer
* Louis Marchand -- Eiffel lexer
* Simone Margaritelli -- Hybris lexer
* Kirk McDonald -- D lexer
* Gordon McGregor -- SystemVerilog lexer
* Stephen McKamey -- Duel/JBST lexer
* Brian McKenna -- F# lexer
* Charles McLaughlin -- Puppet lexer
* Lukas Meuser -- BBCode formatter, Lua lexer
* Cat Miller -- Pig lexer
* Paul Miller -- LiveScript lexer
* Hong Minhee -- HTTP lexer
* Michael Mior -- Awk lexer
* Bruce Mitchener -- Dylan lexer rewrite
* Reuben Morais -- SourcePawn lexer
* Jon Morton -- Rust lexer
* Paulo Moura -- Logtalk lexer
* Mher Movsisyan -- DTD lexer
* Ana Nelson -- Ragel, ANTLR, R console lexers
* Nam T. Nguyen -- Monokai style
* Jesper Noehr -- HTML formatter "anchorlinenos"
* Mike Nolta -- Julia lexer
* Jonas Obrist -- BBCode lexer
* Edward O'Callaghan -- Cryptol lexer
* David Oliva -- Rebol lexer
* Pat Pannuto -- nesC lexer
* Jon Parise -- Protocol buffers lexer
* Ronny Pfannschmidt -- BBCode lexer
* Benjamin Peterson -- Test suite refactoring
* Dominik Picheta -- Nimrod lexer
* Andrew Pinkham -- RTF Formatter Refactoring
* Clément Prévost -- UrbiScript lexer
* raichoo -- Idris lexer
* Kashif Rasul -- CUDA lexer
* Justin Reidy -- MXML lexer
* Norman Richards -- JSON lexer
* Corey Richardson -- Rust lexer updates
* Lubomir Rintel -- GoodData MAQL and CL lexers
* Andre Roberge -- Tango style
* Konrad Rudolph -- LaTeX formatter enhancements
* Mario Ruggier -- Evoque lexers
* Stou Sandalski -- NumPy, FORTRAN, tcsh and XSLT lexers
* Matteo Sasso -- Common Lisp lexer
* Joe Schafer -- Ada lexer
* Ken Schutte -- Matlab lexers
* Tassilo Schweyer -- Io, MOOCode lexers
* Ted Shaw -- AutoIt lexer
* Joerg Sieker -- ABAP lexer
* Robert Simmons -- Standard ML lexer
* Kirill Simonov -- YAML lexer
* Alexander Smishlajev -- Visual FoxPro lexer
* Steve Spigarelli -- XQuery lexer
* Jerome St-Louis -- eC lexer
* James Strachan -- Kotlin lexer
* Tom Stuart -- Treetop lexer
* Tiberius Teng -- default style overhaul
* Jeremy Thurgood -- Erlang, Squid config lexers
* Brian Tiffin -- OpenCOBOL lexer
* Bob Tolbert -- Hy lexer
* Erick Tryzelaar -- Felix lexer
* Alexander Udalov -- Kotlin lexer improvements
* Thomas Van Doren -- Chapel lexer
* Daniele Varrazzo -- PostgreSQL lexers
* Abe Voelker -- OpenEdge ABL lexer
* Pepijn de Vos -- HTML formatter CTags support
* Whitney Young -- ObjectiveC lexer
* Matthias Vallentin -- Bro lexer
* Linh Vu Hong -- RSL lexer
* Nathan Weizenbaum -- Haml and Sass lexers
* Dietmar Winkler -- Modelica lexer
* Nils Winter -- Smalltalk lexer
* Davy Wybiral -- Clojure lexer
* Diego Zamboni -- CFengine3 lexer
* Enrique Zamudio -- Ceylon lexer
* Alex Zimin -- Nemerle lexer
* Rob Zimmerman -- Kal lexer

Many thanks for all contributions!
pygments.rb-0.6.3/vendor/pygments-main/CHANGES000066400000000000000000000603421250413007300210500ustar00rootroot00000000000000Pygments changelog
==================

Issue numbers refer to the tracker at
,
pull request numbers to the requests at
.

Version 2.0
-----------
(under development)

- Dropped Python 2.4 and 2.5 compatibility.  This is in favor of single-source
  compatibility between Python 2.6, 2.7 and 3.3+.

- New website and documentation based on Sphinx (finally!)

- Lexers added:

  * Clay (PR#184)
  * Perl 6 (PR#181)
  * Swig (PR#168)
  * nesC (PR#166)
  * BlitzBasic (PR#197)
  * EBNF (PR#193)
  * Igor Pro (PR#172)
  * Rexx (PR#199)
  * Agda and Literate Agda (PR#203)
  * Mathematica (PR#245)
  * Nix (PR#267)
  * Pike (PR#237)
  * Hy (PR#238)
  * Chapel (PR#256)
  * Kal (PR#233)
  * Eiffel (PR#273)
  * Cirru (PR#275)
  * ColdFusion CFC (PR#283)
  * Idris (PR#210)
  * Intel objdump (PR#279)
  * MaskJS (PR#280)
  * Inform 6/7 (PR#281)
  * MQL (PR#285)
  * APL (#969)

- New styles: "xcode" and "igor", similar to the default highlighting of
  the respective IDEs.

- Updated the Makefile lexer to yield a little more useful highlighting.

- Lexer aliases passed to ``get_lexer_by_name()`` are now case-insensitive.

- File name matching in lexers and formatters will now use a regex cache
  for speed (PR#205).

- Pygments will now recognize "vim" modelines when guessing the lexer for
  a file based on content (PR#118).

- The NameHighlightFilter now works with any Name.* token type (#790).

- Python 3 lexer: add new exceptions from PEP 3151.

- Opa lexer: add new keywords (PR#170).

- Julia lexer: add keywords and underscore-separated number
  literals (PR#176).

- Lasso lexer: fix method highlighting, update builtins. Fix
  guessing so that plain XML isn't always taken as Lasso (PR#163).

- Objective C/C++ lexers: allow "@" prefixing any expression (#871).

- Ruby lexer: fix lexing of Name::Space tokens (#860) and of symbols
  in hashes (#873).

- Stan lexer: update for version 1.3.0 of the language (PR#162).

- JavaScript lexer: add the "yield" keyword (PR#196).

- HTTP lexer: support for PATCH method (PR#190).

- Koka lexer: update to newest language spec (PR#201).

- Haxe lexer: rewrite and support for Haxe 3 (PR#174).

- Prolog lexer: add different kinds of numeric literals (#864).

- F# lexer: rewrite with newest spec for F# 3.0 (#842), fix a bug with
  dotted chains (#948).

- Kotlin lexer: general update (PR#271).

- Rebol lexer: fix comment detection and analyse_text (PR#261).

- Stan lexer: update to v2.0.1 (PR#255).

- LLVM lexer: update keywords to v3.4 (PR#258).

- PHP lexer: add new keywords and binary literals (PR#222).

- external/markdown-processor.py updated to newest python-markdown (PR#221).

- CSS lexer: some highlighting order fixes (PR#231).

- Ceylon lexer: fix parsing of nested multiline comments (#915).

- C family lexers: fix parsing of indented preprocessor directives (#944).

- Rust lexer: update to 0.9 language version (PR#270).


Version 1.6
-----------
(released Feb 3, 2013)

- Lexers added:

  * Dylan console (PR#149)
  * Logos (PR#150)
  * Shell sessions (PR#158)

- Fix guessed lexers not receiving lexer options (#838).

- Fix unquoted HTML attribute lexing in Opa (#841).

- Fixes to the Dart lexer (PR#160).


Version 1.6rc1
--------------
(released Jan 9, 2013)

- Lexers added:

  * AspectJ (PR#90)
  * AutoIt (PR#122)
  * BUGS-like languages (PR#89)
  * Ceylon (PR#86)
  * Croc (new name for MiniD)
  * CUDA (PR#75)
  * Dg (PR#116)
  * IDL (PR#115)
  * Jags (PR#89)
  * Julia (PR#61)
  * Kconfig (#711)
  * Lasso (PR#95, PR#113)
  * LiveScript (PR#84)
  * Monkey (PR#117)
  * Mscgen (PR#80)
  * NSIS scripts (PR#136)
  * OpenCOBOL (PR#72)
  * QML (PR#123)
  * Puppet (PR#133)
  * Racket (PR#94)
  * Rdoc (PR#99)
  * Robot Framework (PR#137)
  * RPM spec files (PR#124)
  * Rust (PR#67)
  * Smali (Dalvik assembly)
  * SourcePawn (PR#39)
  * Stan (PR#89)
  * Treetop (PR#125)
  * TypeScript (PR#114)
  * VGL (PR#12)
  * Visual FoxPro (#762)
  * Windows Registry (#819)
  * Xtend (PR#68)

- The HTML formatter now supports linking to tags using CTags files, when the
  python-ctags package is installed (PR#87).

- The HTML formatter now has a "linespans" option that wraps every line in a
   tag with a specific id (PR#82).

- When deriving a lexer from another lexer with token definitions, definitions
  for states not in the child lexer are now inherited.  If you override a state
  in the child lexer, an "inherit" keyword has been added to insert the base
  state at that position (PR#141).

- The C family lexers now inherit token definitions from a common base class,
  removing code duplication (PR#141).

- Use "colorama" on Windows for console color output (PR#142).

- Fix Template Haskell highlighting (PR#63).

- Fix some S/R lexer errors (PR#91).

- Fix a bug in the Prolog lexer with names that start with 'is' (#810).

- Rewrite Dylan lexer, add Dylan LID lexer (PR#147).

- Add a Java quickstart document (PR#146).

- Add a "external/autopygmentize" file that can be used as .lessfilter (#802).


Version 1.5
-----------
(codename Zeitdilatation, released Mar 10, 2012)

- Lexers added:

  * Awk (#630)
  * Fancy (#633)
  * PyPy Log
  * eC
  * Nimrod
  * Nemerle (#667)
  * F# (#353)
  * Groovy (#501)
  * PostgreSQL (#660)
  * DTD
  * Gosu (#634)
  * Octave (PR#22)
  * Standard ML (PR#14)
  * CFengine3 (#601)
  * Opa (PR#37)
  * HTTP sessions (PR#42)
  * JSON (PR#31)
  * SNOBOL (PR#30)
  * MoonScript (PR#43)
  * ECL (PR#29)
  * Urbiscript (PR#17)
  * OpenEdge ABL (PR#27)
  * SystemVerilog (PR#35)
  * Coq (#734)
  * PowerShell (#654)
  * Dart (#715)
  * Fantom (PR#36)
  * Bro (PR#5)
  * NewLISP (PR#26)
  * VHDL (PR#45)
  * Scilab (#740)
  * Elixir (PR#57)
  * Tea (PR#56)
  * Kotlin (PR#58)

- Fix Python 3 terminal highlighting with pygmentize (#691).

- In the LaTeX formatter, escape special &, < and > chars (#648).

- In the LaTeX formatter, fix display problems for styles with token
  background colors (#670).

- Enhancements to the Squid conf lexer (#664).

- Several fixes to the reStructuredText lexer (#636).

- Recognize methods in the ObjC lexer (#638).

- Fix Lua "class" highlighting: it does not have classes (#665).

- Fix degenerate regex in Scala lexer (#671) and highlighting bugs (#713, 708).

- Fix number pattern order in Ocaml lexer (#647).

- Fix generic type highlighting in ActionScript 3 (#666).

- Fixes to the Clojure lexer (PR#9).

- Fix degenerate regex in Nemerle lexer (#706).

- Fix infinite looping in CoffeeScript lexer (#729).

- Fix crashes and analysis with ObjectiveC lexer (#693, #696).

- Add some Fortran 2003 keywords.

- Fix Boo string regexes (#679).

- Add "rrt" style (#727).

- Fix infinite looping in Darcs Patch lexer.

- Lots of misc fixes to character-eating bugs and ordering problems in many
  different lexers.


Version 1.4
-----------
(codename Unschärfe, released Jan 03, 2011)

- Lexers added:

  * Factor (#520)
  * PostScript (#486)
  * Verilog (#491)
  * BlitzMax Basic (#478)
  * Ioke (#465)
  * Java properties, split out of the INI lexer (#445)
  * Scss (#509)
  * Duel/JBST
  * XQuery (#617)
  * Mason (#615)
  * GoodData (#609)
  * SSP (#473)
  * Autohotkey (#417)
  * Google Protocol Buffers
  * Hybris (#506)

- Do not fail in analyse_text methods (#618).

- Performance improvements in the HTML formatter (#523).

- With the ``noclasses`` option in the HTML formatter, some styles
  present in the stylesheet were not added as inline styles.

- Four fixes to the Lua lexer (#480, #481, #482, #497).

- More context-sensitive Gherkin lexer with support for more i18n translations.

- Support new OO keywords in Matlab lexer (#521).

- Small fix in the CoffeeScript lexer (#519).

- A bugfix for backslashes in ocaml strings (#499).

- Fix unicode/raw docstrings in the Python lexer (#489).

- Allow PIL to work without PIL.pth (#502).

- Allow seconds as a unit in CSS (#496).

- Support ``application/javascript`` as a JavaScript mime type (#504).

- Support `Offload `_ C++ Extensions as
  keywords in the C++ lexer (#484).

- Escape more characters in LaTeX output (#505).

- Update Haml/Sass lexers to version 3 (#509).

- Small PHP lexer string escaping fix (#515).

- Support comments before preprocessor directives, and unsigned/
  long long literals in C/C++ (#613, #616).

- Support line continuations in the INI lexer (#494).

- Fix lexing of Dylan string and char literals (#628).

- Fix class/procedure name highlighting in VB.NET lexer (#624).


Version 1.3.1
-------------
(bugfix release, released Mar 05, 2010)

- The ``pygmentize`` script was missing from the distribution.


Version 1.3
-----------
(codename Schneeglöckchen, released Mar 01, 2010)

- Added the ``ensurenl`` lexer option, which can be used to suppress the
  automatic addition of a newline to the lexer input.

- Lexers added:

  * Ada
  * Coldfusion
  * Modula-2
  * Haxe
  * R console
  * Objective-J
  * Haml and Sass
  * CoffeeScript

- Enhanced reStructuredText highlighting.

- Added support for PHP 5.3 namespaces in the PHP lexer.

- Added a bash completion script for `pygmentize`, to the external/
  directory (#466).

- Fixed a bug in `do_insertions()` used for multi-lexer languages.

- Fixed a Ruby regex highlighting bug (#476).

- Fixed regex highlighting bugs in Perl lexer (#258).

- Add small enhancements to the C lexer (#467) and Bash lexer (#469).

- Small fixes for the Tcl, Debian control file, Nginx config,
  Smalltalk, Objective-C, Clojure, Lua lexers.

- Gherkin lexer: Fixed single apostrophe bug and added new i18n keywords.


Version 1.2.2
-------------
(bugfix release, released Jan 02, 2010)

* Removed a backwards incompatibility in the LaTeX formatter that caused
  Sphinx to produce invalid commands when writing LaTeX output (#463).

* Fixed a forever-backtracking regex in the BashLexer (#462).


Version 1.2.1
-------------
(bugfix release, released Jan 02, 2010)

* Fixed mishandling of an ellipsis in place of the frames in a Python
  console traceback, resulting in clobbered output.


Version 1.2
-----------
(codename Neujahr, released Jan 01, 2010)

- Dropped Python 2.3 compatibility.

- Lexers added:

  * Asymptote
  * Go
  * Gherkin (Cucumber)
  * CMake
  * Ooc
  * Coldfusion
  * Haxe
  * R console

- Added options for rendering LaTeX in source code comments in the
  LaTeX formatter (#461).

- Updated the Logtalk lexer.

- Added `line_number_start` option to image formatter (#456).

- Added `hl_lines` and `hl_color` options to image formatter (#457).

- Fixed the HtmlFormatter's handling of noclasses=True to not output any
  classes (#427).

- Added the Monokai style (#453).

- Fixed LLVM lexer identifier syntax and added new keywords (#442).

- Fixed the PythonTracebackLexer to handle non-traceback data in header or
  trailer, and support more partial tracebacks that start on line 2 (#437).

- Fixed the CLexer to not highlight ternary statements as labels.

- Fixed lexing of some Ruby quoting peculiarities (#460).

- A few ASM lexer fixes (#450).


Version 1.1.1
-------------
(bugfix release, released Sep 15, 2009)

- Fixed the BBCode lexer (#435).

- Added support for new Jinja2 keywords.

- Fixed test suite failures.

- Added Gentoo-specific suffixes to Bash lexer.


Version 1.1
-----------
(codename Brillouin, released Sep 11, 2009)

- Ported Pygments to Python 3.  This needed a few changes in the way
  encodings are handled; they may affect corner cases when used with
  Python 2 as well.

- Lexers added:

  * Antlr/Ragel, thanks to Ana Nelson
  * (Ba)sh shell
  * Erlang shell
  * GLSL
  * Prolog
  * Evoque
  * Modelica
  * Rebol
  * MXML
  * Cython
  * ABAP
  * ASP.net (VB/C#)
  * Vala
  * Newspeak

- Fixed the LaTeX formatter's output so that output generated for one style
  can be used with the style definitions of another (#384).

- Added "anchorlinenos" and "noclobber_cssfile" (#396) options to HTML
  formatter.

- Support multiline strings in Lua lexer.

- Rewrite of the JavaScript lexer by Pumbaa80 to better support regular
  expression literals (#403).

- When pygmentize is asked to highlight a file for which multiple lexers
  match the filename, use the analyse_text guessing engine to determine the
  winner (#355).

- Fixed minor bugs in the JavaScript lexer (#383), the Matlab lexer (#378),
  the Scala lexer (#392), the INI lexer (#391), the Clojure lexer (#387)
  and the AS3 lexer (#389).

- Fixed three Perl heredoc lexing bugs (#379, #400, #422).

- Fixed a bug in the image formatter which misdetected lines (#380).

- Fixed bugs lexing extended Ruby strings and regexes.

- Fixed a bug when lexing git diffs.

- Fixed a bug lexing the empty commit in the PHP lexer (#405).

- Fixed a bug causing Python numbers to be mishighlighted as floats (#397).

- Fixed a bug when backslashes are used in odd locations in Python (#395).

- Fixed various bugs in Matlab and S-Plus lexers, thanks to Winston Chang (#410,
  #411, #413, #414) and fmarc (#419).

- Fixed a bug in Haskell single-line comment detection (#426).

- Added new-style reStructuredText directive for docutils 0.5+ (#428).


Version 1.0
-----------
(codename Dreiundzwanzig, released Nov 23, 2008)

- Don't use join(splitlines()) when converting newlines to ``\n``,
  because that doesn't keep all newlines at the end when the
  ``stripnl`` lexer option is False.

- Added ``-N`` option to command-line interface to get a lexer name
  for a given filename.

- Added Tango style, written by Andre Roberge for the Crunchy project.

- Added Python3TracebackLexer and ``python3`` option to
  PythonConsoleLexer.

- Fixed a few bugs in the Haskell lexer.

- Fixed PythonTracebackLexer to be able to recognize SyntaxError and
  KeyboardInterrupt (#360).

- Provide one formatter class per image format, so that surprises like::

    pygmentize -f gif -o foo.gif foo.py

  creating a PNG file are avoided.

- Actually use the `font_size` option of the image formatter.

- Fixed numpy lexer that it doesn't listen for `*.py` any longer.

- Fixed HTML formatter so that text options can be Unicode
  strings (#371).

- Unified Diff lexer supports the "udiff" alias now.

- Fixed a few issues in Scala lexer (#367).

- RubyConsoleLexer now supports simple prompt mode (#363).

- JavascriptLexer is smarter about what constitutes a regex (#356).

- Add Applescript lexer, thanks to Andreas Amann (#330).

- Make the codetags more strict about matching words (#368).

- NginxConfLexer is a little more accurate on mimetypes and
  variables (#370).


Version 0.11.1
--------------
(released Aug 24, 2008)

- Fixed a Jython compatibility issue in pygments.unistring (#358).


Version 0.11
------------
(codename Straußenei, released Aug 23, 2008)

Many thanks go to Tim Hatch for writing or integrating most of the bug
fixes and new features.

- Lexers added:

  * Nasm-style assembly language, thanks to delroth
  * YAML, thanks to Kirill Simonov
  * ActionScript 3, thanks to Pierre Bourdon
  * Cheetah/Spitfire templates, thanks to Matt Good
  * Lighttpd config files
  * Nginx config files
  * Gnuplot plotting scripts
  * Clojure
  * POV-Ray scene files
  * Sqlite3 interactive console sessions
  * Scala source files, thanks to Krzysiek Goj

- Lexers improved:

  * C lexer highlights standard library functions now and supports C99
    types.
  * Bash lexer now correctly highlights heredocs without preceding
    whitespace.
  * Vim lexer now highlights hex colors properly and knows a couple
    more keywords.
  * Irc logs lexer now handles xchat's default time format (#340) and
    correctly highlights lines ending in ``>``.
  * Support more delimiters for perl regular expressions (#258).
  * ObjectiveC lexer now supports 2.0 features.

- Added "Visual Studio" style.

- Updated markdown processor to Markdown 1.7.

- Support roman/sans/mono style defs and use them in the LaTeX
  formatter.

- The RawTokenFormatter is no longer registered to ``*.raw`` and it's
  documented that tokenization with this lexer may raise exceptions.

- New option ``hl_lines`` to HTML formatter, to highlight certain
  lines.

- New option ``prestyles`` to HTML formatter.

- New option *-g* to pygmentize, to allow lexer guessing based on
  filetext (can be slowish, so file extensions are still checked
  first).

- ``guess_lexer()`` now makes its decision much faster due to a cache
  of whether data is xml-like (a check which is used in several
  versions of ``analyse_text()``.  Several lexers also have more
  accurate ``analyse_text()`` now.


Version 0.10
------------
(codename Malzeug, released May 06, 2008)

- Lexers added:

  * Io
  * Smalltalk
  * Darcs patches
  * Tcl
  * Matlab
  * Matlab sessions
  * FORTRAN
  * XSLT
  * tcsh
  * NumPy
  * Python 3
  * S, S-plus, R statistics languages
  * Logtalk

- In the LatexFormatter, the *commandprefix* option is now by default
  'PY' instead of 'C', since the latter resulted in several collisions
  with other packages.  Also, the special meaning of the *arg*
  argument to ``get_style_defs()`` was removed.

- Added ImageFormatter, to format code as PNG, JPG, GIF or BMP.
  (Needs the Python Imaging Library.)

- Support doc comments in the PHP lexer.

- Handle format specifications in the Perl lexer.

- Fix comment handling in the Batch lexer.

- Add more file name extensions for the C++, INI and XML lexers.

- Fixes in the IRC and MuPad lexers.

- Fix function and interface name highlighting in the Java lexer.

- Fix at-rule handling in the CSS lexer.

- Handle KeyboardInterrupts gracefully in pygmentize.

- Added BlackWhiteStyle.

- Bash lexer now correctly highlights math, does not require
  whitespace after semicolons, and correctly highlights boolean
  operators.

- Makefile lexer is now capable of handling BSD and GNU make syntax.


Version 0.9
-----------
(codename Herbstzeitlose, released Oct 14, 2007)

- Lexers added:

  * Erlang
  * ActionScript
  * Literate Haskell
  * Common Lisp
  * Various assembly languages
  * Gettext catalogs
  * Squid configuration
  * Debian control files
  * MySQL-style SQL
  * MOOCode

- Lexers improved:

  * Greatly improved the Haskell and OCaml lexers.
  * Improved the Bash lexer's handling of nested constructs.
  * The C# and Java lexers exhibited abysmal performance with some
    input code; this should now be fixed.
  * The IRC logs lexer is now able to colorize weechat logs too.
  * The Lua lexer now recognizes multi-line comments.
  * Fixed bugs in the D and MiniD lexer.

- The encoding handling of the command line mode (pygmentize) was
  enhanced. You shouldn't get UnicodeErrors from it anymore if you
  don't give an encoding option.

- Added a ``-P`` option to the command line mode which can be used to
  give options whose values contain commas or equals signs.

- Added 256-color terminal formatter.

- Added an experimental SVG formatter.

- Added the ``lineanchors`` option to the HTML formatter, thanks to
  Ian Charnas for the idea.

- Gave the line numbers table a CSS class in the HTML formatter.

- Added a Vim 7-like style.


Version 0.8.1
-------------
(released Jun 27, 2007)

- Fixed POD highlighting in the Ruby lexer.

- Fixed Unicode class and namespace name highlighting in the C# lexer.

- Fixed Unicode string prefix highlighting in the Python lexer.

- Fixed a bug in the D and MiniD lexers.

- Fixed the included MoinMoin parser.


Version 0.8
-----------
(codename Maikäfer, released May 30, 2007)

- Lexers added:

  * Haskell, thanks to Adam Blinkinsop
  * Redcode, thanks to Adam Blinkinsop
  * D, thanks to Kirk McDonald
  * MuPad, thanks to Christopher Creutzig
  * MiniD, thanks to Jarrett Billingsley
  * Vim Script, by Tim Hatch

- The HTML formatter now has a second line-numbers mode in which it
  will just integrate the numbers in the same ``
`` tag as the
  code.

- The `CSharpLexer` now is Unicode-aware, which means that it has an
  option that can be set so that it correctly lexes Unicode
  identifiers allowed by the C# specs.

- Added a `RaiseOnErrorTokenFilter` that raises an exception when the
  lexer generates an error token, and a `VisibleWhitespaceFilter` that
  converts whitespace (spaces, tabs, newlines) into visible
  characters.

- Fixed the `do_insertions()` helper function to yield correct
  indices.

- The ReST lexer now automatically highlights source code blocks in
  ".. sourcecode:: language" and ".. code:: language" directive
  blocks.

- Improved the default style (thanks to Tiberius Teng). The old
  default is still available as the "emacs" style (which was an alias
  before).

- The `get_style_defs` method of HTML formatters now uses the
  `cssclass` option as the default selector if it was given.

- Improved the ReST and Bash lexers a bit.

- Fixed a few bugs in the Makefile and Bash lexers, thanks to Tim
  Hatch.

- Fixed a bug in the command line code that disallowed ``-O`` options
  when using the ``-S`` option.

- Fixed a bug in the `RawTokenFormatter`.


Version 0.7.1
-------------
(released Feb 15, 2007)

- Fixed little highlighting bugs in the Python, Java, Scheme and
  Apache Config lexers.

- Updated the included manpage.

- Included a built version of the documentation in the source tarball.


Version 0.7
-----------
(codename Faschingskrapfn, released Feb 14, 2007)

- Added a MoinMoin parser that uses Pygments. With it, you get
  Pygments highlighting in Moin Wiki pages.

- Changed the exception raised if no suitable lexer, formatter etc. is
  found in one of the `get_*_by_*` functions to a custom exception,
  `pygments.util.ClassNotFound`. It is, however, a subclass of
  `ValueError` in order to retain backwards compatibility.

- Added a `-H` command line option which can be used to get the
  docstring of a lexer, formatter or filter.

- Made the handling of lexers and formatters more consistent. The
  aliases and filename patterns of formatters are now attributes on
  them.

- Added an OCaml lexer, thanks to Adam Blinkinsop.

- Made the HTML formatter more flexible, and easily subclassable in
  order to make it easy to implement custom wrappers, e.g. alternate
  line number markup. See the documentation.

- Added an `outencoding` option to all formatters, making it possible
  to override the `encoding` (which is used by lexers and formatters)
  when using the command line interface. Also, if using the terminal
  formatter and the output file is a terminal and has an encoding
  attribute, use it if no encoding is given.

- Made it possible to just drop style modules into the `styles`
  subpackage of the Pygments installation.

- Added a "state" keyword argument to the `using` helper.

- Added a `commandprefix` option to the `LatexFormatter` which allows
  to control how the command names are constructed.

- Added quite a few new lexers, thanks to Tim Hatch:

  * Java Server Pages
  * Windows batch files
  * Trac Wiki markup
  * Python tracebacks
  * ReStructuredText
  * Dylan
  * and the Befunge esoteric programming language (yay!)

- Added Mako lexers by Ben Bangert.

- Added "fruity" style, another dark background originally vim-based
  theme.

- Added sources.list lexer by Dennis Kaarsemaker.

- Added token stream filters, and a pygmentize option to use them.

- Changed behavior of `in` Operator for tokens.

- Added mimetypes for all lexers.

- Fixed some problems lexing Python strings.

- Fixed tickets: #167, #178, #179, #180, #185, #201.


Version 0.6
-----------
(codename Zimtstern, released Dec 20, 2006)

- Added option for the HTML formatter to write the CSS to an external
  file in "full document" mode.

- Added RTF formatter.

- Added Bash and Apache configuration lexers (thanks to Tim Hatch).

- Improved guessing methods for various lexers.

- Added `@media` support to CSS lexer (thanks to Tim Hatch).

- Added a Groff lexer (thanks to Tim Hatch).

- License change to BSD.

- Added lexers for the Myghty template language.

- Added a Scheme lexer (thanks to Marek Kubica).

- Added some functions to iterate over existing lexers, formatters and
  lexers.

- The HtmlFormatter's `get_style_defs()` can now take a list as an
  argument to generate CSS with multiple prefixes.

- Support for guessing input encoding added.

- Encoding support added: all processing is now done with Unicode
  strings, input and output are converted from and optionally to byte
  strings (see the ``encoding`` option of lexers and formatters).

- Some improvements in the C(++) lexers handling comments and line
  continuations.


Version 0.5.1
-------------
(released Oct 30, 2006)

- Fixed traceback in ``pygmentize -L`` (thanks to Piotr Ozarowski).


Version 0.5
-----------
(codename PyKleur, released Oct 30, 2006)

- Initial public release.
pygments.rb-0.6.3/vendor/pygments-main/LICENSE000066400000000000000000000024631250413007300210620ustar00rootroot00000000000000Copyright (c) 2006-2014 by the respective authors (see AUTHORS file).
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
pygments.rb-0.6.3/vendor/pygments-main/MANIFEST.in000066400000000000000000000002561250413007300216110ustar00rootroot00000000000000include pygmentize
include external/*
include Makefile CHANGES LICENSE AUTHORS TODO ez_setup.py
recursive-include tests *
recursive-include doc *
recursive-include scripts *
pygments.rb-0.6.3/vendor/pygments-main/Makefile000066400000000000000000000026421250413007300215140ustar00rootroot00000000000000#
# Makefile for Pygments
# ~~~~~~~~~~~~~~~~~~~~~
#
# Combines scripts for common tasks.
#
# :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
# :license: BSD, see LICENSE for details.
#

PYTHON ?= python

export PYTHONPATH = $(shell echo "$$PYTHONPATH"):$(shell python -c 'import os; print ":".join(os.path.abspath(line.strip()) for line in file("PYTHONPATH"))' 2>/dev/null)

.PHONY: all check clean clean-pyc codetags docs mapfiles \
	pylint reindent test test-coverage

all: clean-pyc check test

check:
	@$(PYTHON) scripts/detect_missing_analyse_text.py || true
	@$(PYTHON) scripts/check_sources.py -i build -i dist -i pygments/lexers/_mapping.py \
		   -i docs/build -i pygments/formatters/_mapping.py -i pygments/unistring.py \
		   -i pygments/lexers/_vimbuiltins.py

clean: clean-pyc
	-rm -rf build
	-rm -f codetags.html

clean-pyc:
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +

codetags:
	@$(PYTHON) scripts/find_codetags.py -i tests/examplefiles -i scripts/pylintrc \
		   -i scripts/find_codetags.py -o codetags.html .

docs:
	make -C doc html

mapfiles:
	(cd pygments/lexers; $(PYTHON) _mapping.py)
	(cd pygments/formatters; $(PYTHON) _mapping.py)

pylint:
	@pylint --rcfile scripts/pylintrc pygments

reindent:
	@$(PYTHON) scripts/reindent.py -r -B .

test:
	@$(PYTHON) tests/run.py $(TEST)

test-coverage:
	@$(PYTHON) tests/run.py -C $(TEST)
pygments.rb-0.6.3/vendor/pygments-main/REVISION000066400000000000000000000000151250413007300212250ustar00rootroot00000000000000bec55c895c04
pygments.rb-0.6.3/vendor/pygments-main/TODO000066400000000000000000000007231250413007300205420ustar00rootroot00000000000000Todo
====

- suggested new lexers
  * IPython sessions

- lexers that need work:
  * review perl lexer (numerous bugs, but so far no one had complaints ;)
  * readd property support for C# lexer? that is, find a regex that doesn't
    backtrack to death...
  * add support for function name highlighting to C++ lexer

- allow "overlay" token types to highlight specials: nth line, a word etc.

- pygmentize option presets, more sophisticated method to output styles?
pygments.rb-0.6.3/vendor/pygments-main/doc/000077500000000000000000000000001250413007300206155ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/Makefile000066400000000000000000000127221250413007300222610ustar00rootroot00000000000000# Makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS    =
SPHINXBUILD   = PYTHONPATH=.. sphinx-build
PAPER         =
BUILDDIR      = _build

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .

.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext

help:
	@echo "Please use \`make ' where  is one of"
	@echo "  html       to make standalone HTML files"
	@echo "  dirhtml    to make HTML files named index.html in directories"
	@echo "  singlehtml to make a single large HTML file"
	@echo "  pickle     to make pickle files"
	@echo "  json       to make JSON files"
	@echo "  htmlhelp   to make HTML files and a HTML help project"
	@echo "  qthelp     to make HTML files and a qthelp project"
	@echo "  devhelp    to make HTML files and a Devhelp project"
	@echo "  epub       to make an epub"
	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
	@echo "  text       to make text files"
	@echo "  man        to make manual pages"
	@echo "  texinfo    to make Texinfo files"
	@echo "  info       to make Texinfo files and run them through makeinfo"
	@echo "  gettext    to make PO message catalogs"
	@echo "  changes    to make an overview of all changed/added/deprecated items"
	@echo "  linkcheck  to check all external links for integrity"
	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"

clean:
	-rm -rf $(BUILDDIR)/*

html:
	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

dirhtml:
	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

singlehtml:
	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
	@echo
	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."

pickle:
	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
	@echo
	@echo "Build finished; now you can process the pickle files."

json:
	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
	@echo
	@echo "Build finished; now you can process the JSON files."

htmlhelp:
	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
	@echo
	@echo "Build finished; now you can run HTML Help Workshop with the" \
	      ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
	@echo
	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Pygments.qhcp"
	@echo "To view the help file:"
	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Pygments.qhc"

devhelp:
	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
	@echo
	@echo "Build finished."
	@echo "To view the help file:"
	@echo "# mkdir -p $$HOME/.local/share/devhelp/Pygments"
	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Pygments"
	@echo "# devhelp"

epub:
	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
	@echo
	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."

latex:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo
	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
	@echo "Run \`make' in that directory to run these through (pdf)latex" \
	      "(use \`make latexpdf' here to do that automatically)."

latexpdf:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through pdflatex..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

text:
	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
	@echo
	@echo "Build finished. The text files are in $(BUILDDIR)/text."

man:
	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
	@echo
	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."

texinfo:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo
	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
	@echo "Run \`make' in that directory to run these through makeinfo" \
	      "(use \`make info' here to do that automatically)."

info:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo "Running Texinfo files through makeinfo..."
	make -C $(BUILDDIR)/texinfo info
	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."

gettext:
	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
	@echo
	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."

changes:
	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
	@echo
	@echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
	@echo
	@echo "Link check complete; look for any errors in the above output " \
	      "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
	@echo "Testing of doctests in the sources finished, look at the " \
	      "results in $(BUILDDIR)/doctest/output.txt."
pygments.rb-0.6.3/vendor/pygments-main/doc/_static/000077500000000000000000000000001250413007300222435ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/_static/favicon.ico000066400000000000000000000410761250413007300243740ustar00rootroot00000000000000@@ (B(@€ 	$6FMMMF5""5FMMMF6$	2OmƒŒŒŒ‚iH*)Hi‚ŒŒŒƒmP2:`ˆ¨¾5Æ8(tÆ
:Ƽ wJJw ¼!&ÆhvÆ8AÆ		¾¨ˆa:<f”»HÖDÍæFèêEèêEèêAÌâ.ÊŸjjŸÉ	¼âÎöêÍöêÍõêÅêæVdÖ¼”g<<g—Â#[ßKèðIè÷HèùGèùFèùDèòB ÒÝ´~~´ŽªÜÍ÷ñÍöøÍõøÍõøÍô÷Îóð€•à˜h=<g˜ÃVáLèóJèúIèýHèýGèýFèûEèòDèÝ)´~~´´×ÜÍöñÍöúÍõýÍôýÍóýÍóûÍòók}âØh> <h˜Ã/uâMèóJçûKèýIèýIèýHèýGèûEèòEèÝ
	´~~´¬ÏÜÍöñÍõúÍôýÍôýÍóýÍòýÍñûÍðó
ƒ—â

ÙkC&=h˜Ã:ŒâNèóMèûLèýKèýJèýJèýHèýGèûEèò;#›Û±{z¯q…ÙÍöðÍõúÍôýÍóýÍóýÍñýÍñýÍïûÍïó™°âÅžuO.	 >h˜Ã4‹âNèóOèûNèýMèýLèýKèýJèýIèüHèö=µçÈ—b_‘À’®áÍõóÍóûÍóýÍñýÍñýÍðýÍïýÍîûÍîôˆœä˪‚X3&DlšÃ:”âQèóQèûOèýOèýMèýMèýLèýKèûIèõ8Ÿè
ΦrA;f—”áÍóóÍòûÍñýÍðýÍïýÍîýÍíýÍíûÍìõ”©éÔ³Š^8/OuŸÆL"»âRèóRèûQèýPèýOèýOèýMèýMèûLèô-‡äʦyK%<g—Â	w‹áÍñóÍñûÍïýÍîýÍíýÍíýÍìýÍëüÍêø
ªÀíÙ¹‘d;7\„ªÌC«åSèôSèûRèýRèýQèýPèýOèýOèûNèó9—âÅsK)<g—ÂizáÍïóÍîûÍîýÍìýÍìþÍëþÍêþÍêýÍèù¯ÄïÝ¿–g<;d·
	
ÕF³éVèõUèûTèýTèýSèýRèýRèýPèûPèó,qâØjB%<g—ÂdráÍíóÌëûÍìýÍêþÍêþÍéþÍèþÍèýÍçú­Âòá˜h=<g–À	ÝY"ØîVèøVèüVèýVèýUèýTèýTèýRèûSèó&gâØh=<g—ÂiuáÍìóÍêûÍêþÍéþÍèþÍçþÍçþÍæþÍæû³ÇóâØh=<g˜ÂáLÀòXèúXèýXèþWèþVèþUèýUèýTèûUèó2wâØg<<g—ÂGQáÆáóÍéûÍèþÍçþÍçþÍæþÍåþÍåþÍäûÂÕó	-0âØh=<g˜Ã"áTÑóZèûZèþYèþYèþXèþXèþWèýWèûUçó
FâØg<<g—ÂBJáÎçóÌåûÍåþÍåþÍäþÍäþÍãþÍãþÍâû½Ñó*-âØh=<g˜Ã
/â^äó[èû[èþZèþZèþZèþYèþYèþXèûWàó!OâØg<<g—ÂAFáÏæóÍäûÍäþÍãþÍãþÍâþÍâþÍáþÍáûÆÙóâØh=<g˜Ã.âVÒó\èû\èþ\èþ[èþ[èþ[èþZèþZèûYÞó%OâØg<<g—Â7<á½ÒóÍâûÍáþÍâþÍàþÍáþÍßþÍàýÍàûÂÒóFKâØh=<g˜Ã%Fâ[áó^èû^èþ]èþ]èþ]èþ]èþ\èþ\èûUÔó&âØg<<g—Â"áÎáóÍàûÍàýÍßþÍßþÍßþÍÞþÍÞþÍÞûÊÚó>AâØh=	:f—Ã%Lâ`æó_èû^èþ^èþ^èþ^èþ^èþ]èþ]èûYÕó
7âØg<<g—Áß	ÁÑðÍßùÍÞýÍÞýÍÞþÍÝþÍÝþÍÝþÍÜûÍÜó;>âØh<2`”Â%Uá_áó_èû`èþ`èþ`èþ`èþ_èþ_èþ^èûSÁó
+âØg<<f”¼
(+Ù¹ÇìÍÜ÷ÍÜüÍÜþÍÛþÍÛþÍÛþÍÛþÍÛûÊØóQVâØf:#O‡»0fß`çóaèûaèþaèÿaèÿ`èÿ`èþ`èþ`èûSÄó
âØg<:aбÓ¸ÃêÍÛ÷ÍÛýÍÛþÍÚþÍÚþÍÚþÍÚþÍÚûÍÚóY]áÁ“^/4j¦/^ÕeèðcèúbèþbèÿbèÿbèÿbèÿaèþaèüWÂô
âØg<4V€­
Ô«µìÍÙøÍÙýÍÙþÍÙþÍÙþÍÙþÍÙþÌØûÍØóaeÞ·E?{	¸hèâeèöeèýeèÿdèÿdèÿdèÿdèÿdèýH ö
åÅ™h<
-Rƒ´Ù±ºïÍ×ùÍ×ýÍ×þÍ×ÿÍ×ÿÍ×ÿÍ×þÍ×ùÁÊë"$É‘Q?{5^¸gèâhèöhèýhèÿhèÿhèÿhèÿhèþ^ÏûîÑ¢m>1]‘ÀâÅÍõÍÖüÍÖþÍÖÿÍÖÿÍÖÿÍÖþÍÖùÍÕëHJÉ‘Q?{5^¸jèâkèökèýkèÿkèÿkèÿkèÿkèþdÓøçÂŽ[3>lžËèÁÈøÍÕýÍÕÿÍÕÿÍÕÿÍÕÿÍÕþÍÕùÍÔë	ILÉ‘Q?{¸q éâmèönèýnèÿnèÿnèÿoèÿoèþpèûdÃðײ‡\8<h˜Äã	µºôÍÓüÍÓþÍÓÿÍÓÿÍÓÿÍÓÿÍÔþÍÔùÁÇë  É‘Q4j¦1]Õrèðpèúqèþqèÿqèÿrèÿrèþrèýrèøm Ðë
Ö·d<<g˜Ã⧪óÍÒûÍÒþÍÒþÍÒÿÍÒÿÍÒÿÍÓþÍÓûÊÐóSUÞ·E#N‡»8eßtèótèûtèþuèþuèþvèþvèývèývèød¿ïÝÀ–g<<g˜Ã
00â°²óÍÐûÍÐþÍÑþÍÐþÍÐþÍÐþÍÑþÍÑûÈÌóEGáÁ“^/2`”Á:áwèówèûxèþxèþyèþyèþzèþ{èý{èúuÖòáØh=<g˜Ã++â¾¾óÍÎûÍÎþÍÎþÍÏþÍÏþÍÏþÍÏþÍÐûÌÏóJKâ×f:	:f—Â+Náyâózèû{èý{èþ}èþ}èþ}èþèþèû‚!åó+âØh=<g˜Ã'&⻺óÍÌûÍÌþÍÍþÍÍþÍÍþÍÎþÍÎþÍÎû¿ÀóLLâ×g<<g—Â.Má éó}èû~èþèþ€èþèþ‚èþƒèþƒèû{Óó'âØh=<g˜ÃONâÄÂóÌÉûÌÊþÌÊþÌËþÍËþÍËþÍÌþÍÌû½¼ó**âØg<<g—Â
,á}ßóèû‚èþƒèþ„èþ„èþ†èþ†èþ‡çû‡ãó!/âØh=<g˜Ã;9âÆ¿óÌÅûÌÆýÌÈþÌÉþÌÉþÌÊþÌÊþÍËûÍËó**â×g<<g—Â5á{×ó„èû…èþ†èþ‡çþˆæþ‰åþŠäþ‹ãû‹ Ýó0FâØh=<g˜ÃE@âʼóʾûËÁýËÂýÌÄþÌÅþÌÇþÌÈýÌÉú°­ñ''à—g<<g—Â&áˆ#áó‡çûˆæþŠåþŠäþŒâþáþŽßþ Ýû$×ó0CâØh=<h˜Ãh]âDzóÉ·ûɹý	ʼýʾýÊÀýËÂýËÃýËÄø°¬ïÜ¿–g<<g—Â!à ÑñŠäú‹âýáþàþ Ýþ!Ûþ‘"Ùþ“%×û•'Ôó/@âØh=
=h˜ÃOCâƪóÇ­ûDZýÈ´ý
É·ýɺý	Ê»ýʾüÊÀ÷½´ì׸c;<f•¿#Ýx¿ïßù Þý!Üþ‘"Úþ’$Øþ”%Õþ•'Óý—*Ïû—,ÉóDUâØh= ?i˜ÃcOâ#ÄŸóĤûƨýƬýǯýȲýȶý
É·ûʺõ˜èѰ‡\7;cºÚ|"ºï!Ûù’#Øý“%×þ•&Ôþ–(Ñþ—*Îý™,Ëýš/Çûœ2ÃóZ)iâØh="BlšÄ){_â/Á–ó)™û%ßý Ä£ýŧýÆ«ýÆ®ýDZûȳôŽäʧ~U28^Œ¹Û}%¶ï“%Õø•'Óü–)Ñý—+Íý™-Êýš/Çýœ2Ãýž5¾ûŸ7ºóS"\âØh<
 BoÆ&mMâ9¿Šó3Àû.Á•ý)Á™ý%Þý"Ä¡ýÅ¥ýÆ©ûƬóœŠâÄrK,	5]¸
×n!˜ê—)Ïö˜+Íû™-Êý›/Æý2Ãýž5¾ýŸ7ºý¢;¶û¢=±óQ TâØf:>l	Ç2|SäC¼€ô<¼„û8¾‹ý3Àý.À”ý*Á™ý&Ãý"áûĤó{jâØjA$
5\†¬Ìh‹äš-Êô›0Æûœ2Ãýž5¾ýŸ7»ý :·ý£>³ý¤A¯û¥C©ó@~áÁ“^1;gšÆF“_äM¹wôGº}ûB¼‚ý<½‡ý8¾‹ý3Àý.À”ý*Á˜û&ÜóydâØh=
1Qvž	Åu)”â2Ãóž5¿ûŸ7»ý¡:¸ý¢=³ý¤@¯ý¦C«ý§F§û¨H£óm5fÞ·I]’
ÁHWâT·oôP¹uûJºyýE»~ý@¼ƒý;½‡ý7¾Œý3Àû/Á•ó#s^âØg<	'Cj˜Ãn/‚áŸ6¼ó¡9¸û¢<µý£?±ý¥B­ý¦E©ý¨H¤ý©K ù«Oë@!:É’Xy°A|GÚZ¶iñV·múR¸rýN¹výIºzýE»ý?½ƒý:½‡û7¿ŒóUAâØg<=g—Â`$ná¡;´ó£?±û¥A®ý¦Dªý§G¦ý©J£ýªLŸù«N›ë’FÉ’X€¸Y¦^ß\µgóY¶kúU·oýQ¸sýL¹wýG»{ýC»û?½†óG3âØg<<g—Âa'ká¤A¯ó¥B«û¦E¨ý¨H¤ý©K ýªNù«O™ë£RÉ’X€!¸\«_ß]µfóZ¶iúV·mýR¸qýN¹uýJºyûH¹}ó!N9á×g<<g—ÂU'Xá§G©ò¨G¥ù¨J¢ùªLŸù«Nœø¬P™ê^0SÉ’X€¸S™Tß_µdó\µhùX¶kùT·oùQ¸søN¹wð,ß—g<<g—ÁV)VÞžDšë¦Iœë¨Kšë¦M–ê†BwÚµJo¥"Î[¨^ä[°dêX³gêT±jêL¦fæ$Ö»”f<<f“¶É:7É<7É.*ɵŽ]2O}¥¿ ;"Ç @%Ç8"Ǿ¨‡`:9]~‘‘‘‘~\7-Mm…ƒlO2/DQQQQD/$8HMMMF6$		!!!!	
				ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿàÿÿÿÿÿüÀ?ÿÿÿÿø€ÿÿÿÿð€ÿÿÿÿà€ÿÿÿÿÀ€ÿÿÿÿ€€ÿÿÿÿ€ÿÿþÀ?ÿÿüàÿÿððÿÿàøÿÿÀ?üÿÿ€þÿÿÿÿÿþÿÿ€üÿÿÀ?øÿÿàðÿÿðàÿÿøÀ?ÿÿüÀÿÿþÀÿÿÿÿÀÿÿÿÿ€Àÿÿÿÿ€ÀÿÿÿÿÀÿÿþÀ?ÿÿüàÿÿøðÿÿðøÿÿàüÿÿÀ?þÿÿ€ÿÿÿÿÿ€þÿÿÀ?üÿÿàøÿÿððÿÿøà?ÿÿüÀÿÿÿ€ÿÿÿÿ€€ÿÿÿÿÀÿÿÿÿàÿÿÿÿðÿÿÿÿø€ÿÿÿÿüÀ?ÿÿÿÿÿàÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿpygments.rb-0.6.3/vendor/pygments-main/doc/_static/logo_new.png000066400000000000000000001177601250413007300245760ustar00rootroot00000000000000‰PNG


IHDRñ¦¿!cbKGDÿÿÿ ½§“	pHYsšœtIMEÞ.3w6 IDATxÚì½{œg}ïÿ}âu"9ñ­ãÆIœH¹K@€Ù¤µ
vñBsÊšR=mL)­}z¸lZèù™]n»Ý_
x[ g·ð+Y—"JH,.]°ÛvKv 7ɹJ	O'ÞqÖ±%;vžó‡4Òh4º=I3ÚÏûõòË+if¤gfvž·¾Æ9'€{9»w‰€ËÄÀå@âàr ñp9x¸H<\$.—‰€ËÄÀå@âàr ñp9x¸H<\$.—‰€ËéÃ.Ð˨ªJÉdro*•Úäõß%Q(b~¿Ÿ$I¢P(„A`À8çØ eN™3G©ìhbùÿ^Y‹äb;òpñç_-ý¢ÿâW­_2_²z=ùW®ÂNž$›ÍÒìì,Ïd2=ÿ»dÞÆ`0x ‰`ðèA ñ€Ï>t˜~ù_ÚÓG2G/yö¡ç‰„]ñbDŒŠR+Υ5—ŸOëo”Øe7Jtö¹+±»À‰—OУ‹ÐÏýüñG<|Åböùü… 0RŒ8凎,§U+ýtåÀutåÀµ—¾þ¢Á_ø!e7˜ššâš¦-»ßÛçóQ$‡Ãzôx a^zî8=øõú?Ñ©ã/çµ+veÏYä+¾¾þF‰^ûÛW0	Qzá…ìôÇö$ïîgá§O”I;CÖ3“Ð+.S’{÷¯§¤7_y㺷<á_y.v.p%sss4??¿ìÿÀ’e™E£Qòûý80ð0x .Ï=x˜ü—îÁÃ%WŒ¸£ÊçªDãÙ­+½v-ýúû_Ï.¸üUØÑmàÄË'è;ïù›ù'ç>V”r6’®ø¿%
Õ{«V®¢7¯¿éão¾ì¿ßæïƒÌîbrr’뺎QÀçóQ4…ÌÀÃ@⪜zéýüîãéù§J2Έ¸c¦ø­ZÑxvÏ´ãy9vݘ»v{Ý9=ò}ég_âÙ—Sqϳ*òŽ‹Â³{~Uß*zç5ÛØàºÍØéÀhšFSSSøãfƒÏ磡¡!F±3ðxÀ–Ã&å3?á'Ÿ¢º‘wÔX4žñœ±œUîI‘µô¶¿ü5vêåµÌþ_í§¯>ðœ™Zä%1b•R®™(¼’ÄË/ψSäÂè=¯ýCTè6étšfffðÇ­’$Q,c’$agàÎÂ.V’_{莽ÛËO½tŠòî†þÏS”<Ï•þ'›é³yù‚3*{^K>O‰Oþ?yüeBÜqðóÕþÑÒ(ØØáå2®bËà1Ó@ÙGç•–Oþ)MáÚ±'1¸#ZQQì<$(ãÞÛ~ÊS_KÆÊ$•äUºÒs¼ø3/À-mɯøÂ“/Òþ¿ÿB ûµŸæŸœÿX#Ë–Æ·r€¬|µ~fÅŸ9éÙÃôŸàÚ±H$x<Íf³Ø¸HǶËåhÏž={±—pˆÄ[&,=¾H>ú#~ê¥SùH8Ûšw…èºZiµ-“_7¿kJnÝh55ųÙ,v "H¼žgéñEúé‡çùéc§ˆÈ$ኒÎÜ„ ÿ‚5­¶(þ,™†€3§ÙšE VÚ\™Ø£ò·*û 5ª6´ŠÂ³ïFñûþ'?üÒc`Âï÷ÓÐÐPK×Ôd2‰Z,t	H¼àñ©{ùÃã?)†GØ‹¼òè»â²Ô`}<2ÉšºÑ|­Eã?Ÿ}îJºzózp¼ãª­¬V»æ£ð*›YÔ^ÖrŒÔ¨ƒgxvµñŒè¼S§—è›÷ÿOþÄÿŽÀ!dY¦V¢ñ2™e³YìHº$žÇyä³?á¿úFŠÊ¤Y;ÁRCi´5ëãÕH³¥ŠÇÑxT¹½×ýöèJÛ o¸è´ÆmÔeþçúQxõW”-[7¶J<YWzÎ’^ˈN^¢ï$ÿ‚|ö»aŒ2ÎÐj4
*Ð ñ<Ì£ŸQø³ß}Ü$ç*ÓhÍbÎ,â¨ð¸‘úxÖºziµÆ{°*ëV>æ¯Ç©ÿÂUôÚw\9†QnŒU+WÑðUï´LÌ+Óc©bÌlä^ÕfͤÑV—zÔÀs¥h½üãùG><øìwÞ„‘ udY&ŸÏ'¼~&“Ù€½@çÄó(~FáÏ}çñRÄ5&òì"ììD3ùŸ²´Z^=­¶\Й¢ï¬ÉîqùÏ¿ö׳³Ï]‰n‚
ÿ7ºzÍ5–:…•é³Õ¢ëŒ4GÐ1‹œ+ßfe*lù¶j5²(oŒÁ,Ë1²¤Ü2N?zôÓêÃÏ& p€H$"ü%É¡C‡öcÐy ñ<ÈcŸþ~ø;ùÎŒSã"Ê›OXÓo™%ËÕ6–ju¯­]k¯Ñh¼«7_F—Ý(a ØñưU+W‘X^šxµÒhÉÁÇl^³ˆ9»î´vË‘%ÝöÇ~jÿ½OÍä0Ò´F8.WÉd°èxâô±S”ü“ïç7‰9nfÕD^5áfÓè¢Vô^Í´ZKJ.ñæ¢ñ.¸ü|úËèH+Ȫ•«èÖw²U+WUw5¢ðÊŽÆ-rÎô•K·juð¨J'ÚÚÏñòšy¦Ÿ‰8-übúœ½~2hH$ÒÒúº®c'Ða ñ<Âéc§(õ'ßã/ªÏT¤Â•Džùq-‘W)öª7º(m¯|½ZiµÅÏDGã­	¾Šnú«7CàµÈ%ý—ÒÈ;™¿ ò¬;´"
Y¢í,RÏš*Ë,r®l«Ôc6
.˜%ú®ì9‹À+„g•m“è‘çî¦}ŽBäÐÁ`PxÝÅÅEì@:$ž8}ìüà÷øñGŽ”¤G"Ï
W­é«YWÔÇ+¾géaþ¹M.¬]t×ϧ›þê-¨ƒç—ô¯§[oüóRkkvšµ¤ÏUJ;sméõZuðì£òêK=¢zÏx¿GŸ»›þ
"aB¡ð—&èP@çÄs9§¢‡ÿø»G¦¬ÆÆE3‰¼Ê=k¯¨gޏ+mÓ>­¶š4o«ø¸°5—ŸO¿5	ç4÷¯§‘F"ÏØÿ•Qx¥16GÏYó¡+^ÔJ™5×¼«ŒÊ³J=KT^UW™ºûèá»èßû?uú€&ÀNÀC@⹘3ÇNÑÃø.?aDàY"èZyÄ«4¯à&ÃË…[ùã:iµÆûSµFD—ŸOoÿ!ðÚÅÅýëé£7Œå›]ÔŒÂ+¯{WZÆ>Ö>âŽ*RmY•¨<[YXWàQÙ{ïñøswÑwüC~êô€&Âëjš¶{€Î‰çRN^#iµÁ¡Ëé×þüF¼.ã_y.ýù†Ï±Áu›¨²™EéÿZi´Ö.³õÒjEžd,k¶Á¬ò±´ÎËg–h.ù>ˆ<êÐJ]<@gÄs/þøIzâ–‚À3	0kZ"û.°v{ˆ¼âsÅ÷ª\¯V£‹b—[ªŸV{ã_ÜÀn„Àsï‰|ˆ
®Ûl#ÖxÕ(=²‰Ú³_¾²v^e³‹üñSMà5ÓØ¢¬>^!2ïåÓ/Ò’ïå:D€ » »,ÞõÈ;ù‰}wq"bĈ³¼ôâĉ1F¼ Å8ã…ç1FÄyþõb	;ƉsãµB7PΈLËr2‰·ÂºùíËU®GŒ•­Ãó4È
NŽsâ…í×'*|p¢ÁßÈ.
b°]H,òaƈóŸi?²M£µ‹°£Z,ò®ªÀ˿ּÀ£
G–m––§‚È‹ñ·Fâ,pîup,d2ìÐ54M£l6[w9¿ß¨Q—N§—íx5ò»H’„æA@×uZ\\¬»ÜÀÀì0Ž
®ï4$^7/nw=òÎ_íÜw—¹Ø¿!Ðò‚—:ðÒ2%YÇ.® ÚydzlºÊuŒÏXpyÜ,ù
J’É¿Ñçn~/ò¶jå¹ïÿÅÝW”5¶°þ̪ÿáà…ïþ"F:;‘;tèišFš¦íÍf³›Z‘Ç’$‘Ïç£P(Ä$I¢uëÖarÞ¦qK§Ó¤iÚ†C‡í3óx
$I®Ÿ°§Óiãwoùxõù|$I
Œ‰P(Á×$Ùl–4M£t:Mº®...Ž·2&Á`°lÝzë­Ì
“]×iaaEáݺñ®·¯"‘ÈØÐÐЄW#<›9oš•몪ÒÜÜï¦0±»¶D£Ñ‰vM2³Ù,)Šâêc6²h4ºl¢óÒé4ÍÍÍq7Öh•eÙ3×v^+4M£={ö¸nŒÂáð¾h4ºÙ-)ÑÙl–‰Ä¨ªªãn>V
wý>KUUZXXpÕqå•ûH¼N^\ÿ÷ùÑo?LfñFd…gyT&ûŠ¢­¸¼uf!çȳl«ry¢«Ï¡
×<òüº;u?yf© Â^iLàÙDÓ‰<»´ÕÒj«‹=Óÿ¬ôØxîÊ×|^ÙgÑ1rªŒå$ñEú˜ˆhË–-lhh¨©u&''–>ŸvîÜÉ–Ë$¶Ù¨HÑHÈå6Qñêd\ô¼!"ŠÅbu#Y5M£x<ZÇøÖ­[:U…æææ\)ïª]g{Yæ¹YÞyñúÑŽk…W®õí¸^4=Ï×4šžžöÌõEô^Ωs?‘H¸úo[Ž«jœ…é^gxæ/Ì_¼óá’t0ݪ3Ή8/ö¶`œ—aFo^ZǨgW\¾¸
Ó²Ååò¯•–-Èóz…eYÙz¼lÛÅÏkZƼüÊóΦx=Ã5k7ж7}ŽùûΫÒèÂ*ë¬uôxÜFàÙ?W«.žL¤¢‘
륟ù2ýì‰à[°lÑu}ƒèºÍN*UU¥f&¹\ŽTU]6c1777ÚÌò™L†ºuó;77G“““ÜK¯pŽONNòD"±¡‘ޏn‘ÍFÉ-,,ðzã755åúÉS&“¡©©)GÆËˆPJ$žš`ÏÏÏóÉÉI®(J¯ýí¡ééi>33ýÒ!ݸ~ÌÍÍ-›kE2™ô̵ÞÉë…(ñxÜS×ã“L&;ö~Ùl–âñøèÌÌŒëÿ™«x<>ê¶ûH¼ðÌ_þˆ¿øíƒåÒx™3Ë7"CÞ™[qÒëeâ¯ðz¹Èã"σԀÈ3oÏ,þȲüÙçM¿þw[X?^OñêÕ!úÃ7~žùûεitA±g¤±R™ˆ«'ðªu¯µm¦Á*›lTKŸ-Eó•GåYEßÓ/|ƒ~–þ0DX–¤Óéý¢ë6û­d:mö=EYçf¡ÑGÓ“¤NÞx›EÈüü¼ç&*–ãjÿää$ïôþ˜‹L:ªgÓÓÓ¼‘”í^/UUizzÚF;r¹%	>==íª´çÆ“víÚåyg'=Ü(Á¼Våë³îÞ½Ûs×zEQöOMMq‘ýÑ
ªª’W¯1ú›`ÜCxíÀÂøŽ»í¾¯Í<û—?âKw>\=g4ñ´Få£Þˆ,Qy¦¨:³|+._mÜòºù1/ÖkVäQŶóË÷_9@7~aë¿rƒÝƒ¼zõôoœb¾•çÖ”oÄʣߌHºÚx¬J_µÔ\c;vïYÜ&¥ä/Ÿÿý<ý!ˆ<°¬h´èr5š»æ/..6}ÓftŒìu¼q¨(Š'¢·š#»wïæ³³³{½•çÄäÉ«âįD"ÑTôp<J¶ê IDATõbtL5á²k×.îÕk¢!‘½
Yí|šžžæ½-nŒS­KnG×uš™™éhk2™Üëåã¹Ý_¨ªJSSSžþ"Âø;ä–¨]&¿ˆ,é¬ÔxT^CéµdoåRŽÈ9‘×ÅÝð÷oc+Ï;¾x•ïÕô¾7~]´:/òJá™õÙ
ºŽ[/ˆ‰NîõãµW#pj‰"¯ŠQ¥5Ø}6TFßQÅë…óˆ¬]j©¬s­5:ïØ‰‡èÞƒÿ¿64ÍúW½ƒzŠVk°‰H<"¢h4ÊDº éºNªª’,Ë=5­D²v}®ÙÙÙ¶¼`0HëÖ­Ûèóù˜'óÏš¦‘ieüœN§¹¦iÔΉA<ç’$±n‰'Ð4Z-L)
1I’Èï÷7tÞ
sŒÿÓét[ëk©ª:.IÒD4¥d2INã7ŽSI’2öE#ûߨš¦¦ÓéñvMòöìÙãºãUÓ´¶éºNj¹\ŽfggùöíÛY»Ëœ˜Äs€SŸ§ç?öC~êàÅh9nD¶±’È3‹:cV·3dg<ÿzÉß奛!ç¨$á˜qÆëy	gˆ<óö¬‚.ÿ?+yÅÏdy¯þí+éêOþ7†ÑC×|Š1ÆùÃÏ&*šXP¨ºÊfDöÏšjKÑwDT}g•reÿÛ¾NÛZÊ>Dßįýë_õ:8è	Z½±
‡ÃÂ)#ƒƒƒ4??/*¼¸,Ë=õ7H4Â0´MhÆãñÑvL $I¢p8Ì"‘HÃQKæåL“AfLÈ“É$¥R©¶Çééi¾cÇÏŠ<‘&ŸÏG‘Hd,Oˆ¦j›e_a̘¤§R©
û–'‰D‚K’Äœ’F²,…Ãá‰P($\wÒ8n
ûb‚ˆ&t]§t:MŽJ
£ÁÂÈȈ+®FI§·(‰l”eù€“×UU¢‰Çã<0Ñ/»:ÍwÜÁ[“h4ÊB¡PKѨv׌Âõ}4™LŽ;uÍh÷¹‹Å˜×ê?nÙ²…9]šC×uù¶Þß'I’Š_,
4tÌuê•Â{·mÛÖ±ˆLÆù²‰tn§>Oϼç_ù+K'‹JZ€J‰³ÌœDkșℬë™"ùŒ§9"éŠËدÏeX±ZYéý¯×µ®W¶\^ð]øŽ+éªOÿ°åÇ~Š?ò잊yµž]ý;ª*úœŒ¾«.íŠg(3?GÔ·¢Ÿn¸öûl5DžgH§Ó433#ôÇí¶ÛnëÙk]6›¥ÉÉÉ–n0c±kE ÅãñQÑ´;w²n¤á´ƒd2I»wï:F·lÙ†††ÿLíH“ey,N´S†¢Îì Ó߬[™››s|2d79ŠF£,R'~WUUinnÎUÝr;½t]§¹¹¹Q'SÛu]höoŒÓ©ø¸†¤ÓiRUÕ±ñ422ÒÑkG'®æ1‘ey¢¢2›ÍR*•rôšÑÎs%›ÍR"‘u{C¨@ @ÃÃìµu[¹Ï³;ÖZùb©Úõ·_¨mß¾½c¯N|žž}“¿rì$•Wº+I²’N(*ËUÈ:*eše^Q70Ó¶M‚Ð,çŒmfå"°ìgf/òÖ_EWBà:ìO߯<ôµ¯²+­}¤]µî³Ü"×xÓÑw²Î.
™êUZDÞàµ÷@äyH<{fgg÷¶Ò±ÑçóÑÎ;[š˜´26Ñhtãððð^‹ééiá›ÇvÈL]×i×®]ŽEȲ<6444ÑIéšÍfi~~~ƒ“)•Ý>æÚ=1F£·lÙr ¢RQš››ëjÔJ§åÝywÇw86‘ìö‰D±ó¯×'ÇC–å±X,6Ñ+×
¢|
óÖ­[»¡œÍfIQG~G'îeù¼ÈìBmϦ§ááaáq°¦;ý{ò“Ÿä^9ÿu]'EQ‹‡Ãû:‡tZAN|žž‹}“s#¯:›ÿ©T¿Ž3f›bk^®˜b[L¡5Õº£RJly­ï¸ã¾cÇŽ®\#ªI(I
wåØtr‹)/8þ–Íl½jFˆrÕEïºû­×}‰ùúVÓYõÄ[µçª	¼ZÑw¦õ*#ó*›cØ¥í–Ä{!bЦ.#N?ù'±g!ò€ËI§ÓäT§4Ñè¹j7àƒƒƒEÖ-tó온ª*üMm4u<:^Q”–¿9nµÙI;	…BŽˆ‘^ˆÚðù|®x–ãhs»e[žyÙêñªªêx'›†8щҭ×'dÑÜÜœ'¿xr£ð·ŽM,ké\é…/ÝD+÷fݪµXãž—n¹å–¦¯P(Ô±¨rH¼9þ¯Éé·þàdgæ™Wж£
IGfW±•¥ÔÖO±%û¨ïÜÜÜh/_CZ=.½gÔ%sóõÂ8WZù‚Q×uO)è6DSù¹ñ‰Dš¾wêØßH¼È¼{¾`ŽêqRæ•ÄÕ¨—Wžbk~­ZT^CéµDÔwÞ9´~â-7­yçÕ÷`´Sœ{-½íµÿÌÎî[m+êNŸeÕÓbKrª¦Þ–§ÎÖwÔ˜¼3¯ÿÈ“{ôÉâ›<àt]§ééiîD}"ÓM‰ã`@€‚Á èuÜ‹QQš¦	§šntzBÕj^4Ýèvg8¬ÅýåÙh¼h4ºÑö@["N
)á•ñ’eYøúHD¤ªjGîK
‚j\týááaæ…kH héúᵈ¯n7|iòÚÖê¹²€#är¹
‚cèÚk³Q§¯‘(ÁN§CâÕáÄ7“;:rÏÊ.ge^cõòZ‹Ê+EÞ•§×öw6]9ûÚÁÀ¹×ÑÛ"_g>Cä±W²«xžle 5Q÷®¦¼cË»âÏŒèÙ#ÿD>õÇy «d³Y𛛣]»v9Ò•³“Ñ·\.G©TÊscÔJa+‘‹í˜XƒAöTíÜH$B­4»ðj
%ŸÏG[¶lñÌX


9^W(zFJ¼ç=ï>V5M£N¤Ô¶…‡÷¹¥YB£×Ñ,^*!Ëò˜×:ê¶òEc:ÞOÀ:$´/Ý~¼
˜ªÉbŸÏG·ÜrKÇ¿€Ä«Á±]û¹~ë÷ÿ†L`ÍÍ*ÊêmYd^Qè9!ó,ò®\Ø™¥\sQy}«Ï¡Ðîaæ¿æ6hßÅïÜëè¦ë¿Ïλ®¹ôYª_ÏNÐÕê8Ûœ¼«ˆfyG¦ÏøÜÿD=õˆ<Ðqt]§D"±arr’ÏÏÏs';c¶Nþ#‘ˆðdÝku†²Ù,%“I¡ˆ•p8¼ÏiÑJm>ŸÏ×’`è¶ j¥îŽk(E£Q×§Å99)·;^½$‹Ì×ßVºö¶;¥6›Í
GáŠØoöÚ˜O´Ð”Éõe |>
Oxm\B¡p4^§„7¨ŽÛ§Øá÷ûiÇŽÌhzaü‹ÅblçÎ,‰tü3AâUáè­ßçÇvýÄÔ¥2?ñ7§»šeQ¹@³
¦ežM“kŠmµÆe{d•××:ǹç\L¿޳s¯k0úÎ&…–ñ|}=j¤k­òŽlÖ!“¼£²÷ÈBÓ4R…¦¦¦øää$We;ÚÚÇb±¶OþE£ñt]®¿Ò
R©”°4“eÙñÉ®hm>c̼Õd=®E×õZ
%¯
,Y–É©Úx^”˜­ÔWJ§Ó{ÛùÙZ‰JíÄß–vMäEÿf‰~‰ÓI¼|®
_×:„Ë.áµ{‰BÆâ?Y–©[ç$ž
GG¾Ï³ñ‡
ʻΚ;ÊVÊ<Ó„¿U™gÛü¢±Û²ˆ=kTõõŸC—ïÞÊ|×BàÎqv_?mÿ+˜"ò΢WÊÜYuWÔO%›×M祠¼3w©5Ë;ëµáð»é¾ƒoâ§ÏÅ€aAeü›››£D"±azzšñ©©)žH$x;eÂðð0ëDŠC+骪z¦Á…hä`  §¿áÕu]¸6_  ¡¡!OŸ_’$µáä¥Jí¨¥Ø)"‘ˆ#]þ¼(1Íç›h„Q:ÞÔÎÏ&•©Q+NF…s.—ëhÑfñªð7ßKˆŠÿL&ƒºx]¼Æ1ú°Ê9:ò=žýæCDÄŠÑk¼hÙòÓuC¢åƒÞxéYF¦ªx†Œ+(VŠ–ã…ãÄM[åF$+=fĉ3Óû"oȉ³ü68ÏK
^üü…7Ê/@¾kÖÐkþú­x +¬ìë§M×}‹ýûÁßá/O–œU¶?›Î;ñFU^/¼T:MË™—©\¾|jË–“ùj@ŒˆNœx€’þ&\ýcÖ·â|ºÇøØÇ>¶ì£)eYëÔͼßï'Y–ÇDÒ²TUžp»¤H§ÓÂé:í(øÜÊD²MNºÁÐÐЄh*`2™Ü?<<̲F’¤Í-¬K^O4É	!!«ëºãÇ©h*m è‰(¼VÇÄ¢„¿qŒ‰FïB$9rNÝÇ¥R©Qì½æYÖ/åhñæá§SÏ–	2““#[9W¶}t^Yª-/Oµ%‹hYæQu™ç»öºä_~¸–7„¾ÈB¯Ù^!äΪҴ¢š¼#V]ØÙ§Ù’m7ÛryW.ôËÏ]*‰;f/þ<õ=üØ&~"¸”h4º1‹uµ¶\+E©UUÝëÖ}ÛJñ÷vDFˆÊ§^¨-æääUÓ4×wšìaÒÊï IÒX¯§’$		ÙÅÅEÇSQÙу‘¼Bc¢iÚ†^ù]\z®à¦®KˆÞ#¨ª:î…ncÙJ¼’À{Îü¬¥£%	EçYV¬Z7Ï€YRm›–yU:Ùöÿîµ´îë7Cà÷ß­ÿ+v}ðK_´«{g[3Ï8o*¢èªDÛUé4k>ÿÌçjeÊlõ¨;û™å׌3gŽÒAˆ<à2|>ÝrË-lxxØ7𢓼T*µÉ7€ÉdR8uJ42±	¸Ð¤¾j‹Ù!­æöJ@ '¢ÐZÙ½rœŠFŒ¶#M0™L
}1á厴vˆ
æBWÑKâkݺu¢Q«¸)ìÒ9AD´gÏž½ØƒÍ±,%^^àý3?z–̲ͲT…Lk4:¯~ª-/˜³¾g‹2ˆ¨ÿw¯£ÿfx†‹×¾ïïþý—­M-ÈVÞñšòŽÙÊ;nûQýFDÝ•]l®yÀeò‚n½õV榉Õàà ðº®ÛÇ¢‚>Ÿ¯-©«­Ôcê…ÚbNO:Üœ~ÕŽŽ¤^û=zILˆ§íÍ™LFh,z嘴þíÄþk'½”v^øû)µŠCŽ%ÑŒŠT*µIQìÄ&Xvïtê9Z¼ùk–¼ÒäÛNè‰Gç5‘jKÎɼÕ7_GkoB«là9Ö­ýý?}]ðÿ|¹2­¶9ygßi–,b°z£ŠŠÈ½¢î˜­Ø7_Gˆ^9s”~l×Þý[mЭIq,c;vì`n›TµÒ1T´ãj»ÐuR©Ô&‘uÛ•v&Ú©2R/¦ÒµÖ4ÀÍõDk¹õš%:¶½D«z@T
ŠÖsý=«`Ô—›®@`_/	Òi»K$.cH$x+u„—ËJ╼êÒ®úk–”:Ûè<ÞD#Œëæ5!óÎûÝëhíç ð€‡oŠ.øý?}Õ_—Ï^Ñߤ¼3ƒUëÝ5֨®IEùº6×*e_>"ïñô»¾ÿ‘Y„ŽƒŽN·lÙÂFFF˜›Ȳ,”§ë:¹é毕ÈÀV"Û4ïé{
ÑÚinO©íz1‚Ë«rB4ú´š¬T96=ŸŽßJó7Ò«_8y…Vº¾ÅãqŽˆ¼ÆX6ïtêYZ¼ùŸ8_Ê’œsZè5W?Õ¶ì½êȼóÞ}]ð¹·AàÏsaà?“¯½‡­ìë¯"ïx¥¼«Ù¬¢z£ŠÚQwV'&îìÈ<õþMy àááa¶sçN644äúÜP($÷Ýá/âp½F^äýÐ$òª5«°—pµ¢îiRQ«Î¨¸³òäSïßôÜá¿Åd´|#F7nß¾³X,6áÕè‡p8,\ÿIQ”
Ýþü¢@ ­+"o9LÀ!ÜÍÀÀÀö‚;öƒH¨$IûzuLñêÎ{!Ð]¢Ñ¨#5ýË:qâ~ùe·#šTÅçóoPC¡3Šò÷ÚDÂï÷ÓàààFEQšŽúXXXØ?<<ܵóH×uáˆ~.Pt›Bºó8öCw÷C6›¥\.×ôz½Vs
¸ÿþt¶nÝÊâñ¸#
™L†fffx0¤¡¡!yž§g%^6~ÿèÒÈžñúÓëÎ
=nØ7¢bÛZV¦"ŒÈ<“‚`&yGéljvÝôñUx`9È‹sÖÓõ×̱ÝÂ_:ñ@}Yg:£Ü*îÊ–gDGg‰1â—­E¹ IDAT‡Èë&·Ývö¿ˆF£DŠçr9RU•ºÕ¼C4ÐçóQ8nÛçZ\\Z¯×›Z
ôÜï„IpÑf½x~õˆ\í@–eJ&“ûR©Ô&§¶iȼ@ @CCC,/kiÛ“é´yw÷¸}ê¬1™¯—&Ûjj­ýóeÅøk6è¬g<^Ñ6vÝôñU¿¹
—	°\è[q>½îêyvÞª×UÔ¾ã5kÝ‘MgÚZuîM•eÔ\ZmÙ:6+¾pd–žúÅû‘Z–=@€‚Á ÐºŠ¢tíZXXØ/²ÞàààÆvÞŒŠFâ-‡dD€ók¹‚È5Ð.b±Øævœÿº®S<ç“““<.×Nñ='ñ²ñû
Ï –˜«÷z§„žy;¹P’y+VŸCkþõ},Gò"ïGì¼U¯+“Þ•µîª7©¨VçNDÜ5‚YÚ±V6DÞ™3G1à`YF…¢À4M£nÜÔ©ª*”nVø]´ó³‰Fâ!J@ä®fnBôË&z¿ßOÛ¶mcNÔdz£y1>55Å'''ùÜÜœ+š›ulNÜK¿L¥À3O£
j¥ÏÖz½‘çͯ5³*õó/«ÇúÏ¡o½—­_ˆ+X¶ô­8ŸÞpÝÏØãOýþ…ÝÅSÉ>ÅÖz~U¿2Ô¢•4Y‘õŽ™¥ì‰ûùUWíc+VœAË’H$B@@è¦LQ”ÑX,6ÑÉÏ+­èIÒétOÀå$
hI’hÇŽlzzš‹~ÉÙèy8??ÏçççI’$’e™÷=;î•_ä¥ÏïãÇ?ÿoU^mD´Ù͸EÖãu–o\èq^zî¬Wù(ð­÷²•á‹pE€ˆ®¼ì«ŒñçÌÚœ]w­J;;Ndï§ÇÛ‘–5Ñh”%‰¦åX2™žèTªP+Ñ¢‡MÞàŽŠÞ€@.—ª÷9??!,c:%òÌ÷c‰D‚'	’$‰¢ÑhOÖÏë‰tÚ¥‘»øñÏï£ÊÔØFjâñž·{]ôùzËš'øùÔ¿³ú}øÖû ð°pÅe_e®Ùf›.[~.9Ÿ*[«¶]#Ûoä=‘‡ÔZ°\mP‘Ëå(•Juìs*Š"$ÉE"‘¶¾ÅÅE¡®–¨— ":tèÐ~쀆Èëtdœ¦iÇù'?ùI>;;»WUUÊf³=±O=/ñ–F¾Í³ñŸSó®Ú2<_k»­
½òçúÂÑÀxT#tÙWÙk.üHMyW‹¦w"d!òÀ2Æï÷“,Ëc"ëÎÍÍu$$›ÍR2™’dˆÂè&’$ÑÈÈëVÉT*µÉÜÃëiþž–xywŸé™V¢ðê½.¥×Œè«|®/|!
Üùû¬€š¬¿dŠ/»}Q}iÖL4\'¢íj­ËŠ’à~J&/çÙìýl°ìˆF£Bµít]ïH-¦T*%ÜÐB4Ò€7ÀNË¿ßO;vì`ÃÃÃmkxQ£!ÆÌÌŒ§bxVâ•Gà5ý&Ò¶ÖëNuµµ./ðþcý>œñ4ÀÚ5Û6‡
"ÏJÓi²MDÛ9)íjqæÌQzì±My`Ù!I’p@UUGÛýùD#þdYssºj·n° —A##°Ü‰F£të­·²nww6bx1:Ïs/åèèýKAàÙ.Aí‘võ^oT$ÖZ>ÿ8ŸBûx4Ék¶mn4"ÏÀ6M¶‘婽ÒΈ<°\J;UUu¼õOÒé´ð7¸¢†M-ÀyB¡vXöÚ±cÛ¾};sƒØ6¢ó¦§§¹ªª®ßž’x|)G‹7ÿÿüä’x‹F%[+¯7¥Wz®/üj<Zà‚5Û6_ºë¦Z]›‰¶ë¦´³ÛÎ+gŽÒãy`™!˲pdX;oÆD#ý‚Á $,3Âáð>ìJ„B!Ú¹s'‹Åb®y™L†ŒÚyn–yž‘xy÷~:¥QãBM¤.^;¤_c)¹þØë!ðp€Àùï¼çš«ö1Cä5m'*Þ9#íÙΙ‚È[<2»£
–¢M EiKƒ‹l6Kªª
5´,àé¿c›±¨D–å¢Ìëvš-Q>Õ6óééiîÆ4[OH¼’À{Æú
5/ÕD–qJêUλžú§¶Bàà«V]O×\½õõßT´]£tJØUãÌ™£ô‹_¼DX.
߈%“IÇ?è7´>Ÿ
-`™‘J@dY.¦Ùʲ<ÖíÏ“Édhff†ÇãñÑv–gi×K¼¼Àû²%¯Ö—ê{N
¿|^ÿÔV|+€Ã¬ò_OW›"òDÄY«ÒΩH=ëöž†ÈË„@ @¢7tªª:~ŽˆFø‰FvÑŽ»Ê‘$‰¶mÛ†¹

…(‹M|ö³ŸeÃÃìÛ%HTUŸœœäíøRXWK¼3¿Ôï›W99WOt™FÖ­-õòxïÄE€6±Ê=…¯½ë¿¾¹µä\-<§êáUÛDX.Ȳ,Ô"•Jmm@aG2™nh!QØi4MÃ-hË–-ldd„¹¹9nÅï÷S4¥‘‘622¢ÑèÆnÕÎËår´{÷nžH$6t{¿ô¹uÀN§4Z¼ù+œ/eëLo­ð–³.Ëël§Ö{ñºÏûco€À œ}öetÕUûØcmâ'lB8ç­lçé_¼S6û_wñ®) g	…B„ÚÂÂ


9ò9D#ûdYsCáfèÛ·o_¶÷$„ë=Î!I
fÉd’R©Ôh2™ït怢(û:DÛ¶mëšœw¥Ä˼/›^µë#"®™åª-Ëx­ÚúöëöOýΘ?ö†	œŽt†+Î/мV:»:q7Ú®;Úçÿ-9s”_ºþvˆ<г

±x<Þt*«ªª|hh¨åsC×uJ¥R›DÖ$/‚p€v‰D(‰LÄb±‰n=£VÞöíÛ»"ò\—N[)ðˆšKmfy'Òq›mŠÁ!ðè†Èóû¯ohy'Òb®…Wï=ô#³ôË_¼Ÿc´A¯‡Éçk¾	”®ëÂÍ(Ì,,,­0¡x¿ß¿Od=¤åÚM$¡X,61>>În¹å&Ëò˜È}¢Èõmff†w£á…«$^^àýçK'H\®µ£6^«/J¯AàÐ]V¬8Ÿ®½ö>¶fͶ²çÛQÏIaÇšxEˆ<ÐÛ“IÜ(²îÂÂBËç…ªªBÛp"
P”P($ôÞét€$IÚ,²ž›º9zCèíܹ“Åb1‡÷µóý‘×éßÓ5ïÔtAàU»Øw2¯=móïx¸€õëogkÖlëzãŠF¶-²ýÅ#³ôTæ]üÌ™£lÐsD£Ñ"ëe2j¥Á…ªªBëû|>
‡Ã8€6ã÷ûI–eÚ¶mÛf£Ãm»jTjšFnvá
‰—«£úïÎT‰À•u­Fï9·ë?‡ú§n†ÀÀe¬_;°Dä™iWt£öGî½xônJ?¶	"ô@€‚Á ÐºŠ¢ßh‰FòE"‘1/v&t²£/ÀÛb\C^½~E£QÚ¹s'Û¾};“eyÌé÷Pe2™ìØïÔu‰—/Œ.Ü1^INívõ–_†õŸCw~AààNÖ¯¿]xáGjuõÞ/—½Ÿ2y ‰F£B§ÓÂÂÂ~ÑÉh&“ú¬CCC]½­Å·¸¸ˆ
@’$áð<¡P¨˜në´ÌK$«×U‰—xñ‚Àã$&êÚ)øÄäë÷ÑÀÂú¯Á€‹Ywñ»týíB5:%ꉋÁ,DèA"‘‰¤Fär9¡¢|Á`Ú•ÂÑn4MÛ‹#
 Š®ë£Ø·—yº®“¢(ùü]“x¥¼F¨äëtÊ-'Öï§;?€GX³ms5‘׉¨:Öæ÷1DÞ©SOa°AÏ §(JÓi±¢|¢ŸÑID#ñt]ß„£ z
Ñ4m{àV™·}ûvGjæ)ŠÒ‘h¼®H¼_ù§+Sh[Ä#r>å–7¹|a2^xÎ<„!òÚ!êÚ-é!›½Ÿø
<›½ƒ
zY–E'–¤iZÃË«ªJ¹\Nèæ0‰xvÿ6³½ÏçÃ5Г„B!i9*/—ËQ*•jûçí¸Ä[ù?ö©»/i^е7åÖ™´Û¾ðk
)´xx‘5Û6_¼ë¦+Îoj=7HºF>Ó+gŽÒ“mâ9ˆ<к	Ýp)Š2ÚIJB
-dYfnÙW¢@Òé44€p]<\C^¹§ŒÅbÃÃÃ-Ý»‰Þ36CG%ÞÒÈ7x6¾PåUN‰Æk_T^^àý)çUç¿óžÐUû˜Uä¹EÒ±ÿUãÌ™£”È=B4j‘L&ÇIyh6jÏòÙ\³Ÿ„d'"iDDëÖ­Ûˆk`ÜWR+"OÓ´¶wæî˜Ä˼{I\ÎtRö5¾N^àmg¬ß#€À￞BWíc}+ÎkUÎ5Dè$IŠ2k4å¡™ˆ=3²,ùý~7í'!Ù™N§ÑÜ@’$Y/™Lrì=€—ˆF£‡÷‰®ßîäŽH¼’À«'çSÛklݾ°Dwî€À Çðû¯§ MD^³tRÎ5Dè…N¡¹¹¹š7Ùl–’ɤPavÑÁ6NÀEoDÑÜ |
Éd2Ô‰Bïà$±Xl³H-P""MÓ6´ó³µ]âeã÷Žfã?¥æ¤Z«µí:—‚@oã÷_OW^{óû¯¯xÍ­rÎŽjŸÍ¨‘‡®µÀËȲ,Tt]×õšß–¦R)¡†’$	OxÛ…hwÉ\.GÉdËI’HtBÛ‰BïàìÐOÑhTh*wèСýíülm•x§S‡hiäë‚­Å99'ëÚ#ý1€eÀÙg_FÁ«ö1¿ÿzWÈ9&ð¯gÎ¥§ÓïBºð4¢7ZªªVM—­©çôgi7¢Í-R©Ô(Ž0@(J/[XXÀ=Às
­×îZ m•xÇ>õmî\zl#8!þ[Ϥþ©÷Bà°LX±â|
^µùl"òZÁi!'J.{?~æÓ¸ÉËîFKUUÛétZ¨0±Ïç#Y–Ý:º„ˆ¦z‹P(´Yd½L&ÓöBïà4@@(³B$‹£Ú&ñ²ñŸŽž:ðDƒKóÿµBóïçÝ@ýSïe8¬X^ÔyŒÜ#äD9røïiµÀË7Z²,u`UUÕî9¡è3·Fá&àBëår9Û}Ô´»ø4½D$^wnn½Ï!ZF ´MâßuÏxçä\ç$ Ë›+Χ+¯½
¬ÙæZ'Ê™3Géùg>ƒh<àYdYj&¡(JÙqŸÍfIUU¡è3шÀN
…„oF{5.‘Hàš@ƒ
B몪:Žh<€×Íbh'm‘x'ð`ÿ™_.:°%îà¿Öß'/ðÞ uëog5Û\ùÙXÿ޽›Îœ9Š^½Ñš`êº^Ö¼A4ê,ïàvŠH$"­˜Édz.jMQ”¶×­ ×ˆD"E×E4Àkär¹
nûLí‘x?|ðÅÎÈ·fhísôO½o`Æ	‘ÇÚð¯Μ9JÇŽÞ½£¼ÊÐÐhƒ‹âqoÌk”h4ºÙíû'Oˆ®+ÚèÃhš†(<Ä®sD×UUu)ì´"Z;K»;͊Љ—»çA·ÆÛü¯>ýS¿?æÝ8C`eÝúÛÙ~´'jâ,½¸gFx•p8,”2šJ¥6y"7È@@¸æ\'‰D"Â)µ™L¦,bÑ«d³Yš…À@ÑBïñxœÛ54Æâ⢫>O2™¤x<>:==ͧ§§y"‘ØÐK²¾ÝM*Dp\âNýŠøÒ	j¿|s*j¯^ 6¯¾xŠ­}ͧzæ÷9vôn*ð,~¿Ÿ…Ò½Ê"òšA4°ˆî¢|
9¯OÀggg9"§•>º®ÓüüüìEÄpKzg6›¥ééi¾{÷n®ªêx&“¡L&CŠ¢ìŸ™™á³³³{½~¿Íf…Ên´»†ãïÔÇŸîÞnvV
žóö× .|ͧٹ«ßÒ;7Ùû1¨ÀËL¡t/UUy*•j:ÕçóQ8îùýÓðx<>šÉdp’в,·4IUe/v¼Fª0h†¡õÜÞ™Ífiff†×ú{šJ¥6ÍÌÌxú‹¿T*%´^+ÑÊÐçô_Y:q‰³µìœ¦ñ/ŽVæfÔÀ4ÌÚWŠ?öoM]Ýz‘yùäS¿åó_Fx‘@ @Á`š•5¢ÑY‘HdÌï÷÷üþ1OÀ%Ib²,{금Ç㣢]‡åD£Q6??Ï[8¹$I¬Ý“Ýv377Gªª–E÷J’DÑhÔs×HÐù¿Å"d2Êf³ÔÍûŽFCišF333|ûöíÌK÷IB׸uëÖmlççjC:í!—EcQxgo¸‚V\²W@Ü»ú-Ô·â|Ï×Ä#"Êeïÿ>Fx}‚Ù©÷ò\Ô~«é¿{öìá^êì
€ãר–SƦ§§¹W;DëºNSSS|~~¾"=_Ó4ŠÇã<£/¨‰¨ÄsŠf€išF“““ž;×Óé´ð—’$hçgs\âu¯ž³ÿúÂãªhߪë±p‘HDø[îfƒy§	…B…×Ïårž˜€g³Y<Ú€ßïoù˯\G¬¨ªJ»víªû¹UUO$¨ÿª"IÒ˜Èz¢bN iZÓÍŒsÝ+iô…{á}ÜîFggáÔ±‡õû±Ó‰h¼NFü9M«ÑxnŸ€ëºN333€¶]ÿZþ#—ËÑÔÔ”'&÷…ÎÖ{ãñ8oTb(вt@5$IŠäÏd2]«Á(Zã.—ËQ<÷DË™™áX@ í_î:.ñX¿z!ïtê—¸ªšæå“OõD:-½@»ëŠD"žÝ?¡PˆdYkenýv=™L6)Çï÷Óðð°#·3Fú©['÷Š¢Ðää¤Pó£……,À–Vî!âñxWšF´ZÛ.•JmšœœäÉdÒuãatÜmåÞ!‰ll÷çt\âåÓP½/ñNx¬
Nf³÷Ó˧žjjæÒ+Vœ=1ÁlURÕB–eÏ»øááá‰VëZß®'‰
Ýž€ëºN³³³{wïÞÍ›M÷ˆIˆp8¼Ï‰m©ª:>55ÅÝÔå5NÓÔÔO$Â×MÓöâHv´µ¥ë:%‰Ž×]”$É‘ÜÝ»wóééiלïFŽV;ØG£Ñíþ¬ŽK¼³úý=ÂÆ—NÐñ¯ìå
òÂ3Ÿé™k†Ï=AOF'Ú¸mÏï¿ßO[·nuä|We·Òâ²Ù,ÍÍÍÑ®]»„"eâÄb±Í­~``¤Áw{rŸN§izzšÏÌÌ´Ñ›ÍfqMUiåAUUÇ»‘žêÔ—˜™L¦x¾w+2O×uŠÇã£SSS-Ÿëª“ÜçôÏÞpÕ¥”g«‚wæ¸'¾òcò½ýõÔ¾W@M^<2»÷ØÑ»{æ÷9
:@ IƒAjõ›U›رVSJ\4 d2¹Ï	ùU¸æsss444ÄÚÒ¬ë:-,,¢(ˆ¼ Køý~ŠÅbl÷îÝŽMôŒÉ}0¤h4Ê:Qº ›ÍR*•"EQMÅ…BøbTeppæçç…×O¥R›¦¦¦øðð0ëT‰¡¡!J¥RäÔy’Éd(“ÉðB™’²,íÜÛ(étšTUu´ñU«µ†Åq‰×¾„X¿¿K©¨Î
B¾tœoþ<¸óÏD /™ÝûÌ/Þ¿©]WíNõáó_tZÐk7È,“É8z*ɲ<ÑKû(‹mv"âÄÀ,óœ¾!7&ÚÉdr/¢îp‘H„¶lÙÂæçç½Ö“{ŸÏGƒƒƒƒÁà'E…®ë”N§Ûz=ñríTÐ~ɲ<ÖŠLÒuvïÞÍE£Q&IRÛ;¤nß¾MNN:úš®ë¤(Ê~EQÈçóQ$“$i"
Q«÷ƹžN§GÓéô¸Ó
gÂáð¾vïsƒ¾vlÔ÷[¯§lü€ÇO§üߟ¼Èû¸ó/ ò¯ïÑé¯oÏ]ý,è)dY¦={öS7š¸9î4F$Íôôt[oÈC¡Ð>I’6‡B!h(íDÓ4Z\\$MÓ(Ns§£*Î044Dº®µ£#t.—+^KˆòikëÖ­Û(IÒ@ P÷z’ÍfIÓ´âÿš¦íÕ4mS»;Çʲ<Öîˆ"à}¢Ñè„çM¡N·»o‘$iL–å	§î_ü~?íØ±Ãñûó9_Ø'ãæßÃçóѺuë6ú|¾ºÂ)Ns"¢vß7ø|>ÚºuëæN/í‘xïþu–è@ðHgâSøÒ	Z¼ùs|õgbcþÿÛÞý·qæw‚ÿ5IKliD‹@Ä™ ÙC|›£
tÕÐGŒu¸ž'ÁÕÉ3eÁ­’":“AI—©¡é]'’V²­gëâŠ9Ìî–½˜É˜\úªŒ‘Íøv"רuõn8Eæ…û¨Œ$ˆÎˆ)S–Z’Eõ½Z
 ÿ¡Ñ¾Ÿ*—K
  /Më!â÷ûk²¸\.:zô(3::Z–¬;wîÐÂÂB`aaA”’.ÌsYÖíý…Ãá"¢r·«l½ì~NÝ¿?îAÕ±RοGÙàzxvvvØï÷ïÝ¿ÿ³>w9ƒ<¥ï‘mÿ¶jûáp˜±b.uôèQx ‰4­…ï5;;;læêÏ,ËÒ‘#G˜zkóÝÝݧÌêÕ¨EÙB<6üìȦgŸ"ë‚7¹ò½/‚<€ú•à™ÁN!à–m½´óáAm_lîuå÷û/ÔIYÑÑ£Gk2ÈCk„Ãá‘}ûöÕMXÞÜÜLáp˜A_ÐkÏž=ä÷û-ù±pzzúœ™ûˆ#û÷ï¯és®“NUª­7”sçÛN÷3L˯¶²çöϰ6ôÃkC!âTP?ÌðÌ`VØØ¸¾úÄ»è•5­££ƒŒÌYÒÙÙÉY9çI¥¹\.z饗jjˆzÈX«¯¯Ž9Ró7õíííôÒK/1µ<ÝXcÿþý¬èÑV®Õ˜ý~?½ôÒKL{{{ÍÖ‘ßïß[ɰ¾¬!^Sç.Úv:|ªr!\.ó?ƒûˆäÔ¾ë7(ÍĵÌxÕ‹UKúümîQî±MO¢²¡n(u7Y¿ßÿ\½•Wkk+


1ÕÞ›=d*§££ƒNœ8ÁtvvrµöÝš››iÿþýÌÑ£G™zú‘ʫڇ£·¶¶ÒÑ£G™Z›šCº–¨ÄÚ\Må~6¼wäþ?\¾ý£MÞ³=²3!ö‘Ø2ú]ô`¨AÖoÐÕâ]ábÑçi9Ø-ùÜ9@;j&œp8º/8ŠuûýûúúhÏž=L,¥Õ᪅´XGµõ(ÔÓ[°Öz;¡j§X–¥ç)‹‰«««U_/~¿ï¾}û.Tºg/ÚÉÆï¥u•T»ö̇Ã#­­­#~ø¡X®²*·îînêììd¦§§izzÚ’lË¥½½úûûmÖ7Yñ&ÛN÷3âÚm1xUÉm­zR·íô¿60|ìFm€§•¿Çô•FÛÚÚJ.—‹´
{öìÙ‹£¾öMOOëjV~¿¿î¬s¹\444ÄÌÎÎÒÙ³gmÞÜÜL}}}Œßï¯ÊòÖwttÔTO'”A핃Ô+¯ZÎ#‚‰S}}}#vùñídã÷Ò:LÔÎ?ÐõõõQGGSŽàÛªc€eYêëë#¿ß_•a^kk+íß¿Ÿ±zÚbš¬z£–ÑßgˆÄA^õbÿ>Ÿ¿":⌠ uøðaÛŸWÐNêèèP½ºkss3õ÷÷Wŵ°€8q‚Ù·oŸáyæ*y°,K~¿ŸNœ8Á9rÄví¾³³““Ú¼]ÀeDÑúa¬B죓kC1lŸb0·š:wzäT§»ÂEJ¬ß¨’3ŽŽݶi‡{´.†ž={¶è¯–Òµvê"eºözýõ×u
á8qâB^•e¼°°@óóóçV—inn¦={öœêììÑÛŽ_~ùeͧåööv:zô¨%çÑ¥¥%*5á¾}û˜¾¾¾š=¶PõU‹‹‹´°°ðìâââGV÷ÐËÎj蜂ãÃþ×Õ:Wj®ùùyZXX89???¬åï­]ùùyºté’åí^ºŽèèèéì쬊+âYäYÿ›:wÓã?ü.ÓÔ¹WõUâ®p‘®)x•8K–ë=¿òÄ»\K
-b¡Æêê*ÍÏÏÓüüü£beY–Û³gÏsÕòÇŒ›¥X,fë°¦‡ÅÅEZZZ:¹´´4lÆEyss3¹\.êèè`:::L™ËÈî!^î1^9Ï^jîsßÔûEŸž/;‘9
ÐDRÏ¢‡sWÊ\ ‹§­Æ•1àáÍy­Îëʤ6_ïm¿¡Ò`Ó³ÿ‚ñ?b˜–
-Qy¢îÏ&y÷® ÕØpó<-}Åõ¦ß9Vzñé½àA½›Õµ Eww7zZÕ85½wì¢ÁÂ>AèëŠî5ä	±ÿv‡€}ÜÌŒŸ[â7öÀ³*t³"àkhÜN_F€unuu•fgguMÝá÷ûQ€`
vù Öy"•+¬+ö~âÚ-ZúѰ›F`73ãç®_~! öùVö¨3#àkhÜNî§8Ô»¿û»¿ÓõºîîîSXô¤öéN˲,‡Ò«5ØéÃHAž9óÇYÔ{ÏÖ†~Œ  ÂnfÆÏ-_~!`FgõPY5ážàmfŸFeC]¦§§uýñïîîA	Ö>½Ãi].~ Ë5Øíiò¬îUWê½ÕAP9R€'ßnfW‰yð¤÷hD€ðÈÂÂݹsGóë\.&L¯KKKçP
P-ìø¡˜–-² ¯RAycÖ†~<¼6ôc‡ €uV?yM\68„ÖйÊ?ÞNxœ={V×ßY¿ß-êÄÒÒR@Ïëò@%4Øõƒ}äí²øË~±_!öZú‚<,_~A¼ñÉiÃáY9B83öùئ'àä˜Õ5ßYss3uww£ëÀêꪑ9ñP€`¹;¸‡AÞ1fÓ³ÿ¢{·ªw_ñý±iye¶|ùñ³Ìxþ9†Ê3|Ö”ó©÷6³OÓ®ßü{x9ôöÂ{æ™gö¢ôêÃââ¢î׺\. X®ÁîiÙB­SÇ6ü¿Ø‹µ+Ñj})È×nãˆ0Ù?ðÏ7dN WÎ!³òý6³OÓΧ8¦¡q;* Ko/<""¿ß%Xæççu͇‡*¥¡Z>hËè¨ò¬œ;Ϭ÷y8´v%ô:‚<Iž‘@­œ‹]µ™}š\ðòèí…×ÝÝ}ªµµXA ……½óá¡·&TDC5}Øü ÏêÅ.Ì|¯üýÜ_¸Œ ÀÖoÐ?ñ‚=ðìê)íKËþà(3Ò¯»»{%X¦§§u¿¶½½½5 "ªíäY1\¹B»ÂûB`̃õôëâÝ›çU‡bv	õ”ö§´Ov[/<‚ ÐOúS]°ÛÛÛ±âh™Õ}a‡ã*¥¡?tËè0-£pÊܽšÝ«Oÿ¾yÿ§xá2ŽP
¤ïžpñÑ6=›‘P®Ü«×¶8ÈåA€ dzzšîܹ£ëµ}}}J°~޽½5].V¦€ŠiªÖΆý#DDkC?Ö·‡r­DkÎë¥ ÏÿwLSç8RJP
ðä­•1¡•3&)¶9hÇï"hP°´´D~ø!záé$ÍÎÎÒüüü£2dY–Û³gÏsÝÝÝ5õ=õΙHDÔÝÝs0TLS5xmAžC»âû×n#ÈPáÁú
ºþq@ü\¸ø(0+Õ:-¹R¡<€âb±˜î?ÊõÞoqq‘ÆÇÇE…^Œ……qzzš˜ZXô#‹ÓÛ[“ˆhÏž=hlP1
ÕþذDyhm9¼0cŸÚö!yZ ìžp‘–æ¿–×OËpÖJωWjðŠ;{ö,---ézm½÷Â[ZZ¢wÞyG,l---Ñ[o½%ê-c»˜Õ½"-Qgg'‡Õ‹ ’jáK°aÿˆóÃa†iaÉüUjÍõîãákĵ[´…Ø/NâøÂçÂEZþ8 >X¿QôyZC6³æÄÓ+w·½ˆ ˆùùyÝÃh‰Ðo||\UÙݹs‡Þ~ûíª
ò–––t/z"ñûýÏ¡Å@%5ÔÊiêÜMŽø	†iÙbpOfõà3ÜÉ_'®Ý¦µ¡ÿ4Œ à¡Ï…‹t=àéíuGex~¡×êyýŽ'ÞåœîQx,--FÛÙÙÉÕs/¼ÙÙYM}1*ÞýÙ/Mºý¶ò¶_Ýs›:Ÿ GüôlÅ‘
5áæ'¯‰7?9­º%˜Ô•»e74n§/#Àxdii‰iqqñÜââbÀÌ`¦¹¹™Nœ8^U2‚ Ð;ï¼cZPªÄårQGGÇ^—Ëu¡µµ•ôO]]]¥••éø/]ºTÖr	‡Ã³»©›O²6…Ø/LØ“ýu´÷/jê|AÔ„—_ogÆuµŒr„tf·xxPo¤žu+++DD´´´tNZuuu•Ê9ŸzU•®›ryJu’[‡ãTkkëÈ;wž½víÚGÒörJöïßÏøý~`;uâ	òÌœ«|ñ‚<¨v7.¿ 
™qSÂ:±B-´ØëàA½™žž¦³gÏŠfyT½ªJ«DgGÝÝݧÂáðŽ°£ºñˆ´yvéu§öy"5u>Iÿð(ÓÔù$Žr¨*R€§å¨¯ÔœxzÎ›Ø§©í)Žih܎ʆºðÁ<;==ýQ¥ÞžzõäaѰ»º
ñˆˆ>û³¿oýÙ_™x{®çuæ†w*·e+9⯠ȃªñi‘!´jZÝW«E€õfqq‘ÞyçŠ]h ÀÓNúàƒNÎÎÎ×Ó÷ƱÕ ®C<""!ö‹“kCÑa}·íå¼Ý×òÜÂÏAÕàÁú
ºqé;â½›çUùv_àBéùð •kåÓRš››éùçŸG(cÀôô4}ðÁ5‘ˆù šÔ}ˆG$yÿIÇ/Îö
ïrŸó0È{AØ’¸~ƒV>ˆŸ5áÕæ!ÀƒzõòË/[~‘PÆòªiUZõ·Œþ!zäAE‰ë7hµÀZ5Gt5¬V‹€èõ×_WWWËúÝÝݧúúúFZ[[QàX]]¥jóÞ@­@ˆ§àa7,*÷È3ãVßìA{ܱíôÀÕ-ßûßv£¶Áòö%\¤Õ¢¸~£ä,–±e”£%J¶ À ¢‡Ã0?üðò\htvvr~¿ÿ¹ŽŽt‚@ÓÓÓ4;;[ö V/—ËE~¿ŸéììDx5!^êƒ<»†w¥‰
¨eô4€uíJ!ÀSw´–·¥˜Ù2·:¨=z^ýuÓæRknn¦gžyf¯ßï¿€žwö±´´D³³³ÏÎÏÏTé@ÏårQGGލIñŠ(äUox—AXÖž„‹t#à•#°³C˜‡ ßÒÒëî­%…2Ðë®:ê{qq‘Ï-..ʽ†Ëå"—Ëuª££c¤££ƒÜ@-CˆWêF}í6­„†Åû—©¼säY17žòcl¸—ZF¿àÊ&7ÀSs´VãJµ­O¼Ëmu<‡Úȧfèekk+µ¶¶’Ãá8ÕÚÚ:ÒÑÑA.—à «Üêê*­¬¬Ðââ"ݹsçÙk×®}DDtéÒ%ÕûŽ
–e9—ËõœÃá ÖÖVB¨õ!žšôµÛ´ú“l§å¶ÞÊçë¿´ù·ÿgzü‡ßg˜–­¨p0Õç7ÏÓڥÐ?rõ·*3[hëïr[à@5 JcZ¶#þ
ÓÔù„Ê[~³‡ÎŠ/ýº»?ûï´zU×n¡ÂÁ4w2ãç>åöÀcˆH©»g¡íTd»šÇJu-Uó5ÏC€V@O<
Š÷ÈÓ:øÎŒç™ÝOI¤¦Î¯‘#þ'葆ÝÍŒŸ»yù…€¶#Ðü£]m‹ÓÓ*à€Uâé°6ôŽ(Äþ_·þZž+–ññÒñ	‚<0ênfüÜgÙOÔ}$ZÛ2´¶ÒíðÀBñtZz;'È3+(çÊ´Ú¢‘Æ]m´ý'Ì4u~
•
šäxæ•Æ3ã9
ÛÉùÇ<Æ>ÊË Ä3 tg‡ðNÏc·1-[ÉFª	Ÿ¼&
Ÿœ6­÷]¥{åÉŸ‡*!žAÊAžÙClË;|¶Øvy Ö­Ë/ˆw3ã&yæÀ#"Zúóa!öó“¨mäxDÊ=ÚŠõ¼ÓÓ[Ïh¯<-=÷cŸ¦{þ@étš¤y"¢d29Ž_æçBœk±\3™Ì£ˆ(‘Hˆ™Lu‚cÀRM(ó°áÞ"¢üyví}Wì1å>UkC>üð»~=ò꘸~ƒn]úŽøùÍóy1
GSä¨b4nWóX©£žQñøcìÓÔúÇ44nG…W±d2I‚ ;·³,9Nòx<(P¥²5ZÞ8‚ËueeEq›ÓéD€e♌
÷Ž4<¾õÏ?}ñíOŵÏT¾ªœƒÍð$kC>,®ÝŠlùÞþݨñú#®ß Ï>ˆëÂEÍœží¤ã±bûTózxµ!w¸‡Y<ϲ×ëmëêê"–eQÈ`§-ƒÍ¿ýÌš#þ
ôl-ñLµ‹[è}\ë¢ŶotóÕïZÄŠu&7À“˜µ€E9¶Ð:|–^­÷0Ïó;âñ¸øÆoˆÉd
–AˆW&MO’#þj‘ ÏŒá³å›ÿ®øö‡Û„ØÏ	A^ý×oЭ⃜Obç OíãB[[Ê=´CŠÇãb<?Œa$`7™L†8Ž#Žã¨ÞæmC½@-ÃpÚrn6È[	ŵ[Ù­f-n¡çqó¼G7²±Ÿ‘(¶Œ¾È Æk—àI=ð
Í{gÅZ½sá•zœuPËïâ8M²:G"ÃkÀxž§h4š»E"s»¢^ ú!Ä+wgƒ¼O_üâý…_©x…æ¿+´]y›û9=øô–øø_T1„ªÍºp‘n}Åõ¶—3È+õ"csáÉG€W<Ïr$iÓòA(NÏó»R©Ô¥_ÍÓé4%‰Ã¡Ph¥•Æóü.¥mç*JõÕ
Ãi-ð0È{iê|²È³Ôµ_€'¹û³$­„Näô8„Z°.\¤ÛD’xÅTÃ\x¹#ÀƒbX–%ÇCÁ`ðê±cǘ`0¨x¬$“Éqžç«ê»	‚@ÇQ*•BET1´eËd2oªÙ¨œªB<‹0-[‹y•ZÜBívuÓÞÝ_X¤•Ðqy5B
ð¤xJÉEµÏ…‡´
‰DŽã®WÓ…îo¼!&	qrrRä8•P¥7­hË çv»ûÕlÔÎ…Õ!ž…òƒ¼J®N«v»¶}Ü_¸„ ¯<xŽa¥ãºÐñnÒv5éym3<Ð)Û3/ïØáy~G:®ŠïL&7,þÁq)¨BhË $P ØÍ²,±,K@`w @Á ^p.¨˜ÏbRwã÷ÿT¼wa¡È3í27žÚç~±íþÂ%Êìû¸ý'ÿŽiêlG¥W™õ›çI¸ôÍCh­XԢؑªeÑ‹–'ÞåšÏ¡¶ÁÈ…x*•"yh—J¥v¹ÝÛ+ìÔ´eƒÁ«…¦€ÔÎ…Õ=ñ*€iÙJ­S§6\è——ê[ÜBnýê?ÑJè˜xá*¼Š|ž?w›¯Þ!´j†×"À³ôôô(õÆ»‚’€r@ˆWA-£¨äU€'m×n!È«"ŸgÆÏݹü‚ª>ývò
=¾
˜¨««+o[µ§€êƒ¯Â¾òŒÎg¯ïÑ¿ÖnÑJèäÙÜç™ñsw/¿¨DÏ;«µ@€fcY–œNgÞöL&ƒÂÓ!ijåy¹J|åðŒI\»E™}ß…؇'QÛö#xÅžSíA<(‡Ã±,ß¶²²‚‚Ó!ij‰–Ñï3-£ß?•ÿH¥W§-´]$­ŸumhtAž½Üûä5QàU*°+ÇðY¦q;µþæß3ð ÚauZaÃ"¢µ¡ÿ0üpKµxùÛÖ†Þ~ø]÷ Æ+ëîåÄû™qÅÇ2¿O¦šý—ZaVÔ°O¦q;=þÇ4±O£²¡âA t:Mn·›X–-Ë{d2Ün·-¿?Ïó”Édˆçùë¹y<ž6""·ÛMÇ’zH§Ó$®t:ýKé1§Óù²Ãá˜p:´sçNÅ¡ÒzðžJ¥(™L^/ö¹£Ñèuù6ÇÓfäB0“ÉÐùóç'“Éñ"ဘPWW×@ooï„Y!šôýçææÞO¥Rá"Ÿcœˆ}N·ÛM===LWW—îïÇ}wŸÏ7
…&ìV6F$“Iš™™‹,èÎ-s§ÓI===ŒÚcÊmÇnõie[N§Ó433sxnnn\º1,UÇR»ñù|šŽ£x<.J¯D"ŒÑ›ÏT*ESSS¢ ät:é{ßûSÉvS‰ö^ìxÕZÌÍÍ•j늟ßëõN”3¤©Æó¨õ‚:±þº†çyJ&“¥®#6|/ŸÏ·»§§çªÞcã8J$"Q0d€bY+£9Ž£ãÇ3òj#Š"JÁ†„ع“_ôÈS¸™ÔiÝ®oþ—Ô2úoÔ¶µ”<±BG“Þ×{œiÜN-ðêÏóFEÙ…Ûr$i3í<-ôÊ+¯äŠo¾ù&#¿ˆäyþÑÅe© @Ïó™3g6|ŽH$ÂHéJe¡E Ø¯ª-g齓É$%	±ÈÍÉ÷
W\€¦ÓiJ$Ê_+§ÓIÁ`ñz½šß{lllCÙ2n·Ûecô˜‹ÇãºË•eY
y7$J7`•l;v«Ïr¶eù¹-‘H½	/ÅívS(Rº¾òÊ+ÊÎh=g2Û°O#!–Þ¿9•<;^µH¥R”H$D#6y½ÞØúõœ¯ìV®Å>Uõ‚:±î\håß;5ŸŽ;öèLjÜ 
Q
þ 6`N<›bÃÏ´Ný	ôl5!Ö°gÏ<á/?¤µ¡?CŠl¡{zàÙq¾;­«Ï!ÀkIÃêä7®*.ÀÃf®`{þüùÃJ7á¹7
FäS+‘HìŠÇãº/䉈8Ž»"õÂÒ#™LR4xÒ…ôää¤ÇkyÒçΆ#/£å166f¨\³å ¹L­n;v«O+Ú²2	ð¤ýD£Q1•Jin+©T*Ìqœî÷ŽÇã×åû¼}ûöïTâïD¥Ú{¡ãUëgŸœœ¶¹T*~ã7D£Ç¯ÝþÆè=÷©Ô‰µ×5©Tªbï”I[YY!AhllL,੽&…ê„á´6¶éÙ=äˆÿ	³zE×>+ñìr¯B[ž¡µÂ_~HD$¢G^y‰ë7èÞ¥ïˆë7Ï—ý½¬Z+¼‰}šZžâ¦q;*,‘;Œ#ç‚i@¾Íãñ´å±.Íøu4;¤fÃͶ47•ÄëõÇq¤÷ÂZšãE-žçó~–†Ë8Ž	ùEevÅ!*ét𦦦Þ×Ú+'wx^¡[·Û=àp8&rÊrW:þe¡‹u)Ô0Ò›Çec”R@";^–eŸsG¡ç—*ÓJ·fÙÈ%MIDAT»Õg¹Ûrîðe%Ùù"cn·»?ç¦òp:Wº©¦¦¦D‡ÃQ´§Q Ø-/ÇD"!z<Í=Ç8Ž#¥6ìóù,m'ÕÞÞs‡|jçn·ûë,Ë^ÍùŒï_»vM1h¢Ñ¨hÆøZ8¢Nì}.T{áñxv«-o3®!ˆˆ¦¦¦ÞWbƒA¦ÚæõâÙ½‚:¿–
òN‰âÚ-aœžNn¢IûQ‘ôHDþòCz°ö™øøè¿a˜–/¡ÒM&®ß »ÄÂE]™Þ€4¾ÆH׈¬¿9S¼Qôx<
7”H$ä7šb 0üãÅÜÜ\ÞElWW×@îP§ÓIƒƒƒLnžç󆆃A¦ÀEªÖ›è+¹ñÁ`°èüXÙý÷g2™þD"‘wQŸJ¥ÂÉd²_í[étºà…·Ïç+6ïÎU"j’É$q—f$“Éq‡Ã1¡7DªtÙ•J¥{¯×ý…n3™¥R)š™™ÉëA’L&ÇÍÑTé¶c·ú,g[
õ¢ñù|===êw‚ˆ&
̓%½÷Þ{â±cǘ"7›W¥…3r½÷Þ{âàà ê9xž4”nf«µ½'“IR
‹¤aEæë'¢~žç‰ã¸¼ãR

ÍOXíçQÔ‰½Ï…Òu„Ò¹D*o¯×[h¡‰~"ê/4•‡ÑkˆT*uX^VÒÜ{n·ûª™‹rB<0%ÈVòôxF‡Ëjy®ºmwvV®þZtLý)‚¼2xzY± …Þý!À«¥Óišœœ•.*•æMË^`
ä^€KA‘Ñ›†™™™¼ÏÑÛÛ;¡ôÙdy=œÌž7ÅívÓÁƒUß8N:tèP<ÿ¯ò›•óçÏ‹>Ÿ¯dp#Jû>xð ªÞÙ‹tòù|L4Ín¤·‡P¥ËÆ<Ïç

…B%1Ž?ŸÏÇp—×c£Ð
¢vh;v«Ïrµåd2™¢±,KP5¤Óé¤P(4áõz'&''7„™L†8Ž+ú¹<ÈÈç±Ëd2”H$«é¹"‚âyÙãñ,WzN¨jjïÒÐ?¥ï vÁÇC§Mi~´lX|ÝŒùi«õ<Š:±÷¹0ûw>¯Ç¹–y>³uÓ–»0…„ã8Ñëõê
MåeTéùq¡r0'^•hêü9?|‹iêüZ‰pMïcZúT‰ž'*Lföðy÷ÿa‘V~÷TU¥¿~ƒîðôÎC§å5zæÁ+µ?ùcðÀjÒdÊJ½Uz{{Ú===y7¡©T꺑ϒŽ’wÃj‡_aY–Õt!/…&äC23™Œª9pæææHÞÓKú,ZC·b«¡&‰ëÕV6&ÿãò-aZ¶‡ÆÕP(Ään+¶»·j®O5Ç¿Ö]<8p ï\¨šÊoÈ•^—L&Ç“ÉdÉ÷ššz_~^fY–:ÔVçB½’É$)…zVöù|ŠuÊóü¥9eÑîP'v¨“d2™×ã\*o­×@ ¯7  ¤f®PeƃAxu
!^iÜÕFŽø0ÓÔùd±èFÇcåê™§Ýý…EZùÝ—äT,À+ÅŠ€ÏiŸðÀJ©TŠ&''ß/ày<žåbADvøÆ²ü¢ÙÈäÔ333‡.ÐÛìP^@ÀÐÐ¥ï¡æãüùóyŒ:¤»×œdÈ/’Ô]¥ÊÆòïìõzߎ;ÆD"æøñãEoDíÞvª¹>åu"}b¶^¯—|>߀Ör¯×K@`·|{©•89Ž#¥¹µ:ÄTú·šŽAˆã8Q)˜Ñ[Ž^¯WqHc2™|¿^ÊuR]u¢t
…t—w Èâ*¯S­J
W†Ú‡á´U†iÙJŽø³:)Þ_øGytS,Ö1i»Úçjë…—»ýþÂ"Ý|í±å­‹Å.tú<=¤{¼¢ÇY³hE©Ï¶Ù9@[Ü£ð@“t:½#jêÁ#ÂŽR7žn·[Uo¯×›7ÔcfffW0¼ªçÂ^>)¡á¼•`ôâÒëõ˲zð<=,çT*•2y<že£saIsàȇÄè­»J”9NÕs÷عíÔJ}²,KÇŽcxž'·ÛMFÃ/¯×;!ú%í»ÄÍiÞüxÒ0ùÁÁAFá¼n«yðªùøPš'Òh0#•|‚T*¡_ïqV/çQÔ‰µu’N§ó®#|>߀х?z{{™Ü¹z¥ÞxzþîØaЍ<ôÄ«BR÷ÅÐZ"k<Ñ‚o'­Z{–nÿø¯xÔ¶vë7þúwÖ3ãêŽ%ÛõìKïk
=¶É9@[Ÿxh&‚4dDõj<µ¿ˆ+Mäs^z<že³†#»Ýî¼^³z¿G=µ;ÔIÚêò¾"?™1ϰÓéÌë…Ìóüu=û±Ëˆ¨,„xUŒiÙJÛrœaÃß,ðŒJ,p!ªKcJí!×>£[oýg5­ÞýON‹âú
mÇi¯2«zÝå>†ìÂçó
êšPXéâ«Ô„ï
™ŠÃ=ì2¹±Yk8M¿~+¥•û†|ee¥*ÊÆ,^¯7ï}ãñ¸Èqœïm»¶SíõióólÞ¼zDDSSS¢àʇëÙc¼j<>AP:‡š†îܹSé=w¡Ý¡NìT'òÐÐëõî6k߇#&»~ÐÜËPþCÔ/̉WZFÀ‘(Ä~ž³µRóã©}}ñ^xÒs„ÿç,m}é÷¨ÑýeTt©R^¿Aë×Xðq3çÀÓû½mvÐx`˲y=CT^œ¾ìp8&²ì¾©óz½±ÜIØ¥•2Õι’J¥«	W*YÎVSšüÚ¬ž9ûS¼à×rLTû*r‡<ϲ|å¾D"!ÎÌÌPoooÙ&Û¶cÛÁª€å'Òéô¸|~¼h4ª¸Ð…]æÁ«ÆãC©Ç“ÑyÀäíWá=IDmhw¨»–7˲WÍÚ¿ÛíîÏýû¥g8-~ð	B¼±1È«Ôüx&õ“¹õÖ[ÞzN	ë™qÝi«]Â:¥ÇX÷(mn{õf\@-G"‘гòù|ýò•gff»Ýî’gÙ(ãò‹z;ݸÖê
´Ãá@¡Ñ¡C‡Ú¢Ñ¨(¿áÉd2ÇÅD"A>Ÿo·×ë½jæ
'ÚNeonAÐ<´MOOy…BŒ|Up¥ÏÉÞíÔ‰ÉçJ•þFØì:D„¯¦´Œþ€aZ¶ˆ·ôAgTb½ðdÛïüÍjAõ–ô 3ñ¨øô®úªõ5zö§åý¶<ñ.·É9ðjj‰Çã!§Ó¹áWع¹¹ñ`08Qê]i0»,hQéAάá=Åö—N§ß'¢þz*k–e)‰0JAžt#ÄqÜŽã¤Þs»{zz®šQh;ÖI¥R477÷>Ïóa¥›[+oZƒÁ £´€Eî1i—yðjéŠÀuRïåF1­ØæÄ«1ÛNÿÓ2:x*ÿ‘rŸƒÌî…÷Å6qí3ºû7mFí)Á{¿¢ÂECû0ûNÆèœzð –õööæMÒ?77Wòuò9À²+Ì¡@+D„ºŸ'çP©ÅJìÞ¯6L£w˜«UóÜ{ŒE€õpŽfYêêêÈ£+NÏóoHçææÞ—oëé鹊҄Jr:
…&‚ÁàÄÜÜÍÌÌˆÅæN“æÎ›™™¡ƒ2Z{# í”G2™¤BCV¥EÜn÷×µLô>33cJ (%	±Ðñ”H$‡B!LøUÁëõÆ‚Á ÎY B¼Z¾IÌy7_ýѰ¸vKö¨YÃkMš¯†èÁÚg¨Ðb%+ToÈ)yLãvÚÒþ_˜¦m½¨P¨½½½ò‰öS©Ôa¥'™L†äú{½Þ†cTøï,ËžC)<*iØ#“=^)•JôÒé4‰‘H„Ñ:ÏÚŽ¹¤`U¾ÝétZq˜çùåL&³Ãè盚šz¿X˜L&Ç=Ï„×ëEe€i"‘ƒž¾`GN[ëÕáoŽ8â¯3LËV•¯° žÆ¡´D"Ý_XDe+ñõê‹Óf=ð¶>Å!Àƒº’¶,¿Ušƒ*•JåmëêêêG)>¤™=$Pin·uPàØ488È;vŒ	»•†Û
‚@ò•GÑv¬wþüùÃJmjpp©ô¼Çå…°J¦¦¦l9¸šÚ¬œÖÕˆuRk×v…¯4u¶ÓÆ Ïf«ÔÛ†u㪊®ì6à5²O£¡îø|¾¼•æ“Ïù•]õX„Ùò¯¬¬ PuÞˆƒÁ«ÇW\#;Tò0ÚNåÚ‰¼W£´q¥‹H§ÓÄq\ÞÅb(b¼^oLþ=Þ{ï=¬$©S¡P'õ¡)ØB¼:ñE·¥À3´^÷	öLí…—}¸åK¨D“•«W–÷d·ÓxPǼ^oÞ¯íòÐ!™LæõëééÁO9”†»¤Óé÷Ë}1_îµÝJ½óä7§…zÑ¡íTæ&Õçóí®t€'Åãñ¼^š^¯7æóùèÀýòϘ
ýP©:(Ë` Nê½¼WVV£dÀŽâÕ‘‡AÞ†Ö™3wžhxÛc¨Àb
ùK¿¥¸½\w*f„|ð”C…L&C<Ï?úw*•ºžû¸4÷l$txž›¹¥PÐáp àuÜ(ÆŒ›S´SŽë¼mÇ”E?xž×=Çq»äŸÍétÒú¥ºM[óïà)†
ÉdòýœPbÃpWW×@¥{ÉØ‘×ëÝûoAçCÓ#»¯
¡ Ûí&,Ž`Þ1¯'ÄCÛ±/#=†R©qwE¾=
mèÅéõz)ì–?orrRİCí<OLVa”#ê¤ÎÊ{ ÷ßò†ì!^bZ¶’#þF6È3qúÅäF犴2MÿSûj®HCÞÖûœ¦j1R¥÷ÛÀ>M[žâ˜†MO¢âèQï ù…z&“¡™™™]òç÷ôôL Ôò¹Ýî¼ÞCÉdòºûVškÍãñìF©ë?æÑvjÛÌÌŒ®ah™L†¦¦¦ò.Àn¥aó@àª|œ 455…KÚŒ~5ç>=0ÌuR%å=¡PN×Q2`»{A}Úä)1y‘‹’‰Oñ°oó·öîA­)ÞMO£3³rÈ­à1ÛQi9¼^oÞ…c*•¢d2yEv¹\®yتý×}¥9ÒxžßaôWtA'×ïéé¹ZOÇh"‘Ø566&&‰]F3WµCÛ±-õ£T&<Ïï2òþét:o±µâñøuùçw»ÝÛ˲
……c ŒB›®®.R0÷j,´@	 Nìt.”®#ä?2ñ<¿ç°„xuìawF!È3k­Š¿
*†ÒnúF†ÓªÐè,ÏÜ«Fzãå>Ž 0Ç“w3H$”&uo3ãý
ܸW}9öööæ–Œ­›œœÌ<Ïr=
¥M&“ÄqÜ•ìß•h4j¨L•zÉé
جn;vc´-+½>™L^Ñ[¿‚ P4Õp—7ºPH'ÿJ+'	¨§Ô³ÕH}=‹Œž/쮜ß
ubýuÒœ­fœK8Ž£W^yE_^o<é†GëE³ 499ù¾ÒäüÁ`°­žŽMùÍ^:¦7ÞxCÔ3ç Êm¥¡’vl;Õp㪥-gË~Y©Íh½ÉçyžÆÆÆt…<ÏS"‘PF˨	x@Þ÷ "Ån¡°ÞÞÞ	¥U£Ñèu­å˜L&k.,*°ú.ÔIõŸ‹]G‰zzäe2ŠF£×¥—2™½÷Þ{è™
† ÄbZ¶RËèP6ȳA/¼œ×oúFmúF*IM=6n§Æ¶ÁòìÛÀk79਼p,6W˜Ò¯Ãz)ݸó<¿crrò}3‡:VÂÁƒW>F£"Çq%‡r
‚@Éd’ÆÆÆDùbDDÁ`©—a™ÅŽÍlÈ)F£ÑëÉd²d¹¦R)ŠF£×ãñ¸hö±meÛ±3Úr hSj3Ù6 ê&5ŽF£bî{ªûPR:.¼^o,¨.‹P(Ô¦v$‰Ãª8NÅöÂóüŽ7ÞxCL&“%{žñ<ÿ¨­×CXÄqÜ•rödGX{]S¬÷o"‘£Ñèu5çÅt:Mñxüð™3gDù·o߯ÉiB€¤etˆ!"Qˆ}hÞNKöÂ+ü¦åK´í•ÿ½ð´4课Æ<¸ñSñpQ±XÅÅ.¨f¥×>æ ÍO¼‹:PFìVZ•1{Ckê{6žçEYÐN¥Ra·ÛM,Ë.û|¾6³ß׊¬P(ÄÈCA(‘Hˆ‰D‚Ün7y<žÝ,Ë^•]ð_Wêy—S?ZB…Zº9ŠD"ŒRŽì¼ƒ¢t³ép8佺vëét:Mé%geÛ±£mÙãñÏçÏc—ÉdhrrRdY–Ün÷²ÇãÙö­¬¬æy~\éÙëõÆAx®X{’LMMåÝd³,Kè×v8p€™œœÜPÉdrÜãñLÔúq`âñD+++yǃ¶fÏ¡yÇC:~ÿÚµka¥ãÁívS­!ôz½L:ÞpŒE£QQ:ÿ•ãï&êÄÚëÇ£x‘û7O:/ºÝî¯ç^Kð<=Nï(–*
ÿÐtÏ"€\ÊA^zá©xî¶Wþ ©³•¢µQ?ù.óùÇQ\¿aê~µ†|ð´ëé鹪4\Ãçó
˜=›Çã¡@  |d/ìwðŸfffòzKç?žçÅH$™"uRùëé:BiŽUY™«¾–`Y–‚Á S«Ó;€u0œò´Œ1ÛNG²¿(8·ë…WtA‘¶|7Dìï~ëߣ6t4jöizLçðU³æÆ{¬íExPQJ7,Ëž³ûçv:Šó:)­Ài†`0xU>i¶Üµk×´–³euZê|ppÐðÐW–eéСCŒÖÏÎe£—Ûí¦ÁÁA&Þ<ϲõcUÛ±{}mËDD‘H¤Íh‘@ °{ppaYVÕ9Wéæ8ì6€ƒÁ	ù
z¹§	¨†ö®õu¡Ph"
jë^¯7‰D3?s¥ËUÍZz¸iù>¨kÎ…¹×Ù@vÙèwñù|ƒƒƒðÀœû}(Ùò½oïn:Ã0-[<£|½ð¶½ztaÛ«GiØ‚<£…Zêõ
Û©¹ý¿7»GQPQÙá’˲Ãþjøìétz‡B8Q¶÷…B….RK-8 /gdzlV(#ŸçLϼfRè
…¯×ÓòZ§ÓIÁ`9~ü8£gh”ÝËÆ`PCÇgôÌèñx–C¡‰DÚÌî!WζS
õi¤-çÖí±cÇŸÏ7 åZºA
ƒWs¶õËžÓ¦T®¹åèv»)\5zã/YÀn+ÿæTúø¯Ú,/g-ï-µu-íÕãñ,G"æÐ¡CýF»¶;éo‹Òß–e©ØÐu£õ‚:±æ\˜û}#‘H[$Ñ|!­.œ½™ÐX_yÇJ9¯¡º0¢ˆÅQ 0qí}ú⟉wö·òGЇxªzámÜδ|‰ëß6oþÖÞ»(y“êïÞ¯èóÅïl˜#¯T‹×ûxã¶^ÚüÄ»³éI<؆4á³×ë¥jR—L&ó&x…B–ýr›ÉdheeåQ/‚R}±„Úçký<©TÊ´ÕE³Ã_¤ïy8“ɼ™s±}Îív÷Køf/ÕT6F?ÏóRù^—ÝÄœs»ÝýR V®V´jªO=mY	Ïó”N§I„]étú—ZëUz}±Ðr•«ÕmÄnÇG9>Ov*Ŷîv»¿îp8®:¾üòË¢B¨ÔVííN„G墿3šý}P'֜՜³eØ–ý?
7ËYÎPÝâ*÷.¤èÖ[ÿ·xïBŠTõÂÓâmþÖ^ÚöÚQ¦ÑýevÜÿä5qýúIóä™ä1›ž¤ÍO¼Ë4nëEAF7,¬À²,?~œÁ…Ú@5Óê6 ʦg½´éY/sïBŠnÿÅ_‹wv¡ð“5x›¿µ—¶|÷;̦ot¡ËÙпúÓØö"­_ÿá†0ψÆíߦÇv"¼0I¶7Ó†á€]]]!Ðvª½Ê¹ÝdP' ãÞEZHaž¸öÝùÙß¾|÷oþöOï]H‘¸vSý>¾ÑE›û¾ñÿmþí½ô¼³Ó¸š¾úÓôÕ×hýÆ_ÿÎú§?M<¸yžÄ{¿Ê.å÷Æc·Sö^j|üy®qû·ŸÓ³pvþüùÃòm½½½(´€j¦´Ë²WQ2¨Ð!è´|‰ØµïMö_í{“ˆhýê¯i=ýkº÷·sŠ#1Ý_þ£Æ]_~=îì¡qû·ÿkãöo?\øÞ¯H¼û+ïýê܃{¿
l¨çMOr̦'ŸkØü$a®;€òÉd2”L&Çs·y<žåj˜ÇmŠáy>/h7k1@Ô„x`ŠÆ]_¦Æ]_¦MßðbUÒ*ÃlzÐ=׈⨈D"ñ¾|[ À¼4h;UMš››—oG`„:}âTÏó”J¥Â¹Û<Ïr¡•m \‰Ä.Žã®8N:xð c4Øá8n— ¶y½Þæ¬D€>
(€ÊÈd2499™7
z íX-•JÇqW¤6FÅt:­{ÉdòÑþrù|¾~”6êôAˆPét𯯯Dù¯á@`7z íXM¾b© 466&r§i?‚ P"‘ØÇó‚vô–E€1Œ(Š(/Ègffv)ýîv»)‰0Ò€¶P‰6¦9Nêééa¼^/Z8&NÏóÄqœâ>X–¥ÁÁAÏ N@?„xeÄqñ<={1½Cé"ZºŽD"&–@Û¨”t:MÑhT,ÔÞ$g9÷ß<Ïï(ö|´SÔ	˜!@™$“IRº‚i´»J§ÓôÞ{ï‰ò¡œz¹Ýn
…Bh§¨0V§(“•••]¥žãõzcèÇ0@´;p»Ý488ÈdA(Ù¬–e)0>ŸÐNQ'`ôÄ(žç)*þ¡õz½1ŸÏ×ɤÐvìJ𛛣T*u½ÔðLIv¡„6E¨0B<€2âyžÒé4=üÜét´€jm—‚ ä­š*
ËDE@y!ݹ€½!İ9„x6‡ÀæâØB<›Cˆ`sÿ?öॊŒ¡ýIEND®B`‚pygments.rb-0.6.3/vendor/pygments-main/doc/_static/logo_only.png000066400000000000000000000400501250413007300247510ustar00rootroot00000000000000‰PNG


IHDR^^Í+wbKGDÿÿÿ ½§“	pHYsšœtIMEÞ!د§¶ IDATxÚíy|TÕÝÿ¿'		Ì‚Š@²A7ªþ´B]ÐÖŠåicíò€KŸöi]Rmk¥€Ð>}ÜbíæR
­µ+¢µU%¶
mqa‘°ÊŽì	É„dHH8¿?f&¹Ë¹wî>÷Þù¼_/–ܹ3“33÷=Ÿó½çžC€»0«wäœãÕËB:ÛŽSÓ¶fâ‚OÑ©ãËBßþeÛ—D§Ÿâï¾¹qCÏÿ÷ÄvÒþå=?-*§HŸB|ÀÍ
”YS(ÄtÙÿñAÚý¯½»·5Ýÿñ!âÉOLϿĈõˆø¤“ûQéðb*Ÿ<˜ULLùýú²Ý×þn˦Æ
#›â‡’
ïý—%þeÉW °O„F•Œ£Q%c‡M©¸z·~ÿöãí´©i#­9ðmjÜ@&ÛAN>J"e8 ^àG´ÑÚ?5ð]ÿü”:ÛŽ'U&—¬l›TÄLrx3¢òɃéÌ/Œdƒ†k×<µnõ+Û»Úe‚J‰©çgÆU“ŠlH´œÎüÙQ—V|þ¯Ûp8~˜^Ýü
­>ð!9Ôš|Ú¥éÓÄÜàÀÚƒ´öÙ~`íÁ^ö$[RoÓH½¢û>³Œ.˜5
Þßwí®[ÿÜýK·¿yW€BÒJ‰LGd…}
é³åWß=mäWð"ᾺåZºýMr©ôÙŠÏS$†x#tí¤_Å·.ÝÑ+ÐT²e’œ¤—zEâ•r¥ÃûÓï»$#ò}~ýs÷/ݾô.­î·“)‘%_¥”´J"etÏ%O0‡ÚAK·/¥Lµcæ¤Ñà¢á¯r Ÿìdåÿæ
Ϭ«JW’oaÞû.ø–æÉ¿¸à››ù&OÜñðöZòÿÊÈ·wJºFS	4L™0õþϨW\Gâiβl·{ùžå=ÒÍT;ÿÇ´·u&ˆáýþÍw¼¹Mu€õÈ”+Z.Ø&9†¹âqzƒ«ö•þ»wÝ!z¿ný^—DrQ	Šäß<Ê䨙±í‰&ÞÕFs—}Õ²|wÅvÑÓkž"?´ã‰÷LÛš>ÆAñ}éþ‹ïxc›L°ŒsÝÔËL¦^+¼ýƒ6Ì?¼½Å“¶Ï{w.'B®ŠøN¥D’¤DijŒwµÑ߼ƒ|k׆(9j‰hÍÞ7è•õ÷ó´&Änéþóö¥¼«µCU.`¤QZЪtl¯úÀu(õêŒïõDÀ†ÆµrK)QÜm—ŠIÞ5—^Ž›Ú¶fßôäÊoñ´ƒŽuÅA
ñ†Oºÿ¾m)ïj픋³G¬Êº«ºä îŵS/3‘zI'õzn\ÁïÊ„×F›M‰â3ýb±I¾—ý¬ì®ïoÝBO®¼™‡¡Ï|täñ†Kº+o}“?Ú©H³\‘fÕ%yêU—˜²Û)ó%Wœ¤§^åê$lc¶&eñÉ(ÑøW#)1݉(AmT™•¢R¤Éƒ­ŸÐïVÞÄÃÐŽ?~t;äñŸO_Û:ôýï%¥Ë¹fi@«Þ›®ä ªíj

3šzµN²•º2Oo¡ÎZbZO‰Jñ©ëœ"	1I×\0é‘q:xt]TÆxÚñ'Èâ
2{ÿöÉÈuÞÛ•.	Kj/9¨ÒWÜßBê•RÿF¹³ØâÐè0]Q‰»êæS¢º®Ý5'A×\´MÚ…?pt3; •‡¡µ+gÑÁ£[ ^@éþtùi	 7¥ªK"+G5(Kš'Úô†—‘ºœ@ª$->ÉæÖºlcJÆLUwÏ¿€VÝ“)DÕ“(õOD‰»æ\Ð5×ßF’m±cûh|t/C;þ´ê{Y+_ˆ7 ÒmXðÞy9@\¯5\ï5Pr¥Þ4¥	y	ƒ§M½Ã'ŸêÚëuíèkëE¥½
X‰‰‡])Å%êšS2ýé×CYÏ‹Êå%Æ©³«•ÎŒîåahÇó«¾›•ò…xƾ¿~R¹a~Jº‚n¾J.ê„*®÷r…dŸh³šz¥Tœ7ØÕók#IQ#KË`JT'@y·\¯kž®Ú»ÔŒHlëèj¥3‹>åahGݪÿ¦ƒG7C¼ÀŸl©YÉ7Ìo²æªyù¯¢¾k¨Þ+=ÀÒ¦f{©7õÿü~}hÌÔrW_»ŸO}€,ÆXJTŸˆÒßWñÚêÔC¥²ÕHSé±³+FgEò
h;^XýßôÉá¿C¼À_l¼ï=¾ç¹¹hI9‚ÀX‰A·Þ«S‚ÐK­†S/©ï¬/ŒôdÕáÒÈ@a¯ÀhJLwÒI¶oÚ®¹F=T &Ƹ°nJŒ¨³+Fgnà·]Uôv¼ºîhýþ¿B¼Àlš÷.ßÿ×-¡ªK‹%'ÛÒÕ{UF¤)9(ÍtR¯xh§è B:óšQ³½x>õA&®}«©Ç´*¡ñ®¹¶ÀÈÀ¶Þ4™øy鯹ën=»êœ´ƒÖïâ™—îW·ô&Sƒò%Y‘|¥0(‡˜i•äRU/¥^­¡eŸ¹iË÷p¥á1¥g(êÕ\÷òYù6õʱ®Â®9“§BùØW­“P\8û—HV)!¾µiî·Nªº0í 
ûÿñ‚̰yî?øÁW·ô
Ô¨|I~LYš`ÂÕƒÓ]Õ¦®×jÕŽ¦Þ1S+¨bò`O_Ó;'ÿˆ%.¨°’vuj£z]seÂd‚ÛíGŠ.üÛ›æ,ÿϱ—A;håŽÇB{l[>“Ì9‡]¢«µ“6Þùoþp_â°œ⌈+~&b‰íÉw”'îÙ_ö3“ì'þYy?žzžä¾ÊÇJíK’}å£~ÜÒÅ4ý‘ËX¦^ãï/ý/?Þ&¹ÂK^ÿTo㪳ýª.¶Æýr”]nÕýRJ»+j§‰ÿKŸgì)×Òâí›YÚ1uÌ}þ(³öFâõ¡t¾õ7ÞòÁ>á
©ä«ZPR™|5†Šél#1Ó+9h§`íÔ[:¢?]ýÓϲL¾Î_þ8‹ô)TÕ¬…)‘‰†X)“¢âvIªÓ­‡2ÁÉ)›²bŒhã—éKÃGò0´£~Ó½¡;Î!^ŸIwý-ãm{?¨&ä+¿¨A˜™öÏ\½6› äÐ+(ÉÏZÏ/yœÒÅtõO/õ´®«-ß'X$YvÐ=³¯è’“@PÒ®¹\bZõP.ì¾§XzY¥žoÓ—éºá£yÚñNÈäñúHºnþkRº$›´Ü¨|¥“«“°2­rñÅ‚z¯h”ƒ–´å5,ùh‰ÒáÅtÕÏü!Ý]ödR¾ÚiWTÿ”]Nˉ‘qA=T1V)0Åp+ÍÔ¨)+õè‚MÓô£yÚñÎæSgW+j¼Àº[;iýMåí›UõÒžeu\ýš¯ªÞ*ûY^{%ÆduXíúor?Åï {~Q]8ùó€ÅtåϧøJºRî~ë&ïjSÕ6™ò½ þ)í>«»Óòz¨‘}H F¦øIJ"Õ"*í7†Þ;ÄXÚñ…³~OùyQÔxuÚ76Ò†›^åñMÂäÚ[†³ž|å?«G:HoÓ¾2M9‘Ž´ÄÀåÃɸ|ìçé—UøZºDD÷_ö-×I»‚n¹¢Û-êN+E¤'+y÷]=ä͸¬”É”SSÛº¤Œó0´ãµµÿI]1$^`]ºo|•wí”%F"õÈ"Ñ3ÉW’JÏÃuF+È’­îmŠ‘ÉÛF\1œ.¬>Ÿå=¹ÅÝ|ol»*ª%pB•õïcäÌ¿ZLÖdEš'°JúAËC;®>ó™Œ'_$ÞJwóá'Z;Kêȯ:ë©¡’õäÛ›6·‘¨N+NQ½W|›úDÛé—KºDDw_x?-®k$O‹ên7iÖCéQã,?ë‰CÖdÅtdEÄéHÛzº¸'ù»K>þz`“/oˆosçdÔ÷è¡ÿÃ÷¶nŽuÍ1;a`¼¬RV"É™“iÈŠ)¦,È+¢µ±ÓXÚqå™ÏRI¿qJ¼o¤»e櫼ëhGO^Pž@ë)—*KŠ“f¦ä«qLYJl“=—¿r8M°tS<¿î—üƒOßN{"JïgJ»?iwçÓÈŠi
L=%#©ÊDùIù†¡WŒÿSFäñ€–··Ó®{ÞIJW"4‹òÕ’¨¸v+¾ºM„‚:“ éJGKœw×d6üŠ¡yÏêÖ=Ê?Üû¶)Éæ’é×P%'ªÌÉJ=@™¥É± /JkcƒYÚqùøçh€ÇòE×ç4-Þ8}Ç­Kxwë1ùDäÒi{j¸\8Í£păš¯ÞÕmªZ­Æ•m²9¤÷—Ô~Ï™t‰ˆªÆßÆÎ<•Hãì¿h+éÉŠs%x$+ƸjÕˆã]-4!º‡‡¡o­«¢#mëñ¹‚x=àÈâÓ÷ÜS¿¸÷Ä”üR܄ܸâä•R¾\uÒÌ®|e³	äËäk&
†œõÞç¼»&÷­™tS|eüíìâòk?!åÉ5åÿ™Æv²6$KWVL,+ÕhÕxdõyÇ»c4®pŸyÖ-·½KÖL£mÿŒ“kîÆé{~´l±p¨˜ < ,=ˆJ²pš“ã+;‡éœlS×{óƒÏô-¿rDG6¼Ÿ?^z57[çí9)§ºC}Rʰ¬t®c‚:¨úd©$FD4yäCw?óñã„ 4|ÐWPãÍFš_ÚXµçžeÏKzî²Ñ	éêºÂÛÈWQ£5%_QýW£ÞÛç¤|:ó»çô6mD,›Þ×{—NãL1[WŽá“P&d¥9u¢XVò…'¹ª*Þ®þwò¨‡ï~fíoA;¨¢ì+o6qè—+ùÁ_½/L¶âô+(i_8‘z<©Peû[–¯úMù2¢¼“òé¢G.gýGÈÊ÷÷'o]a)ùZ••æ¶Âš©(ŠOJ1¥°’·7²fö³ÿfAÚAeUo6°÷‡oóæ—6Èd)N»J²Ç_qfK¾iËD¹Etá/²Wº)~þÎu¼£;&¹Ì€t…ceÍËJt9-鎃wÉ{þeò¹ˆˆFz½¶­ž…¡*îƒxÃ̾$¥+(èɵ·t .-è×}õä««H¾¢¯Ö0³¼¢|ºàÑ+X4Ë¥›âþ¿_Ë;ºZ%2:Ñ+bÕ×ê!Xº²­KÆ5—ÍIWU%FE:Tvו—UÑ[»?`ahÇ9#ñ†Sºoñ–TÒ•¼ººu\Òƒ^Ý7݉µÞ’„IùªfëÝ?¯¨€&?z9‹Ž*Á›-áÁ¿_“¯É’CJ:9¦æ:­_f´ªÝ%W¦Di‚Vv=-ÛõC;Î9ýQˆ7LìÿÁ[¼eÑuŠÕ8I¦*=ˆê¶ªº¯RÐÆNº™‘¯òÒâÔþE£KèÌ{.„t5xèŸç²ä«-'3²bºËípˆi¬c¦‘V:” Hü;¬ìzªßõ>C;Î>ý—oÐ9ë ýw¿Å¾µ•do1ë}‰Í¤_3¥¯ä{Ò¨:ï×W²>'åã
×áé•7òƒG7÷Œp0*]Õð¬4ÇNjÔ›×€™H‡Òèú÷Ô’«é½½YÚ1iÄ/©O^ˆ7¨ÒÝóµ—xÇúCŠt+YðÆJúMWzHsÒMyi¯ùž4ª”ÎýÍ•,Ò5Díû3ù¡£›UÉ׊¬XÚ«½ŒÕAÓ¥Ãq)Ò!“GbDí7žV7¶±0´ãÂq¡>¹ý!Þ I÷ÓñŽõ‡„r•¾å"Y
Ó®*ýj—Ò×}µW6*ߓƔÐ9¿™éšä÷ï3!_¯)Yïªß%7—Å)Q*³háxZÝt”…¡Œ{Õ–|!^¥»÷†yÇúò¥ÅéÖZúÕ:ñ&œG&äô#ŒÈ·ß˜:û7W±¼"H×
Ï|ð
~èè&ÒM3ôJg¼kºOfÒ¡¸FÚ{ßháxZÓÔÊÂÐŽÏŒû«eùB¼^J÷«/ö”HšdErÕ°áôk¢ô 5]¤æX_|O¾f4¬>ҵɛçñõû_M/]ƒã]Í áZg¤º]Þ
—vÇ¥éR-3¢þ…ãiÍ‘C;Î<ý·-<âõ#ëÑ¡»Þàë÷¾½ï@Úô+{Û
¤_Í*Õ}ÓOx.’ïÉ׌¢1s.fЦ3,Ý4—oØÿ™tYºY¿T«ìêÕA©ÑÑt¨N‰¬wYÊÏÒ–¶þ,í8oìß(ZxÄë7éî»þÏüD¬CœbM8}úU_>,º¿*ÕŠê¾Êm¤=1ú kFÑè¹—@ºóö¦9|ãþW¬­âkb8–3éP[PRQIk¨y¹QÚÚeahÇùc_£"ò…x]–îþª룑R¬"ù’æ~ÚéW™XÓ¥_ýÒƒVÝWTÏ%FTöÅÑ4
Òuå[àk?}&ÍÂ\5Ç­Ö(ÕØ4'žŒ¤C•˜D)Q2W¨RZÛÚ‹XÚqÞØ×
ËâuQºª^à'b²T+­¦€•H8“~Í–D—K]víh9Òu›M^™òΦ/#ÅÌfzóXé’ë¥C;Ýq­‘RimŸÄÂÐŽ‰£êh@ôb×Ä‹‰Ðõ¤ÛpVÕñ±c=oJïŠ
’ÕT)9A8çêý““tÒsÅ$ç=ÒÔ¤þ”|.žÞIÓ¹lu
ÕÄçÊýH>ÑùÈû.¹Òõ†1'_[?eÌ‚«s”Â5 ]ù~Š®ºjÒðÞt¨¼€AWö¤^[Ž	×U%Õî-4¬àS>팟<ôv|¸ií;üŒkŸ$^
âo|RÐxç’còš®ü%ã’²‚Ñl®ü N¿ZÃÎä)V‘„5ÖQ1ÿÒ©¯]%zËæ‹§¿»ùG‹IçòZQ—\kL«°[άuÇõ’¡²[N’”ª,®þxÝ[›æ\‚vЩ¿Rƒ´ýyÝ­Mw.yTÞi!¡€õ꺲aû™-?ˆ¤ª¼¯ÞȆÔcT,˜éf˜gÿu.?ÞÕBd°ÆkäÄ“ºËm´>ª}©­º[.íÞË?õri=Q÷ö¦Ùׇ tІ|!^¥{äûKåŠWÈy¯ÿ¦K¿zc~Õcy•/¸ôêÒéc^‡ú2Ïsÿ:›ïnvÉUÛôÒ!#Õ¼µê%ÒÅuOe:´+*éýDznÙæ_‚våñ:&Ý×%ÑÛà€€­”̦_ÍÒc”ST@§ýðBH×g<ÿï‰üxW‹ÆP,圷zéP<;—Þ¼ê¨ûê‰JúÿS~“Ví[ÂÂÐŽ1ß„x¤ý…uwùþë÷KGdJÀN§_ND¹Ñ:ý÷_d‘3Ât>äÏÿ>‹wvµèvɧCåXVArÔ¨:)*ÉǘNø
Z³ïu†vŒ©øÄë­/籇—Ë_¦#©e¨xKíX£þkää›^ú͉ö¥€týÎëk®âÍmë4»äòt(H…FÓ¡c¢žn–ˆJONø
Z»ï5†vŒ®x
âµCó÷_ãí/|,xÙŵXU
¶+`ú¯‘òƒrî^QúÍíß—†ÿþZÖw,¤ÞXs%onkžx§CŰ«4Ýq­9j튊É6Hë°ò£çäߤuûþÊÂÐŽÑOA¼–¤[ý¿ð±lˆ–_l¦üÐSÓPŦCºã͵Wð–¶u”›þ¤“~w\47­S¢Òê¶+ïÓ¯píŒífahÇÙ•A¼æ¤û7W&]#V\If_ÀâåÒ	X÷ä#ê;v úóË Ý€òÖÚËzä+J‡éºãú'œiÑ1QqÒ;ŠR?'仓½ÿï¼nˆ×(-Iér—#½„µëÀVl®þ«~ûŽ-£¡¼ŽåF`°óá'·ó]‡ŸŸtbê4¨·ø£f·Ü°¨ôëžLûlˆB2\"߉´«ur;.:ïěޱc«þ?¶d³FGŠ€µÊiFBˆœnr½òCò¡óÇ¢aÏ^Çr ÝPðÑÖÛø®CÏ	WgЖnýÓ9QéuÃõ„Û›0ÉwWl;j;.:âÕÿ}cǨiÆŸøñ†­·&a?	8\
}öKnÈXµõV¾ûПÝqõTŠ™•¦¤dDùÒ7¿‚öµ7± ¶ãÂs­y0+ě«GºL-XfOÀ¢2„ò1¸ô«ÞŠ€uNÀŒ+£Óþ4Ò
)
;Ì·ïÿ­ný3¨Ä³v)“ÙºgúT¨q„ÈÈËíO‡:O° µÃªxC?;™Zº’:™ô…í™I\y©¦r‡ÞÙÀw”ìß;£˜²~¤œy¬çC ™aL:«qÉï)™ÍL:Zô?ÆBº!§²ü§lâˆ_ýR4ãV	&Û!ÉÕ`ÂY¹Äsá&ûüÚ“ÖôüQÎЧ8¦ÉæÛ•î«<¦qêîn¦²üÌv˜'/üÒý£BºL+‡&þ'ýëéò(SpjGi
–~£¦öçÔ3鑬TiâíLu­RÏŸºZ‡§‹'‹¥pRМ1ŠþÇ8*»ÿ
Lë˜)»á6F¼`íöÿþÓZy¤3mi'Cñ™ýtÝp'Ò-×ìjww7Si~1?Òyœ¥V	mâíj8@M3žQHWž\ÕÅ«)˜„)XöÍ(™›—)“·Å\4c•=éf§•}í¿Îñ›'¤©0G9¹ŽN2d¢Ñ‚ýåŸ_ÁüÓÊdi ݪu1ïDw3•ä÷áçŽþãUAmGÖÖxSÒåÉ	Ì5WûãÀ5wckÁFëÀâ˃E5à~_®¤^	éf)¼zNöoÐÕÝb"ÊO4éÏY új¤B®sñ´‚Ñ»}DEmýÚmß™êçv|æ\ˆ7)Ýý
é2M7+aý·ÎÈh3î÷åJ*}p¤èó®îf©%¢b¤y›^7\zOû~ÎÈV$ß·}{ª_Û1Ù¢xCUjPKW¯´ ]rÐÛ®,h—"Ô'ãW—!’ßb½Ëñ¤)A”>8í6H¤¸ô콬Oní“k²¥s´NH)»òŠÏº¤΄]pùç_KRF»çÒ}·ï˜5åÌ-b;²"ñ&¤û…t­¥ZoSpúE2SŸ’‡§ÝÖïËã	Ý%ï~tŠ$ùê½Òë†Ë‡¨	d†S!sPDÆÖЦ]w3¿µ#«oǒѦ¿Ôt¤Zn{»¬Øß³›±L‚B~ω8Ép4HèqñÙûYQáY‚„+F¥LvâTH©é¤B«É6»vWÓÐ_ã~lGVŠ7^·úÞæëZÒå6KÎIX¯!½Q¿‘pÉCWÝ
é‚tœ[¹’õ;Kc$€ÎÏ)I1í.x&d+ÛŸ56-¤¡e_ç~jGVŠ7^·úÞXõËóµÇÔ§}ÙŠ¶Ëºs¹„¦àÜh>
xøê»¿2þháìqﳓ
Ï"RÕ@¤BãõN£’b6e«¼ãáÆ…4¤ì<í°SZÑ$Ó5Þxݪ{cկ̷Þ4–íÚõ`¥¶s¢Tòâ
¬Oå Ø˜fÕúsx{ûõ'Y?›Ï\’
³pÇ¥3ißá?°L·ãülªñ&¤›JºVJv“-·ø8õ`E
NH÷«.°Ì¤q²A¿©™
vÁ­¥óÓ‰©IDAT$B»©ÖÈýRqáY<Óí°Jà.>úP=o{虊¾³xšï2+÷ãiöO¿oÏÿxï¶œþ}iÀ‹_e}*O†=€-FU<Í?Ô¸Pð©ô6ÙZIµévo¯¦þ…y¬}5ó{;-ÞXõb¯[eâåsBÄÌâötû2U7E#4àÅ ]à#UòÕ®uúARf}Ö_MQ‰|ý,Û@–bÕ/ñxÝGKN•œ+1¤Û–Wy2•,‚tóœ^ñ4;uÐíº]p'ºßÒò™‚Ýî}<)ßL·#tâMHw•
ÉZªÑ¡gfä¬Þ–W9ˆJ}åAºÀ%ʇְµõFdæ¾•Z­Lãþñøj*È+æ^·#´â•']£'¾ÌˆÖŽˆí§Þ„t¿ÎX´/ì\¥¬tæÔÓ“òµ“:ͦA'E«Gww3äs?¶#0âå±cÔ|ã³Ié:™h±ÕýyRº'SÉ¢o@ºÀ3–Μj4ùêv½} Z-ùæ+’o&ÚHñ&&0ÿïX²Þ`š5’zݱÙ4Ì%Ò=Ò“ï¨Ó_›[ìH̤hEs"™|½lGàś«a¯		Z©óº!jcåŠHÕHd”ÅÓ_?{â–’¯™4hUPÌ!¹yœTÙaDEí27Û
ñöJwŸÑ:±S"ÖÞ©šHÑšk!]àΞx„åå›Jƒ^¦Y;²îîn¦;gMQÞ+ßLµÃ·âMH÷	EÒÕ»,Ù;)éDÒÖ\‹¹t¯˜4¡7ùÚ‘]A9•ˆ•·+)_¯Úñvï>’”î>ƒb´Z絺}I'’îtHøV¾ý"-Í2æä°0§R±òñvíœ5ex¹ºìà´ìÍüÎÖªC“ät5쥦Or‹;ðk:5õ2³qõöHÕ$ŠÖ\éß³aÃ$Þ_íœ(º¿SS6è:pðæÔóŸ}NoBºOpk·PVà6ö3›^­§âhÍu³!]ÆŽ]Å
%É7Si–‘;iôÐÁGh`éLîU;|'Þ^éÆ-ŠÓ®–1H÷K³#U“àpA“o$21£’u£kŸús¤q!•)äëuÉ!#âMH÷qIÒµ"D7j½vO¾õÞé‚ Ë·´t¦£‚t+Ŧ{|Ñs4%åk·o犭IéÆm¦X·ÊöeœîÙ.4å嵬´tfÆOž¹%ð¦Æ…4 x:ÏD;<o¼îƒ{üÇcIת`í¦dçöaÑŠÖÌ€tA¨ä[¢H¾^¤XFî'd"¢–æ—©_d"÷⹤x6o¼îý{cÕuóÓ7‡xKÌÜÇÌþÌò>,Ú—JÝÂò*OÅÑ
B'ß¼Üb~èà#Ž>®×gœµžïX|5õ‹LämñÕžýJž$Þ^é¦K¢éR¯›É×zúMH÷[.-§
©aÃÊÅ3›yU°“’Ó=_<)_¯Ê®‹7!Ýç瓪Yú©Á‰E#Hº +()9UK¾^”˜ËÏ“’¯_®^@Ñþä?vµÎye¨÷æò}X²¼I&ÝÁ8*AÖÐÔ¸pÙxU
ðšÜÜbêên6ôëL<Ç㶦o¬ú9¯{ßÅ——yx_õþy•ƒ©ÿ#_tAVÒÒüòU»wÎz­»»9pb5ò;åæÓq
ùJ7Nð“xµ¥›‰ï?çÓo^å`*YômÆ¢ «Y·f—Ê×/ruâ÷0’|'øå’á„tW’µg2µ“ýqdñ1´÷Í«<Ò Éø	GX^n±gÌ0ƒœ »»™òr‹¹ípT¼½ÒuB¨Nˆ³{RNºð`*YôH	•‚i%ý,T?È×1ñÆëVÞ¯û·IÚ:æVúå:åH-ùŠæwð«PÍÈÿDw3õÉ-æNOei	i·«áSj¼üîíKäÝcDªÎ£¢yÓ!]Ò°eÃ$~L0­d&$ê4}#)®¸Èâ¬LÖx[ç¼Ä+8]^0_Ç•¯vEk¾
é`€QcW±¾g6sºáv‚>_M'Ÿ:Ç‘Ùo¼îß÷v®øÄEa:%nóÏ©:Ÿ¢5_Å\º8 _Fþ‘¨UþÂW®µ=üú|ï„ê¸!]ìÉ·D2³YX¤îîf`p"u=lM’Ó±dm´{w“C¥/ª;Æž'R5™¢57@ºØà´òZFDüHãBßýnvîÖæ—3[jèxcm‹ýê‡ú¯tÕˆfCº8'ß:ÓJ•¤Óì¦Þ!‚…3=K¼Ç^_ë°03û­ùÚìHÕdÌ¥€ÃòÍÍ-æO+™Ib-¯L±#pËâíjØC‰	̓ÒQài¤ûuH—8eH
ËÉíÏ훊öØ-7X.5t®Ø²+sÍæŽþ)˜v&Aº¸Ë Sç²~E—â…°#Þ±ö¡NÐÙ?Æ)š75]< bT½écùôϰ‹¯ò\¼]
Ÿúü-6&èüGRîÐRx„tR ã•r,¾ú5ÏÅ«¿`epþäUÁ‘€‡ô-œ˜õ¯AN¶¿¸àyê·.¬¾äþ0÷éjØOr¼c‡©ák`9ñ&ºèÁ/5t®ØœÁaqd¡x;w˜y>ýcgbËâ͉FBy¬Úž\Æq8à>{¶]šcíÀžjËçþ,‹7ÿÂÑÃÒw‚ñ§ýÉ·QrÀeZ.sbžƒ,/5Mž˜r{î÷¥ÎcmÔ4ã!ùàžt÷íœ5Å­n¿×ôLÌÜ´}¯š@~¿8¨Äò}òÀ%éºù^×wí^gO¼_¾À£/o$ÎcíÔ4ãA¯[q/ìsxß\î¶t3AÓÁGl¹Ï–xó/#¹êË/	×~Ù!VýôüxÝrÈìß9‹7†dR)…Ì7aûŠ~ß¿fv&–åq[Ò/ö¤Û’œ=hõÛtÄ[ßa_ú'Ruá‚üGSÖR3ú¼/ö¤ë~w¡C³«9´¼ûnjšñ·v!‚†õñ4_.Q´æ&Ì`€ÇÒõ);äæÓ‰îf™ÎÈäòîy•C©h^ÕìÌP°š€Ót-ê–S¬ú)\d€{¶Lá±Æ…›eÌhâ4¤¦ž9ø˜¶oŠÖ9Ïóö'—zšF½É1;7LâñÕ!<êô/I±Æ…ªcL&oŠ¢y׳HÕE'RÿJ¾˜Û÷¤K䯓oZÒõMâM«~ŠÇë–‡ôcÆ)¯r•,úcÑBu «Ù%.÷õÑë¬t}‘xSDknbEó¾ÀKÀŒ%ð®†]Ô4ãÿ|¤+Hº~"f&I÷/I­™ípm"ôÂ[.­¹iv°ÄjÈd3[×°U^ðûØÝƒî V‡Ëžˆ—ˆ(RuÑoåëm½8%ß®†]8AÖ°mÍλ›]e&Só)åµõÍ6/	Ψx•¯?OÄu5줦?‡|AÖH÷Dw³)Qfªl`UºwΚêv;\9¹&¢sÅFj¾ñW:]ó`—äY´JýåUÃÑ	²JºîYÞÙ)éš¹ÿ(?\‘áT²èn¦=‡¯_kíwKÌl†äÂÉvIyÁ«Ôê©ç²"]_—¤øg–;¥Š”|ãuïa~
Z.Ûú“%]¯Dé…”sr‹éäòÚúC’ò‚WÂ÷¤Ô Å›^§hùóEknž©ºx]dét`.Ý̉úÒ%ÅÜf×÷¥Qòu¦ê—¥‡äĪ7?^÷.’/¬t)–êq2¹zQ>Ð{N³Òuº9™zcÍÉ7“#¬?'ä‚,]7Å“‰º®tYvÖÝÌ29n8#¥ÙãÄÚ%caýtŽÓ9"US´æfL®|Ï‘}sù›«Fp™f’®‘ç¤RƒÌüÑÂdòšɺ¿ˆ&§xÝ?(Vý$¦•¾æÐÎY¼yß<Û	Ô$ëÄcöɯ0U^põ¤žÞðÔØüÏðH°^Ì,'^÷.ä|-Ý£‚	ÌÝ*-8Y:0òØ‘‰t¢sóK;rüòƳh!
xñ‡,Rõÿ|œbí=OJ¾˜ßø‰ÃÒu3º™&•Û72‘ºâ«™WÏoôw´¦î^x‹UÿŽÇëÞs ã¤h{œ¼Êr*Yt¦•¾•.÷ÁÑâÄcD&Òq…t|îÓƒZã­¹Y‘|3=\Ì©ÇJ˜ßágH¾ £ìß2E3éÚIƒN&I;É´ ™týÐŽ@ˆW.ßLsÿ± _Iöm˜Ä;Zß1,¿ˆØ¨Œ#E—ªÊ~jGŽŸ?Ñš›Y´æf‡§•t{yyã$äûSÞÕ°&žJ·S2—®™ØÛ£¢¥3©³õæE;B)^"¢HÕÅìÉ×…ÝÇë½?ä2)]'DäÆÉ6«•ΤvŪ~(-N¼æåë¶h¹¡¸%Öù×Ù¿a?_mX,™ì’[yŒ”týÔŽ@‹W_¾AmúÇ€|›ìY3@•tÍH%ÓµÑtQT:“â–êA×¢|K—ÎWÌéëNÈÛêc$îÃcmÔ4c×ýó;ÇøÔÀæf…âT×*²E)ÝÑ#]¯Û‘â%JM®ãÄX§’²=Ù*ïÇcí«~|>䜔®Õt륄­Ü¿¬¼¶¾Mc}4/ÛzñZ—¯»csÍßWȸ•t½’°Û".+¯­?’œÀÜoí¥xË×ÉÚ¯²å¦öU?ùKì5¸T›v"EjÝ?%Ý ´Ã±2…›—›¡{÷aj¾ñ—¦•ôòÂIíý#U—P´æÛ˜V¤¥­qá²#:«FpO?¹îYÒÍd;*Âtɰr‡¤’E÷¸´š…Û©ØØþ‰i%ÃÌf@—öÆ…ËšÓ,Õc$µyQµÚ•X^[ßlp}4?×xŸx{~ŸX;5Íø™…áXN•!ÜØŸ+’ïg‘|¦tEI—»öitïÈÝ/'·˜rÒÌ¥›‰vdmâíù‰&“o¹ÉÔ»t+ßW™|ÿN±êÇ0¿0$]³	—ÚÏn‚TÞ/'·˜r“Kõ©Y‘x¥É·åŽ'xÇ’}lÍÞÇØ¾‰i%g3íëd9­ûæòVÉR=Ü¡O#÷É¡•týÒŽ¬O¼Òä[üô,Ru1enœ®Õ4lì1»vPÓŒùœÇÚ`ž,¦yç,™t¤9§S¡›#ôÊ~i‡UrÂú¡ŒÖ|‹Eª.ñP¶Dî”Äû@¾n\gÕ£vªûn¥¯÷{HËAhÄkK¾Î]fÿ9Òï×Õ°šfÜÇ»vÀDY*]'®Ó#ìÖv")W‘tƒÔWÓ²_k¼"Ž>ôo{è%ÁYMÅnìoþ<4‹ö£’E?ay•°RÈiÙ9‹·ë$]îø§ËÛ# ?2‘x|5J;ÊQãÕæ¤;¿Ä¢5ßší\)Á»‘FöIL®ƒävš¶LáñÆ…º)ÌÉìõ8Ù”tƒÞˆWB¤ê’	ùº7¿‚µý­W.ߣÔ4cäR7Lâ­ïî®fê$›Ù²‚HºAjÄkX¾ÿeaBõL	×hç‘K’ï<¯{ó;„Lº]«FØ“Ó'§¬¤ÇüÈD¢ä¢”AmÄkP¾Ú“ëx5šÁî~Úe‡Xõ¯çC¾á“®W%§¡‘}û•Î$’$Ý ¶Ã,YqrMDb­³É«À¼˜æÃ©R¿ñÛ£5ß©ºtôLš’KõXù$øõäWH÷xãBäv³xr-kÅÛ+ßù&/ÁõÏh#·Í›¹»ð–Ï#(%§uL÷Îs?QnŠ«0)Ý ·c(F5˜§÷ÒÛBƒo‡õ^'N®ißÖ:§vh¬úטÙ,ÀÒ%‹%¯»åF÷ë§nÛRƒkÉׯ	×\NˆTM¡hÍw1³™Ï9œ”.wä]÷_r”J7èíP^KŒY;¤rðQO$ß²•Jf6ssDƒ“£Œß¯«§Xõ¯| ]#	,Þ–‰ä˜Úw@ym½4é¸4 ¼ÖÖ{Ä+mS¬=y!‚™9}½ž'É^N(˜v>õä{˜ÙÌg4ê¬ìçôkt¿åµõGuVP;¨PRb@âu€Äœ¾?19§¯“enóöô÷ëX²’šfÌÁä:>áXãÂe‡?b=ë£1“É,Ó©ÑÈ~ÊkëÛÒ¬vȤ‹Äëiòu~~]·S®h{^åp*Yt’oéh\¸¬UcsîÑ'Áí䘒nÚ!”®ÕÄñê«~ŒÇëþîSáZ—n
È7³Ò=š”.·üzû‰2ûé..¯­oß9kjÚ¡™t!^×äû[‰|½®–¹sîÐATüôX^åpØ0ÒÍDÂu{T@Nn1å)¦uj;JG×SŸÈDmB¼™”¯?‡¥¿-±-1­ä|È×âûæòø¾yŽ¥ÜL§Få~9¹ÅÔ§»™…¡é¤ñfL¾N—Ü--èm‡|ݧmç,Þ!™K×+9y%.–”nÚaDº¯G´?ùÚ®Ö9ášÿè'Fu,€|=nÐä›nQy!¨í(1(];âÅp2Þrõ°hÍ·MN+éÄ>Þ$`k£ÆË«y¼nf6sXºÉ	Ì&«—“…û¹]oŸEÒ
r;ÌHׯI"U—.ˆÖ|g¶7)×;éÊË*Î×½
ù:(]=©8)'#b²"%­Çè™Ø#Ý ·£lüvO¤‹Rƒ
âuïÜ«þí|ç…ëVGÌŒŒÛ¢5·ÍŽT}ÓJZäè–)ü¸bÕ§K™¬‰ö‰L$&X5"ˆí0ºžrr‹Í5^ïéXò~´åŽß¶ðØQ£¯š‹·;+ÝEónÚ]xË1­¤IZ7LâÝɹt3-Y7†dõ‰L¤œ¤tƒÞ«Ò…x3HWÃjš1/Í%¸þÑNÄ‘ªÏQ´ævÌlfAº~I¸N~åK¥ôvØ‘®ñ¢Æk“¼Ê
*Y4Gçê/'J™“n¢¬ò6ŪoZ#å…
“ø	ÁªVjœf“’ÝšhºÛ™†tƒÚ»ÒµÄëš|ÝàÜ+é¦HÈ÷È7t»%룹)ßLŒˆ”Τ\E)ƒÔŽÒ±«2&]”\(;´ÜñkƒK¬ûg™™mÓ>Cý¹ó;(ˆ	V0óêzÝ-7û鋔ΤŠU#‚ÚŽ¨Í¹t(5@¼“Xb}®Ž|3;1Žéö&üT²ègo’VU#ÂPÛI7¨ípRºvÄ‹RƒÓ]ˆh?*Y4—åUV„Dº¢d¿•šfüsúJ¤ëEy¾ÍÈí‘ҙIJ0´ÃiéÚâõD¾v¯Pˤt¹†|·e½|[
.JéiY¹oߤtÃÐ?Iâõ@¾ùŽ3 T«£ÒÝfEðÆÝÕ°/¿w5l˺÷÷èšœ4–êqSNvVã5#µhym=”ØßIâõ@¾^œÇ"US(/@¼§«a;5Íø	O¿š…Û‡Û’Ÿ2¿Ë·cËÞÝúNàºÞF¥•™HyñÕ,툎®'–Ái!ÞÐÉw¶ÆüÞ/ûãTÚ•R0íê_s'cÑ“|õÚSL`î׳úV¥•›”nÚáéB¼¡—o@¥+I»Òmy•§SÉ‹÷ûF¾Ç«Fx‘ä¼’–RºAn‡Ÿ¤kG¼¸€ÂgäU§Ò¥³¼ÊáÊVö5.]"¢®õ[©éËwsã‹„ºX^ph©+éÆé‹	D—Њ¤ÔvøMº¶„ÄëO—àÞË»¶g({9€µ†å³Ô—Ì*ùóK¾)éú5ÝÚj•™H}tjºAj‡_¥‹Ä2ÓJ.$ßL(Á=é&Ê*[©uîcùïÜ9«'éú5ÝÚ¹„¶ t&õI&Ý ·#LIâ
¬|3u›ã™žˆˆâ/¼Ií¿{i‹—¯kwóËWukËDÉÁê}´nË/IL1—nPÛѯ¼6tÒE©!@e‡–;åKþe±Ó毃ò¾¬ÿITúÆoYî“=y=™X˜Ò.´›'’nPÛÑχ˜£ÔeÉ·øé±HÕç<:¥#Ä\pûS/óŽ%+I»W^D…7]Ǽ2æ„€Oæ½5+¬ÜâéÔwÄbÏë×¼»™º>BN¶£OÙí.ļ+A¥cKþyWÇÿ¼¿sÅZâ±VÃi7ÿ‚	TpÅŸL»h”ßn:º›_¾ª»å•×N´¾C¼s‡!i±ÜbÊ)º”rû_[Ÿ§37„Çí î–WÈb;(·x:ÆåB¼ ãòîÔ½çuþsð;ää»s‡žü€ß“­¥¶7.\vB¹v[~…o$›ö˜íÜA¼cñÎtB!áÔ9¨Ýz ^Üæÿq!ꈠéÏIEND®B`‚pygments.rb-0.6.3/vendor/pygments-main/doc/_templates/000077500000000000000000000000001250413007300227525ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/_templates/docssidebar.html000066400000000000000000000002031250413007300261150ustar00rootroot00000000000000{% if pagename != 'docs/index' %}
« Back to docs index
{% endif %}
pygments.rb-0.6.3/vendor/pygments-main/doc/_templates/indexsidebar.html000066400000000000000000000017531250413007300263070ustar00rootroot00000000000000

Download

{% if version.endswith('(hg)') %}

This documentation is for version {{ version }}, which is not released yet.

You can use it from the Mercurial repo or look for released versions in the Python Package Index.

{% else %}

Current version: {{ version }}

Get Pygments from the Python Package Index, or install it with:

pip install Pygments
{% endif %}

Questions? Suggestions?

Clone at Bitbucket or come to the #pocoo channel on FreeNode.

You can also open an issue at the tracker.

pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/000077500000000000000000000000001250413007300222415ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/000077500000000000000000000000001250413007300242545ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/layout.html000066400000000000000000000063311250413007300264620ustar00rootroot00000000000000{# sphinxdoc/layout.html ~~~~~~~~~~~~~~~~~~~~~ Sphinx layout template for the sphinxdoc theme. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. #} {%- extends "basic/layout.html" %} {# put the sidebar before the body #} {% block sidebar1 %}{{ sidebar() }}{% endblock %} {% block sidebar2 %}{% endblock %} {% block relbar1 %}{% endblock %} {% block relbar2 %}{% endblock %} {% block extrahead %} {{ super() }} {%- if not embedded %} {%- endif %} {% endblock %} {% block header %}
{% endblock %} {% block footer %}
{# closes "outerwrapper" div #} {% endblock %} {% block sidebarrel %} {% endblock %} {% block sidebarsourcelink %} {% endblock %} pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/static/000077500000000000000000000000001250413007300255435ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/static/bodybg.png000066400000000000000000001452771250413007300275370ustar00rootroot00000000000000‰PNG  IHDR)‰+ù pHYsHHFÉk> vpAg²gÜŠ€IDATxÚMÝ;–›É•-`¬Æ$èÁ Ž‚ÖÊ1È Cc€Ñ–Fƒü4ÒÃ$(ƒRUA*éJjz¸Øû;Aª{u‹"3ÿqâ<öcóûË_þüÛí~ÿ}÷ûû¯ûûý·Ãýþï·ßw¿œïÇßwßÿço¿=~9ÿ¾ûÏëýþ—?ÿzùíðÏᅵÿú‡ß{üþò×?ü~ýËŸÿöøÏëßÿôËö·Ûï×|˧ývøuÿÌOßï{üëË/Û߯ÿÓ¯—ç'_»ýýO¿_ÿý1ÿùÛá·Ã¾Þ¿î½üåÏÿø”OýÛãù©ïùö¿üù÷ë?¿çSóÿïÿòç_¶;=¿ãÓóJ¿œó{üºÿë~Ùæ{ßýíô—?ÿûãó÷wýïû|{~ç>Ÿóüeûë%¿û¯¹ç5Ÿ¾ÿO~&Wðü}÷Ûío§ßnù¼_ιú~ÎOçŽÿõá—íóÎÿÓ¿¾Ü¿~ßýýOÿøô¼¶]îîŸßïÇ\ï—ïÿ“'ðü¿Ãó;ŽÏ¿=ýíôü”G®á~ÿ¿?ænþú‡ûý?¯ùÞßw¿^þùùùyϧõ÷?ýûãó\rýÿyýåœoþ}÷O¿lóÌžwôöëþù–Ï¿}éÝžï÷ÿ÷¿Ï§÷¼æßwù¶üͯ—ÿ|ýuÿ|+»ßwÿïóFŸÿí”gЫ¾æS~½äïÿñ-ïì/¾ÿý¶ùíöï·¾ŠÛ_ÿð|ˆ‡\Î_ÿðŸ¯ùÿ¹ä}ùûŸüon0þ·ÇsYœþú‡\Ü¿>ä‘ç_ÿù=¯á÷Ýýø|ñÏ‹Ìëx¾äCnùùÉŸò•¹Á|ûõò÷?å±üû-1øÿýoþ%íÿþø·Çóv¶Y>ÏÇtÉßþþ’ozÞü5 ä~Ͼ”ós©<¯â÷—<°çÒ8ÿçõ¹l·ÏO¹ÿçk>õ—óóú¾d)g1ÿûc–Ïóï÷¿¿<Ü#KêŸòÓùŸ|oþ6îo§çbÎKxÉ"üýšoËkÏky¾î{®æùç÷<öçÿn³0»e±?÷‘{ºÿù9¯!OæßòÚó¿ÿïó©Ï%rþççüK6EžFþ6¯"‹öù§{>%Ï- 8KÿyÅÏír¿çÞ~9çe9déeñ>bû\H÷lœ<Óç:fƒ}ÿŸçÿßåiféåóþþ§ÿ¼>¯sŸžíœŸûÛc“ ÿÏ×þèóþùù¹Û¯÷ã_þœuß5÷Œ¿î»¿ÿþh%>wÞ·¼¦¬ñ|Ë%fÿþþ\k÷ìßÜÌßNY,yØÏÏ»ÿ~Í.ûûŸþòç¿þáù8oY‰ù¶ßÏ‹8ý²ý¿?þvÈ féåõçå?W¯©ûòÔÕ~MôyþÜsçUä…þv{î™çîÎÿ=÷ù98;*Wžù¯ùÏ,äJ²üŸ{æ˜+¼ßs}ÙOÿ“]ûŒJ§çUó0óz²ÌóÿóÕ=þ²Už¿³ÿ÷Çlœ|câZžZ^|>/¿õï·<³üíóŸKë”È•í“×—h‘ˆð|¦Ÿ²•žï£¿‘œe‘¨÷Ÿ×,‰|ã?¿çUçä}dùþrþ×—Üuî8$‘.Ë,¿ÛHþþë¥ïåùüòFÿþ§M^In0_ÒUùž™Õùû{R^Ëóå]s™Ïð9a)_úü×Íûñ¹®yŒ¹ýÜföL¾2k3¯ÛRùíð¼È{nño'û<ßüû{>ÿ·[w–Y–À÷ÿÉ…eg<_ã.¯îo<ØüÝsq}ìžx>ö„ú¬úçm½ä‘ä{Ö³ã~9çSžâ¹¼ŸÆÅHÊúÏ5玞/ð’ݘË6ÈŽÊî~Fš[‚yv¾áÕNN¼Ê Íoå¹d§vÿ^óiy. ùù×D†DÑ,†gT¸'^<#Ò5wû|:ïyîY¶‰¢k =_Ò6‡Ás©œó~9ç Íßf!=Ÿò1‘ú¹Ny "ažýó¹¿dä»ó»YÝñyÏcî__™žÑø˜˜h»?Ÿýs³oòȳž»ñ–]ó æŸ…|_žKÏÉ™õ˜WôÌÚÌJ€ÊKùíöü×k^Z‚¯×ó¼¼—„è¼²}³C³†s;Ïз~Éd÷åu'¼åAd…ËKòpr¶fe' þ¾Ò²àþù=ßžúÏïÏÏßç{òâóšóØòÐrNçç.s.æÑfåEþíáÈÊÂÉ1Ö½üÜoy™YV²Œž¬ï½ßçËÍ'w<Œ¼ø¼€ìéç ÛæÞò›ùÉdP¹Î|G£Æ6ç¹£á~ÌÍB{žâ_ò»Ù¿ÿ~ËçI?ãË#Ë18‡hr†,Ñ|F"Üs'_¹²|òý¿^òyYpù³h&Ê3ó$Ér¿Yü6Ûó}Ü6ÿyuJ²ò± ÃùµÜô3ü_z‘×¼¨<¤„g|H^qÐ?>åç•gf-öL¾J|žñà”tÅm=ãÁ£¹À>Ë&·ŸÀ›þ×—\X>)éQö]^w{–iRþ5K/k77+•)üû-ß…™Ãë¯x¾îKöJv­»v^ö÷3¸7 =ó»(YA®/‹$‡C›lˆ¼”,Ìç2Û5õz4idËòɱ”´±yÇ>{0‡]6Iwþ5Q%ÿš×“ÅšM•C¤÷sKìÌ^ÍÕ'‘Kñ<Ù¿÷¾æÄλÈ3Ï6Èf'çàÈÏeqÍûzÉ’ÊÌ«ÍbÎrÌw5þœe›øòOÙ¬¹ƒÜüýO^YÖe{n;£W›\4ë'Iú–ÏŸ²Ïòº³/³+òò²—s‘yÅråœmÍißžrAÉþ³+ó½ù·,º<ˆŸ)¢ã&a8ÿšïÈcè øœoËžùÇ·Ä­<ÚÆ¦Ay= o§çÕ?܉£­j¦Ä(!҉إrëÝ5øf—e©äE%¼æ~J»€¹ƒ~ÏÏß&ÂeYªÖŸ÷öÖJä‘-”ðžWû|ºû,ZòðÔI_óœó½Úš*‹¤µy¾©ž´óÏ(pì!qMüS™%‘ôæ>Tpùä<ßdyñ¹®üFÓÆæ‰ÏøÚúç¹6Ù¿¹éçŸbRª„×¼”dÍù•ÜFJ²ìÙìÚ×{ cηîýág‚ñ9;>¡/«=äð¾ee&väwS&nd©5òj“@år¹Ï×ø17Üüþk.<Ëê__ԿݲÆeî ðyy ð¹ÒœµÉä#Éêa’éçÎrxÈàó(|ó =WÙ ÒžF® /êœß-îÇd×=²®=NÉC’PåÞ²¤z(’¸:iŸËûµ[à¹ë³ó’g<ë€ï½âDÖ÷„÷öœçÏ}J¡’+HÎE£:éS8§äÎ’I–‘ƒ&O0Y}þ6›)ËÇvÎQ™¸“O±%’«ô0¿dKæén’Ó?ƒå÷||NŬöì¢T¤9mZŽ|r£Éò°²S/äet©ì³óÝñÏÕ™“)ÇŠ‡£Ó”D%Ÿ‚¨¯â˜ô-'\‚oœÓ*¯07‹!·œà›p˜+Í.sþ%Ïnï!gè=Ë& _Vuî#ý EëtNY¬ÍŽ  ¢îéSA^@L‡ïÿ“À›Oî­þóRmðý²<óWÖÒ ã˜W’CNI˜§ŠêçíV$?È“—“嘜?Ëãš¿eÇf'§`sT=»mJ¶Dåæ6»dù½¼™,ê\]–^ÌkrŸÖÛÔ8yy2ݰû¡/yÏùwIê&§PY¾È Íž–ç!jd$΃ûí–Ûï«K!Ö˜ê³yï-ûRc(g™ ¾—{kªyή4ýëC‹¥“]ýž˜ÓÌ|ŸVÉ,ŸÏйßnyØ©,Ÿ„Í,[9ðß–TA´„ýì2û¤éѹEí.;q ©{û˜å˜»Î''·H ÑÎÊ÷=‹Ì¯Âgòûè«S7¯¤wtãrìLâõ–Nec9æ8IJ—c1ùF6VRÄDÚÜe3™}zþ5O7-¤”³yY\IÉÓ±ÉFKi´8¶ÑÓÊÆ˜ŸÎïäÐÌÖÍ•ú”dsù»,fÛ%Ÿ˜'´IøÏi¡Í’µÝ¨›—|²Í‹CwãÃNJIf©$Ü$Ì*nçðù(’=ä sÖ&–$À?â%/"§iK–«ßí¥ï†Û#{†Wé`þ”Ý”‡˜ ßóïòüÓ-û'/O™8§ø!á-jšºëù{ÎLÞ®Û—…”ßNiÔ*ú˜:•Èsé­ÆLº ¿jìܧ›?i‰?Y*YR©òºؽZ¥'F®¦Ý·S¶PžùóÉ4JåIç ÈÏ? Ô¯2ùgñšŸì+?—û´¸²’ç.uSò¯Y® ‡xŠyìʇÚ$J Û§»Oɲþý}“s&i¿MȽ$£õPÒ¬‘b¨³Xr²g'ç´ïWÞ²Ö$ù­àäÙyHÙý õÙÛÉ7²¤²[’+kí&@9“uó‚’{gÇg®Q”Ýÿ³ušÖFöbŽ¢<Þ¼¬ì¨,Bõtò޵0ó·É†LS¨±ó|r»~·<Îdæùÿ¹ ý\cÃÜñý˜]¦‡‘R+{*»VµŸg•oo:øÚEqKÃ*÷Ÿ”§‘ç"AsdL²®mîéGû{þS±Ü…Õvo{8lNW’ƒ¥í¢m>¥qæ’Ô/‹¿Ÿ÷9F6q"uþîYfýæìžÞû{SVh_ÏYêçA¤á’W’ÕÛTè”0™Ã!?ŸÌú’ ·z?çÅ;ÓUäãÙoyèyPY>I˜òsþçµè_5úÖ ß6nÛ~¤8KL"×þÀA®’×–ý¹OÚ#ÊC´ŸünŠÚ,†ý´m^\{_÷>./Y÷#ù‹hÐ.É!Ë&޶mîÙ‰zMŠ_Z³·óî`KŽž¨Í“sZŸÝ˜ŸDXþ\òó|³»³às¿Ù9³³Õ”ªédß&FHVsÌf %*%ndq'õ³@ó’õ ô_t*“@f1¦ÖȆûûŸ6]‡||.,ž›¬Ä„ 5gXn*áUk7'7œàDÌ…§¢7¢HÞ™Ÿ¶Cv.4 œ<º,/mÒì±_}ÇžÄ[YsÒË•TæRëæfL ðg>/¯,ËÂ#iYy\²‘.šcr•î“Çž×!i˲Î3ÈÞIo®uÏÅ PL) ó:²ò¹‰9Z6ÔDK£C‘%¯ßFmšg“i­ç’Å-ýÍòÌõåJm±Œ»²%-ÚgÍkMÜÈæT„¦i—ûΑší˜wé˜íaøjÉ$§QPj&é9üß“‰lòâìË6ywJ»Ü`Û<œD9»g÷-+/\Îß&Fd¥æ”4ÚH»(+X kÿ&Hgáå’6³:[ùœ¦9º£I²dëɤ g²º¶I€ò›"’? ú^cQ«íYÀY@º-â¾wI_[;?Z[Ÿ }rÏù“ëïc_Êë:bä:‰…ÉA ÈÒ°ÊkÌ·äœÎ÷Ú¡ mµ-vM^Òãk›ölž_²‡–Þu>£‰Ü6ßšE˜+j_ð½ýš]òƒÜuk’¶Ÿš¥•Ýr3ÏÞÉŸb¤•ÞÃt_¿n$YÙÉ1ûCׄkU¢~“ê,Ó«Êe™—½Ô“3=ƒ†‹@›b©ü[ ×$Îá”i-ú®ö`öQG3ûŸ™¼–ä¬ÙM­a?æaK*óB³øRc'0›ö¥šHEÐÓí ¥¬žÈCÌ>“ÖJDz,ÛgÊySm?ÏéËŒY_ì6‡W_ã!ÙR;ô¿I”³:ÚÊpzÙ$¹ÒŒ˜r¯ õRÝ´½dëùÝVù—\A^^®&|î!{>2Ì”ªYÉ(DÛ~ïmjµwsS“‹¼Í|r7S;¸y¶ù×4ûó²™Ä²Ô`›4*V{'%x´ò¸•xÙG­ãÏyy­Ô/š™­b)¦òñé‚u´qIj• o­þ’×G#!/-!-«3Ÿ@¦ÞîØ8g÷%祘äïr}é$(»[Ð%‘ó&=ºzìæiY„m ]œ}¦ָýkÖ–ˆÔ¡Ù—ž—Vï}è)(5­óœóÙ ÿ{)&ZžiGÎ÷ăì÷l±¤’-׊HP7ÆšSþ%EJÉÔ$Í}¶iˆëäZd?bD"_z›ŒÝ[þ›H£²Zs[¹ÁÕ4é¤í®…§oHxÉ ÛŒò‡£Ý‘ÆŒœÚzÎãK@6MË'w"uÔá+šåK÷Æ($/¥ê4¸‚ Èùãš\k{i—|bÂ5„KZ4m•sÉþÁ)RéH4Ò\ÅWÒGò€ÔQÈú©×¤µz9¼ŒÉó)ÙÙ-<y Y¶=ªîééÿ˜¸Ÿ³?3N*ÈåÒìVs*‘µ5Á.‹!¿™E ¹—œ ¬¦p“ÎsÍÝ·3Rƒ«ò¶fŽØ_ŸÕ1¿m°žë6¡Ì›èqÒÙmú9÷ã&-ÿ˜Ç$°§êíÙºp¹£jZ6¬åhM*âÚÖØ¥šmåpH…›L!+Š&7Þéá~õu¥ I;$”æØ±l‚k™î`@S‡<ÆÎ+:©K 5KÈ÷*=³²;UØefèJᑚµÿrO¤IÐטN–¡y›W‘WÖnÅE»µùøÕ«PÆ&IÍd›¤G¡7a„“²ÔÎËsh{¬ß¬ˆË·%óÈNÒiÆ1sÈ£DŸ¼ –¢Ù¡"Cî]reAYÌNq3Ûj5¶D=Fá>]Çl@z‚†ay«÷û&!ÜÌøY$µµ¢”%`”’½Ÿ•ÖÑK˦{rôâV9³SrA Òwóxùn ¬#T`.7A·éLÒNŠØQʶAÿ˜Wn’Pœuš ÏŠý9‰ë’ :æ«¿KO¡‡×ivóó쓾Òf-íL¼+œ~VÛÌÜ•}žoMØO’•göa_ê;æ|N†âU$g(˜ë‘'©fOšgTÖœá˜(÷›—­X†¤ ÍìîØºã‘´ét;³2¬DÜ[*µÖñ¯^Ñš%$3qƒNÔû—=$bæêT9jòw›„ÿ7ÚW–ƒ·/Õé`ÒÁü¥õ¬›¬ÏŸP–8é]^r¦KÎÐ!L±e‘?÷,œ3{?¶gõ»Áeq<7ò4p´‚Jœ¶ç‹ù}‚/ZÁ2;ŵýz9ЀQ‡dR8GRÛôÚ¾í¤|%5„Ñâ±ÐÊ¥Y‡"øÌ%o€'‰RôTÚh9åümè¾%˜çlý1mÜö;ؼ´Œl:XxëÃSkI{7úœÂi¹» ® õð©v ¹fãtoŸuDY[ 6êœÄ¡l¡…‹Ì3U"oºÙ¡YÙÆ!ù5ÀÏümOÉ „ ˜UE^|^£¢¦Qà‘¬AnVlÏÝS^£Ó~%wöLG€LžµêÈÈ«…PY'Í›fÈ—éB¦Ö9ØQ¶Ówÿš@Û¶{Á„2ɬ#)™¾é¿4(£“¸›¨’{kßâ¥GÜ#/@ï¡ ¶‰EÁ§â©?åTï å»NB° ¢¶jÏþ‘¸a)Û@x‰ZWYfÀp)â²—“µˆ¦‰ÏJêÄÓD­¶Ú¿AU¥W:ó”6±ò†´øcÒ]úÑéÝ´ÿ½̲N@ŒVr×˼·±ÐŽP¡žÛÀ öÀ9k' ܧÁyÊOÂÇ&jï?£†* ÔYÊ’Ê9˜Ð—x3«PÌï$§î 8š½·\ú”[Õ0MŠcÖ8&ÖiËÏæ¥tþvƒ;ÌŸ‹$ ÚðêˆI°ÍƒMÆšëËYœ˜ósŒ%%uÖæ)$Iµ“"jj?ÓÚ»Ú%÷QÆuõKÒmÏ@:?Uœ`³u¯QU‚ÁWêŠç’À²wOg¿¾8™Šÿ»66õëëËoxÀŒm”¾O푪\#²-•“öIöùB ¡)äw[Üä÷IvŒ8óX´ls€ìû/ ‹ÓÅÚW•ð*gHÞRDãV&cÄ•aøœZC‡ eéNG]ÍÙ̼=Á«Žf3ýOrŒ朲ïÓä=dtT*KÝÒè†ÿfÙûÙÁ9²rGU€"@­ ÿæú¶K{ŒÀÍ„T~¦ç—^³ÑÖ]Éh$ï¹PÒŽaÛåó”à4×øŸ¯§,oöB^xƒ$,+Ñ£ƒÄÏ ,d³hâ¤j ^Yu\›!%c4©¼j ·žNHÝ™•·©óqºû;)"<\ÎÜÖ ™fE«\Ú¡€ÞOYZèÓ5-9ÕÞ³Pó8=öº”Kz©&¦ãÿ%wÑcâCQŽ|}Õ5ÈëÉþ¬´5 ò !òwÚYÈðÏ3ƒLí2„ü\禘Ù5v:›œkÕ©b²LÒ®é]Þ‹¿úÒxp–IÌ ® .¸èÞ™aA{Ë'ÏÙ¦™ÅQ§ÒÓmŠX(îÀòž‡×´S•êü…$[Õ>Ä“\ÜðÞÉ”ͪƒGÈGæ2WÈM_Þ (àÔåuóR kxף립¯’ÑN{Ú"TokiôHΰÀæsUÉð_P5zt}`52ZG-«ÒÉß+â:KÈ ù”¬h¾Ç´Y>š$ûÇ È«5ÅŠ‚œM êsǽó««Ê‚ÉJM’}›B¶Mr0°Cކ¼³‰òv¹Ä9fÛY,¥c}®QWÖÑwÓyŽŒd‹Ì¢»šçš,(qt“°‰O·o ‡W“½¾¦«&%Œ@g†g‘ì·„òìßüI •£!Û0Gî ÞÝÆåH"+¦ "G fŽB'ÿ†ÄÕögG¦IfÚéw3ÙÓBsr‹,Óc˜Ü‡Ž¿‚¨s¿[9I­5 "»;áåñýœ°¥dmSIË´½\°Xv£®_–ŠŽH#ÍŠ:µU³šb°Ò™hY·Ë·¹ó;_s—Rv^Áò“Ó@&9¨´|rˆ ¿¤|Åý˸žK‰=wà–Âë缾\lÅ&¯?µkrL=úÂ3O ¥Ÿòšò·YùSÂfI]ÏEAË5eÒ¡ZmÈìãrßÁ>Ó!˜Ùb€Ÿ[ù餈¸ È ŽœïšSfY‰~æyŽü–OÍ)i„“ÛêLnZH0‰yñ¹ÇN8_ šs—¹¾ì´§ÚÍÈ £Ìßµd|d±âK4ùlÄÒ8÷¢´¦Ú\¾i?•6²IC*M£6!DëfÚ63z¤çNÔBÙ¡ZpÙµ¥®¶ .¶¢Q, ASZ=…,‚ÄÝüçPÚvY¤ÅEvÈ.ÊÖ€ Nĸeã¿&¤dïgÿ¤¤ð‘¹US<èü$i‰&¡ûÑ\ªž½’± Ý{A_tò;,n.á0/Iˆ,Hì"e²¢-1"KG6…×ø(¯B= š5ål~Ÿ]›{k#ì Ø†¤§ãª nh¬à-Xõ¼xJ@b ö¼0¶"ÊmtÍÿãÛÆ!·UR”ÿ6+§Qàž›î¿žµmÚ1{×ÒÉ«ðâSè”Ò¹Oi”u›‡Û c‡î´Ëêr3œ£¿ì«^¦ÐrôÐÊÁ ¢ º¨YÈ1qç¶!< U\…#v’ælÂfþ{ö°Æô*ɰesL``  ùä¡” °hëJ].È+Jž#ÅM̱˜ÓÞQ°™P‚uÛ‰¶àtoE.íµ•ï0²D +»Ù«YFf,0ÉMH}DÂBi>*c×d`˜“ÿ<{ x¢²ÏÛä2eª‘©z Qø¨=›ž˜š4gr?¿½Y|`b &ì¹é?f¬f°º÷a!°ìÖOY2†¢ÐàÚJ­í€ò) Üù™ANìì´|›o 9‰[òœà ‡VÅ¢×××]Pµ&o;î/-œÒ7‹šAÇ:9±§ÿ>­C9Л$12{*ßVNÐA¿3ß]~Àá\…Q…ƒË`€†£(æä9|—¦ð„I034Ù¸qîÛûÁ,"’u°t×mL´ê,â½Ü‚žû`y©óDöG7c›<ÑŠIÉ.4WƒÊ+ÓÒ…"ĘkîŠ `œ”PÚdãXXrËÇ E³|JD¹€-èÆg'4}{ÞµXÁFSÿ6Û¸&g˜ ÿ¦‡˜eal 9oåçö¥j¥´a•ñp×-ÈO !¥ &˜˜W¯*ãÁ½ét‚±ïRnq[TâµÅÙWˆÊFQ˜ ×ȽWúQ–1é¡Qâ½™JJòhò;BY¹ª¼¥d(-÷hõ‰3zªbbg e7§«+åÔ­(k+À}3²ŠlZa?Úoû&)X[•;½>`†Ü¾qI)€à6¨_d¥·šx3*)¡É¦#Æ09Í‹)(¿µ®Îëù š+IêYîÿvš­Ÿ Nµ¤…ÅýwWÒcº—ÒÒ0mˆ¾W»ã®Ž&'‘;êJh#j[\ÄKq — ½áj¨‘…HL\C.[#‹É8¸à’:&Nu¥¶Nv,¬¥ö‘/giÑzìt%&ò‰°Ù$É–0'J<;åóš|ޣؙù]Q% dÞJ—/[«ÍôDèàn›$Ù•Ý¿Wâ)žk~Ĺ]HY°äžÿ»dáyÁ9me¯y¸ég=Ë-.JÉêä1})hX”E ZIT^VLê 7šÐ{4.ÏHI*QÁR`%@æ1M¡h­tM#¥PÌ]Nñ,ï<Èf-[ ¼¤QNÝro.É®ÛbÝÒéÚ™ÇÙôÀ2{°'îµý›ü S{»Êi ¥òt±t³àoçM“T‚s`&f[æˆ^ão½U=Pœ`Œë¼‘,$ØÇ, 2Y@ù9ùC0{=#b,ÉÊW/¯ aºX÷[oµ@tž 5Òo‡iÑÍ9“‡€í,ÃÆG¬.Æh¬Pdë® Á#º²:=A,ëÈktUN°ÜRBgY'H[ñhZ™E]„Òµà‘£“44W…Ö’¬ &¯<;r‘Æ0;_—½ñ¢žqÊ5º€–¤AL´k¡ Eyµ­D¸ÍMÍXti-Tway‰À¶N*ª,Û|…ÌƒÖ akDzMQò>Sa_«÷ÛVÿ¨›¢¤-÷²Ñ_ƒIÍ«U7"båÅ.jhÉY™ìUèÅ…—ûRÂÖE£1—YT] Ž„æ<„öM`!iÔ.ðþ¯v’ *sHRü}¹-XÉɲ²ó¸SȲ¸dÜ¥{g^qIz4­’Æ£ˆ  éÈ¢ÁZÜÜUÑ›j~ç@I¢Ù!Wø߆r¥ƒÑ»&6i©Ucú‰˜•µ©UQy Äךž–>a–iqÛ6‡U(]¼GÓEìTိ‡’må°)Ø­Y ~,!)ñ_ÿ°Y€Ngcçjm²dLYÐ÷­ ­—»°&Në#¿¼Ã:‹M{ξ¼éÝðŠæDTò&3¹(‰íèn‰™%€ŒèšB\®o3mÉ mM$ç:óý-)mªJÓÜ’E©”He´yÕ 5ù+IeîÞˆÒãxІ×,‹’ÇNù ‘ÈQÞO¯*Ü&—Õ¬ù=»$çGö…Þ0t/ÕtòçžAÛ%€"ÜÀ¿÷zÿJÛyD¢ÚT_À’Îøæ5J¨ÊºØ{EÅî›ì|sÆçAÇtôQ^ ¾wËœS^9½¯\½ú#˦SŠ"käÞ”3ÚQ¿]äroKÊ­@¹6‚²5a¸ó§t[ïìø!×¾ë…k¯ M‘ï$b–/yiùzÁÝÍb èUÖôÎFZÚ©Ó¾ãüÜq>Y•䯛nGdJ‘Y¶qÙÓ̦ªÍN‰ãˆéæ—°LibmóåãÍ6? (‰EEìé ¨‡™ºÕ$ø{´ç|ÉMç²IˆÝ[º5Ð#`÷ì¾éä¶SE—u»_ðÑ0@Rºå…Y¢þ¦ ³˜˜EÂlöÿ‚)O¹@e¡åƒs ?¢7‡.õ"²ÿ³D«úw$×Eý¦Ñċ߾‹kÔÅÄ…• r]€üÙ ˆÍ‰­MÑš¨—ÿƒÎ/£W°pyQ¥‚ퟤŸý…òQ–q‹E4©عåf7,¹BÛ÷m5½®–YjK€à_âÔ÷ÿÙ$G÷ÚsûjĬ©]Ñžxæ@¯ð{ä¬R«œïÙ=òƒ–P!wœi†H‰2ŒÐ•jµ}£³“Wë\íc:w®ö‰.bÅCø¸*’Û*¬’{Xú ª)‘cA©‹QúªN§È—e“»4öÒyWãæv–ðfŽXñ ¼å\5JóØ‘c#—%/nåX¸IÃ5ö^E.vHÙÈ–ª{ r}Gªy•¨ü2Ë©ÜÃI%ŸÊ¹èÎe\om‰äRZM=ø »>õ½—´ú‹ŸûÛi#Ç4NmñÓVÑ•?ãôƒuuȆ²ÌßVþ·¦’i@œ£¬0dªì³L ôШúȱès20 õM/Ï7É^yï(³´íÍuJ‚F ‚½cäÒ$pjgô5ºœNUŒá•)$!£!šš—å€.ªSºŸ2eáœv§¹ò¹×tÆ"Vâ«®Á3aýòóY¬J_z_2rE5⊈SHøVW²Š†•è(þ`±$æä³I„Ó%\}ÇóŠQôÞŠ½LÌiÅ’L'C¾ê4'Xªî¬¿éÃíTšùBù©yYG’¯÷²“Á!‚Ê*L\êd¶X†Ïq4OÅ2—× Õ–)Tl^G…V/«°ƒÅ_Œ‚F®“Øf•e§i×?4­Tã£'H¨q$£8D©}³HòKUó9Ï%{ÛÜOTI¦/2Ðákw¿‡aîÓSsÜ™T–”s…O )®jš·yö6¢¸;ýÎâ_¹Ç!±¾a"%#3‰Iò‚‚kb‘cìTZýmÓÚƒ)¹´q•dzx¹}la©ÕçMPÍß”ütðÆ¨§à㱊Bðl1µÿ´Z®dÅþl Yñ·¤@¸ðkXìu¾ÿPÉgO—”u4‚-”ë«E˜x% M.¿B©¶!ˆ4€ÃÛ{x´îÙ‚´õY8]Ê{ˆß¼Xlhb6íÜVG®Ol§!4š"滋ÜÛÂéÔ¥Ô´¬p²5 Á "4SIJÆ´HlKv“7“ÚI5Wôµ¼…åyõYRÐ#@û ÖÑâ÷f^¡Êúå¼É ’SÄÍÅZõ8(°û;g§Ñ3rg4o×0@TEßÙú‰N!a©N…W]óåæVÉÀLtó© É(ÛTù¢èK‘)”R (êà˜.]Gº÷Ùƒ=íåãP„°If#h±õ¿ø Ú"9rÇ:‹Õyk?!s·¤ŠÇ„f-:úêoäºLa€’-ÚBÓFÃp*œí¢%UØLÄõ–hæy’ƒæKÍþ ™ÖP÷Ç…)JDKÜÐûWoåÎs-šÊP¢ûd±fƒée$ùÜd]„ '’‚Ó«PòV½Ú}^ø… ¼UÇ>§i>Åiß|ý¨{IŸKÉÚ<â¢ç–sÚ!ÒÑÉ=ꇇ Õ”ÚÞô°’QÌbøí½9ÇX1gZ iøDŽ'iMìtYÛBzhÃÀ2哊&8cÄæ (úøDüRbÈÕ1Ý ¹T;©w3¾.ĺ$®ùSžuUn€mĦžG€(ú f•Qi3Âk4XŠÄeú…å?ýìŽAˆÇ—ñÙ΂â'Ô˜¬Ô¢3‚J¥gÞ…ñ0·Ç- 6¯«I”ú—^FE*8ÀÙH³h7f!ÈJ¢…ºv~#y„Ì\µä_שå9w™–ý–ѱ|WŸèØÅu.³xøQ©”$oÕ^lñšë3EÌË«jèC M‹Å‚p{¡íL\+ù©õL%5:. ٵŪ‰ úÖ–ñc1• Ç_ÂÚ}oà´¹ËTk;i+¦ªTý U';0ßÇ “™RDÞÁÀráùºM˜¿PÇ 6H‹®MÓ7r¨„œÓƒ= EDÝK­HüïDhÚ¥;ÓÙ!•; œ¥Dq;Ë6Ũ+ÈÓä¢b4=üý@Uö*®ð%­uùE¾‰ë±ì 9ÿ×iéEnò¡Óê«,â7'†ü\Eú‹B*sòkÓ廦Þq(mô‡2†vôæ>0+Sö™0$[@WÉ5н/ÐÊ )«’­²ðK2fÝ»³ol Á!ƒÆt`À“….Seg,‘&‡ŽLí·LîÑgŠYÙ@)-çNzêÙGÙ䨼 4‰ Ó8Ð9ÖX5{ב35qËR®Ê×5‡A[>W([ËcôÿnvE÷•îbÒÐöêB:QèLÀ²Ï7æªúSW€µeAè…Y1*ÄLãº>„)—‚ws•+òXž ÜÄ-yM"Àò¶Â®¶FRb}Ñ1(¦…Š^ˆC(ïÓdÃÏñùë~¡…Yć‘«RMÉ—Û¤š?ˆÝˆ<*{¾ÅÝ;á‹F&Àƒ*¥ÑžQ!çG‡Ê¯&ßżŸÉ+ôfŽ#¼²λ›g/x—ž~vah¤Ž*4ˆÃöLï°õ ¬=Ý!Òky8· —æˆê « úE\Kš‡ÐÅ c {R"wôU[1•£ÖÓ>ÛŠ*«öl6D¶KÁ_7bÑAJ¨˜yãWº¥d­‰í ç3Ñi*üøÚšp?@ŒÌC±œ«ÓË@UOÙtb|:̃pšfëLL±#ŽÈ¶¡é̃Á&b'ÊœŒtó8—ÀCW•~4mà5KÀÉ 7yëc=—<ѱRz×s ÍJ©©Å/°yØ. 2ãÑ3º¦­Õ¤É €†§d’{3ÓKxRó*òPµÁiïéL£dÐ=ÍÃöÔ¨÷·ÇØj‚2²†U—2™öxK\{ ^ :,Y¥W¿§d¸¬!(€ˆM½ËædyGâUjû‡6ÚÏYýD½Üdä¿$¢Ý&û ÆßM#g-®`‹‹Q1O&JÒ›9¡yPÆý9`LŠàÂ*a!\–ü¡ÁHÎ(ž8¹pRê9Õ¼Rìa=E|[>DÒÆ§ñÞ"êäZÄÄy,ì¼MÊ±Š—}&—T‘‹UBVá2†ø y7AÂìc £fñ"+ÖrN¢ËyŸ×]Þ[kñî¤$•|€r†Ǧ­iGaé‚bêäçl´hÉ)b™’aX‘a©m•Ù{’¡à÷©sØ,#°sl@ãÓ¼äê ìõ ÐT‹i).Ï¥Œ‚»Ã°¯û˜ É há"uN¸ABy)ôg‰k¥|[¥ .ôÈL7»@¾A]ñ "™¸»ú*í°É<͆uÙ<Âh¸o ß>ÏRÅ´Ë ‰Ê‹özÍ(‹Û¬®xÑè÷ªT5-’5ç¦Z¯v_”ò¬)ÂïÒ]ñI]½/ ³GËO(ì\.ñ9ÐêX€Pglr…Ë5=Ô™0×s$´%´Õ[O6ßÉ^ÛÇ›P1/+àÔ çkn`*ÈÔ!»ö~<´->D§•õò³ûëÌÜí‘«`î.OÈ<4]{M'mfø¯8)"ôÎ¥Ò¦ñ¢{×莸‚@ž‡É^GºW‚˜í@\q®‰9íg–öEb¢ÚQs»²Âh)øY#»È®Îa—-àfaÆF"&xÛõ7]NÔnÃÄÆÑq¦(e¬Î¼Æö´š¬å"+–±¢î™jÚ•ÆESK2/o8ó_ WÍ&Ö°SÓ)IÛLXÊ´²r»€^ ŽD35#‹:†Õ4¹ ÑýÐóà~ á,áJ]‡”[a5ž­V˜"ŽŽŽ™4•nQ\ì¼1ÿíÝ.ÏSk®%“7ç4¸Ç3G 6 ÈÞ2·$u É;d\Õ¾ £±Ši=QGF3ŸÌ!AeFºIU9‘o@uÚØX"Óµo0zä\U&,£æÕ6YitCNôDáþ&Y.Ôœ0¼2n` ZÞˆÕÆ­Ä™@.’ú.ðL%µ¼‘c»á2àA6[ rÀÈʨ{Ü‘>-?¾¶cnä°¨#@êHÐrN[f"ÄÉM“+ˆ£œGƒðœñC¬ùâõd™9RSúr0¤‡æ]¢IëöÇmÞÇÊ<Òki{çlÄè…ðŽ3¥ãÉ­:ê߆hu¢ÜEèÉ{3­^6©\Á·Ð†CY›mi ¦Ýlø¼$Õœ¡$Ôa€ G³TF|Gz¸ŠAŽ«.ËȾ³Ì‚ÃðYDç“ѲéwÖð–tU.à˜ðª·™ÏîÃ9@ê¨Éa€èhÁêòׂÁºÀ)b‹ÐÌ´ØÐUñûFí@5‘Ïf·›ã¤#œA©<'Úåú£•­<¼!pÀ2ÿ¥m¸WQ™\”MyÖNÊ6 £/8V#×?X"c«‹B½!×L—$‡Ö&_»Ðê,Π]T¤¥V|_})ÂqxåNFV¥'´*7€û×г©CZ%ð4y¨ @ÓKü¨¯ò]OáÙ/š.÷mú¼™öµvnMܹþÖ5§Œj´ÉfOÖ'®+ŠºF''D,-V×·`oàLêº!¶è*úY˜»Y ÊÄò÷w$]m=~ª(`&v8çú:—”}¥‡BÒ%ÝKŒ TyUúšäS¢_Ãë‘¢8£ä«Ú!¨ äFïn¸ª‚ûâÂSª.…༹æÃívöß©XgÕ±€ž/ŸÁȲJ—hãh,ÎÖT0á­þ~Û¬} ,ú¢ìäÝXpÙ$ûÔüYM_ÅãûÂóœ˜ö~"œ³hè0ùLŒ Åzd&{f•Ë}dNÃÙÀ·J£=”åü õÇÈÅ1[Ž7¸oä@’Ê]†8õlú^ñŽ©œö-wA`å¹s³HZê3UX~ˆ¦üÙÍ!¸"npÉ(Üë‹ç¬•éÙÊ6³ Ã(û͸Åo8”­= ÅZæÐˆZ›v†'"Á2N×ÑÌ<¡VÈ(–E«Éýû x¨‘-ˆ* :ÕnBÓ _@Õ”²(Æ mФ åj­j÷à¼F¿‚4Aº’D¹™0sro¼Ôò-©ò™e%êi¼ ÿykôÛyüÍ6©Ïa´@ކGÕP;°Ê@„Á‘Æ!¿lS’¯žÁO»+ç~‡Hmϧÿç Ê›ar¡Rrç¿Ý6~-)Ȳ†(DúÁþiÎÆ ™Ó˜+Ó.åç8vÐÿ+–øÅ¼NŽÎå&ó(=²¬Itï’?¿‘3É«]gTòHdãÑZ[}%Í©ÄKÿËc¬6i%+9H3`ò”Zñ@)/Æa k b|¹AÇKéx˜b푌„ôMÞáÎ%‹Lêò¢…Üâ#Á@2hMdWÓÊ3ÓhhHØ(Ú"¤#Ø=“†Ë$„sÊ’*”«¸Cð[¼"NH€»•´:™¬÷÷èà‡¶'(?“†— gkÒfyhÒ¤–ô5ˆGK›Z÷V/ª‚Xɳ¤"ó•.Ý^­£ØGþØüóààz²w€;$WÎkGAjŽ’°ÁŒeOOX~#jéZ•zƦmÃü5™syÌUÌ#f¹?ÑçGM©Í›¶q‡æR@Ï'£²C:Aò$avÖ&ET¦1Èâç aQS÷ïH¨©ZÞ‡ßHBªã_ÏÓ&ÃXصhCëEEͶδ Ĥ¦Hí‚Us@h$ço7Ë&…øK³ÿbzÊÖyPÑ‚VÁ'aŸÚ;`Ó ˜íZí}Qñë(óÀ ãÚõûÖÝ]M½ëd¾†H ‘fIvÒvÜA O™Èë™ûm%#›(h MÙ‰+ï,,Lö"ò⦭š•«+Öè—jØH¾=Àard¤>7_ 5®»¯Ñ”Ñ–~;ñøeå0®$ÕXg àaàMÔØö‹^^²cõc±»[”1/܈9!«*†œEOèzõTfƒój” ÓM ê—óŠEs`IÒøXøkÒð )…IÃæ™/ðsyã䳯†FÝ™­˜³׉ˆ±´,ޤÛèB¥»àN%DŠ™P\“Ä{qß(oÛeˆ”¼÷È#;7ÍüEîC ádqMì¨`´pý©ÙÊËH®ÞLñPÔë¡´ëÏ`zÆ7“¡ö›WËÛ„`©,’œ0ECéx@O˜¬‚_a¤ÓÚŸYCžYYiæ…vÈ}‚ïuÎù YO#YQ¸À楇ËY jKdT»Rµ&~µk’ Wõ¾ú÷5yP³íÌ«Æp#6{Iç©C;?Õc:ºÝàÒ|ì’³„jP{aŒ¨së1#[•^ ,Z½´5éʧwør^X?}NÕyiÊ*áuò盥ŒjJ‘Ä‹žͨ¼€ad(Ul,Få°”¶3P¦Y%mÃE(#ú@¡dAðVYÊÍc5‰X»ã¿£ Äÿœ¤¤â;Œ r a˜qcÜÑ-Gñ5ï`ä2‹â±¾¡ÀÙo‹ú!1¬|˃Àpø·¥‰5õåˆ6óÇX'ÝF¶õùnÑ¢eSÏë@¢®@ëBQÓ¬é²à/@Â&7ÉÖiYV µ-7à®{d]‹!81iÈÈã'D5„»dŒ_°^éYÜP%ÐMÉ0¤N¾(1iµ\5ÑÇ€| ¹j9ÂvEþ|Ô æ"Œý€¤Ryø7¥7½fW'N×…†iŽbÑU<þØi@ÃÍù{ S%±ÞP±è|fÉÕê®jH¥b•H ƒMŸàõjsÏÕçJjuž?¯›|Kh5VwFÓ4ØÛ— á5´mé»çL°L¼©¯äs 1¿²¦ƒ#ʱ蹩FC¦o|!G “Pú¸Ò’,†BöïÚèÿ5aÙ#;,#xÀO„n³ªvσ7û¤"0JÒÚÈ¿gBÙÔ3l|‡ßŒo ,× 6NzwÀm ü²\B)˜À8…$†+³-x½Élf†²ë?^h”Õåd»dÖš¡Ü5d`y‹áçëéó>[ Ž`˼êŸh›ú^æØøÝe_9®ŒSb…®Ð@õUl’s¯æÙž­D"=ä2ý_° º½±ä.ðó4Bo‡E2¦6Е^^éP÷™ö¾bo±ý~Ýè¸å4Ð÷ö¢¢xS!PžÄK©"».S½ÒMqÄS¨™å“‰èl虜Ïn µÁî´ÕIJfQH³$e<ök-Ø2¥m¶ Pí¬6¤GïkK%é$‘†É ”þ ö*ˆÞ —Õ„lO)‡³Cë?X¤¸QQÚ/=Úž©ÓGúùs9l’çˆtÐV5Ž@¹ ˆ‹?¨cpZÕ‰>È¥²“a…`¶±8“ðÁ e¸«ÑM½Á ×;Jø‡D”DÓÊÚh>ŽY癆¤j\+¢^t_ ¥ÕÕêdÅ"R’“ÈOç'¦5Hc†Î“ ¡&Ú¨—ÆÐK”¢ÉØW)%iÞÄÔ{š~¢)ÀËOJç,ãÆåŒ2žO»È4\ˆÎë¦þglL;?ÉØXJÎŽVdæ³àr[ÃÛ;m;ªA½Žq{¥À¹Ë<ƒ,ΩË̓I÷ës³Ì,d&±žZëýúˆTlûÁº‚îàòPVSö6~ÃÕú ,»`âdvaµô¥©²6-Q¶¾’»Öçßéÿ®“©kæ¥üÔ³s+ž/ABƒáR“^ô¬ôxë0<Ê*Ææ~@¢È÷â#R[rqþÄ?Œ&Qv^†ÅÓ=|G¡ª‰üVh„„©8Ä›üäܘX”Ï4¼ü€<Ç| ´„0¥½oÛ·,󴈾ÒîÅ©YŒ=¹j»›É2Á¤·H/È@ia%“Òot¿ÅiUJ XׯØK2Ô‡$|FR8… »´TÚd*f€ @TK¯GÑ¡•Wz × è•a'J¥”‰àZ…a^kÝ|³û‚ÚX”ÎNÿsÉçܪc]µv—s=‚KÊ©ÆfÚÐÖ.cRG»7nÞ NkÃòIâv98ƽ±J2é”P­3Àw"¢È]P„f¿8À5W¡7ñK/°¬£+Œå´,=–jq}Ó.§L@7KEašÙ'á‹´aÍH ÔüÄ{%yø™Ž>fv¼×á'×$"ý² ¬ëƒºŸoû@DªÄ‹LÆxï·Ã†Ko•ºö+×9pEüñÛ.¼p MÆ´I3T¡iƒ˜¤eñC'«îaoË¿›ŽVgŽŽì“òuO:g5«)7(I¥›æð£¤Ô]v ½w/'•ƒÜALq&\/ E¾¤Ö ñxÈ”#íc%¡ˆ¨e¾ —åc\]Ý”ËÂ"Šˆz–^i‹ê‹Óưv˜7ZÞI%M'ºô:âÑëÓ˜—5ƒMó ÑÍÀ²ÐD¢z(ûqF{¡‰¾º­îÞW OÞcÓÕt/æ®Zxê¸õýËeGÇkµU»t‰©(ÜK›ù9ub¥€'C¢*ûh†˜Láêΰ8»‹ü’^.wLÀÓ/&HfµíF^U,YW° $twíîu½Ý·ù¼¥…ÔáË0þ`U6GŒ´±†ìWK«vä4?Kª'öZ áwv¶“´{ö³[ *jÌ"$š%»ÍW! ˜‡Öø*déŠÅÈõ/°¯ƒR{“ñGkíÊrd?êø_°† .x3!¤îÉ¥ã§Ù#)Ο”ꌃpI:ë)Œ`ÄgFލùhLö Ï|[Òf†¬cycë¬YɃgHÊ­§oƘÈÃ×-ÕìöïNÛylñhœTvÒÖy™£¨^ÝoÃ¥ùmè£J˜€\Rðu5‘½Ü Ðí ÎÜÉÙkšMÈ7€dm6بe­; ¨7ê"* _î¨Kêò5y•”Ã2âß>2%¨m¦Ex\–ðè3˜IƈWW~J¥MáO›‚Uj„{N‹Ç£›Ð¼°šâ£#óÔ¸”"Lׯàˆ]4AÌ ®éÛy!uôêÒqR¨µ[ëÂgÌæ‡hu[É`j¾ZÞ+Ë`ÏHz û‡ë ‡Ž²'Ö |Ó°*e*;Qá캨ä¦èd!-HZôÛ*Põ«ÓVÚx¦‡†WAfÛÚ°ÆlùŒHMãDšN|[( ›íä…‹ILè¦ëˆ}Ó ¨3¾Ñ î€âÀy"`ѳ1ù„R¹6ó=,}éä×—\zGµcaÌ“yêeqs=0Úí¾ãàT/ñ L ­=™y^V;r7E¤JvÁ¦1)ŸŸ©GÛÜuýàL‘$¾ª•½Jus—­ ®mѰ`ë@ÆçQ&…€SÐOä][BwI§I§—Lð«’‘±m!æmœw <èŠWϰ‹•Ý‹ûø¼(ÿÌkGNⓊE>¤aÏð7o‰¿:䡬’B#Îúaêx"£š³ù“ˆf&!’qÛËYÍâpŒ+Ãú6®&#µôÚäîZžá‰ÀkÓÁ»“]ò›†Pþs~IåÖ^NiÜÇydásÒ lë ˜¥V'|å9Ò²XóÀãpªVŒCî rŠí²žaÌ%ÓªRë'%2¡-tÜ’Y.†ÀÜ krµ_]#ØyÏ!2®Ä¯Ï@iJ±B²Åd¯ö1{p0hܪmÝ–Lû˜ÊÊ%ÙºÊ@›ruj>ø9â3…YÕ¼¹á:S€Á¾YpØCý@Á¬À#£dõÇø œ”ŠF°¯~˜ ²ž.[ö•ÔCö¾=–\ž¤}R!`‰Ö$;S@–µ|ÚwܯP_®ÂiÜx¾,σ‚ëÏ‚¤Ü¨“3Á’6¶Ïð…%YksNŽ]_þ›©oáX4Ú"NgfØ Ã™³ƒJ ,'Ò0ÂkØßÿÄ Í°ýZïàröFmù%@МO8-çh²l*XþnÈ ï<õú¯í[“yú¢cwpÐÔqœôT="R*’’´XçU(º2ï&ß1êe]y} ›Å\›¥¶Ú ÷Î}¨bm#¼lH]¤ñ·AÇî~Š`åŒ'g#GþÂn\~ÛâŒa§V¦-¢UÃY K­=‘=Žº=0¸ˆXRLòèªACÊP–ˆçâ$ýPïk¿ªüõ÷#³¡[QMÅ*\I“ͺ…β¯Í(Ø’^“½eÒ«¤)›µ­($ÀY†¨èüSf•%ÈÈ ÛÐ8³S¡c—ßE/'ä-¼P„Ä4ˆ«Ž5“CüN°¶q gTååÀ|Cé¨äÍD±œ¤Ö)Z8„ŸfNÁ›C?/ÔûäTn4;’’ƪ­ÐÛ”Zpxz Ä(ksÔpÆ6NVQ‰í3×óe”AϨí¶7ür/¦Õ&ÀŸþ\g©Í]E½/‚$?Pæë’¢B6Ûõû:æ_ÍZ\õFþòç XC ²jBÉh´»ÀψöÝhÁ¢Ñ‚X ™‚—î Ê„´Iî¾±.à) äj¬V=ó;0w^ü‚ûÞQáy¸-Ž™y$èózS`©£µIsð™’dÏ7é6B;uMÐhî‹ÒÛ2‰ÐÌ*Æÿ¤¹R=Ðq'ÔwÇ_€­q-Ž']¿"®\ÍrHòþNI¶"ºn ¼òÒa6#ЈJ.@É‘Òb Ä4]€6¡«E­•DÞWÿ”`lÁcï†U(y~ÿ†3` ˜;¾i¬Þ1<©`Ÿ¬„-c•‚’Fzܨ$7S ˜ÃÌ­nìO”a€^}¢…⨣bgX¥_°¨KaÇ ¦ø<ÒN-ùc TŒþFîÖL³éú djÍøCó{”GÙÏUM-”õŽ¿Ÿ—jò)¹leÅ«JàW³¦rß)¤øší…õú¬ã Wš¹j’†á(Ž%çÐdJÜ{ ½§y6ÇáQåÀP²JÅ{hj!ÉÇ;¸öš:/ÚMäŽfÐxæÎy€=$G~6ÂzÚ—oûþÅLS^%oOÆ äÙ#ækáØçå‡KvqŒå·¸FeC¢¸x©`Í®©/ƒ;Ëç‘H›Ù+É’„Ñ*õ´âpyðB½U E‚“‚ÁJZ’ÙiŒÛ?RÖ<ËýêÿQaVMDV “D/1ÁœQå:»Òéæ `‰ÍÁ‘æ)yM ¨º”ŠÁ(¾˜;:û®.µå¸q;|&’Ö1eÎû¼žþí Ï•:¾a_:S« cn…Þ©HþZJ?­±+V®>7€ÒE/¦U \ð $¤j¡šÆ}L¯F Íà/¸ÅÄè%YCúÚ!¦+~Ú ¹t:w“#cѽ]>“‹ÚÑÒ ˆÛ‘” …/D°µ‹ÿN|aJÁ3À¶z¹Hæû‹§dÃ4}»{X'ÒM»‡ íX®ƒå ¾ÒU«Å´<­0ySúú¢@¨•—‰æc}â6 É¥sUô‹ŽtÍQ4Höe˜U®  ˜åzÉ£r+eó&\ÃïhzÝ$NôËÆ3ç0ð³²èHËôÁ$[F”¥œEštÕ¨iPp"jå¬Ù{:wzi`«MÆš®â/˜øÓj] ÕÀR¾ ùò{J Õï¼p1ÔÑçRŽŽbÃû‡P#.#!©ñ'®â ¿-‰‰„u2»Æ´T,ttyC[ V5í|2}U–¦Y5„¦£f~]f·Ä¶¥ÖÍ7ªË^ýƒ8¯.üŠ öO[}½\RÎîÙØ€4À0Ó‹ébë2‡CIÊþ]ýçRžnrj•xÖ©^=ò“QhQ¶ã±F¤ °òˆìø:c[ÍçÊÐ\uMõ;ú-Ò8‡H»ûqD½:§¥b|ÉŒuÔ±„ð†™«ìCQɱ“ïõ»º„r˺*¥×²˜^µ^LûRD~Ë4ˆ\Ÿßb­‚Ïx¢·åÝfÙ9†oóû³e«œk,:áD“hù³Ë–– ”ä}p–·Q Cq¨3îW` í˜r}nôd¨‰SÆ­3U{_Bðá‚m•m\t±Ím x1¾ C@ôA© 4ôÍÃÐó’æéLhѤ!Ô<¾v±xôˆéi`›ž“¸äÍ{ïÒ&Ϊ_ö‹z|§+‚ )™ÐOÇ.¢DÚJF=[ùæÄ—æCG‡CÇD_nXccqb  ¦'˜£îg'»RŽ?õúOèÍ,PŒà,.î šÐ¨ì}ª¶€ÍñØÀ³:9³°Vy›ÓÅ1ÈHÒaœÛÊëdEZYiút WŽ«ÞpÛÍ€'KNï+»ºz¥W­XòëLh b²ßœÞÏ´UêAï 3ê1‘XÂËY4t>9!9b:›¸æñ®NDð’6ñ:ýôù)šàã·ÊÕƒ¢gׂ]€À ú\°ÒÁ`ïÆY]›*/6[Ô&Ê ÷êbôJ(Û/«hˆÆôò^’úQÊÉÞR4¿cE¥5‰fjÙúãT±h5iƬK…–¸x;{’.Нúænù^'@uŽ7[Ž€}ˆŸ¥.–N¹3¯³÷#ÊG%SnP±Ô8Ç·Ïè÷»³/ßfàÅ«økäQ™ç¡cšk­&o™¼uvk^&FwÉþ¬4€ Èp Y@„÷ÄNvñ9uM“¤ò`¡Pâp€JdY.džʔ‘“ŒšÎ6‘ËγR A÷®  ©ÿй7ÚÌÕ¼‹ ¶‰Ói°'=6sØh\–—ÿ\#;™•\ƒê¬ÁºåîUù2†²`ï£÷ñB,µ-Ÿ‡nZ¹}†0ƒ\H{žE„Ö¨µgF»7b Ÿ°ÖcgÉ%qÒHë”:&á)-ƒÒäRîøPÐdªÎû™04)7µp®NNlE¡j×ë…b.—ܩݨlá%^Ð÷·afXrYY8ô{jm#¼Bê]>t©…~uü„Ò›ö e¼æü¯ºzJ­“{!6¿l§hAß›Î,ïbïu د ¨,µÚIàJœRÚ÷­¡TªB2p}RIº)¹r:y™Z:4‰ò¬Ã¡Y£2zïB]në%˜ Ëïp‚³ V––'¸AêpötÝ¿Bõ!pö”%ôSsO°¯@ÚMq¡$ÄUõ¥ ¥¶íð“ˆ[5¶†:A/::¦€Åõ“q˜Ñ:å&Df ‰[Jã[¢´=uOÓ„ÞÓØ¯záYÃT¢Ɖ\–+EÈt:3ŸŠ£0ÔÐúé‰HÁŸiŸh˜Ã-e§c"Éåå9£\Zß²4Ê:;«¹ü·1ReáÄÚ¹ˆ™°¥ .y?¢„ⵕoG§¸±X™á_rP•z^8ØGwÿ bWá[æ’ð‰ê_”íÖÝãÆSíÀP³Rô`ðT;ÿ½€NR)Ê\ré1‘L†4ÈTµW%ÓT§ÇÊ ºoòð(LcKÌÝ^Š[ìeº«yr* ²OÜ“©cSF©Âéwe'÷S*L°¹÷ŽâÏyZ-i¯ž•*“šw’¶W Ïq ^ÚÇä-‰eåxÊsßMÊiÀ nJ­&SM¼™-M\j?*¡Ò1dF”5Ù>ÚΟxU`õPúîdþ”N®¨íb*ø|fùÀ¦ª!w«Š5ð³B·¬Zh8{.’¿’;î­ùßíзFèܾ¸›î#fk:‹d‰£×5”B -áí̉‹H[³@ œ’5¿+UGÃï E£pk­qÞÔ˜q-Š$îÄ f]U!û:Î [¢<̰ŒuVñß'e¹PWÉ-Pøj߈™ê^R.MŸX¤ñÊ‚¼V,!«,²‹Zè|MÚxwì(Ly},uàNf:,œ¨“¯í¢9¸sª¦¼<è+Ç™2‚¡u†±¥©ÆMIë; 忚ú/ULÖ^Í /(ç'6ÈJZ¬P¬LÝÒ¼e´ŽÐÍ+ 4­Éѵ?0sâN-c€*NØÌHF¥åá‰Ú®ÁH…ÞÞFœ¢Ø£Q}Z(ê›Äp, w,³TÛ•ˆ.4ºŒ‚£:eYÑS:£ã%Àw68?¾Ýaü· ÉR±¸’Jj LTð«,È„ƒ0~bb=OY]¿9»¿.ÀFõE·d+| hÓ ”Ùàß:wÙufx#q­[»ð“ÌeúL;í õÕVØgI²Ûš¡kÒO†IS–±»sº*#oA Kˮݗ§ì­ÀºP%ØCÙêQÔ–í+ì[ÉW2§F80J‚pªr’ã"|]HA\¢4bï³ôȼ$ 3[îôÿ3„ÍX[”¹t{òYÙesVÂ]Òi3ñLv‘Ç®/ªƒLá8ˆRmò+âØ%еŽ×tʵ䅎cù;FµAÏy"ÜõçÖ„´÷RO¯LN-su’øo@›t 8ßèëäŒ×M<‚±_¨áq¬Ñ:Ê‹yvêæãaßàPXL n4û¿%lq*92}*/á[Oº†æc®@ßJ·þ©Z!P÷Ùý)jÀ*òj—o¸)|ÏÚi3ç{Gùÿ‹QSŽ»bN+¼¶RÿJÊ¡˜ã½V20Šèƒ'Uß‹åP&59§WõQÊahk•šùh¼“2 ©ž˜ *§WV6àWŠEZãb]Hõ<Ò ,Hí Ùõ@pW«KQˆc¶$0PGÿóºÅüž$jqœ~ŒW;…¦&å §‹.\Ú;J7«"ÞcªØ7# €ÒpŽåË“+ákÌ·)ç–îþòþfó–oîl¢’3¤– ª\z"tåÕ.[„Iß=pí|"ê%Ž"}Â6[?ªç¥`mß4¶˜Þ—úŒï9ôäõÈÈfÑý%|ËÆ2íh\dý©04þ‚†²ìÁÄSm°Dâ´ÇˆWxèpyÏ1Ú@4k;ÿ0oÃÊ\ŽíwÕWŒ’s̨Sò¶7uüHï d‘r¡Õ½Úå)à¤öarÌ-Ö –ˆ¥WQrôÝkÖ`Ç&jbu榎f”ä!)’B-N+ôE•Kš•G8Y‡\]¾oA#]êçs…³cŠaLŽ(uU ¦JXb‹ƒ»9€"­]ÜiIQìÊ#æ5 èU¥“‹Š>/Š[x{ª7z‚×mzù“±Ä …‹«œ±7@û7s3ÅÈgÐcYµL£Y{@J>¹¦Ô5l‰±‰¶ö¯W&çô"=S­­ð£Åp[á¬:¯‚¦§ªŽ:]qGCQ±{%¥ÂÉC”=$æø^™«.UåO\ŽÛ^*ÄÃWÁ¢EaAh^ &¨bÖ°8~ÛCá€ËOÂ!…,i¹FF^çW,D6[õW{%1>W2z•º;… ¿ü¥_·^ó\l*„îE_zK¦¯K¸Ë1Rqû½6šã™Q±ÊÄàà ZCœ†ŒV$%Ú-R<ƒn@ §®õ_UÛÛ2=䨔±še‘nÚ,Õ¡ê3&Ï/#Už¿äò‡iœ~"Az7Ø+œþ˜IBqpþé;zy2¨Œre(Þ(hÐôÅ!ƒWîèŠr´‘\)!ØÁÛBHV2¢/¯¬AdŒä5DdÑ7ŒuÚÊf?ÕØ™'óä•f¡k\™ õôž—üÓH×”¸.…•NoüÊ¡–b7ÁânuW¹˜£È2rÕਖò¦²cG_¹ZÀƪcª»ú|ã—3Ü+£CX!0N5ÄØ1ÜÇÀõBÎiÆ0¥=УfÕàûaäÓ¶Ò‡}.P‡*paÊÏ‹êâ`H2:þWáPÙ•åX-?ÈBË5›0™JÕ,"Ëæ ¨V‚%›9"qÈ¡ƒtHQR‹Y<•°7e4TÖg€L‚o"©Ñ"ó}d0ïiù¨cR *‘AnÊÉü°´Â¼<£Ä¼F^.ùœ‹^Õ]“œ£~¬ºðšƒ…™¶‘ï®Ç>üÕÓòÖ†˜ŽÉ3$3'»dç-½R¶OÄ&òÛY¹ã/*ÓW¯G¬Uú5¯P2I ZªË|Ç‘ÄÝ"°#=gŸL³æ¾QÎXÚYÌá–”´ p„%tË\ Uôq ù {œN[îšqDB:eP>Ë…YoSŸ› Å§íU6t©¹}±¢½‚;¥$Ko˜Êmz·-|0E‚-ë÷‚ä´O% Â`ÓjÓéæž8Mq×gœ$(Æ ±Â÷€<9óp0È¡þ–Pcn.»o™‘/[rOœ9 l;Oÿ<( „ÂG¿b¼æÑûÛÜ"ß§ÕÄðL¤ºÍ½vtµ®ê¾ËâVYeI´žû.hDÆ:ÒÇìÁ朘K¾Þ‘ñÃ+%aZ·‘(¤Ð‚¸åSò\òýš5¹òë(eL,`ü±¨  ¦AKó›Ò@ú/8Õ®*ªö‚ô('žBEÎd€ÈÔ§^Ï`o?,ìÚ±Y„<ÁOm¬íŒö³óÉ¿œ7€C&ÐJ˜–‚í¿3Œ×}Ë Cߤ,nÀÃñ£gv@ OÈx…hS‰€2×€§-•xÊŽç«ò‰.<Œ6rGVš€%#ËÑ×;SÞ¤ÏÅì*U AùvòÝ[„ê!zJ ¿(<;/DwxEà<¦e{dxIÑñI`ÕOQÅt²2Á<í6$6V"›H#ËжÎR^¶Ð3‘}°œc4“( Ÿ˜«B˜O£§Ïw•Y°««-\`^‹B9Tâäfµc0È *P)«s BÛÔRõ›KœÒ£ˆ> ×Z¶µ+yS¹"R.ÏúSÝ3Y3Œ•Â@ôð#¥ —ЗLjÓEó&c’Ìc |™B’§…â!¤ÉîYÚ¨fWm×…¯p±JdœD$šýÀª â–kiŒ¸kÂkƒ‘”½ÜZÉô?Ù K™Ö6/¤,Å0°yÆÙ¦:‘"0÷±¸­¯wO/³ÔÄ‘â˜;_ É&²V—}¯?Sfç•‘ ¶%•Mz+ËqƒFÜ¥¤««[héuèÕAžW‘ Ë£Ôé/|Ãs :}É@\ÚY˼E>¡tƒHŒ´qWÏm©aë.€YQ jxeïð‘r}Qãg¤ }o¶ò£t2ª5°¨Á]5"%p ëF= {TõÚf®ÒȺ§Q NË'Q…¾79YDމÊòZ¬žÃàxy éµs(ÝŸ’{l@)'¶cdŸ'³ÑÖ)¡{ ÑcÚâÈ0†/Éž²3j<©Ïýo/|vѳ™7¯Ð¬¦î)å36‡ ö\.ekâYL-I{9záÚ}¥:•¦–Ë_CþÂD åú+-£,Xg‘/ &¼98yV‘ Àéôɬ0ˆŒá™‰™¦&Ÿ¹®«žßñåÄï±ÃØý’’ÑcÄ F»©~É>Ÿ§×GU™B|¶1žc"¦”\<3iè (Û(Év§™«b+kZ°Ü0vL2ùCQ®aãݹŸì_¤*ë™í AÖD|Ι„,"é«}Ò¦NDz€“Õ²8pì‹ê³ïÀ+¢+¸ùîugù#U¯ SˆÇׂº{[:ß¶fAî8ý/w²³“š¶üRl¼ÉOKÅ—¹5Ál•ÊR®ÃÇx‘ä°Á¥ÎB*­¾†Ø4gožGóñ¦«m÷žaÚ>æZW!ÀÚJõmAsp«j'uC _³ÅÄ¡ê ðgÊ™kµ±³udd¦#4ên°ìó°>vY¤¯ÇÝKË)Ž×SÑÎiŠQXhâM@DË cÓöe‰×úK¤!Ý(,Df5 ¥7’Q¬›_õ(š·ÂÀ®IJÇ6µPû5¯øQ•_-&³' $1)cäO&”JFÕK ÅüîbÎq ¯EåÏ_Çs-=¤0c±¾…­Ž|1!?).ˆÁœ)d÷<:½ùÞå{¡ç&Wà±ôsñëlšYny]Qgk¬›ðJP~!è48yÕÓÕ]jkÞztÍM¯sIŒtd±3Q$‘ªqŠñêeP½Ï÷¶iRÉäi|Ük»²¥_¸ØËKÙC£Б–ÞŬãÊ “’U“k<ÂSu,{*EðÒ!IG(¾‰Víí,$&50†¹ÂÚh´=h—ë¿%ÙN,©ÔQWÕ¼ÂHʈ» ‹â|^(†*4]P©©åÀ@LIÉíµ7[:/K ²·u5ØKÁÄ×6$„ùƒ*ºª3ÛZ\ƒF‘µ“6®vGUw¿aª°/Êê,¥ü „A˜FãÎþÈÿVacÃ[Ï­ ¯Û­­Y²È+0o“ñ%›k! ‘G,/ÎC£ª¡«;™â†ž3v.WNÉìÒ;¬CÊ–7 ’ s”g5 äC˜\jü8¢Þr„eçIå%3†1&Wù+|Yè kËHÊ©ñHÞ䉆G¸‹ú(Í0nÆÚÅ1š¯~[Å¥yæ½e9lȉà‰0q„&í(åÂ×’‹šýQ:ƒx²\Ÿ§w‘²æÓÇê…ouδlåÅV" !DËR¬÷ËÙ‹:sÕ‚2^X«Ê({*uñm!.^n°s°-mÐB6+¥*½ô:Æžª¥á)Ž:nXòƒZA>ø„Ðä-âè¾`¡Žªs¹ ›w7†Y‚»MËv¬gªØk<.ª@@dãäMj;T ù-àõñP=êÏÈ}p)°±¹(±@#†ôƒc‚ÕÉ‘wΙm¥¿– =ŒÒ=¯­UUâÏÈ•³|ÀœB]•ï3u».õ~Õ±œÒ(6‚ ÙÑêaiñSòAXuZÈiL[ .¡žŽ·C^9Èê¨âæ— ,h¹œƒ{J„gµ˜ï­ä28Põø‹ û"ÑÓŽ>Òg$l°,ÉtŒ ¹;¹ÑööÊzm÷ãÈä¥ðµwÜăÜaȆ§µv½ß÷Õ~O][§FX;?)åŽãŽëMoFÞùE£XEÕÄV–6ì`ÙÆ{ÓM:åFâ˜Ã ×\»ˆoÈåÙDŠ;¥êú›`&þåû7‹¯ ܼt­Úî ÷<œ §?膚u™yeuÖZ­›&§%j¾­-€dͤ Æ*õÉ‹"‚G_ñçìýávÙO€[•H}@ãï§“Ÿ¸A:ÑbÕ¸nnOžÂp¹éÖÃØv ãïp‡2w‹ºÖÏZ]y؃b¼R;O°W h±_,læ8rÐ D&H{Äè]FعеeY_AÌÐö4 ȼtlüIbÍÅsZ:K[Äž­Q -›ž™–~7\Æl{j R†Vx6ÓºJDÀµ±H"kj|®và‘“ÅOF=¿ŽÅx&Ç÷qñÊJе”i™¨¢Œ„æë„ãE# LýfzCêš'µ9I[CÇ$´ª“l^˜¬ßnP‡Ò2êLU…[vwõh»Ž 7Æ|äAn }=*xlØB òÖb`Gaª°ï­þU^@‚Q ­uæ)¿ rqØt¯áwa…ЪV³$rŠ HZ¸äÙüV¿ µ*z£•]uâx¼•®¸."áw"Ј+Ȭlß’×¢ôSFç—z¹f [TN}:¾¥y™phÛ¿KzƒçU³ ã$ ¸Ãñ„Þz6GÃÿ^J§‰–gŠI1ƱÌ Q " ñ-{Í  #W°ÞB½B™¨|}^'¶T‰T$¾½q¯’‡[·™:; Þn«õjñ4à ä9.åE»jü_­îàÑ|T®Ù¿fëŽÆC4„ôày,™:{°Âó<Ñ[]ɪwâù:†n#º®ƒæQ³i§ zmÖ‘=(¸-:ª™¸6ø|ùBÇ5&ϧ ±±˜õj²]ѹ‘Íß:~¦ÂyŒùœc¶ «=Ž,†¦ì¢_^rŽçd5…›tHœsYul …WèNccúÑì]=m`³Ê¹1ˆî‡Ö它O\AxtTëžtMq„øaÇ]ךTĵ­±¥¦ œ}4REÑäJ;=ܯ#(z!i‡Õ¢¶l‚ešîàg¤/rŠ&ux¸Îøä=ÛêNvt‰s¥ðHÍZ^õJ;¤>iL[üPüá2³¾ÐNw¡ÒzCŸª›•Õ3ól„SBüw¯Ñ7/=äÂHÎè^ÙÓ ®øVyFëuXª¿ºçÕO­?¹² ,æ¼Á µv„4ñ+Kú¬W±£Ó~Xj_Gc³Š|¹Õ1rã°ñ.ì,/ìVü/ôó~ÊÀ6q°ŒM|©Ó†Ô9å»\5 )ŽÕÑó`]Џº—šÌ¹£+Ê X¼’@“8œ=Î"zm4ÉAlU®Ë‰Ëµ‚¦ƒYH:‚D—  ²µÝÆs(Y”ú…atGttLàÃ|R[34¨—U¶N3ð-,JBŠ8Q€ÅÉ(ª®œÆÚxlíp ³SÙ0qQ×דì¢Zµe|߉û ê¯~cEæú(³ca£ôf”t°š' Nÿ’†$0<Ëe5‡ŸwT‹9 “°0„ÿÒë^ c‰aùÉ Qö\n‚ ïoŒ:!£gü)àÂþvNÿ2&RSް0Á;]§ßR#éLýÞsÿ 8GŒÎþëúKt¨©0Î8:†9S笱Ń1MÛ¸;æsR·±º¬l‚JÔö¬èëƒ(ZÁrìîc»{¯º¡Ëu Œ¤lèæsz ‰²ÀW@Ö³ô JZ;˜ˆ[J?€'eùíT꺧ù^Ÿ–ð_ñøöWw¼nL:Qu+lU“>µ–´w£ßÁ)œ` û¬¼—Í¢H²@¹ò‡ v3sOQÈØÝøç'&`%Ç‹„/'ãªa,âjõ~cäÖzºžD›‡ÛräaŽG&Ž}S­žöÕÀáÄ ôTß‘¡ºb߯5Ï@ "@eM§—†ét!®¼»Lö Ši‹¨O¨õ œ˜Pb {Fš*C=×½ø Ï:Ç$"1#*ýQï¡ 6–½ÀŒwlj0/^–Ñ/ëé$†tku„cÈ«%=•­„WrÛ}DÃñ¦7"šòƒÜ¬ÊšÀUβEŸ6PD[Ψ F•dÿfàQ? ›ÓœL„«Úy]É.u´RΤeŒ÷Ã&gíDû48ËZ†MjïÿV®Â+TP5ûïÎX9uB_â̬Bq”2Ï˳šù„´N~^8÷ƒf;/)KSI\…Îßnp‡¤Ç{íêˆ! aUÒû((·ÞZc,))ÒxžB’Tû—ÚyžjÚrj—JÜu³ú%é‚¶·G{w<ÀJèÅ#b•ÊyŽ£46¿ ãˆ6߃Ä"û˜œ) A'9ð«í_€D8·•’À²wOoÉ?,媎L’®½¥ SyÀŒ¸úÓA{”ë{Cøð+Ú²Sí2ŠXCjÈ6$I•Ï6!—Q´‰µïw¼,,Nëð€H ™jþtÕqÏRÁ…"wÁµ[‡ eé¬+Í)lʺ}q>y§¡NUKz_æ +Íé~0õÓè–F{ö¥Œ}ã…œá#«Zíwz9Š€ZÙu"Š‘žás¶& ò3ͨŸRyPòÌ×Y¿â¹v'5Ó7Í'õJ"A˜ÓžppËÈ1’½@”ÑÜ*;tœú·a‰â š˜’˜¸Ç–­¯±Âl¾¹õt#’Yy›:/PŠGSV<¼Ðëy”£¨²´J2–U„²f/Mµ=§q•‚Û+H51ÿ/ü“±ÆUü«®AÍ.ÒŰ Œx:óŒ%E›}Îp ½«Zò063 ¼0Ä!ÐYâjÈGpÝÕ%“'9NHËþfaV,šî_ì:´@ÉüüÕ>_^`¬¿FØšÎá€vªR¿èÔk Ú‡x²ƒ‹Þ;™0õ¤tÃ]K.s…\UâRTÇÉRÑON®Cšo±~Ûø/±:EcI‹3ÀÜmÍçª.K1•2'Ð<ŒC fCF+â¨eU:ù{Ï¥³„3מ1i…Ö‰üÅØ·Q.üÿÒ0M êsǽ󫫢² îLVLt¨©‘¾’×u’ùJ«ÑÀmIûä nüZ1³;ì¸î€úÝi V¦‰8â-6>™%Yô|•£¿IîIDATˆ„M|º…xk8¼šìõ5]5)Ñ `:3<£ˆjî<á…§@c3÷ƒaŽÜ¼»2Ï; ‰4Qaz"ê¯ñA3û—¬zwÀ‘¾@;ýïÌ#YãŒØk Ú3†á«ÊÅœT}³õ 5Ô‘5ÏÑV§έ4‡Ørý–i{¹`±ÚåœV0ŒgØÃ¡`ŒïoËTlŸNy~– V;Øùš»”²óª[ é¹À´ÏàåñÝ4Zþ8Ë |áÑMóÌãÑŒ0c)ã-÷q’Çjëã¿Ú:t·ò§„MÚ£ô¯’6-×”©m܇ċCh1ˆï`Ÿ‰R3[ ðsËâiRÄ\dPGÎwÍ)Ú?‰~æyŽüÆã3}³&¤÷媅“ÈÏ ±Zßq|P¯ˆõ2¨V(Q()ÃwåR‰a U C"–ƹµ|bIt‰â!•¦»O.qw‰÷¤œ£/J„#w¢¢fj–*)W[qûÝ”wr"÷Ty”=¡.î¡;¤yåb“*„ ó¹Ê54û‡äŒ#F—tÒ°³‚“W©M°ˆd$P$ •ƒ@'Ÿ3]úWB¤h%eB¤#ÚGëæáPïÊrTaÿht£‘‘“-]l+8Ûüå,ê °3رXéð-# ƒ×–iÅ ·²ùæ9꺄r¼+úø›+Qoq–œ—ÕD;‡ÌI–'ºz@4cnÉç1ß6Œ ë˜IÜ])ÅÅ_÷›B‹¿€¤½•”àÙ t#}ewóM Óõ+œ£å¡!A¢È¤" ”³c`Ù¢mÓŽÙ»–NÍdyZ\— ĆÉÃÅQD÷¦WŽŸLâŽ?v–!b—U/Sh9z ™…F·g&÷‘­ü2LŸ²ûÍ9ѳ±“4g["oA¸4¦WIAI0§r¨ƒÝ(éPìÏ;Åå• ä²OŠ›˜c1§½£`Óˆë¶* _8Æ[‘K{m%À;¯ZHTß`tXÆØshcTP©õjÜ;9ÕΚ@µ”9Âß« Ëõ¶Dõ–©DV0卯¦/Pôq%áòw&÷ƒðÛ‹4‹f®ñÜdìÁ’Ž…Q-ï.Äj)+È"?­nFÚ`<¸ß9°u/>fNl®~U =/–<Ü<:xBáU±ŒúÙcW‚WÓqa CRÃX§â.íÁëytðõFD^{‡ëép2·è\LêÊØ!œ/‹Ÿñ@ h8Šbï'(Ïb+[\ÿ1[7o…Pdí‹ ññûI.' l4±¨áÿœØÅxùQöHû³XÙ3mº` IÚJ§?‰-ø“eÖ@éHƒ§ò1CÑÊ8žxâ ,#¥¤m?5¾Èô«lþF©.EÇ úoËìB:˜£"Ç_Ï3À·ç虾…œ¿è„»nAÎxZ)5iÄļú%.©K 5K´¡ ÅmQ‰í¶Ë,Æ*Œ‘îüBBÃ׃ôÓ±Þ´ù¨¹T¥ô¶´Oèþú‡Mþvýu[ÛO¿¯Æ.]:;ØéZií"V£åd5ýÇ…g´®×'™ìx¹ã’ RÌ(lP¿0‘HÎ`TR¸S“'LG Œ!UQȽtÇp_mÍ{5û?a-,S–A–ò4[?;2šF¸\6o5¨¯DõM0gÜPMã‚Ts:,ÉIPY§ZœïÀèK ƒ²ÌЛ†/5¢‰‰kȵTͨÙ®©#«-É-‘pYz,µÚý5giÑzìôgº¥Š`élÇÊœøÇ§ÍH¯Ý—‹æj•ãšÄ)œ¬Ý¢l?«p³g­µT²+»¯Ä R5gáÄ]çv!e«™ù•¤3áêNÂf€œ‡›þ8I©zmmÇlkò 34löÂ8ù|’DåU`Å,ûÙ‘‹;ÙÁxO‰ éécÙéô‘½Pø+Šá²(šE+]ÓHáÌw]|$úŠ·œ?—tS:"4}étí¬|ÛÉp|…/< Û߸ɲ0µ·« p‘ÖPŠZŠœž*⼉"¥Ñ<çâº7"”yj¹²É¶÷[m9 +ïvV_RÁÈRA¾ª Ѓ™Ûb,µŸši e$D€ ¹fŠwC:jÓ†#KFÏÞY†'ŒXMÆ(„>//ƒ<ˆŠ¹‰¥‚Ecy®*–öXBgY'š{·âÑ´Rt‰Ù;Û;W…Ö„š”LÍârh>9` ¹ Q¦JªÆA§¥'¢X …í½ðsÀh675cÑE¤µPÝ…!ä%Û:©¨²lóyJ0òœ7,ü ™D(Û䘀II …$€ÂH#вH‰rå {‡öª¾4#¸.j(•aò|È9Xe¿ʃX6«HÞc¤°Ç`Ô«°4jxÿW;IP•Ð IRü}«„˜d <øR©w¨s\¦Ñï#öt©B•B ú¾ÒÝÊKišüÁÐ6‹†Þnîªè5Î5¿ùœµ–ðÝh(W:ÞM1ñ9k©UÉxú‰Ä9"@*ª€4—Û/›à/ À&Åâ2¶¼—šÊå§7J-/Šw£r…ƒ\iU^ïŽ ’¹8”*°Öt:;Wk“%cJæÑJF,a L|lØë(&2ÖYlÚS¨•ðÅ+šñ ¹Ì¨üŸ†/&Ò^5qŒÇšˆå…ÊFt0òýi(KÁ¬F\êE”XÖjÀò=…‚ÇÛ5Ø"m(Z—E¾—Û€ÄD•ÄvŒ2ÄŠÌ@FtM!.×·™¶ä…6‰&’s5ß×+¶ñ–‹H6¹J‰TFûWÝÐ ’wJŸL·ÒF…$ÕRëÆ=@S ßûŠ`Yš:$KRáV±¤g‹ #Nneêµs¦ŽÏß@¡EÿÒVÓü«.½WŸ×nâ¹2¶œÁÄߨØK¨ÊºŒÍ›ƒl…â0–S ­ôìUn[Lyå³Ðw«þ0ñÌç–Bÿ‘:0þÑ$|KPþöSÊ­@¹6‚²5a¸ó'ò¹ewǹö]/4|g-/’4d©ò–¾üÁlÄ¡¥’¡ ‡ÒXà¡f“¤|“@«GKªFVÝôzíŠ"É·˜§ªätäÔÓE™Ý!äãÍ6?#SU|'J,g3uçšà ìÁ$7͸©ª 5Gf0[6ïvÄ]ÎFV´Gj^×è­(òž¥%êoh„òDÂlöÿ2røûe¹°ˆîœbïˆÞÔ‰ò§ºÄó:s$‰cùªÑÄëˆ6N»wLgOÎsRÜÌy&£Ë“sNpép„üðÍ/צª]*Õx–¡<†þBù¨ÂÕñ–‚VÅs—xÚ:éøíÐ쯜ÉiI; ùÆ e“`>ãºÁ æS¤~: R*Ì^á÷ÈY¥VY€ºmÁ\!ÔÅzì|&<ÙjûFg'¯Ö¹º èGx³ø].0N¢-ÂTX%÷°ô+ TS"Ç‚R“ÍZ¨ˆ:þìdÆ^:ï bÜÜÎÞÌ‹ > “嫌Π[8™5’ö;o5}ÿ8p“†ëeÄc’\@ÉÙU‹Nß‘êAÞE3¼/S±ÔPTòYÛ¸< apxú\´§(дN 9Þ üB]Wç§|‹Ÿž°Š®ü§¬;5ÈxmÞRPžT%ì6•Œ¼Ú™ƒP(dªì³zôm%©üïTÇðCÔ= ¸ñ„Û'9&RªcòŸ×)Iw <è#ž>Ëœ¨tÓÁžªÃ+SH BF[Æ ¼Vñ-x`m¬—Ò†ǨÏòî5±ˆ•xÄ*…kÂа~õ"äÐô®âÓGºÉËÛ†aãQ³ËÖ·eºùaøöA=MÉÓ0§’°íˆ!Ù¿š+ŒàG=ø#5!¤+œ\ Aø:2jˆ½ÆÊ_ÇKkGY¿„­¯ruØÚ¼ÊÖz &.u2[,Ãç8šB‘îïH?ïµL¡bó:Æ}h ;XüÅ(hä:‰]`VYŒõùà| %}æXz‚„qKq¬ÍàÚ7‹$¿ÔQ5Ÿ)Œ³ë´€5¢DŽ&íî÷0Ì}.?‚êŸäKÓ/>(¤¸ªZz‘°ÅÝéw>¯j#ß-/õ"’H0ùúŒ}ªéœ–FF‡Ñöß&´—NWI¦‡—ÛGÀ–:7» ªù~ÞõL+¡¨ñÖþ̸2[#ß å~6ˆ]«Æ–lÃ5‡yÁ „Ê-Ù¶P®¯aâ•$4¹üj¡ÎèëQ*ÁØ2!Ûc¼a4/V&¿y±ØÐÄlÚ5¨gYWŸØNCh4EÞU3¹7*Â…àm-¥šä\@ùMBpƒÍTRãÁÚ±µ2uˆLtÃØÜ¯+gë,P‘gà ‚ÁîÖ#ÑH{•œ"n.֪Ǚ–#v?3E©J2š·k˜ ª¢ïlýD §°®ÙÌ$ …ÊÉo»çíȯŸq—@Ì;}8š´ÃØ`þ9%»:Ò½ÏÜ3f¾ä ÷SqÍ Z{®âé3¨£t«òÆu¡ Û­¼} Âe©(mýSnÀ1¾ 8iq)ìÆ´ò‡¹´–Ta3Uc{Q$Ç7D1oä²ÈÞUõà,ý¯—v¯ôˆ ƒ 5–KÕ.ß4`¡YtƒRvVX›ç^S$Î*Kà«-ïIY¹-·aÏ¿Q±ÉëFÖ¬KàÉn%m†Ëc2VÐYÅ+²ã1‚í#8½ %aŸ£¨¹òuUà­:ÎøL9MIÏãÒ’¥rLÁBbîrÿS)UMîQ?÷â§¥r²ãÇ,ý+ Èšœe•÷AtX•6#¼Æå6\¶ÛÁò1ýÂòŸ~vSSâñË)l‘ÕóŸzæ„ ‘´xkÞÒšÅÜ·€Ø¼ìXA~\ÆÔ?ŒÖ4û¹¦æð %]ÓÏÛòMäÉod»ÈÌU;@îYvͬ¥ÃôMòmZ·ÐÆä]\•æZü¨dZ’7mzþ h#/ßR‚øDa³ô´ò*´-y¶RÅPeôwlVe 7Ö6yé Øóf“5œ|Õéà•G_ñòEä ,ž¡Û”±hú„_–%ãâ'iÑ¢©cúÆNž3Žß‘,”ìt?¨›À±ŸÏÈ cig)‘ÊȲM1ê x™æÑÓ1OþþÅÞ1yÍHkü Q䛸¹ˆà1çÿ:-½ ÈM>tZ}•¸ÍîÀlA!•9ùµéò]ÓÉ¿_@åm|q뫇w ÖKRþÌEˆ,únˬÕ8&¯Q’’dÂ/ɘu:tïξ™a<0¦“ØÀøž,tªv$ž²àtä(`jŸ¸er†8«PÌÊJi9wÒS/Žñ¡Í‘Gm™+cU³w9SC·úwD‡'TËÄR¶.—ªØÄÞd@Bj¸Ûéþö¿•—RTÁ¨È^`¡åUö§®kË8‚Ð 4bT”ÃÚ€ºaksY´€ÓÀ¦— }ŒÝ %¯ITv0–›A_$Œ:Šš†*[ž\B¤Ù5°¥;€ìì -Ì >4>(Õ”|YtÍŸNÄnD•Œ‹=¿œ?)oý,Wán¾e~.5Í¿•¸²C€ 8ÆýÏ@UWR8ïþmž½à]zúèpÎk÷ŠçÓ<çŸÏOÖÁΧLæ BÞæIš#¨Ïsª‚èq97ôoŠ3š‹ÚåTK`‰Ñraüú)gvÏ„üÚè¹uÏÑvç"½[t3oüJ·”¬5± 0”´¢ž9G£ÕìЈÅÀ+êt?š{¯ÿÍse6• è0b –P>QNt z`tМJ „`±eNFºyœKà¡‹ëÆšÝ"GRDž"szn_Œ•2ƒÄ˜KhVJM-~ÍÃtD°’žÑ5íh­&M^4<% T"qj—³»];”¡‹Á°Ž«B÷”›/ùkíãÜybed +æZ‚9ó9Æ´H´ÇàLeÆY˜%íô^“U€äÖÛé‹‚qÜ û¬$®O ¼`$Y3EL¯[à6¼cöŒ¿›FÎZ\ÁZzH»V‘5¹;bÀ—õÖó¢`îT½S\X%,„Ë’?4ÉáŇÖ)sË%h‘ƒEV’šiƒ–ÔPÚ¸lG|æ¡ûPÉ‹zH/Üw«S~Z„szà¸x®€ZYùÎo|P;÷{˜”°Jåë» ¨¤TrS!ÝAóƒI„á=vhšÎ„ f;6_¥¸Ý)5¾Âù©²Hx§o˜˜¥ùƒƒŸuʽ:YòBÖß2M]TNNB%[?H¶ó¯-6ånš碗PÒA)+‹½\ZÌ]Œ¾{V1ë£õRG—wð¼Æã@E·¢ì‚N¹š±ž©é¢E¦_W~Þ¾ éÕÒ\©±²éX¬-&t3tyªœð»£[ö’ý[©*öO(–‘?Ô»XnÂÔî †CÛ‹¢X4äq‘¸z­{ØAž1Ý.ß °˜+@‰^¿Õ‘0ÎÃïΛâVȪÒ^cñòÃ,îƒqqvfi^P.íëh¦¾ülª`q·"aýì²B"TðFçH雽¤ Är€Øïf|4ˆÕþ?Ììö)TxŒ`¼³Gr4¤&±’S‡÷šzHluî@7ØÒkå䎱ü_Ý» {E¦Ù-B¡Z×µ·L4$m¨º¡HòNç:¬AÀö‚ÔŒ `YQ‘ä4ŠJæ+Ô¶(à6¶¾üt®˜çm„ 9ºKFžëy1 C uÂdÇobA–(n'%¾n;æjT‹˜¤¡«•„mœGVì©3‚-A•üÎJó ɸƒzO ;-H$E%y¿.îMm3>fqv-VK¨J= —žhHUçD¹/Ë$›LDeÕ¿û×dAåGßÚzèôWlö¤û¦©D l‰Z¶^9ðgrA“×&q’E\í r*ß“”L¤3Ý„ñÇDÊ[>ñ_%ŒÎZäsKR×…XÑ.שM)YjlÔPÀ‰²e;‰+bð;q(r#ùTѹÁÎÀ²0É]û£GÎUåaÂ’1j^m“•‘F7ä¤2,Âß$ËÕ¸†WÆ LA˱ڸ•8ÈE©o÷Ñ3}·T*ûô•ÊnÄeÀ+‚l ·Rµû€P¿Ð9[õV2ðUšX´œÓ¤™õerSÄä â(çÑ ƒIp8Êb‚0€RÖH²$+9H3`ò”Zñ€‰.Æa k b|¹õRKéx˜b푌„ômÁíŠ$ºÕje×Þf§ð#øyÚEÓÙ)¾÷¡!a£h‹ŽX:®¬íKúÛrÊ’ÂçØäaçÔ jÄ š»íA"¤ùãV Þí,|âålMzÀ,0MšÔ’Þ ñhiSëÞê…CC+y–Td—K·Wë(ö‘?6ÿ<8¸žìàŽÉ•3ÆÚQŽ1ÍQ6ÅD_ØÓ–G_[£ZzhsR/ÃØÔ>d1RÈ•Ç\AîÊÉ/ò'Rú¨)¹w Ìü\J<‡æR@Ï'£²C:AòTˆ³Û¤ˆÔÑdåJkò÷•cSÊÈ5Ue`TFÂÚD±–Zϼm³zZ<¨þ‹&ø=‹Ç,[•^ ,Z½´<ÎÄ:Co +X?}NÕy2Ê*á–¯Ê%Ûô$Þ/Ooz^‰º‰9ÉÔ¦¶‚*6£rXJÛ™í£Y%mÃE(#ú@¡dAðVYZóÜÃje1MkäÕ¨¯V:Û…s+=lïõYÜ]³al _ ~“2¬uúiÜÄÛS)éஞ®§ý¡êD“-U›‚&éÉ%ÚÌs¼Ê¾Ÿ‰ÃC·…m}¾[F´¦TÇó:¨[|gk[.€fM—……KÂ&' [§eY%Ô ´Ü¦ljAÈÈUȶ+òç£5aì$•‚ûÞ”Þôš]Á¦ÅÛ»“©®­ Üâºeÿ:É„k(~œŸ ½q»ÙòÓbMd`6‘.2' „½âXNs4©—‰Xj[óx¾dpý€Y¸<êß¼Tn ãepÔË#ª:÷‘ÂðI{ "èÀJ‰_AͪòÊõé;Ò;ú¸ˆÔæµIVAÝBëhC“e;Í/˜F ÃÍþèLå:¨Ô®´æG¢1Á<ªüIêæS{)âñjWTQÝêä“©`?yçhNæ†6N´Š1u³Mn4ÅtyÚ¤Ï)1ëìÆ¥ekï1u ­©A¬7çü†ê)ö"X¶ ¦Òjh7 ¤@¤!Š>pv£t•ˆÞhx°_„J,í$!U:2{thÜÁâª^Æj`VgHžÔZÔ­òwÚàzœ„\€×-ÌÁòàÔ]šÌM¥ó™%W«»ª!•Š]T"1 6|‚׫Í=gQt{H×%¯›Ïw(5g£iìmˆ¿©!Â۹½¥ïž¶Ã2ñ¦¾’Ï)ÄüÊš.W°Ya.ygÂa*\Bn9Y99·tÒÉA÷æAPÑÿkÂ+ô}ÁË-ѤÁ7Ý󣇧Yƒa´ AGœ mddSϰñe~3¾¥ÕI’®(=Yu¸ ¶ËŠ$“B¶lRÁZ¸2Û‚×›Ìff(»vÊsLëuÕi®~è/ö_A0»,)†[kÁŒ`™W}àÍ`³@ßË¿¢ý’¯WæÀ=ƒîB²º3“-‰¦X¶‰ ô+³÷‚ÕÈ%š%wˆb›œôn€ŒÂßxñ€W[Ù ­óß%69í§‚BÚqKóVßÛ‹Bˆâ L$Ÿ!ñRªÈ®+Vé&ˆ8â)ÔÀÌòÉDt¶wRÛg7ÐÚ@ŠÈ-µ-úB@FsE¹dΙ—Z=ß _A ©ÉØV ÚY‡¥z`de~N•Pl̵àFê¨Ðö§ó)¼ZÀì"”ÃÙ¡•Ù-Rܨ(í—mÏÔŠé#ýü¹6ÉsÄ :h«G}B'í»âêXœVu¢r©Ä{X¡\ý†X*‹V0â1e.0i™9zNÙ®p'gë¬@ÍÇ‘"Û›ºåï´"r+4VrE¤$'Q¿Â3U½‡|[ÖΓ ¡FV¨—ÆÐK”¢ÉØW)%iÞÄÔ{š~¢)ÀËOJ—G¬ßÎdx{žviV!:¯›úŸ±1çÃ$cc)ý9;Z‘™Ï‚Ëmþ ‡²ÙQíêA]åJÍYs—Zqä3reO€,¶¢²q\C%¸%¼mõ•¹XQ|D*¶ý`]Aw𙂩~QŒcI·ëi19¨ß ×:]Drl‰²…ô•Üi.Óÿ]'S»^/å§ž[y ô|™1 W²éEÏJ€·ã|6/ð…%J'S\œ?ñÏC£IôÓö¶IÓ; UMä·ú—½ª&“š1mgÒ¶‹ò™†—çU®b²â ¸¦ß ¶oY<æi}¥Ý‹S1²{rÕv7’e‚Io‘^ÒÂJ¦ KKÙý§UQ(-ರOÅ^’¡>Ä2&“ïϵIW÷tÌÅSj1i÷6„¿"‡i!ÕÁêP;†Ž#:d½/õ}³úu°vþÆ= )ç‰q5&ð™+{œs+/Öî²b®GÐcÉC9ÕØLÚÚeLê,ê„RŠÜ€à´6,ŸÜ¥dvpŒ{c'”dÒ)¡>¶ç¶ƒˆÂwjSgÜEhö‹¼Qszs¿ôš0B”Ó²ô@Z²ô”È&ŠtñeFño¼È°˜`ÍHóÝZψqŒ0à d:ú˜‰WI>«Z£´ZœÁ¼U”±ôíD\`r­šžyœleyö¤aJ©Ê<§Q×®‘L.Yö_·a~Û!— Q2¦Mš¡ M›¯Z?t²êÖñ¶ü»éøg÷X¬Ã×=éœÕ¬¦Ü $•nšÃŒ’vPwÙu4ôÞ½œTròKŠ3áÚ«ÀwnNsÖð5 oÔO1Ð  =‘Ƽ"…v·ö1«ºh_mI z ê[G¼èŒgÙŰS(ÑÝQ].&ŠÓà²fTO;ÎZƒºkâ½SWUÞÓïNت+¥8·;²ƒâ¢íŽ{1wõÐÂSÇ­‡ì_.;:^ƒ¨­Ú¥KÌ2ÃJ–66ó=rêl3x¼‰’5lz°h›ù6†ÅÙ]ä—äèôr3&Êb s¯“$Õ4²b®€š¥î»@BÇŠb–ƒºŠÞîÛ|ÞÒBêðå@°*›ƒ#FÚ˜C)ÏÊA@Pª¬¨-~ãb,©žØk5„ßÙmØJL"ÐîÙÏjlª¨Ià;hÈnoœB£•ó]S¤j~[èžœ¿º~0,8Dƒ¾³ŒfdGó¢ÀŠqϼQ ÉŽÊc‚ö´QWÛ•”çOàtãàÅ\’Ϋ9夛IægmÚåðåè TÑb„!ëØCÞØ:$kf”‡gHÊ­§oŒ×ÆDPN¹ƒk(æ)“ÊNÚrR;É4A4Òü6ôQ%­¤ï˜×ÀBI Gèv gîäì5Í&ä@²6lÔ²ÖÔ‹ÆÛý¾é ½hö-ÃåOÓzAeèÛ'Iøò¢`Ôqë3z ‚ˆµÈà£&ð‚W×!R¥MG[äso‚tD‹ÇW:åÕ'|ðæ=@ruÎó&r²ù,ìB )bfpMßÎ ©£/P—Ž“B­­ØZÏ”d±g6?D«ë€ØJî`+ fà«å½² öŒyØ(È4ModüÔ”•“Vß4¬ŠF™ÊNT8».ê¹é=²–$­úm¨z‚dý[QUô‹JZÑô½ò;Ù°v´:#wWìqË9¢úãÙš­ùx®xE<¹°€üÍà(œw =“ßH(±¤™ïaéƒXfä×—\zGµ_8vñƬ"Ðõ±7x7côªå­¬ƒ ¤µ'3ÏËjGî&i„È“]°iLʧÃgê>“@‹YE‘$¾ª•½Jus—­ ®mÑlµ¬ ùðB̵ƒÂGÀ)è'rÈ®M†‚tªHO¾TÄÂJ@Tá qÞ%ð +Îò³Ê{mãŠa$àÕ8ö‚sÛ_ûPÈ×–ˆ¶¶ÉÒ§.6àb1€^q#ÔñEô|ÖœÕIjŽQâå(¶—³šÅáW†õm\y®Ú,„âíE IjÙ?Y¬‹*“]©Ómos«Ýe 3SÁ;Æ< št‹Çˆý®e §WärAä†Môè`N²Õæ'ì5ªqª‰z£ÓÌC¡zæozœ‰\=vpœä\–ŵÆÏø9â3…YU´ªáœM‘dÁa# ô³v‹Ê  ïWŸ“RÑvàÕsAÖÓY¶ÐôØ:öXry’öÉ 0Z“ìLYÖòißq¿B}¹ 'Ĭéú-è½aY†Œ‘Û%Ô\U¹Ã±y9ÿdDê[8¶ˆÓý~Ýd·–-šÏT¼D±«ª½ýì=ñål“†$ÃF=¼1ŒÚòJ .P¤ŠEày˜ –ƒ¿òÂ;O=Ôí[“yú¢cwpÐÔqœôT="R*’’´XçU(º:Úºc&Ö:j®ȼŒ¾†ÍN<¯ÍÒ [­*Á;÷¡Šµð²!u‘Æßê0õãsÆ“³‘£a7ò"Q˜RÖóÐꢓ€G hÕpFrK­=‘=Žº=0¨s=_FôŒÚn{¾)÷ðbXmüéoÀõp–ØÜU6‚BÉšw£ß(…xÂÿ(ñŸÀ¡óå­„«—µ Ö\¬šP2Zí.ð3¢}7;´h(‘.†LÁKweBÚ$wߊ[~ðrõ" `ýÌ¿`ç¾wTx:3LÒÀÑ[çÄ‘K­M øŽG£ÏïH£>º@é?´N÷|V˜Dhfã”’-gêŸâ/€~ºÇ“®_‘NW®f¹$y‡²"ºn ¼òÒa6#ЈÂïîS / »¼·)^µ@–‚ω·ŽykÓN0t©ÒÞ °D‚gÀ0uÄÑh†ç/ìSÓ¸#–±J‚t~ªö†P¤jñxÂìO”a€^}¡¬gê!LR*"qçw˜` ÙPêô‘: WaÌK’kJGL_uCaLú½&¢ÁÂÑèÉ´ð‡æ÷(0²Ÿ«ªƒŸÞ`©ç'R<&a’ËVV¼ªîÑ’ê·@FòßZ‰”fû_aý£~'ëx›ÓÌU“Ü0 Gq,9_6…Jeë^c­X>côIøˆ¤òǦi§eRõêƒ^`e&G0V»£‰ÜÑ /Ƶ¢‡iŠáè°µ/ßö'ü‹)™¦¼JÞžŒȳGLímú°ß…ÅÊF–8¢ël®¼#0g¥e³kªÅËàÎrÄy$ÒfvÇÊFrWþþÂIû 8\ÞÁE¼PEoC‘à¤à­…ìGhIf'ï¡îWôS#úB(9‘u,s|¤è€!Ýià‹ÆZî H7AýŸùH #¸Õ70–G•›m*8pèïX¿¹Hö²’Ö1eí¨?9ܪóÊØbŸ]Ä€Ã/dcÌ­Ð;IÀ_Ké§5ö­ˆ…£Q2G@àÈŸ$‹Yxx†?Ò µPMcâ—Æ@Íà/¸ÅÄè%YCúÚ!¦k]ÕÛäÒéÜM5ž;Z¦Td—ÏäÀ¢v´tâv$%ƒ{¨„/¤¿ÚÅgX1¥ààG[½óýÅSZô]&s¿Àz<1nÚ=lhÇÀfY§4¹»Âµ°r¥›GU£æÃ€¢Ö‹æbù4$—ÎUeÐ/:Ò5GÑ P©M%×0Ëõ’;G )eóž^üŽö§×mAâD¿lζ/ù¬Ö­øÂnYÂË2šoÌé§eË÷š+ùHaS¯¯è ÷ŸÁ<‘«=îWì’T¾¢UajLëL°½P:fôkâ°˜ÎZŠ£î£$öê«Ç}±ßëø]ZV"ùyiwÐ]ÏÂlÚZùf™93¬¤Ä¬óXGåZŒ¤óº ætüy­‚—‘ÅX|gÀü£±˜_£»‰§…N«LÙœ»m:xØP“i²g³®Ô£ì5ôåÇ2íij³]{¦,ß—­lÕ3¤O5tÇí«ceò¯ì!eÙûµülH|Á¶Ó×3»-¤©zv‰>·" c•dQ”8¤•Lä–´…½*A 3Éœyè–¤'¦²–\u–½Ž`›Dkaåéú-sF2Wy&S~õ̘-Ϭڟ_ø4$^±³ m F–ªþƒ_õHV*)t}À´ˆ5í'ж_*<ÿ(÷aÇc1 ÒÚ耠d‡òû$ŵÂÉTxšžË¡Â#‹azæ;Ä$DeN³áZ˜€fN6†¨iAݾnô=“ #z¬a5°e7)MšvE«ôÖQ!0¨åõ ëCüþ(¡Be8™Ã‹j1ó%r5z å,}OÈŸ—.bB.£éz§ñaÞ¿¢ÉHéÆùäbmRX9PMŸªf ¼&¹Q7Ðù\‚œ)Ø–ÄÔ‘GHm–›*;ÇNÓÕÜ¥KœxÆ©½æûj½ÈïqnácÌ»ók)yð`ÎäÓºÇDÏxiWÖc«¯GpR*¯ ð9ã Ì´b….‡t±õH™™ÊÚ…8è{¿í&§V‰§JЫG~2 -ʶs¼Æ«•GdÇÿÐÛêuT†æª³hªßÑï™§"z^Éíöœ–Šñ%3ÇÂRd®²E%ÇN¾w|×wËõ|¬bjkW8ü}ƒüë@cRDªMË4ˆ\ŸßbíÛOô¶¼Ûì"»#çÂÿÜÀÓ;r«Ã:?ؗݫ۲fv ÜË‘ƒÆ>ì9”þšÉíí² ¿9…H½RëcêNçô¾d `ÑÑÑ_bT4·U$àî•Ñe¤‚ÒÐ6†@š§3¡E“†PóøÚÅ"``àÑ#¦?¤ÓCân7ïy¼K˜8«¼‰¼›¢4H'#!ƒ%®eÌöð§1›¨‰“âLÀ¨Gcëg|^ÄzîMA®­$?ȧC ÍŒºŸ8äJ«ŽzÚXuTæ¦/þ¢ênÒ±_Ò¬xC…bŽùa÷¢•¾7`Ö*O`Ü[º8é_ç¶òº™ ½ ªµ;ý¬0 ȉò0KºÚšdX=Ÿ£]^S‡ Ö"W'äG =ÑGî½*õTôjÔ8M$–ðr ONHŽ˜Î&®yÉ„«¼€$¤u?}~Š&ø¸Ä­rõ èÙµY< '(ès=ÂFHƒP7gumª¼Øl5R›('ܨ‹Ñ?(¡lŸç’¬`“63˜ i¤VˆPp JÁ¨ûFÊ4 ˆªU\Ø;tfÝš4í"cÖå¸W|ñŽÂ(I—•3t”r¥VQ¿ÏXo«`Ëeñ³ÔÅÒ)wæuö~Dù¨dÊ *–çøöý~wöåÛ̼xõ<*óâGfÛ4ÊŒŸðWG+ûËÈÒo³|èŒwn÷‡G2ÚÕ>Á´ý!®Â þå'®óyÁBA6[d~aœg£}¼v5ÀrÅÌo: < ÷*—'d¡ð®×VÊ8½¯»¢´<»-$´qý:GxJÒUwÁ⤶{[{@Ò냖J´Y“š¼^>!äs™yæéMÅc£STƒ]IÒ7ˆ²±:ëëMIñq„M.DZ‰4™/ÑÞ\è¬IJÕK„2¯"n @UFþ"¥á.Þ Yf0“=ÔíËØ‡‚ÞÚXƒ¼Äé “0Ã’ËÊÂéü¤Ö`‡ƒ—?V®_$|¤m½Œ6ñþN(½iŸ4)ÃHrìH@YK¨'6¿l§haO›,-Vlbïu د ¨,µÚIàJœRÚ÷­¡T6,!Ò9RIm9ǶnDb6®ÇÒ\^‡Ãs ÒªS`5äÞ¡ÇX -S¹ŠÇFë˜è@’5ŽÔáì麅êCàì (Kè§æž`Oo$§ ½bOWž†) )ÀÚ˜Dܪ¶0ÔzÑÑ1,®ŸŒÃ<LG!2K€HÜšPß.:œt´Mè=ýªžéþJÔÀ8‘Ër¥™Ngæs@q4†úÎ8© Û3í s¸¥ìtL$¹¼/ã—0Epç% ¬G> ì0ÉKß›Õ\a×dFž TÂj ~ ª¼©ô ãv¤Ìi…%ègY”Y&“¦v~2‡\ÛôÏßT"áØ‰´‚ì"\i“¦w&ƒÙÉíóõš±Vª^³#¸Fßb1æô×F¸K@÷­:ÖW8ºZ˜ ¢Ë¼J?ŒZ67¬že¤º8Š••;{¡JÚ¢ý?Ð"0÷™æ®8B÷]4–\! p  l«Î š £%‚9¨Æ-¨;ÀLÖ¬ª,ÙÒuðü˜ŽÄm–äCQ°G–61|Ž;mé.,WS#ÚÂz°È'/œFÀãHÌzp“ï3ä¿ ì´ïL ÕùE/œ|d ¡´q/ ‘Gµ¢à‡½@“ZcÇïFø)YãHf’’¤jëçy’,î»FBùŽ2 >IÑ5d–M-ûÔš7žÜ œ/_¢™"©ì½å‚Dšž¼(dMܹ†Íë9VUàŠÞnúoL>ï¥4sª°¬Ù èiír>vðÆç§|¿O„¸µT4•‡jZ›hël¥>L ø¿ÄÉoO\?8 ‘ÍÔÐÝT-¼#«7r=0ÔΗ³Hž$:|Ží<ñF„PlÙjïœpJ;n½ žõÒ ”Ä‚=\G)»(«ˆ°ÎóO¯žåáèçìý¿.UyOÎ[}.ŽNñ¶®`e*<¾dî*õ"˜¾#­+’tâRÜ2—„OTÿ¢l·î7žjv€’{ÛÂà©]Ä'z#À±ÊÜ,›õˆ‰d2¤©šPiWŒÜàþUö€cå]€7yx¦±%æÀn/Å-ö²÷ÑÌ;SÕ6 á EpEõ£pú]ÙÉý” lcî½£øºÂ¦¤ÝÔt±Íædš·’¾=gîÕøh¢2 ¢Gú¢£vÿN6)I3¸P %ú•C•±._‡%™T¤ú†4Qõ•Tûh;â/„ÕCéŒ(éC]IŠ ¨àó™å›ª†Ü­.¿0+t˪…†°çÒ!ù+¹ãÞšÿÝ­”þ C¹ˆ¨›,Ñ^gÑ‚,qôº†R°¬7ì»7ԙĊ|Næ¾+U³¸’Ï`lâqµÖh<âløÆ×=$DEž÷PzÈ–&QfXøXñ·ÚsÊamf~žÀEÙÛÁ+—¼âcÐ'u½í:ÖÜ–†36ºØÉÐË»;N²øÚ¬cg¾•Ë­0å‰ OZ%Âo†¬eÇm™¦°°C•<Øù=X’* ‡ðcg±:|KÔR©’L{œeXg‡ ¸ô—9lÒÁ‚fñØ2š›eFa¨'|Eõ4’“^Æ&üÏòÂ+@Ç`;wγ!›Î–Doé)yßSKÑGÌ‘ ^È^ªû®½‰‰HÕD]Ž!è“´)£Í7Ò ¿Æ†7¸Íš›Ó‘šxuv¾®ÇI˜œeÁRö/IÆ%H=å3÷£QV<¯’;.Âj9DWA™µ6¡ªó#woêÊM0áˆÖF œýXKÞ@ªYI‹Š•©[š·ŒÖºy…"¦59ºöfNõ·“1@'lf¤K÷¦åá‰N‘Áˆ*fÄ)Š=UÑ7ì‚¡.°IÜ ÇzÇ’±ÅíqÁR Ë(8ªS–=¥3:^2|g¦–ãÇ·û/Œÿ–$Y*WRIœá©€ ~•™pƧÛÈ‘HÒ˜e‹”C®¢2ã’ ]}Ñ-ÙJŸÚte¶ø·Î]v>¯dÂí…¶¸ÒÅ©rý7½*MâeUï¿£@ù$,•¤Y³0ç,«§@™Fd\¬|{&‘´TŽ2Ô=Õ YãÆÌ0EpȾã§ÓF®Æd ;’œ,&!Oìþò Q&öKà:Ie1¸uØM¦_[÷*s§4îlâ@\Ò´¸Ýws’|¯oŠ= ¤ˆ_JßÛÑòÙ’ŠTÄ•(ûCb›Äë˜ÙÉFc ¢zŒK¨ü­â++89š…òßdÞ'êU{lŒ¤Ûc|3Hnk|¿ašjíötÞ7wœsѲ…ÆÅx­ÄÍð4k7»"»6Ÿ SOÎJºRgúWM„Ð5é'ä)ËØÝ9]•‘7Œ .¸Ë®Ž1eh&Ð…*ÁþÈV¢J&_Q;T1̲Œp`”áD=’ã"|]HAWpÄÞgé‘yI@ghßéÿgÒ—cmuR檱’æ‘àË^< .ŸèíÜÐðõRu©#P@é^~%‹+®rþšN¹–t\DZü£ KtC9WÉ£Ú®/Å7 ˆ*îl—œ&ï.d¥T½øî MºÎ„ œoôu8µøD"뼌s¹ÖQ^<ȳS7/ö-ÿ­Èþ‚øZÏxR¥ß_,‡2©É9½ªRC[¨ŒÐÌGãlS¤zb6­·vŸFÞã¢Ý^#íÖ¼ &ðF,ºcÜÁéCñ#×إ&‘Æ1ùÄfᣘ§nEÖgôno–ëçáPÏ‹J{Gé&¡‚ˆ÷˜ê#öÍH`ã‡4Ü/yyrŸc ”‡HòZ‹Æ|Í[Mq¿!Šn²%±PU.å…xôjµS-AUBRRpí|"ê%Ž"}B\Kõ¼ Ê4¶˜Þ—>ÓÆ?ÀË4Ûéþ¾ecYï†r‘õ#¤Âæ°ø ʲOµÁ‰Ó#^±$?&è®ø‚Ð`yYÖ@ª«q‡¦ã)ªš…uØÝoÐûJE¿Ü}ZÝ«]žNÚa¼Zú¢ }¤£²ã½Š°óÝÖàͺUþ ʇM|@Í(ÉCR$u…`.üŠZ.õ˜ÈR©š”éÊ ,ßG–Yl⯊¢é'f³°ÓÆÔé8”ÙdvU ¾ƒäÌh¨¼pi#\½ZRÐ 漆½ªôcr±[rý£Ú^›ÞŠXšÒËŸŒ%H.®¶)co€öG¶L{C¥}g@Ž(ižÑ/èîÁa«µ±#w6ÈŠ±‰¶ö¯W&çô"=S­­ð£Åp[ᜈ^MOUuºâކ¢b÷JJ…“‡({HÌñ½2W]ª ËŸ8 ú~ ëj †oe7¼QkË{LPÅSqü.¶†Â—Ÿ„C6Nµ@î sŒ¼Î¯Xˆl¶ê¯öJb|®dô*uw A~/0ÿÁ<-<ÏŦª®ÁmÑÇ—Þ’éëîrŒäoú°·lÞ¬!{5™á¤ù5~-,{ÖasÌ®öñ:R¤À87A„-Æâ*Åú³Éí,ª¢Ó_Ûå°°áÿ«^à¯A®Æx™ãžÒ('<0Pzƒå«Ï#£L¿P#…Ð¥AnŠ3^Ü(åziõP½q  5D½;qÃ88ËÂCdmŸ¨S™«Ê8¶Š [nbŽdVÿ JI5 ‚£dì(anaÌ ÇP«¬ë¨r½±™#‡ 1’ZÌâ©€½)£æ¼>d|I™ï#ƒyOËG“Ô^‰ rSN懥æ}üvÛ0`LíÌ=3?ÒÙûf,§”pX^ùWìxEEÿ\„¦7ÒÅÖÿòÖ†˜Žsƒ„#ò¢À¬–“íRÐ+eûDl"¿Í¹ ]1Àš×# Öb} ŒšW¨™¤­Õe¾ãHânØá²O¦Ys_(gl¿÷ÆœnII GX‚˘k¡Š>$_a q:½IëQås°\˜q›‰>p´ø´½Ê†® uvrö¹éIõ î”’,½a*·éݶðÁ%ïvðdYxqæ¶ÚF¸t¿íùð*$Öä;qÂTz¥)£%úE!o‹S@åZŽ>þ=³íì>²m•Lù®á’þ=g(ÛÎÓFÇŸƒ¨"nÌè4Cn‘o‚Ó‹â‚F¤ºÍ½vtÕ¸ë¾ËâVYeI´žû.•„Œu¤Ùƒ2áŸGᔄiÝFn B â–OÉs©)÷}àø×lµ6†d6¸ š‘Îð®0ÅZšß”ŠèÞ¢•jz郠ú-ÅãÄS¨H“ÚÆèý-p¢Ie'g¯æ×Z°; Eû"1Ñâ¢h%LKÁößP£Æë¾eò¾I=XÜ€‡kñùÂì€.žñJy;Ÿ˜J”¹<€,¾3FÌ‹‚Ðýa~ý(ªøÊÅ(‘‹ó1KF–£¯w¦¼IŸ‹ÙUª‚ò?ìä»·ÕCô”~Qxv::^ˆ îð`/§e{dxIÑñI\V”ÍG>ÿº‚9wG¦¹@+EQ€¤ofsV…ìFÿ ÙË9F3ÿ÷Çÿ×GB¥V%êÌ%tEXtdate:create2014-01-18T09:53:19-08:00R¥‹%tEXtdate:modify2014-01-18T09:53:19-08:00#ø31IEND®B`‚pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/static/docbg.png000066400000000000000000001675601250413007300273460ustar00rootroot00000000000000‰PNG  IHDRÈÈrªåŠ pHYsHHFÉk> vpAgÈÈëJ|–€IDATxÚìýp^éuž÷½¿HJÚDs›´GŠÉŒwÐ .X-wœh¬U2T¶@¥DYݪn%m·>ÖŽ‹=16J! ©ž ?É™^9b—Z¶Ùk•mN„”¼h`‰JV?Q´nd=&Vl²ƒPr"K$~|÷¾ïþqÎ{ïs¾ó]F5;Uq?Xà‡ûÝï}ßóžóœç<ÇÃûKÿ¦Óy²óžÎ׉ˆˆÂjX -?íg|;.ÄùxŽàÇÍ»·'i,»uÚt;ü;MÄq¦ w“vâl¸§äø-·íîòç~ѵýž?ÌÅV#ù ÙPv<»'âX.wËÛå·ä¯º5¾ŸÏGãH<É•kñýð=o¸›´Ãçäk¹ ·évÂlh…)>Fže!ÎÇs|¶ìDv:»ÄçÇgÉwò;ùÙr¯¼W>g+WÃrÙâ«óÓñydLà®øw{]¹Ï†>'Ž>Þ'^ÅŽ’<×\l…)|kütò®á=ÊØÂ»Ãqà·ƒ÷)wBDDƒ¿0¸8ôQþ}ÿ}í}ß;Ÿ-›öç²6ž‡¯è—|Û¯Ãũ↌ó–Ûvwe¶Ü¶»+wËã cˆoŸG¸é»8ž|oò6÷Ê{åó8WùHõF¦ýŒo«¹ ÷Ïc(Ï;[aŠÇÇ_˜ù«Z °"øYxdx¾ÙyÎãÉãÆwÅ÷#÷ +¨q¦Áùñ®p¬ÔÝÂìÂÑÀ¹Í¿ãÌ—· oVž¬‡þuè]C§Ý\ÑìâwÕùWÃJháV„s[f œ7¾7™“|ÿüt`zpcÆÕìs¯~x¾ñµxÄx9àYÑy¶s¾sKîvÞ-¸eù69yËlÄyÂ'|1‘Kþªƒ‹®,™{Ó~Æ·ñºh7øw|:´-2ÇxñŠÆMw6ÝÛœ¡ûG~äè;:Ov¦;_s‡×~k¼ïs}«}ï<|¡ó‰Ãûq6´ÂTñ(ïrY½TÖݦÛá)ž¿šßÉÏâ²AŸ} |èØ©ƒ¯Ï`w ¾ßß ^…˜Á`ﳇ 3Óºé~”‰Äe;.ë½ò'<æÙ`v<» /{.´Â~¢u}Wü^ø}5A¦Æë6›šj[nÛÝí[ÿO |‹”\ñ|öLöb¹[Þ*®°ÙÚÿGûs{¿bŸçR“e=>¹ ÞæB+LùEßökê»fNâŒUO ž¾|§vL¬÷ký,ô1­m=gYäpŸ²Aî—÷ÊçÓ»pÕ»°o7`¾¼–5Äöíôðë€WDogÞ3Ÿ¹éH6Uå£Å©ÎËåjX ­´h•VˆâÝŒ;8™øsž …µ¸oÇ“Ž¹4È‘#;ÜèNó}f[¥ ÑmQ»šÐ»ñvXmÄ«aÊM¹šMƱ ^§Ûð7]ò(ùvÈy×bÓÏKÅ<s9YŽ•ÏçÓùLÞvƒî¸“;«ñb<ÉãiÇ¿ ‚ŠèÉbb°L¸Q7â–å½¬Ò ‘,þélÆ·ã`ÜŒ²ÃÓ,]¤+|ÎênWÜÎл†~öÈùγÅ:¿çGýˆ¿_y²gˆ8TÙ_=xl¯501848Üyáð‡÷eÙŒf ÙrÇ#Ñ*Ý®6-Þl §Â”ßÈnúlÑÏdkåhIåyYöDó‘Ä S¤¸†ÏB 4žž=l¹•p×Ïû¿¬<šUºMäܸ»[Ì•§Š)~ 4M3i&Ф#Úñžü0MÓ ïcÂ;å;”«åJÙŠûq%ÓªoÓšu›n™ˆ¶ÓáEëF݈;ÉÏB£DtRÎIžœ„м ñ›u«nÅí¸IO.ùÈÒ©´ d4–èjÎà{_+Qf]6Íd*¤[q;ž£yZ e™l¶æ²›~'LG )8%·é–‹G‹{Å ·ëFœÌF ìÈýLÄù8çi$¦Ø‹Ç–NÐi:‹á<¯zž“lª¿uøåƒ·Ò*µü¼[ðËîൿöó˵ÿÛƒƒ_â‰Uî–·‹+‘A¿ ƒ¾¦½íz“·æŒMû†õ ,Z„Oaû]4g*¶7A%î´øDkC„ /?þ«ò¹`k2ChŽ›FÍþ÷5nücB{1U/tþÁá} å–|Û¯±‡Îã™ÈÎä—ØÏâßûŸîûXÿÑýŸÙÿ±½ÜoÅ7„Y„½î8ž=~Ø|O‹½â|ëá/=_\ü Ÿ…·ëÂúæ³`§žÈø k†Íýô×c’™À^9¬VµÊÀ‡Ra¯ ÉñžÕñfÎÛ±R8×$Åá¡Kƒ¿vd¡øáâXñÙzu—²N]çɽµs¼Ü+ïÉUÛÉïäg³Ù™ü9ŽÑl©am0aEµ.·ì9ënÓíX_^]Òæe4Aõr'浡‰fË.` ]Ñ<©ßÐÙ Ñ:ä*d0æÛ®Mv‚ñÂ\lh°¬ÙUa;Ž lNßJ[ÃÕr'‹îª_+-OunàÈË™ÏgÏd/†ëåµò©ï ~éðµÃ/¼ïÊköm6Á·M0<Ï.~ j!o`»õÚÅoç.`‹óÚ™†s¬Çh®bŸ7¾[ÜZÔªyè™›ÒhvýÚto ¸©`œ?Q8ÿkÌ1º â·ÂJGàߎ{ëÅS÷t¾ÆÛ^Æ›Ä^y¯x¾6åt7çi·GûÛ­H‘hŠcÈþ}ë.ŸÍ[ñLñlñÎ-Üüºßô2 Œ12%áÆbÞΩ¤J‘"¡—É7çZÕÂf b²Îáw_ Eš¡D˜˜÷ ~Ù-ºm·Æñ³¹H3´&y±Áx¼rkWi%yy9唟ïc¶¼XN¹ Õ픳åH™ U¢«‘*Hu¬R Ô ;q7^Œ'…i‚Ty4Œ_€»VØ ÛaMp=>~•Æ+HuˆvÊÝr¥¼’SNù¥r½¼XNÅi?ÛùV¾Ÿe¼MXŒo‹Ú•¯7êF’»>øÛƒ¿;´rðæƒ½ýÇÕ®›ÌЊ»7b;Lyòäו×ʧh6=c~)ÎÅ‹aŠ&h,™ÑÎRñÎï Òào}tï+{¿ñà:¾kÙ6–|+¬Y¿^¶Ì-¿íïÆù8“6!™äÛ¾-Xêj\‰-4»“ws¯¸á'³1ߦUº˜&7_Ý/úy¿&Á kÃßt;ˆXaM¡˜'>žƒ+`»Âé%¼ªoÌì¿)®ÒXle'²íüfý–Ûök´GâI7K×êq¨C­lÃËv8{È.¥â&ñÙöÂJheKy;?Û¡¢Ý¡‰Á;ƒŸ9üæÁÂÁ›˜ÜÀcΩtäþ`ð([Îl  ¼<5Ã<‹ˆæcÊj-R›”·+^çbO¦œ¸xC”Q&s¬˜Œ§Ša?—µ|âʺãî$ ÕI7F=ØX‚HŽf Ù2¾#OÙM/Á@éLhïRf›¼Øo¹i7ãTZ@¼Â‰8žèÊì4ð*+WË{e‹Í¦¼,Vë)#?E¯R›Öćâ•;(¤ía•Æ5ÎÅ$!†™G/ûôî±WåGÝ‚?éÉd(n‡„ÊmÄMJÔB¸ 7æ×&f”°ÐQI#Ú‚¦§Ú‘ûG~äè;˜­Î¥*l˜ÔÈó³§¢œ[ÅÜ+œ!r¤É!¢icZ)Vó¡Éc£ÉA¢2(€Í©*EÞtaÌ1ÿ¥’ëHs1¼y›eN Ÿîª¹¢á»ã̑ϱ£4? *Œ°¬ÚÑ«Òp;²šË†åJ2` Ç­†ðÞÔSÀóØ*jññªNs:›ñm¡€¾å`ÿqž'ü®3˜™õ³”- åœWo¾ÿóÿzÁ²j]2Clqjâ‰úßÞÿîï–»å­âòá O>°»ÚoÅÑÀÒG‹>Øòf‹Oaž‘òSŒï£îÁìi¸ƒ¡YQå†ïÓco늫oŠl,¥Ö–Ú4•@7åŽeTáF¦ŠÙê8ÄÙÒnœÊEÏÖ¾€-Ú`LÌ– ™¢hJ[Zu6Á¶ÞwðØÞ‡-»H¯B®nzdÂ]`E©÷?ðÕ¡ÏÁLž]¢¸i¥€½w+1lÚœ†ù€‹Üz»<æøfñÞð!ÜäkËjÒ/ sâ–ŒY6»Í(õ˜¸á=+ÕHil+Ž¥dTÏÒJuu‡œpC^MC }ðèùƒ÷í?¶÷a67ü/Uaxò¤wIÖf%´¨2²½P-¡¸³Zºgè˜ b(;ž_`Ã$ÊPlãÝÕ´Ë!o‚ÏNd§³ç8Ð@ÈÖêUÙJ+ë`Û0 Á0ÁêO)nNÃÙ´Q«CEœÚB…pÙ#þÁ² 9m €L=jî`2ÙPá§‘âoµ”ßaŒ ÿ¶5”Ï.0¯ ƒ8 ÷¬ê™,-ægñôe¿¬A…BUð™3ð¦¸÷Õ¿þàºÅ(íøà¬ÀñìÁÂçe:1'ø DÐã &tBDU À›²Æß¾ÕW@sÙ#Meaü‰Ê×Cq»…bleŸ…ìï«ÿÂàâÐGÙ«R[/'ëØÅYtWýZeg¤€üq$%žã/×xAÙÂS>¿ç™ “µåt@1­Ý{:é€.È·ž¿šßÉß+e±63%,¸ëþ¤ŠÏø¿¤Š¦Jî_2•±¢zªÑ^ Ë¥hEÉ™uÀu&¿$Ç §’V„=Rüe€Û1ädó‡UÄË ¡(ŸÉ“òç©¿yðŃ71úÖ£°«L˜“vW¶øeTeÖI‰´ºêü)¬«ËÔ0bh’fo}ѵýZú½yUj#i¨X%I0Hñ¤­L«RG€oɃQÃ;GbvZ­ÝÒR0°pÿÈ}bUò. qWÁñ8L@3Æ…2ÊH:Xóqñ3š*<¨.NunpiÞºvìOÉ…ì(ÔÔ|œz’YO÷¥?ƒTÿÿTûß>ðîïò" ÅN~'?+äOÖ®®GF–¨¿â=ðçj²9®Ãa¼ NPü’(:LûsYÛjiöx"ФEuPƶ°”ºI3KQ@t ä½Ûñ&}ƒ‡öPÅ2ÞÕî©Ök>­º^gEÓêè^ݺœ»©Ð½IÅGž£(!|‚yR›ûYðW!7°ÓÃÐø\¸9¡c”äeø‡ƒŽ-7ܦÛAƒ…Ö±?k.^LXƒ:n.;‘ŸÉž+w‹[åe¬ITL&‡S ƒ¯&g¸‡Ø›™²ø‚Q„Äʶ٠/ŽÆ‘øˆ,éùéì9<Ý I M“Ls±Ú´•»Åíò²ÛrÛîuü«}ŠTqZá >ž}ôªpãÁPN }h†0l´e7¨«‚eF(àœ(QÍæ¬¬`„®· ç´Vƒ}þ„é5ûWö~no¡Õi°´dûW%s @Úð[/F+¦ö–ʱï˸¡ÏØ$‰Oa7N9Ïnq»¼œ½?{&û\—FUõÔ2ç³ãÙÔÛP‚„튎ر‚Êœ“Ö òe1,kÛj«Ü‹ÎÅ‹•X°‘IQÞNlþ„õ¶ÐÛR» ÿpÞá¥òZù$.Ôt'ÙŒoã2æ ä}Û¿b%œd¢Ú$® ÀçB3ªr¸1[É4÷Ô Ã t„ħ³Èˆ"4ÀÇ…„¦ …Zöà ݦ«•f ;š”'ÕâD¾;,ð•”_™•²Üñdb+L‰ºéûÛûp“>»]¨vë²#¦é¯Ý0¶5˜,Â{à$¿/%ŧ¤Ë•žÊ`>šîÓ’ixMñ]Y1S‹Xñ™äG~üè8×C%Ìš¬t.·23­Ç|€ ’ 팲-ÊÐ0ôk¶€{ɘ0´šÖ؉Ùz{ÿ»¾Ë2]?zп?mw\~v·±~ ð‰e(É¡’ÓÆW”é ‹MI‰5˜èr†ùéì9ž²|_§)òPÉ·'ø<–á‚>züùÑÍ£ß9öC¸ûaÀÕ4¹mhfuÄ0H´r}Š÷hØaZ<¨{°¾ì´Š™ÕЬ¡*¤?“_â±ÅØzÊ Ø,å©ßŸ=“}±!|ƒv ±98¼YÜ&1øµÆ‹ïgšH ÛÃH>‚÷l£“´ ºyyx¤Ôd¶z­›¢«jUN2Ð[S–µidÙ;Û ›ñ9µUϺ7EÓ`¥’-6ŽÓçpÉÖÈ2 Õ->—™Qh¶X\¨Øé¼§óµ¸/†Ë©,P@9¦0Y;.Æ«q8W@ûj\)eÛCüK~_¢v³\Žãofír6Ü.ŸÊ…E:Ç+ß w9Þ7©2RâIè7éÆã]6I´ÊÓ×ÏdíŒ2’ÁÚ)Fã©ò©„jÅ›©”ñp²3~8œ¿š·òçܧÜuw¦³Û‡ýT?Zž*_æåmSÅÙD6ž¥>1“åX2L¸A6D ø/‰ÛµW¢Zö¬(Ä×å $…ÐûnÌ £‡%Sa6¬„)GnÓ‘Òê¬ätÖgiéuÚ¤VI×Í/ D©>Ï+a²\ ‡ÅЭ¡_Z<òÑý·<¶÷xÜ ·£(ŽÇ 7wXYL<_rä¦Ð/ÕpÖ X–ýp˜Né”E\ qÇïâJ¥’mdçª …}OŠ7y¢¶'6vlnüºßôSa:PPÁ©´«špãîy7ä7 f»Z<Œ…©¸ÛQi!ðïÎÃûCƒ_b.`9ÛVÜŽ µ™ˆÛN|«¸·ãóž2ªymuQzº“:$—s¾JwH¶@~;²ANÑ0$[Ÿ«ê pÕíÐl¡)ñ¤(»éS…#ÑXL9ÑUQ7yDQR Ì|´D^a57¾â:ƒú5 #Œlõƒ×¾¼ÿÖ8,Îø…l;{ÑQÒÿ([µFéWËÖØÈÚÑt]âx?”mæËånq­¸â—üE¿fõ0å7|Û¯±ñò£~į †ÅfH†˜2è[ÿ 7…dËFÒÕ°©WÅaÅD]vËÉQ¾öqx@›gÿ Rå)Åx6\µª•MbÊÐÕP@/¥VÄ”¿f´Ï»± ¾˜­†l©º7¸ç&¸*‚@˜Ç¾>6ic) b[Ä?WÊñæMY4V1˜ ªLàÍ ÔU~ÝÆg _‘Ï ¢YØd"ªHÅÚÄmëî¢ ÛâïvÇêœõȧ3ówqÖI-¡ÍÈp¦ý)9—逊z’ŒÇ „Fq.+Çfëð[‡_>xꪀùO=¤ÊÚêïÛlÿøkaÚQ!D‘lëJ¬XÄÚF6.âõÁŸ‡§½ñÌ=ZŠ5(÷³iS½ (hRñ¯øh¬™Üxìþ›¿ÿïdF‚ƒik¶,–ŠfÈÛal2RVä¡ û9ÎK·¶Ô4‚6×l#©‚À¦m  Zw7¹/gWì&ÉR[øžÙ´ —3†p~¤{$Èó—‘”ÀŸ6¹„: ÉæEÀ  Ò‡œ¬ÙÌWó0ŽÆ¦Šû$ö=Ýÿ±þ#è²ò cé )qŸØøu¥Tµèëeþõlå;h\;&?=—šËÖªhŒØœ þõRy­|©ŒbòX7„i‚fÕÅùÞØT1¨ÌEè— qñ³9åræ©ËNeoÌ¥Bì8Ú©a”?WIơȥlz 9Ï GÕµ¥²}Úbl\ÆæÒ¨Ú÷à:AðË5‰œ”Àec7ƒ2,P(ÆŸ°iÃ7sFBB™c`ª$c½`V;/)õ. Fzꀵ´Ro[Ü./£!Æ·€5¼ÖT¡êâÝhJê·“_B“Ä&LòÂ`=¬¤b—˜Ì:\1Gû(®”-–îc +,ÄñJ¡aÉ{r‹îf•¤:Ü£´ïmº·çî%E- !'hŒ(ì†ÛÅ”õÝXÿ;î¹í0Å0ÿþîþµ½™O üæà—èYú]*—èj±–¯û™|‡é¸î÷§RøüàW?Ã5€Žˆtà£fô†»I;Ålq±˜Ê¶²ílX”ȩƌýaÜŠ»È…ùÐ ËD´¬ÍœìÛþ¦Ûa$ ¼'O¾í–\%·MKtŽ‹?.v‹ÛEò}xrϹí0OäˆZ,¼'aãd+E•œ!|ìü¨j0™vˉn¹¾Æ+’ÄV¹]>OCtœˆÍÖÐÓC¿tä< ½ÿ÷ý5ÆçâXœRì$r7"¯ð½ѽªv‚9RØ¿÷õp1Nyòm¯Ú¦ ôÉ"…{²o²DWãpÜ·SPf×\Ù*_çÙ‰V>UŽVþÔóù«9åI×ô¥x->‰9D[XãŸÍÚ©ê€Å?š#ñd<OÇaÔ›£qSGTce‹ÙÕü’$XF‹‘Î Å}¿N×HPò|:¿ÓwV¤)n%ê͆Ò/ù¿–cGBñ¤®‡V˜âKúi¿µ2wÖÈ#Åž¿µç¶+V+‰ä(!\âþÏ„s ¡Y‘¯ÂGvŠùι¾Oå¿Ù÷ü®»íÏì¿oÿÔÞ‡…ˆ`xXÙböL¦Â®Háb|Õ) H•=ÎÇ*O¼àI0FÂgÖDsrÂWpû†¿êDÖYv]„T¹ñä\‹S¢MúR‰OJÃîÇŽ|ðÈy«½1ÍEj:ÎÄ67ÎP^ JÜMFªFÙO“a¬¶ÇK ©˜•ú}É8/„q- S|N%ìC‘B ê'ܸSa´H˜ ­rªB¾æËçY~WSá*²UÛtË´DmZÃì¡ìÿà-òï­îýƃÖ }õ=˜{ð÷§ü‚Ÿ÷çгKšž ã|2Þ Ã4IcU'ÊÈ·q›AJ¤–åžãX»E+\Î({&Kþû¼¬kº·+úlW2ó9ã¼àç½ 6Çq.¶âÙ„ÛΆݜÛvSHÝà–´ùz~'ß¡yZ ÷úÉlÌ}|èƒGÏï_ÙÛð¸{Í‘F«ÝVíïÈú] í²å·²íÄœ*fËS0b‰…Ï`ÚÍd;âmÑv2vâ¸Ì–­â wÏTßâk ­ 3kǸ¦z0ݰ߮ªÂ…ä+Ùt]•ußC/ÄBG«îÌ'úâ/~âð~ç©Î{:_“|™?­ÜTþªXW–KõpH\ú†)®ÎðTQSTž½fİ£.°ºé(gÁf¹+i7•qX®|®ŽPc•¼láHS0þXÔLõþC¨ž=&ÓÒݪYØÏm?JËÝãÒ%Ì$â=#=GN¿k„ºå ó«ò§ªãŤ"ª¤ŠC+<.è+ÁFòHá§³=™¬š¿ks¯—XRc¬x±õ0–]¥*d —S‰;¢þ‘HypTÉôyðwP´TÝ Ü4Vªö™ %(\jƒ ÷=iZÞ.®ˆK ê¦ýO÷¬ÿhJ·WfKå7áIÆ/Xî³.9~]Ð%6""˜çÛþû¹-v‹ÛåeV³@p'b:-$C^H0ÕxšòBâûâ“¢¶Â9z^Øï=9E™S0…¤yN·8W eQf¤¡«ŠבðäRìâ'~.„¥ÈØBUÛâT©ªaß#æÃwÎ~+û°=¨Â’Ý«úÓ¼×´ox%Íÿütöœ¼YÎJ×ÈÚ#8p:{ ÓëâI1–1dˆ!âyPòÓS8Çpîñý º¬ðËg“ÒVqE•+ƒäK½%"}#…ʰ–UrNÌ÷1ߊRvqÝŽžÄa^ò}©±øéÔXœÿåí<[œ?¼…TzUŽˆõ> ýÀgãÛêbÄVìyŽÀ>+AœØc¨ÑçRêüÕìNßÙÄ=aÍ&ÈܾfFš UùHÇð„PÌV%£,gë©ÂTK{l%‚ü@ªzJ™û‘ôªz´\åLè^-Ü,¹¼†âX Tã²T’ÊÓþ—¾')GùÝ4Ê•²,ò0›íTd»[7©M"•Ažt£–šÃ²dLˆð¶3…Áh¸ùy´¹¸· ÔNPËx.´ÂpäÖ6`ŠÆ–—á¼Å¹”Î×Ѽâv‹à=êvH]DÝ™I<}h(÷2ŠK¹°Òå“ÝòVrp ò¿”WêF§Åô’Yì`þš8îÒ9ìRDS(¯'è£%—:ŸÉ/ñ¿ªéª_±âI0/†©Šy\QOÑZK0ˆgyy¹E0ˆÖºWL&+Ü*/s)ußLß…þÃ$¶×½ç ˆíü‚ëÖ ª§GpTï̯§~vܧº6g˜?Bc”Rì]t×{Tÿ‹ èô"b«íä½@¾O)4Øæé& ÇÒñhØÏ‚Öh(Ñ{J¸UÝHBÀf¤˜<¼1:–Ë€¬ v“L €%WiTVù8*’w ægQm OÈv;.Æ)^Ìœ‡E¾ˆ;¾,ãV‡cbÔp.I ¶tŒ(£‹èÜZYG\‹ÑD9ll›R{sû‡ÇÖßPp¾êÞ\)»JŠìzy­|Š]U€5IãÉɨ SµŠQHùhQYZƒrb ÂÃO¤«˜H÷à+ß;~ë»"PkxU2¬XÜhª½°\VbZCµzlàxh¶*ôE[ .Îä\¼¦¸&ñð›‡_2LƱ0œ-f팸-;ß[q¥ø¹âÆÐ¥#<² ¥Ô)~N0S¤XQ7³ßæB+ËÓ¬#¢ç”Ö–IsGEnõºáÆâç—•Ñ\¹^·ªóœCðRq­x„¥‰©b¯Š¶Ü¶SÕyÙìB •-#¨ O9O…+¨1Kë²TòÙ©^äÁÌ¡qÌ)»Ów69F‘âIZ¥[Ú-h©†å²å•Ò#¢ñCbkwE‰x!j­&Y…gÉõ¬.¬ÈžbV‘/L¾kiþì•°(³*¦ ­ð„ìf ¢]½Œÿä*—+sö¡bu‡ ‘fE×Ý­ƒŒ0>?{OåÙ¶ÇfbH×D¾ŒteWVNu‚ÀM©é³I‚N9Ä¡Â=ÞOÂë¿¢Âß ?©%Uêĺõ·Ë+J©}2ŽÅa†ä9W«)@UŒ’q%ñ{×fØÂ#TUWJóäI÷Ù•¢‘¿b+y>’M•”"!Ó xu % ˆ—  P“WÞn)½¾i<ùÅlÈ$a šªºwzŠád{cµ,Ò“òÇM·ƒòSò–÷Ï}ÿúï¯Ô“µRĸqç,èÎÖšC¼)O”¨&h]™ á'^ÝN%Ç P=f'•Là£å©Î&²ÂÃÕ¬p‡´5†8z„0á0(Àïr¦æÁÑpÿ,;›:upØ`Ç–øØŠH+Ÿ‚RÔ¬¼Šjß 7S(âŒá†$XÊ£ ËñnäR%0@¶ÿvÙ«²,œæÆnØ~ÕÜ¡ÕwEyœz†ë‘TåPœ 1u ³³e1è5Ña³\{xq˜­7ä;䬺ÕÚÇ¢:tÄÕ€û—ÊXÑÊJÀšÅÌ m ¤8ƒÈw‡«§U\óT×"Â/Ð;¤±-K?—Ëb{Ø)8ã@Z{oq0&›}«¸"ûÏžÉ^¬È¥•º©ÍßÙP[Zì–·ŠËù‰ìLžÊƒ@­‰We¥fq± ^úôЂêXÓЙ{«N‹¦2 –"‹"½¤«m£ës[‰†^–ÑÚ Ö7”3<´%Ö 0±eY¡áÆ&# ¥Ýø¼ªPÜ;ìÒÅ'’7ø¾ýÇö?ŒVœ ±8,³¥}fGÆÊ"ãÙÜF]d&Y¿‰ gü$Ž-oØÇ7uÛtK‰A¡lAºç ÕBÇZµª¸A±Ñ> bÕ´~ñ•ÀaË*.ô(DœßrBÅ¿Õ!Ä3ôUE¼ u‘º³àcãuñÎóOõ]ï;#µxÜ6 ”8¶÷K®ªü²ª9úyðDž°¢}°Ø¤hVô0ÿÑþÜÞ¯àâ´JäMÍ,®^ï]•BƒQ o"¢gÑ(¶Û,˜jxaÕ6 mì[cI¡Ö¬¤§èî `ý)ëÙ=\ÓÕãÌ’³­Òš2h¤ð®šæ^Ý2³pãÄF³M¥æVºÚ*¬¨Š5}ø»±•JZí € Sª¶p|3Çïû €s#gØ»ü½uûKèÎ5jH‚u´§Æ“»W§ åģɓó7˜6«o; #·^†ïD~&{Žäγó[R½[Þ*.ãNÕ£ºúð9;þ®]ÌöÌX®¬Ê€M{«Ú•Vz¸7w· ¡À‘Á'íÑN ¦Wõ^*®SS&ŸÂæ"åuz_µÅ0™Í–5ÄV£ýDk:9Ãx[hÔìâÇPšÇ’)kzš¼Kž!üŒùNM¸±âEðî±ê C—íÈÂþÏìÿØÞ î¦ök8ìF}yËhªÐÃbŠô<Ô"2…¡ŸR5 ±HâaŠ=ö¶±SÙ ïò_…Áò2ÖÍ«ö™:–ÿËúPøxÊŠ›rŒœ­TÅcEjvÝ1èC÷½­0[á vÎU⡈ﱟüêà?>üÖá—ÞÖ¸áOS0òp€~“2T*)>ôgMàîqn¾Oââ´…A–@Ð÷#¨®Ø Gÿb¡žÙý`²M z0æMßÅu¾¼bÏ¡OÔPÖ†é +¤Ç›"›3DÁx6¾á챿ñ›<“qMÉïët31q)µ»´áu…c6¯§œ’†–è² õÀâª&n{uĦbÎ •ð±1Fíá(šê?U öÒ*¾ËëS…œb‚ÀCª œ^|}¼âÐÀϯŸ§ÂÁ[@ñÇTö)¯Ê„x'85±z‹•˜Å#àÛ¦¶š–#tÝÄ Gx¸G1ð”•`4¹Æ[á½&éDåGïF½)só„Ïn9\V[ eílðØ” °ÚR8Ú¶bÔ&%¬©å7Î{,#ÌÓ”í½$æÉ ¥6ÛÈÀg´Q¦Ç&»ñ£‡eÛ‘¨¬>e Lï%tYÐ¨áŠÆc,àƒ†Uiê±– =(+(ÛŒÐ;Oýëåf<É< qgÃJÙ’¿ÎÒµ._ rˆ~Òä|sT^+Ÿò[Ù3Ù‹î:mº:OÏt©±c? CɃ8YŽWˆâf2|ù:ÝÉÚ‘âÅôÚ亳Žó2ÝÉýÕƒå½÷¿µÿñ'úí?ÕCÒÞèI­Çs•ígô¥Ð O2ØééŒfÇd”ŸN5÷¬¦ Ë/ -æÚdóÙñLAæÙ`FiÁpm=Ëé6ÑY…¹ÃSy6TµJ“sÔmvu]d¡h¿çãBT=Z yJE3˜µd?íUvU ýtvø7÷¿‘ÍúvöJ9WÜ.‰)ÍR¸_)WÃrùNþ”«¡•~—Mb7´èrÅ«úâþ›âÅǹ ¯UÞ¼¶Aÿ~<Ç]ºUçLãf•‹ß¢¶»KqS{Rùzv§ï,ÓDå;'èL‚Y¸cƒ%" ¹q'ºéJa"®¤˜Œ--"r‹nƯ%j:µ=•«¡U1 (P˜b.nâÅ·âÉÍÁåét!È­âŠÏþÑlh…)& °Q³áù¨hºrbEÀ7QËÎä—”³Ê¦wcÈTZWMwPÈ”ÁÈ–êlÚÏøvßÓ}¿Ôu4.ò޼- Š\ÿ›ö÷—Ý@_I_,º¶_ÃLÂ4CÅD$H³Ã¢+¤æõø]T†Hj¨ ­ƒP=‡H³4É{~j¾[Ô]C’;ˆg¥NÝõSK÷À¦íN~6I'2™À·ý¾)É!òè2¥²c{l×nE¢D¯Gƒ¿ÅïÈ Ú`]¤POñ)£É*•ì+¾ÿ?îÍîý÷G7þѱ¨áäâ z5íÏeŸdï°Ti`MÛЃ–ûj>Y#@õÄ,¦ËTe%ôC'A(ÕŒÕ+Âä¸âdlËSª=€EJ…ŽDHG)m%Ø †Ñ>>(| äk‘‹E³jyˆŽNØÅŠp‘s­‡X‚#¨ÔO @€Þ3ù%¹pP•¹ä¢hÚ°³È$ÅáΓ÷t¾Î™Äo ~IyÌb¯Ñij„ÙÌüÖ«ê~µÉ€Àq]?u:»$ /Œýºv eñsI&ÃU…  N¦&˜¸h0ð”0YÌPw¢@Îo —4Vå €q”§Sý«cuõš!Š´E힟HÞf] îŠ• 8†Ü¨Ü,«b*~œS‹2×âÑi[ržòm¿ÆxÏ4yò{-áý{U8˜í%5€¦ÌXÍRÛ¸»‚&£«Ò\çñäšQ7u]˜JĨU äa%À Ú!ökS‚T ¢­ày.{>/Ц• öÊZ7È¿ó'¼ø]ƒƒž‘ ø.Õçš·Å0ÐDñ1$mÐlÊ øQ6PÉÙƒ² Åáwùsi¹“ßÉßË  ¥Xpƒe7œÒ™]Þ©°_4£¨:F¤M€jeÆš Ž #ífµðK†móÎÚËRM÷£&¨†KºŒfÜÔ²DYDðDðœr l*ê)ØôÀ1 b§J>H „òF»Û£%¤¬ÖMÇD >—ÒÝDz'+B è "h3ïØ±—áâTñ2{UR¼µ^ëš1V…’2VÅ×C^˜*t T3®5À¿ÔÚ±@»a¢É ÁV‚·45O¥hÚÔ&9M‰êÀ8æ–j… ·'àPÌi›1QÈæ¨UU`CsólÔŸËÚÜ“ \8ç8öCûïÛû¹½¿î§ý'|›æ‘HÜ2^ãOdÛþÒ«ìX;‰#²f¼¢8þ·ßòmߎ»n3*P™Q-ñs§‰ˆâDÜæ’žD®—¹ø«å½2•€PÝD³)(>Ú:ÍøÆ€²E?“­q©³:ãA,^¼Úá>‘x4KÙŒ_ãû‘„Àd Ã)xì.qÓ~ÛµsÊ)?ãfT=>öû³Ì{n‰(’èÁCçJ1”ÓDD Kð8™ùT3ÀO Y]–öäÛ5«Þmºÿªkûµ°ä[AR=8qî&íV…ÿÀSSÔå·íκÙÚŒ¢('Êñr8;Ÿ?“ߥ¥8/`q;wgœø•/y†¨¤‚Š q”y¥°t“Lz7h>¬œˆ­óê¹ow±i‘¹ŽgàKŽ1¼0å<›œ£< xprò~ÂÒ"L7å3ó®xäþ‘ÿìè;˜W…KΖ³ rƒfWÕ‰m[_†Iz鵫›VcF$µ¬ÄE|d‹‚|_“ 3út¶ÓŸ½[Û` ?·›:ý5UMâh+](vÁæòH\@  U„¦A¼-2>´ Cßw„:xßþcûÇè]CVÄ©©'cò§ù®êódªG¬ì¥ٕأ"WœYƒH™jr›$sÀ’° Cý°[®z:*9meÛ­ÎØûVÒÉ]‹_ô€€T‹ªr†+ÈpLoËcƒ¢önž&›*6[üJ@er š*1:¦EUzözÒKþ‘ý)p­±DXl;2¡5ªÅY?”m¯a©P‚«ë"Õ˜ÃhHõH2€$NjnV‹âÔïÑAOÌP¨P¹*W) ¢'À3„?ª"Ü„ó,€gê+>«Qt(©ÑÖ[žø®C„ðç+RŒ¡7Âílª¥âš½+ûãÁ¼ÚVa&}6©­¦ >•£©ÏV"ZcZ ]„„fÖ™z”Éׄ#*V°zÅß´+NV:iÔ:Vë)Žüñ¹[§*ÙÊ…³œiüi¢ŒÚV©–+o%Åt‡U¯mÞi[oZŸQUšMË]FsÉÒ",×/ùІ}Ø6³P‹ÖI±Þ‡•"±Uþ=H¡@)@$ßúM–`‰Þ•”CÑ8ÛpÁ¾q¼[ôÑèX/OCZluñŠ™ xÿèËà=àø4uëk*Ù±BŒ¶ØÈÎKÓEÃw$?òãGÇãh|G<) ë]²sÕ†œXy×£xH¤X¦ƒür[¾cYÊ£½ÉJ¨¬Ÿ-„ Ã[$šª€‰£©ix¹R¶ê Gn»êVÜó~Ý·ý2Y~~ܯ1sªØ-n—³‰l<;'’r”‘o3]“[¥¡?"Aå”)N9·P)TÌz‘§nt*@èŸìgýE¯8Ù”IMfc>™ÚÅì™l­x©¸VíÒmz™GÌš*s‘?žõ}jFOþj¦*;Ÿ9éw)mâh¼âÙ©–ô~Æ·ù¹G!cUÝέÎe¦ ~{hðÈÂÁÖþØÞ‡UŒ²¤äYÆ*ú4fÏ×›_œ3¡jOcq¸\(ÇËs唟­æy+­5ÞÔy¥ 1²@*¬¹^n&¼Øùãþ‚í+žmdçÒŒÀŽÍ$JĶJ·ˆ„@>j¾ÅÊË ý³˜N[ao£eñ*V+f°n»¡ ³GD Ô-Á?‚œ<–hXÏÅü°£Î¸ÊCs^*¯…'_;üòÁÛz>ñº†'…G*XŒ~nu»š<,UTd<4ë¶C²˜fcÃ9‘±EBVpF–=벚:*â’Ö˻ưšÚ©ÛfîM?ªBÀÈòرµÅäŠÙp¬ A¶r1¸Ž†X†ËÂÀëá3cïe….!rd«)HŽ­Hµ Jô TðñÔW"¨Q±Î„2—°~‘J…ˆ9^¥I%Mµù’_Úp ì—˜DgrirI¶ Ÿm¨f!#Þjî ¿ƒç±@¥:(DàáP…1´wXÕ6VxœLŽ:Ÿ8¼/†x.¶Â—HË•@K4Ö!bº©$hQ?~À[y;b«(4LòUÃÑ+Lj÷”ˆ‹¯£:>æþÀ7y𤽂÷€Ÿ(]PØ>Å›3d;ñáÈóâböthSK™BÉ&秳簉/dK_Áü¬¤k^èüƒÃûr+¤Ã-·Òb3’¾30”ª/ºdX*‹õ;¬T“®†„ˆ )à æ)ÍÃî`¶){+ÇCøl¥±ql©áG¹ig›¶©Æë¨² ¿£“<颻êר—Gõ«&ž£mƒ†ì'ô‰,Q­Su5)ô÷¨Ù0 *\71–Ú„ed|¸/a£âu²ÓÕÂë¥(àºqülÐaåŒ-ª…..V±YyV¹“"°íìËà)Å»Ÿ=§2”kŸCQæâÉÎ{:_ÇþÀrŒ!(¢AA.%‚âÒ²Hn jÉÃgÉ«ê x6œä)&MC§†p‹Ÿì3â,1·4ahˆ•¹§–c2ÒªÙþPz¿SĪlw9Q%ÈRCq6ò¦È3¶—¢GzÊP=pÝa£Ù&uü&ŠvrD£c¿kÓbø.0ºRŒ3X¡öíä–³k[™sã¬b´)¤?3¶DgÅ%"j§å&Ij–TÞ+© êk‹šâ ·àæÝó4DÇéB—˜r«ô Óí°ÀšHš‹D‰À¶”µ3eæh•Vª+ÓÙé¬M[´MIhí;ý_­r1«´‡9a¬”KWãJ™Xõ³Ÿî¢;)ÇŸ÷g²ar~ëhàÛCƒï'Âé0åNøÓnJî'ˆ"Ñ*]L#œœ^?ßÅ Ÿ,Ç*+ëf ”¦ñ/¢1‘¹™º ZØXy ªÊ$ 47Òk=¦õp1N±ÆVØ+)ìEé&g`Ó³ôÁAÙB<IîÉò,hPäI§i&eýP²Fü²—ˆèI¥"ËÛÃKq$òç²¼ÕýO×o[º¥þÌ´évüªoûWй¢UÐÑïýÙcçÙ ”ï ·Ê+ù‘T¯ÊêoÒêe·n#ÊéüŒ²3ù%‘œ›y6Q>3#­åWÊ_/ﲜ÷©Ì§ósùSs˜`Ñå%Q/e}QUc0Š7C/æ:üîVý²Á‰$vãÅxRD'ܸk•£áv)²EÑô^•lÊ(mÓ]LpI–Ä­¬]¢iGÔfÒ•”‹I8–¢Ê Q- žM˜ÊÍÖ\mt5QâCzá™ÍJjæbT*ò6§£2zp‡¨Ù jÁaà¿â¥¸¼À=apávÜ+žTÕ±Q®•ú²É/qc‚¾§û?ÖTίÜà²Îi ¾ÓÕ\ë ÛñPvÉgA0`º£OÁž‚E‚ì†d<»ôD ˆ`ýD1š`ìd1KZ ÎK"²“°HÐùb}ýG«êX½-…ìÛþUfÔ àŠ3ÄfîzhÐ]Âp ¯ØD‚ Ž"0²^ŒþAz/Ðñ˜ËïùHkz´<Õ¹›·ÚÈÝU¿ÆH+CéyýŒ×¹BŒ-#.ä–4^˦xÎv®âï"÷½NL%/OŠŸL[@B±áS‘6Èm×¾›Ü­¼<–”õ#~J$ÐĈñ*X}@™çãqá¨,-Š)ÛÈ6“Q ëa3ˆT›[t§Ýšò•øÕ²œ¦s¤ho˜OD'™‰¦¼cð‘hªÄô\—Ʀ¤\\_¥‡=ZŽ”OqA)MÒ‘ô.ž+[©w®< ëLœÏžÉ/•¯7˾§ûîô¿× »SÅ™b¢ø@g˜É“Ü1˜é¦6 Æ]‚qiÉ_·²g2BaÏ%P ðrv"˺„ˆKÇeùéL•Ãå­òå|'¿šTÃQy5?‘Íç)[´KD—-'áÞM±"kALõ”%Öø~\‰Ã,S—Mû‹™-Ë9JD'5dNcÉ_ãâj>Cœ¥±ø—Ä mu7ÞNm¯ò‰¬§ÒÜÉr%¼Gã©„p%O1¬Š8n Ø15Y`snÛM±tŒl³±Õ³¹ƒ©Ì­0ß¶ÖNÈFã9Ýè!#:ã×ʹ²U\ T¶Âí…7—û峺޷¿½'ÄìÊ\Žy)V/jjèr\+Qá˜ã§.X}.I‡vŒ¨hˆŽkÀDl¹M·LKu$$³tƒZaǯûMÒOû;Ò­ê†ÄméÌ÷œ"3IÚm>´BÝž¥µ½B—(`êµ/ Y¹=<©s¸3  Æ}LŒÒÕTÞªÖä¶äêTU7J­)íZãgjx÷ã»Â’”=CO k¸0/ƒ÷£Äm >«’ Ã|]É$2 Ÿkñ þ%ÚÞÜO…CÝ@âGOBÌ› ­ð²«¤e9›Ù{kV=æÑTg=É×mêü,â<Ü4a5,—Ø~?Gc'b/¬·Éõ•ìÕò,àµø ²ÜÎw«øè Û‚Ä ¾.Wð¼QeC½ÇSú„óh(SÅÕ¬LME¹ÚkÈ/Uý¥oUïàG¼{¤^sXÒû=“_BŒgÎÁûöÛû0oÆêlü^˜¾‘Jª4 ÎX]¨ø\àÇَШ‡%>DZ–Ž.n͉ìtv ‹º¤®¯YK ¸ R:•ò?,]Íææl_¼Ü(úB”-±\dØ7| › IüCû¬áý[S¢èðz¬Á²SǃDnïÊ-0,Ç{ö4QÑ„á瘉³µ~•Sµ&KOW‡{ÿèZ¶œÇÎ.”©>CÀÆB]MõÖvË[Åe<sp69€ùJñ°À Ú|e>}¦q©íé c¢PBìˆk¡©CSsÛݯG‹³²šR@<»X2P‚qXÑB,À²óxE ý 4ëÑá¼B\qMy|eaŒÝ°Í›’r^„ÇP?Ð0ž0¶ïQÕmŒ”¢6ð•m:Ó´èÈ BËÍGò+Áo¥>€‡_§ùAºC’ .n——‘W»ñ'ÑH‰qÙ4BÛ¿¢ ‰6ji7ij¤‡#›'¥DZ{^ êv]Èju*37AcqGaþÄŒcqÏ/å;¨Núâ¼ïà±½ÛJ4Ô–\Úbµü„¾€ENìa6ïpRTkfzŽqîï©Î{:_ã¥5s2ž†å„ëQEÐù½¤^dúÖ’…¸’´€Ý©9åMeÉV,°‰‰áæÑð®l[P›¡ûA…âÈ#õÔr¸0«h…qÔÙ ATÌ4vWn`ÏÛú;¾®`UÀ«jI9Ó´ }xó`ÛºØ aö(6õ¿XvÆ,ùŃ߹ „} V¨OñÀ5±ý‘#©ÂIäaÁ½a“ZëàÌ8Y÷ÿ«ïþÝß{§½,Ø.¾|:ëþ5i$4Õ‘[µ¬& +Þ ~‚@÷šrJ„Ì‘bІղáÅ¡ê‰À­‘Ź‚Ï‹z[L7UÒzŒÑÀ*Àny«¸Ì~,3À’x¡Ê‹‡¾Ö¸,ñ¯¶S±x¾N"{ ‘<ÑDõ¼ŸÄeGV8`…Ú|Ä\ÄÚÑãçå;Qrzp‡ÇÎäé8ül µâµX²‘I*ò~‘ ý›PN¸¢j¯€3gõ^ÞŒI-Ûzç?–RW«m^eëÀáP¦¤¼P½e½+B©±*VA YéÔóíŠ-G†4¼HõwPl<;²ô@ˆlWa蔣 ƒàHT•Æ‚ K%hev0(UXÚU†Š8âe(Á!=HVÃr)ÙR [†‹SÅh¦šíåSíKUÞLÌ9ÂGTI N$:l†Ú°õñ€ìÔ¬ô»hbР —*cfåÌÔv‰sv`ªð~¤­_ucÉý‰iÿM†~âKžÈÎäÏ¡ ö›‘0³±ü,ˆ¸Á˜ðU0÷gê:§Žý£ÿä ßfT¨šÝ‚K˜±5徘ÑÃ- æ±–jq††‰Ñ˜u¶‡Ýªy#äDhB¦¾Yè ¨>XˆF˜ÈvüæûAÛb}á¾à@`Ö^Ãò2¨£ ÁØÚJ <Å!¿`m¶µÁVAí+º£JD¥A’5°™Dפ—(; ûÝ›µÄ½MŒuæ›ÔJm°lÃCÔB}Eô¶øn±Æz M¹?üÜ Ôà1ðÖÞ‹©} $mÕžÍEÚ¼[šâuÏj± æ>ÑÃ3wv„Ñw³~e¥*ð^¯ˆˆ0´êæÖ/°›ºõt¬6¹ÒS UC­ï†×²½lVóü9'£8“hu;lÍ/ºMåh6ëÚØ1[¸toÊ‚­‚D@F|@®%Dce4Š0†?æ!.Gc›JØZ?tV±nk—ø÷#›G¿sì83Pšù­°²ê $~D·h²Æ—e`\ß&YUn¦©5UjTaWá‰ÅüïÎ ‡Ÿ8|Єjaé²°äÑ4”ÂX$‹Akk8l°‰æÃšÈ´hë ƒ>4h’Ða¨‹‹ Óx–…3íukÂC,Œ3€èUÙò{\6ÄSE¿Ø8’T(Ï‚ŸÛðÇJY_fe)]S9¨ªAñýz4 ˜å·á®,e„mÔ…†)‡v6=èP—»B?åõð°1$x1hJ,P®R×ðv-L¨\MóØ,Ú/å©°¼­rî~V–Ìb J»ëÑN©1¾øW í£÷dµ®zxanHçžG‹SÅËœŸjÒÒbcÁæ* –ãBµZQMF—="J–'e½34£È,Z„uu*ôI4‘hàpÏÇä@Óµ¬ŽoÞ]&¦MàzƒvÈŸ´ç=Ñl¡ñjì¤mxüèd &IÕ ;ƒkǪÂ)4™Aw+tk;ý¢Od¥à,`¦ 6QjÔ TÝ96ì$¢fGýipÔä á.×cÆ=œÛ&A2zèÍxZßТh¶˜ÃÅ2Ö ÇQµa¦öíw-À¯îܘ üÄ æ© f 4jÖ¡QK£×íÙc¬Y´P=šc>Þ¶,µaYaxS—Hú“ŸêûÀ»¾»÷Õ¿þàº.Nê D= ëš(â6”FËІ7‰õÔØÝö•CÁE[Ä£.Œê6Zc°¢á«ì* 7ÇÓôèæÑ?:v\¨zŸ#‘_#L9%þŽÜtÈdâ_ñ Šq‹F§Á«^R½>‰>zahÚø lh, n=4|H&°0¹"‚þpq¬óÙŒgø%ƒe¹ÖÙF| ü«Æ`þ؈;{ìo¿ñ›lª,ÁΫ­@ ±Ù†˜ÆÕ!FVzS cl/ çWaTCë5ëjNšÚ²ð8°ÙÂRjŒ~dôÉ’û1¸ªÅ¯Uoó†6+|æâÑâTq#U·Ë+¹ÕÕVÜ+C–·À›XGÖÜ/VRÛ(?ïgür˜ +aÊ‘ÛtÒ,Sõª›÷ ^Ü]6UlãÝ–ß®ú—͹íУµ^²Ëq3™ ñ–êòcµ·°¥¿^7Úv;YÛŸMMÃ8µh‚ÆéyVá±qãD¤¨äÐÄ]í¨°-¤¶¢ùΖò¶V²'rD"¶ÃšD¬á%%¦óa!,³¶ŠÉqëʃÕýÇöŸøüà?CºSî.ãÙbÖVüò'Ü’Ûv¯W b)ûd¹ÆÊ°¶T~"ÛN‹¿^ÆÙçx©gëµAiRz@ü ±r¶)RBàk„+²s‚7ÝôE–‚@ª¥J‹.®u>›ŸÈÏô}(ŽÆÍxÒª|-1Uœ {Ÿ#ú0qJAÁP[J TVM""¥Š¿Ê$mj5tV¡²Ì;1¬ûÆX¸ÊfÃH˜ÊNdÛù¥0[¶Ê§ü–ßöÃáz9Rž¤Y¢ä层›´È…€”[¥Ò¼#êÕó†I!¨$"ªÅh¼BcOø;þR¤z´¥”ú顟=r~anïœ'Ož¤î$Åa6(~.k%)§$[䯦òø8gâɸO%#•-ºÓÙZ¹^^,§ü‰lÛ_b¼1”ce+îºÍ¸“SN©L\+ñ†Wš…¦½´POÐxY³QwËÛåqíë–áj[iòS%±>B§ ±ÁÝ8àƒˆé±½7xwÚ-oW”Ð0»Ó•s#H‹š¿uËKÿ‰·ëOÉï€_¦‚>H“vR+ÃN~'?‹irþ„1>.¿èºÿcýG4…rhìU#& ð#Yêu¯”ISZ¨uÁ2j® èøsUÍ”h„ùZ˜ °‘ö‰ü¯¤xóC†:Ÿáóï÷}ˆ}4En€@•3˘¶Wf0ÿ oߦdñ0SŸà[H]ë¾S8çñmZÅ]A‹`s¨Ô–ðå®8õ;ä Ûs!‹Ýø€w [}"Ž%57dÉÛõ«$'CXÇ^ƒRjÎÖcó°µî¨`[ë´évø ¢ßT-­*ß„.™m¢™nº;ƒf;Ç`/ì4ƒ #å긤§£B*ÓÿC>GŽȪ¦’æåÙ ÁQÕ?Ñ’÷…+bºZM,0a–:hYZ8¹mm~ M;/t>qxßBÝè§ @¢%ö%ëOØ4 ÿÒTÛˆ•€Èϲ5†HJHºŒVÒt=¸fZ¡¬ûºøö± ¾GÐ ›S7(cÕM5°sûO[ ˆ‰µŒ,Ûr÷¦F'Ÿ»:ë}ÃÉÛÝö>½Z„¶Û0/~Œ?Á”°!ÄæF«n´½eBàÒ‡A5w”—U9®ÞæJíݶ»‹5(ý¡¸ø /#O yÕ!®Ú9QÏÞ`ߣ÷6Åek4F•œN¥j$SŠ™”GfÐ:TXu ¹ÊÇðíû\ßú~’[Ø>‰ĉa_‰ºYcÊÏjÝmºñtlÅ>S*$)‚¤áYÓÄ„ahYÓ”";ÊΠ©’<ò§9è62&Jï‰ß‹‘Ê“íÁò?•) öå9!–4û³Z KÒ݆ Ñm¡šÖ‘“°  1Šß#d[-ÇÊ–u›î¤\òUp )lWÂü†SUW»7®=‚°î…çýª_I„½#ß92xT‹ý ~³Kz™É26Cž¨íÏýHü´ßöS6q‹^÷¿ñÓžü”›vÇ]¯–e¦ØÂ~Wîv=.D%¤SN–· é•"Ü™l³â:º·Â|ãÝhÜt'Ë…b¾¸A®EWø»mÈÙ–òv~–ˆž¡+8ö^ZZÂíš(ÇË· N.}4¾ïÄ÷vv;·§h”FˆÜy¿í_IÀ¼#+\é„û>¤ÀŸqw‹.F:Ÿ¥%Gµl´&ûœàbë¥2ìâzq­óY7çZ~ˆ–‰ØoòÓÝ„ ëfËVq™®‡‘ø¤u­ÄÏBO®Ó­4Õ/fí”ûãc†Þ5ô#•¸w6ZrçüÏì(Úü 4^-o6IKÔ¦5¤k–»%WüßUOq·$7á¶Ý]š§’Nj äùCPs{ùxòmÚ MJ@ÇœkU€÷l @Ù†ßÌÚÜÿ&[ÊÎUógɵ]·bg›Htî1´T/ø8Çb›ÕÙ“ JDâ¢`¯›UM *Óïåx97ÜXL>ΆÛt;û{û+{Ï~~è«CŸ9 Úçv'7ܪ[q;Ü)!|ñ§(#?¥À{Þ27èfÜÉÖ³Íì$ÍÓ],}´8UÜÈ(£ì‚„„Šf¹†‰£ZQÁåmóTt§¥°†³ZFÊÖñ¡ù°=ÚTiÓîM°Â  Ä}@„ó›J@1k,b#hUSïI¦ ›uU$:X„ª.Ή\6~ñX²ƒA¢Îv8oJ)Ÿæ›8YV@mÒ;S\s³"ì›[w7Ý)î€ßåF Çþ›7üí7~“·@\`¸… yBÿ]Ñ•Ñ71sÒªzX£‰ ÓØëÀÖZ`Y âe|E÷4 „>ðZhtšt#zÈ¢”)!jŠl¨Ëó–}ùGüÁýo\`ZÕaàV]¨´R ÃÀ÷S—>ð‘ÿ£û nØýe÷3þ/;‰¢Ã? ?üÕøÓñ]ñGýã¾áÿ¦{Ýý[÷½x?þûøÏéÏÓ[éxxc¸¶ù¯Ù‘ýdöxÃÀKƒ·8ôÏõÿ4ürœ %ü“🇟óìý;üoúßò_‘eÿ]§Ïø{þ£þÇâïÅÿ™ûMÿw_qwé‚ûžw“î¯Ñ3ñ÷i<¼1 „o_l;ü‹ð·ü_÷¿è_ MÚ ß’y(‹ø ~ÏFŸ¥·Ñ¯ú>Ôÿd8Þ~—Ï/nð#ñyz?‘_¿Ä¿âþ3÷97Á÷Ægæ«»w?áþÏôwÜÇéã>w‹þ'³¯e¿“ý¹ð¯Â×ýŸ>@vÿo÷÷ûÊíÿ­ìY©ú ýMw>Êgˆ¿ÞÏãyønãgé…ø«<2t’þô÷¯éiwÏOÏÑstI¾ûr¶–õñçñ/ÆwÅå“åÊO÷r¶–õÉtüóô«á¿ ”ŸÍ?ÿ¿ì~ÂÓýk÷-÷lüÙ¸ß?_Éý—î'ü7ù_ú¸û8ÿ•ÎÅß?K/Ðq¿â~Â3ž‹ïo?K-¾‹è9ÚçßÝëtÁ}Ÿïß¿Ù?âÿEüø/ã;ü/úf×ù÷ºû·îûñ/Ò?‹?Ê÷æÿ®?ê¿ ýew™ßð¥c—ÞøÕÎÿëð¿8<ÂsOð™×Ý¿ußóè¿íßÊï”çÏ¢øAúkñ]<xnÄOÓóñWü²û ÿ þkø—åÿ)ü-õ.øœ¢§éÃ+ំ_â·É÷ ‹™×Ågâ¯Æ§ùÌþ˜ÿsþ/‰Ãï‚g#¿5>’ƒî—³µ¬/ü£ø+á|üÇáx|ÚýŒûËî©øÓôÏâÊVúÿ¤_ä·Ï3Ÿ¯È÷I4@ƒâãÿjxcMÏǤÅp;!ß9ÿõ™øû4.Oijn€hïªó÷‹ÿËáÏþï‡þ§¡ÿ]ñÏ‹Ñb#á—â×ÙbˆÇ_÷¿è_‘ù›î}Ôýÿ[î/—GŠ_.ÿ±û89÷wx¸ËBžÞJ?äQJùëØúI8Ês5#Il?ôAaWaut5Q@F 0b0àR ¦‘ “²!.Á±õßX–ivìF ¨†KÂAð’ÍÍPÍÝ·Ž7²oª2‹.¹”Q*‹¶0•™/àŠ#sÚîÿ¶ ŠØð_ÑWíÑtöÙÎùÎ-†äóÏõ}¡ï'e5N]lkCúß..³÷çÂÅ:±À}ƒ+1!‘Ê™ÁÛ’ ›©\rm¿ÆÚê,GÕqQÝûèÙÒ}ˤSç 4fE=OÙö:ÏØLø–B„Aø. Jׄ^à<ò»¶™ò¿P×@}ô%±k:Ž€\•ïL ˆÏY@ ˆ­sÐb ¯]ùPÐÜ’„ª‡M¢ôºc ’åã‚›nTÿ¾-NmòÍÉÒ5š*¤ÉÎÈ_Í„“Iɾ©· îÅÍ–®su‡8tƒñe«ÀªnáýX½D ?å©Ù_ÄJr‹¶±¥içê*{ËÛrR&Óùþ§}Òö¼tDþ—=b.îé{ºïcýGŒð‹ýLû™ÔÞ*;‘N òx€|)=‰z =…;O¤6´áZù¤°` « àÍâ3¢GTÔÂØJ¶û òv X§šF!ߢfxfD ªq]üq"h#г µÄÜÀ³ l¼sœÏˆ”ÙÑùÄÇ Ö‚zRÞŸê¼§ó5N’XÝ= #ôtl\’ˆ£Ó4S½ŒÝòZ¸œÉD¤˜MÈ™¸?ð#ƒ_B¶:Sïdyχ…°\N†±²&ÊÚLäã‚O¤G‹‘âd¹®¦ø™©nq7ÞÖ¸R¶èg²µ0ÆÃ0–€Êþ9ïgür\¢«q¸*õ$ÔiÈ÷¶Ç$º˜êé(k—«tµLØÙjh•­l1kgÃLûÄ _ÂÙbÖÎTÞ¿ëÉ·}›¦‘Â\l{´0Ç”u›n9P @R;ÇÂ0~ca¶ÕÃæç*wË•JÄvšf´ø5O߃كý}ÑŸôOù÷ø£‡/nîÑvòƒDO Ò·ý+q+¶£2FRb½¶«]”ó€ëÙ¹ü¹b®ï¼ìOdÛ¹:Ï^ƒ¸þ5ñ4Çt+“r«Üö_=Ý·Iýˆ¹™tcÔòä7}›‰—4‰¦R¢] ÂÏeÉ»!GNŒ]˜ •/°ND;‚ m„›e‹?Qs 5 n‹ñ“–˽r%DÙºæB«Lr'2¢Ô?‰MÌ]£a$(ý’&=/&*‹ùX¢s´FDí„4Ñ,]$1:åh¸]öHÉug©Eírµ\)[ÙVFÉ·uCîNÕçyÔ¸e¡¶b ˆ:Ü:üòÁÝþß8X=üÖáØÁÛ*ìõžV”„¨"⦵VÜ./ç Bù¼_Ê®úµ|ÝÏä;‘"ÅÏ TID°ø‰üÕüNþ^lUŒe¥òzȑӔ³‰¸­ ŸÅjq±HDŠÙ@aJŒEŠÄCÃæ©ÊˆµÓ¾ŠžB6Íd2ùœª¥+$YeêÏE¢)šˆ÷h˜ViœÈ ùMwm•¹È?Êç²?„é0¦X©BMŠÒH§@o><á$Ðu›nYjMÄù8Ìll7í·][U“ñÒÝpcQô*d^Ê7ó³4DÇ©&jŒU¥N'Üiw—ï¶bÝ£áb´8Uœt“~̵˜»ÜÿjÿGú¥Ñƒ×¿tðDÜã0ÍR+›¥>ºäƪ➥øLsa$<á6¨ǰ™ÛÔfy^hªd.­Ò Q¶‘Ë.°ŠF¶”µ³56Rià1ú¿hdî1ð œõê6Ú•ÒoxÌó^+ñF¾”ŸËÏÃÅJq#®Òr¬S@+åVÑ›ºÌÌùÐÂ:‡j{ HÝK¼pVéoz”ˆ”ÚGÜ-/FÕc·L¹./xÞ‰¶›S@ùNNy’`fŽþ*ÝÖï)ZÄê ¢¡2MçHé¯3ç^Ö¾øP¬œÆã¹âÙÎùN{ðmW‡^aß9[Ï6³ ¼‰Ê¿üãÀ6GîŠÌ}I¶­öJØçê{ºÿcýG° ,X«%n-;êK5Wûµ¡ÜØÐÙO@‰:vû!µ)[춦2"8›W(ÌÚ$ÉãÛå‹si`¬et hŠJÜÙÐ;TšvÄÂ’T!ôÀÖá¸óyljŸ±­ìÕüN~vàmý|KþºT…0JdÐGSe;Ü`-!·,åyU@é¸*>ÇöY‹U™ôÝmA  Àz: (Ò ’uåyýU§½N؃gmsvh¼ÀiQ3D©”2øìª žÃ|žiR¬ÃïA³áªJ™>4¸NEªÀPŽð*8Op® ¤kœÿ¨ìÂ×$"¡ï'õ²¬³‡2Îß»ñïÿøw/a I$ÂcJ)  ‚åd‹6›x¶ÐÃ|ýhÝmæVc¶‹"î½MtMû]¼œ:˜êV,v£#†Ç(ª§IQ÷ßGU“P·-l«ñÆök0nMx"Ÿ™!y~ïÿÁá}¦#5aÑ_õk?¸ 2’E°g²“`¥|äF‘HX<=èĦÀÅRI~R‚ý«m¥bn‰Äì`i±=RˆTg)œÄ·ÙcÙ;4C‘a»vÊæmÚd༕3 *RÙÉïäg™(50 Ôqal1#ï—ÿð¿;zñ€¥’’ÿ…òÉr û‰ü§³¿ÏiÅÁ¯üüÐ N*3YÓ™’RýWáëaA’¼˜¿çúêïùïù¸ôWÃãy\rBõøëþý Ø~Ãÿlv’Ï/ ìŸq_qOqršïö呲(?£Ì=ð&mÐoñXñ‘œ2—q~‰®ÓgâïÄ¿ÿ‰Ð;~Ñ/».ˆÆßt装þ'úÄ“B‰à·Æ™Äß©)Çý³7|ŸE9eŽ”üÈ~$ÿ<Ç乎ù?çÿ’ÌÀGâóô~_B#xcßào1Aß#ÏU„´%åÿçé­tœß;•œóý·ý[™”ÃÉ~Ùÿ™ÖóÛñ§èEþßþËä ™½ÇdJÓd~Ðs´ÏW”™üËñAü+ü»Üá§éùø+üÖ„RÃ÷ƒä‡x.¾7¾CŒ `þËVÇÇ3…â³ô6úUþ«Œ¯å¿ã>Nçó‹ÁçìóGýO–ÿ¡üÃòò¯~zµ2¯’\xÕ®BQL&i,sö°ÿ­ý¼&%÷Å¿=8ûß8üуþƒiÅúim¹˜pE`Xퟸÿ0}‡ï’´¼›¦sZE$ËSÊ_à7!F€^R\¼$ûŒ˜ª·ûšWûŒx¤}FÜ3qü›Îi=\fêsä£Á[P€´Ieð~ÈÛžtBúGûs{¿bÁiëi¢‰DlTùŒ’ñüY è{) ©ÁȘ/ƒÒ¨€t()2#¥‚å”¶]bçÀK¥ói¡è—!Êc!zm¸àýXB&ت¤MüUQÝxÇ@´:£^ƒìÌüÂ`ÿAmÆæ0‹‡7gŶMCħÀÎq SðxKŽí!Îß’b×ßüÝ¡•°VÊXOJmç« P·òÀþ³П²ç²°ýŸÙÿ±½¦/ȤÞª¢Ÿa_sëø×¦~Ñ€¨ÏÁ²ZÜ÷¥Ém°'µ3C@ªò  )ÐÔ”ð_µË5 /=²W0ÐØM„u>±¬T~‡ÊŠ)*H’•BaS‘‘7"ü'EO’VG÷³å&V|.…E¡¦†îù‘£ïè<Ù™î|-{5¿Ó÷Þ|'¿Ów7«±µû6GÖCõi¤òÀëÁ›G[-'ØÕ±xg—nËVVªUÆZ=~ã#`À¥f,iÙye¬J‰‰/«¦å†í$ÅOoeõì Ä_L!@C6¤;-FD®¯ˆïT5D8ñ|-QŽÿæáÞä^{ðøk?ÏŠÑC }ðèù½£þàþ7ð%Ù†ÑÖ¸ô96œcìSÖÔãÏ õ5±T¬¸=vKä»ÅnÀíÁy±ª ¨]a|IµÈMX§ÓºÍæNpܵ’¸hˆíÛéÁå1K¯hƒwÛ,“ÏÜt$›ªòÑâTçå2ùÎ7ÝNßçúVûÞyøBç‡÷YA{Ò%£ÀE3 0Íܰ¡D>”aQYa¿¦ž|Wj< cM-Qz˜0³ 7Š\ZdØ Ñ Àãm­®\#Vܼ—ÆCÝV¾Éâ4pÓÚT‰Ü¡o)Ë+Èl”Å6íÏeí½Õ½_¿}è]C¿vdáàÍÜ.1¬„V6š-dËq4OE’êå=N…)¿‘Ýô;¬¦PŽ–T^qD.ÑäˆæcêA‘brËWi…¤e¶LÄ-·îrA©òhVé6·+æÊS…èãˆÎOëIG´ã'<ùaš¦IY7áÆò¸î<îÇ•8L«¾Mkª™Í“ÖF݈;ÉÏ‚%©Ž<¹)l7[PAU³£IO)p GéTÒ¨–ÑX¢«º…¼ÔÕ¸[)øÍ*¢€¼ø­¸ÏqS)71[sÙM¿¦#¥ÒYGnÓ-÷Šn׸“~Ëoû»6ËV¹úóq8ÎÓHL¾ ÔÒ :Mg» ÎçC‹«óÙT~ëðËo¥U"jùy·à—ÃBç:Ô¹ÙùZÿÓ}ÔÿÎ⇋cÅ…8Ç\‹„@n_n*Þ-+ HÓó-¿íïZR•yÃØâóèqƒ)Üüøs‘è¥@aMôBÈ‘KÛk9˜íq1¾O.Ý·ÑmQ»ZÆ»ñv…èmÄ«aŠgš<×d WÚð7«æï€4¥„UYGæ¹DÜ|²+ŸÏ§ó™¼íÝq—ˆ«ñb”bÇŸg5z²ºZ‡C6ngk\IÆÍ˜BæYºH‚ÌVw»âv¤ÿÀ³Å:¿çGýˆ—†¸îÁW¾wüÖw¥C2tæèºïcýG9`Äý»¼¢°êÚàtWžýàPÜx°å–L€v“?z¸“àâoj·ÑÔOw{L6”³Z_ )!-ÆÑ@³MÍÖšh¶aG(¸g[[‡cnÇJåL'i,]üµ# ÅÇŠÏÖ“µL^!*ÜCÿ·Yáãð‡÷ËÝò¶îƒ¸å(5ùæ61b½NkÎ,IÕ¦kpùÙ%¾Ø§°ÝÔíwUö›³› Òr÷ìú²ˆ0츮|.“²fÍqÓ£9ÿ⠴\-Úc«”ªÀ›‘ßV˜r{—¿÷¯n©©;çz°ï˜€’´uWÒ#¸3,'TtV ÉXwÅÀ6S¹G^†7ù ÅâÅa…Þ|Vs½Ç”2W±Ï‚/ÛpÛ\ÏÃÏlsˆ=²W(Á‚Á®$øtM[…ÕØæ;<²yô;ÇŽ¾å`ÿqic5ïü²ÛrÛt7ŽÆÊE¡Ú=° ã\h¶l~Êš°&-v»åêPØÑƒ ¯Ž „Ý8M‹¹b¬¸! µ—ü­‰D/ïy‰ËnÒ·œš”, h}¿åÛþ® Y7«iÁª˜‹îtDO;"ÂðÇÅ~q¯xµ[p+în °ZüŒ,»(>éDÃ~#›ñ;Œßɱ½‚xŸdeWÞ–FãJ8)^Õ·?pð{4Gb+Ûʶ9ϧò¥¼¯Åé8CÊÕr¥$·înú¸å¼Èt–¬)M1æÕ¢ïcýÏå³y+ž)ž->ú$JÈ¿î7}âš³$Ü w:yRùbÞÎ{ð¶DŽÎÔµ‰àÿ0f:ÙMÖáï"J‹4C‰E8ïü²[tÛn߸¹H3´&y±Áx¼ ÃWi%yy9å”ÈŸåly±œrþªÛ)gË‘2¥€ˆ®ÆšS>Öœ Ô ;q7^Loª1Ä£aâ\Ma+l‡5Áõ’˜ßx•Z'¢–*Ì)§üR¹^^,§â´‰í|+ßÎÏ2Þ‡&¬Æ·EíÊ×u#i• ^úô‘…ƒ÷í?¶÷aå5'·iÅݱ¦ø†Ï0YvãH¼¢dÖ‰Kp6édFå"qËuõYÛ ¹ãn'L„±È”‚j~ëðËkùb~'¥o·ïVÿ‘°VJ aø-Ë”3/eW½hüc ˆßrx”(Ûu·] '݉÷$3„=)4ܼ ¯†V”­‚dÿ·GÏÇõ¸U H‰Øè|úJ˜âw]éÁoWì|6^œä­h®l•S~Փ׉,ž±“n¬+chà›’,¶•¸™öÛ®ê1Úí¯)6[QPc™Q£a$œ¬|yJ‚æì›ÓÍÓ9^)|66U «‡7‡ká)¿”=“½èØð]/¯•òIØ-oWXw_4Š…ò¿áÎe;ŒÆóÌ7‰ˆ‹röÂJheKy;?Û¡¢Ý¡AüÍ¡¼ù`ÿ$“h‘ÚÔâTºj Á#*¸³c,Én?{OÜ`‚—ú"µIíbÅk­wñ†(£LÌb1OÃ~.k%ÕNè²’ýgÒQ6–Dø£ÙB¶¬^?e7½w¥3¡¼K6©È‡–©9ífœ‚9Å+œˆãu1svÕ¯¹Af6—÷ÊOq¥ d°Où)z•Ú´&¾Ã4Íñ8Ëö°Jãçâ@Rt!Ìïý¼_“`¿µáoºD¬pƒkAV.Ï Ã ¦ÜçÌÀw†¿´ÿæýý½Ç¹Dv"ÛÎ/Eh>æ·Ü¶_£¥8OºYº¢ÞcaÊ+çªÿ­^O•Oá,F+L $ÿÁÁ/aƒiK?ÃÝÆö8Ãrté-Š!Fõ‰íª(½©Ê– J7º¯=œ|8Þz:Ò½cLóSÈïÀÆgÁœÍË(Ü$¼ñók|O›ÁDoÑ·ýc lªØ‡bøœ]táX͆‡Ke‹áv ðç0eå÷ -ÊÚ ØË9Ûšˆcq˜¯Ë²¹ýoíÿ©×€Wåñ8òL!ToS@MyaÛ¯0rÃê¯JÕ!@ù® 3…$á6ÝŽ ÃPPÿÓ2s{=“úèA;@çë ¥ÜÙ˜ë5++£ Øm ïyù)]«Dÿ.à7+%˜ê‰°ôíL~É¡rÿùì™LÔY¨«i0y<ÛF`º‘?a×nè]Cc}¥ñþÐP¦5X£™v{C³• ›€ä ” ¦¶²hú•–Ì D‡Ñò;ºyôŽg¶ºÈ%œÈÎä—ÔÈó³§¢œ[ÅÜ+œ!ЇUÝ(_ìVqEQïÁpH—4E*Ï‚«~Øó²ì4"½ #ºé‘65‹LL©"ܲ‡pw²Nñ/84³Õê`šÑ±,-eXJsµPhoÕ©À\âÝZAÛêÊžM‰“ Ya¸8U¼ŒúSÕ™Çã°øV …3Tnš’6–¥UFÕÈs!·sÑ(ˆòúßÞÿîïrÛúÃ:Ÿ8|€›–Ü¡n„Y× x¥ÄŽal{àS˜g$¢PcÎ.uÆGÍŠš™†ŸØÃ6kÊÙ4i ¨¢g†óØ£(Çp-£ 76U\˜…〠“•TVzª,ú„ê]BÕ"­]z7â°ÕÄ?)Ú”#—|U³Ž |„°gDT”&L‚ä÷® Ãé•jûÔÔsM³ž„|%Þƒtu† ï gc¸aÃ=›xƽK_\+W”ÀÐ, 4jx'˜ßDS=jB"™²Kx¼d+b0+%uùJ•æDñ|ÅÓ‘7ž_àßQ'“?g“ÄÞ8ѨT«Šç%œä60¶ð_žînÑ·ý+}ŸÊ¯÷Ÿi"ʪ¨bó—Õ\’”TeÈ_á‚ÀY«t×rà 鑆¼­Ÿ’7<ëË'Ïàl1‡hcjp«ë1ë '‹‘ †½HoFè]Ö2c É«ÚKÞ:þË6G"6ÐzSTa~wlÚV"+ïkL*²ÿ­â ™²Æ’SÚÐ=,^ É‹¬é ˜¶ÇI)F›P®‡&VŠƒÕ·A16È–O¨°uKt…1a‡8vªðœjeìp5É ]¹n?UPbO!nÈ“Œ Ý™ÿ" —X⮠Ó'Åx“K:JUÁMª%˜ûMÀzô*Éïˆi&÷\¼˜BQdÉs£'ƶxãT¢½jáKiõšéžD«k‘Åeƒ‚K—ºiØ !©¹û¶_Ãû‘Уuû2»IÛ‡æR¾‹„ó¸ñ7¹ò@YÁöDbB4¨ë€t!Æ‘x’í½+ûãÁ¼+$@\/¯•OUâ·Š$…ý:B0‹{päÏÝ:¥XQØq„§/Û¹†ªn+‹gàNŽ>øƒûß°1?–Ejp¯èÁ‚¡çq‚߸Ü=¾`B'­ Œ^Øg¬1Âr«¯`{©Weü‰ÊA±hSç|ÍÖE·¿ ¬Îb¯uó_üf“±è®ú5 ÓÈtW "ÚU«§Vúîp¥ÛÅçÊŽçØ0‰$$Û¢»ZéúÏ‹ÏNd§³ç¸,![õMÙ–•´n’ñS­Ø À´­+쪱gÓF­mpj ³Âe Œ`&×oP‡œ¸ÀÛ£FجG~9 ÁKCŸZ`M4¼'gHÖ/H¢¸ «”@wK˜¸]8‘@ƒ¿*âå†PþÎä©’{"ŽÅaÛØEìQ¨‰ì[æ$¸–šU  ß ‚|iz¹êü)¬«Ë>p¶Ä94L"Ò&¿×ýªÔF`ÝZ×w×´ß l*”:|KîŒÞ9“×-Õ"ûù`v<»À°:bUò.GCC@ÛÃ…2ÊÈчâ3ÔèC OB¸Ø ão‰ùŠi GÐI¼ ›Zn%e±63%,¸KÿY Ÿñ­c lª°÷»ðÐØBîs5,—-”öîˆÎä—äV7Å´{XìfãŰò¬v?±- °…„q}~à«CŸÁRê&Í,•RmÐ-ÉaK.›ô! ¾ÐC«A Ù¶-°}z-SßJî«ÅÓpPfË”§6Žö`ÿÃÝJ­Ö³Å:¿'„O0Ojsb? þ*ä6"ÊÏ…›ໟ(kÃũΠ.C£‰¡(ûSb(ü>™ ¡ùƒõ’¶žBZ´–ªÎÌ<Ä ;%B¡`qs&žÏžÉ^,ARYLèã=`ùa÷e¸‡%K(JÏà˜¡Š6ßDY¹å]¡ h9Z+a›52#; kÃè4XšŸý+N< íG¸•™õb´bjo©œôz“UOåšîÓ&§Ë—Êkå“|WÖÇD Â"V|f®úäL 0Ë×XÔEÊ­ ™Àþ`Éï&…¾e`Y }1Y~;›‹+±`#3’ÞZy;±uøÖÛBo GX†ó¤/•×Ê'q¡¦;Éf|—1¿èÛþ‹(ᦈŠóRàø\hF€÷ f V„Õ ³³gÈÃ}:‹ä*B˜EÜøÑT¡scg5æh7ôå…™B4«”«@wìr¡ÚRà­X[;­bfñSôA8Rå×,vžF€&Ÿ…÷gÏdŸClH²K¯æwò÷ÚWbspvúÚà×/¾¾ŠŒ˜H ÛÃH>‚÷lwû4Y»y.x¤¨c¶ºˆu€·RM¦Êˆ`&Í“õžlp‡Çc°FÕÔL+¤/X³…¼øw`‚ S t±³õöþw|—e~ô ÚzǸü¬wlý¨÷®<&„â¬CïI¶[þ±ªzð-ã6al¤øœux݇JT>Á籌<ô¡0âáϹ¿$zë¶áž5[J²:bªÙ PFm/O^R)ÓÚ·³l3»PR ’°Evv“ý)¦®å×Ü(‘#·év¸>oÔem!.Æv\+v;·;_/¨C¯ÉüîÑñ½ý›v¸@š €ù%TPñ²_ô+>¹¸T²HŦ;)ÆHêã‰è9®)“¨x2¿š­…Åp1LqÑ& ¶­Y±¦J è‰|,kÓ"È òþ¶A7ãsjêϺ7EÓ`¥’)Çés¸§¾xÙU¯¤oÅç:‘ŸÎžã@#%ÄÝßüÝ¡•b§óžÎ×âj¼Z,¤²x@uä›,dí¸¯ÆáH4^í«q¥”i„ø—ü¾Dí8fÃJÙòäofír6Ü.ŸŠ[q;…–ˆ‚ÉØNúq¿–md ÉHɽ‘§¬æÂÅŠTAŽH²Õ~´»h#Ì*[~Ñ_M`ÿáêáÊA«Ÿúß=ð¡8§¾V,•3EæŸbšf´—Áɼìý¨ñº@ýýÙ|¶¦xð¼‘LzªŠ-7Ow¹š5Œ†‘ðŠ’ñÁ oÕm;ñ©Ë¹pª|ÂÏy©®µÌA1L¯Ò&íd“uÀXΕ­RÌnF9eÃñýq<ólc´WÒöÌÞ"-ÑsâëMøq¿^ ­ÐcvñÜãöñ‡¯~â@ôªÜhÜt'i"Þ£a^×¢‹ZÊÎUfhZZ •%¡ä“ÔÈc™ˆvK S4G-;ÜN™Ä\ÙrŠ7y¢¶'þ²4Z÷›~*L ÊÙ“¾onÜ=ï†ü¦»`»¡¡¾OÜŠí¨´ø÷áÃ;oâ ‘ 8±äl[q;&Ôf"n;ñ­âVÜŽÏ{ʨæ‰ÔEž¸¯ªs¾JwH¦/™p“D4ŒÉÖçª4¶¯ºš#4%že7}ªp$‹ 'º*j¨hʼÁGKÉ`VGâ+®3¨_8ÂÈV?xíàËûoÃñÇâŒ_ȶ³¥zú²Uk‘æ”s¨¸Z®°ÆFÖŽ¦‹ Àû¡l3_.w‹kÅ¿ä/úµ0®…)¿áÛ~—õ#~Mü²É8^ùV蕳Ÿ»H•‘ÂOB¿I7ï²I¢Už¾~&kg”‘¼Çb4ž*ŸJ¨V¼™J¯';ã‡Ãù«y+Î}Ê]wg:+±}Ø/@õ£å©òe^Þ–Ú’MdãYê3YŽ%Äs²·bhÀIܮոÕ²g4¾.oxR½ïÆÜ0zX²u͆•0åÈm:R½ °÷8ç ×g4šuÚ¤VI×Í/ D©>Ï+a²\ ‡ÅЭ¡_Z<òÑý·<¶÷xÜ ·£tHˆn,î°²˜x¾äȩޑÐå€uM¤  Ó)²ˆëq!îØà=P\ b²ì\vABBÄn,H†½ÌlöAM}@všXà*"Ç’Ç>µ)UtY-⃟+åx~[tC1˜ Ø9ç—Gê*¿n㋸_‘Ï ¢X𠤀bŽýBxÅm¸„¬Ø·Ë8Vç¬G>™¿‹<âe²ÔÙ‡‚õ¿pn($ XB¯„€ÚZ a'Ï(&sðý°ÃcÛ$ýg) Þ99fÃU«²Û$¦Ü£¥qƒR+â•Ê_xJšPÈM4µèiPÂÆÎ±h>ðXJþµ4ñá™Üxìþ›¿ÿïd1‚ƒ0§5[›@3dm±7)+‡¡ý\-!C_´Ô4‚6wcw`L*ãB#Â…/KÈ£¡›Üç®Ë—“d©-|ÏlÚ„ËŽC8?Ò8m_1µ'²Óù%¼{·l’PÿÖ‚ñhÔÐÚná(Çfëð[‡_>xꪀùO} ˆµÕ‘ªÌ ôpVÆÅiЪض)ª;·üi¢éxy6=†œ‰ý–åÈ¡ºVK¦£-vÁF@|y£݃ëÎ$×$2ȇCf·‡ ^ð'lÚ$ÿ²³Ù3b¤ìÑâTñ2š*6í®Âj°G¥b Þ%Á˜®VzÛX›&õkÅíò2b| XgMªn t¦M.{6’Æçˆ]ª^&L/€+bA;$%ð'’¢A Ú X¦X@ƒˆJr²Æ<_ÎÃwŦŠû$ö=Ýÿ±þ#bóÈcé )åÙœ*Øøu¥Tµèëe™K «`{(ßAã’Ø|ùéì¹Ô\¶V}P}’ߟ=“}Nð¯—Êkå“H½“Ǻé@xNs¸^ø/ß›*N‚I7æ¡îâ!\ï謰•N l1$2ˆâËçÒv!vm´6VÕ‹Ïœ÷`I°ß-nÉ÷áÉ=çZ´Ã`<‘#j±|—„“a¬Ur†ð±“šªibKÉ@ÝjX.[q!ŒW$‰­r»|ž†è8‘×<=ôKGÎ3‚Ñ+ÙOÞ_cLq.ŽÅ)ÅN"wÓ©d0ßÝ«¸Èäȑ†J_ã”'ßöª ‘„¾*}“%º‡ãn¼²BbŒæÊVù:'"ÑJ§ÊÑÊŸz>5§<éš¾¯Å'1‡h kü³Y;U°à™øG³q$žŒ'âé8Œúq4nj…}–l1»š_’Ëh1Ò¹¡¸ï×é ê”OçwúΊHÅí DrÙPú%¿â×âm'-P\)[,ÝÇÀ²³PÌwÎõ}*ÿ;¿àwÝmfÿ}û§ö>,oÍð°²Åì™L…]‘ÂÅø ªéþ@) ö88g¨¿<[ðF“7­Ñ0v8³&¹~¼‚Û7üU'²Î%` ˆåÎű8%Ú¤/Å‘ø$Ï[áU½onïÃUuä˜æNJ€?gb›g¨( %9'#U#lÍÉ0VÛ㥆TÜ ú}É8/„ñ.sfº?¼ªÎF¡ª÷Bõì1™–î¶:Ü~nû»Y. ‡B˜IÄ{FºþŽ~ýu'W¹›ùUùSÕñè[¤OrF€‰` €¾î«°×½bKmø~xJqaMµßvßµ¹× &,©±Fä–_nÙUŠqn¸QLzÄ!ÌÏFDÈ U¡Uò•lÇÌ.ʺϓáîca¶U£ççe™@æ¬užê¼§ó5É—™t Ø›ÊõëÊr©ž¢aKVgø¤€PSTž½fð‰²ÃꦦMŽÉ]™\SÙ™åÊ÷èêÅ|VÉ˺yÛUEë˜@r)vñ“}ÜÙ-o¥…'÷ÀFdÑ]õk” êF§Åô’Yì`þš8î܉Wòz°åu”w<¦[Åþ—ÏÙy¶8x K°|ZÕ'‚öƒÜù:ÝÔiZ#‘NQ-I8V¢%ÿ̓/¼‰K©óW³;}gñ½«Ìè‘áliJÉ·@:†ß¾xîb¶*å×qŽ©l8»xnC Hoæ~˜Ê+H™`Ó¤VV1Ë(q.¯¡˜ß&ÖäsÓ*ÍJ9Êï¦Q®°(M3ó°¬Ê•­0’hsºà5øAMÅ€ÑvÐÃß=ŠÒ/ùаÊgདÁBÕ>s.´ÂX”ƒLq¥—d*ø›ŠKÅ„µF4ôÈñáOÐ86q°õØ?<¶þ†›¹#© è4Ò ÎwØXg‡bA ž¯éh8ÐlYA[¹:{ ¬gÄBCö¼p¾ð‰0åï²áÏ-K^<ò ¬¤øñP×&ê–§:7ø*\J^*¯…'Ù¤ª7à·%©àö© qø‚#K‹±eÕÖ4¨>›PmªØ|@Â-“M• ?Ë®tÉÉ9KÇ›TðœøW| âYe7Ë S‚ÑŒaáp ±6µ‹¿^6ã>©8\Hz0ò¯¶}<¾_‹šY\Œ=/” ´5zÉfcKËš ŒÃ§Ê_w@²_“$Œ’ªSýò~€Z-vÔ?Â%†ë­Ð ÂÕÒ{`òðw™•Lp Õ‹Vª!¹ñ/4R–W…ײeÌ*ÄC¶—¡‰>ÜÀáˆÉ¸sŒW”àw.^ S\“È]^+„Þnio²Â5¶È™ÌJá›ê)©Æ VØh™¬À8m^o œhÐ<5$®Gdi))*¬+ÜãòïÞ7MÒ ü¾rE_œ§Zæ^uœž÷Kî\òh<ù‘ªƆk»©'"Ú†ê|fŽ\ ->^)OAsSlÿ-‹ÚwmÙ»Â|8ÇG†É8†³Å¬·eç{+¾RüFAC—Ž|úÈ‚”RS¤ø9UÀL‘bEÝÌf|› ,Op&=§j÷±Lš;*r«× 7w8_£=æÊ•ðºUçÌ ‚—ŠkÅ#ô(µHLs…hËm;U'Á×.´$Ø2µ°ŒË¹x*\AÍFZ—  ’£Mücc3‡K=§ìNßÙdh"Å“´JÊëH ´ÎT¡ v)¶ãI7á¶Ý]š¦ÓUßÕ] Ä-Èå) 3(>Ô’`47ÝN$ºXí“4‡Ëëåµâ g%Ôö”µÃDX)[4J#Ú‹¤óDD\ñªè¦Éë¼MÄyÕ½ÝýåW80÷»þvöÚáì!LÑ=¡yóC |šˆˆ +²ùí–ׂJÉ_Ädš<¤béìé6ÝsôóG¿sì3• %D|¢¯ "»Ñ0´H'¸Hï*-Ç5©%œ÷ ~Ùp§Ý]¦ 0G#Å“òÔ{q»L0üz\ˆ©Z€¥f·œå—¢œ¹ºÍ­œS&œ‰s™è¦DŠIב|TŒ®¦òU·–bìú¯~²/Ãv×’*m8&íÂQ©}2ŽÅavwPTÀ$PU%æg\I¼ÅÞ\g[x„ªêJi@ÓtŸ]§ü[Éó‘lª¤ œÅæBv¸ûÛ™D•¬`òÊÛ-¥w.'¿˜ ™„“E£©ª{'ŸHò¿¬–Åî}ª¤¿évT˜itkUk8À¶q“‘/^:HQ²F ãðÈw_ÚX`V‘/L 4|×–%1†È¢Ìªø.´Ââ}ƒê?Οÿ´) TVÀÔ–ºC³êåÞT¸Zw´Q2Âøü5u~„‚öuVq&Ôs²¼"pmnгÓÅjizÕed²fº«Af (1¬DZ¡“Þ"6JPª= Ëm&U ×¼[pË (r%èý‚sy<]Œ¸­°iP&“mO!ð9*‘J§¶ÚƒÃnŒ)pXq»«Æ¬~;I !aR™D7¹U¡?쀹?Ë€š¼ì%ûÆcË…/ª¼£¦Gp%ŸC_%4¦ÀBˆm,0 ÅÜœrŽüW¾"{—¶]…hŸ®×#ìE#x^]•yc¼j¡ H,-0¾=08ø%I›Ô|÷'T³Þÿ¤) žù ØíV¶ ,<¼Iið*l·nƒ½ˆ°—Šc ŠSÃ=Wê¬u9 ­™íáÝÿ¯¾ûwïhíš:»Y¸¹8 Vh¸Q´¿¡T¡>Uxi¥{Ûn1üòØ%Æé'h,ç'²3ùsMì3[Îje‘ñln£.Ú¬ßD·Ç–É ØÇSø¶é–­¿ŠüAÈÂÏBô+ñã œŸ(ΤJø‰Øô ±°¬.üÜÞía§DàLÀÛc©ÃÊù1`LûùCž·"—Vê¦6g;¶”½Ø-o—eÂfi™_È«êÏÃ\•6œ€âŸ†ÎŒØÛ\uZ4•‰˜bRdQ¤w$_m‡]ŸÛÊYôïpuØ–.Jš™G›`¶¡£ÕbGà™m­%…Z³‚Vß–£i³P®‘h[1•›¦fo€Þ••ÜM¯§¾ºefáDÄF³M¥ævÙ[Åä‚«š>üݨTªCõÒ¦²~p|3Çïu»ÁX(‡ßÜCÂix›@À*þ­nª K^E¼ uܺ³ ™ÆëâçŸê»ÞwFjñ¸ÍÌ öÈü’«*Um ÈŠ2Úy…b{è…Á •",WFg¢iµ¢Y±\K«¶‚«©‡ ‚É9ZgïD9=’{½»(ZƒL#ójý¦´“Ô7”OÖýZìƒYºƒâ°©>ëm¡Q³‹Ÿw lü5ôØ‘¦ÞvŠ4y—¼ò3æ;ùü½È©‰¥øë¶Ú~èÒà¯YØÿ™ýÛ›±é^ÛÎ_ž]0hôÑèa&ÐÃ:‘I &ÛŸÙAD¦B¡TgMF¯©Y\“†äÃIhˆeÎ…‹Ðrâ­ÇÔdÚ¬f|Ó»@ÿ— L=í<Û9ß¹%%лå­â2zÖ=ÚIàŠ€ÏÙØñwíb¶gÆre%[`ˆJ=´v­®o$în¢Š#ƒOÚ£A´V‹¢é)äx–—±D{K °íBñ¤øI“ îÀö̶èÁ?4=Ò¿À¦ïâñµ„·ÒÊ'j(ë±;>¯`;Ý•ha6¶Âo8{ìãoü&k«ËˆÉ —€ Ô£Òê Ol^O-ò†B4Øi‹«šdmíÕ{0ÂŒ¹Ä±Â+Ú©l…wù¯ÂÃy–âØöàj Í1þØrÔYµÒ†ýox÷ÀwKâ·Ì}G ·Å3„ÁE•ÀÖ[H8€|âÀç¿:ø¿uø¥ƒ·5njU6€'–….‹åUÉœ‡ RIñ¡?k:Kwsó}ÚPp:‹aáUŽ¥1O˜vµ «-…²v6x´š>–å$wšV–hg‰|ÖÔrmúþ•½ŸÛ›· 0OS¶—‰˜'ƒ>Øl#'Å9ˆAÕBƒbzXMtM¹ð;ØèØp’-š4jèá16€²DS4È̲ÔVÄÔz¶¦úO•CøYÅw10UèÁ)æem4Ði&ÔÇ+=°äx»â¹qðP(3•}Ê«2pÞ n¥H e`autljŒö¸‚¬÷d×o6bà)[ú+?ö…Tlucgd[a£±M•<Øtvå·²g²ÝuÚt;tžžéRUc bL?ÏÉr¬¸B7“áË×éNÖŽ/¦mF®;ë˜awÑÜ_=XÞûpÿ[ûx¢ÿÑþSý7„¦ƒžÔzøêƒ?¸s……s³ùìx¦ ól0£džX „å¿›è¬Â4”µ*Am¥!<ê6»º.²°´_óq!^PÔÓš§T䇙wÈã£E²Ê®¹B…6²¿ÃtJeùAKÙMU€˜`¼%?Fk´HmRrÀbM‰®FÊÖ³Í삨SoÅíª»ì–oû»¢o 6Õ­º—\Üiš!ÁÅh•n×½£ÝJÅ‚Y¤ZSí‰V˱ØÊOäwòK,w#þà wÚÝåÈàíïüÒý±ûîûÿ.›õíì•r®¸]S%0¤p1¾R®†åò# ¦–«¡•~—Aß -º\ñª¾¸ÿ¦8GcñqÕç&ª¼y+lƒþýxŽ»t«Î™ÆÍ*·µEmw—6â¦ö¤òõìNßY¦‰ÊwNЙ¶°:¢N2¹Áܸ5·[þ:W’ÃÍh1‘[t3~-Q=©í©\ ­*sGÂëpq»?íOgíb®luêöXfú+m¹g’ÆÆÎ ÓnGˆ Kþ¢_“Ö'¨íט€ZN*‡ÑdÈ„9UÈÍã°áù Lw¬yd³e«|ŠF‰ˆ"x‹ÒNeõÝo'a4ÞŽO¹ 7–ˆ52ÚÏÝÎ/u^8üÄáSO ¥gÝ:gã“ÍÎ×yÄÜ’Ÿ©¸ò\QHþj&ÔÈò¥b³Üñ³¾í•ßÁ?œï>|áðôÁýl4;ž]àdûòªaõ7«ô›6‰:ðôë4ãS{ˆõòb™ÚŽÍ¢)4+a"Œ‡^]&âxfÙ(ÖzC"«øk“q, ÇÕx1žd•1Cè`ßæ¯æÛùYÕå[{§–ŸMRdL&ðm¿¦¸KœCä )Õåî±]»]½|ø[ì1YA±Üàªc¤Œ&«T"°ü™ {_}ðë®Ý<úGÇ~\÷W#èô?—}’wKÀ&¤RõpG’ûaÀ}ý– 4`Ô²l?cX VÅTü&8§e®ÅXÓkv÷ú¶_crÛÈà—m4'dyˆŽA¨ØE ‘Ÿ†‘áà”Eê,´¾¨•¹ê&BWð|uÿ';ïé|3‰L7U3Yì5ú‰x–TbðlÄéõV” ×õž§³K¼½)ÙösDJ&ÃU…e  N¶RCÀÆ Lf,ž&‹êNÈù­d e«’‹`ð%%p®¬pL‚Ø+¶÷2h“uïn7„z4¦ê!¡7t“¯¡*Ð/ädŠ)ïi"ö2\œ*^f¯JŠ!Ök ƪPR&˜,’$t>:šƒJª.c“ÿаP{톉–& !†²ãÙY`ijÞ JÑ´©Mrmâ%qTÞeC» þDî¤Á‹AÏÈ|—J}ÍÛâÑš(š] B4›2(¾±\|5æ{0߀ċßåÏ¥¹éN~'¯¨A@b n°ìE`ÄÅ~ÑP<§:è˜z4ª•k½ƒ¾;näü-6‚Z‘Â6®£"I¸Aê é~Ô ]„Î 2øø\±'–²¿Æ¥›°MƱ .+òbÅŸšöÛ®SNùÙ87£Êèñٰߟe²r»ÐHD‘D:Á‰¡œ&"b\‚ÇÉlÌ'îh ;˜%aYUO¾]³êݦÛñ¯º¶_ K¾JìÁ1Ùp7içÁêƒ?¸ßbÞÖÞÒƒ_p R@þdŒ¾IDO1>ÂŽìùDävÐ?²ÊÀù²­Œh-/;µ­R«P9(øW lj0÷±Êžš¢î¸mwÖÍÖ¦Û…—åx9œÏŸÉïÒR‰°¸Î»3îEô8ˆè QIЦÄöã‘<#çk–H«ÐhÜŒ‰ò:G­J1î6õç²6·ïå‚|ÎJ^av.£r5Œ•­@a3¤C© gu‡â[ÍÒµ.­…Ô`Ó-ûü™ì,Æv\+'Ë[Å•ì|öLE•`Ã"H;ùü,tý'Î Ó§è]¦î¥f¨»a9‘Bnýô±b_F`Þ‰$7ãËþD¶í/!­ºZ•í$ŽÈšñŠ’mêUü–oûvÜu›Q%ÁÕ’w=-³q›;Hzyqž'«å½2)ÐSÝô·)(>Ú:Íø´rýL¶Æ¥Îê<Œ_³Øújh‡süDJ^á.Û °‡V$M®…½Þ°î\édC± êX!q%5ì™mƒx[d|ºG°¥8*4ðçVFvè]C£ª:4sÀÖZ ¹mõg‹t~Oò¡ qƒmfOdIˈüÚhÉJ'©¦°R)V™mòŠ+i®¸Þ1z³˜(riÄHÍC2FìãdcÉÍKTÌúÖS7º@•àHûYÑ+@N0–.[€²ƒÉļ[_ÌžÉÖŠ—ŠkÑ.ݦ—¹mGÖTáãñÎÀWÂù«™b+v>9rÒ?NÚ.-ÐxÅ[Q-éýŒoór¯7ƪ:»[Ëñ-ñ‹ajðÛCŸ>²p°µ?¶÷aµç/Õ;6£H:afð|=™ât˜ Uûx‹ÃåB9^žË(§ülе’ïV™€–Wa£ |TaÍõr3á/~È÷lŸÞl#;—&4J6“(Ð*Ý"Bæ¨ùßÃP6’䕞¨Eíl'oç®—TžŸ—½’£!0ÙÌŠb,ýM“´YÉ/¹s~q–rAòeótƒÎÑYЙm†&ݵŒt3ªæ’¿óÄo!Î ÄÈʸWu½¬ó±²Å-°ø“ï ~‰kKŸüØÐÝΓtºs©œ,dž+çÅ0%­½fã cMŒ ôˆ®¦^œLº¶¦ «ª¥Åny-\æÕW<ó~ͺ—D“森p䱫nÅ=ï×}Ûï !waÂû5fz»Åíâr6‘gçD“2òm¦—s«4ŒŸ$¦œ²a)ͱJê*â’Ö˻ưšÚ©ÛfîM?Šqkd.n'Ç›âLÛ^ÜŠZ ²•‹ÁE;Ä"0\f^ŸyðÒЧ,°·¥Ð%DŽl5¥ɱ^VAA‰¨ × l<¬¦ëöÈšÖúDön­(þ`™±õ×,&…Û›U±èžEè 3¡¨3ÑP@Þ„Fê¶ )‚t¥<–”YÏÅü0Ššý|o$²–üák‡_>x[Â'^×ð¤Ô[À45üÜ®©&K™È ͺíèŽ]𜈠Û"!+8#f‘‹Ÿfk’·Z ¶Èt7>À‰h,Å&G¬Sõ<°„¬2‘m4ûp_‰€óm§2—Ð kRSö¡*ixÿ2oò×á¥ÎæÏ¢¢ª\»mÚцÏÛê7ÈãÈS˜6+h¤Ä ½½ÿÝßåtPL@CUj6¡à¼ïs}«}ïd/Lÿ¨ÃiôãšV5Mbœ¶õ¯mî‹«Q3‹YÛíSq `¬šÇb}.¯z¹+T›ÆÜØõGPV³ø‰Ò…é(ÖÔvâS¶üD~:{_‰ØÓ¡Mý-e %;“ŸÎžÃ¦˜}xóØZwQ»8±ÙΑ÷F|öJ†¥ÂkdºC¿9ž "/'ãU¡ð´Ð P*š5Ú¡o£ú–¡T²Â•7${kB‡[Œ,{%`"rÔ=ù,qW•ï°‰Áb¨“èL.MyÉö[â³ ÕUȆ·aèïày,ˆnéÐ §ø­©Â)ÈÚ;¬j+<Žû9¾ÐùÄá}1Äs±¦¸ÔI žX^‰{ö=ZžêÜ`l‹é¦òÆQ?^ÍÊ[y;‚XÍJÄüO|—ô “@y%þºðÃhóáÁVè±!u£`žÒþÙí6eCäxpG­Ô¬²Ö ?¨QeÛ+aËR•í2âvø; ›È“.º«~÷FT¿jâ Ù6hÈ~BŸÈòzl77åÓa6Ö´rR¦ß€ªpÝø,jb5Ë4uD¦’’Óýü,9Ò<—퉩Ø^üÉÃѨ‡¶ªSÉ`¢áÛ·ÀcÅ$œW2nF%U™<*òFÈç±:Vè $c]3¤ÐàZ¶J¡=Ôî@¦Ù²ºš¢1¸âfÛ- cÃU…©Á*{ »õl0¥§W­!…öØ#pXÑ„áƒ)sc…è2Õ"܈ê=œÁS ±*ÛÀ]NÔb·ÔPŸ‰8‡9„]í°Á‡‚{ Õ}Ÿ‚Ä&uü&ŠvrD£c¿kaf|è­(Æ,Tûv,íÀªnâ é¥(ຠTmÐaåŒ-ª…!9V±Y)g¹“"PÁoÃSóÈÞº=§5ñ(…Ø$–‰¢ÌÅ“÷t¾ŽÍ,äC¨Fƒ¢V«!‚¢+`‘MÜМYÃgÉ«ê ÆbXý^4ÁèÊÒRœìÄ&Biꂃ2`x ’ÜsåYРÈô¦™”¡@ɱ£/Ñ“J•‘‡û¥8ùsYÞh¡¥|—¸Ð2•W}Û¿RÌ­‚Ž~çèÏ;ÏSª|_¸U^ÉȤú/VS’Ö »uQNçg”É/‰„Ûhܬ’ñ0)ÙTq8Pþ£r®¼Ëb Ü÷-ŸÎÏå;œêf‚E——D½”õE¥ˆUÀ(Þ ½˜ëð»[õËNdgÞãIMœpã®UŽ†Û¥È€TDÓ{U²E(£´Mw1À%Yb·²vv‰¦Q›I –›£öv\`;ùül1ZŒ7DZ¢³âµÓò‚0J*ï•Ô•šh‹úë ·àæÝó4DÇéB—˜r«Ú$6üM·Ããƒ&’æ"Q"Ü.eíL™9Z¥•dj³éìtÖæñá3 þöÀ¯ ­ìÿÌþþÞL\¥å8Ì¥\ºWÊĪŸ ütÝI9þ¼?“½è “ëð[‡t@ß|o<N‡)wŸvS t?A‰Vébá¤ûù.ùd9VéX™:–lêa:ÿ"™›©« Ms©h Ö5“0ÐHIoPŽðÖÃÅ8Å[a?¬Ta/âüˆì¤ØtsX¯šÙ±lŒ^‚–BömÿŠ¢í7("¢E·™»Z t·Ã+6‘ Dߣ 6˲ιêxÌå¬|$‹Ÿ€H¶ljÁÐÔìÀv÷ëÑâ|Šjë ©røÀeÕŒƒ!Ä\HíÂ+Jè¡Y7Ȉÿ­l^ ¿e‰—¶¹VÈmÇP™!¹-[Í^׿æl_¼Ü(úÂqàðSmȰoø–4m{lèƒGÏó&ôð¾v4l{ eÊaÔÌ4[&Ž!‰ìyq [‚={š¨ÔhÂðsdØZ?v/°5Yzº:Üû¤ÚdË©Sv؉JHlz0@k·QK»!ž%=ÑØ<)%ÒÚóJP·ëB¦P«S™¹ ‹‰üƱ+Àü‰wÇâ0ž_ÊwP^ƒôÅÁæ©(±†ºÑfÂi¤ú²`Ñïù˜Mã{ÜÕ°¤Ê.ýƒ£þàþ7P£)ˆz Ö5Q.{ÍæÕ†7‰|jü–íGi5$”~¦1©ª&,±Ã¨A( lØÉ¦ªXøA²5yCè•“ùQ>;ãMŠôЛñ´¾¡Õh¶˜ÃÅ24ÀQµaR‘ìw-À¯îܸ8ø‰ø” Q%€; uÈÎ@ÈŽYSÌ)¶‘\W8[á !€An‚ÏiM•Ô©â}év¬–ë™ü’ ÐÌJ–®,ÿ©2ËæèÇý“7ÜC2m6Jf¢«¢ Z1—gò;”@Ùý_'žk0 c×<¿ò ­™€J@ùÕ¸´&jU6¤ D°«0;^G7þѱãB-†w…GŠaÊ¿ñwä²E×iø+ž}jet̲ ‘¡¦š°.âÜf—"éßÉžË I̬»Õw+S…0¹?zÇú ¯ Ï¿#¬.œ¯ Ä>À÷Ô ûll…)Þ×Ñ© ÷fc+L嘿ïC¨Xˆ–ÒÚQþÚxD©<$ VVØy’Åí­*eÃ=j¡ÉëƒXÌ(”«yd€pÛ°«<ßPVÒ™#²6ðùÁ¯}[`Øfe¶€m¬Ô¤Ž»¥ Ö”ö´ éÑ¢ €íj;9]²ÒwVŽÑ^·Çø4¨k)3Íž8t`§óÂá'ï[Õ-|ãÈl²@n'¸•Z‰>+¨I !Àñ±Û˜êhÌ=þXÚ ²ùœL7-žíœïÜÂñkD“1T„÷òzƒ&ê ·-¬Ð9˜âÖ¨?ƒ©ùw°…fF;ØE $¥¨µ÷ØÀñ_-wCÒœµ {‚½*ÞýÐèà®…Ó'ŠM´‹ÂS¸æ(wkÅjZÁ5ýŒõÀÒR\ð¥ºTHyvL©…)ˆc­nAÓ„s¼äÛ~KC˜%ŸÊ;`L@zE‰ù²a°»Ó’-S¾¦‘PN»¬âÄã{TÂ&ˆñõé>Ã@d ½†¯ž îúN?…mG÷ÌŽg d¾ «0!˜&Ê4òXmÀ–À£Š5§\ØÄ¸¤a„a7úJ"¸Õõ 8ï¢Ç$Ž”ÊÉ6ÃL+Ô;5H™a·+¶½ØÄò0¹"‚þpq¬óÙŒÉ Ÿ£d°,ךŠÃm4%DæåØÙcûßdSe)vë!­oˆ‚6lĬŠZ<0éÿ#*îÉØ^ί¨†ÖøÓÄánjs€éj,¥Fo"íT5’%÷cp ‹©^Á m øÌţũâFþª>z^¥É÷¡†ÕH”a;At —“Âìâ|<‡‚Åòt¦¸ÝóHb°x¨%¬<¼Ù½-˜oê냄 ËîÑ¿Œ¬íÙc++š:atÂf‹³ðx Ûõ’êÿ“ès¡†¦ÏÀŽQ@ÝDZhøø<¹œz¶)Àö‡uĘˆ Ù9Á›îŠaÚ"KA ¥‘$D¯â‡‹kÏæ'ò3}Š£q3ž´Ž_KLçÂÞçˆ>ÜXýoRÅ%*«&‘RÅ_5u6µ:ë@Z&‹‹õ°vˆ¨­‰a6Œ„©ìD¶_ ³e«|Êoùm?®—#åIš%J^7•–“r«TšwD½zÞ0)„•DDuñîWèÆ Ç_ŠT6‡ÌGÞ~äÝGÇ÷öæœóäÉ“´¥œ¤±8ÌÅÏe­$’d@üÕTnçãL<÷ã©d¤²Ew:[+×Ë‹å”?‘mûK‘"ÅJ¾¦+[q×mÆœrJZ`q5®ÄJ&Ûr¯LqMˆÅz§ûÅJjåçýŒ_³a%L9r›NšûªÞšó~ÁËø±©âQr[~»ê·8çZ´CKtŽÖzÉ.ÇÍdn$Ä[ªË•/̳îz¨›†ídm65 ãÔ¢ §çÃ|h…eÛÁ;NDŠJ¾Qà…ÑØŽ ÛBj+šïl)ok%{"G$b;ž<ù6«ÔJIü|XËÜDÅ/¹ÕîÁêþcûÏ|~𠃟¡GÝ)w—äl1k«z˜'Ü’Ûv¯W b)ûd¹ÆÊ ›òÙvrVj·#û»&Ùzí5)= þ%«U(ÑÜñµ014"íSì"çþ6hÓí䯓 ê|†?Ì¿ß÷!¶¬ŠÜŽgj0m¯:Í`>P!±¾ìãp3eð‰8ùŒGH׳º NˆzX+I­ñ0–úåTªUµòQÂkº JÔï7llÏ…,vãJø€lõ‰8‡Y• Yò¶‹œ2Höƒ°Ž½$ ʤÔ|·¼]^‘9 ~b­;*ØÖ:mº>ƒÒ8Ô ß¯n  ]%¡è`ÝÈ2òmë_1U¿=ø»C+¨Ø¡3øŒÝ) 3Á‘ù&¶ABA~Ož…ÃÊ9ƒi¦Å Í_‡ºe‹e>X{èJ~ü2ôñªIZo]é#™;ùü,ÒzøÆø¸\¬ÿéþõ•$”Cco-1a€j‰kR‹H™4%Ç¢b±—ʨ¹ €âϱZˆ£H5°žbiÍ2¦PIÓõànhÅŸºF©±e)ÃêÖ‰…—Ý7äéz”þþ©„T™XËH-mj€ð¹«³H7lNÛ£ÛÞ'r©pAb¾ CHÛDSß¼S 3±÷*Žaƒ[¹:.iãé¨Êô+’Ï‘c ±ª ®Ùl,ˆóPõO´dcLàÀqΫL˜¥:[–VÓ<ÄYÍãÉyêÎ OÞ·©9Œ«Ðž¢½Ä¾dý »2o5Õ6bå²hºã‰ õ^ ·¤áYÓä¶ yYÖt¥È޲3hªxDuQÆDé=ñ~b¤òdz!Xþ§R彑æ¤ÙŸÕJX’¾è6dˆ‰¹¬=Éî™Ä6blvÒVö)Pñ20%lÈäê<±êé¡Üã/<¯pa£š»ƒmCå"Ym‚=kiÀá¶Ý]¨A©"ÅÅyœKˆQ€ÒnUM‰µ!¡ 5(ñ£1ªät*6Ùª¡˜Iyd­C…Uš«| »}ŸëûBßO²$´í“Aœ&ñ•8 ›…0ö¡ü,ñ§ÖÝ¦Û‘È *”óŠ”°LÄVÐOw' %¬›ýÿµwý±yV×ùÜû¾ŽíüÚFç¦ ë‚(ªiI2Ò²ç$cÂÐÀd•™ªb5ì‹´$²y4a6jóUY]‰aY¬Š Œº{|‚Ñ4D8ˆUKø!‘„Ôe¥MBìÏß{ïþ8ç}¿çæ|oÔ¿§ù(ú~¼ßûÞ{î¹çžó<ÏI •í´Ï-ö÷šSHñYȺ¦}t<IÕ÷FÅ´öÇŸi\ÖøÅL¬ƒ;…ô™.;d‰Š6èµëxy÷P[¶¼Ù%õQ‘†®™œI¨²Ã¶ó]UóSÜ}Ä´›QsжRà,L`Rl¸ä˜}ÜËÇ’-Ò•(=8l2…,á½Ñ‘£hÄ–¢"÷¿‰ú¢® +ßgŠæbÅÎ"Ÿíƒ”j_uÁûßê‹Q‡¥¬DÐHDݾWr¥ #NŽ’ôÿíI[ÒìGL«OcœS2c&.ô7ükãÏŸž¤IšàöÍ 0cÜ)SøOQDve¼g¡WýX4•¢y´•z¨Û šS¨ï×T.¯Œ(¢¬½DFœó2-¦dD‰ßƒ/¹ÑLhˆò5îò¬«]i #7áÆ]¿´)Àxú'Óf¼QÞS~|r¾±E{Xo„²Èy+M4¶À@Qƒ’ÝÉjÛaGíJ 4Á¨ŠûߨKv¥é0M¦VË2EÓß•»ö=>ÒI–'Ç+ÒÛI°~#Q)³·³Øp=n«“Ï›_2ó’žÊÖÊA1ÚÁ¯èmC®ÖãUD´–žÉÊGãi( Ø®ö¤-YÐÐÑÐÛ¸Áó'ýíSg¦Ž—WR -&2wÙQûJš˜7Ö %>ÇœÈÎZsªòG•ÅS{©ÏPU6Ú®ž•¼ØpD) »²¯²{j¯ ÝÙ‡IΓ¢¥‰X*ž*Èó§pÕÍa¼XqU ‡¦¡±Fá}k>ᘦ›žJ¤+} ÷¤) ZÒ$P•D²+@ä“9 tŽy¸0M’ñºuRUH%LcE’_Á™>8î*n˜ šÝŸHôqÛ7h‡Ý˜4n#µó«Ü¥nžŠO¡ M]ñøÐ}èž’AiÕžÇ-È™*«Ðüy”u¬:q¤`äÑž'a”GÒ6þájB^$\±ll9HÙÁC¢TRÎ_kÐ00¹Ü>·;¹WRò|<ì˰?¯ pa—¡´žê ’—G†ÈëQ¬|^Á8/·%÷©ÄêÐ|kÐSajk0ì”*€†‰Ö åädër‰ˆÆ‚©î«ð"Á¬™J³bWTžíšæÂG9t|5œN¡¯‡S­Q%‘`¯-Ú!Ñì1-j˜$ÆøEæ%'o¥!&Z+dSNŒÎ»þäô¯Q—„?-‰.O;Víps¡ÑÊÚõ³'qõÔ­S‡¹ìƒ¹­<©f.£«’Ä<„;2;|T‡©ôÔ˜.>j_ˆÉ3”‚‘ Wjr°ÝZ;A{ôŠI{‘Ê?›œ¯çmCŠÏèvgZ›–n³†‡q­8–éà¶`Ê@¹ í¤F^Imäš¡õÈð Z^1øV˜x´­kÉo” d®«üz¯Ýi‡P†“KìaâcñɺÛóx‹A$¾ùŇÞZ·Áœ¦nsŽæÑh–ýœk_÷ïø·ü"»Înˆöñ+æ´ùØœó7ÐË~!]A{¨Éþ½a_’$ýv³f½1sóìŸOýgùËåétͧ&É’Ì£/Ð,sÚ|lÎÚì¯ì|šëûi–}Îî·‡ü ~™_hÚÌrs§¿‡îôËh/- ]þ¿ý»þeÿ$õû'ì³ÄåwÝ[ÉŸ¹‡£ÃÑ;Ñeî]÷¦ë‘kþ­¡uî÷¢{0Ú]%|2d§ÍÇæ¬ÚïòkøÊv¦½ÌÞ$1ÎZÿµñë´…¶Ðfù$±/DCQûGÿ„»Ë?åšüs³¹Å¬ö7ÒË~¡˜æÐËþó>­1ãnÔ½îæ_äû¤zª§Ù3w¹Ùþ.1©6Íö†ŒÓæC3ÎßòøÏümb^7øe~¡ŒÆ“ÔïŸÀå!cÈwÎï®õïQ›<Ñ ~™_È×ä»*ï™z¼ü`Ã4þ[ãïW^«´TF|Å=èßt³Ýv7*jß¶ëì™ûM7m0WÙýæ–dzå‘ä)³ŒyÔÆ¦×.5Ûͳƒ® ùôyš¤Iš0W™fs‹¹ÙÞbHé¾ï¾çîð7úe~¡ý†9jï—y9ïí_ãùâ_çw£/GK£¿­ŸUÿ|ÃñÉë&4±Ê>fgØÝ#~“»ÍýÄ}É}ÇþÖ–í"¶%YöÏÓ>zÚŽÛ öj¾sóœýsÈœ¢ns–G‰GÆÍvõî¨dåFÝëîa~^*Ñí—y¹VügþM‡½´€vÙ:;Ã.uMn¶û__Ží<›çý¯ýkrøâücó¬iç{ã+󯛯˜%æ/èQ³¶ñH¢mÓ·è/é>ó_æy/HS쮋’ ÏÐý¦›6ðØÆ‚5RggØ¥~/íñ»xddU¾OkÌ8__ì„¿ûB4Õñëb9¼F8¼à§{!Šêdû¼‚öP“t_uÿ¯Šß‹o¶Ìû¶yß|hðwû1¿Ìÿµ?ín2_5KìÛü/m3Ûˆø]êòoùE~/í¡&;`–Ø·}—¿Ý_ëï¦;ý2š¤-4‘jºWÅdD4K‚7ˆ¶P¯3ÿ}¦h‡X[]€êl,½vAmÕͱž¦ÂjdJ qž ¬ÑØ¢6L¬ÊNh&ùlƒ Õð] Ô>ð†ˆ÷y‘ñê:NcIìBŒ# ¿ÎJRÕ,b¸d§¦’›üæÄõ÷5ln|²±Gö1n ¸ö †‚޾$ŒÂ iŸÄ*~[? §bS‘„¿Îÿç›ïÆ( #Ï>ú¨‹†ˆ¨˜fšh#­'q:I‹;‘ÔH©Êïn¤“Ád )DG"Jc[ÓhNfP³Øh+¦TÉ‘£ò‘òÏ&OeäžÖ‰j q†æú3þD˜WŠzmg4äÚ]›kFʺÄû[m§=àûh§oΨéÖOeLm“íF˜1ƒ~}ʧ£¨˜ ÒÎ$Í ºBRˆz£bÔ̰Ït «Ä&\M2×½Q1 ê†ü]K¶h‹Ôaˆ‚±nÆëÔ´˜R:ïBã_î[]3¿‘˜­õûù¹’3É@&ºÝA¡ø5ÛääÆÉ‰‰•\䱫í­vFyO¹Tc? aRègü_ôAðg”ÅB¦ø—&ÆJ¡[ŠãF_p+ÐU‰»¤¢h$ꊺ™•õEÅhˆ]† w!i‡û ºßîGÓý 1ëÙm3æ:ã¼ý€?÷Å]ñªJse rÐÒ_M©$;˜Á.Ù¶º↳á&H©Ž§¸pf½ËîÔBD{ÞŸIÖû Ç š î`b^D£ù)Õx,¦8•`fŒþ ç)°TÏê ¢IÐA]è¯3æÞ!ô³ó=®ÍwMQùñr±aAý×Rè@4•¢n6Jù—ÿ`âcñÉøv‰×ž¯ì®ð“öÛ¾h§Їmg<æÉ“VJ+äHX+ø»’²]=ukù°¤V_@¼Œß3ZÛ ÌBe°²¾’)6:r+Åé'OìÊÙ=e±b1a¤uD‘lŸ|Í ¥+À d«Þä‰VR»§f¤6"ÓhK¦“AåRþqcÜK<ë:\§[ÉJÁ&Gž\:òéAokzxä RŽ„-¦dHp€šeí~«oföˆé°£¦°_Ù9Ž˜V/zržè‹Kñ*j¤&ª5Z3ªÓs¥9Åw›‘ÉÇ©¹ÒR¹¼2Ï,·­¦À\‹iǦ¬Ÿ;ízˆN~P~cr…?ã×ûfÚHGê£}¦5#÷ôùµ¾Ù¦QuUºÃ r ¹e)Wj*@Å ÈœØ>«7£IŸª!³ äÓéP<(âB9¹×›0Šá‚=RpUÍrâuÖ ³T2ì­”ÃfnÑž8wš!̰èãjRU}häPù)]ÂÇ_A§Œ»«(@g]*%ð†Äµ¹4Î¥jΑçHzYVk|¦(O7‘Œ'ý©l[5*ᘋw`숳€ÜR‰^«zšÁ{nCD?qì 3(i (í#Ä»"ê1”ãj#¨Ø©à; «Ì©äñ‰d‡Îs…‚æ ±ÍÙ1^ƒ ´¬á,ì˜ ;„c/Tƒf+uÕP$ÎmEÇâ“ñªúÓ¾^ÿaj·YÊ%™Á?‰îÖ>vUÁ¢œc°ƒñƒ)ì9¹¢kpÓ5àyŠà¢K³¿ (A¿«±Èº#±<;Ä&ZLV_KòA§¸ò¥…Ñ­ë{¨q‡ªB"t!%ÆIÚB’™§ZbœÙ0óåYçXÄ‹KæXÐ}1þ”‹å\¬e¸—Ÿ¹ÄËQÌvõî(‹ ñ§qßÍ%ULiKÉÿ šOM hˆÖÙ³Ñ>†È5?²¿²ó¹ÈÍÅ~Ùÿ¹Lþïþkô ÿßÜl™Õø/bduL†0LA¬r’¶Ðÿb´$º1zŒ Õü¹Ã'©ß?áßñwøŸH‰šï‹å0¾ËßîÉDò¸1€€ ÆK¢£ÇÄtøó ¡ØK h¿+ãÀËõQ³¶ñõeYò5ëì »4ù4ù(ù€Þ§5f\æ‘Gwõ÷iGxß7¹Ã½–<\[Ã/þ„ P°ë¢¿±ÏóÚÚÛ×]ÁÝïnÈñió±9+%ùï&÷&õÑ’øÆè{|'?n¸azùå?œ#Ö²…¶Ðf€¼ëÞt=Îàg,ÑígkáB;ÿ.—磣öîhžáüy)í/r_r§¸ðÀJ¸ÀÏ–Ýé—IA€gùºÓ/ ƒ ø#ƒo`¾0!@†k0Lg­ÚøÎÄYê\¶ÿ­-ÛED˜i/³7ñud©?fgØí¸=k¯–ò<8z|Û®³{ä`{ÔÞÍãë à†í®ïOïA!Éô¤’<¸{a¶¥q»Á^ÍŸdÛ“q~žöÑÓlùïXgÏFû${¿é¦ rT…»J µ#$|¢FâOéÀºî™—î+WC®¯ï*ò©¹‹*§û®Þyô.ä8rø\zg®G@¦÷j|Þ4´®M©Ñ±­¦ï`C-œeÝë9‰ç[ÏîÜ/9÷¤ã¦<½*þ-Žª&v\øÎ…­ú©q–s¯¢(v)ZÛg Úƒ…ö€.IÅ›xoyÅqÓE8(ÞO-?à„¨<”£ÛÜ­Õ9GU€oçQ÷5M'’£:˯pB€£­Ê½S·NFÈz Å.ü&·žOË©N»*6© Ï¢úåâòÆc”8Ë—ÿñÀáðaë'<æ`n(àa¥µ*¢G¡Àqbd:Ê£XØ uJÅñ)Ê…vUX£á§–̘‘y˜,Ty‡_×èù@£³?ütlÄA#CHG^F s¬ÏBÖ#yϪ(àŠ¹UÅÁUáBÊZ„f¨=,Ì=ÎÑ`ý+T@Ë®t´Ö݉x A6 Á˜—ÔNçs‚>~Em$Açp …š Uºë${G9„e lE'[²2ÅEÙ½ ‡ˆ3Ñ}åU 낳™8;Øx-¨uÂ:BXCjØ6ÁPv[¨¨a%oÅž \{;½«k\ ¢Qä¦;lWTÄħ =*R+3EGì0¼#1Å v¬wtyAV" D!érÐÕ÷R0LÊbï– ¢ÁÄ<› Ê€€óEÓל5܇ƒ‘¶=º? 4ÅÒ‡KAÎZ€_ƒÔ>Æb|Ž»™1Š+Ø]O‹Ôò`’Qd¡ÏpÿÂYC;‘¸¸¢øIIÀÓ]Ôa¨JýA+7[Š ±µ@R»â6 8ªß'NŠÓçèzWº(ZÑÛ6 Cê´½n¬‹ Ö Äı³Rþ¨QFPëKƒoÄ[£[8€NÑ9Hd·Å2"´Íh,¾‡Mn½[H$3”÷O½ßâ¦róz‡àþ,øÿO©þŸK©bH"È|ª!Å‹ñË%™’šÇ œÒ!ÀŠ6n*5ä­áe„sx¬ºëR^7Ƽ>OùjûÇã?®M¼ÿRÝðŒy–©ŸK÷BÉ&@ÀqÓ‰ÝëóÒl]uk¦=4m:7“úò™äDe»eWÅû$•‘R€øiüƒU¤zèN¹èã1F[ v #ôÊØž÷@,ºÇ™)“q0m  µðàÄqÐõO7x€ÉCÃ’\€j¦€‘)zj ®á®÷ð ^ Òr7U¯ƒQ­D©ünÖ®"€˜,§VßÌÕCéÙ7lJf ].יּÃE{/º*˰¶ê!7u`KÀ b¯ù·t^IîJÕ[ù“:âw°.„ðˆ Ë£Éd@ðB÷8q˜YœÇ<)j„øk Ü vÒ¬Aýªwp8Å*9zÈZ"0BljiæI0¹gz*Õm^5c±k¾51íB‡í°”eZˆhæG‚]º%¡d‡i'2©þúX\2«\‡£T)°±M¶` ,ÏøQ2dd‰Ê'!8DÔ»<67¡R Fœ›vÓfR`! YBt"!³ÜÒ„¢!3jÈø¡Ê;£Ÿå íD&Õí"óª!?ìK¾FJ•a¢‚۞㯠yüŒç“õi*†#°ˆqTt‡=i‹ õ¤>ÛJC †”É`Âô骣Ú\Èr‚ƒtÀñ(1Ì/F6š“fŒññ™› ¨èÛÍ•~³Œü ð…`faœ¹]Xyx²496㓟Ìü¼ßLOúž‰oNŒ^¸/@ýðçÉŒf,…aWrc î;â®x,¡d…6C¿ôòQJíÿý½³­‘mŽªDwÓ¯ôm9-®™m«Gpüñnôk4ò«DAAAdñâÅd„ ‡ÒÓÓ]©µbYæææD.—ßqwwOyï½÷6yzz>á›*ʼÚö\ÌfùÄŽßT’Z½lÙ²[µ”ä呬¬,æèÑ£`YöööŸ¦¤¤lÉÍÍ­@TYYY_üöÛoÇ÷íÛwdذa|+æÁ£¼îæñWޤ’<†ÓÀFH:Ýó¢ß‘“ª|9 Ž¡¥ÄDJÁ€¡¥D‡¬¨†¬(¥ÈK+z¡æÌ´¢4°„Ê´¥Ê5(-A•îK?§5ûûÁÒô˜ÛبzÛ’™™ €7â³Ï>Û `k``à?ñññ}t͈”RÀæaÆن††¢OŸ>|OăG˜5k–¸°°ð L&ëG½½ý3fÌX OOÏW¾üÌ«V §s3µÍã·OÊ À2D£%•Zóª!ªÑ^¸§ç´00±6x¡ÏgghWFB4Z@§CN‚Òî WªQŪœ^¡–ÄF¦´ K æ[“&L(û)&UfæÓ”fÏ‚C(”U)2œo%ïM2“8¶å›SE;vŒ\»ví}ccãDýs×®]û.\¸À Š*`nnÞC­V—}W*•ÈÊÊêýº”ÿ• ©¨ΣÉ]p½múÑè“Ê,„á(]BÒìŠR²‚ÖÔGŸjV”jÖnæ{Ìô‰{Qe¾ž|÷Òoï3›Fi ŠÑ1í1eQ~å÷ZŠ!¥ÄÅ %ïŽàdÔ 7¶·<¹€oU:èß¿?]¹r¥ÊÎÎn+¥OgB •J½bccÛtéÒ…UCUËcâb5¤¤õGiM~,ÑhY„B@( ŠcEÉÒË—OE~Ý.øzw¾vjpæÌØÙÙ=pww‡®oŠ˜››¿ÃKˆž¤ž;2¶Ý…ó”öˆûùâ×ųÃP¬¢¬&BKT¬ÖÅ,E™_ŠÑѤ´Ú”¡•AVƒööŽƒWôJ÷wœ^øs$æÅá½ݶ7µñ*b…e‘~¤tÓUyµÆü§.ø 5X¨K5+£EFI9'¯YasÈ.Œxë+i÷]\\ü~8zFF†€oÆe xé£Ð¤oNÁy~g$Ì;³!ñûó#‰H”Fð!(8,p 8 ¢Ùƒ4£Ò$`îj*í4Ћ’ ®þoÂ’%QJC‹ÖïEgß<_¬È6aÑäîÓjP¬F›b¡.ý¬ñM±åR(QPZ"‰ÍØ»ônü²bKãæ«øª (•ÊZåa¤”J¶nÝjÓªU+i›6m CBB0hÐóÉ___lݺÕÁÆÆFÝ¿ÿŒíÛ·c̘š] 7n, ¯?}ú´Utt´ýÖ­[Í7lØàæââ2„Rª¤”ª®^½dmm­*((ˆûôÓO ÜÜܤŒQ£Fչ̇ÂàÁƒ±yófËððpƒÑ£G¶oß>¯2¹mذÁuß¾}Öl``à €‘ËåqëÖ­;¸eËÖÄÄ$ù£>Š€³gÏâý÷߯é]mÛ¶5 ±Þ¼ysc‡¾(uÚ3ñññ‡333ãìííe©Ÿ~úiª¾œž•µaÖ”RƒÅ‹[ÙØØ4|üø1íܹóG"‘ÈŽ"ºpáÂ*SSSµµµu®··wRÇŽë%ïääd899áСC†—.]²hß¾}ɨQ£²×®]‹)S¦àÈ‘#8p `õêÕvM–/_.ûçŸæSJK(¥\TTÔ>¥R™ijjš×¬Y³Ì.]º¤¥&o­E¡:TVæÊ2³…Beeÿß·oj3A^Û¦(¥¢]»v9( Ǥ¤$V;ùžR ¸¹¹±)))çÍ›—­ÍYZW¹¾TûäÜvEÒ7§vI?ú˜r¥œC5Ib9RJL¥ùø8¢Ýj†Ñì5Ç¥Š£mì ]ú7jÞp gbLè4ìóßgÿ;r}ƒ8éÍGYEO$¢CJD»•ú«Jseæ¿R­Kk,%5#†³U¯:yýߢ°ÇÓѾѯ$T’»O cm3NÔ+V¬8””Ô]W›²³³[0gΜŸàÆÞÜ­P(lõïßa—.]‚žÇýµ+00ðDjjj+–e™Fù?~»¶ƒª† È„ è¾}ûšfffÇÅÅY2 cM)•¨T*èG.ŠD"¨Tªl±X\lkk{aÈ!_:;;çÔ—pOœ81ïäÉ“3(¥ÄÔÔ4#))©í€T%%%9r$ݾ}û=§R©l(¥ÆJeù>ŒeYˆD"p'e&¦uëÖÛ‡ ¨ÛaévÔðçŸþòäÉ“aœ(¥FJ¥²Üs€@ ˲Çq™ÖÖÖvvv ÆŒ¬ <+(¥æ¿þúëÇJ¥ò›ÂÂB#¡Ph-—Ë+È[ €a9€, ‹3Ó§OŸ&‹óë:Y\¥R9,^¼øV~~>c`` ´··ï2uêÔpíšhaaa=:G&“u …ö%%%•–…"g&×ÀÀàÚ|°«U«V{jûîoܸá±ÊÄÄÄ—žžÞ$::ÚPÛ6U*ºv횤V«3t8€2 svèС³÷îÝK†^ã€ðСCßݽ{wtII‰˲–J¥º¡î Ã@,C.—gH$’"''§£'NœIQ×…¨^IÅõÙ·ÐO7bדý €Ýİ:D¥“8V—¨8¦tiŽe f̼mò;­íÛP«A½*ø;r¼mÿ×òðÃß/æ'˜ ÷” ´ZSAéjXåCÖµó«„ŒVÆ­§viqhí«ªå¼H’:qâz÷î•+WÒÄÄIJ4I„4kÖì__ßß´¿]¾|ùÖÔÔÔ±eÚ­Dñá‡vèСƒìy<çŽ;†Ü¼yó€vaG¡PˆÅ‹;B*µÛiSÒÙåää¬ÍÈȪT*딈—ã88::þäîî¾fРAéuÉ@)uúæ›o’´A'Ç¡E‹úùù}¾hÑ"33³°„„„Z¯F)ÇqpttTÙØØô?~üÙ_ý"‘þþþ8~üxï[·níÏÎÎ6®ËsÒÒÞšØÙÙÅ(Š^ß~ûm\}ó3fee1;wîìQPPpB*•–Õ—Ú>˲pss[йsçÕ-[¶Ì­í}ׯ_ÿøáÇž,Ë‚ã8êèèHfÏžM¶oß.(..^õE]Ë...{¼½½çvïÞ½Z»ë‘#Gš\ºt)R¡P”1 S¡¾©Õê J)Ú¶mû`ܸqÍ+«_ÀСC±k×®6™™™ÿÆÆÆ A걉‰ ,--§¶oß~Û{ï½WXÓàxI>©¸ÿm.%¨>;¶—ÜNóMàí\¨Ò£ñI= ŒÐGÙž¨Ô0´6üÇû«Žn„ìÜÇ9¯T‡ýaÓ/ánÕúÞ¯éí¬ ìNëúžž”f¯cd4Ú–6,Õ£´ÒÂëkNÝiÿ#\¸×ù­2óõîÝOžÌ<ÝÏkNo#‘ñ–phM~P—‘P™PCLZÿ) ®Ð¬O9äò¸ÎÜöžô¿ç ß6Ô¡C‡Fè7d†aàçç'Õ=fddtY÷»B¡€½½ýF___Rïû=zË—/o+“É,´Œv¹{ŸígΜ©ðtJMM½^XX(Òïœ4¦b‘H$•H$™¢ ²…BaŽ@ PVÖaåççÛ†††ž8wî\OŸÚvºz@‘HÄÄÇÇ_‘ËåæÚri:®<‰D’)¢,--£(¥ r…Ba˲LSJ¥éééÓV®\ùãîÝ»GæååmËåЕ‘P(Ã0Ù"‘(•aíu‰Åâ –esõ;QBÔjµaTTÔ¢#GŽøúøø`ݺuµzÖ!C†ÐM›6%eddôT*•eY•@ 䈉D©b±XʲlQeóð²³³½"""b¿øâ I}ê !üñÇ:™LÖA«ÙPJ!‰ rD"Q ˲ÍÍÍ£<‹ÅY ÃäW&“‚‚“”””ËÆUÝÏÊÊJÆ0 (¥e[U…Ê6!$\?Ð% û÷ï÷:yòä …‚©¬.‹ÅbÈeYV [,C[}¶_²dIZUå+g~‘‹¸¹-(¥F©ï»Ç%å5$ )]fƒT“ –CÊ ¥ÎAÂWJ£”£ „Uª`ÚÚþï¶; º4x/:|µ3`h68J©ÏÎCöæ?Ìè£õMéšø-3ýiÓ*1Ú‰ÁT¹"ñÿnG:@ûG ó‰—Ëbú&“SHH™0a“““3F?üÜÖÖ6ÜÜÜ<üÆðññÁýû÷‘••õwbbâlBmãIIIù€RjD)ª÷»0_j¯«-Cƒ ~PÁ©½iÓ&’ŸŸo’››{QÓYÝÿÇ9;;/V*•×Z·n]ðî»ï–BÒ Eƒ .0VÆÆÆ£ãââ&Êd2]gAANŸ>½oëÖ­-ÍÍÍ Tç:À²ìD©TÊBÀ0 ,--¯PJçzzz¦ 6LFIÕþ6''Çýøñㆉ‰‰ †Ùš––f¡Û‰B‘‘ñmVV–@‡ (bkk{ÑÊÊj…J¥ ›4iR!!Dª£uئ§§;¨Õê}u;­ââb\½zuóž={Î1¢ÆðBJ)³|ùò¿SRRìôC(Ê5j´9''gk“&M2{õêÅI$’DJ©Edd¤Ù™3g ÌÍÍ>zôhlQQQ ]y§¥¥Ù,[¶ì,¥´S}̉‰‰ãt ÛÍÍí‘‘Ñz±Xü`øðáù„2sbvv¶ÓŸþi`mmý~jjêOÙÙÙåž%##C|÷îÝ4«,ÀdìØ±ÿN¿@ff&²³³Ë›ã8êééI„Ba9Q*•Q®®®¨`êó÷÷ÇÂ… gr'Ö7ÚÚÚ>‰D¿ÚÚÚ¦<|ø0ÖÕÕ• WwìØ±Qxx8µ··÷OHHè/—Ëí³B-X¾|yhxxøÀ-Z(_ªOªpÏ}ð†<<Ý*÷çó÷dçâ ”ç§Ýk…¦ã“¢|RGp `ÖÝíd“•}zß›p-7xm:ÚS¿GÆ ‡î||#»ðNkª2"Òš÷ÊÍ©Òæù+K£T:LKV r8ÙŒ‹nᱩÑÛà“Ú¶m[Â;wè.GŒ1¥C‡†Ø‰ñññÎÚßSJáîî¾nÚ´iSžÁÔÇ.X° ³¤¤ÄB{ÌÔÔ...Ž©•9דâããtËÍ0 œƒ¦OŸî”4Ð…näÜï¿ÿ~+##£n‡¢y¦óÓ¦MëVS4ÜÍ›7Û_£”V:(uttüÙßß6¸£&Y¬X±borrrµ#D‘H›~³fÍú§¦ëºyóæå>ô×O&loo:|øð®®®êê®Ø5==ýœB¡(G –––ñcÇŽíìää”TUD¢ÖC)¬[·îè“'OzëŠD"œûN™2¥Úù-k×®¥ÑÑÑ•šØŒŒŒr{õê5¨sçÎÕ&›Ôº`É’%'²³³{éûîZ¶lÙwܸq'ôÿ[Y@ÂÁƒÿ=þ¼Ö<§R©ðÓO?}nbbò§þÿ«‹îûå—_¨Ö¿§­ËÞÞÞËÇŒ3»ºAæ Aƒ(¥ÔhåÊ•SRRÚèiã÷Ï’%Kä/ÕÜg<”Rc©ÿñå—CÊiæ6q`©v>”ÆôG90”[Á'ŕΕ*QÂê}·ƒMVöé5çy z6YBˆjpë¿Ú7´îyH@ gîãÀBUnî«D¡õ[i‰ -k‹gXÄ;ap÷a7j®…Ö´C)%Ë—/¿YA999%uèÐa]eÉemll: …ÂrUjjjÏC‡×·L{öì™'“É,tI‚a˜ ãÆK¯Œ 6oÞ666 uå-—Ë!—Ë÷iuàPKKKxvîÜùBM ‘u͸sçÎíkcc“¦×±“ììì QQQÚ}esDZúÇd2™Ae÷®Š ®_¿>>++«Ü ÉÚÚ:âÓO?½oß¾*ŸeРA4$$„¢Y³fµõòòš. V«Áq,,,âÚ¶m«|i>©Ü™GJ+Õê«–é=6ǨÊiÒ=Í­§;·,ƒ„ÎD^FC`ZTƒo:ö ì34á§‹hü{Ï×Ö¼•S©~¿ÉªnVÝÏ2DAË‚(ˆºÌ÷TF\Ð ªÐ™ü«M«Ä…E7ÚÝŠèø¸U“Ó¯¢L´Ë×ZSIJJ2\µj•˲æ«V­šúÓO?q)))mõ ŠeYN,û…††¢²ä²£GN±¶¶ÖŸ=Ú(--­Y½ý‹.Òí< !°°°ø¹2óOvv¶ALLÌ,}““……ÅŽ±cÇþP×{§¤¤('Mš4ÃÈÈ(BÏ<ƒÄÄăõ6Ç‹ÅQ*•jQ]&Új ¥S§N‹« ptt¼8kÖ¬½u]lïÆ3fÌ÷‰äŠI ?ú裫J$¬ N™&•JMuË$ S† 2 ,,LQWÙL:u ˲qºï;!!ÁøÚµk#jšVÉ`€8;;w›;wn6Ô%!2!„ëӧϧúA ™™™ž{÷î}iƒÓÛ·o[ê·Cƒ? !5Ϋ҆Íoß¾&LXåééÙ¶Y³fÙžžžÏ›7ï³áÇs/Í'e¾r (¥Æí×\ãR m[êƒÒ,EX¶˜ðt¡uª©Ø”hüU (%„CÌ6Zn7¡í쌭w‰í¸V¯µÿÅʸ(t?vëÝ)%òø5ÐNù…uüPšdµúßK7‚¢¢=¯ßq¸Ù¡UJ{B-,º c£6¯Âã²Ξ=»Æé”RºpáB;“†ÙÙÙJ‰D⟟_aùxíèßÕÕuñäÉ“OU±e``ðÃ0´¦#Í|”åþ§³R[û†……A/`"sêÔ©'+ëh7mÚdÏq\9£¾©©©rÞ¼yæÏŸ_gAj´-å¥K—>8zôhŒvÃ0ÈÈȹùúúÆÕqt++«ƒ'N¬sh~pp0ºwï~kÅŠO=t;/CCC899MÔ’G] Õ LMM÷wÒ%ˆØØØ1Tñ,’Ÿþy¶þ bàÀsõ©¼&&&ò#GŽüqúôé­FEÁåË—¿°§.×233{èààp¹>“±£££qîܹ‹fffñ999®:ŒÖß}÷÷_-\¨ñC>©ËÆŒƒµk×âóÏ?¿ À¦L™‚šÚãsѤ —/AÜj™Ñ20žKÎkTêèçžRÕÝ ó™{Ý”…³B$î=ï5;óëxÝ JýÛ^]ë`Ñí—rÚ“6ʯÍéipEyÒbZ•ÖöÆë Ez+c£6È‘|‘ð€ñ5m„ßÂÂÂþ©©©M …w~~~YCÐ'(KKËŸ§L™²`÷îÝÕÖ‡víÚe¦H·QÅÄÄt.((hZ‚:sæ bbbz@ÏÛ®]»ÅUu´ŽŽŽýår¹P¤~%„”<‹@;wîëààPN›bYÖL©Tvxøða]MPèׯßÅú”CÛѺººV˜$­P("¢££žå9½¼¼þÕ/+€Á•ý6997nt‘ÉdVºõÅÉÉéQ§N¶×7ÓåË—1pàÀ666åê_ff¦+¥Ô¤Žë‰^½z©ê“-ÄÓÓŸþ¹"//ï¨îñüü|DDDôYeggGuëÇqpqqùZ;0«-¦L©è®©=>’2žÝŠ 1íT‘éhV‘%!DC>¨°g¨¦Ã¥¬ÆXú+ 3WsT` €As›QîÇFŸŽøl¦wÄ›†‹ƒðn“]ß¹Ø|4MĈÊL{,)oæ+—Û¯Ü1Z–A…ZÝ$òQ×ë9Ò¶–C™ôÆÐ¿é IDATÈJ£¹p 4ð;wî‚€€€G¤ï¾ûn´••Uˆ~ÃÚ°aC­‡÷AAA¤{÷îË埔«ïÆÆyªòMddd Ó#W!äŸç±8£±±ñoº±J¥‚@ ðiÒ¤IäinnŽÆ{–2uîÜùO}••• 6iuªÃ‡~®?8IOO¯RËT«ÕÔjµ±îï !‹´|}ðÞ{ï$ÉiÝãjµÚpÉ’%æu² XY{Ö÷îááÁè‡kggg¿´…Ôúôé³_$•{'ÑÑÑ-NŸ>ÝÞÇÇAA/®¿y&’Ê_pP¼÷n/éçûþ¥2yó²„z¥Ý‚FkÒ„Sk¿sOµ*F³G™OÊH@Œûztw>0jwÆìP¸ùo"þ×¼tÎNÏ kš¹ý¶°¼J]‰&¥É¤®cî+‹öӼȒ’‡â„Ä/o^mjcí‹Ø¸ñ¯µŒ´áÑ»ýüüÌ ¶ÔÅŒ4kÖ¬¥ú R©ôƒ³gÏ:Ô4ú ¯¯/ݼyóâ‚‚‚ò6ràÀ7ß|#Ó÷MhGí*•ª[9»'Ë*FŽ™õ<g,)) —H$úÚKÓº’¾££#€ºùGô±qãÆ4CCCýò%xyy)žñ½çZXXè‡GWgÚ«—ŽGn``õ<ê ««k–n9$‰U“&MšÖEÖ:tÈ{ÖrX[[W°½´… ¬¬¬âu©T*³«W¯ÞرcGóñã_\_óL$eúS?®¹4¬påÅPš_Ì<%¨ŠÛSÓW:Q•r:D¥¦Bs1Œ†6eÐïlæWÿÀvY¼éˆIþ ζãlâúÛ±ÀLÉBEµAºZS™ö¤CXDcƒÒ¾D@.O Ož ½óI{w·-ÿ%QQw\©Ë&‰®ØÛÛ_533[ÖªU«™³fÍj0eÊ”QÎÎÎ…Ÿþy­o @pÏÖÖö n'#—ËmcbbZÕ4VëìMJJš§??«S§N»ª2ÍPJ%™™™åüW†††ùž‡P---å,ËR½u}ˆà™;Nccc莮 ///™¢z×®ÍDOHII±ÕóGÉÜÜÜ2Ÿ‡¼è^[­V#++«N®‡æÍ›?sÚ¶èèè3ÿõ &&&?êûý¤R) _±bÅ©={ö Ö±B<·û>SàDÁÒÓý —ž †’#x:¯æBu>ÐÒß \̉ñWß7é}l–÷ÅÛ€†N_ØO[wïQÿ#……—¨º ÐhL(Ó– ']ýÏa@”ªTa^ÁñÉ)ß7ur\ôð?z45¿ç™`¶.КyLLL¶äää ÑŽÄ9Ž#yyy Ô8gýúõ¾?.G8ÖÖÖÿöèÑãTUÿ¹wïÞpµZ ­³ã84lØð¹=WXXX&€TŽºEF¦ ƒÈÈÈíÏZ‘HÝ0mMYž‹ AŸüªƒ¹¹y7Ýɪ]»v}.=ºT*ÍЦ¥ª¼5iî>k9222¤ÿu_õÅ_lY¹rå— mu&å•J…”””)))=–-[VdmmýÍøñã×üç$%·cpñ®›¡Têt‘Z¢ÒíBµçh…=¡TÍAèiƒ±mGô>W´û>ŒFzãmÃ͈vhéu,16q¶GVöö*eº¥¶-èJ’êJTgÕýójUMOû-<"¢E§æÍÃÿMO_;»Yo\»térjçÎYÐDB™™ÙéêÕ«.ï¾ûn•þÇ3wîÜ¢ßq¶hÑbQu÷Ó%5-!$''o†¼¼òJ¡\.·ˆ]²dÉ3_[¥RA&“U0á½­˜9sf»€€€”””+ÓJRSSRSSW/X° ÀÄÄäÃ0»† rËÃÃã¶ÖÂQW?aG=Y]WB:~û‡òÓQû¸Œ|<£5íÑJ¶ÊL€¥ÇYKq–Á¸¬Ñ¤»¼•íšßÄ£X_¸7XÓ¼ñ¹6O@³„–î€!Ñ (ýL*€PZ‡_ÏÊÚòçÛHPЬY3™‡‡ÇvÝ‘pII >|x¤ªÿ\¸pçÏŸg8Žû@÷8˲÷ŸúÇ8@­co”Æ8˜´-þó ÷¦­¸Zx¹!#+†M5ÜínlØ2§ŒxˆfMÈòDTÑܧÿ‚ ˜0Á/1aÊO˜0å­“«¯¯ïb±X­C6ˆŒŒ´?uêT…t÷ïßG—.]о}ûm¹¹åWh°¶¶>9cÆ Å€µÏxB)…——Ï$oh)òÄbñ­·ñùµÙQ‚‚‚0vìØ5~~~Þ666ÛÍÌÌÚÁA% DZ)))ý¯,_¾ülHHȇϤ”ᥠš;%Ø_›uˆËõ4$uÚ’Z‡¨ÊŸcZdKz6v²>ûE¢Í¿_ò-@[k_dfÁȨ]\³f·Ú™™ö(#!í #uÜ@•ÈÌXû]JòÜ .kß*yÞ¸q„ü¦M›Ñ3ÓØ\ºtÉSßÁëíí J©Í;w>Öõ·p‡>ø`e}S)))|Å~Éà8î¹oÄÒÒ²ç Aƒ²ÞfÙúúú"::5 ÿúë¯ÇÛØØ˜¶nÝú WWW…v`Vh*• ©©©Ý._¾|`ýúõ›§)­ªC­|RÂNÈÿ.deñÞ[3@kJÌUÁ}ó¥RA3ûTƒQm|ä§Ÿp|sªk_Énƒ!‚8äÞ=‡“JejÏ C”ʆ-U\“ =í×ñ¢:%y5¾²àaDs4iñÆËÒÇÇ.\ ·nÝú^$ T*•,P¥ejjºÁ××·±þŠ§Ë—/¨»ÌƒZ­FëÖ­{xx$Ö´R«f¹}XóµúÅA?xÃÀÀ sÑ¢E~%%%Êçu@P" Ïk;ÖºfÓxÓ “ë –5j=€õ{÷îõ‘J¥þ‰‰‰,ËúäççWXÏ‹ã86::ÚwáÂ…Eþþþ5j(Õ’”,ø_Žê€Ü Ûƒd[¯Œ‡Š«¦;Ôý®F¥qhvvÏ6÷®‹áoß¼ª†‘áÓÔF-[¦öŠŠêVXp¥ÖUjçË ¯~õ sãf·}ßYvéÒ…¸÷Ýwß=V(M´&55ÕëÞ½{ [¶l£ýí™3gD×®]›¢Û¨ ¡P(|Ô¸”¸««+nݺUŽà<<<|üÈ×êccch7Ôök………÷MLLâ_ÄýÞv‚Ò‡îÄúáÇßðñÞ½{Å– ÃüëWXX¨¿`) ¦­ZµÊrÚ´icª[¥ZsŸá¨ú-—ŸŒ•®o©²@‰ê¾s€JaûÉ[>m¡¼£æ_míñèQ7Ò¸ñ•ö¦¦]Oé/_WÁ´Wq=Ý(JŠoŠhH)5z›äزeËMºvsŽãpòäÉrö>…Ba›ŸŸßJo}@Amîѹsçh½´EHHHðµøÅA äê½CzìØ1ÊKæ¿ÃðáÃå~~~©ãÇÿláÂ…ÄÅÅe•H$*Ô7¦¦¦Ž<}útƒê®U)IåÍ,«˜õþÒmòáþT.GuzýP¿‹º7:gúëàÆŒ¹ašÙ¯ƒø Txy£q±£ÑÈë|/[û¯Ã´QµõOUFfò’Óã¢ûFQJ%ŲÛo…GŒ±ÜÁÁ¡Ìf®I’ÙrÛ¶me$>>þ¥R©ŸwoÿçŸ^£i:::„«–––åî‘››kRPPàÎ×ä…Bñî(] XRJùh•WÓ§OŸaggçeccS¬÷îØË—/¯3I™®ø˜ä|ø›*:} Ôj”Ì«N›ª$ä\@ÀX°Ü=ñ}ù?á2þuÕnî»–ú qrþÍÇÚzüB5hL5iXy¡Nñ1ƒÏ¶AZòü·BŽVVV õò͙֘ ؤ¤¤±º& ‰Dÿ}µ ˜ÐÚé­¬¬òu«Õjá¶mÛ,ë’ˆ³*h4A~§''§{ºßår9Üxɼ: „Ð3f¤ЯÏ?Ö™¤ ¾Ù=Iq+vT*Tn«L{ª$ÂMìVØF,úŒg÷æ×3ÀÞá[š™¾ήAŠE#",K‹TŸ¨?B€‚Ü¿;f¤þü§½Óâ7^~!!!ÈÍÍÝÄ0L¶ //oìܹ󢢢r&4h°‰’Q—…îlllÊÍÁ¢”Jô­)SM¸pá5j$‹Å¦|k(EDD’’’Ž ¥Þý+ tY¯”FuÖØØ¸,£:Ã0HLLDHªät¸¸äø½ÏžjPúäTÓÜ(M®>!—Í듳ýµæCÏ»YxÙ†6nµÇÈøÝ ,cP· *ú¨²3–û½ ²4hüýýÓLLLžèÚÆ322¼®]»Ö÷áÇmtµ,cccLš4iÂÆImº»qã¹sçκi}(¥(**šG)­wÊ ÀÀ@téÒ„Ùr¹Ü„o ¥hÞ¼9ÜÝÝ !åÒ¤çää4Ù¹sç˜ú,¡mâàú.ûñ*(2úŠºå~ðàýáÇà÷߯W!´–++«raê5eð¨Ðhäß²$"¦}ÍZ“ºjÍŠ¡ui´Üúì¼Àlåh¾5=Gx5»ƒ¤¸ñhèua“©Å°ÑZª¶þ)}¨UR$Å~2ò-1;¨Ú·oÿ•~Å¥K—¶¨Õ꺿511 j·¬º>>>´{÷îé”Òr eÓÓÓ6lØðG}Ë=cÆ ¬_¿~FLLÌt¾”ÇСC¥vvv—uß)Ã0ˆŠŠÚtüøñÆÕe© 4‰ƒ]===_Kͬ   BwðÅ0 îܹS«ðü7bÙ²em‚ƒƒo^¹råîï¿ÿþל9sêUPJ ’’’ [ž*¦mTMRªÈ$–× 1Ueþ+=ÎXæ²^öËeÁ×øô‚àì¶é)? Ûö¿Ä’¦u6õém”+iõ6È-$$}ûö½äîîÎéšRRRì´s¨´Ü%‰6ÕÇÔ£G‚fÍšÝ×]>‚‚èè詇úvîÜY§k®ZµjHLLÌÊ*fõ¿õ˜1cÆ—úIi‹ŠŠD‘‘‘ûÍÌÌlê¢ i—””$X±bŧß~û-;wnÜêÕ«×5 ûöí{­d“““sB?U×ãÇ‡Ôæ¿&L€Z­Þ*“É•J¥eZZڨŋ‡œ={Ö¢.e8x°t!ÖÍ›7OR«ÕDw€èèèXP'’åZÿ©º­Tâ²â<Å•‡EÂŽ|ëy‹ÜJ_"©Ÿ™¤hÉ[‘—J;iW©TöѪ;²£”R fÆŒGêëG3fÌh“t}³Æõë×78pà—O>ù¤ÚQyhhhÙçÕ«WïNJJÚ«Kz<ÊËŠ’Ù´iÓ¥úqrrróS§NÝ;qâÄ€ÚæóôôÄÍ›7{®_¿þRFFÆv¹\µZøøø/BCCû<뢎/³fÍÚ«¿®ZFFF·;v4JSUJ©µîsss? ½uäÈ‘Úã—/_®öC† ÁÉ“'û<~üøçJ¬SëDR‚fÎ1×R“ªbS«]Eíܾ¶pá[Ð BjÜx˜[û"3eÑyñý–Ï~EæÎÛ$?—{b±¸Òå^ !ÄÊÊê™’Bï¾ûîgBa¹hv(•JÑåË—ç¯ZµêaBB‚×Î;­)¥åì±±±æ÷îݳݲeËðE‹åÄÄÄŒP«Õ,_ë+GŸ>}pÿþ}8::þlddôPw`@Aaa¡ý©S§Žlܸñöþýûß[ºt©EFF†‰žödõã?ZìØ±ã 6\ݽ{÷Éââ⎺‹-RJ¡R©Ì_7ùBJlmmoèÊE¥R‰£¢¢.>|xÔ‰'ì~ýõW‹¢¢"ц *üßÀÀ`­~_•JåvöìÙ•Ë–-K>pàÀ´ððð†K–,1¿xñ¢Åõë×-nܸaqèÐ!‹?þøÃ. À{Íš5g?þJ¥*·J¦……8ŽÛReù+Ä1‹‡ødËÏÜ¿ píj~üÊMõT®Fqð¥ùÒ±¸Yl›þ‰,ø Guæ[Ós$(·-H|ÜlNƲ­ r<‹Ä Ýþ¼ؾ52>|xÆâÅ‹Éd2_ýðrù¤I“¶}ñÅõ¾þ7àããstûöí«nÞ¼ù¥@ (×qÆÅÅ5‹ÅQùùù)?üðCêüùó3LLLHQQ‘`ÇŽ2™Ì,##Ã’ã¸2-RJ% Q©TEjµÚˆo Oáíí …!!!Ý}šÑžS©TP«ÕF”Rk…B¡­Çe‚U«ÕprrZâççW\'MJÒ­¹\ÜË{Ké™Úù *l„•Cqöþh©ßê%|˜ <Ø·U«Výlmm39Ž«²s©lôN)¥ÎÎÎW;uê䟂:.±ckk«ÔµšPJallüÌ©šôI^,?³¤@ PëÊ©¶+õNž<™4¨`ðàÁ­›6mºJ,£>Á&”RpSSÓ===MŸ>½!„«)oŸ®Æ\—r×+++Vß¿ijjZëä„¥¿¿OWW×-B¡´’JÈ0 ®_¿^AXcÆŒApp0&NœèííýŽÝýÕŠk •J+++8994iÒ°uëÖ‘š¦ T>™÷‡`ÎòÀ×_ ½]vW®QÕ’Á 5Õã”O2ZÍXjur!ŸÃ¬ž¦¯€KÓÛL\D“jeêfp%ÐYÿ°ÚWPÕ&9gº6¾Ú%-Þ7ïYË×®]»±X¬íhiƒ ²&Ož|ýU•g·nÝÖ/!!¡Üä]33³¬#FœÔÍŠþ,øàƒhrr2>ýôÓ_ýµm§N¾566ÎaF®Ÿ½[¿Ã „”'ôèÑ£ïÌ™3;õë×/¡>$РAƒ{æææ»µ‰uÅb1úöí{ôYŸM¡P ¨¨è–eµd¥øßÿþwéyÈM.—¿+‰ÊÞM›6mŽÕåÿFFFR??¿é?ÿü³½——׉DRL)®Næ„°,Ë1 Slkkû¤_¿~}¾ÿþûŽ'N¼½½±yóæ6ééé­ ó§OŸ~‚RðªÊ”RÊ,]ºôHfff?] ¦sçÎ|ôEßïÞ½írrr¼¥R©•µµu/¹\N affÆp)“Énš™™ÝûüóÏ#! í!S¦L±600¸E)Ë7hiiytþüùkx^áÚµkåç盘››ß™™š2ßë—{×®]=âã㘚šfL:õX]Ë­í{züø±Åþýû{3 cЪU«Ë½{÷~\×õÍÖ­[‡É“'kËÛÄØØ¸SJJ G)¥NNNׯŽUS½¸páºtéHMMuÛ¹s§R©ljaañOµZM5Z%‘ÉdW†‰177;vìBH~]Ÿ¿Ú'Ô<äÍúsGñžËŸ Nê­¬¥@ܧm†ÅÖ™v<õÔ±3Hœ~-/ýŽ:«žÔç ”šd Ûe¹4 sËÏÞRdfíûÖÉ288éééÖ©©©wT*UÙê¼fff ,pÕíÜ^$ªë ª:wàÀváááaùùOÛzmHŠÿª.?+jXª£4àÁ4Ào¬øý3‰åÊwÕmúÝ%Prä_Û¬îß&­ÿÇ>ç£ÅüÛ­)º‘Ò}#yétÔ®%U?#Ó¾7\š„¹BÞJ‚Òš. †rç¤kê±³³Ûीjueçnܸ'Ož(åry¹ãvvv¼ÇŠEP5’”Næ,vø²žöŸ€€«y_5a‘ªÈgÙÖSw,÷Ïçßn5pô:GS¢:_+É?=€!ÕjqN(n¸ÏÑóx/yñ¢·]¶R©t½^Fˆ"‰D²íU.³lmm»””””;^PPpœo-<ÞTÔ:J(ó½¯a}æ—`qÏV£ˆ±¤–ZTÕçÕÑ)vÞS’²ÞmÊð8þmhtß@b¸ÇQyÁ¥5(Tó]ûY(l°Ì­EôpBHžä¢øÞlÚ´éÿÒÒÒÊœÛÇÁÙÙùñرc£^Õ2•®Í˜œœ<[×Á²,%„D%''ó ‡Ç‰zÍ-Xºÿ£¢?ïÇ1•kQÕiXåÁ6´‡Åö¯: :\æ_‡.Q¹\W):T%QZ[ SÀЬ÷v‡F'ÆòR>ìþï¿ÿÞ...6+Ó0…B|÷ÝwmŒŒžëD±°°0ɽ{÷&0zï½÷Ö7nÜ8ûY®÷×_ Û¢GRݺukׯ_¿ÇüÛåñVkRº0ùæ£ýF³}ʺØhòüUš^½ŸJ•H¥£~½T°8x0ȂϿ•/¢$¿t½"µJêšÑø¾Z‘Ð輤êüM¨â8Ó.Ë›ò¨_ÛDGGoÖ%(pww?nddtûy.Å@)]¼x1%<<|eDDÄ/;wî¼~çζu½Ž6ÁmXXX£ÈÈÈ5„²†ÄqlmmñŃ')=äÍÝ “ÙCþ2ž=d01WCJ´†ã²D˜‰â]g‡\{ÏpTWäÍ\÷Ö½‰éû ”:dE÷‹S•Dµ¨iù÷šÎQ ˜ÙÍÜâèuavÊ£npô:÷ÖVòÐÐPPJ™ÀÀÀ³IIIåØša˜ccã™ÀóuþîܹspRR’…vŠL&óøë¯¿®îß¿¿'ðÔ|W|||‘‘Ñ$44ô¶L&3Ò—ˆÅb 2d"ßñàIJf¿Ž ïb¾uV{b zÊU©-U}üéw.3—æµþRΈŸ‡˜­œŒ¬žß¼/@7 “îwKð¼¯(¼F«ò-¡–a$0³™¸ÂÊ9À7+aÊ[MPPTTÔ}éÒ¥ÿ$''wÓϒݸqãU£G~ô¼ïéîîž Ÿ}@­V‹îÝ»wòÇ 444¬qòͶmÛš, ŒÌÎή«ÏÃÃcSÆ o=eéyðxUñLË3®8ãYƒ‘;}½µâÂý8.5ÇLe—¬É«¢“–F$ÛØùÖ'~½T¸l/Œgã_‚,{«C~Ê‚µ"¡ ©TNó•~§€¥ËÚM¦¶S&d%LµËÚ·¦2oÛ¶ C† 1»yóæg‘‘‘LII‰«J¥š”™™I8Ž«¦íàà°å«¯¾zaqø‹/ž’››»¦²ô1„µX,–¹¹¹%K¥Ò gggÊ0 Ô&&&rrrJ¥Rëg°á8YãÆó8þ|þ³LœåÁã&©r£Ä˜T³œQKo«3ÝkON•tÅ”R"ÉÐοš­˜<¯`Ùb2{Ä—"ëAkX7»ƒœ'4T^¿É)3Ì(yú>h]É  „ˆFVã&Z¹nØ–—¾fv³ÞªÊ|ëÖ­æG —J¥åRé§•³ IDATl¡”ÂÉÉéÉûï¿ÿNxxxÖ˜1cž{Yàïï_~ùeqQQѼÊ—jóòBÊòùi?kSU;;»ÈÏ>ûÌÇÒÒ²ˆïÂxð$U äÍ\³•“PrêŽMáÏ»¢Uáñ&²¤ÎݬîgB`äÿQ¨Éì}óæn„Ù¯Þ8áKcFÚ+òޤr\Q•ÄT[mŠ -Ú84 »““8– V¾u•yþüùó Å/ÕVxBàääÔ¿ÿI^^^Ê—Q®ãÇ÷¿råÊ!™L&¬k}x{{ïêÚµë777.885%çäÁãuó<.b¶r@Ò³u¦ÕÙ¥ „][$”šýêIP åPøËŽ>ÒñKw™ý:9}ÿF¬+K_(Hþv "ïï(ÊQ¢7b µø¬ûa͆V£Û;4 »“ú õ[IP`ii™­oÓÕVLMMS\\\>›9s¦ßõë×_ A%''£_¿~Ç-Zdbeeõ‹D"‰‹Åeåª,#º6·V dY6ÉÜÜüÈ€ÚŒ7î“ .px‚âÁkRuÏÃpTW¨2ì¤ÃÙ®ŽKïU‘kCTå‰ÞivÌòàO²ºÎ€õùÀ×^èréòâFÿH¹’:kPTOtŒØãÿµ³tßy+;n<¬Ü¶¼µ•999Y°ÿþÓ‰‰‰]8Žƒ‘‘¬¬¬8@°½qãÆ;üÛ³gÏü—].]g÷îÝ&©©©Ö¦¦¦S {Ëårïôôôršž©©)¬­­ÕJ¥r{ƒ vÞ½{÷Æ?üPHQ×%á)ŠRP‘7Ì]7½ghùñí¢¬ ·– Ë>wêÔ©Ú߾ހ'¨ÿ¸néÖ±Uwyü$eóï*ä|´V/)éç³»¢ª²‰¾ÕhT„@qù¾}Πy‘%§Â hCÈ+/à¼ðF€ü¨ÿù§/ÿPEòA- J ¡Ø-ߪѩVf²Û0zM²™_½zõ¹_³AƒØ»wïÄC‡uvvvæ[ôk‚ýû÷w:tèР—yÏ={ö´üûï¿ÇÕö÷°Üºuëè={ö°Ï³ÇŽk²wïÞ/ùúZ;¼Ðÿ–û€Ô÷wXÍ•çÿœlKèÇD,¨†¨P-Q‘€(oDÚ. Š ”6$„ä¾ê6kñyÞ?ªŠ®ÿ@@¡]­P½§×?§ýÌìcŵd…v… Ùmˆ^d±111dõêÕ¢–-[žP©T&•ü$ìƒ>°³³{¸mÛ6ŒûüÒªTª¶ß~ûíz—k)))¨ùfýê#??ÿrqq1PK—Ù3gн{÷²}} T*o%%%±¶Öæ÷öööÇÂÃÃ;¶jÕê6€H½rîÝ»×kjLaaáׯ_Ù¿ÿh|ûÿJ“ÒÂ"hòlYÀ£MßGÄBTž2©z‚Òݫƙg¶ûårÈêùå+)\J©(ÿž£Wr¿F J•#XM¸]«´† éþ"¯A@Æ éÈ‘#¿}ûv—ÈÈÈFN:›óãÇ'üöÛo‘›6mZÅdÞøÿ¶ñÇ¥”)~ôÞ9uîÁj£AU«Iq€È¬´™ëŸÀÒëÜk—JëGhÖ¬Y”¡¡aXll,(¥†^^^¨Ž¬ô#«!Jé¥N2¨Ž ÃÂÂH]þ÷îÝÊ®QׇTõ¬µAUgU”­Êçã8NUÛ{Ö%àE+¯º Bj*÷Ñ£GñÎ;ï<š3gξV­Z©ëúÿúܳ*4mÚT1þü]mÛ¶9zôh¹s/^$u©µ…¦Î+!ªjêêR¯^§ÈBÁ˾¡õ©eÈ›¹f+§…‡\îTðíÆ+\V.@H5)€„€ËÈAþüµkò¾þ#Éì·éç|4–ûyäô¨$^ç@ Z ŠxïU—„¿§«ÑZìõ5) @b5êiÃàæ n¯µ¯EkV"„q•JÕvåÊ•š7oÞ’a˜Ó•ˆkÖ¬…††öعsç‰ëôôtk`YÖréÒ¥ ¬­­ ?ûì3©n¿i|àÀnÉÉɽ þ¿½+kêØþgr³² „€‚€(‹âëCA´(?|·G[xu_Šb+ÖJŸ¨(®µ­Š"ˆZ\©¢ ds§<7 Ù!†= d¿¿?JlD\ÚJ_}Í÷óñƒŸ¹¹wÎ9w¾sΜ9C¥lmmo&%%¹>`£¨¨<==¡¾¾žK¿pᦲ²2¥•••Z«Õäp8åþþþ2ýCoß¾ yyy³žB(kmmµ§Óé`jj ·nÝ …²õâÅ‹fÏžý1@GGGì;wdff®˜8qbB÷b> Á·nÝúÃÅ‹ý‹‹‹›ÝÝÝ_!£Óé >>¾àÆÏÈM¡Pþµ}ûö¯–.]º!-- BCCJ¥Þ½té’`РAç %99Ñh4^AAAFgg§™LƒW¯^2™VTT”‡ãød„PGb€„„„ÜæææÑVVV@$!77X,VĶmÛâ—/_þ¹¾ÎÞ0jÔ(§sçÎíqssûÞ ÇÉÛ¶m+ Óé………`ii ÅÅÅ R©æcvM$-qppxî<•ÜÜÜ5ÖÖÖG+**ÀÔÔŠ‹‹A&“-¯¬¬<ãø „®ººzUmmíj­ög²¢¢¢Ã0¨¯¯÷€Û8Ž“vîÜy@,Ï …`ee÷îÝƒŽŽŽKKËû8Žÿ !Ô  Õj=¢££oŽ9òP~~þ™L6!ÎÎΦ𡑤zÀôƒ± ,¸ ”QïdjkŸü½eÚškÚÚ'ðâ ðr¢B¸¼YE_7ùþK̹òí©Ö¾ö˜>{Më) ²§âá{¤®ÎI\ÛìýÚ&ü -*`$ëµ,çËëe5Q@ËòðõæŽó÷÷ÇÏ;w%++ËdðàÁÙaAWW×7–––ÿçééù4$X(‚B¡°.,,O ª*¹\® //ï»Ó§O‡988¤¹»»ßàp8—wïÞý´‘HÄa0EëÖ­¦ßšpéÒ%‡«W¯V´¶¶Þ4˜ÀöíÛ³«««Ý\]] ?þøã§Vobbâµµµ1MMMùË–-ã8ppG$ Š‹‹Íx<Þ½U«V=}Njjêû÷ïß‹Å{Ïœ9S$é­M|}}áæÍ›ï§¥¥EñùüÒÈÈȉ¡J€;wž¯®®öOMMÝ+;;;÷Êåò‘»w/{Ø72™Ì‡4íÇîöF"‘ˆÌd2N˜0ÁÎÛÛû©'..®ºººú«ŒŒŒëS¦LÉòññYÒÙÙY˜••µðŸ*222X_~øðጻwïNÞ¿ü¾}ûü½½½µz77†aŸŸoãçç7iüøñOÃÐ7mÚTÐÔÔ²{÷îÀѹsçFÈ I$î|°˜D"Q\]]o|ûí·Kª««g ‚Š¥K—:é¿¿cÇŽí¸uëÖâM›6åÀ0©Tê¨T*áöíÛÿÔh42__ßÍ“'OŽÒ»%õ²ý¥×¤z‚2êPß&à^7 mO`ÓëA«ƒÞ3R௰¨ôE:ÐTTŸlLøW_‘= p§àšú ¸¶eòë®?õFX?Ü&€™ ú‚íV·¾íÁ»oAH$’ÐøøøýñññIñññI6lHŠ‹‹{íÃ`0 6lÀüùó2 myyy,À/¡µcÇŽ…ÆÆF¥RÉ$šÊÊÊi¿Fß“’’Ø2™,ØÌ̬$222øÀ••sæÌ™ÂçóOët:ßÁƒ»õ$·yüøñ™†k~+W®œÔM‚¡úIÛÈ‘#7â8Þ„ã¸æÝwßÝëêêº]¿ÚÑѱŽJ¥Ö.]ºt°ž ²²²`ÆŒK8N¶T*}7--ma½d2ÆLž<9*//àOKPÿu’€§9øgó*¹Rl°~Ü_¹¢§¢ÀñµZè:yy—²àÎÅ…ü>•_ùðÝ\U3Á«=r/#,„H€QßýÜÌõ~¬¬2 ÌÿøÖB𛛇I$’Ù‰d¦D"™ÙÒÒ2³¥¥ÅÁÕÕUþ·#Fˆ»«b±XqÍÍÍ‚óçχ†„„ÀáÇ¡{Æ·ÓÔÔæÌ™3__Öí“ Ãzµþ9NÃÝ»w‰z—ž~ð©©éc …/^€ÒÒR–R©$šššF!„´|ðnhÅ)•Ê­ d2Ùç†n)gggèé~xçwîuuuAUUÕKÛ&""B£ÕjA«Õ‰¡ÔÔÔõ–'‹ÅÊ.//WxxxT‚3àÙÒÒbc0¨ÓàÔFYeÐßÒ<|:\\\étúN÷Ô ;vlŸÏü©B¡$IvCCÃç÷ïßÀqü(BÏÎÎxéÒ¥~‡^÷@B2™ l6ûyï>Â]¿‰ÓÍÍminn.>§ûcÇŽ…7jººº*T*•·á N¡Pz­—J¥öz°¢!òòòÀÉÉ)+!!a¶X,N!“É ¡PxyëÖ­éÓ¦M;aoo/ILL½Û-00pMRRÒt"‘¸&_¾|mÞ¼ÙV©TÚZZZ #""z¾{¯.uSÓgÞý– Á>“0Œ@ ØáÝ V8ŽÔjµ=BHÝmqBrr2š={öä„„„;÷ïß$‰àââ2ËÇÇ'WLð:}ö[åvppøìþýû­$IÞ›ÅVVVö#‰D‚ææf¼§%õ¢:ícww÷5ÕÕÕ0iÒ¤z^+)){{û›‘‘‘PSS£ë9Qàpz7¾ ÂkÉQ\\­R© µµ5`ùòå&†8Çu C´Z-H¥RdX¯ƒƒö6+Ä?“0gã¡mÁ ';Ѷùý¨õÍ‚—T/V”þ¯Nº–ö1}:(+JI€®¿míI¯‘&@2û¿•´þ·(›’€ò–äá{‘%E êgΜùàE¿ |J× •JßKMMå@H$ú^§ÓuÉåòx}$ÞkÙÓ/8›©'ºººT&&&½^ojjÂu:¼««Kóºõ¾ úÙjdddjnn®°¤¤äH]]ÝØ¶¶¶qÉÉÉ_oݺuÒ²eËž®K 0 ,..îlYYÙû8ŽÛ#„øàƒõÇù_#þ””ÊÚ8È.övò—ýÈ^ï^„g”~äqmy}k9PßDä¼Xœ—”0P¬V/§ ¶¬€¿$AL:õ“ɬ€”œœŽN§³är¹kBʾ¨O$}O¡PàÆ½:ãÅb1¦V«Y ÑoºnCØ Aƒš>ýôÓ£QQQcp×jµÚ< üj¾xñâB„P“T*¾{÷î%†ØÞÞlh¾I(•Ê¥4 † ’Ù“ öîÝËBYZ8Ž[^¹rå–‰‰ ¨Õjgg烉Äu×®]‡þ½éììLQ©TPQQAúoêo~~þ!*• Ç·ÿ£ëÞ§‰šÎbø«ÃÖÖö€H$‡s•N§kÂÃÃS{þ†Ãá4ét:àr¹N¿óî&‰MUUU!wïÞØ‹¥•C  ((èÀ›z¿·nÝz`óæÍ_ã8þÌBL]]J¥’k4š§302™,>|xa{{{?‰DO"‘FŽYû&äÑjµÀårGöp=ÝQ*•PWWÇîQŽ©TªU]]]ÏÌÆ¶·´´ŸÏ_¿páBuxxø ssóšÚÚÚ¹>z‹«¯°pᄉČž×îÝ»çlaañ»÷J* ýÚ_'ÀÏ멽è®ð2©Tºé»ï¾3ïᎳܱc‡H§Óý¾I;‹¥Ójµ2„Çqª¡,T*5ÿÑ£Gï=zô¹#HRSSýcbb_½z•j$©>ó«÷î‘ùÄAýþ /ò¥ö.GÆTÔi~û— ûL>’í.5"ØÛ³jôÑÆPé#‡0\äJïöâŸ$“ù yyy€aX ‰DjkjjbÛØØ,Ci{¦mE €¶¶¶ÏãââV …BßR_```ãèÑ£Êår³³gÏ–ÆÇÇGæååE?~|ݺuëꛚšÜ­­­¿usskìmPúĨ"‘HXccã¼øøxåÚµkW8p zýúõkŽ=*“É<âææöŒ rÆŒA,‹,“ÉÀÂÂâ˜OÓù®˜Ì,‰D2,>>>åÚµkãþùÏn¢P(P[[{~ß¾}ß …ÂÏOŸ>ýùúõë‹kjj>7\Ã;pà€¯X,µ°°È_knn¡®Õ«WÛ1 ¸}ûödžk2oEEE€j0Û¥/ŽžIDAT`Àºöövç5kÖ4§¥¥Ååää|ž’’r$--í§ŽŽËß[FK“J¥P__$;;{N „……uº¸¸èè耆††æ„„„ÏŠŠŠ¢÷ìÙ½k×®'b±Ø¾—5 _åuqqQs8œ{:ŽsâÂ… «õ²xxxlÃq/..>¸k×®Ü~ø!êìÙ³Ÿ%&&–””\T*•ÑMMML#Iõ1Ú—m‹ ;V“Ç Û‡H˜ 4Zƒnîa]i4@à²ÁtÖ”p“÷}4ñÙ§²‘…û1ó™çÆxucSßQc¬É¦N—ÊïTþÏV«Í£ÓéÀçóÕB ——Ì™3GD&“[LMMÕ4-S(>—ÊÀÑÑÑ™B¡\#ïܹ`bbRÁd2[Bètº®7V“É@ 8sæ Lœ8q¥ÏªÎÎÎBF³%333öþýû_â8®ìם߿… ~" !00´Z-Ža˜D£ÑœêµÿÉä;, x<ÞKsÊ-Z´èc''§È¶¶¶< …²ñÑ£G±:n½Z­®e³Ù‹çÍ›·¯W!²¨T*DDDì}A»çÀ£Q5FkåñxOÝwYYYÀb±>äñx…]]]³òòòæw¿Ç›áT*õªX,¹téÒ†âââ †Ñ]\\Â-,,~d³Ù-†E³X¬¦Õ«W‡öRg(‰D‚„„‡Wé ”¾@îJÖf(·F£É “ÉjµZééé B¡"""blllÖR(ùO?ý´:++kCiié ‹u…@ |ÒK†5¼ÀZi¤R©Í<O––ÁÁÁ{lmmSÛÛÛG}ÖÞÞÎÔh44 ÔjõI€¤¤$˜={vüˆ#>Õétw»ººþ}öìÙØæææXµZ]4dÈ«žu©Õêl6[Íd2ï¼ mnòx¼NòˆˆˆùýúõËDËÏÏ_ƒã¸ €¿¿ÿÉ   Ùt:=§££ÃûÚµkñ·nÝú·T*ýÇ»èííí,`0÷X,–F¥R•Iê ƒ•øsò_vêWŸ˜†MJÿ÷N\­Ðêt¿üÃU* û»–¶p¦3fáá¶Åúv`î,„Šh·7ˆ@ó Pü’RPÏ›8ÂX@dÏL&[­åQíÓ„åþÿSÖH$‚K—.çr¹´‰'žøµ÷'&&Ú) 3“[¡¡¡¢ÞBŠÏ;'N,·³³ó²±±a"„bþóŸÿBHÌçóD"ñc6›ýI“Éd2---ýû÷wY¼xqBèi¦„ööv055µ“ÉdÓ{>[(°aîóù|š££ã sŸÕÔÔBH3oÞ¼­`¬••“N§3-,, pŠŽŽÞ…RZú3„ºººØlv*NÿI¿ñÒ*•ÊŸD" éM¶~ýúÕYXXcõå0sæÌúÑ£GûXYYÑ5MÀÏy÷æÍ›wÇÚÚzœ “Åb1---Æ ôñÇïçóù#íííH$’ñ\.×!Tk˜@5==xÌÚÚš÷²>W«Õc ÂÐÈ]caaÁwttÜ¢/¯ªªšÅd2-ËËËe¿äƒ\ºtéz'''g.—Ëd±XL‡ÃX¹r¥ggg#Bè™­2™lš‰‰‰Ã \Î6›íäèè¸ 44vîÜ mmmslmmL&s‹Åê())©333£‹D¢H€?ü’““!44tÛàÁƒ=¬­­™ ƒieeÅ4hwhh¨¸Û*{ú­´¶¶þÛÆÆÆ !T!‰ž“E.—0`@˜¡î#„´³fÍšÂçóÙ\.×!¤())sçÎÁèÑ£xzzúÛÚÚ2X,ÓÜÜœiggÇœ1cÆä &”&''CYY`vÏç³׿‰Ä·ÞÚÄ¥ŠË7TšŠjK„¸æ2rÀßOS½/ÿѲ¨Ê'ÙéÂÏ_Cì\ò±®®B@²% Œ–G±ÝµŒxLJüã°}ûöغººè#FŒ™>}úÕ¿z»è“¢nÙ²åpSSÓl6›mC§Ó.\ˆµæ¤ÆÇÇGGG·<³©ïüùóQQQŠØØØÎ¤¤$Ó_{¬‹o¹%eÄÛ‹êêjÚ©S§’ZZZ¬¤R©—¹¹y½@ H§Óå!!!ikaïÞ½‡***˜d2y*†au~øá{{û £Ö<¯¿þzYmmí6­V $é2…B‘Óh4¿ššSƒÑ6nÜ8?ooïÛ}-GRRÒüGmA™Êåò³\.t:‹\.wÆ0L>`À€aaaÉÆ3’”o Ôj5çСC…B¡µ²²:rþüùˆýû÷+ÿˆM v9rDÙÕÕE–Ëå_¸ººî7n\S_lÞ}Ûqüøqðòò"ìÛ·-ö*•ÊNZ­¶ŽÅbí£P( 3fÌê]Ê} ÇѾ}û¬:::æZXXl”J¥Àd2A"‘¬b±X‡ÂÃßüÚÃ:0ˆ?„B¡‘àÂ… ÆFø•8}út¯ºcèR6Â#Œ0Â#Œ0Â#Œ0Â#Œ0Â#Œ0âOÿH€üÒµªIEND®B`‚pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/static/pocoo.png000066400000000000000000000041521250413007300273720ustar00rootroot00000000000000‰PNG  IHDRJ?G?^bKGDÿÿÿ ½§“ pHYs “ “åA8€tIMEÞçgÑò÷IDATxÚí›{•uÇ?Ë.àe¢,Je1‡ıT˜², }”L3¦r&¼DŒ(bŠ©T“Ø 1˜NÀ—‹c†Z^HMÁD, YãR "—X.ÛçûÆÛ™Ã²œ={vœgfç}Ï{yÞßû}ŸË÷y~¿…²”¥,- ­u`Ñx8¨”´¡%ÇÓ¦ÄóãÓÅ® Ty ØÔ{€{Ê®w`÷{xX Ì>)ieÙ¢öTg€þ’æ —"¢ÍoQѸ  IºÐVõ&°Éà­="ŠˆÏ¿ª<®g€eÀçÓ€c.Àj 8MÒª#Êõ"¢?°h LŽnŽ:zœ³$­z•ñµ#Æ¢"¢ð”ÞÖÛÕÎNôù’žŒˆjàU ;𸤋k "¢ð²^|¸¸Ø ì´0"†S€Àq’6GDðpð`ˆ¤Í‡«ëÍÚ£žÀ·€ÉÀ<àg½¯˜OÍð±z»ÍqlIDß*,*"FÓ€s$½ÔDkš Œf¿½€“5’Nʺgº³ág$½ž:þ]à^ èÓåΡZÔ½ÎFÏGDï&€ô%`¤3Ø×~ì>ÌÎÍqëh ½Ýí"i’uts¹óá–ªxÜäoqDtÍó¹£ýì%m‹$íj$…¤Ù7Iªõîçnj€Eø-Ô`p¿þqé!ZÓÉ@à>Ió}¸ø_x{#Ôä´I“íÊ=‡Z¨G€£p¯2 œ“s•.E:G„"âXþðOáDêÜ)h •hP$ ž®Œˆ[ TÕ!^ÿðoààçn…̾ ‰ˆIf×{ýULOYÊeÀÄ,ËYfZðh U¦:Ë2ΫW€1!Iÿ(¶EmV•&‰ƒ¦~¼àÌ5Õ ÕßðËv6ûžÃRûFÄ• <û.7ñ~}«Zá0QíûŠkQ’öDÄRg¤ À JÒµq‡­ât3æSÇzIÚfG#%íËRýWƒýhDtæ[à,à&ǵz`WФ6$߆Ã"â!IÏÓõÞò¶ ðBâB’Öß·åœm«º.‹-¯—43ÇØ \+Ýšèà^eºÖ±!5††>êÛñ0Â:O-63ÒÛ%ýî×ÜêZí7Yƒßw—›tu²x˜kKúmŠ o•´%»"¢íTNp¢¨‰ˆ3Š^ëEÄà’:å8wðgàaIר&ÜäŽv÷[ý{ð1ß Ì¦¥ø1fî7Ø\­h@]dk™+ihÖ¹YÎlçIz¶ µ5ÀÔd…3j[àïÀOÍ«†96bÆ?Þ g°Ø±`°ÖÀþËívÿ‚Uí”^ãª}^Êš–Ú Ö™ˆˆžŽ3ã·Ýb©´…<‘ô\à[nÙ,wðï\ãW½Ftóê8‹-Lñ¢DnövEK­-v±…. Û9û½›ÓnIÏJh‹{Õuaw%ú¤zÿ%D÷òÆTMi³$ü¤D$_°¯·)0P—µn­^ÒîÖnQivÛ%O ÔØC¸gš[(³“r¦T\àÓyê8ÁÛ1™rŠˆA¦Û€áÍéÞ…êÝTÑD *éѽÚ»H®î—´§T€Úl êÉ´ƒó‘]©ý €/7pm?s¨:—.” P都”E«²J«s¸6ç•B̲¨Õ¶ˆz»FM:¶f•Ãàv׳Z;¥”¤:àõ”5\ž‡šîe%=£vqqH•dÖ-¬“ô\Ie™‘Ú‡:¶3U\'€7@#â(2‹ÊNñ¹)Å"µ…*=Õ-Ï žÌ'Eí^‚x“³bwó­:2+kJ(O#½–*e†åÙRI¬ª>¸ÇXço[Zª Ôþ÷òÔqiVöK¤™ÕuI¶ÛZÊ@=Çþͨr7Ÿ.A¶ Bf‘FŸæRDi jùÿ)ðòtãd³¦­ª&5æ¥ÔÚPõ@uDtˬAìŸÂOË>I«K(·Gf¦,¡-™eÑùÊ]i"›ð'Š,͵|úG©`œ¬HÉW^6­Èª+K(Ó„§ÀjÓ]»È4·Ÿ2—úe±ªjFÝc/št®o¢®d&6z®îÃÅõô>™)öiú{µãÔ^Êr`‰ˆ·"b~KŽ¡ªD°úð“²É”¥,e)KYš$ÿøÝ{Rp«dIEND®B`‚pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/static/pygments14.css_t000066400000000000000000000165751250413007300306310ustar00rootroot00000000000000/* * pygments14.css * ~~~~~~~~~~~~~~ * * Sphinx stylesheet -- pygments14 theme. Heavily copied from sphinx13. * * :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: {{ theme_font }}, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif; font-size: 14px; text-align: center; background-image: url(bodybg.png); background-color: {{ theme_background }}; color: black; padding: 0; /* border-right: 1px solid {{ theme_border }}; border-left: 1px solid {{ theme_border }}; */ margin: 0 auto; min-width: 780px; max-width: 1080px; } .outerwrapper { background-image: url(docbg.png); background-attachment: fixed; } .pageheader { text-align: left; padding: 10px 15px; } .pageheader ul { float: right; color: white; list-style-type: none; padding-left: 0; margin-top: 40px; margin-right: 10px; } .pageheader li { float: left; margin: 0 0 0 10px; } .pageheader li a { border-radius: 3px; padding: 8px 12px; color: {{ theme_darkgray }}; text-shadow: 0 0 5px rgba(0, 0, 0, 0.2); } .pageheader li a:hover { background-color: {{ theme_yellow }}; color: black; text-shadow: none; } div.document { text-align: left; /*border-left: 1em solid {{ theme_lightyellow }};*/ } div.bodywrapper { margin: 0 12px 0 240px; background-color: white; /* border-right: 1px solid {{ theme_border }}; */ } div.body { margin: 0; padding: 0.5em 20px 20px 20px; } div.related { font-size: 1em; color: {{ theme_darkgray }}; } div.related ul { background-image: url(relbg.png); background-repeat: repeat-y; background-color: {{ theme_yellow }}; height: 1.9em; /* border-top: 1px solid {{ theme_border }}; border-bottom: 1px solid {{ theme_border }}; */ } div.related ul li { margin: 0 5px 0 0; padding: 0; float: left; } div.related ul li.right { float: right; margin-right: 5px; } div.related ul li a { margin: 0; padding: 0 5px 0 5px; line-height: 1.75em; color: {{ theme_darkgray }}; /*text-shadow: 0px 0px 1px rgba(0, 0, 0, 0.5);*/ } div.related ul li a:hover { text-decoration: underline; text-shadow: 0px 0px 1px rgba(255, 255, 255, 0.5); } div.sphinxsidebarwrapper { position: relative; top: 0px; padding: 0; } div.sphinxsidebar { margin: 0; padding: 0 0px 15px 15px; width: 210px; float: left; font-size: 1em; text-align: left; } div.sphinxsidebar .logo { font-size: 1.8em; color: #666; font-weight: 300; text-align: center; } div.sphinxsidebar .logo img { vertical-align: middle; } div.sphinxsidebar input { border: 1px solid #aaa; font-family: {{ theme_font }}, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif; font-size: 1em; } div.sphinxsidebar h3 { font-size: 1.5em; /* border-top: 1px solid {{ theme_border }}; */ margin-top: 1em; margin-bottom: 0.5em; padding-top: 0.5em; } div.sphinxsidebar h4 { font-size: 1.2em; margin-bottom: 0; } div.sphinxsidebar h3, div.sphinxsidebar h4 { margin-right: -15px; margin-left: -15px; padding-right: 14px; padding-left: 14px; color: #333; font-weight: 300; /*text-shadow: 0px 0px 0.5px rgba(0, 0, 0, 0.4);*/ } div.sphinxsidebarwrapper > h3:first-child { margin-top: 0.5em; border: none; } div.sphinxsidebar h3 a { color: #333; } div.sphinxsidebar ul { color: #444; margin-top: 7px; padding: 0; line-height: 130%; } div.sphinxsidebar ul ul { margin-left: 20px; list-style-image: url(listitem.png); } div.footer { color: {{ theme_darkgray }}; text-shadow: 0 0 .2px rgba(255, 255, 255, 0.8); padding: 2em; text-align: center; clear: both; font-size: 0.8em; } /* -- body styles ----------------------------------------------------------- */ p { margin: 0.8em 0 0.5em 0; } a { color: {{ theme_darkgreen }}; text-decoration: none; } a:hover { color: {{ theme_darkyellow }}; } div.body a { text-decoration: underline; } h1 { margin: 10px 0 0 0; font-size: 2.4em; color: {{ theme_darkgray }}; font-weight: 300; } h2 { margin: 1.em 0 0.2em 0; font-size: 1.5em; font-weight: 300; padding: 0; color: {{ theme_darkgreen }}; } h3 { margin: 1em 0 -0.3em 0; font-size: 1.3em; font-weight: 300; } div.body h1 a, div.body h2 a, div.body h3 a, div.body h4 a, div.body h5 a, div.body h6 a { text-decoration: none; } div.body h1 a tt, div.body h2 a tt, div.body h3 a tt, div.body h4 a tt, div.body h5 a tt, div.body h6 a tt { color: {{ theme_darkgreen }} !important; font-size: inherit !important; } a.headerlink { color: {{ theme_green }} !important; font-size: 12px; margin-left: 6px; padding: 0 4px 0 4px; text-decoration: none !important; float: right; } a.headerlink:hover { background-color: #ccc; color: white!important; } cite, code, tt { font-family: 'Consolas', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 14px; letter-spacing: -0.02em; } tt { background-color: #f2f2f2; border: 1px solid #ddd; border-radius: 2px; color: #333; padding: 1px; } tt.descname, tt.descclassname, tt.xref { border: 0; } hr { border: 1px solid #abc; margin: 2em; } a tt { border: 0; color: {{ theme_darkgreen }}; } a tt:hover { color: {{ theme_darkyellow }}; } pre { font-family: 'Consolas', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 13px; letter-spacing: 0.015em; line-height: 120%; padding: 0.5em; border: 1px solid #ccc; border-radius: 2px; background-color: #f8f8f8; } pre a { color: inherit; text-decoration: underline; } td.linenos pre { padding: 0.5em 0; } div.quotebar { background-color: #f8f8f8; max-width: 250px; float: right; padding: 0px 7px; border: 1px solid #ccc; margin-left: 1em; } div.topic { background-color: #f8f8f8; } table { border-collapse: collapse; margin: 0 -0.5em 0 -0.5em; } table td, table th { padding: 0.2em 0.5em 0.2em 0.5em; } div.admonition, div.warning { font-size: 0.9em; margin: 1em 0 1em 0; border: 1px solid #86989B; border-radius: 2px; background-color: #f7f7f7; padding: 0; } div.admonition p, div.warning p { margin: 0.5em 1em 0.5em 1em; padding: 0; } div.admonition pre, div.warning pre { margin: 0.4em 1em 0.4em 1em; } div.admonition p.admonition-title, div.warning p.admonition-title { margin-top: 1em; padding-top: 0.5em; font-weight: bold; } div.warning { border: 1px solid #940000; /* background-color: #FFCCCF;*/ } div.warning p.admonition-title { } div.admonition ul, div.admonition ol, div.warning ul, div.warning ol { margin: 0.1em 0.5em 0.5em 3em; padding: 0; } .viewcode-back { font-family: {{ theme_font }}, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif; } div.viewcode-block:target { background-color: #f4debf; border-top: 1px solid #ac9; border-bottom: 1px solid #ac9; } pygments.rb-0.6.3/vendor/pygments-main/doc/_themes/pygments14/theme.conf000066400000000000000000000004011250413007300262200ustar00rootroot00000000000000[theme] inherit = basic stylesheet = pygments14.css pygments_style = friendly [options] green = #66b55e darkgreen = #36852e darkgray = #666666 border = #66b55e yellow = #f4cd00 darkyellow = #d4ad00 lightyellow = #fffbe3 background = #f9f9f9 font = PT Sans pygments.rb-0.6.3/vendor/pygments-main/doc/conf.py000066400000000000000000000176021250413007300221220ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Pygments documentation build configuration file, created by # sphinx-quickstart on Sat Jan 18 17:07:37 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) import pygments # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'pygments.sphinxext'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Pygments' copyright = u'2014, Georg Brandl' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = pygments.__version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. #pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'pygments14' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = {'index': 'indexsidebar.html', 'docs/*': 'docssidebar.html'} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Pygmentsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Pygments.tex', u'Pygments Documentation', u'Georg Brandl', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pygments', u'Pygments Documentation', [u'Georg Brandl'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Pygments', u'Pygments Documentation', u'Georg Brandl', 'Pygments', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. #intersphinx_mapping = {'http://docs.python.org/': None} pygments.rb-0.6.3/vendor/pygments-main/doc/docs/000077500000000000000000000000001250413007300215455ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/doc/docs/api.rst000066400000000000000000000241571250413007300230610ustar00rootroot00000000000000.. -*- mode: rst -*- ===================== The full Pygments API ===================== This page describes the Pygments API. High-level API ============== .. module:: pygments Functions from the :mod:`pygments` module: .. function:: lex(code, lexer) Lex `code` with the `lexer` (must be a `Lexer` instance) and return an iterable of tokens. Currently, this only calls `lexer.get_tokens()`. .. function:: format(tokens, formatter, outfile=None) Format a token stream (iterable of tokens) `tokens` with the `formatter` (must be a `Formatter` instance). The result is written to `outfile`, or if that is ``None``, returned as a string. .. function:: highlight(code, lexer, formatter, outfile=None) This is the most high-level highlighting function. It combines `lex` and `format` in one function. .. module:: pygments.lexers Functions from :mod:`pygments.lexers`: .. function:: get_lexer_by_name(alias, **options) Return an instance of a `Lexer` subclass that has `alias` in its aliases list. The lexer is given the `options` at its instantiation. Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is found. .. function:: get_lexer_for_filename(fn, **options) Return a `Lexer` subclass instance that has a filename pattern matching `fn`. The lexer is given the `options` at its instantiation. Will raise :exc:`pygments.util.ClassNotFound` if no lexer for that filename is found. .. function:: get_lexer_for_mimetype(mime, **options) Return a `Lexer` subclass instance that has `mime` in its mimetype list. The lexer is given the `options` at its instantiation. Will raise :exc:`pygments.util.ClassNotFound` if not lexer for that mimetype is found. .. function:: guess_lexer(text, **options) Return a `Lexer` subclass instance that's guessed from the text in `text`. For that, the :meth:`.analyse_text()` method of every known lexer class is called with the text as argument, and the lexer which returned the highest value will be instantiated and returned. :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can handle the content. .. function:: guess_lexer_for_filename(filename, text, **options) As :func:`guess_lexer()`, but only lexers which have a pattern in `filenames` or `alias_filenames` that matches `filename` are taken into consideration. :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can handle the content. .. function:: get_all_lexers() Return an iterable over all registered lexers, yielding tuples in the format:: (longname, tuple of aliases, tuple of filename patterns, tuple of mimetypes) .. versionadded:: 0.6 .. module:: pygments.formatters Functions from :mod:`pygments.formatters`: .. function:: get_formatter_by_name(alias, **options) Return an instance of a :class:`.Formatter` subclass that has `alias` in its aliases list. The formatter is given the `options` at its instantiation. Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that alias is found. .. function:: get_formatter_for_filename(fn, **options) Return a :class:`.Formatter` subclass instance that has a filename pattern matching `fn`. The formatter is given the `options` at its instantiation. Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename is found. .. module:: pygments.styles Functions from :mod:`pygments.styles`: .. function:: get_style_by_name(name) Return a style class by its short name. The names of the builtin styles are listed in :data:`pygments.styles.STYLE_MAP`. Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is found. .. function:: get_all_styles() Return an iterable over all registered styles, yielding their names. .. versionadded:: 0.6 .. module:: pygments.lexer Lexers ====== The base lexer class from which all lexers are derived is: .. class:: Lexer(**options) The constructor takes a \*\*keywords dictionary of options. Every subclass must first process its own options and then call the `Lexer` constructor, since it processes the `stripnl`, `stripall` and `tabsize` options. An example looks like this: .. sourcecode:: python def __init__(self, **options): self.compress = options.get('compress', '') Lexer.__init__(self, **options) As these options must all be specifiable as strings (due to the command line usage), there are various utility functions available to help with that, see `Option processing`_. .. method:: get_tokens(text) This method is the basic interface of a lexer. It is called by the `highlight()` function. It must process the text and return an iterable of ``(tokentype, value)`` pairs from `text`. Normally, you don't need to override this method. The default implementation processes the `stripnl`, `stripall` and `tabsize` options and then yields all tokens from `get_tokens_unprocessed()`, with the ``index`` dropped. .. method:: get_tokens_unprocessed(text) This method should process the text and return an iterable of ``(index, tokentype, value)`` tuples where ``index`` is the starting position of the token within the input text. This method must be overridden by subclasses. .. staticmethod:: analyse_text(text) A static method which is called for lexer guessing. It should analyse the text and return a float in the range from ``0.0`` to ``1.0``. If it returns ``0.0``, the lexer will not be selected as the most probable one, if it returns ``1.0``, it will be selected immediately. .. note:: You don't have to add ``@staticmethod`` to the definition of this method, this will be taken care of by the Lexer's metaclass. For a list of known tokens have a look at the :doc:`tokens` page. A lexer also can have the following attributes (in fact, they are mandatory except `alias_filenames`) that are used by the builtin lookup mechanism. .. attribute:: name Full name for the lexer, in human-readable form. .. attribute:: aliases A list of short, unique identifiers that can be used to lookup the lexer from a list, e.g. using `get_lexer_by_name()`. .. attribute:: filenames A list of `fnmatch` patterns that match filenames which contain content for this lexer. The patterns in this list should be unique among all lexers. .. attribute:: alias_filenames A list of `fnmatch` patterns that match filenames which may or may not contain content for this lexer. This list is used by the :func:`.guess_lexer_for_filename()` function, to determine which lexers are then included in guessing the correct one. That means that e.g. every lexer for HTML and a template language should include ``\*.html`` in this list. .. attribute:: mimetypes A list of MIME types for content that can be lexed with this lexer. .. module:: pygments.formatter Formatters ========== A formatter is derived from this class: .. class:: Formatter(**options) As with lexers, this constructor processes options and then must call the base class :meth:`__init__`. The :class:`Formatter` class recognizes the options `style`, `full` and `title`. It is up to the formatter class whether it uses them. .. method:: get_style_defs(arg='') This method must return statements or declarations suitable to define the current style for subsequent highlighted text (e.g. CSS classes in the `HTMLFormatter`). The optional argument `arg` can be used to modify the generation and is formatter dependent (it is standardized because it can be given on the command line). This method is called by the ``-S`` :doc:`command-line option `, the `arg` is then given by the ``-a`` option. .. method:: format(tokensource, outfile) This method must format the tokens from the `tokensource` iterable and write the formatted version to the file object `outfile`. Formatter options can control how exactly the tokens are converted. .. versionadded:: 0.7 A formatter must have the following attributes that are used by the builtin lookup mechanism. .. attribute:: name Full name for the formatter, in human-readable form. .. attribute:: aliases A list of short, unique identifiers that can be used to lookup the formatter from a list, e.g. using :func:`.get_formatter_by_name()`. .. attribute:: filenames A list of :mod:`fnmatch` patterns that match filenames for which this formatter can produce output. The patterns in this list should be unique among all formatters. .. module:: pygments.util Option processing ================= The :mod:`pygments.util` module has some utility functions usable for option processing: .. exception:: OptionError This exception will be raised by all option processing functions if the type or value of the argument is not correct. .. function:: get_bool_opt(options, optname, default=None) Interpret the key `optname` from the dictionary `options` as a boolean and return it. Return `default` if `optname` is not in `options`. The valid string values for ``True`` are ``1``, ``yes``, ``true`` and ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off`` (matched case-insensitively). .. function:: get_int_opt(options, optname, default=None) As :func:`get_bool_opt`, but interpret the value as an integer. .. function:: get_list_opt(options, optname, default=None) If the key `optname` from the dictionary `options` is a string, split it at whitespace and return it. If it is already a list or a tuple, it is returned as a list. .. function:: get_choice_opt(options, optname, allowed, default=None) If the key `optname` from the dictionary is not in the sequence `allowed`, raise an error, otherwise return it. .. versionadded:: 0.8 pygments.rb-0.6.3/vendor/pygments-main/doc/docs/authors.rst000066400000000000000000000001101250413007300237540ustar00rootroot00000000000000Full contributor list ===================== .. include:: ../../AUTHORS pygments.rb-0.6.3/vendor/pygments-main/doc/docs/changelog.rst000066400000000000000000000000331250413007300242220ustar00rootroot00000000000000.. include:: ../../CHANGES pygments.rb-0.6.3/vendor/pygments-main/doc/docs/cmdline.rst000066400000000000000000000114121250413007300237110ustar00rootroot00000000000000.. -*- mode: rst -*- ====================== Command Line Interface ====================== You can use Pygments from the shell, provided you installed the :program:`pygmentize` script:: $ pygmentize test.py print "Hello World" will print the file test.py to standard output, using the Python lexer (inferred from the file name extension) and the terminal formatter (because you didn't give an explicit formatter name). If you want HTML output:: $ pygmentize -f html -l python -o test.html test.py As you can see, the -l option explicitly selects a lexer. As seen above, if you give an input file name and it has an extension that Pygments recognizes, you can omit this option. The ``-o`` option gives an output file name. If it is not given, output is written to stdout. The ``-f`` option selects a formatter (as with ``-l``, it can also be omitted if an output file name is given and has a supported extension). If no output file name is given and ``-f`` is omitted, the :class:`.TerminalFormatter` is used. The above command could therefore also be given as:: $ pygmentize -o test.html test.py To create a full HTML document, including line numbers and stylesheet (using the "emacs" style), highlighting the Python file ``test.py`` to ``test.html``:: $ pygmentize -O full,style=emacs -o test.html test.py Options and filters ------------------- Lexer and formatter options can be given using the ``-O`` option:: $ pygmentize -f html -O style=colorful,linenos=1 -l python test.py Be sure to enclose the option string in quotes if it contains any special shell characters, such as spaces or expansion wildcards like ``*``. If an option expects a list value, separate the list entries with spaces (you'll have to quote the option value in this case too, so that the shell doesn't split it). Since the ``-O`` option argument is split at commas and expects the split values to be of the form ``name=value``, you can't give an option value that contains commas or equals signs. Therefore, an option ``-P`` is provided (as of Pygments 0.9) that works like ``-O`` but can only pass one option per ``-P``. Its value can then contain all characters:: $ pygmentize -P "heading=Pygments, the Python highlighter" ... Filters are added to the token stream using the ``-F`` option:: $ pygmentize -f html -l pascal -F keywordcase:case=upper main.pas As you see, options for the filter are given after a colon. As for ``-O``, the filter name and options must be one shell word, so there may not be any spaces around the colon. Generating styles ----------------- Formatters normally don't output full style information. For example, the HTML formatter by default only outputs ```` tags with ``class`` attributes. Therefore, there's a special ``-S`` option for generating style definitions. Usage is as follows:: $ pygmentize -f html -S colorful -a .syntax generates a CSS style sheet (because you selected the HTML formatter) for the "colorful" style prepending a ".syntax" selector to all style rules. For an explanation what ``-a`` means for :doc:`a particular formatter `, look for the `arg` argument for the formatter's :meth:`.get_style_defs()` method. Getting lexer names ------------------- .. versionadded:: 1.0 The ``-N`` option guesses a lexer name for a given filename, so that :: $ pygmentize -N setup.py will print out ``python``. It won't highlight anything yet. If no specific lexer is known for that filename, ``text`` is printed. Getting help ------------ The ``-L`` option lists lexers, formatters, along with their short names and supported file name extensions, styles and filters. If you want to see only one category, give it as an argument:: $ pygmentize -L filters will list only all installed filters. The ``-H`` option will give you detailed information (the same that can be found in this documentation) about a lexer, formatter or filter. Usage is as follows:: $ pygmentize -H formatter html will print the help for the HTML formatter, while :: $ pygmentize -H lexer python will print the help for the Python lexer, etc. A note on encodings ------------------- .. versionadded:: 0.9 Pygments tries to be smart regarding encodings in the formatting process: * If you give an ``encoding`` option, it will be used as the input and output encoding. * If you give an ``outencoding`` option, it will override ``encoding`` as the output encoding. * If you don't give an encoding and have given an output file, the default encoding for lexer and formatter is ``latin1`` (which will pass through all non-ASCII characters). * If you don't give an encoding and haven't given an output file (that means output is written to the console), the default encoding for lexer and formatter is the terminal encoding (``sys.stdout.encoding``). pygments.rb-0.6.3/vendor/pygments-main/doc/docs/filterdevelopment.rst000066400000000000000000000043521250413007300260330ustar00rootroot00000000000000.. -*- mode: rst -*- ===================== Write your own filter ===================== .. versionadded:: 0.7 Writing own filters is very easy. All you have to do is to subclass the `Filter` class and override the `filter` method. Additionally a filter is instanciated with some keyword arguments you can use to adjust the behavior of your filter. Subclassing Filters =================== As an example, we write a filter that converts all `Name.Function` tokens to normal `Name` tokens to make the output less colorful. .. sourcecode:: python from pygments.util import get_bool_opt from pygments.token import Name from pygments.filter import Filter class UncolorFilter(Filter): def __init__(self, **options): Filter.__init__(self, **options) self.class_too = get_bool_opt(options, 'classtoo') def filter(self, lexer, stream): for ttype, value in stream: if ttype is Name.Function or (self.class_too and ttype is Name.Class): ttype = Name yield ttype, value Some notes on the `lexer` argument: that can be quite confusing since it doesn't need to be a lexer instance. If a filter was added by using the `add_filter()` function of lexers, that lexer is registered for the filter. In that case `lexer` will refer to the lexer that has registered the filter. It *can* be used to access options passed to a lexer. Because it could be `None` you always have to check for that case if you access it. Using a decorator ================= You can also use the `simplefilter` decorator from the `pygments.filter` module: .. sourcecode:: python from pygments.util import get_bool_opt from pygments.token import Name from pygments.filter import simplefilter @simplefilter def uncolor(lexer, stream, options): class_too = get_bool_opt(options, 'classtoo') for ttype, value in stream: if ttype is Name.Function or (class_too and ttype is Name.Class): ttype = Name yield ttype, value The decorator automatically subclasses an internal filter class and uses the decorated function for filtering. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/filters.rst000066400000000000000000000022761250413007300237560ustar00rootroot00000000000000.. -*- mode: rst -*- ======= Filters ======= .. versionadded:: 0.7 You can filter token streams coming from lexers to improve or annotate the output. For example, you can highlight special words in comments, convert keywords to upper or lowercase to enforce a style guide etc. To apply a filter, you can use the `add_filter()` method of a lexer: .. sourcecode:: pycon >>> from pygments.lexers import PythonLexer >>> l = PythonLexer() >>> # add a filter given by a string and options >>> l.add_filter('codetagify', case='lower') >>> l.filters [] >>> from pygments.filters import KeywordCaseFilter >>> # or give an instance >>> l.add_filter(KeywordCaseFilter(case='lower')) The `add_filter()` method takes keyword arguments which are forwarded to the constructor of the filter. To get a list of all registered filters by name, you can use the `get_all_filters()` function from the `pygments.filters` module that returns an iterable for all known filters. If you want to write your own filter, have a look at :doc:`Write your own filter `. Builtin Filters =============== .. pygmentsdoc:: filters pygments.rb-0.6.3/vendor/pygments-main/doc/docs/formatterdevelopment.rst000066400000000000000000000140471250413007300265530ustar00rootroot00000000000000.. -*- mode: rst -*- ======================== Write your own formatter ======================== As well as creating :doc:`your own lexer `, writing a new formatter for Pygments is easy and straightforward. A formatter is a class that is initialized with some keyword arguments (the formatter options) and that must provides a `format()` method. Additionally a formatter should provide a `get_style_defs()` method that returns the style definitions from the style in a form usable for the formatter's output format. Quickstart ========== The most basic formatter shipped with Pygments is the `NullFormatter`. It just sends the value of a token to the output stream: .. sourcecode:: python from pygments.formatter import Formatter class NullFormatter(Formatter): def format(self, tokensource, outfile): for ttype, value in tokensource: outfile.write(value) As you can see, the `format()` method is passed two parameters: `tokensource` and `outfile`. The first is an iterable of ``(token_type, value)`` tuples, the latter a file like object with a `write()` method. Because the formatter is that basic it doesn't overwrite the `get_style_defs()` method. Styles ====== Styles aren't instantiated but their metaclass provides some class functions so that you can access the style definitions easily. Styles are iterable and yield tuples in the form ``(ttype, d)`` where `ttype` is a token and `d` is a dict with the following keys: ``'color'`` Hexadecimal color value (eg: ``'ff0000'`` for red) or `None` if not defined. ``'bold'`` `True` if the value should be bold ``'italic'`` `True` if the value should be italic ``'underline'`` `True` if the value should be underlined ``'bgcolor'`` Hexadecimal color value for the background (eg: ``'eeeeeee'`` for light gray) or `None` if not defined. ``'border'`` Hexadecimal color value for the border (eg: ``'0000aa'`` for a dark blue) or `None` for no border. Additional keys might appear in the future, formatters should ignore all keys they don't support. HTML 3.2 Formatter ================== For an more complex example, let's implement a HTML 3.2 Formatter. We don't use CSS but inline markup (````, ````, etc). Because this isn't good style this formatter isn't in the standard library ;-) .. sourcecode:: python from pygments.formatter import Formatter class OldHtmlFormatter(Formatter): def __init__(self, **options): Formatter.__init__(self, **options) # create a dict of (start, end) tuples that wrap the # value of a token so that we can use it in the format # method later self.styles = {} # we iterate over the `_styles` attribute of a style item # that contains the parsed style values. for token, style in self.style: start = end = '' # a style item is a tuple in the following form: # colors are readily specified in hex: 'RRGGBB' if style['color']: start += '' % style['color'] end = '' + end if style['bold']: start += '' end = '' + end if style['italic']: start += '' end = '' + end if style['underline']: start += '' end = '' + end self.styles[token] = (start, end) def format(self, tokensource, outfile): # lastval is a string we use for caching # because it's possible that an lexer yields a number # of consecutive tokens with the same token type. # to minimize the size of the generated html markup we # try to join the values of same-type tokens here lastval = '' lasttype = None # wrap the whole output with
            outfile.write('
')

            for ttype, value in tokensource:
                # if the token type doesn't exist in the stylemap
                # we try it with the parent of the token type
                # eg: parent of Token.Literal.String.Double is
                # Token.Literal.String
                while ttype not in self.styles:
                    ttype = ttype.parent
                if ttype == lasttype:
                    # the current token type is the same of the last
                    # iteration. cache it
                    lastval += value
                else:
                    # not the same token as last iteration, but we
                    # have some data in the buffer. wrap it with the
                    # defined style and write it to the output file
                    if lastval:
                        stylebegin, styleend = self.styles[lasttype]
                        outfile.write(stylebegin + lastval + styleend)
                    # set lastval/lasttype to current values
                    lastval = value
                    lasttype = ttype

            # if something is left in the buffer, write it to the
            # output file, then close the opened 
 tag
            if lastval:
                stylebegin, styleend = self.styles[lasttype]
                outfile.write(stylebegin + lastval + styleend)
            outfile.write('
\n') The comments should explain it. Again, this formatter doesn't override the `get_style_defs()` method. If we would have used CSS classes instead of inline HTML markup, we would need to generate the CSS first. For that purpose the `get_style_defs()` method exists: Generating Style Definitions ============================ Some formatters like the `LatexFormatter` and the `HtmlFormatter` don't output inline markup but reference either macros or css classes. Because the definitions of those are not part of the output, the `get_style_defs()` method exists. It is passed one parameter (if it's used and how it's used is up to the formatter) and has to return a string or ``None``. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/formatters.rst000066400000000000000000000031201250413007300244610ustar00rootroot00000000000000.. -*- mode: rst -*- ==================== Available formatters ==================== This page lists all builtin formatters. Common options ============== All formatters support these options: `encoding` If given, must be an encoding name (such as ``"utf-8"``). This will be used to convert the token strings (which are Unicode strings) to byte strings in the output (default: ``None``). It will also be written in an encoding declaration suitable for the document format if the `full` option is given (e.g. a ``meta content-type`` directive in HTML or an invocation of the `inputenc` package in LaTeX). If this is ``""`` or ``None``, Unicode strings will be written to the output file, which most file-like objects do not support. For example, `pygments.highlight()` will return a Unicode string if called with no `outfile` argument and a formatter that has `encoding` set to ``None`` because it uses a `StringIO.StringIO` object that supports Unicode arguments to `write()`. Using a regular file object wouldn't work. .. versionadded:: 0.6 `outencoding` When using Pygments from the command line, any `encoding` option given is passed to the lexer and the formatter. This is sometimes not desirable, for example if you want to set the input encoding to ``"guess"``. Therefore, `outencoding` has been introduced which overrides `encoding` for the formatter if given. .. versionadded:: 0.7 Formatter classes ================= All these classes are importable from :mod:`pygments.formatters`. .. pygmentsdoc:: formatters pygments.rb-0.6.3/vendor/pygments-main/doc/docs/index.rst000066400000000000000000000015741250413007300234150ustar00rootroot00000000000000Pygments documentation ====================== **Starting with Pygments** .. toctree:: :maxdepth: 1 ../download quickstart cmdline **Builtin components** .. toctree:: :maxdepth: 1 lexers filters formatters styles **Reference** .. toctree:: :maxdepth: 1 unicode tokens api **Hacking for Pygments** .. toctree:: :maxdepth: 1 lexerdevelopment formatterdevelopment filterdevelopment plugins **Hints and tricks** .. toctree:: :maxdepth: 1 rstdirective moinmoin java integrate **About Pygments** .. toctree:: :maxdepth: 1 changelog authors If you find bugs or have suggestions for the documentation, please look :ref:`here ` for info on how to contact the team. .. XXX You can download an offline version of this documentation from the :doc:`download page `. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/integrate.rst000066400000000000000000000023071250413007300242630ustar00rootroot00000000000000.. -*- mode: rst -*- =================================== Using Pygments in various scenarios =================================== PyGtk ----- Armin has written a piece of sample code that shows how to create a Gtk `TextBuffer` object containing Pygments-highlighted text. See the article here: http://lucumr.pocoo.org/cogitations/2007/05/30/pygments-gtk-rendering/ Wordpress --------- He also has a snippet that shows how to use Pygments in WordPress: http://lucumr.pocoo.org/cogitations/2007/05/30/pygments-in-wordpress/ Markdown -------- Since Pygments 0.9, the distribution ships Markdown_ preprocessor sample code that uses Pygments to render source code in :file:`external/markdown-processor.py`. You can copy and adapt it to your liking. .. _Markdown: http://www.freewisdom.org/projects/python-markdown/ TextMate -------- Antonio Cangiano has created a Pygments bundle for TextMate that allows to colorize code via a simple menu option. It can be found here_. .. _here: http://antoniocangiano.com/2008/10/28/pygments-textmate-bundle/ Bash completion --------------- The source distribution contains a file ``external/pygments.bashcomp`` that sets up completion for the ``pygmentize`` command in bash. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/java.rst000066400000000000000000000044421250413007300232240ustar00rootroot00000000000000===================== Use Pygments in Java ===================== Thanks to `Jython `__ it is possible to use Pygments in Java. This page is a simple tutorial to get an idea of how this is working. You can then look at the `Jython documentation `__ for more advanced use. Since version 1.5, Pygments is deployed on `Maven Central `__ as a JAR so is Jython which makes it a lot easier to create the Java project. Here is an example of a `Maven `__ ``pom.xml`` file for a project running Pygments: .. sourcecode:: xml 4.0.0 example example 1.0-SNAPSHOT org.python jython-standalone 2.5.3 org.pygments pygments 1.5 runtime The following Java example: .. sourcecode:: java PythonInterpreter interpreter = new PythonInterpreter(); // Set a variable with the content you want to work with interpreter.set("code", code); // Simple use Pygments as you would in Python interpreter.exec("from pygments import highlight\n" + "from pygments.lexers import PythonLexer\n" + "from pygments.formatters import HtmlFormatter\n" + "\nresult = highlight(code, PythonLexer(), HtmlFormatter())"); // Get the result that has been set in a variable System.out.println(interpreter.get("result", String.class)); will print something like: .. sourcecode:: html
print "Hello World"
pygments.rb-0.6.3/vendor/pygments-main/doc/docs/lexerdevelopment.rst000066400000000000000000000546161250413007300256750ustar00rootroot00000000000000.. -*- mode: rst -*- ==================== Write your own lexer ==================== If a lexer for your favorite language is missing in the Pygments package, you can easily write your own and extend Pygments. All you need can be found inside the :mod:`pygments.lexer` module. As you can read in the :doc:`API documentation `, a lexer is a class that is initialized with some keyword arguments (the lexer options) and that provides a :meth:`.get_tokens_unprocessed()` method which is given a string or unicode object with the data to parse. The :meth:`.get_tokens_unprocessed()` method must return an iterator or iterable containing tuples in the form ``(index, token, value)``. Normally you don't need to do this since there are numerous base lexers you can subclass. RegexLexer ========== A very powerful (but quite easy to use) lexer is the :class:`RegexLexer`. This lexer base class allows you to define lexing rules in terms of *regular expressions* for different *states*. States are groups of regular expressions that are matched against the input string at the *current position*. If one of these expressions matches, a corresponding action is performed (normally yielding a token with a specific type), the current position is set to where the last match ended and the matching process continues with the first regex of the current state. Lexer states are kept in a state stack: each time a new state is entered, the new state is pushed onto the stack. The most basic lexers (like the `DiffLexer`) just need one state. Each state is defined as a list of tuples in the form (`regex`, `action`, `new_state`) where the last item is optional. In the most basic form, `action` is a token type (like `Name.Builtin`). That means: When `regex` matches, emit a token with the match text and type `tokentype` and push `new_state` on the state stack. If the new state is ``'#pop'``, the topmost state is popped from the stack instead. (To pop more than one state, use ``'#pop:2'`` and so on.) ``'#push'`` is a synonym for pushing the current state on the stack. The following example shows the `DiffLexer` from the builtin lexers. Note that it contains some additional attributes `name`, `aliases` and `filenames` which aren't required for a lexer. They are used by the builtin lexer lookup functions. .. sourcecode:: python from pygments.lexer import RegexLexer from pygments.token import * class DiffLexer(RegexLexer): name = 'Diff' aliases = ['diff'] filenames = ['*.diff'] tokens = { 'root': [ (r' .*\n', Text), (r'\+.*\n', Generic.Inserted), (r'-.*\n', Generic.Deleted), (r'@.*\n', Generic.Subheading), (r'Index.*\n', Generic.Heading), (r'=.*\n', Generic.Heading), (r'.*\n', Text), ] } As you can see this lexer only uses one state. When the lexer starts scanning the text, it first checks if the current character is a space. If this is true it scans everything until newline and returns the parsed data as `Text` token. If this rule doesn't match, it checks if the current char is a plus sign. And so on. If no rule matches at the current position, the current char is emitted as an `Error` token that indicates a parsing error, and the position is increased by 1. Adding and testing a new lexer ============================== To make pygments aware of your new lexer, you have to perform the following steps: First, change to the current directory containing the pygments source code: .. sourcecode:: console $ cd .../pygments-main Next, make sure the lexer is known from outside of the module. All modules in the ``pygments.lexers`` specify ``__all__``. For example, ``other.py`` sets: .. sourcecode:: python __all__ = ['BrainfuckLexer', 'BefungeLexer', ...] Simply add the name of your lexer class to this list. Finally the lexer can be made publically known by rebuilding the lexer mapping: .. sourcecode:: console $ make mapfiles To test the new lexer, store an example file with the proper extension in ``tests/examplefiles``. For example, to test your ``DiffLexer``, add a ``tests/examplefiles/example.diff`` containing a sample diff output. Now you can use pygmentize to render your example to HTML: .. sourcecode:: console $ ./pygmentize -O full -f html -o /tmp/example.html tests/examplefiles/example.diff Note that this explicitely calls the ``pygmentize`` in the current directory by preceding it with ``./``. This ensures your modifications are used. Otherwise a possibly already installed, unmodified version without your new lexer would have been called from the system search path (``$PATH``). To view the result, open ``/tmp/example.html`` in your browser. Once the example renders as expected, you should run the complete test suite: .. sourcecode:: console $ make test Regex Flags =========== You can either define regex flags in the regex (``r'(?x)foo bar'``) or by adding a `flags` attribute to your lexer class. If no attribute is defined, it defaults to `re.MULTILINE`. For more informations about regular expression flags see the `regular expressions`_ help page in the python documentation. .. _regular expressions: http://docs.python.org/lib/re-syntax.html Scanning multiple tokens at once ================================ Here is a more complex lexer that highlights INI files. INI files consist of sections, comments and key = value pairs: .. sourcecode:: python from pygments.lexer import RegexLexer, bygroups from pygments.token import * class IniLexer(RegexLexer): name = 'INI' aliases = ['ini', 'cfg'] filenames = ['*.ini', '*.cfg'] tokens = { 'root': [ (r'\s+', Text), (r';.*?$', Comment), (r'\[.*?\]$', Keyword), (r'(.*?)(\s*)(=)(\s*)(.*?)$', bygroups(Name.Attribute, Text, Operator, Text, String)) ] } The lexer first looks for whitespace, comments and section names. And later it looks for a line that looks like a key, value pair, separated by an ``'='`` sign, and optional whitespace. The `bygroups` helper makes sure that each group is yielded with a different token type. First the `Name.Attribute` token, then a `Text` token for the optional whitespace, after that a `Operator` token for the equals sign. Then a `Text` token for the whitespace again. The rest of the line is returned as `String`. Note that for this to work, every part of the match must be inside a capturing group (a ``(...)``), and there must not be any nested capturing groups. If you nevertheless need a group, use a non-capturing group defined using this syntax: ``r'(?:some|words|here)'`` (note the ``?:`` after the beginning parenthesis). If you find yourself needing a capturing group inside the regex which shouldn't be part of the output but is used in the regular expressions for backreferencing (eg: ``r'(<(foo|bar)>)(.*?)()'``), you can pass `None` to the bygroups function and it will skip that group will be skipped in the output. Changing states =============== Many lexers need multiple states to work as expected. For example, some languages allow multiline comments to be nested. Since this is a recursive pattern it's impossible to lex just using regular expressions. Here is the solution: .. sourcecode:: python from pygments.lexer import RegexLexer from pygments.token import * class ExampleLexer(RegexLexer): name = 'Example Lexer with states' tokens = { 'root': [ (r'[^/]+', Text), (r'/\*', Comment.Multiline, 'comment'), (r'//.*?$', Comment.Singleline), (r'/', Text) ], 'comment': [ (r'[^*/]', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ] } This lexer starts lexing in the ``'root'`` state. It tries to match as much as possible until it finds a slash (``'/'``). If the next character after the slash is a star (``'*'``) the `RegexLexer` sends those two characters to the output stream marked as `Comment.Multiline` and continues parsing with the rules defined in the ``'comment'`` state. If there wasn't a star after the slash, the `RegexLexer` checks if it's a singleline comment (eg: followed by a second slash). If this also wasn't the case it must be a single slash (the separate regex for a single slash must also be given, else the slash would be marked as an error token). Inside the ``'comment'`` state, we do the same thing again. Scan until the lexer finds a star or slash. If it's the opening of a multiline comment, push the ``'comment'`` state on the stack and continue scanning, again in the ``'comment'`` state. Else, check if it's the end of the multiline comment. If yes, pop one state from the stack. Note: If you pop from an empty stack you'll get an `IndexError`. (There is an easy way to prevent this from happening: don't ``'#pop'`` in the root state). If the `RegexLexer` encounters a newline that is flagged as an error token, the stack is emptied and the lexer continues scanning in the ``'root'`` state. This helps producing error-tolerant highlighting for erroneous input, e.g. when a single-line string is not closed. Advanced state tricks ===================== There are a few more things you can do with states: - You can push multiple states onto the stack if you give a tuple instead of a simple string as the third item in a rule tuple. For example, if you want to match a comment containing a directive, something like:: /* rest of comment */ you can use this rule: .. sourcecode:: python tokens = { 'root': [ (r'/\* <', Comment, ('comment', 'directive')), ... ], 'directive': [ (r'[^>]*', Comment.Directive), (r'>', Comment, '#pop'), ], 'comment': [ (r'[^*]+', Comment), (r'\*/', Comment, '#pop'), (r'\*', Comment), ] } When this encounters the above sample, first ``'comment'`` and ``'directive'`` are pushed onto the stack, then the lexer continues in the directive state until it finds the closing ``>``, then it continues in the comment state until the closing ``*/``. Then, both states are popped from the stack again and lexing continues in the root state. .. versionadded:: 0.9 The tuple can contain the special ``'#push'`` and ``'#pop'`` (but not ``'#pop:n'``) directives. - You can include the rules of a state in the definition of another. This is done by using `include` from `pygments.lexer`: .. sourcecode:: python from pygments.lexer import RegexLexer, bygroups, include from pygments.token import * class ExampleLexer(RegexLexer): tokens = { 'comments': [ (r'/\*.*?\*/', Comment), (r'//.*?\n', Comment), ], 'root': [ include('comments'), (r'(function )(\w+)( {)', bygroups(Keyword, Name, Keyword), 'function'), (r'.', Text), ], 'function': [ (r'[^}/]+', Text), include('comments'), (r'/', Text), (r'}', Keyword, '#pop'), ] } This is a hypothetical lexer for a language that consist of functions and comments. Because comments can occur at toplevel and in functions, we need rules for comments in both states. As you can see, the `include` helper saves repeating rules that occur more than once (in this example, the state ``'comment'`` will never be entered by the lexer, as it's only there to be included in ``'root'`` and ``'function'``). - Sometimes, you may want to "combine" a state from existing ones. This is possible with the `combine` helper from `pygments.lexer`. If you, instead of a new state, write ``combined('state1', 'state2')`` as the third item of a rule tuple, a new anonymous state will be formed from state1 and state2 and if the rule matches, the lexer will enter this state. This is not used very often, but can be helpful in some cases, such as the `PythonLexer`'s string literal processing. - If you want your lexer to start lexing in a different state you can modify the stack by overloading the `get_tokens_unprocessed()` method: .. sourcecode:: python from pygments.lexer import RegexLexer class MyLexer(RegexLexer): tokens = {...} def get_tokens_unprocessed(self, text): stack = ['root', 'otherstate'] for item in RegexLexer.get_tokens_unprocessed(text, stack): yield item Some lexers like the `PhpLexer` use this to make the leading ``', Name.Tag), ], 'script-content': [ (r'(.+?)(<\s*/\s*script\s*>)', bygroups(using(JavascriptLexer), Name.Tag), '#pop'), ] } Here the content of a ```` end tag is processed by the `JavascriptLexer`, while the end tag is yielded as a normal token with the `Name.Tag` type. As an additional goodie, if the lexer class is replaced by `this` (imported from `pygments.lexer`), the "other" lexer will be the current one (because you cannot refer to the current class within the code that runs at class definition time). Also note the ``(r'<\s*script\s*', Name.Tag, ('script-content', 'tag'))`` rule. Here, two states are pushed onto the state stack, ``'script-content'`` and ``'tag'``. That means that first ``'tag'`` is processed, which will parse attributes and the closing ``>``, then the ``'tag'`` state is popped and the next state on top of the stack will be ``'script-content'``. The `using()` helper has a special keyword argument, `state`, which works as follows: if given, the lexer to use initially is not in the ``"root"`` state, but in the state given by this argument. This *only* works with a `RegexLexer`. Any other keywords arguments passed to `using()` are added to the keyword arguments used to create the lexer. Delegating Lexer ================ Another approach for nested lexers is the `DelegatingLexer` which is for example used for the template engine lexers. It takes two lexers as arguments on initialisation: a `root_lexer` and a `language_lexer`. The input is processed as follows: First, the whole text is lexed with the `language_lexer`. All tokens yielded with a type of ``Other`` are then concatenated and given to the `root_lexer`. The language tokens of the `language_lexer` are then inserted into the `root_lexer`'s token stream at the appropriate positions. .. sourcecode:: python from pygments.lexer import DelegatingLexer from pygments.lexers.web import HtmlLexer, PhpLexer class HtmlPhpLexer(DelegatingLexer): def __init__(self, **options): super(HtmlPhpLexer, self).__init__(HtmlLexer, PhpLexer, **options) This procedure ensures that e.g. HTML with template tags in it is highlighted correctly even if the template tags are put into HTML tags or attributes. If you want to change the needle token ``Other`` to something else, you can give the lexer another token type as the third parameter: .. sourcecode:: python DelegatingLexer.__init__(MyLexer, OtherLexer, Text, **options) Callbacks ========= Sometimes the grammar of a language is so complex that a lexer would be unable to parse it just by using regular expressions and stacks. For this, the `RegexLexer` allows callbacks to be given in rule tuples, instead of token types (`bygroups` and `using` are nothing else but preimplemented callbacks). The callback must be a function taking two arguments: * the lexer itself * the match object for the last matched rule The callback must then return an iterable of (or simply yield) ``(index, tokentype, value)`` tuples, which are then just passed through by `get_tokens_unprocessed()`. The ``index`` here is the position of the token in the input string, ``tokentype`` is the normal token type (like `Name.Builtin`), and ``value`` the associated part of the input string. You can see an example here: .. sourcecode:: python from pygments.lexer import RegexLexer from pygments.token import Generic class HypotheticLexer(RegexLexer): def headline_callback(lexer, match): equal_signs = match.group(1) text = match.group(2) yield match.start(), Generic.Headline, equal_signs + text + equal_signs tokens = { 'root': [ (r'(=+)(.*?)(\1)', headline_callback) ] } If the regex for the `headline_callback` matches, the function is called with the match object. Note that after the callback is done, processing continues normally, that is, after the end of the previous match. The callback has no possibility to influence the position. There are not really any simple examples for lexer callbacks, but you can see them in action e.g. in the `compiled.py`_ source code in the `CLexer` and `JavaLexer` classes. .. _compiled.py: http://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/compiled.py The ExtendedRegexLexer class ============================ The `RegexLexer`, even with callbacks, unfortunately isn't powerful enough for the funky syntax rules of some languages that will go unnamed, such as Ruby. But fear not; even then you don't have to abandon the regular expression approach. For Pygments has a subclass of `RegexLexer`, the `ExtendedRegexLexer`. All features known from RegexLexers are available here too, and the tokens are specified in exactly the same way, *except* for one detail: The `get_tokens_unprocessed()` method holds its internal state data not as local variables, but in an instance of the `pygments.lexer.LexerContext` class, and that instance is passed to callbacks as a third argument. This means that you can modify the lexer state in callbacks. The `LexerContext` class has the following members: * `text` -- the input text * `pos` -- the current starting position that is used for matching regexes * `stack` -- a list containing the state stack * `end` -- the maximum position to which regexes are matched, this defaults to the length of `text` Additionally, the `get_tokens_unprocessed()` method can be given a `LexerContext` instead of a string and will then process this context instead of creating a new one for the string argument. Note that because you can set the current position to anything in the callback, it won't be automatically be set by the caller after the callback is finished. For example, this is how the hypothetical lexer above would be written with the `ExtendedRegexLexer`: .. sourcecode:: python from pygments.lexer import ExtendedRegexLexer from pygments.token import Generic class ExHypotheticLexer(ExtendedRegexLexer): def headline_callback(lexer, match, ctx): equal_signs = match.group(1) text = match.group(2) yield match.start(), Generic.Headline, equal_signs + text + equal_signs ctx.pos = match.end() tokens = { 'root': [ (r'(=+)(.*?)(\1)', headline_callback) ] } This might sound confusing (and it can really be). But it is needed, and for an example look at the Ruby lexer in `agile.py`_. .. _agile.py: https://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/agile.py Filtering Token Streams ======================= Some languages ship a lot of builtin functions (for example PHP). The total amount of those functions differs from system to system because not everybody has every extension installed. In the case of PHP there are over 3000 builtin functions. That's an incredible huge amount of functions, much more than you can put into a regular expression. But because only `Name` tokens can be function names it's solvable by overriding the ``get_tokens_unprocessed()`` method. The following lexer subclasses the `PythonLexer` so that it highlights some additional names as pseudo keywords: .. sourcecode:: python from pygments.lexers.agile import PythonLexer from pygments.token import Name, Keyword class MyPythonLexer(PythonLexer): EXTRA_KEYWORDS = ['foo', 'bar', 'foobar', 'barfoo', 'spam', 'eggs'] def get_tokens_unprocessed(self, text): for index, token, value in PythonLexer.get_tokens_unprocessed(self, text): if token is Name and value in self.EXTRA_KEYWORDS: yield index, Keyword.Pseudo, value else: yield index, token, value The `PhpLexer` and `LuaLexer` use this method to resolve builtin functions. .. note:: Do not confuse this with the :doc:`filter ` system. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/lexers.rst000066400000000000000000000037671250413007300236160ustar00rootroot00000000000000.. -*- mode: rst -*- ================ Available lexers ================ This page lists all available builtin lexers and the options they take. Currently, **all lexers** support these options: `stripnl` Strip leading and trailing newlines from the input (default: ``True``) `stripall` Strip all leading and trailing whitespace from the input (default: ``False``). `ensurenl` Make sure that the input ends with a newline (default: ``True``). This is required for some lexers that consume input linewise. .. versionadded:: 1.3 `tabsize` If given and greater than 0, expand tabs in the input (default: ``0``). `encoding` If given, must be an encoding name (such as ``"utf-8"``). This encoding will be used to convert the input string to Unicode (if it is not already a Unicode string). The default is ``"latin1"``. If this option is set to ``"guess"``, a simple UTF-8 vs. Latin-1 detection is used, if it is set to ``"chardet"``, the `chardet library `__ is used to guess the encoding of the input. .. versionadded:: 0.6 The "Short Names" field lists the identifiers that can be used with the `get_lexer_by_name()` function. These lexers are builtin and can be imported from `pygments.lexers`: .. pygmentsdoc:: lexers Iterating over all lexers ------------------------- .. versionadded:: 0.6 To get all lexers (both the builtin and the plugin ones), you can use the `get_all_lexers()` function from the `pygments.lexers` module: .. sourcecode:: pycon >>> from pygments.lexers import get_all_lexers >>> i = get_all_lexers() >>> i.next() ('Diff', ('diff',), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')) >>> i.next() ('Delphi', ('delphi', 'objectpascal', 'pas', 'pascal'), ('*.pas',), ('text/x-pascal',)) >>> i.next() ('XML+Ruby', ('xml+erb', 'xml+ruby'), (), ()) As you can see, the return value is an iterator which yields tuples in the form ``(name, aliases, filetypes, mimetypes)``. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/moinmoin.rst000066400000000000000000000026701250413007300241310ustar00rootroot00000000000000.. -*- mode: rst -*- ============================ Using Pygments with MoinMoin ============================ From Pygments 0.7, the source distribution ships a `Moin`_ parser plugin that can be used to get Pygments highlighting in Moin wiki pages. To use it, copy the file `external/moin-parser.py` from the Pygments distribution to the `data/plugin/parser` subdirectory of your Moin instance. Edit the options at the top of the file (currently ``ATTACHMENTS`` and ``INLINESTYLES``) and rename the file to the name that the parser directive should have. For example, if you name the file ``code.py``, you can get a highlighted Python code sample with this Wiki markup:: {{{ #!code python [...] }}} where ``python`` is the Pygments name of the lexer to use. Additionally, if you set the ``ATTACHMENTS`` option to True, Pygments will also be called for all attachments for whose filenames there is no other parser registered. You are responsible for including CSS rules that will map the Pygments CSS classes to colors. You can output a stylesheet file with `pygmentize`, put it into the `htdocs` directory of your Moin instance and then include it in the `stylesheets` configuration option in the Moin config, e.g.:: stylesheets = [('screen', '/htdocs/pygments.css')] If you do not want to do that and are willing to accept larger HTML output, you can set the ``INLINESTYLES`` option to True. .. _Moin: http://moinmoin.wikiwikiweb.de/ pygments.rb-0.6.3/vendor/pygments-main/doc/docs/plugins.rst000066400000000000000000000050251250413007300237620ustar00rootroot00000000000000================ Register Plugins ================ If you want to extend Pygments without hacking the sources, but want to use the lexer/formatter/style/filter lookup functions (`lexers.get_lexer_by_name` et al.), you can use `setuptools`_ entrypoints to add new lexers, formatters or styles as if they were in the Pygments core. .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools That means you can use your highlighter modules with the `pygmentize` script, which relies on the mentioned functions. Entrypoints =========== Here is a list of setuptools entrypoints that Pygments understands: `pygments.lexers` This entrypoint is used for adding new lexers to the Pygments core. The name of the entrypoint values doesn't really matter, Pygments extracts required metadata from the class definition: .. sourcecode:: ini [pygments.lexers] yourlexer = yourmodule:YourLexer Note that you have to define ``name``, ``aliases`` and ``filename`` attributes so that you can use the highlighter from the command line: .. sourcecode:: python class YourLexer(...): name = 'Name Of Your Lexer' aliases = ['alias'] filenames = ['*.ext'] `pygments.formatters` You can use this entrypoint to add new formatters to Pygments. The name of an entrypoint item is the name of the formatter. If you prefix the name with a slash it's used as a filename pattern: .. sourcecode:: ini [pygments.formatters] yourformatter = yourmodule:YourFormatter /.ext = yourmodule:YourFormatter `pygments.styles` To add a new style you can use this entrypoint. The name of the entrypoint is the name of the style: .. sourcecode:: ini [pygments.styles] yourstyle = yourmodule:YourStyle `pygments.filters` Use this entrypoint to register a new filter. The name of the entrypoint is the name of the filter: .. sourcecode:: ini [pygments.filters] yourfilter = yourmodule:YourFilter How To Use Entrypoints ====================== This documentation doesn't explain how to use those entrypoints because this is covered in the `setuptools documentation`_. That page should cover everything you need to write a plugin. .. _setuptools documentation: http://peak.telecommunity.com/DevCenter/setuptools Extending The Core ================== If you have written a Pygments plugin that is open source, please inform us about that. There is a high chance that we'll add it to the Pygments distribution. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/quickstart.rst000066400000000000000000000147731250413007300245050ustar00rootroot00000000000000.. -*- mode: rst -*- =========================== Introduction and Quickstart =========================== Welcome to Pygments! This document explains the basic concepts and terms and gives a few examples of how to use the library. Architecture ============ There are four types of components that work together highlighting a piece of code: * A **lexer** splits the source into tokens, fragments of the source that have a token type that determines what the text represents semantically (e.g., keyword, string, or comment). There is a lexer for every language or markup format that Pygments supports. * The token stream can be piped through **filters**, which usually modify the token types or text fragments, e.g. uppercasing all keywords. * A **formatter** then takes the token stream and writes it to an output file, in a format such as HTML, LaTeX or RTF. * While writing the output, a **style** determines how to highlight all the different token types. It maps them to attributes like "red and bold". Example ======= Here is a small example for highlighting Python code: .. sourcecode:: python from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter code = 'print "Hello World"' print highlight(code, PythonLexer(), HtmlFormatter()) which prints something like this: .. sourcecode:: html
print "Hello World"
As you can see, Pygments uses CSS classes (by default, but you can change that) instead of inline styles in order to avoid outputting redundant style information over and over. A CSS stylesheet that contains all CSS classes possibly used in the output can be produced by: .. sourcecode:: python print HtmlFormatter().get_style_defs('.highlight') The argument to :func:`get_style_defs` is used as an additional CSS selector: the output may look like this: .. sourcecode:: css .highlight .k { color: #AA22FF; font-weight: bold } .highlight .s { color: #BB4444 } ... Options ======= The :func:`highlight()` function supports a fourth argument called *outfile*, it must be a file object if given. The formatted output will then be written to this file instead of being returned as a string. Lexers and formatters both support options. They are given to them as keyword arguments either to the class or to the lookup method: .. sourcecode:: python from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter lexer = get_lexer_by_name("python", stripall=True) formatter = HtmlFormatter(linenos=True, cssclass="source") result = highlight(code, lexer, formatter) This makes the lexer strip all leading and trailing whitespace from the input (`stripall` option), lets the formatter output line numbers (`linenos` option), and sets the wrapping ``
``'s class to ``source`` (instead of ``highlight``). Important options include: `encoding` : for lexers and formatters Since Pygments uses Unicode strings internally, this determines which encoding will be used to convert to or from byte strings. `style` : for formatters The name of the style to use when writing the output. For an overview of builtin lexers and formatters and their options, visit the :doc:`lexer ` and :doc:`formatters ` lists. For a documentation on filters, see :doc:`this page `. Lexer and formatter lookup ========================== If you want to lookup a built-in lexer by its alias or a filename, you can use one of the following methods: .. sourcecode:: pycon >>> from pygments.lexers import (get_lexer_by_name, ... get_lexer_for_filename, get_lexer_for_mimetype) >>> get_lexer_by_name('python') >>> get_lexer_for_filename('spam.rb') >>> get_lexer_for_mimetype('text/x-perl') All these functions accept keyword arguments; they will be passed to the lexer as options. A similar API is available for formatters: use :func:`.get_formatter_by_name()` and :func:`.get_formatter_for_filename()` from the :mod:`pygments.formatters` module for this purpose. Guessing lexers =============== If you don't know the content of the file, or you want to highlight a file whose extension is ambiguous, such as ``.html`` (which could contain plain HTML or some template tags), use these functions: .. sourcecode:: pycon >>> from pygments.lexers import guess_lexer, guess_lexer_for_filename >>> guess_lexer('#!/usr/bin/python\nprint "Hello World!"') >>> guess_lexer_for_filename('test.py', 'print "Hello World!"') :func:`.guess_lexer()` passes the given content to the lexer classes' :meth:`analyse_text()` method and returns the one for which it returns the highest number. All lexers have two different filename pattern lists: the primary and the secondary one. The :func:`.get_lexer_for_filename()` function only uses the primary list, whose entries are supposed to be unique among all lexers. :func:`.guess_lexer_for_filename()`, however, will first loop through all lexers and look at the primary and secondary filename patterns if the filename matches. If only one lexer matches, it is returned, else the guessing mechanism of :func:`.guess_lexer()` is used with the matching lexers. As usual, keyword arguments to these functions are given to the created lexer as options. Command line usage ================== You can use Pygments from the command line, using the :program:`pygmentize` script:: $ pygmentize test.py will highlight the Python file test.py using ANSI escape sequences (a.k.a. terminal colors) and print the result to standard output. To output HTML, use the ``-f`` option:: $ pygmentize -f html -o test.html test.py to write an HTML-highlighted version of test.py to the file test.html. Note that it will only be a snippet of HTML, if you want a full HTML document, use the "full" option:: $ pygmentize -f html -O full -o test.html test.py This will produce a full HTML document with included stylesheet. A style can be selected with ``-O style=``. If you need a stylesheet for an existing HTML file using Pygments CSS classes, it can be created with:: $ pygmentize -S default -f html > style.css where ``default`` is the style name. More options and tricks and be found in the :doc:`command line reference `. pygments.rb-0.6.3/vendor/pygments-main/doc/docs/rstdirective.rst000066400000000000000000000015511250413007300250100ustar00rootroot00000000000000.. -*- mode: rst -*- ================================ Using Pygments in ReST documents ================================ Many Python people use `ReST`_ for documentation their sourcecode, programs, scripts et cetera. This also means that documentation often includes sourcecode samples or snippets. You can easily enable Pygments support for your ReST texts using a custom directive -- this is also how this documentation displays source code. From Pygments 0.9, the directive is shipped in the distribution as `external/rst-directive.py`. You can copy and adapt this code to your liking. .. removed -- too confusing *Loosely related note:* The ReST lexer now recognizes ``.. sourcecode::`` and ``.. code::`` directives and highlights the contents in the specified language if the `handlecodeblocks` option is true. .. _ReST: http://docutils.sf.net/rst.html pygments.rb-0.6.3/vendor/pygments-main/doc/docs/styles.rst000066400000000000000000000076771250413007300236430ustar00rootroot00000000000000.. -*- mode: rst -*- ====== Styles ====== Pygments comes with some builtin styles that work for both the HTML and LaTeX formatter. The builtin styles can be looked up with the `get_style_by_name` function: .. sourcecode:: pycon >>> from pygments.styles import get_style_by_name >>> get_style_by_name('colorful') You can pass a instance of a `Style` class to a formatter as the `style` option in form of a string: .. sourcecode:: pycon >>> from pygments.styles import get_style_by_name >>> HtmlFormatter(style='colorful').style Or you can also import your own style (which must be a subclass of `pygments.style.Style`) and pass it to the formatter: .. sourcecode:: pycon >>> from yourapp.yourmodule import YourStyle >>> HtmlFormatter(style=YourStyle).style Creating Own Styles =================== So, how to create a style? All you have to do is to subclass `Style` and define some styles: .. sourcecode:: python from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic class YourStyle(Style): default_style = "" styles = { Comment: 'italic #888', Keyword: 'bold #005', Name: '#f00', Name.Function: '#0f0', Name.Class: 'bold #0f0', String: 'bg:#eee #111' } That's it. There are just a few rules. When you define a style for `Name` the style automatically also affects `Name.Function` and so on. If you defined ``'bold'`` and you don't want boldface for a subtoken use ``'nobold'``. (Philosophy: the styles aren't written in CSS syntax since this way they can be used for a variety of formatters.) `default_style` is the style inherited by all token types. To make the style usable for Pygments, you must * either register it as a plugin (see :doc:`the plugin docs `) * or drop it into the `styles` subpackage of your Pygments distribution one style class per style, where the file name is the style name and the class name is `StylenameClass`. For example, if your style should be called ``"mondrian"``, name the class `MondrianStyle`, put it into the file ``mondrian.py`` and this file into the ``pygments.styles`` subpackage directory. Style Rules =========== Here a small overview of all allowed styles: ``bold`` render text as bold ``nobold`` don't render text as bold (to prevent subtokens being highlighted bold) ``italic`` render text italic ``noitalic`` don't render text as italic ``underline`` render text underlined ``nounderline`` don't render text underlined ``bg:`` transparent background ``bg:#000000`` background color (black) ``border:`` no border ``border:#ffffff`` border color (white) ``#ff0000`` text color (red) ``noinherit`` don't inherit styles from supertoken Note that there may not be a space between ``bg:`` and the color value since the style definition string is split at whitespace. Also, using named colors is not allowed since the supported color names vary for different formatters. Furthermore, not all lexers might support every style. Builtin Styles ============== Pygments ships some builtin styles which are maintained by the Pygments team. To get a list of known styles you can use this snippet: .. sourcecode:: pycon >>> from pygments.styles import STYLE_MAP >>> STYLE_MAP.keys() ['default', 'emacs', 'friendly', 'colorful'] Getting a list of available styles ================================== .. versionadded:: 0.6 Because it could be that a plugin registered a style, there is a way to iterate over all styles: .. sourcecode:: pycon >>> from pygments.styles import get_all_styles >>> styles = list(get_all_styles()) pygments.rb-0.6.3/vendor/pygments-main/doc/docs/tokens.rst000066400000000000000000000232331250413007300236050ustar00rootroot00000000000000.. -*- mode: rst -*- ============== Builtin Tokens ============== .. module:: pygments.token In the :mod:`pygments.token` module, there is a special object called `Token` that is used to create token types. You can create a new token type by accessing an attribute of `Token`: .. sourcecode:: pycon >>> from pygments.token import Token >>> Token.String Token.String >>> Token.String is Token.String True Note that tokens are singletons so you can use the ``is`` operator for comparing token types. As of Pygments 0.7 you can also use the ``in`` operator to perform set tests: .. sourcecode:: pycon >>> from pygments.token import Comment >>> Comment.Single in Comment True >>> Comment in Comment.Multi False This can be useful in :doc:`filters ` and if you write lexers on your own without using the base lexers. You can also split a token type into a hierarchy, and get the parent of it: .. sourcecode:: pycon >>> String.split() [Token, Token.Literal, Token.Literal.String] >>> String.parent Token.Literal In principle, you can create an unlimited number of token types but nobody can guarantee that a style would define style rules for a token type. Because of that, Pygments proposes some global token types defined in the `pygments.token.STANDARD_TYPES` dict. For some tokens aliases are already defined: .. sourcecode:: pycon >>> from pygments.token import String >>> String Token.Literal.String Inside the :mod:`pygments.token` module the following aliases are defined: ============= ============================ ==================================== `Text` `Token.Text` for any type of text data `Whitespace` `Token.Text.Whitespace` for specially highlighted whitespace `Error` `Token.Error` represents lexer errors `Other` `Token.Other` special token for data not matched by a parser (e.g. HTML markup in PHP code) `Keyword` `Token.Keyword` any kind of keywords `Name` `Token.Name` variable/function names `Literal` `Token.Literal` Any literals `String` `Token.Literal.String` string literals `Number` `Token.Literal.Number` number literals `Operator` `Token.Operator` operators (``+``, ``not``...) `Punctuation` `Token.Punctuation` punctuation (``[``, ``(``...) `Comment` `Token.Comment` any kind of comments `Generic` `Token.Generic` generic tokens (have a look at the explanation below) ============= ============================ ==================================== The `Whitespace` token type is new in Pygments 0.8. It is used only by the `VisibleWhitespaceFilter` currently. Normally you just create token types using the already defined aliases. For each of those token aliases, a number of subtypes exists (excluding the special tokens `Token.Text`, `Token.Error` and `Token.Other`) The `is_token_subtype()` function in the `pygments.token` module can be used to test if a token type is a subtype of another (such as `Name.Tag` and `Name`). (This is the same as ``Name.Tag in Name``. The overloaded `in` operator was newly introduced in Pygments 0.7, the function still exists for backwards compatiblity.) With Pygments 0.7, it's also possible to convert strings to token types (for example if you want to supply a token from the command line): .. sourcecode:: pycon >>> from pygments.token import String, string_to_tokentype >>> string_to_tokentype("String") Token.Literal.String >>> string_to_tokentype("Token.Literal.String") Token.Literal.String >>> string_to_tokentype(String) Token.Literal.String Keyword Tokens ============== `Keyword` For any kind of keyword (especially if it doesn't match any of the subtypes of course). `Keyword.Constant` For keywords that are constants (e.g. ``None`` in future Python versions). `Keyword.Declaration` For keywords used for variable declaration (e.g. ``var`` in some programming languages like JavaScript). `Keyword.Namespace` For keywords used for namespace declarations (e.g. ``import`` in Python and Java and ``package`` in Java). `Keyword.Pseudo` For keywords that aren't really keywords (e.g. ``None`` in old Python versions). `Keyword.Reserved` For reserved keywords. `Keyword.Type` For builtin types that can't be used as identifiers (e.g. ``int``, ``char`` etc. in C). Name Tokens =========== `Name` For any name (variable names, function names, classes). `Name.Attribute` For all attributes (e.g. in HTML tags). `Name.Builtin` Builtin names; names that are available in the global namespace. `Name.Builtin.Pseudo` Builtin names that are implicit (e.g. ``self`` in Ruby, ``this`` in Java). `Name.Class` Class names. Because no lexer can know if a name is a class or a function or something else this token is meant for class declarations. `Name.Constant` Token type for constants. In some languages you can recognise a token by the way it's defined (the value after a ``const`` keyword for example). In other languages constants are uppercase by definition (Ruby). `Name.Decorator` Token type for decorators. Decorators are synatic elements in the Python language. Similar syntax elements exist in C# and Java. `Name.Entity` Token type for special entities. (e.g. `` `` in HTML). `Name.Exception` Token type for exception names (e.g. ``RuntimeError`` in Python). Some languages define exceptions in the function signature (Java). You can highlight the name of that exception using this token then. `Name.Function` Token type for function names. `Name.Label` Token type for label names (e.g. in languages that support ``goto``). `Name.Namespace` Token type for namespaces. (e.g. import paths in Java/Python), names following the ``module``/``namespace`` keyword in other languages. `Name.Other` Other names. Normally unused. `Name.Tag` Tag names (in HTML/XML markup or configuration files). `Name.Variable` Token type for variables. Some languages have prefixes for variable names (PHP, Ruby, Perl). You can highlight them using this token. `Name.Variable.Class` same as `Name.Variable` but for class variables (also static variables). `Name.Variable.Global` same as `Name.Variable` but for global variables (used in Ruby, for example). `Name.Variable.Instance` same as `Name.Variable` but for instance variables. Literals ======== `Literal` For any literal (if not further defined). `Literal.Date` for date literals (e.g. ``42d`` in Boo). `String` For any string literal. `String.Backtick` Token type for strings enclosed in backticks. `String.Char` Token type for single characters (e.g. Java, C). `String.Doc` Token type for documentation strings (for example Python). `String.Double` Double quoted strings. `String.Escape` Token type for escape sequences in strings. `String.Heredoc` Token type for "heredoc" strings (e.g. in Ruby or Perl). `String.Interpol` Token type for interpolated parts in strings (e.g. ``#{foo}`` in Ruby). `String.Other` Token type for any other strings (for example ``%q{foo}`` string constructs in Ruby). `String.Regex` Token type for regular expression literals (e.g. ``/foo/`` in JavaScript). `String.Single` Token type for single quoted strings. `String.Symbol` Token type for symbols (e.g. ``:foo`` in LISP or Ruby). `Number` Token type for any number literal. `Number.Bin` Token type for binary literals (e.g. ``0b101010``). `Number.Float` Token type for float literals (e.g. ``42.0``). `Number.Hex` Token type for hexadecimal number literals (e.g. ``0xdeadbeef``). `Number.Integer` Token type for integer literals (e.g. ``42``). `Number.Integer.Long` Token type for long integer literals (e.g. ``42L`` in Python). `Number.Oct` Token type for octal literals. Operators ========= `Operator` For any punctuation operator (e.g. ``+``, ``-``). `Operator.Word` For any operator that is a word (e.g. ``not``). Punctuation =========== .. versionadded:: 0.7 `Punctuation` For any punctuation which is not an operator (e.g. ``[``, ``(``...) Comments ======== `Comment` Token type for any comment. `Comment.Multiline` Token type for multiline comments. `Comment.Preproc` Token type for preprocessor comments (also ```. .. versionadded:: 0.7 The formatters now also accept an `outencoding` option which will override the `encoding` option if given. This makes it possible to use a single options dict with lexers and formatters, and still have different input and output encodings. .. _chardet: http://chardet.feedparser.org/ pygments.rb-0.6.3/vendor/pygments-main/doc/download.rst000066400000000000000000000026341250413007300231630ustar00rootroot00000000000000Download and installation ========================= The current release is version |version|. Packaged versions ----------------- You can download it `from the Python Package Index `_. For installation of packages from PyPI, we recommend `Pip `_, which works on all major platforms. Under Linux, most distributions include a package for Pygments, usually called ``pygments`` or ``python-pygments``. You can install it with the package manager as usual. Development sources ------------------- We're using the `Mercurial `_ version control system. You can get the development source using this command:: hg clone http://bitbucket.org/birkenfeld/pygments-main pygments Development takes place at `Bitbucket `_, you can browse the source online `here `_. The latest changes in the development source code are listed in the `changelog `_. .. Documentation ------------- .. XXX todo You can download the documentation either as a bunch of rst files from the Mercurial repository, see above, or as a tar.gz containing rendered HTML files:

pygmentsdocs.tar.gz

pygments.rb-0.6.3/vendor/pygments-main/doc/faq.rst000066400000000000000000000146401250413007300221230ustar00rootroot00000000000000:orphan: Pygments FAQ ============= What is Pygments? ----------------- Pygments is a syntax highlighting engine written in Python. That means, it will take source code (or other markup) in a supported language and output a processed version (in different formats) containing syntax highlighting markup. Its features include: * a wide range of common languages and markup formats is supported (look here for a list) * new languages and formats are added easily * a number of output formats is available, including: - HTML - ANSI sequences (console output) - LaTeX - RTF * it is usable as a command-line tool and as a library * parsing and formatting is fast Pygments is licensed under the BSD license. Where does the name Pygments come from? --------------------------------------- *Py* of course stands for Python, while *pigments* are used for coloring paint, and in this case, source code! What are the system requirements? --------------------------------- Pygments only needs a standard Python install, version 2.6 or higher or version 3.3 or higher for Python 3. No additional libraries are needed. How can I use Pygments? ----------------------- Pygments is usable as a command-line tool as well as a library. From the command-line, usage looks like this (assuming the pygmentize script is properly installed):: pygmentize -f html /path/to/file.py This will print a HTML-highlighted version of /path/to/file.py to standard output. For a complete help, please run ``pygmentize -h``. Usage as a library is thoroughly demonstrated in the Documentation section. How do I make a new style? -------------------------- Please see the documentation on styles. How can I report a bug or suggest a feature? -------------------------------------------- Please report bugs and feature wishes in the tracker at Bitbucket. You can also e-mail the author or use IRC, see the contact details. I want this support for this language! -------------------------------------- Instead of waiting for others to include language support, why not write it yourself? All you have to know is :doc:`outlined in the docs `. Can I use Pygments for programming language processing? ------------------------------------------------------- The Pygments lexing machinery is quite powerful can be used to build lexers for basically all languages. However, parsing them is not possible, though some lexers go some steps in this direction in order to e.g. highlight function names differently. Also, error reporting is not the scope of Pygments. It focuses on correctly highlighting syntactically valid documents, not finding and compensating errors. Who uses Pygments? ------------------ This is an (incomplete) list of projects and sites known to use the Pygments highlighter. * `Pygments API `_, a HTTP POST interface to Pygments * `The Sphinx documentation builder `_, for embedded source examples * `rst2pdf `_, a reStructuredText to PDF converter * `Zine `_, a Python blogging system * `Trac `_, the universal project management tool * `Bruce `_, a reStructuredText presentation tool * `AsciiDoc `_, a text-based documentation generator * `ActiveState Code `_, the Python Cookbook successor * `ViewVC `_, a web-based version control repository browser * `BzrFruit `_, a Bazaar branch viewer * `QBzr `_, a cross-platform Qt-based GUI front end for Bazaar * `BitBucket `_, a Mercurial and Git hosting site * `GitHub `_, a site offering secure Git hosting and collaborative development * `Review Board `_, a collaborative code reviewing tool * `skeletonz `_, a Python powered content management system * `Diamanda `_, a Django powered wiki system with support for Pygments * `Progopedia `_ (`English `_), an encyclopedia of programming languages * `Postmarkup `_, a BBCode to XHTML generator * `Language Comparison `_, a site that compares different programming languages * `BPython `_, a curses-based intelligent Python shell * `Challenge-You! `_, a site offering programming challenges * `PIDA `_, a universal IDE written in Python * `PuDB `_, a console Python debugger * `XWiki `_, a wiki-based development framework in Java, using Jython * `roux `_, a script for running R scripts and creating beautiful output including graphs * `hurl `_, a web service for making HTTP requests * `wxHTMLPygmentizer `_ is a GUI utility, used to make code-colorization easier * `WpPygments `_, a highlighter plugin for WordPress * `LodgeIt `_, a pastebin with XMLRPC support and diffs * `SpammCan `_, a pastebin (demo see `here `_) * `WowAce.com pastes `_, a pastebin * `Siafoo `_, a tool for sharing and storing useful code and programming experience * `D source `_, a community for the D programming language * `dumpz.org `_, a pastebin * `dpaste.com `_, another Django pastebin * `PylonsHQ Pasties `_, a pastebin * `Django snippets `_, a pastebin for Django code * `Fayaa `_, a Chinese pastebin * `Incollo.com `_, a free collaborative debugging tool * `PasteBox `_, a pastebin focused on privacy * `xinotes.org `_, a site to share notes, code snippets etc. * `hilite.me `_, a site to highlight code snippets * `patx.me `_, a pastebin If you have a project or web site using Pygments, drop me a line, and I'll add a link here. pygments.rb-0.6.3/vendor/pygments-main/doc/index.rst000066400000000000000000000037171250413007300224660ustar00rootroot00000000000000Welcome! ======== This is the home of Pygments. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a wide range of common languages and markup formats is supported * special attention is paid to details that increase highlighting quality * support for new languages and formats are added easily; most languages use a simple regex-based lexing mechanism * a number of output formats is available, among them HTML, RTF, LaTeX and ANSI sequences * it is usable as a command-line tool and as a library * ... and it highlights even Brainf*ck! Read more in the FAQ list or the documentation, or download the latest release. Though Pygments has not yet won an award, we trust that you will notice it's a top quality product . .. _contribute: Contribute ---------- Like every open-source project, we are always looking for volunteers to help us with programming. Python knowledge is required, but don't fear: Python is a very clear and easy to learn language. Development takes place on `Bitbucket `_, where the Mercurial repository, tickets and pull requests can be viewed. Our primary communication instrument is the IRC channel **#pocoo** on the Freenode network. To join it, let your IRC client connect to ``irc.freenode.net`` and do ``/join #pocoo``. If you found a bug, just open a ticket in the Bitbucket tracker. Be sure to log in to be notified when the issue is fixed -- development is not fast-paced as the library is quite stable. You can also send an e-mail to the developers, see below. The authors ----------- Pygments is maintained by **Georg Brandl**, e-mail address *georg*\ *@*\ *python.org*. Many lexers and fixes have been contributed by **Armin Ronacher**, the rest of the `Pocoo `_ team and **Tim Hatch**. .. toctree:: :maxdepth: 1 :hidden: docs/index pygments.rb-0.6.3/vendor/pygments-main/doc/languages.rst000066400000000000000000000051441250413007300233210ustar00rootroot00000000000000:orphan: Supported languages =================== Pygments supports an ever-growing range of languages. Watch this space... Programming languages --------------------- * ActionScript * Ada * ANTLR * AppleScript * Assembly (various) * Asymptote * Awk * Befunge * Boo * BrainFuck * C, C++ * C# * Clojure * CoffeeScript * ColdFusion * Common Lisp * Coq * Cryptol (incl. Literate Cryptol) * `Cython `_ * `D `_ * Dart * Delphi * Dylan * Erlang * Factor * Fancy * Fortran * F# * GAP * Gherkin (Cucumber) * GL shaders * Groovy * `Haskell `_ (incl. Literate Haskell) * IDL * Io * Java * JavaScript * LLVM * Logtalk * `Lua `_ * Matlab * MiniD * Modelica * Modula-2 * MuPad * Nemerle * Nimrod * Objective-C * Objective-J * Octave * OCaml * PHP * `Perl `_ * PovRay * PostScript * PowerShell * Prolog * `Python `_ 2.x and 3.x (incl. console sessions and tracebacks) * `REBOL `_ * `Red `_ * Redcode * `Ruby `_ (incl. irb sessions) * Rust * S, S-Plus, R * Scala * Scheme * Scilab * Smalltalk * SNOBOL * Tcl * Vala * Verilog * VHDL * Visual Basic.NET * Visual FoxPro * XQuery * Zephir Template languages ------------------ * Cheetah templates * `Django `_ / `Jinja `_ templates * ERB (Ruby templating) * `Genshi `_ (the Trac template language) * JSP (Java Server Pages) * `Myghty `_ (the HTML::Mason based framework) * `Mako `_ (the Myghty successor) * `Smarty `_ templates (PHP templating) * Tea Other markup ------------ * Apache config files * Bash shell scripts * BBCode * CMake * CSS * Debian control files * Diff files * DTD * Gettext catalogs * Gnuplot script * Groff markup * HTML * HTTP sessions * INI-style config files * IRC logs (irssi style) * Lighttpd config files * Makefiles * MoinMoin/Trac Wiki markup * MySQL * Nginx config files * POV-Ray scenes * Ragel * Redcode * ReST * Robot Framework * RPM spec files * SQL, also MySQL, SQLite * Squid configuration * TeX * tcsh * Vim Script * Windows batch files * XML * XSLT * YAML ... that's all? --------------- Well, why not write your own? Contributing to Pygments is easy and fun. Look :doc:`here ` for the docs on lexer development and :ref:`here ` for contact details. Note: the languages listed here are supported in the development version. The latest release may lack a few of them. pygments.rb-0.6.3/vendor/pygments-main/doc/make.bat000066400000000000000000000117541250413007300222320ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Pygments.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Pygments.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end pygments.rb-0.6.3/vendor/pygments-main/doc/pygmentize.1000066400000000000000000000066501250413007300231010ustar00rootroot00000000000000.TH PYGMENTIZE 1 "February 15, 2007" .SH NAME pygmentize \- highlights the input file .SH SYNOPSIS .B \fBpygmentize\fP .RI [-l\ \fI\fP]\ [-F\ \fI\fP[:\fI\fP]]\ [-f\ \fI\fP] .RI [-O\ \fI\fP]\ [-P\ \fI\fP]\ [-o\ \fI\fP]\ [\fI\fP] .br .B \fBpygmentize\fP .RI -S\ \fI

%(title)s

''' DOC_HEADER_EXTERNALCSS = '''\ %(title)s

%(title)s

''' DOC_FOOTER = '''\ ''' class HtmlFormatter(Formatter): r""" Format tokens as HTML 4 ```` tags within a ``
`` tag, wrapped
    in a ``
`` tag. The ``
``'s CSS class can be set by the `cssclass` option. If the `linenos` option is set to ``"table"``, the ``
`` is
    additionally wrapped inside a ```` which has one row and two
    cells: one containing the line numbers and one containing the code.
    Example:

    .. sourcecode:: html

        
1
            2
def foo(bar):
              pass
            
(whitespace added to improve clarity). Wrapping can be disabled using the `nowrap` option. A list of lines can be specified using the `hl_lines` option to make these lines highlighted (as of Pygments 0.11). With the `full` option, a complete HTML 4 document is output, including the style definitions inside a ``

Code tags report for %s

%s
LineTagWhoDescription
''' TABLE = '\nFile: %s\n' TR = ('%%(lno)d' '%%(tag)s' '%%(who)s%%(what)s') f = open(output, 'w') table = '\n'.join(TABLE % fname + '\n'.join(TR % (no % 2,) % entry for no, entry in enumerate(store[fname])) for fname in sorted(store)) f.write(HTML % (', '.join(map(abspath, args)), table)) f.close() print("Report written to %s." % output) return 0 if __name__ == '__main__': sys.exit(main()) pygments.rb-0.6.3/vendor/pygments-main/scripts/find_error.py000077500000000000000000000136011250413007300242460ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- """ Lexing error finder ~~~~~~~~~~~~~~~~~~~ For the source files given on the command line, display the text where Error tokens are being generated, along with some context. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import print_function import os import sys # always prefer Pygments from source if exists srcpath = os.path.join(os.path.dirname(__file__), '..') if os.path.isdir(os.path.join(srcpath, 'pygments')): sys.path.insert(0, srcpath) from pygments.lexer import RegexLexer from pygments.lexers import get_lexer_for_filename, get_lexer_by_name from pygments.token import Error, Text, _TokenType from pygments.cmdline import _parse_options class DebuggingRegexLexer(RegexLexer): """Make the state stack, position and current match instance attributes.""" def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. ``stack`` is the inital stack (default: ``['root']``) """ self.pos = 0 tokendefs = self._tokens self.statestack = list(stack) statetokens = tokendefs[self.statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: self.m = m = rexmatch(text, self.pos) if m: if type(action) is _TokenType: yield self.pos, action, m.group() else: for item in action(self, m): yield item self.pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': self.statestack.pop() elif state == '#push': self.statestack.append(self.statestack[-1]) else: self.statestack.append(state) elif isinstance(new_state, int): # pop del self.statestack[new_state:] elif new_state == '#push': self.statestack.append(self.statestack[-1]) else: assert False, 'wrong state def: %r' % new_state statetokens = tokendefs[self.statestack[-1]] break else: try: if text[self.pos] == '\n': # at EOL, reset state to 'root' self.pos += 1 self.statestack = ['root'] statetokens = tokendefs['root'] yield self.pos, Text, u'\n' continue yield self.pos, Error, text[self.pos] self.pos += 1 except IndexError: break def main(fn, lexer=None, options={}): if lexer is not None: lx = get_lexer_by_name(lexer) else: try: lx = get_lexer_for_filename(os.path.basename(fn), **options) except ValueError: try: name, rest = fn.split('_', 1) lx = get_lexer_by_name(name, **options) except ValueError: raise AssertionError('no lexer found for file %r' % fn) debug_lexer = False # does not work for e.g. ExtendedRegexLexers if lx.__class__.__bases__ == (RegexLexer,): lx.__class__.__bases__ = (DebuggingRegexLexer,) debug_lexer = True elif lx.__class__.__bases__ == (DebuggingRegexLexer,): # already debugged before debug_lexer = True lno = 1 text = open(fn, 'U').read() text = text.strip('\n') + '\n' tokens = [] states = [] def show_token(tok, state): reprs = map(repr, tok) print(' ' + reprs[1] + ' ' + ' ' * (29-len(reprs[1])) + reprs[0], end=' ') if debug_lexer: print(' ' + ' ' * (29-len(reprs[0])) + repr(state), end=' ') print() for type, val in lx.get_tokens(text): lno += val.count('\n') if type == Error: print('Error parsing', fn, 'on line', lno) print('Previous tokens' + (debug_lexer and ' and states' or '') + ':') if showall: for tok, state in map(None, tokens, states): show_token(tok, state) else: for i in range(max(len(tokens) - num, 0), len(tokens)): show_token(tokens[i], states[i]) print('Error token:') l = len(repr(val)) print(' ' + repr(val), end=' ') if debug_lexer and hasattr(lx, 'statestack'): print(' ' * (60-l) + repr(lx.statestack), end=' ') print() print() return 1 tokens.append((type, val)) if debug_lexer: if hasattr(lx, 'statestack'): states.append(lx.statestack[:]) else: states.append(None) if showall: for tok, state in map(None, tokens, states): show_token(tok, state) return 0 num = 10 showall = False lexer = None options = {} if __name__ == '__main__': import getopt opts, args = getopt.getopt(sys.argv[1:], 'n:l:aO:') for opt, val in opts: if opt == '-n': num = int(val) elif opt == '-a': showall = True elif opt == '-l': lexer = val elif opt == '-O': options = _parse_options([val]) ret = 0 for f in args: ret += main(f, lexer, options) sys.exit(bool(ret)) pygments.rb-0.6.3/vendor/pygments-main/scripts/get_vimkw.py000066400000000000000000000027061250413007300241120ustar00rootroot00000000000000from __future__ import print_function import re r_line = re.compile(r"^(syn keyword vimCommand contained|syn keyword vimOption " r"contained|syn keyword vimAutoEvent contained)\s+(.*)") r_item = re.compile(r"(\w+)(?:\[(\w+)\])?") def getkw(input, output): out = file(output, 'w') output_info = {'command': [], 'option': [], 'auto': []} for line in file(input): m = r_line.match(line) if m: # Decide which output gets mapped to d if 'vimCommand' in m.group(1): d = output_info['command'] elif 'AutoEvent' in m.group(1): d = output_info['auto'] else: d = output_info['option'] # Extract all the shortened versions for i in r_item.finditer(m.group(2)): d.append('(%r,%r)' % (i.group(1), "%s%s" % (i.group(1), i.group(2) or ''))) output_info['option'].append("('nnoremap','nnoremap')") output_info['option'].append("('inoremap','inoremap')") output_info['option'].append("('vnoremap','vnoremap')") for a, b in output_info.items(): b.sort() print('%s=[%s]' % (a, ','.join(b)), file=out) def is_keyword(w, keywords): for i in range(len(w), 0, -1): if w[:i] in keywords: return keywords[w[:i]][:len(w)] == w return False if __name__ == "__main__": getkw("/usr/share/vim/vim73/syntax/vim.vim", "temp.py") pygments.rb-0.6.3/vendor/pygments-main/scripts/pylintrc000066400000000000000000000211471250413007300233330ustar00rootroot00000000000000# lint Python modules using external checkers. # # This is the main checker controling the other ones and the reports # generation. It is itself both a raw checker and an astng checker in order # to: # * handle message activation / deactivation at the module level # * handle some basic but necessary stats'data (number of classes, methods...) # [MASTER] # Specify a configuration file. #rcfile= # Profiled execution. profile=no # Add to the black list. It should be a base name, not a # path. You may set this option multiple times. ignore=.svn # Pickle collected data for later comparisons. persistent=yes # Set the cache size for astng objects. cache-size=500 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= [MESSAGES CONTROL] # Enable only checker(s) with the given id(s). This option conflict with the # disable-checker option #enable-checker= # Enable all checker(s) except those with the given id(s). This option conflict # with the disable-checker option #disable-checker= # Enable all messages in the listed categories. #enable-msg-cat= # Disable all messages in the listed categories. #disable-msg-cat= # Enable the message(s) with the given id(s). #enable-msg= # Disable the message(s) with the given id(s). disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R0201 [REPORTS] # set the output format. Available formats are text, parseable, colorized and # html output-format=colorized # Include message's id in output include-ids=yes # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells wether to display a full report or only the messages reports=yes # Python expression which should return a note less than 10 (10 is the highest # note).You have access to the variables errors warning, statement which # respectivly contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (R0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (R0004). comment=no # Enable the report(s) with the given id(s). #enable-report= # Disable the report(s) with the given id(s). #disable-report= # checks for # * unused variables / imports # * undefined variables # * redefinition of variable from builtins or from an outer scope # * use of variable before assigment # [VARIABLES] # Tells wether we should check for unused import in __init__ files. init-import=no # A regular expression matching names used for dummy variables (i.e. not used). dummy-variables-rgx=_|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= # try to find bugs in the code using type inference # [TYPECHECK] # Tells wether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # When zope mode is activated, consider the acquired-members option to ignore # access to some undefined attributes. zope=no # List of members which are usually get through zope's acquisition mecanism and # so shouldn't trigger E0201 when accessed (need zope=yes to be considered). acquired-members=REQUEST,acl_users,aq_parent # checks for : # * doc strings # * modules / classes / functions / methods / arguments / variables name # * number of arguments, local variables, branchs, returns and statements in # functions, methods # * required module attributes # * dangerous default values as arguments # * redefinition of function / method / class # * uses of the global statement # [BASIC] # Required attributes for module, separated by a comma required-attributes= # Regular expression which should only match functions or classes name which do # not require a docstring no-docstring-rgx=__.*__ # Regular expression which should only match correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression which should only match correct module level names const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$ # Regular expression which should only match correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Regular expression which should only match correct function names function-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct method names method-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct instance attribute names attr-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct argument names argument-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct variable names variable-rgx=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match correct list comprehension / # generator expression variable names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # List of builtins function names that should not be used, separated by a comma bad-functions=apply,input # checks for sign of poor/misdesign: # * number of methods, attributes, local variables... # * size, complexity of functions, methods # [DESIGN] # Maximum number of arguments for function / method max-args=12 # Maximum number of locals for function / method body max-locals=30 # Maximum number of return / yield for function / method body max-returns=12 # Maximum number of branch for function / method body max-branchs=30 # Maximum number of statements in function / method body max-statements=60 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=20 # Minimum number of public methods for a class (see R0903). min-public-methods=0 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # checks for # * external modules dependencies # * relative / wildcard imports # * cyclic imports # * uses of deprecated modules # [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,string,TERMIOS,Bastion,rexec # Create a graph of every (i.e. internal and external) dependencies in the # given file (report R0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report R0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report R0402 must # not be disabled) int-import-graph= # checks for : # * methods without self as first argument # * overridden methods signature # * access only to existant members via self # * attributes not defined in the __init__ method # * supported interfaces implementation # * unreachable code # [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # checks for similarities and duplicated code. This computation may be # memory / CPU intensive, so you should disable it if you experiments some # problems. # [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=10 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # checks for: # * warning notes in the code like FIXME, XXX # * PEP 263: source code with non ascii character but no encoding declaration # [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO # checks for : # * unauthorized constructions # * strict indentation # * line length # * use of <> instead of != # [FORMAT] # Maximum number of characters on a single line. max-line-length=90 # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' pygments.rb-0.6.3/vendor/pygments-main/scripts/vim2pygments.py000077500000000000000000000633141250413007300245670ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vim Colorscheme Converter ~~~~~~~~~~~~~~~~~~~~~~~~~ This script converts vim colorscheme files to valid pygments style classes meant for putting into modules. :copyright 2006 by Armin Ronacher. :license: BSD, see LICENSE for details. """ from __future__ import print_function import sys import re from os import path from io import StringIO split_re = re.compile(r'(? 2 and \ len(parts[0]) >= 2 and \ 'highlight'.startswith(parts[0]): token = parts[1].lower() if token not in TOKENS: continue for item in parts[2:]: p = item.split('=', 1) if not len(p) == 2: continue key, value = p if key in ('ctermfg', 'guifg'): color = get_vim_color(value) if color: set('color', color) elif key in ('ctermbg', 'guibg'): color = get_vim_color(value) if color: set('bgcolor', color) elif key in ('term', 'cterm', 'gui'): items = value.split(',') for item in items: item = item.lower() if item == 'none': set('noinherit', True) elif item == 'bold': set('bold', True) elif item == 'underline': set('underline', True) elif item == 'italic': set('italic', True) if bg_color is not None and not colors['Normal'].get('bgcolor'): colors['Normal']['bgcolor'] = bg_color color_map = {} for token, styles in colors.items(): if token in TOKENS: tmp = [] if styles.get('noinherit'): tmp.append('noinherit') if 'color' in styles: tmp.append(styles['color']) if 'bgcolor' in styles: tmp.append('bg:' + styles['bgcolor']) if styles.get('bold'): tmp.append('bold') if styles.get('italic'): tmp.append('italic') if styles.get('underline'): tmp.append('underline') tokens = TOKENS[token] if not isinstance(tokens, tuple): tokens = (tokens,) for token in tokens: color_map[token] = ' '.join(tmp) default_token = color_map.pop('') return default_token, color_map class StyleWriter(object): def __init__(self, code, name): self.code = code self.name = name.lower() def write_header(self, out): out.write('# -*- coding: utf-8 -*-\n"""\n') out.write(' %s Colorscheme\n' % self.name.title()) out.write(' %s\n\n' % ('~' * (len(self.name) + 12))) out.write(' Converted by %s\n' % SCRIPT_NAME) out.write('"""\nfrom pygments.style import Style\n') out.write('from pygments.token import Token, %s\n\n' % ', '.join(TOKEN_TYPES)) out.write('class %sStyle(Style):\n\n' % self.name.title()) def write(self, out): self.write_header(out) default_token, tokens = find_colors(self.code) tokens = list(tokens.items()) tokens.sort(lambda a, b: cmp(len(a[0]), len(a[1]))) bg_color = [x[3:] for x in default_token.split() if x.startswith('bg:')] if bg_color: out.write(' background_color = %r\n' % bg_color[0]) out.write(' styles = {\n') out.write(' %-20s%r,\n' % ('Token:', default_token)) for token, definition in tokens: if definition: out.write(' %-20s%r,\n' % (token + ':', definition)) out.write(' }') def __repr__(self): out = StringIO() self.write_style(out) return out.getvalue() def convert(filename, stream=None): name = path.basename(filename) if name.endswith('.vim'): name = name[:-4] f = file(filename) code = f.read() f.close() writer = StyleWriter(code, name) if stream is not None: out = stream else: out = StringIO() writer.write(out) if stream is None: return out.getvalue() def main(): if len(sys.argv) != 2 or sys.argv[1] in ('-h', '--help'): print('Usage: %s ' % sys.argv[0]) return 2 if sys.argv[1] in ('-v', '--version'): print('%s %s' % (SCRIPT_NAME, SCRIPT_VERSION)) return filename = sys.argv[1] if not (path.exists(filename) and path.isfile(filename)): print('Error: %s not found' % filename) return 1 convert(filename, sys.stdout) sys.stdout.write('\n') if __name__ == '__main__': sys.exit(main() or 0) pygments.rb-0.6.3/vendor/pygments-main/setup.cfg000066400000000000000000000001741250413007300216730ustar00rootroot00000000000000[egg_info] tag_build = dev tag_date = true [aliases] release = egg_info -RDb '' upload = upload --sign --identity=36580288 pygments.rb-0.6.3/vendor/pygments-main/setup.py000077500000000000000000000055631250413007300215760ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Pygments ~~~~~~~~ Pygments is a syntax highlighting package written in Python. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a wide range of common languages and markup formats is supported * special attention is paid to details, increasing quality by a fair amount * support for new languages and formats are added easily * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image \ formats that PIL supports and ANSI sequences * it is usable as a command-line tool and as a library * ... and it highlights even Brainfuck! The `Pygments tip`_ is installable with ``easy_install Pygments==dev``. .. _Pygments tip: http://bitbucket.org/birkenfeld/pygments-main/get/default.zip#egg=Pygments-dev :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ try: from setuptools import setup, find_packages have_setuptools = True except ImportError: try: import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages have_setuptools = True except ImportError: from distutils.core import setup def find_packages(*args, **kwargs): return [ 'pygments', 'pygments.lexers', 'pygments.formatters', 'pygments.styles', 'pygments.filters', ] have_setuptools = False if have_setuptools: add_keywords = dict( entry_points = { 'console_scripts': ['pygmentize = pygments.cmdline:main'], }, ) else: add_keywords = dict( scripts = ['pygmentize'], ) setup( name = 'Pygments', version = '2.0pre', url = 'http://pygments.org/', license = 'BSD License', author = 'Georg Brandl', author_email = 'georg@python.org', description = 'Pygments is a syntax highlighting package written in Python.', long_description = __doc__, keywords = 'syntax highlighting', packages = find_packages(exclude=['ez_setup']), platforms = 'any', zip_safe = False, include_package_data = True, classifiers = [ 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: System Administrators', 'Development Status :: 6 - Mature', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Operating System :: OS Independent', 'Topic :: Text Processing :: Filters', 'Topic :: Utilities', ], **add_keywords ) pygments.rb-0.6.3/vendor/pygments-main/tests/000077500000000000000000000000001250413007300212125ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/000077500000000000000000000000001250413007300221505ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTML4-f.dtd000066400000000000000000000017571250413007300237320ustar00rootroot00000000000000 ... ... --> %HTML4.dtd;pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTML4-s.dtd000066400000000000000000001042251250413007300237410ustar00rootroot00000000000000 %HTMLlat1; %HTMLsymbol; %HTMLspecial; ]]> pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTML4.dcl000066400000000000000000000054761250413007300235000ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTML4.dtd000066400000000000000000001311411250413007300234760ustar00rootroot00000000000000 ... ... The URI used as a system identifier with the public identifier allows the user agent to download the DTD and entity sets as needed. The FPI for the Strict HTML 4.0 DTD is: "-//W3C//DTD HTML 4.0//EN" and its URI is: http://www.w3.org/TR/REC-html40/strict.dtd Authors should use the Strict DTD unless they need the presentation control for user agents that don't (adequately) support style sheets. If you are writing a document that includes frames, use the following FPI: "-//W3C//DTD HTML 4.0 Frameset//EN" with the URI: http://www.w3.org/TR/REC-html40/frameset.dtd The following URIs are supported in relation to HTML 4.0 "http://www.w3.org/TR/REC-html40/strict.dtd" (Strict DTD) "http://www.w3.org/TR/REC-html40/loose.dtd" (Loose DTD) "http://www.w3.org/TR/REC-html40/frameset.dtd" (Frameset DTD) "http://www.w3.org/TR/REC-html40/HTMLlat1.ent" (Latin-1 entities) "http://www.w3.org/TR/REC-html40/HTMLsymbol.ent" (Symbol entities) "http://www.w3.org/TR/REC-html40/HTMLspecial.ent" (Special entities) These URIs point to the latest version of each file. To reference this specific revision use the following URIs: "http://www.w3.org/TR/REC-html40-971218/strict.dtd" "http://www.w3.org/TR/REC-html40-971218/loose.dtd" "http://www.w3.org/TR/REC-html40-971218/frameset.dtd" "http://www.w3.org/TR/REC-html40-971218/HTMLlat1.ent" "http://www.w3.org/TR/REC-html40-971218/HTMLsymbol.ent" "http://www.w3.org/TR/REC-html40-971218/HTMLspecial.ent" --> %HTMLlat1; %HTMLsymbol; %HTMLspecial; ]]> ]]> ]]> ]]> ]]> pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTML4.soc000066400000000000000000000005761250413007300235160ustar00rootroot00000000000000OVERRIDE YES SGMLDECL HTML4.dcl DOCTYPE HTML HTML4.dtd PUBLIC "-//W3C//DTD HTML 4.0//EN" HTML4-s.dtd PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" HTML4.dtd PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" HTML4-f.dtd PUBLIC "-//W3C//ENTITIES Latin1//EN//HTML" HTMLlat1.ent PUBLIC "-//W3C//ENTITIES Special//EN//HTML" HTMLspec.ent PUBLIC "-//W3C//ENTITIES Symbols//EN//HTML" HTMLsym.ent pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTMLlat1.ent000066400000000000000000000273671250413007300242250ustar00rootroot00000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTMLspec.ent000066400000000000000000000100241250413007300242740ustar00rootroot00000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/dtds/HTMLsym.ent000066400000000000000000000341561250413007300241660ustar00rootroot00000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/000077500000000000000000000000001250413007300236705ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/99_bottles_of_beer.chpl000066400000000000000000000062011250413007300302150ustar00rootroot00000000000000/*********************************************************************** * Chapel implementation of "99 bottles of beer" * * by Brad Chamberlain and Steve Deitz * 07/13/2006 in Knoxville airport while waiting for flight home from * HPLS workshop * compiles and runs with chpl compiler version 1.7.0 * for more information, contact: chapel_info@cray.com * * * Notes: * o as in all good parallel computations, boundary conditions * constitute the vast bulk of complexity in this code (invite Brad to * tell you about his zany boundary condition simplification scheme) * o uses type inference for variables, arguments * o relies on integer->string coercions * o uses named argument passing (for documentation purposes only) ***********************************************************************/ // allow executable command-line specification of number of bottles // (e.g., ./a.out -snumBottles=999999) config const numBottles = 99; const numVerses = numBottles+1; // a domain to describe the space of lyrics var LyricsSpace: domain(1) = {1..numVerses}; // array of lyrics var Lyrics: [LyricsSpace] string; // parallel computation of lyrics array [verse in LyricsSpace] Lyrics(verse) = computeLyric(verse); // as in any good parallel language, I/O to stdout is serialized. // (Note that I/O to a file could be parallelized using a parallel // prefix computation on the verse strings' lengths with file seeking) writeln(Lyrics); // HELPER FUNCTIONS: proc computeLyric(verseNum) { var bottleNum = numBottles - (verseNum - 1); var nextBottle = (bottleNum + numVerses - 1)%numVerses; return "\n" // disguise space used to separate elements in array I/O + describeBottles(bottleNum, startOfVerse=true) + " on the wall, " + describeBottles(bottleNum) + ".\n" + computeAction(bottleNum) + describeBottles(nextBottle) + " on the wall.\n"; } proc describeBottles(bottleNum, startOfVerse:bool = false) { // NOTE: bool should not be necessary here (^^^^); working around bug var bottleDescription = if (bottleNum) then bottleNum:string else (if startOfVerse then "N" else "n") + "o more"; return bottleDescription + " bottle" + (if (bottleNum == 1) then "" else "s") + " of beer"; } proc computeAction(bottleNum) { return if (bottleNum == 0) then "Go to the store and buy some more, " else "Take one down and pass it around, "; } // Modules... module M1 { var x = 10; } module M2 { use M1; proc main() { writeln("M2 -> M1 -> x " + x); } } // Classes, records, unions... const PI: real = 3.14159; record Point { var x, y: real; } var p: Point; writeln("Distance from origin: " + sqrt(p.x ** 2 + p.y ** 2)); p = new Point(1.0, 2.0); writeln("Distance from origin: " + sqrt(p.x ** 2 + p.y ** 2)); class Circle { var p: Point; var r: real; } var c = new Circle(r=2.0); proc Circle.area() return PI * r ** 2; writeln("Area of circle: " + c.area()); class Oval: Circle { var r2: real; } proc Oval.area() return PI * r * r2; delete c; c = nil; c = new Oval(r=1.0, r2=2.0); writeln("Area of oval: " + c.area()); union U { var i: int; var r: real; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/AcidStateAdvanced.hs000066400000000000000000000207131250413007300275160ustar00rootroot00000000000000{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, GeneralizedNewtypeDeriving , MultiParamTypeClasses, OverloadedStrings, ScopedTypeVariables, TemplateHaskell , TypeFamilies, FlexibleInstances #-} module Main where import Control.Applicative (Applicative, Alternative, (<$>)) import Control.Exception.Lifted (bracket) import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad (MonadPlus, mplus) import Control.Monad.Reader (MonadReader, ReaderT(..), ask) import Control.Monad.Trans (MonadIO(..)) import Data.Acid ( AcidState(..), EventState(..), EventResult(..) , Query(..), QueryEvent(..), Update(..), UpdateEvent(..) , IsAcidic(..), makeAcidic, openLocalState ) import Data.Acid.Local ( createCheckpointAndClose , openLocalStateFrom ) import Data.Acid.Advanced (query', update') import Data.Maybe (fromMaybe) import Data.SafeCopy (SafeCopy, base, deriveSafeCopy) import Data.Data (Data, Typeable) import Data.Lens ((%=), (!=)) import Data.Lens.Template (makeLens) import Data.Text.Lazy (Text) import Happstack.Server ( Happstack, HasRqData, Method(GET, POST), Request(rqMethod) , Response , ServerPartT(..), WebMonad, FilterMonad, ServerMonad , askRq, decodeBody, dir, defaultBodyPolicy, lookText , mapServerPartT, nullConf, nullDir, ok, simpleHTTP , toResponse ) import Prelude hiding (head, id) import System.FilePath (()) import Text.Blaze ((!)) import Text.Blaze.Html4.Strict (body, head, html, input, form, label, p, title, toHtml) import Text.Blaze.Html4.Strict.Attributes (action, enctype, for, id, method, name, type_, value) class HasAcidState m st where getAcidState :: m (AcidState st) query :: forall event m. ( Functor m , MonadIO m , QueryEvent event , HasAcidState m (EventState event) ) => event -> m (EventResult event) query event = do as <- getAcidState query' (as :: AcidState (EventState event)) event update :: forall event m. ( Functor m , MonadIO m , UpdateEvent event , HasAcidState m (EventState event) ) => event -> m (EventResult event) update event = do as <- getAcidState update' (as :: AcidState (EventState event)) event -- | bracket the opening and close of the `AcidState` handle. -- automatically creates a checkpoint on close withLocalState :: (MonadBaseControl IO m, MonadIO m, IsAcidic st, Typeable st) => Maybe FilePath -- ^ path to state directory -> st -- ^ initial state value -> (AcidState st -> m a) -- ^ function which uses the `AcidState` handle -> m a withLocalState mPath initialState = bracket (liftIO $ (maybe openLocalState openLocalStateFrom mPath) initialState) (liftIO . createCheckpointAndClose) -- State that stores a hit count data CountState = CountState { _count :: Integer } deriving (Eq, Ord, Data, Typeable, Show) $(deriveSafeCopy 0 'base ''CountState) $(makeLens ''CountState) initialCountState :: CountState initialCountState = CountState { _count = 0 } incCount :: Update CountState Integer incCount = count %= succ $(makeAcidic ''CountState ['incCount]) -- State that stores a greeting data GreetingState = GreetingState { _greeting :: Text } deriving (Eq, Ord, Data, Typeable, Show) $(deriveSafeCopy 0 'base ''GreetingState) $(makeLens ''GreetingState) initialGreetingState :: GreetingState initialGreetingState = GreetingState { _greeting = "Hello" } getGreeting :: Query GreetingState Text getGreeting = _greeting <$> ask setGreeting :: Text -> Update GreetingState Text setGreeting txt = greeting != txt $(makeAcidic ''GreetingState ['getGreeting, 'setGreeting]) data Acid = Acid { acidCountState :: AcidState CountState , acidGreetingState :: AcidState GreetingState } withAcid :: Maybe FilePath -> (Acid -> IO a) -> IO a withAcid mBasePath action = let basePath = fromMaybe "_state" mBasePath in withLocalState (Just $ basePath "count") initialCountState $ \c -> withLocalState (Just $ basePath "greeting") initialGreetingState $ \g -> action (Acid c g) newtype App a = App { unApp :: ServerPartT (ReaderT Acid IO) a } deriving ( Functor, Alternative, Applicative, Monad, MonadPlus, MonadIO , HasRqData, ServerMonad ,WebMonad Response, FilterMonad Response , Happstack, MonadReader Acid) runApp :: Acid -> App a -> ServerPartT IO a runApp acid (App sp) = mapServerPartT (flip runReaderT acid) sp instance HasAcidState App CountState where getAcidState = acidCountState <$> ask instance HasAcidState App GreetingState where getAcidState = acidGreetingState <$> ask page :: App Response page = do nullDir g <- greet c <- update IncCount -- ^ a CountState event ok $ toResponse $ html $ do head $ do title "acid-state demo" body $ do form ! action "/" ! method "POST" ! enctype "multipart/form-data" $ do label "new message: " ! for "msg" input ! type_ "text" ! id "msg" ! name "greeting" input ! type_ "submit" ! value "update message" p $ toHtml g p $ do "This page has been loaded " toHtml c " time(s)." where greet = do m <- rqMethod <$> askRq case m of POST -> do decodeBody (defaultBodyPolicy "/tmp/" 0 1000 1000) newGreeting <- lookText "greeting" update (SetGreeting newGreeting) -- ^ a GreetingState event return newGreeting GET -> do query GetGreeting -- ^ a GreetingState event main :: IO () main = withAcid Nothing $ \acid -> simpleHTTP nullConf $ runApp acid page newtype FooState = FooState { foo :: Text } deriving (Eq, Ord, Data, Typeable, SafeCopy) initialFooState :: FooState initialFooState = FooState { foo = "foo" } askFoo :: Query FooState Text askFoo = foo <$> ask $(makeAcidic ''FooState ['askFoo]) fooPlugin :: (Happstack m, HasAcidState m FooState) => m Response fooPlugin = dir "foo" $ do txt <- query AskFoo ok $ toResponse txt data Acid' = Acid' { acidCountState' :: AcidState CountState , acidGreetingState' :: AcidState GreetingState , acidFooState' :: AcidState FooState } withAcid' :: Maybe FilePath -> (Acid' -> IO a) -> IO a withAcid' mBasePath action = let basePath = fromMaybe "_state" mBasePath in withLocalState (Just $ basePath "count") initialCountState $ \c -> withLocalState (Just $ basePath "greeting") initialGreetingState $ \g -> withLocalState (Just $ basePath "foo") initialFooState $ \f -> action (Acid' c g f) newtype App' a = App' { unApp' :: ServerPartT (ReaderT Acid' IO) a } deriving ( Functor, Alternative, Applicative, Monad, MonadPlus, MonadIO , HasRqData, ServerMonad ,WebMonad Response, FilterMonad Response , Happstack, MonadReader Acid') instance HasAcidState App' FooState where getAcidState = acidFooState' <$> ask fooAppPlugin :: App' Response fooAppPlugin = fooPlugin fooReaderPlugin :: ReaderT (AcidState FooState) (ServerPartT IO) Response fooReaderPlugin = fooPlugin instance HasAcidState (ReaderT (AcidState FooState) (ServerPartT IO)) FooState where getAcidState = ask withFooPlugin :: (MonadIO m, MonadBaseControl IO m) => FilePath -- ^ path to state directory -> (ServerPartT IO Response -> m a) -- ^ function that uses fooPlugin -> m a withFooPlugin basePath f = do withLocalState (Just $ basePath "foo") initialFooState $ \fooState -> f $ runReaderT fooReaderPlugin fooState main' :: IO () main' = withFooPlugin "_state" $ \fooPlugin' -> withAcid Nothing $ \acid -> simpleHTTP nullConf $ fooPlugin' `mplus` runApp acid page pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/AlternatingGroup.mu000066400000000000000000000046021250413007300275220ustar00rootroot00000000000000/*++ $Id: AlternatingGroup.mu,v 1.4 2003/09/08 15:00:47 nthiery Exp $ Dom::AlternatingGroup(n) -- the Alternating Group of {1..n} n - integer >= 1 Elements are represented as in Dom::PermutationGroup(n) Author: Nicolas M. Thiéry License: LGPL Created: August 8th, 1999 Last update: $Date: 2003/09/08 15:00:47 $ ++*/ domain Dom::AlternatingGroup(n: Type::PosInt) inherits Dom::PermutationGroup(n,toBeDefined); category Cat::PermutationGroup; axiom Ax::canonicalRep; /*-- size Size of the group. --*/ size := fact(n)/2; /*-- generators A list of generators of the group The first 3-cycle (1,2,3), and a maximal even cycle (1,...,n) or (2,...,n) depending on the parity of n --*/ generators := if n<=2 then generators:=[dom([[1]])]; elif n=3 then generators:=[dom([[1,2,3]])]; elif n mod 2=0 then generators:=[dom([[1,2,3]]), dom([[$2..n]])]; else generators:=[dom([[1,2,3]]), dom([[$1..n]])]; end_if; /*-- allElements List of all the elements of the group --*/ allElements := proc() option remember; local p; begin [new(dom,p) $ p in select(combinat::permutations(n), p->bool(combinat::permutations::sign(p)=1))]; end_proc; /*-- cycleTypes: Count the elements of the group by cycle type. (Cf Cat::PermutationGroupModule). Same algorithm as for Dom::SymmetricGroup, but only even permutations are considered. This is done by disregarding partitions p such that n-length(p) is odd. --*/ cycleTypes := proc() option remember; local t, p, gen; begin userinfo(3, "cycleTypes: starting computation"); t:=table(); gen := combinat::partitions::generator(n); while (p:=gen()) <> FAIL do userinfo(5, "working on partition", p); if(n-nops(p) mod 2=0) then // Compute the size of the conjugacy class of Sn indexed by p // and the cycle type of a permutation in this conjugacy class t[combinat::partitions::toExp(p,n)] := combinat::partitions::conjugacyClassSize(p); end_if; end_while; t; end_proc; begin if testargs() then if args(0) <> 1 then error("wrong no of args"); end_if; if not testtype(n,DOM_INT) then error("argument must be integer") end_if; if n < 1 then error("argument must be positive") end_if; end_if; end_domain: pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/BOM.js000066400000000000000000000000661250413007300246450ustar00rootroot00000000000000/* There is a BOM at the beginning of this file. */pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/CPDictionary.j000077500000000000000000000357541250413007300264140ustar00rootroot00000000000000/* * CPDictionary.j * Foundation * * Created by Francisco Tolmasky. * Copyright 2008, 280 North, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ //@import "CPRange.j" @import "CPObject.j" @import "CPEnumerator.j" @import "CPException.j" /* @ignore */ @implementation _CPDictionaryValueEnumerator : CPEnumerator { CPEnumerator _keyEnumerator; CPDictionary _dictionary; } - (id)initWithDictionary:(CPDictionary)aDictionary { self = [super init]; if (self) { _keyEnumerator = [aDictionary keyEnumerator]; _dictionary = aDictionary; } return self; } - (id)nextObject { var key = [_keyEnumerator nextObject]; if (!key) return nil; return [_dictionary objectForKey:key]; } @end /*! @class CPDictionary @ingroup foundation @brief A mutable key-value pair collection. A dictionary is the standard way of passing around key-value pairs in the Cappuccino framework. It is similar to the Java map interface, except all keys are CPStrings and values can be any Cappuccino or JavaScript object. If you are familiar with dictionaries in Cocoa, you'll notice that there is no CPMutableDictionary class. The regular CPDictionary has \c -setObject:forKey: and \c -removeObjectForKey: methods. In Cappuccino there is no distinction between immutable and mutable classes. They are all mutable. */ @implementation CPDictionary : CPObject { } /* @ignore */ + (id)alloc { return new objj_dictionary(); } /*! Returns a new empty CPDictionary. */ + (id)dictionary { return [[self alloc] init]; } /*! Returns a new dictionary, initialized with the contents of \c aDictionary. @param aDictionary the dictionary to copy key-value pairs from @return the new CPDictionary */ + (id)dictionaryWithDictionary:(CPDictionary)aDictionary { return [[self alloc] initWithDictionary:aDictionary]; } /*! Creates a new dictionary with single key-value pair. @param anObject the object for the paring @param aKey the key for the pairing @return the new CPDictionary */ + (id)dictionaryWithObject:(id)anObject forKey:(id)aKey { return [[self alloc] initWithObjects:[anObject] forKeys:[aKey]]; } /*! Creates a dictionary with multiple key-value pairs. @param objects the objects to place in the dictionary @param keys the keys for each of the objects @throws CPInvalidArgumentException if the number of objects and keys is different @return the new CPDictionary */ + (id)dictionaryWithObjects:(CPArray)objects forKeys:(CPArray)keys { return [[self alloc] initWithObjects:objects forKeys:keys]; } /*! Creates a dictionary with multiple key-value pairs. @param JavaScript object @return the new CPDictionary */ + (id)dictionaryWithJSObject:(JSObject)object { return [self dictionaryWithJSObject:object recursively:NO]; } /*! Creates a dictionary with multiple key-value pairs, recursively. @param JavaScript object @return the new CPDictionary */ + (id)dictionaryWithJSObject:(JSObject)object recursively:(BOOL)recursively { var dictionary = [[self alloc] init]; for (var key in object) { var value = object[key]; if (recursively && value.constructor === Object) value = [CPDictionary dictionaryWithJSObject:value recursively:YES]; [dictionary setObject:value forKey:key]; } return dictionary; } /*! Creates and returns a dictionary constructed by a given pairs of keys and values. @param firstObject first object value @param ... key for the first object and ongoing value-key pairs for more objects. @throws CPInvalidArgumentException if the number of objects and keys is different @return the new CPDictionary Assuming that there's no object retaining in Cappuccino, you can create dictionaries same way as with alloc and initWithObjectsAndKeys: var dict = [CPDictionary dictionaryWithObjectsAndKeys: @"value1", @"key1", @"value2", @"key2"]; Note, that there's no final nil like in Objective-C/Cocoa. @see [CPDictionary initWithObjectsAndKeys:] */ + (id)dictionaryWithObjectsAndKeys:(id)firstObject, ... { arguments[0] = [self alloc]; arguments[1] = @selector(initWithObjectsAndKeys:); return objj_msgSend.apply(this, arguments); } /*! Initializes the dictionary with the contents of another dictionary. @param aDictionary the dictionary to copy key-value pairs from @return the initialized dictionary */ - (id)initWithDictionary:(CPDictionary)aDictionary { var key = "", dictionary = [[CPDictionary alloc] init]; for (key in aDictionary._buckets) [dictionary setObject:[aDictionary objectForKey:key] forKey:key]; return dictionary; } /*! Initializes the dictionary from the arrays of keys and objects. @param objects the objects to put in the dictionary @param keyArray the keys for the objects to put in the dictionary @throws CPInvalidArgumentException if the number of objects and keys is different @return the initialized dictionary */ - (id)initWithObjects:(CPArray)objects forKeys:(CPArray)keyArray { self = [super init]; if ([objects count] != [keyArray count]) [CPException raise:CPInvalidArgumentException reason:"Counts are different.("+[objects count]+"!="+[keyArray count]+")"]; if (self) { var i = [keyArray count]; while (i--) [self setObject:objects[i] forKey:keyArray[i]]; } return self; } /*! Creates and returns a dictionary constructed by a given pairs of keys and values. @param firstObject first object value @param ... key for the first object and ongoing value-key pairs for more objects. @throws CPInvalidArgumentException if the number of objects and keys is different @return the new CPDictionary You can create dictionaries this way: var dict = [[CPDictionary alloc] initWithObjectsAndKeys: @"value1", @"key1", @"value2", @"key2"]; Note, that there's no final nil like in Objective-C/Cocoa. */ - (id)initWithObjectsAndKeys:(id)firstObject, ... { var argCount = arguments.length; if (argCount % 2 !== 0) [CPException raise:CPInvalidArgumentException reason:"Key-value count is mismatched. (" + argCount + " arguments passed)"]; self = [super init]; if (self) { // The arguments array contains self and _cmd, so the first object is at position 2. var index = 2; for(; index < argCount; index += 2) { var value = arguments[index]; if (value === nil) break; [self setObject:value forKey:arguments[index + 1]]; } } return self; } /*! return a copy of the receiver (does not deep copy the objects contained in the dictionary). */ - (CPDictionary)copy { return [CPDictionary dictionaryWithDictionary:self]; } /*! Returns the number of entries in the dictionary */ - (int)count { return count; } /*! Returns an array of keys for all the entries in the dictionary. */ - (CPArray)allKeys { return _keys; } /*! Returns an array of values for all the entries in the dictionary. */ - (CPArray)allValues { var index = _keys.length, values = []; while (index--) values.push(dictionary_getValue(self, [_keys[index]])); return values; } /*! Returns an enumerator that enumerates over all the dictionary's keys. */ - (CPEnumerator)keyEnumerator { return [_keys objectEnumerator]; } /*! Returns an enumerator that enumerates over all the dictionary's values. */ - (CPEnumerator)objectEnumerator { return [[_CPDictionaryValueEnumerator alloc] initWithDictionary:self]; } /*! Compare the receiver to this dictionary, and return whether or not they are equal. */ - (BOOL)isEqualToDictionary:(CPDictionary)aDictionary { if (count !== [aDictionary count]) return NO; var index = count; while (index--) { var currentKey = _keys[index], lhsObject = _buckets[currentKey], rhsObject = aDictionary._buckets[currentKey]; if (lhsObject === rhsObject) continue; if (lhsObject.isa && rhsObject.isa && [lhsObject respondsToSelector:@selector(isEqual:)] && [lhsObject isEqual:rhsObject]) continue; return NO; } return YES; } /* Instance.isEqualToDictionary(aDictionary) { if(this.count()!=aDictionary.count()) return NO; var i= this._keys.count(); while(i--) if(this.objectForKey(this._keys[i])!=aDictionary.objectForKey(this._keys[i])) return NO; return YES; } Instance.allKeys() { return this._keys; } Instance.allKeysForObject(anObject) { var i= 0, keys= CPArray.array(), count= this.count(); while((i= this._objects.indexOfObjectInRage(0, count-i))!=CPNotFound) keys.addObject(this._keys[i]); return keys; } Instance.allValues() { return this._objects; } Instance.keyEnumerator() { return this._keys.objectEnumerator(); } Instance.keysSortedByValueUsingSelector(aSelector) { var dictionary= this, objectSelector= function(rhs) { return aSelector.apply(dictionary.objectForKey(this), [dictionary.objectForKey(rhs)]); }; return this._keys.sortedArrayUsingSelector(objectSelector); } Instance.objectEnumerator() { return this._objects.objectEnumerator(); } */ /*! Returns the object for the entry with key \c aKey. @param aKey the key for the object's entry @return the object for the entry */ - (id)objectForKey:(CPString)aKey { var object = _buckets[aKey]; return (object === undefined) ? nil : object; } /* Instance.objectsForKeys(keys, aNotFoundMarker) { var i= keys.length, objects= CPArray.array(); while(i--) { var object= this.objectForKey(keys[i]); objects.addObject(object==nil?aNotFoundMarker:object); } return objects; } Instance.valueForKey(aKey) { if(aKey.length && aKey[0]=="@") return this.objectForKey(aKey.substr(1)); return base.valueForKey(aKey); } // Instance.addEntriesFromDictionary(aDictionary) { var key, keyEnumerator= aDictionary.keyEnumerator(); while(key= keyEnumerator.nextObject()) this.setObjectForKey(aDictionary.objectForKey(key), key); } */ /*! Removes all the entries from the dictionary. */ - (void)removeAllObjects { _keys = []; count = 0; _buckets = {}; } /*! Removes the entry for the specified key. @param aKey the key of the entry to be removed */ - (void)removeObjectForKey:(id)aKey { dictionary_removeValue(self, aKey); } /*! Removes each entry in allKeys from the receiver. @param allKeys an array of keys that will be removed from the dictionary */ - (void)removeObjectsForKeys:(CPArray)allKeys { var index = allKeys.length; while (index--) dictionary_removeValue(self, allKeys[index]); } /* Instance.removeObjectForKey(aKey) { var entry= this._dictionary[aKey]; if(entry) { var range= CPMakeRange(entry.index, 1); this._keys.removeObjectsInRange(range); this._objects.removeObjectsInRange(range); delete this._dictionary[aKey]; } } Instance.setDictionary(aDictionary) { this._keys= CPArray.arrayWithArray(aDictionary.allKeys()); this._objects= CPArray.arrayWithArray(aDictionary.allValues()); this._dictionary= { }; var i= this._keys.count(); while(i--) this._dictionary[this._keys[i]]= { object: this._objects[i], index: i }; } */ /*! Adds an entry into the dictionary. @param anObject the object for the entry @param aKey the entry's key */ - (void)setObject:(id)anObject forKey:(id)aKey { dictionary_setValue(self, aKey, anObject); } /* Instance.setValueForKey(aValue, aKey) { if(!aValue) this.removeObjectForKey(aKey); else this.setObjectForKey(aValue, aKey); } Instance.copy() { return CPDictionary.alloc().dictionaryWithDictionary(this); } */ /*! Take all the key/value pairs in aDictionary and apply them to this dictionary. */ - (void)addEntriesFromDictionary:(CPDictionary)aDictionary { if (!aDictionary) return; var keys = [aDictionary allKeys], index = [keys count]; while (index--) { var key = keys[index]; [self setObject:[aDictionary objectForKey:key] forKey:key]; } } /*! Returns a human readable description of the dictionary. */ - (CPString)description { var description = @"CPDictionary {\n"; var i = _keys.length; while (i--) { description += _keys[i] + ":"; var object = _buckets[_keys[i]]; if (object && object.isa) description += [object description]; else description += object; description += "\n"; } description += "}"; return description; } @end @implementation CPDictionary (CPCoding) /* Initializes the dictionary by unarchiving the data from a coder. @param aCoder the coder from which the data will be unarchived. @return the initialized dictionary */ - (id)initWithCoder:(CPCoder)aCoder { return [aCoder _decodeDictionaryOfObjectsForKey:@"CP.objects"]; } /*! Archives the dictionary to a provided coder. @param aCoder the coder to which the dictionary data will be archived. */ - (void)encodeWithCoder:(CPCoder)aCoder { [aCoder _encodeDictionaryOfObjects:self forKey:@"CP.objects"]; } @end /*! @class CPMutableDictionary @ingroup compatability This class is just an empty subclass of CPDictionary. CPDictionary already implements mutable methods and this class only exists for source compatability. */ @implementation CPMutableDictionary : CPDictionary @end objj_dictionary.prototype.isa = CPDictionary; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Config.in.cache000066400000000000000000002005671250413007300265010ustar00rootroot00000000000000# INCLUDE_BEGIN Config.in mainmenu "Freetz Configuration" config FREETZ_HAVE_DOT_CONFIG bool default y comment "General --------------------------------" config FREETZ_AVM_VERSION_04_30 bool config FREETZ_AVM_VERSION_04_33 bool config FREETZ_AVM_VERSION_04_40 bool config FREETZ_AVM_VERSION_04_49 bool config FREETZ_AVM_VERSION_04_57 bool config FREETZ_AVM_VERSION_04_67 bool config FREETZ_AVM_VERSION_04_70 bool config FREETZ_AVM_VERSION_04_76 bool config FREETZ_AVM_VERSION_04_80 bool config FREETZ_AVM_VERSION_04_87 bool config FREETZ_AVM_VERSION_7270_04_86 bool config FREETZ_AVM_VERSION_7270_05_05 bool config FREETZ_AVM_VERSION_7320_04_86 bool config FREETZ_AVM_VERSION_7390_04_90 bool config FREETZ_AVM_VERSION_7390_05_05 bool config FREETZ_AVM_VERSION_r7203 bool choice prompt "Hardware type" default FREETZ_TYPE_FON_WLAN_7270_V2 help Select your box type here. config FREETZ_TYPE_300IP_AS_FON select FREETZ_AVM_VERSION_04_49 bool "300IP as Fon" config FREETZ_TYPE_2170 select FREETZ_AVM_VERSION_04_57 bool "2170" config FREETZ_TYPE_FON select FREETZ_AVM_VERSION_04_33 if FREETZ_TYPE_LANG_DE select FREETZ_AVM_VERSION_04_49 if ! FREETZ_TYPE_LANG_DE bool "Fon" config FREETZ_TYPE_FON_5010 select FREETZ_AVM_VERSION_04_40 bool "Fon 5010" config FREETZ_TYPE_FON_5050 select FREETZ_AVM_VERSION_04_30 bool "Fon 5050" config FREETZ_TYPE_FON_5124 select FREETZ_AVM_VERSION_04_76 bool "Fon 5124" config FREETZ_TYPE_FON_5140 select FREETZ_AVM_VERSION_04_67 bool "Fon 5140" config FREETZ_TYPE_FON_WLAN select FREETZ_AVM_VERSION_04_33 if FREETZ_TYPE_LANG_DE select FREETZ_AVM_VERSION_04_49 if ! FREETZ_TYPE_LANG_DE bool "Fon WLAN" config FREETZ_TYPE_FON_WLAN_7050 select FREETZ_AVM_VERSION_04_33 bool "Fon WLAN 7050" config FREETZ_TYPE_FON_WLAN_7112 select FREETZ_AVM_VERSION_04_87 bool "Fon WLAN 7112" config FREETZ_TYPE_FON_WLAN_7113 select FREETZ_AVM_VERSION_04_80 if FREETZ_TYPE_LANG_EN select FREETZ_AVM_VERSION_04_67 if FREETZ_TYPE_LANG_DE bool "Fon WLAN 7113" config FREETZ_TYPE_FON_WLAN_7140 select FREETZ_AVM_VERSION_04_33 if FREETZ_TYPE_LANG_DE select FREETZ_AVM_VERSION_04_76 if FREETZ_TYPE_LANG_A_CH select FREETZ_AVM_VERSION_04_67 if FREETZ_TYPE_LANG_EN bool "Fon WLAN 7140" config FREETZ_TYPE_FON_WLAN_7141 select FREETZ_AVM_VERSION_04_76 bool "Fon WLAN 7141" config FREETZ_TYPE_FON_7150 select FREETZ_AVM_VERSION_04_70 bool "Fon 7150" config FREETZ_TYPE_FON_WLAN_7170 select FREETZ_AVM_VERSION_04_76 if FREETZ_TYPE_LANG_A_CH select FREETZ_AVM_VERSION_04_80 if FREETZ_TYPE_LANG_EN select FREETZ_AVM_VERSION_04_87 if FREETZ_TYPE_LANG_DE bool "Fon WLAN 7170" config FREETZ_TYPE_FON_WLAN_7240 select FREETZ_AVM_VERSION_7270_05_05 bool "Fon WLAN 7240" config FREETZ_TYPE_FON_WLAN_7270_V1 select FREETZ_TYPE_FON_WLAN_7270 bool "Fon WLAN 7270 v1" config FREETZ_TYPE_FON_WLAN_7270_V2 select FREETZ_TYPE_FON_WLAN_7270 bool "Fon WLAN 7270 v2" config FREETZ_TYPE_FON_WLAN_7270_V3 select FREETZ_TYPE_FON_WLAN_7270 bool "Fon WLAN 7270 v3" config FREETZ_TYPE_FON_WLAN_7320 select FREETZ_AVM_VERSION_7320_04_86 bool "Fon WLAN 7320" config FREETZ_TYPE_FON_WLAN_7330 select FREETZ_AVM_VERSION_7320_04_86 bool "Fon WLAN 7330" config FREETZ_TYPE_FON_WLAN_7340 select FREETZ_AVM_VERSION_7390_05_05 bool "Fon WLAN 7340" config FREETZ_TYPE_FON_WLAN_7390 select FREETZ_AVM_VERSION_7390_05_05 bool "Fon WLAN 7390" config FREETZ_TYPE_FON_WLAN_7570 select FREETZ_AVM_VERSION_7270_04_86 bool "Fon WLAN 7570 VDSL" config FREETZ_TYPE_FON_WLAN_7570_IAD bool "build firmware for Alice IAD 7570" depends on FREETZ_TYPE_FON_WLAN_7570 comment "Hint: Use replace kernel to get max filesystem size" depends on FREETZ_TYPE_FON_WLAN_7570_IAD config FREETZ_TYPE_WLAN_3020 select FREETZ_AVM_VERSION_04_33 bool "WLAN 3020" config FREETZ_TYPE_WLAN_3030 select FREETZ_AVM_VERSION_04_33 bool "WLAN 3030" config FREETZ_TYPE_WLAN_3130 select FREETZ_AVM_VERSION_04_33 bool "WLAN 3130" config FREETZ_TYPE_WLAN_3131 select FREETZ_AVM_VERSION_04_57 bool "WLAN 3131" config FREETZ_TYPE_WLAN_3170 select FREETZ_AVM_VERSION_04_57 bool "WLAN 3170" config FREETZ_TYPE_WLAN_3270 select FREETZ_AVM_VERSION_7270_05_05 bool "WLAN 3270 (v1 and v2 only)" config FREETZ_TYPE_WLAN_3270_V3 select FREETZ_AVM_VERSION_7270_05_05 bool "WLAN 3270 (v3 only)" config FREETZ_TYPE_SPEEDPORT_W501V select FREETZ_AVM_VERSION_r7203 bool "Speedport W501V" config FREETZ_TYPE_CUSTOM bool "Custom" depends on FREETZ_SHOW_ADVANCED select FREETZ_DL_OVERRIDE endchoice # "Hardware type" # config FREETZ_TYPE_FON_WLAN_7270 depends on \ FREETZ_TYPE_FON_WLAN_7270_V1 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 select FREETZ_AVM_VERSION_7270_04_86 if \ FREETZ_TYPE_FON_WLAN_7270_V1 select FREETZ_AVM_VERSION_7270_05_05 if \ (FREETZ_TYPE_FON_WLAN_7270_V2 || FREETZ_TYPE_FON_WLAN_7270_V3) bool choice prompt "Firmware language" default FREETZ_TYPE_LANG_DE config FREETZ_TYPE_LANG_DE bool "de - deutsch" depends on \ ! FREETZ_TYPE_FON_5010 && \ ! FREETZ_TYPE_FON_5124 && \ ! FREETZ_TYPE_FON_WLAN_7340 && \ ! FREETZ_TYPE_FON_WLAN_7570 config FREETZ_TYPE_LANG_A_CH bool "a-ch - deutsch" depends on \ FREETZ_TYPE_FON_5010 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_WLAN_7170 \ config FREETZ_TYPE_LANG_EN bool "en - international" depends on \ FREETZ_TYPE_FON || \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 \ endchoice # "Firmware language" # config FREETZ_TYPE_LANGUAGE string default "de" if FREETZ_TYPE_LANG_DE default "a-ch" if FREETZ_TYPE_LANG_A_CH default "en" if FREETZ_TYPE_LANG_EN config FREETZ_TYPE_LABOR bool "Beta/Labor" depends on \ FREETZ_TYPE_LANG_DE && \ ( \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 \ ) default n help Enable this to compile the mod based on an AVM "beta/labor" firmware. choice prompt "Labor version" depends on FREETZ_TYPE_LABOR default FREETZ_TYPE_LABOR_PREVIEW # config FREETZ_TYPE_LABOR_DSL # bool "DSL" # help # FRITZ!Lab DSL: This release optimizes the DSL (Digital Subscriber # Line) software and adds related graphs. config FREETZ_TYPE_LABOR_PREVIEW bool "Preview" depends on \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 help Labor Preview endchoice # "Labor version" # config FREETZ_TYPE_ALIEN_HARDWARE bool "Compile image for \"alien\" hardware" depends on \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7570 default n help Enable this to compile the mod image for another hardware type choice prompt "Alien hardware type" depends on FREETZ_TYPE_ALIEN_HARDWARE # default FREETZ_TYPE_SINUS_W500V_7150 if FREETZ_TYPE_FON_7150 default FREETZ_TYPE_SPEEDPORT_W701V_7170 if FREETZ_TYPE_FON_WLAN_7170 default FREETZ_TYPE_7240_7270 if FREETZ_TYPE_FON_WLAN_7270_V2 default FREETZ_TYPE_72702_72701 if FREETZ_TYPE_FON_WLAN_7270_V1 # config FREETZ_TYPE_SINUS_W500V_7150 # bool "Sinus W500V" # depends on FREETZ_TYPE_FON_7150 # select FREETZ_MODULE_jffs2 # help # Enable this to compile a mod image for T-Com Sinus W500V based # on a 7150 image. config FREETZ_TYPE_SPEEDPORT_W701V_7170 bool "W701V" depends on FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE select FREETZ_REMOVE_FTPD select FREETZ_REMOVE_MEDIASRV select FREETZ_REMOVE_PRINTSERV select FREETZ_REMOVE_PRINTSERV_MODULE if ! FREETZ_MODULE_usblp select FREETZ_REMOVE_SMBD help Enable this to compile a mod image for T-Com Speedport W701V based on a 7170 image. config FREETZ_TYPE_SPEEDPORT_W900V_7170 bool "W900V" depends on FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE help Enable this to compile a mod image for T-Com Speedport W900V based on a 7170 image. config FREETZ_TYPE_SPEEDPORT_W920V_7570 bool "W920V" depends on FREETZ_TYPE_FON_WLAN_7570 help Enable this to compile a mod image for T-Com Speedport W920V based on a 7570 image. config FREETZ_TYPE_3170_7170 bool "3170" depends on FREETZ_TYPE_FON_WLAN_7170 select FREETZ_REMOVE_VOIPD select FREETZ_REMOVE_VOIP_ISDN select FREETZ_REMOVE_CAPIOVERTCP help Enable this to compile a mod image for FritzBox FON WLAN 3170 based on a 7170 image. config FREETZ_TYPE_7112_7170 bool "7112" depends on FREETZ_TYPE_FON_WLAN_7170 select FREETZ_REMOVE_FTPD select FREETZ_REMOVE_MEDIASRV select FREETZ_REMOVE_PRINTSERV select FREETZ_REMOVE_PRINTSERV_MODULE if ! FREETZ_MODULE_usblp select FREETZ_REMOVE_SMBD help Enable this to compile a mod image for FritzBox Fon WLAN 7112 based on a 7170 image. config FREETZ_TYPE_7113_7170 bool "7113" depends on FREETZ_TYPE_FON_WLAN_7170 select FREETZ_REMOVE_FTPD select FREETZ_REMOVE_MEDIASRV select FREETZ_REMOVE_PRINTSERV select FREETZ_REMOVE_PRINTSERV_MODULE if ! FREETZ_MODULE_usblp select FREETZ_REMOVE_SMBD help Enable this to compile a mod image for FritzBox Fon WLAN 7113 based on a 7170 image. config FREETZ_TYPE_7140_7170 bool "7140" depends on FREETZ_TYPE_FON_WLAN_7170 help Enable this to compile a mod image for FritzBox FON WLAN 7140 based on a 7170 image. config FREETZ_TYPE_7141_7170 bool "7141" depends on FREETZ_TYPE_FON_WLAN_7170 help Enable this to compile a mod image for FritzBox FON WLAN 7141 based on a 7170 image. config FREETZ_TYPE_7240_7270 bool "7240" depends on FREETZ_TYPE_FON_WLAN_7270_V2 || FREETZ_TYPE_FON_WLAN_7270_V3 help Enable this to compile a mod image for FritzBox FON WLAN 7240 based on a 7270 image. config FREETZ_TYPE_7270_7270 bool "7270 v1" depends on FREETZ_TYPE_FON_WLAN_7270_V2 && FREETZ_REPLACE_KERNEL_AVAILABLE select FREETZ_REPLACE_KERNEL # select FREETZ_REMOVE_AVM_VPN # select FREETZ_REMOVE_CAPIOVERTCP # select FREETZ_REMOVE_NTFS # select FREETZ_REMOVE_SMBD # select FREETZ_REMOVE_UMTSD # select FREETZ_REMOVE_VOIPD # select FREETZ_REMOVE_VOIP_ISDN # select FREETZ_REMOVE_WEBDAV help Enable this to compile a mod image for FritzBox FON WLAN 7270 v1 based on a 7270 v2 image. Caution: To fit into 8MB ROM some AVM components (e.g. telephony) have to be removed. Please use usbroot for a full featured image. config FREETZ_TYPE_72702_72701 bool "7270 v2" depends on FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_REPLACE_KERNEL_AVAILABLE help Enable this to compile a mod image for FritzBox FON WLAN 7270 v2 based on a 7270 v1 image. config FREETZ_TYPE_IAD_3331_7170 bool "Alice IAD 3331" depends on FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE select FREETZ_REMOVE_PIGLET_V1 if FREETZ_SHOW_ADVANCED select FREETZ_ENFORCE_URLADER_SETTINGS help Enable this to compile a mod image for Alice IAD 3331 based on a 7170 image. The firmware_version has to be enforced, because this variable is unset in the 7170_HN bootloader. Initial flashing might only be possible via ./tools/push_firmware endchoice # "Alien hardware type" # config FREETZ_AVM_VERSION_STRING string default "04.30" if FREETZ_AVM_VERSION_04_30 default "04.33" if FREETZ_AVM_VERSION_04_33 default "04.40" if FREETZ_AVM_VERSION_04_40 default "04.49" if FREETZ_AVM_VERSION_04_49 default "04.57" if FREETZ_AVM_VERSION_04_57 default "04.67" if FREETZ_AVM_VERSION_04_67 default "04.70" if FREETZ_AVM_VERSION_04_70 default "04.76" if FREETZ_AVM_VERSION_04_76 default "04.80" if FREETZ_AVM_VERSION_04_80 default "04.87" if FREETZ_AVM_VERSION_04_87 default "7270_04.86" if FREETZ_AVM_VERSION_7270_04_86 default "7270_05.05" if FREETZ_AVM_VERSION_7270_05_05 default "7320_04.86" if FREETZ_AVM_VERSION_7320_04_86 default "7390_04.90" if FREETZ_AVM_VERSION_7390_04_90 default "7390_05.05" if FREETZ_AVM_VERSION_7390_05_05 default "r7203" if FREETZ_AVM_VERSION_r7203 choice prompt "Annex" depends on FREETZ_TYPE_LANG_EN && \ ! FREETZ_TYPE_FON_WLAN_7113 && \ ! FREETZ_TYPE_FON_WLAN_7270 && \ ! FREETZ_TYPE_FON_WLAN_7340 && \ ! FREETZ_TYPE_FON_WLAN_7390 && \ ! FREETZ_TYPE_FON_WLAN_7570 default FREETZ_TYPE_ANNEX_B config FREETZ_TYPE_ANNEX_A bool "A" config FREETZ_TYPE_ANNEX_B bool "B" endchoice # prompt "Annex" # config FREETZ_TYPE_PREFIX string default "300ip_as_fon" if FREETZ_TYPE_300IP_AS_FON default "2170" if FREETZ_TYPE_2170 default "3020" if FREETZ_TYPE_WLAN_3020 default "3030" if FREETZ_TYPE_WLAN_3030 default "3130" if FREETZ_TYPE_WLAN_3130 default "3131" if FREETZ_TYPE_WLAN_3131 default "3170" if FREETZ_TYPE_WLAN_3170 default "3270" if FREETZ_TYPE_WLAN_3270 default "3270_v3" if FREETZ_TYPE_WLAN_3270_V3 default "fon" if FREETZ_TYPE_FON default "5010" if FREETZ_TYPE_FON_5010 default "5050" if FREETZ_TYPE_FON_5050 default "5124" if FREETZ_TYPE_FON_5124 default "5140" if FREETZ_TYPE_FON_5140 default "fon_wlan" if FREETZ_TYPE_FON_WLAN default "7050" if FREETZ_TYPE_FON_WLAN_7050 default "7112" if FREETZ_TYPE_FON_WLAN_7112 default "7113" if FREETZ_TYPE_FON_WLAN_7113 default "7140" if FREETZ_TYPE_FON_WLAN_7140 default "7141" if FREETZ_TYPE_FON_WLAN_7141 default "7150" if FREETZ_TYPE_FON_7150 default "7170" if FREETZ_TYPE_FON_WLAN_7170 default "7240" if FREETZ_TYPE_FON_WLAN_7240 && ! FREETZ_TYPE_LABOR # default "7240_preview" if FREETZ_TYPE_FON_WLAN_7240 && FREETZ_TYPE_LABOR_PREVIEW default "7270_v1" if FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_LABOR # default "7270_v1_preview" if FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_LABOR_PREVIEW default "7270_v2" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7270_7270 ) && \ ! FREETZ_TYPE_LABOR default "7270_v2_preview" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7270_7270 ) && \ FREETZ_TYPE_LABOR_PREVIEW default "7270_v3" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7240_7270 ) && \ ! FREETZ_TYPE_LABOR default "7270_v3_preview" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7240_7270 ) && \ FREETZ_TYPE_LABOR_PREVIEW default "7320" if FREETZ_TYPE_FON_WLAN_7320 && ! FREETZ_TYPE_LABOR default "7330" if FREETZ_TYPE_FON_WLAN_7330 default "7340" if FREETZ_TYPE_FON_WLAN_7340 default "7390" if FREETZ_TYPE_FON_WLAN_7390 && ! FREETZ_TYPE_LABOR default "7390_preview" if FREETZ_TYPE_FON_WLAN_7390 && FREETZ_TYPE_LABOR_PREVIEW default "7570" if FREETZ_TYPE_FON_WLAN_7570 default "W501V" if FREETZ_TYPE_SPEEDPORT_W501V default "custom" if FREETZ_TYPE_CUSTOM config FREETZ_TYPE_PREFIX_ALIEN_HARDWARE string default "W500V_" if FREETZ_TYPE_SINUS_W500V_7150 default "W701V_" if FREETZ_TYPE_SPEEDPORT_W701V_7170 default "W900V_" if FREETZ_TYPE_SPEEDPORT_W900V_7170 default "W920V_" if FREETZ_TYPE_SPEEDPORT_W920V_7570 default "3170_" if FREETZ_TYPE_3170_7170 default "7112_" if FREETZ_TYPE_7112_7170 default "7113_" if FREETZ_TYPE_7113_7170 default "7140_" if FREETZ_TYPE_7140_7170 default "7141_" if FREETZ_TYPE_7141_7170 default "7240_" if FREETZ_TYPE_7240_7270 comment "Custom options -------------------------" depends on FREETZ_TYPE_CUSTOM config FREETZ_INSTALL_BASE bool select FREETZ_PACKAGE_MOD select FREETZ_PACKAGE_HASERL select FREETZ_LIB_ld_uClibc select FREETZ_LIB_libcrypt select FREETZ_LIB_libdl select FREETZ_LIB_libgcc_s select FREETZ_LIB_libm select FREETZ_LIB_libnsl select FREETZ_LIB_libpthread select FREETZ_LIB_librt select FREETZ_LIB_libuClibc select FREETZ_LIB_libfreetz if FREETZ_HAS_USB_HOST default y help This is mandatory config FREETZ_REPLACE_BUSYBOX bool select FREETZ_BUSYBOX_REALPATH default y help This is mandatory config FREETZ_SHOW_ADVANCED bool "Show advanced options" default n help Show advanced Options for patching the firmware. This is only useful for experienced users who really know what they are doing if FREETZ_SHOW_ADVANCED comment "Replace kernel (currently not available)" depends on ! FREETZ_REPLACE_KERNEL_AVAILABLE config FREETZ_REPLACE_KERNEL_AVAILABLE bool depends on \ ! (FREETZ_TYPE_FON && FREETZ_TYPE_LANG_EN) && \ ! FREETZ_TYPE_LABOR default y config FREETZ_REPLACE_KERNEL bool "Replace kernel" depends on FREETZ_REPLACE_KERNEL_AVAILABLE select FREETZ_MODULE_fuse if ( \ FREETZ_AVM_VERSION_7270_04_86 || \ FREETZ_AVM_VERSION_7270_05_05 || \ FREETZ_AVM_VERSION_7320_04_86 || \ FREETZ_AVM_VERSION_7390_04_90 || \ FREETZ_AVM_VERSION_7390_05_05 \ ) select FREETZ_MODULE_jffs2 if FREETZ_AVM_VERSION_7320_04_86 select FREETZ_MODULE_msdos if FREETZ_AVM_VERSION_7270_05_05 select FREETZ_MODULE_usbcore if \ FREETZ_KERNEL_LAYOUT_UR8 && FREETZ_AVM_VERSION_7270_04_86 select FREETZ_MODULE_vfat if FREETZ_AVM_VERSION_7270_05_05 default n help Replace AVM kernel with self-built kernel. endif # FREETZ_SHOW_ADVANCED # comment "Hint: Select build toolchain if you want to enable IPv6 support" depends on \ ( \ FREETZ_HAS_AVM_IPV6 || \ (FREETZ_SHOW_ADVANCED && FREETZ_REPLACE_KERNEL_AVAILABLE) \ ) && \ (FREETZ_TARGET_UCLIBC_VERSION_0_9_28 && FREETZ_DOWNLOAD_TOOLCHAIN) config FREETZ_TARGET_IPV6_SUPPORT bool "Enable IPv6 support" depends on \ ( \ FREETZ_HAS_AVM_IPV6 || \ (FREETZ_SHOW_ADVANCED && FREETZ_REPLACE_KERNEL_AVAILABLE) \ ) && \ ! (FREETZ_TARGET_UCLIBC_VERSION_0_9_28 && FREETZ_DOWNLOAD_TOOLCHAIN) select FREETZ_REPLACE_KERNEL if ! (FREETZ_HAS_AVM_IPV6) select FREETZ_MODULE_ipv6 if ! (FREETZ_HAS_AVM_IPV6) && FREETZ_REPLACE_KERNEL select FREETZ_BUSYBOX_IP select FREETZ_BUSYBOX_FEATURE_IP_ADDRESS select FREETZ_BUSYBOX_FEATURE_IP_LINK select FREETZ_BUSYBOX_FEATURE_IP_ROUTE select FREETZ_BUSYBOX_FEATURE_IP_TUNNEL default n help Copies the ipv6 kernel module to the firmware and enables ipv6 support in uClibc and busybox. Shows additional options for busybox and iptables and other packages. To use IPv6 with Fritz!Box, at least the kernel, ucLibc and busybox have to be recompiled with IPv6 enabled. The toolchain will automatically be rebuild to achieve this. It is also recommended to include the package iptables/ip6tables for firewall settings. config FREETZ_TARGET_REF_4MB bool default y if \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5010 || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_5140 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_SPEEDPORT_W501V || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 || \ FREETZ_TYPE_WLAN_3130 || \ FREETZ_TYPE_WLAN_3131 || \ FREETZ_TYPE_WLAN_3170 config FREETZ_TARGET_REF_8MB bool default y if \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_WLAN_7112 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7170 || \ ( FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_72702_72701 ) config FREETZ_TARGET_REF_16MB bool default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ ( FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_72702_72701 ) || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 config FREETZ_TARGET_REF string "Target ref" if FREETZ_TYPE_CUSTOM default "4mb" if FREETZ_TARGET_REF_4MB default "8mb" if FREETZ_TARGET_REF_8MB default "16mb" if FREETZ_TARGET_REF_16MB config FREETZ_KERNEL_REF_4MB bool default y if \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5010 || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_5140 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_SPEEDPORT_W501V || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 || \ FREETZ_TYPE_WLAN_3130 || \ FREETZ_TYPE_WLAN_3131 || \ FREETZ_TYPE_WLAN_3170 config FREETZ_KERNEL_REF_8MB bool default y if \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_WLAN_7112 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7170 || \ (FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_72702_72701) config FREETZ_KERNEL_REF_16MB bool default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ (FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_72702_72701) || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 config FREETZ_KERNEL_REF string "Kernel ref" if FREETZ_TYPE_CUSTOM default "4mb" if FREETZ_KERNEL_REF_4MB default "8mb" if FREETZ_KERNEL_REF_8MB default "16mb" if FREETZ_KERNEL_REF_16MB config FREETZ_KERNEL_MTD_SIZE int "Kernel (64K blocks)" if FREETZ_TYPE_CUSTOM default 119 if \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7112 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_WLAN_7141 || \ (FREETZ_TYPE_FON_WLAN_7170 && ! FREETZ_TYPE_3170_7170) || \ (FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_72702_72701) || \ FREETZ_TYPE_7270_7270 default 122 if \ FREETZ_TYPE_FON_WLAN_7570_IAD && ! FREETZ_REPLACE_KERNEL default 238 if \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 default 244 if \ FREETZ_TYPE_FON_WLAN_7570_IAD && FREETZ_REPLACE_KERNEL default 246 if \ FREETZ_TYPE_FON_WLAN_7240 || \ (FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_72702_72701) || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ (FREETZ_TYPE_FON_WLAN_7570 && ! FREETZ_TYPE_FON_WLAN_7570_IAD) || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default 59 help Number of 64K blocks in the kernel mtd device. config FREETZ_HAS_AVM_AURA_USB bool "Has remote USB connection (AURA = AVM USB Remote-Architcture)" if FREETZ_TYPE_CUSTOM select FREETZ_REMOVE_AURA_USB if ! FREETZ_HAS_USB_HOST default y if \ FREETZ_HAS_USB_HOST || \ FREETZ_TYPE_SPEEDPORT_W701V_7170 || \ FREETZ_TYPE_7112_7170 || \ FREETZ_TYPE_7113_7170 default n help Select this if your original firmware has an aura-usb-daemon (remote USB connection, USB-Fernanschluss) config FREETZ_HAS_AVM_MINID bool "Has mini-daemon (minid)" if FREETZ_TYPE_CUSTOM select FREETZ_REMOVE_MINID if \ FREETZ_TYPE_7113_7170 || \ FREETZ_TYPE_7112_7170 || \ FREETZ_TYPE_3170_7170 || \ FREETZ_TYPE_SPEEDPORT_W701V_7170 default y if \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if your original firmware has a mini-daemon (minid) config FREETZ_HAS_AVM_NTFS bool "Has AVM NTFS" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if your original firmware has ntfs support. config FREETZ_HAS_AVM_IPV6 bool "Has AVM IPv6" if FREETZ_TYPE_CUSTOM select FREETZ_TARGET_IPV6_SUPPORT default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if your original firmware has IPv6 support. config FREETZ_HAS_AVM_WEBDAV bool "Has AVM WebDAV" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if your original firmware has WebDAV support. config FREETZ_HAS_AVM_INETD bool "Has AVM inetd" if FREETZ_TYPE_CUSTOM select FREETZ_PACKAGE_INETD default y if \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 default n help Select this if your original firmware has inetd support. config FREETZ_HAS_AVM_EXT3 bool "Has AVM ext3 built into the kernel" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7390 default n help Select this if your original firmware has ext3 support into the kernel. config FREETZ_HAS_AVM_TR069 bool "Has AVM tr069" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if your original firmware has tr069 support (libtr069, libtr064). config FREETZ_HAS_CHRONYD bool "Has chronyd" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 default n help Select this if you have a box with chronyd. config FREETZ_HAS_DECT bool "Has DECT" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_SPEEDPORT_W900V_7170 default n help Select this if you have a box with DECT. config FREETZ_HAS_OPENSSL_LIBS bool "Has libssl" if FREETZ_TYPE_CUSTOM default n if \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON_5010 || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_SPEEDPORT_W501V || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 default y help Select this if you have a box with AVM libcrypto and libssl. config FREETZ_HAS_LSOF bool "Has lsof" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if you have a box with lsof binary. config FREETZ_HAS_NAS bool "Has NAS" if FREETZ_TYPE_CUSTOM select FREETZ_BUSYBOX_TAR_OLDGNU_COMPATIBILITY default y if \ ( \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 \ ) default n help Select this if you have a box with NAS support. config FREETZ_HAS_PHONE bool "Has Phone" if FREETZ_TYPE_CUSTOM default n if \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 || \ FREETZ_TYPE_WLAN_3130 || \ FREETZ_TYPE_WLAN_3131 || \ FREETZ_TYPE_WLAN_3170 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default y help Select this if you have a box with phone support. config FREETZ_HAS_STRACE bool "Has strace" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if you have a box with strace binary. config FREETZ_HAS_TAM bool "Has TAM" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 default n help Select this if you have a box with TAM (Telephone Answering Machine) support. config FREETZ_HAS_UDEV bool "udev" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if you have a box with udev. config FREETZ_HAS_USB_CLIENT bool "USB client" if FREETZ_TYPE_CUSTOM default y if \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 || \ FREETZ_TYPE_WLAN_3131 || \ FREETZ_TYPE_WLAN_3170 default n help Select this if you have a box with USB. config FREETZ_HAS_USB_HOST bool "USB host" if FREETZ_TYPE_CUSTOM default n if \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5010 || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_5140 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_FON_WLAN_7112 || \ FREETZ_TYPE_7112_7170 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_7113_7170 || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 || \ FREETZ_TYPE_SINUS_W500V_7150 || \ FREETZ_TYPE_SPEEDPORT_W501V || \ FREETZ_TYPE_SPEEDPORT_W701V_7170 default y help Select this if your USB port is a host adapter. config FREETZ_HAS_USB_HOST_AVM bool "AVM USB host" if FREETZ_TYPE_CUSTOM depends on FREETZ_HAS_USB_HOST default y if \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_WLAN_3130 || \ FREETZ_TYPE_WLAN_3131 || \ FREETZ_TYPE_WLAN_3170 default n help Select this if you have a box with AVM USB host. config FREETZ_HAS_AVM_E2FSPROGS bool "Has AVM e2fsprogs files" if FREETZ_TYPE_CUSTOM default y if\ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 default n help Select this if you have a firmware with blkid, fsck and mkfs. config FREETZ_HAS_WLAN bool "Has WLAN" if FREETZ_TYPE_CUSTOM default n if \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5010 || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_5140 default y help Select this if you have a box with WLAN. comment "Mod ------------------------------------" choice prompt "Freetz Language" default FREETZ_LANG_DE if FREETZ_TYPE_LANG_DE default FREETZ_LANG_DE if FREETZ_TYPE_LANG_A_CH default FREETZ_LANG_EN if FREETZ_TYPE_LANG_EN config FREETZ_LANG_DE bool "de - deutsch" config FREETZ_LANG_EN bool "en - english" endchoice # "Freetz Language" # config FREETZ_LANG_STRING string default "de" if FREETZ_LANG_DE default "en" if FREETZ_LANG_EN menu "Patches" # INCLUDE_BEGIN patches/Config.in comment "Web menu patches -----------------------" config FREETZ_PATCH_VCC bool "Patch 2nd VCC" depends on FREETZ_HAS_PHONE && FREETZ_TYPE_LANG_DE default n help Patches the setting for 2nd VCC into web menu. It also adds two additional settings (PCR & SCR) not available in the original AVM firmware. Please also note that it is not possible to change the value of traffic_class setting via the web-interface. You have to do it some other way (e.g. using FBEditor or nvi ar7.cfg). Warning: Please read up on what each VCC setting means before setting/changing it. Besides not working wrong values may cause additional costs for you as your provider may treat it as simultaneous dial-in attempts (Doppeleinwahl). The correct values for an 1&1-Komplettanschluss are: VPI = 1; VCI = 35; traffic_class = atm_traffic_class_CBR; pcr = 603; scr = 0; config FREETZ_PATCH_ATA bool "Patch ATA" depends on \ FREETZ_TYPE_SPEEDPORT_W501V default n help Patches the ATA mode configuration pages into the web menu. config FREETZ_PATCH_ENUM bool "Patch enum" depends on \ FREETZ_TYPE_LANG_DE && \ ( \ FREETZ_TYPE_FON || \ FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_FON_WLAN_7140 \ ) default n help Patches the enum configuration pages into the web menu. config FREETZ_PATCH_DSL_EXPERT bool # bool "Patch extended DSL settings" depends on \ ! FREETZ_TYPE_LABOR_DSL && \ ! FREETZ_REMOVE_DSLD && \ FREETZ_TYPE_LANG_DE && \ ( \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 \ ) default n help Patches the extended dsl-settings from labor-dsl into all-in-one-firmwares. config FREETZ_ADD_REGEXT_GUI bool "Patch GUI to enable external SIP connections" depends on \ FREETZ_TYPE_FON_WLAN_7570 || \ ( \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7390 \ ) && FREETZ_TYPE_LANG_DE default n help Patches the WebUI and add a checkbox to enable setting "reg_from_outside" in the voip.conf. #config FREETZ_PATCH_INTERNATIONAL # bool "Patch international" # depends on FREETZ_HAS_PHONE && FREETZ_TYPE_LANG_DE # default y # help # Reveals some options from the international firmware in the web menu. config FREETZ_PATCH_ALARMCLOCK bool "Patch third alarm-clock" depends on ( \ FREETZ_TYPE_FON_WLAN_7150 || \ FREETZ_TYPE_FON_WLAN_7112 || \ FREETZ_TYPE_FON_WLAN_7141 || \ (FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE) || \ FREETZ_TYPE_FON_WLAN_7270_V1 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7570 \ ) default n help Adds a third alarm-clock to AVM-Webinterface config FREETZ_PATCH_SIGNED bool "Patch web menu signed message" default n help Hides the "unsupported changes" message from the web interface. if FREETZ_HAS_USB_HOST comment "USB storage patches --------------------" config FREETZ_PATCH_FREETZMOUNT bool "FREETZMOUNT: Patch AVMs hotplug scripts, USB storage names, ..." select FREETZ_USBSTORAGE_AUTOMOUNT select FREETZ_BUSYBOX_BLKID if FREETZ_REMOVE_AVM_E2FSPROGS || ! FREETZ_HAS_AVM_E2FSPROGS select FREETZ_BUSYBOX_BLKID_TYPE if FREETZ_REMOVE_AVM_E2FSPROGS || ! FREETZ_HAS_AVM_E2FSPROGS select FREETZ_BUSYBOX_VOLUMEID default y help 1. Replaces and deselects usb-storage patch. - The names of USB storage directories can be defined by WebIF (default uStorXY) (or by volume LABEL). 2. Replaces and deselects autorun.sh/autoend.sh patch. - autorun/autoend behaviour can be activated/deactivated via WebIF. - autorun/autoend are useful to start/terminate applications located on USB devices, eg apache, samba or even swapfiles, after connecting or before disconnecting of USB devices. 3. Auto-mounted USB storage devices will be fully accessible, eg it is now possible to put user home directories for (e.g. for FTP) on a FAT32-formatted partition and permit shell and FTP users to actually write to their own home directories. 4. Avoid deleting whole filesystems on USB devices. 5. Enhanced behaviour during mounting and unmounting. 6. Provides mount-by-label feature. It is highly recommended to select this patch. config FREETZ_USBSTORAGE_AUTOMOUNT bool "Automount filesystems" depends on FREETZ_PATCH_FREETZMOUNT default y help The filesystems ext2, ext3, ext4, fat, hfs, hfs+, ntfs and reiserfs and swap are mounted automatically. Detection is done by blkid utility . It depends on the original firmware which of the following points you have to select. if FREETZ_USBSTORAGE_AUTOMOUNT config FREETZ_AUTOMOUNT_EXT2 bool "ext2" select FREETZ_BUSYBOX_VOLUMEID_EXT select FREETZ_MODULE_ext2 default n help This adds ext2 module to your firmware. config FREETZ_AUTOMOUNT_EXT3 bool "ext3" select FREETZ_BUSYBOX_VOLUMEID_EXT select FREETZ_MODULE_ext3 if ! FREETZ_HAS_AVM_EXT3 default n help This adds ext3 module to your firmware. config FREETZ_AUTOMOUNT_EXT4 bool "ext4" depends on FREETZ_KERNEL_VERSION_2_6_28 || \ FREETZ_KERNEL_VERSION_2_6_32 select FREETZ_BUSYBOX_VOLUMEID_EXT select FREETZ_MODULE_ext4 default n help This adds ext4 module to your firmware. config FREETZ_AUTOMOUNT_FAT bool "fat" select FREETZ_BUSYBOX_VOLUMEID_FAT default n help This enables detection of fat partitions. config FREETZ_AUTOMOUNT_HFS bool "HFS" select FREETZ_BUSYBOX_VOLUMEID_HFS select FREETZ_MODULE_hfs default n help This adds hfs module to your firmware. config FREETZ_AUTOMOUNT_HFS_PLUS bool "HFS+" select FREETZ_BUSYBOX_VOLUMEID_HFS select FREETZ_MODULE_hfsplus default n help This adds hfs+ module to your firmware. config FREETZ_AUTOMOUNT_LUKS bool "luks" select FREETZ_BUSYBOX_VOLUMEID_LUKS default n help This enables detection (not mounting) of luks partitions. config FREETZ_AUTOMOUNT_NTFS bool "NTFS" select FREETZ_PACKAGE_NTFS if ! FREETZ_HAS_AVM_NTFS select FREETZ_BUSYBOX_VOLUMEID_NTFS default n help This adds ntfs-3g mount helper to your firmware. config FREETZ_AUTOMOUNT_REISER_FS bool "ReiserFS" select FREETZ_BUSYBOX_VOLUMEID_REISERFS select FREETZ_MODULE_reiserfs default n help This adds reiserfs module to your firmware. config FREETZ_AUTOMOUNT_LINUXSWAP bool "swap" select FREETZ_BUSYBOX_VOLUMEID_LINUXSWAP default n help This enables detection of linux-swap partitions. endif config FREETZ_PATCH_MAXDEVCOUNT bool "Raise the count of connectable usb device to 9" default n help Use this patch if you would connect more than 3 device to the box config FREETZ_PATCH_MULTIPLE_PRINTERS bool "Add support for multiple printers" depends on ! FREETZ_REMOVE_PRINTSERV && \ ( \ ( FREETZ_TYPE_FON_WLAN_7140 && ! FREETZ_TYPE_LANG_DE ) || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_WLAN_3131 || \ FREETZ_TYPE_WLAN_3170 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_7150 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7270_V1 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 \ ) # no patch available atm: 7140_DE 2070 3070 3050 3130 default n help Use this patch if you want to use more than one printer. endif comment "Removal patches ------------------------" config FREETZ_REMOVE_ANNEX_A_FIRMWARE bool "Remove Annex A firmware file" depends on \ FREETZ_TYPE_FON_WLAN_7270_V2 || \ FREETZ_TYPE_FON_WLAN_7270_V3 || \ FREETZ_TYPE_FON_WLAN_7320 default n help Remove lib/modules/dsp_ur8/ur8-A-dsl.bin. This saves about 400 KB of uncompressed data size. config FREETZ_REMOVE_ANNEX_B_FIRMWARE bool "Remove Annex B firmware file" depends on \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 default n help Remove lib/modules/dsp_ur8/ur8-B-dsl.bin. This saves about 400 KB of uncompressed data size. menu "Remove v1/v2 piglet file(s)" depends on FREETZ_SHOW_ADVANCED && \ ( \ (FREETZ_TYPE_FON_WLAN_7170 && ! FREETZ_TYPE_ALIEN_HARDWARE) || \ FREETZ_TYPE_SPEEDPORT_W701V_7170 || \ FREETZ_TYPE_SPEEDPORT_W900V_7170 || \ FREETZ_TYPE_IAD_3331_7170 \ ) config FREETZ_REMOVE_PIGLET_V1 bool "Remove v1 piglet file(s)" help The firmware of this model contains double piglet files. Which instance is needed depends on the hardware version (v1 or v2) of your box. You can safely remove the unneeded instance. Hint: If "echo $HWRevision_BitFileCount" returns "1" you could select this patch. config FREETZ_REMOVE_PIGLET_V2 bool "Remove v2 piglet file(s)" help The firmware of this model contains double piglet files. Which instance is needed depends on the hardware version (v1 or v2) of your box. You can safely remove the unneeded instance. Hint: If "echo $HWRevision_BitFileCount" returns "" (nothing) you could select this patch. endmenu comment "WARNING: Both (v1 and v2) piglet files are selected for removal." depends on \ FREETZ_REMOVE_PIGLET_V1 && \ FREETZ_REMOVE_PIGLET_V2 menu "Remove ISDN/POTS piglet file(s) (EXPERIMENTAL)" depends on FREETZ_SHOW_ADVANCED && \ ( \ FREETZ_TYPE_FON_5113 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_5113_7170 || \ FREETZ_TYPE_7113_7170 \ ) config FREETZ_REMOVE_PIGLET_ISDN bool "Remove ISDN piglet file(s) (EXPERIMENTAL)" help The firmware of this model contains separate piglet files for ISDN and POTS. Depending on your type of fixed line usage you can safely remove the unneeded bitfile(s). Hint: If you are using POTS fixed line you could select this patch. config FREETZ_REMOVE_PIGLET_POTS bool "Remove POTS piglet file(s) (EXPERIMENTAL)" help The firmware of this model contains separate piglet files for ISDN and POTS. Depending on your type of fixed line usage you can safely remove the unneeded bitfile(s). Hint: If you are using ISDN fixed line you could select this patch. endmenu comment "WARNING: Both (ISDN and POTS) piglet files are selected for removal." depends on \ FREETZ_REMOVE_PIGLET_ISDN && \ FREETZ_REMOVE_PIGLET_POTS config FREETZ_REMOVE_ASSISTANT bool "Remove assistant" default n depends on \ ! ( \ ( \ FREETZ_TYPE_FON_5124 || \ FREETZ_TYPE_FON_WLAN_7140 || \ FREETZ_TYPE_FON_WLAN_7170 \ ) \ && FREETZ_TYPE_LANG_EN \ ) help Removes the installation assistant from the web menu. config FREETZ_REMOVE_AURA_USB bool "Remove remote USB connection (AURA = AVM USB Remote-Architcture)" if FREETZ_SHOW_ADVANCED default n depends on FREETZ_HAS_AVM_AURA_USB help Remove the aura-usb-daemon (remote USB connection, USB-Fernanschluss) and some related files. This patch only removes the files, not the settings in AVM's web interface. config FREETZ_REMOVE_USB_MODULE bool "Remove avalanche_usb.ko" if FREETZ_SHOW_ADVANCED depends on FREETZ_HAS_USB_CLIENT default n help Removes avalanche_usb.ko to save 60kB uncompressed space. config FREETZ_REMOVE_NAS bool "Remove AVM NAS Webinterface" default n depends on FREETZ_HAS_NAS && FREETZ_TYPE_LANG_DE help Removes the AVM NAS Webinterface and internal memory file (saves about 390 KB in compressed image). config FREETZ_REMOVE_AVM_VPN bool "Remove AVM vpn" if FREETZ_SHOW_ADVANCED default n depends on \ FREETZ_TYPE_2170 || \ FREETZ_TYPE_FON_7150 || \ (FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE) || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_FON_WLAN_7570 || \ FREETZ_TYPE_WLAN_3170 || \ FREETZ_TYPE_WLAN_3270 || \ FREETZ_TYPE_WLAN_3270_V3 help Remove AVM's vpn and some other related files This patch removes the files and related Web UI entrys, but not the vpn settings. This will save about 120kB compressed size. config FREETZ_REMOVE_WEBSRV bool "Remove AVM web server (replaced by httpd)" depends on \ ! FREETZ_TYPE_2170 \ && ! FREETZ_TYPE_FON_5124 \ && ! FREETZ_TYPE_FON_5140 \ && ! FREETZ_TYPE_FON_WLAN_7112 \ && ! ( FREETZ_TYPE_FON_WLAN_7140 && FREETZ_TYPE_LANG_EN ) \ && ! ( FREETZ_TYPE_FON_WLAN_7140 && FREETZ_TYPE_LANG_A_CH ) \ && ! ( FREETZ_TYPE_FON && FREETZ_TYPE_LANG_EN ) \ && ! ( FREETZ_TYPE_300IP_AS_FON && FREETZ_TYPE_LANG_EN ) \ && ! ( FREETZ_TYPE_FON_WLAN && FREETZ_TYPE_LANG_EN ) \ && ! FREETZ_TYPE_FON_WLAN_7141 \ && ! FREETZ_TYPE_FON_WLAN_7170 \ && ! FREETZ_TYPE_FON_WLAN_7240 \ && ! FREETZ_TYPE_FON_WLAN_7270 \ && ! FREETZ_TYPE_FON_WLAN_7320 \ && ! FREETZ_TYPE_FON_WLAN_7340 \ && ! FREETZ_TYPE_FON_WLAN_7390 \ && ! FREETZ_TYPE_FON_WLAN_7570 \ && ! FREETZ_TYPE_WLAN_3131 \ && ! FREETZ_TYPE_WLAN_3170 \ && ! FREETZ_TYPE_WLAN_3270 \ && ! FREETZ_TYPE_WLAN_3270_V3 default n help Patch init scripts so BusyBox's httpd is used instead of AVM's websrv. The websrv binary will be removed from the firmware image. If "Remove UPnP daemon (igdd/upnpd)" patch is also selected and "Integrate Media Server from USB Labor firmware" is not selected, 'libwebsrv.so' will also be removed, because only those three binaries use it. comment "No brandings available to remove" depends on \ FREETZ_TYPE_SPEEDPORT_W501V menu "Remove brandings" depends on \ ! FREETZ_TYPE_SPEEDPORT_W501V comment "avm and tcom branding can't be removed" depends on \ FREETZ_TYPE_ALIEN_HARDWARE config FREETZ_REMOVE_BRANDING_1und1 bool "1&1" depends on \ FREETZ_TYPE_LANG_DE && \ ( \ FREETZ_TYPE_FON || \ FREETZ_TYPE_FON_5050 || \ FREETZ_TYPE_FON_5140 || \ FREETZ_TYPE_FON_WLAN || \ FREETZ_TYPE_FON_WLAN_7050 || \ FREETZ_TYPE_FON_WLAN_7112 || \ FREETZ_TYPE_FON_WLAN_7113 || \ FREETZ_TYPE_FON_WLAN_7141 || \ FREETZ_TYPE_FON_WLAN_7170 || \ FREETZ_TYPE_FON_WLAN_7240 || \ FREETZ_TYPE_FON_WLAN_7270 || \ FREETZ_TYPE_FON_WLAN_7320 || \ FREETZ_TYPE_FON_WLAN_7330 || \ FREETZ_TYPE_FON_WLAN_7340 || \ FREETZ_TYPE_FON_WLAN_7390 || \ FREETZ_TYPE_WLAN_3020 || \ FREETZ_TYPE_WLAN_3030 || \ FREETZ_TYPE_WLAN_3130 || \ FREETZ_TYPE_CUSTOM \ ) default n help 1&1 branding Each branding provides the web UI templates for a certain manufacturer or OEM. NOTE: Make sure not to remove the branding corresponding to the one defined in your box's boot loader environment. It can be determined by calling the following command from the box's shell prompt: echo $(cat /proc/sys/urlader/firmware_version) config FREETZ_REMOVE_BRANDING_avm bool "AVM" depends on \ ( \ FREETZ_TYPE_LANG_A_CH || \ FREETZ_TYPE_LANG_DE || \ FREETZ_TYPE_CUSTOM \ ) \ && ! FREETZ_TYPE_ALIEN_HARDWARE default n help AVM branding Each branding provides the web UI templates for a certain manufacturer or OEM. NOTE: Make sure not to remove the branding corresponding to the one defined in your box's boot loader environment. It can be determined by calling the following command from the box's shell prompt: echo $(cat /proc/sys/urlader/firmware_version) config FREETZ_REMOVE_BRANDING_avme bool "AVM international" depends on \ ( \ FREETZ_TYPE_LANG_EN || \ FREETZ_TYPE_CUSTOM \ ) default n help AVM international branding Each branding provides the web UI templates for a certain manufacturer or OEM. NOTE: Make sure not to remove the branding corresponding to the one defined in your box's boot loader environment. It can be determined by calling the following command from the box's shell prompt: echo $(cat /proc/sys/urlader/firmware_version) config FREETZ_DL_KERNEL_SITE string "Kernel site" if FREETZ_DL_OVERRIDE default "ftp.avm.de/develper/opensrc" if FREETZ_AVM_VERSION_04_30 || \ FREETZ_AVM_VERSION_04_33 || \ FREETZ_AVM_VERSION_04_40 || \ FREETZ_AVM_VERSION_04_49 || \ FREETZ_AVM_VERSION_04_57 || \ FREETZ_AVM_VERSION_04_67 || \ FREETZ_AVM_VERSION_04_70 default "@AVM/fritzbox.fon_wlan_7170/x_misc/opensrc" if FREETZ_AVM_VERSION_04_76 default "@AVM/fritzbox.fon_wlan_7170/x_misc/opensrc" if FREETZ_AVM_VERSION_04_80 default "@AVM/fritzbox.fon_wlan_7170/x_misc/opensrc" if FREETZ_AVM_VERSION_04_87 default "@AVM/fritzbox.fon_wlan_7270_v1/x_misc/opensrc" if FREETZ_AVM_VERSION_7270_04_86 default "@AVM/fritzbox.fon_wlan_7270_v3/x_misc/opensrc" if FREETZ_AVM_VERSION_7270_05_05 default "@AVM/fritzbox.fon_wlan_7320/x_misc/opensrc" if FREETZ_AVM_VERSION_7320_04_86 default "http://gpl.back2roots.org/source/fritzbox" if FREETZ_AVM_VERSION_7390_04_90 default "@AVM/fritzbox.fon_wlan_7390/x_misc/opensrc" if FREETZ_AVM_VERSION_7390_05_05 default "@TELEKOM/Speedport/Speedport_W501V" if FREETZ_AVM_VERSION_r7203 config FREETZ_DL_KERNEL_SOURCE string "Kernel source" if FREETZ_DL_OVERRIDE default "fritzbox7141-source-files-04.30.tar.bz2" if FREETZ_AVM_VERSION_04_30 default "fritzbox-source-files-04.33.tar.bz2" if FREETZ_AVM_VERSION_04_33 default "fritzbox-source-files.04.40.tar.bz2" if FREETZ_AVM_VERSION_04_40 default "fritzbox-source-files-04.49.tar.gz" if FREETZ_AVM_VERSION_04_49 default "fritzbox-source-files.04.57.tar.gz" if FREETZ_AVM_VERSION_04_57 default "fritzbox-source-files.04.67.tar.gz" if FREETZ_AVM_VERSION_04_67 default "fritzbox-source-files-04.70.tar.gz" if FREETZ_AVM_VERSION_04_70 default "fritzbox7170-source-files-04.76.tar.gz" if FREETZ_AVM_VERSION_04_76 default "fritzbox7170-source-files-04.80.tar.gz" if FREETZ_AVM_VERSION_04_80 default "fritzbox7170-source-files-04.87.tar.gz" if FREETZ_AVM_VERSION_04_87 default "fritzbox7270-source-files-04.86.tar.gz" if FREETZ_AVM_VERSION_7270_04_86 default "fritzbox-source-files-05.05.tar.gz" if FREETZ_AVM_VERSION_7270_05_05 default "fritzbox7320-source-files-04.86.tar.gz" if FREETZ_AVM_VERSION_7320_04_86 default "fritz_box_fon_wlan_7390_source_files.04.91.tar.gz" if FREETZ_AVM_VERSION_7390_04_90 default "fritz_box_fon_wlan_7390_source_files.05.05.tar.gz" if FREETZ_AVM_VERSION_7390_05_05 default "GPL-r7203-4mb_26-tar.bz2" if FREETZ_AVM_VERSION_r7203 config FREETZ_DL_KERNEL_SOURCE_MD5 string "MD5 checksum for downloaded Kernel source file" if FREETZ_DL_OVERRIDE default "1a43eaf94b7989b8cf8e50b2e50c756c" if FREETZ_AVM_VERSION_04_30 default "99b6a701f9cd09319086c8655fced242" if FREETZ_AVM_VERSION_04_33 default "008ecd257e584fc5bbf5e276d4b03ff1" if FREETZ_AVM_VERSION_04_40 default "e6889745b437bde0f5bdb5ada93c913d" if FREETZ_AVM_VERSION_04_49 default "702f4adf12638bfa34a6b10c0ede4b55" if FREETZ_AVM_VERSION_04_57 default "ec2c233bb836e822d9018fd41e123a91" if FREETZ_AVM_VERSION_04_67 default "855d4ad80fc894d9dff52fcaf55d3c12" if FREETZ_AVM_VERSION_04_70 default "4ffc088502c896c11931ba81536fa0e6" if FREETZ_AVM_VERSION_04_76 default "6bf92b81b48a3a05efd3aae6c05fe3e2" if FREETZ_AVM_VERSION_04_80 default "cad33bda041910e2aae01f027465162b" if FREETZ_AVM_VERSION_04_87 default "55a11af7dcfd617c39e75877045ab468" if FREETZ_AVM_VERSION_7270_04_86 default "19280ad861a7e88698d41211996c5ac6" if FREETZ_AVM_VERSION_7270_05_05 default "0e2ddf32808eb329efc4b486c6de0011" if FREETZ_AVM_VERSION_7320_04_86 default "2cad066e0e57aa3e58bf784b396ee676" if FREETZ_AVM_VERSION_7390_04_90 default "fbf515bd77f3d3a64a3095889777cc13" if FREETZ_AVM_VERSION_7390_05_05 default "582c74f0959a687c41c1bcfa599ace9c" if FREETZ_AVM_VERSION_r7203 config FREETZ_DL_SITE string "Firmware site" if FREETZ_DL_OVERRIDE depends on ! FREETZ_TYPE_LABOR default "@AVM/fritzbox.2170/firmware/deutsch" if FREETZ_TYPE_2170 default "@AVM/fritzbox.fon/firmware/deutsch" if (FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON) && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon/firmware/english/annex_a" if (FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON) && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "@AVM/fritzbox.fon/firmware/english/annex_b" if (FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON) && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "@AVM/fritzbox.fon_5010/firmware/deutsch_a-ch" if FREETZ_TYPE_FON_5010 default "@AVM/fritzbox.fon_5050/firmware" if FREETZ_TYPE_FON_5050 default "@AVM/fritzbox.fon_5124/firmware/english/annex_a" if FREETZ_TYPE_FON_5124 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "@AVM/fritzbox.fon_5124/firmware/english/annex_b" if FREETZ_TYPE_FON_5124 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "@AVM/fritzbox.fon_5140/firmware" if FREETZ_TYPE_FON_5140 default "@AVM/fritzbox.fon_wlan/firmware/deutsch" if FREETZ_TYPE_FON_WLAN && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "@AVM/fritzbox.fon_wlan/firmware/english/annex_b" if FREETZ_TYPE_FON_WLAN && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "@AVM/fritzbox.fon_wlan_7050/firmware" if FREETZ_TYPE_FON_WLAN_7050 default "@AVM/fritzbox.fon_wlan_7112/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7112 default "@AVM/fritzbox.fon_wlan_7113/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7113 && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7113/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN_7113 && \ FREETZ_TYPE_LANG_EN default "@AVM/fritzbox.fon_wlan_7140/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7140/firmware/deutsch_a-ch" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_A_CH default "@AVM/fritzbox.fon_wlan_7140/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "@AVM/fritzbox.fon_wlan_7140/firmware/english/annex_b" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "@AVM/fritzbox.fon_wlan_7141/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7141 default "@AVM/fritzfon.7150/firmware" if FREETZ_TYPE_FON_7150 default "@AVM/fritzbox.fon_wlan_7170/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7170/firmware/deutsch_a-ch" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_A_CH default "@AVM/fritzbox.fon_wlan_7170/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "@AVM/fritzbox.fon_wlan_7170/firmware/english/annex_b" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "@AVM/fritzbox.fon_wlan_7240/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7240 default "@AVM/fritzbox.fon_wlan_7270_v1/firmware/deutsch" if ( ( FREETZ_TYPE_FON_WLAN_7270_V1 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_72702_72701 ) && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7270_v2/firmware/deutsch" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7270_7270 ) && \ ! FREETZ_TYPE_LABOR && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7270_v2/firmware/english" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7270_7270 ) && \ FREETZ_TYPE_LANG_EN default "@AVM/fritzbox.fon_wlan_7270_v3/firmware/deutsch" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7240_7270 ) && \ ! FREETZ_TYPE_LABOR && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7270_v3/firmware/english" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7240_7270 ) && \ FREETZ_TYPE_LANG_EN default "@AVM/fritzbox.fon_wlan_7320/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7320 default "@AVM/fritzbox.fon_wlan_7330/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7330 default "@AVM/fritzbox.fon_wlan_7340/firmware/english" if FREETZ_TYPE_FON_WLAN_7340 default "@AVM/fritzbox.fon_wlan_7390/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7390 && \ FREETZ_TYPE_LANG_DE default "@AVM/fritzbox.fon_wlan_7390/firmware/english" if FREETZ_TYPE_FON_WLAN_7390 && \ FREETZ_TYPE_LANG_EN default "@AVM/fritzbox.fon_wlan_7570/firmware/english" if FREETZ_TYPE_FON_WLAN_7570 default "@AVM/fritzbox.sl_wlan/firmware" if FREETZ_TYPE_WLAN_3020 default "@AVM/fritzbox.wlan_3030/firmware" if FREETZ_TYPE_WLAN_3030 default "@AVM/fritzbox.wlan_3130/firmware" if FREETZ_TYPE_WLAN_3130 default "@AVM/fritzbox.wlan_3131/firmware/deutsch" if FREETZ_TYPE_WLAN_3131 default "@AVM/fritzbox.wlan_3170/firmware/deutsch" if FREETZ_TYPE_WLAN_3170 default "@AVM/fritzbox.wlan_3270/firmware/deutsch" if FREETZ_TYPE_WLAN_3270 default "@AVM/fritzbox.wlan_3270_v3/firmware/deutsch" if FREETZ_TYPE_WLAN_3270_V3 default "@TELEKOM/Speedport/Speedport_W501V" if FREETZ_TYPE_SPEEDPORT_W501V default "@AVM/..." if FREETZ_TYPE_CUSTOM config FREETZ_DL_SOURCE string "Firmware source" if FREETZ_DL_OVERRIDE default "FRITZ.Box_2170.51.04.57.image" if FREETZ_TYPE_2170 default "fritz.box_fon.06.04.33.image" if (FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON) && \ FREETZ_TYPE_LANG_DE default "fritz.box_fon.annexa.en.06.04.49.image" if (FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON) && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "fritz.box_fon.en.06.04.49.image" if (FREETZ_TYPE_300IP_AS_FON || \ FREETZ_TYPE_FON) && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "fritz.box_fon_5010.annexa.48.04.43.image" if FREETZ_TYPE_FON_5010 default "fritz.box_fon_5050.12.04.31.image" if FREETZ_TYPE_FON_5050 default "FRITZ.Box_Fon_5124.AnnexA.en.57.04.76.image" if FREETZ_TYPE_FON_5124 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "FRITZ.Box_Fon_5124.AnnexB.en.56.04.76.image" if FREETZ_TYPE_FON_5124 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "FRITZ.Box_Fon_5140.AnnexB.43.04.67.image" if FREETZ_TYPE_FON_5140 default "fritz.box_fon_wlan.08.04.34.image" if FREETZ_TYPE_FON_WLAN && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN.AnnexA.en.08.04.49.image" if FREETZ_TYPE_FON_WLAN && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "FRITZ.Box_Fon_WLAN.AnnexB.en.08.04.49.image" if FREETZ_TYPE_FON_WLAN && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "fritz.box_fon_wlan_7050.14.04.33.image" if FREETZ_TYPE_FON_WLAN_7050 default "FRITZ.Box_Fon_WLAN_7112.87.04.87.image" if FREETZ_TYPE_FON_WLAN_7112 default "FRITZ.Box_Fon_WLAN_7113.60.04.68.image" if FREETZ_TYPE_FON_WLAN_7113 && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7113.AnnexA.de-en-es-it-fr.90.04.84.image" if FREETZ_TYPE_FON_WLAN_7113 && \ FREETZ_TYPE_LANG_EN default "fritz.box_fon_wlan_7140.annexb.30.04.33.image" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7140.AnnexA.39.04.76.image" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_A_CH default "FRITZ.Box_Fon_WLAN_7140.AnnexA.en.39.04.67.image" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "FRITZ.Box_Fon_WLAN_7140.AnnexB.en.30.04.67.image" if FREETZ_TYPE_FON_WLAN_7140 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "FRITZ.Box_Fon_WLAN_7141.40.04.76.image" if FREETZ_TYPE_FON_WLAN_7141 default "fritz.fon_7150.annexb.38.04.71.image" if FREETZ_TYPE_FON_7150 default "FRITZ.Box_Fon_WLAN_7170.29.04.87.image" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7170.AnnexA.58.04.76.image" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_A_CH default "FRITZ.Box_Fon_WLAN_7170.AnnexA.en.58.04.84.image" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_A default "FRITZ.Box_Fon_WLAN_7170.AnnexB.en.29.04.82.image" if FREETZ_TYPE_FON_WLAN_7170 && \ FREETZ_TYPE_LANG_EN && \ FREETZ_TYPE_ANNEX_B default "FRITZ.Box_Fon_WLAN_7240.73.05.05.image" if FREETZ_TYPE_FON_WLAN_7240 && \ ! FREETZ_TYPE_LABOR # default "Labor_FRITZ.Box_Fon_WLAN_7240.73.05.04-20170.image" if FREETZ_TYPE_FON_WLAN_7240 && \ # FREETZ_TYPE_LABOR_PREVIEW default "FRITZ.Box_Fon_WLAN_7270_v1.54.04.88.image" if FREETZ_TYPE_FON_WLAN_7270_V1 && \ ! FREETZ_TYPE_LABOR && \ FREETZ_TYPE_LANG_DE # default "Labor_FRITZ.Box_Fon_WLAN_7270_v1.54.04.86-18582.image" if FREETZ_TYPE_FON_WLAN_7270_V1 && \ # FREETZ_TYPE_LABOR_PREVIEW default "FRITZ.Box_Fon_WLAN_7270_v2.54.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7270_7270 ) && \ ! FREETZ_TYPE_LABOR && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7270_v2_Labor.54.05.07-20870.image" if FREETZ_TYPE_FON_WLAN_7270_V2 && \ FREETZ_TYPE_LABOR_PREVIEW default "FRITZ.Box_Fon_WLAN_7270_16.en-de-es-it-fr.54.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7270_7270 ) && \ FREETZ_TYPE_LANG_EN default "FRITZ.Box_Fon_WLAN_7270_v3.74.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7240_7270 ) && \ ! FREETZ_TYPE_LABOR && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7270_v3.en-de-es-it-fr.74.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ FREETZ_TYPE_7240_7270 ) && \ FREETZ_TYPE_LANG_EN default "FRITZ.Box_Fon_WLAN_7270_v3_Labor.74.05.07-20870.image" if ( FREETZ_TYPE_FON_WLAN_7270_V3 || \ ( FREETZ_TYPE_FON_WLAN_7270 && \ FREETZ_TYPE_ALIEN_HARDWARE ) ) && \ FREETZ_TYPE_LABOR_PREVIEW default "FRITZ.Box_Fon_WLAN_7320.100.04.89.image" if FREETZ_TYPE_FON_WLAN_7320 && \ ! FREETZ_TYPE_LABOR default "FRITZ.Box_7330.107.05.06.image" if FREETZ_TYPE_FON_WLAN_7330 default "FRITZ.Box_Fon_WLAN_7340.en-de-es-it-fr.99.05.05.image" if FREETZ_TYPE_FON_WLAN_7340 default "FRITZ.Box_Fon_WLAN_7390.84.05.05.image" if FREETZ_TYPE_FON_WLAN_7390 && \ ! FREETZ_TYPE_LABOR && \ FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7390.en-de-es-it-fr.84.05.05.image" if FREETZ_TYPE_FON_WLAN_7390 && \ ! FREETZ_TYPE_LANG_DE default "FRITZ.Box_Fon_WLAN_7390_Labor.84.05.07-20869.image" if FREETZ_TYPE_FON_WLAN_7390 && \ FREETZ_TYPE_LABOR_PREVIEW default "FRITZ.Box_Fon_WLAN_7570_vDSL.en-de-fr.75.04.91.image" if FREETZ_TYPE_FON_WLAN_7570 default "fritz.box_sl_wlan.09.04.34.image" if FREETZ_TYPE_WLAN_3020 default "fritz.box_wlan_3030.21.04.34.image" if FREETZ_TYPE_WLAN_3030 default "fritz.box_wlan_3130.44.04.34.image" if FREETZ_TYPE_WLAN_3130 default "fritz.box_wlan_3131.50.04.57.image" if FREETZ_TYPE_WLAN_3131 default "fritz.box_wlan_3170.49.04.58.image" if FREETZ_TYPE_WLAN_3170 default "fritz.box_wlan_3270.67.05.05.image" if FREETZ_TYPE_WLAN_3270 default "fritz.box_wlan_3270_v3.96.05.05.image" if FREETZ_TYPE_WLAN_3270_V3 default "fw_Speedport_W501V_v_28.04.38.image" if FREETZ_TYPE_SPEEDPORT_W501V default "fritz.box..." if FREETZ_TYPE_CUSTOM endmenu # "Toolchain options" # endmenu # "Advanced options" # # INCLUDE_END Config.in pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Constants.mo000066400000000000000000000141051250413007300262020ustar00rootroot00000000000000within Modelica; package Constants "Library of mathematical constants and constants of nature (e.g., pi, eps, R, sigma)" import SI = Modelica.SIunits; import NonSI = Modelica.SIunits.Conversions.NonSIunits; extends Modelica.Icons.Library2; // Mathematical constants final constant Real e=Modelica.Math.exp(1.0); final constant Real pi=2*Modelica.Math.asin(1.0); // 3.14159265358979; final constant Real D2R=pi/180 "Degree to Radian"; final constant Real R2D=180/pi "Radian to Degree"; // Machine dependent constants // (the definition is a temporary fix since not adapted to the // machine where the Modelica translator is running) final constant Real eps=1.e-15 "Biggest number such that 1.0 + eps = 1.0"; final constant Real small=1.e-60 "Smallest number such that small and -small are representable on the machine"; final constant Real inf=1.e+60 "Biggest Real number such that inf and -inf are representable on the machine"; final constant Integer Integer_inf=2147483647 "Biggest Integer number such that Integer_inf and -Integer_inf are representable on the machine"; // Constants of nature // (name, value, description from http://physics.nist.gov/cuu/Constants/) final constant SI.Velocity c=299792458 "Speed of light in vacuum"; final constant SI.Acceleration g_n=9.80665 "Standard acceleration of gravity on earth"; final constant Real G(final unit="m3/(kg.s2)") = 6.6742e-11 "Newtonian constant of gravitation"; final constant SI.FaradayConstant F = 9.64853399e4 "Faraday constant, C/mol"; final constant Real h(final unit="J.s") = 6.6260693e-34 "Planck constant"; final constant Real k(final unit="J/K") = 1.3806505e-23 "Boltzmann constant"; final constant Real R(final unit="J/(mol.K)") = 8.314472 "Molar gas constant"; final constant Real sigma(final unit="W/(m2.K4)") = 5.670400e-8 "Stefan-Boltzmann constant"; final constant Real N_A(final unit="1/mol") = 6.0221415e23 "Avogadro constant"; final constant Real mue_0(final unit="N/A2") = 4*pi*1.e-7 "Magnetic constant"; final constant Real epsilon_0(final unit="F/m") = 1/(mue_0*c*c) "Electric constant"; final constant NonSI.Temperature_degC T_zero=-273.15 "Absolute zero temperature"; annotation ( Documentation(info="

This package provides often needed constants from mathematics, machine dependent constants and constants from nature. The latter constants (name, value, description) are from the following source:

Peter J. Mohr and Barry N. Taylor (1999):
CODATA Recommended Values of the Fundamental Physical Constants: 1998. Journal of Physical and Chemical Reference Data, Vol. 28, No. 6, 1999 and Reviews of Modern Physics, Vol. 72, No. 2, 2000. See also http://physics.nist.gov/cuu/Constants/

CODATA is the Committee on Data for Science and Technology.

Main Author:
Martin Otter
Deutsches Zentrum für Luft und Raumfahrt e. V. (DLR)
Oberpfaffenhofen
Postfach 11 16
D-82230 Weßling
email: Martin.Otter@dlr.de

Copyright © 1998-2009, Modelica Association and DLR.

This Modelica package is free software; it can be redistributed and/or modified under the terms of the Modelica license, see the license conditions and the accompanying disclaimer here.


", revisions="
  • Nov 8, 2004 by Christian Schweiger:
    Constants updated according to 2002 CODATA values.
  • Dec 9, 1999 by Martin Otter:
    Constants updated according to 1998 CODATA values. Using names, values and description text from this source. Included magnetic and electric constant.
  • Sep 18, 1999 by Martin Otter:
    Constants eps, inf, small introduced.
  • Nov 15, 1997 by Martin Otter:
    Realized.
"), Invisible=true, Icon(coordinateSystem(preserveAspectRatio=true, extent={{-100,-100},{100, 100}}), graphics={ Line( points={{-34,-38},{12,-38}}, color={0,0,0}, thickness=0.5), Line( points={{-20,-38},{-24,-48},{-28,-56},{-34,-64}}, color={0,0,0}, thickness=0.5), Line( points={{-2,-38},{2,-46},{8,-56},{14,-64}}, color={0,0,0}, thickness=0.5)}), Diagram(graphics={ Rectangle( extent={{200,162},{380,312}}, fillColor={235,235,235}, fillPattern=FillPattern.Solid, lineColor={0,0,255}), Polygon( points={{200,312},{220,332},{400,332},{380,312},{200,312}}, fillColor={235,235,235}, fillPattern=FillPattern.Solid, lineColor={0,0,255}), Polygon( points={{400,332},{400,182},{380,162},{380,312},{400,332}}, fillColor={235,235,235}, fillPattern=FillPattern.Solid, lineColor={0,0,255}), Text( extent={{210,302},{370,272}}, lineColor={160,160,164}, fillColor={0,0,0}, fillPattern=FillPattern.Solid, textString="Library"), Line( points={{266,224},{312,224}}, color={0,0,0}, thickness=1), Line( points={{280,224},{276,214},{272,206},{266,198}}, color={0,0,0}, thickness=1), Line( points={{298,224},{302,216},{308,206},{314,198}}, color={0,0,0}, thickness=1), Text( extent={{152,412},{458,334}}, lineColor={255,0,0}, textString="Modelica.Constants")})); end Constants; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/DancingSudoku.lhs000066400000000000000000000355771250413007300271570ustar00rootroot00000000000000 A Sukodku solver by Chris Kuklewicz (haskell (at) list (dot) mightyreason (dot) com) The usual BSD license applies, copyright 2006. Uploaded to HaskellWiki as DancingSudoku.lhs I compile on a powerbook G4 (Mac OS X, ghc 6.4.2) using ghc -optc-O3 -funbox-strict-fields -O2 --make -fglasgow-exts This is a translation of Knuth's GDANCE from dance.w / dance.c http://www-cs-faculty.stanford.edu/~uno/preprints.html http://www-cs-faculty.stanford.edu/~uno/programs.html http://en.wikipedia.org/wiki/Dancing_Links I have an older verison that uses lazy ST to return the solutions on demand, which was more useful when trying to generate new puzzles to solve. > module Main where > import Prelude hiding (read) > import Control.Monad > import Control.Monad.Fix > import Data.Array.IArray > import Control.Monad.ST.Strict > import Data.STRef.Strict > import Data.Char(intToDigit,digitToInt) > import Data.List(unfoldr,intersperse,inits) > new = newSTRef > {-# INLINE new #-} > read = readSTRef > {-# INLINE read #-} > write = writeSTRef > {-# INLINE write #-} > modify = modifySTRef > {-# INLINE modify #-} Data types to prevent mixing different index and value types > type A = Int > newtype R = R A deriving (Show,Read,Eq,Ord,Ix,Enum) > newtype C = C A deriving (Show,Read,Eq,Ord,Ix,Enum) > newtype V = V A deriving (Show,Read,Eq,Ord,Ix,Enum) > newtype B = B A deriving (Show,Read,Eq,Ord,Ix,Enum) Sudoku also has block constraints, so we want to look up a block index in an array: > lookupBlock :: Array (R,C) B > lookupBlock = listArray bb [ toBlock ij | ij <- range bb ] > where ra :: Array Int B > ra = listArray (0,pred (rangeSize b)) [B (fst b) .. B (snd b)] > toBlock (R i,C j) = ra ! ( (div (index b j) 3)+3*(div (index b i) 3) ) The values for an unknown location is 'u'. The bound and range are given by b and rng. And bb is a 2D bound. > u = V 0 -- unknown value > b :: (Int,Int) > b = (1,9) -- min and max bounds > rng = enumFromTo (fst b) (snd b) -- list from '1' to '9' > bb = ((R (fst b),C (fst b)),(R (snd b),C (snd b))) A Spec can be turned into a parsed array with ease: > type Hint = ((R,C),V) > newtype Spec = Spec [Hint] deriving (Eq,Show) > type PA = Array (R,C) V > parse :: Spec -> PA > parse (Spec parsed) = let acc old new = new > in accumArray acc u bb parsed The dancing links algorithm depends on a sparse 2D node structure. Each column represents a constraint. Each row represents a Hint. The number of possible hints is 9x9x9 = 271 > type (MutInt st) = (STRef st) Int The pointer types: > type (NodePtr st) = (STRef st) (Node st) > type (HeadPtr st) = (STRef st) (Head st) The structures is a 2D grid of nodes, with Col's on the top of columns and a sparse collection of nodes. Note that topNode of Head is not a strict field. This is because the topNode needs to refer to the Head, and they are both created monadically. > type HeadName = (Int,Int,Int) -- see below for meaning > data Head st = Head {headName:: !HeadName > ,topNode:: (Node st) -- header node for this column > ,len:: !(MutInt st) -- number of nodes below this head > ,next,prev:: !(HeadPtr st) -- doubly-linked list > } > data Node st = Node {getHint:: !Hint > ,getHead:: !(Head st) -- head for the column this node is in > ,up,down,left,right :: !(NodePtr st) -- two doubly-linked lists > } > instance Eq (Head st) where > a == b = headName a == headName b > instance Eq (Node st) where > a == b = up a == up b To initialize the structures is a bit tedious. Knuth's code reads in the problem description from a data file and builds the structure based on that. Rather than short strings, I will use HeadName as the identifier. The columns are (0,4,5) for nodes that put some value in Row 4 Col 5 (1,2,3) for nodes that put Val 3 in Row 2 and some column (2,7,4) for nodes that put Val 4 in Col 7 and some row (3,1,8) for nodes that put Val 8 in some (row,column) in Block 1 The first head is (0,0,0) which is the root. The non-root head data will be put in an array with the HeadName as an index. > headNames :: [HeadName] > headNames = let names = [0,1,2,3] > in (0,0,0):[ (l,i,j) | l<-names,i<-rng,j<-rng] A "row" of left-right linked nodes is a move. It is defined by a list of head names. > type Move = [(Hint,HeadName)] Initial hints are enforced by making them the only legal move for that location. Blank entries with value 'u = V 0' have a move for all possible values [V 1..V 9]. > parseSpec :: Spec -> [Move] > parseSpec spec = > let rowsFrom :: Hint -> [Move] > rowsFrom (rc@(R r,C c),mv@(V v')) = > if mv == u then [ rsyms v | v <- rng ] > else [ rsyms v' ] > where (B b) = lookupBlock ! rc > rsyms :: A -> Move > rsyms v = map ( (,) (rc,V v) ) [(0,r,c),(1,r,v),(2,c,v),(3,b,v)] > in concatMap rowsFrom (assocs (parse spec)) mkDList creates doubly linked lists using a monadic smart constructor and the recursive "mdo" notation as documented at http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#mdo-notation http://www.cse.ogi.edu/PacSoft/projects/rmb/ For more fun with this, see the wiki page at http://haskell.org/hawiki/TyingTheKnot > mkDList :: (MonadFix m) => (b -> a -> b -> m b) -> [a] -> m b > mkDList _ [] = error "must have at least one element" > mkDList mkNode xs = mdo (first,last) <- go last xs first > return first > where go prev [] next = return (next,prev) > go prev (x:xs) next = mdo this <- mkNode prev x rest > (rest,last) <- go this xs next > return (this,last) toSimple takes a function and a header node and iterates (read . function) until the header is reached again, but does not return the header itself. > toSingle step header = loop =<< (read . step) header > where loop y = if header/=y then liftM (y:) (read (step y) >>= loop) > else return [] > forEach is an optimization of (toSimple step header >>= mapM_ act) > forEach step header act = loop =<< (read . step) header > where loop y = if header/=y then (act y >> (read (step y)) >>= loop) > else return () Now make the root node and all the head nodes. This also exploits mdo: > makeHeads :: [HeadName] -> (ST st) (Head st) > makeHeads names = mkDList makeHead names > where makeHead before name after = mdo > ~newTopNode <- liftM4 (Node ((R 0,C 0),V 0) newHead) (new newTopNode) (new newTopNode) > (new newTopNode) (new newTopNode) > newHead <- liftM3 (Head name newTopNode) > (new 0) (new after) (new before) > return newHead The Head nodes will be places in an array for easy lookup while building moves: > type HArray st = Array HeadName (Head st) > hBounds = ((0,1,1),(3,9,9)) > type Root st = (Head st,HArray st) The addMove function creates the (four) nodes that represent a move and adds them to the data structure. The HArray in Root makes for a fast lookup of the Head data. > addMove :: forall st. (Root st) -> Move -> (ST st) (Node st) > addMove (_,ha) move = mkDList addNode move > where addNode :: (Node st) -> (Hint,HeadName) -> (Node st) -> (ST st) (Node st) > addNode before (hint,name) after = do > let head = ha ! name > let below = topNode head > above <- read (up below) > newNode <- liftM4 (Node hint head) (new above) (new below) > (new before) (new after) > write (down above) newNode > write (up below) newNode > modify (len head) succ > l <- read (len head) > seq l (return newNode) Create the column headers, including the fast lookup array. These will be resused between puzzles. > initHA :: (ST st) (Root st) > initHA = do > root <- makeHeads headNames > heads <- toSingle next root > let ha = array hBounds (zip (map headName heads) heads) > return (root,ha) Take the Root from initHA and a puzzle Spec and fill in all the Nodes. > initRoot :: (Root st) -> Spec -> (ST st) () > initRoot root spec = do > let moves = parseSpec spec > mapM_ (addMove root) moves Return the column headers to their condition after initHA > resetRoot :: (Root st) -> (ST st) () > resetRoot (root,ha) = do > let heads@(first:_) = elems ha > let resetHead head = do > write (len head) 0 > let node = topNode head > write (down node) node > write (up node) node > reset (last:[]) = do > write (prev root) last > write (next root) first > reset (before:xs@(head:[])) = do > resetHead head > write (prev head) before > write (next head) root > reset xs > reset (before:xs@(head:after:_)) = do > resetHead head > write (prev head) before > write (next head) after > reset xs > reset (root:heads) getBest iterates over the unmet constraints (i.e. the Head that are reachable from root). It locates the one with the lowest number of possible moves that will solve it, aborting early if it finds 0 or 1 moves. > getBest :: (Head st) -> (ST st) (Maybe (Head st)) > getBest root = do > first <- read (next root) > if first == root then return Nothing > else do > let findMin m best head | head == root = return (Just best) > | otherwise = do > l <- read (len head) > if l <= 1 then return (Just head) > else if l < m then findMin l head =<< read (next head) > else findMin l best =<< read (next head) > findMin 10 first first The unlink and relink operations are from where Knuth got the name "dancing links". So long as "a" does not change in between, the relink call will undo the unlink call. Similarly, the unconver will undo the changes of cover and unconverOthers will undo coverOthers. > unlink :: (a->STRef st a) -> (a->STRef st a) -> a -> (ST st) () > unlink prev next a = do > before <- read (prev a) > after <- read (next a) > write (next before) after > write (prev after) before > relink :: (a->STRef st a) -> (a->STRef st a) -> a -> (ST st) () > relink prev next a = do > before <- read (prev a) > after <- read (next a) > write (next before) a > write (prev after) a > cover :: (Head st) -> (ST st) () > cover head = do > unlink prev next head > let eachDown rr = forEach right rr eachRight > eachRight nn = do > unlink up down nn > modify (len $ getHead nn) pred > forEach down (topNode head) eachDown > uncover :: (Head st) -> (ST st) () > uncover head = do > let eachUp rr = forEach left rr eachLeft > eachLeft nn = do > modify (len $ getHead nn) succ > relink up down nn > forEach up (topNode head) eachUp > relink prev next head > coverOthers :: (Node st) -> (ST st) () > coverOthers node = forEach right node (cover . getHead) > uncoverOthers :: (Node st) -> (ST st) () > uncoverOthers node = forEach left node (uncover . getHead) A helper function for gdance: > choicesToSpec :: [(Node st)] -> Spec > choicesToSpec = Spec . (map getHint) This is the heart of the algorithm. I have altered it to return only the first solution, or produce an error if none is found. Knuth used several goto links to do what is done below with tail recursion. > gdance :: (Head st) -> (ST st) Spec -- [Spec] > gdance root = > let > forward choices = do > maybeHead <- getBest root > case maybeHead of > Nothing -> if null choices > then error "No choices in forward" -- return [] -- for [Spec] > else do -- nextSols <- recover choices -- for [Spec] > return $ (choicesToSpec choices) -- :nextSols -- for [Spec] > Just head -> do cover head > startRow <- readSTRef (down (topNode head)) > advance (startRow:choices) > > advance choices@(newRow:oldChoices) = do > let endOfRows = topNode (getHead newRow) > if (newRow == endOfRows) > then do uncover (getHead newRow) > if (null oldChoices) > then error "No choices in advance" -- return [] -- for [Spec] > else recover oldChoices > else do coverOthers newRow > forward choices > > recover (oldRow:oldChoices) = do > uncoverOthers oldRow > newRow <- readSTRef (down oldRow) > advance (newRow:oldChoices) > > in forward [] Convert a text board into a Spec > parseBoard :: String -> Spec > parseBoard s = Spec (zip rcs vs'check) > where rcs :: [(R,C)] > rcs = [ (R r,C c) | r <- rng, c <- rng ] > isUnset c = (c=='.') || (c==' ') || (c=='0') > isHint c = ('1'<=c) && (c<='9') > cs = take 81 $ filter (\c -> isUnset c || isHint c) s > vs :: [V] > vs = map (\c -> if isUnset c then u else (V $ digitToInt c)) cs > vs'check = if 81==length vs then vs else error ("parse of board failed\n"++s) This is quite useful as a utility function which partitions the list into groups of n elements. Used by showSpec. > groupTake :: Int->[a]->[[a]] > groupTake n b = unfoldr foo b > where foo [] = Nothing > foo b = Just (splitAt n b) Make a nice 2D ascii board from the Spec (not used at the moment) > showSpec :: Spec -> String > showSpec spec = let pa = parse spec > g = groupTake 9 (map (\(V v) -> if v == 0 then '.' else intToDigit v) $ elems pa) > addV line = concat $ intersperse "|" (groupTake 3 line) > addH list = concat $ intersperse ["---+---+---"] (groupTake 3 list) > in unlines $ addH (map addV g) One line display > showCompact spec = map (\(V v) -> intToDigit v) (elems (parse spec)) The main routine is designed to handle the input from http://www.csse.uwa.edu.au/~gordon/sudoku17 > main = do > all <- getContents > let puzzles = zip [1..] (map parseBoard (lines all)) > root <- stToIO initHA > let act :: (Int,Spec) -> IO () > act (i,spec) = do > answer <- stToIO (do initRoot root spec > answer <- gdance (fst root) > resetRoot root > return answer) > print (i,showCompact answer) > mapM_ act puzzles > inits' xn@(_:_) = zipWith take [0..] $ map (const xn) $ undefined:xn > inits' _ = undefined pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Deflate.fs000077500000000000000000000464261250413007300256050ustar00rootroot00000000000000// public domain module Deflate open System open System.Collections.Generic open System.IO open System.Linq open Crc let maxbuf = 32768 let maxlen = 258 let getBit (b:byte) (bit:int) = if b &&& (1uy <<< bit) = 0uy then 0 else 1 type BitReader(sin:Stream) = let mutable bit = 8 let mutable cur = 0uy member x.Skip() = bit <- 8 member x.ReadBit() = if bit = 8 then bit <- 0 let b = sin.ReadByte() if b = -1 then failwith "ãƒãƒƒãƒ•ã‚¡ã‚’è¶…éŽã—ã¾ã—ãŸ" cur <- byte b let ret = if cur &&& (1uy <<< bit) = 0uy then 0 else 1 bit <- bit + 1 ret member x.ReadLE n = let mutable ret = 0 for i = 0 to n - 1 do if x.ReadBit() = 1 then ret <- ret ||| (1 <<< i) ret member x.ReadBE n = let mutable ret = 0 for i = 0 to n - 1 do ret <- (ret <<< 1) ||| x.ReadBit() ret member x.ReadBytes len = if bit <> 8 then bit <- 8 let buf = Array.zeroCreate len ignore <| sin.Read(buf, 0, len) buf type WriteBuffer(sout:Stream) = let mutable prev:byte[] = null let mutable buf = Array.zeroCreate maxbuf let mutable p = 0 let next newbuf = prev <- buf buf <- if newbuf then Array.zeroCreate maxbuf else null p <- 0 member x.Close() = next false next false interface IDisposable with member x.Dispose() = x.Close() member x.WriteByte (b:byte) = buf.[p] <- b sout.WriteByte b p <- p + 1 if p = maxbuf then next true member x.Write (src:byte[]) start len = let maxlen = maxbuf - p if len <= maxlen then Array.Copy(src, start, buf, p, len) sout.Write(src, start, len) p <- p + len if p = maxbuf then next true else x.Write src start maxlen x.Write src (start + maxlen) (len - maxlen) member x.Copy len dist = if dist < 1 then failwith <| sprintf "dist too small: %d < 1" dist elif dist > maxbuf then failwith <| sprintf "dist too big: %d > %d" dist maxbuf let pp = p - dist if pp < 0 then if prev = null then failwith <| sprintf "dist too big: %d > %d" dist p let pp = pp + maxbuf let maxlen = maxbuf - pp if len <= maxlen then x.Write prev pp len else x.Write prev pp maxlen x.Copy (len - maxlen) dist else let maxlen = p - pp if len <= maxlen then x.Write buf pp len else if dist = 1 then let b = buf.[pp] for i = 1 to len do x.WriteByte b else let buf' = buf let mutable len' = len while len' > 0 do let len'' = Math.Min(len', maxlen) x.Write buf' pp len'' len' <- len' - len'' type Huffman(lens:int[]) = let vals = Array.zeroCreate lens.Length let min = lens.Where(fun x -> x > 0).Min() let max = lens.Max() let counts = Array.zeroCreate (max + 1) let firsts = Array.zeroCreate (max + 1) let nexts = Array.zeroCreate (max + 1) let tables = Array.zeroCreate(max + 1) do for len in lens do if len > 0 then counts.[len] <- counts.[len] + 1 for i = 1 to max do firsts.[i] <- (firsts.[i - 1] + counts.[i - 1]) <<< 1 Array.Copy(firsts, 0, nexts, 0, max + 1) for i = 0 to vals.Length - 1 do let len = lens.[i] if len > 0 then vals.[i] <- nexts.[len] nexts.[len] <- nexts.[len] + 1 for i = 0 to vals.Length - 1 do let len = lens.[i] if len > 0 then let start = firsts.[len] if tables.[len] = null then let count = nexts.[len] - start tables.[len] <- Array.zeroCreate count tables.[len].[vals.[i] - start] <- i member x.GetValue h = let rec getv i = if i > max then -1 else if h < nexts.[i] then tables.[i].[h - firsts.[i]] else getv (i + 1) getv min member x.Read(br:BitReader) = let rec read h i = if h < nexts.[i] then tables.[i].[h - firsts.[i]] else read ((h <<< 1) ||| br.ReadBit()) (i + 1) read (br.ReadBE min) min type [] HuffmanDecoder() = abstract GetValue: unit->int abstract GetDistance: unit->int type FixedHuffman(br:BitReader) = inherit HuffmanDecoder() override x.GetValue() = let v = br.ReadBE 7 if v < 24 then v + 256 else let v = (v <<< 1) ||| br.ReadBit() if v < 192 then v - 48 elif v < 200 then v + 88 else ((v <<< 1) ||| br.ReadBit()) - 256 override x.GetDistance() = br.ReadBE 5 type DynamicHuffman(br:BitReader) = inherit HuffmanDecoder() let lit, dist = let hlit = let hlit = (br.ReadLE 5) + 257 if hlit > 286 then failwith <| sprintf "hlit: %d > 286" hlit hlit let hdist = let hdist = (br.ReadLE 5) + 1 if hdist > 32 then failwith <| sprintf "hdist: %d > 32" hdist hdist let hclen = let hclen = (br.ReadLE 4) + 4 if hclen > 19 then failwith <| sprintf "hclen: %d > 19" hclen hclen let clen = let hclens = Array.zeroCreate 19 let order = [| 16; 17; 18; 0; 8; 7; 9; 6; 10; 5; 11; 4; 12; 3; 13; 2; 14; 1; 15 |] for i = 0 to hclen - 1 do hclens.[order.[i]] <- br.ReadLE 3 new Huffman(hclens) let ld = Array.zeroCreate(hlit + hdist) let mutable i = 0 while i < ld.Length do let v = clen.Read(br) if v < 16 then ld.[i] <- v i <- i + 1 else let r, v = match v with | 16 -> (br.ReadLE 2) + 3, ld.[i - 1] | 17 -> (br.ReadLE 3) + 3, 0 | 18 -> (br.ReadLE 7) + 11, 0 | _ -> failwith "䏿­£ãªå€¤ã§ã™ã€‚" for j = 0 to r - 1 do ld.[i + j] <- v i <- i + r new Huffman(ld.[0 .. hlit - 1]), new Huffman(ld.[hlit .. hlit + hdist - 1]) override x.GetValue() = lit.Read br override x.GetDistance() = dist.Read br let getLitExLen v = if v < 265 || v = 285 then 0 else (v - 261) >>> 2 let getDistExLen d = if d < 4 then 0 else (d - 2) >>> 1 let litlens = let litlens = Array.zeroCreate 286 let mutable v = 3 for i = 257 to 284 do litlens.[i] <- v v <- v + (1 <<< (getLitExLen i)) litlens.[285] <- maxlen litlens.[257..285] let distlens = let distlens = Array.zeroCreate 30 let mutable v = 1 for i = 0 to 29 do distlens.[i] <- v v <- v + (1 <<< (getDistExLen i)) distlens type Reader(sin:Stream) = inherit Stream() let br = new BitReader(sin) let fh = new FixedHuffman(br) let sout = new MemoryStream() let dbuf = new WriteBuffer(sout) let mutable cache:byte[] = null let mutable canRead = true let rec read (h:HuffmanDecoder) = let v = h.GetValue() if v > 285 then failwith <| sprintf "䏿­£ãªå€¤: %d" v if v < 256 then dbuf.WriteByte(byte v) elif v > 256 then let len = if v < 265 then v - 254 else litlens.[v - 257] + (br.ReadLE (getLitExLen v)) let dist = let d = h.GetDistance() if d > 29 then failwith <| sprintf "䏿­£ãªè·é›¢: %d" d if d < 4 then d + 1 else distlens.[d] + (br.ReadLE (getDistExLen d)) dbuf.Copy len dist if v <> 256 then read h override x.CanRead = canRead override x.CanWrite = false override x.CanSeek = false override x.Flush() = () override x.Close() = dbuf.Close() canRead <- false override x.Read(buffer, offset, count) = let offset = if cache = null then 0 else let clen = cache.Length let len = Math.Min(clen, count) Array.Copy(cache, 0, buffer, offset, len) cache <- if len = clen then null else cache.[len .. clen - 1] len let req = int64 <| count - offset while canRead && sout.Length < req do x.readBlock() let len = if sout.Length = 0L then 0 else let data = sout.ToArray() sout.SetLength(0L) let dlen = data.Length let len = Math.Min(int req, dlen) Array.Copy(data, 0, buffer, offset, len) if dlen > len then cache <- data.[len..] len offset + len override x.Position with get() = raise <| new NotImplementedException() and set(v) = raise <| new NotImplementedException() override x.Length = raise <| new NotImplementedException() override x.Seek(_, _) = raise <| new NotImplementedException() override x.Write(_, _, _) = raise <| new NotImplementedException() override x.SetLength(_) = raise <| new NotImplementedException() member private x.readBlock() = let bfinal = br.ReadBit() match br.ReadLE 2 with | 0 -> br.Skip() let len = br.ReadLE 16 let nlen = br.ReadLE 16 if len + nlen <> 0x10000 then failwith "䏿­£ãªéžåœ§ç¸®é•·" dbuf.Write (br.ReadBytes len) 0 len | 1 -> read fh | 2 -> read (new DynamicHuffman(br)) | _ -> failwith "䏿­£ãªãƒ–ロックタイプ" if bfinal = 1 then canRead <- false x.Close() type BitWriter(sout:Stream) = let mutable bit = 0 let mutable cur = 0uy member x.Skip() = if bit > 0 then sout.WriteByte(cur) bit <- 0 cur <- 0uy interface IDisposable with member x.Dispose() = x.Skip() sout.Flush() member x.WriteBit(b:int) = cur <- cur ||| ((byte b) <<< bit) bit <- bit + 1 if bit = 8 then sout.WriteByte(cur) bit <- 0 cur <- 0uy member x.WriteLE (len:int) (b:int) = for i = 0 to len - 1 do x.WriteBit <| if (b &&& (1 <<< i)) = 0 then 0 else 1 member x.WriteBE (len:int) (b:int) = for i = len - 1 downto 0 do x.WriteBit <| if (b &&& (1 <<< i)) = 0 then 0 else 1 member x.WriteBytes(data:byte[]) = x.Skip() sout.Write(data, 0, data.Length) type FixedHuffmanWriter(bw:BitWriter) = member x.Write (b:int) = if b < 144 then bw.WriteBE 8 (b + 0b110000) elif b < 256 then bw.WriteBE 9 (b - 144 + 0b110010000) elif b < 280 then bw.WriteBE 7 (b - 256) elif b < 288 then bw.WriteBE 8 (b - 280 + 0b11000000) member x.WriteLen (len:int) = if len < 3 || len > maxlen then failwith <| sprintf "䏿­£ãªé•·ã•: %d" len let mutable ll = 285 while len < litlens.[ll - 257] do ll <- ll - 1 x.Write ll bw.WriteLE (getLitExLen ll) (len - litlens.[ll - 257]) member x.WriteDist (d:int) = if d < 1 || d > maxbuf then failwith <| sprintf "䏿­£ãªè·é›¢: %d" d let mutable dl = 29 while d < distlens.[dl] do dl <- dl - 1 bw.WriteBE 5 dl bw.WriteLE (getDistExLen dl) (d - distlens.[dl]) let maxbuf2 = maxbuf * 2 let buflen = maxbuf2 + maxlen let inline getHash (buf:byte[]) pos = ((int buf.[pos]) <<< 4) ^^^ ((int buf.[pos + 1]) <<< 2) ^^^ (int buf.[pos + 2]) let inline addHash (hash:List[]) (buf:byte[]) pos = if buf.[pos] <> buf.[pos + 1] then hash.[getHash buf pos].Add pos let inline addHash2 (tables:int[,]) (counts:int[]) (buf:byte[]) pos = if buf.[pos] <> buf.[pos + 1] then let h = getHash buf pos let c = counts.[h] tables.[h, c &&& 15] <- pos counts.[h] <- c + 1 type Writer(t:int, sin:Stream) = let mutable length = buflen let buf = Array.zeroCreate buflen let tables, counts = if t = 2 then Array2D.zeroCreate 4096 16, Array.create 4096 0 else null, null let hash = if tables = null then [| for _ in 0..4095 -> new List() |] else null let mutable crc = ~~~0u let read pos len = let rlen = sin.Read(buf, pos, len) if rlen < len then length <- pos + rlen for i = pos to pos + rlen - 1 do let b = int(crc ^^^ (uint32 buf.[i])) &&& 0xff crc <- (crc >>> 8) ^^^ crc32_table.[b] if hash <> null then for list in hash do list.Clear() else Array.fill counts 0 counts.Length 0 do read 0 buflen let search (pos:int) = let mutable maxp = -1 let mutable maxl = 2 let mlen = Math.Min(maxlen, length - pos) let last = Math.Max(0, pos - maxbuf) let h = getHash buf pos if hash <> null then let list = hash.[h] let mutable i = list.Count - 1 while i >= 0 do let p = list.[i] if p < last then i <- 0 else let mutable len = 0 while len < mlen && buf.[p + len] = buf.[pos + len] do len <- len + 1 if len > maxl then maxp <- p maxl <- len i <- i - 1 else let c = counts.[h] let p1, p2 = if c < 16 then 0, c - 1 else c + 1, c + 16 let mutable i = p2 while i >= p1 do let p = tables.[h, i &&& 15] if p < last then i <- 0 else let mutable len = 0 while len < mlen && buf.[p + len] = buf.[pos + len] do len <- len + 1 if len > maxl then maxp <- p maxl <- len i <- i - 1 maxp, maxl member x.Crc = ~~~crc member x.Compress (sout:Stream) = use bw = new BitWriter(sout) bw.WriteBit 1 bw.WriteLE 2 1 let hw = new FixedHuffmanWriter(bw) let mutable p = 0 match t with | 2 -> while p < length do let b = buf.[p] if p < length - 4 && b = buf.[p + 1] && b = buf.[p + 2] && b = buf.[p + 3] then let mutable len = 4 let mlen = Math.Min(maxlen + 1, length - p) while len < mlen && b = buf.[p + len] do len <- len + 1 hw.Write(int b) hw.WriteLen(len - 1) hw.WriteDist 1 p <- p + len else let maxp, maxl = search p if maxp < 0 then hw.Write(int b) addHash2 tables counts buf p p <- p + 1 else hw.WriteLen maxl hw.WriteDist (p - maxp) for i = p to p + maxl - 1 do addHash2 tables counts buf i p <- p + maxl if p > maxbuf2 then Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen) if length < buflen then length <- length - maxbuf else read (maxbuf + maxlen) maxbuf p <- p - maxbuf for i = 0 to p - 1 do addHash2 tables counts buf i | 1 -> while p < length do let b = buf.[p] if p < length - 4 && b = buf.[p + 1] && b = buf.[p + 2] && b = buf.[p + 3] then let mutable len = 4 let mlen = Math.Min(maxlen + 1, length - p) while len < mlen && b = buf.[p + len] do len <- len + 1 hw.Write(int b) hw.WriteLen(len - 1) hw.WriteDist 1 p <- p + len else let maxp, maxl = search p if maxp < 0 then hw.Write(int b) addHash hash buf p p <- p + 1 else hw.WriteLen maxl hw.WriteDist (p - maxp) for i = p to p + maxl - 1 do addHash hash buf i p <- p + maxl if p > maxbuf2 then Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen) if length < buflen then length <- length - maxbuf else read (maxbuf + maxlen) maxbuf p <- p - maxbuf for i = 0 to p - 1 do addHash hash buf i | _ -> while p < length do let maxp, maxl = search p if maxp < 0 then hw.Write(int buf.[p]) hash.[getHash buf p].Add p p <- p + 1 else hw.WriteLen maxl hw.WriteDist (p - maxp) for i = p to p + maxl - 1 do hash.[getHash buf i].Add i p <- p + maxl if p > maxbuf2 then Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen) if length < buflen then length <- length - maxbuf else read (maxbuf + maxlen) maxbuf p <- p - maxbuf for i = 0 to p - 1 do hash.[getHash buf i].Add i hw.Write 256 let GetCompressBytes (sin:Stream) = let now = DateTime.Now let ms = new MemoryStream() let w = new Writer(1, sin) w.Compress ms ms.ToArray(), w.Crc pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Error.pmod000066400000000000000000000016751250413007300256530ustar00rootroot00000000000000#pike __REAL_VERSION__ constant Generic = __builtin.GenericError; constant Index = __builtin.IndexError; constant BadArgument = __builtin.BadArgumentError; constant Math = __builtin.MathError; constant Resource = __builtin.ResourceError; constant Permission = __builtin.PermissionError; constant Decode = __builtin.DecodeError; constant Cpp = __builtin.CppError; constant Compilation = __builtin.CompilationError; constant MasterLoad = __builtin.MasterLoadError; constant ModuleLoad = __builtin.ModuleLoadError; //! Returns an Error object for any argument it receives. If the //! argument already is an Error object or is empty, it does nothing. object mkerror(mixed error) { if (error == UNDEFINED) return error; if (objectp(error) && error->is_generic_error) return error; if (arrayp(error)) return Error.Generic(@error); if (stringp(error)) return Error.Generic(error); return Error.Generic(sprintf("%O", error)); }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Errors.scala000066400000000000000000000005071250413007300261530ustar00rootroot00000000000000/* This file /* which is totally legal scala */ will not be highlighted correcty by pygments */ object ⌘ { val `interface` = """ A "Multiline" String """ val foo_+ = "foo plus" val foo_⌬⌬ = "double benzene" def main(argv: Array[String]) { println(⌘.interface + " " + foo_+ + " " + foo_⌬⌬ ) } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/FakeFile.pike000066400000000000000000000165421250413007300262200ustar00rootroot00000000000000#pike __REAL_VERSION__ //! A string wrapper that pretends to be a @[Stdio.File] object //! in addition to some features of a @[Stdio.FILE] object. //! This constant can be used to distinguish a FakeFile object //! from a real @[Stdio.File] object. constant is_fake_file = 1; protected string data; protected int ptr; protected int(0..1) r; protected int(0..1) w; protected int mtime; protected function read_cb; protected function read_oob_cb; protected function write_cb; protected function write_oob_cb; protected function close_cb; //! @seealso //! @[Stdio.File()->close()] int close(void|string direction) { direction = lower_case(direction||"rw"); int cr = has_value(direction, "r"); int cw = has_value(direction, "w"); if(cr) { r = 0; } if(cw) { w = 0; } // FIXME: Close callback return 1; } //! @decl void create(string data, void|string type, void|int pointer) //! @seealso //! @[Stdio.File()->create()] void create(string _data, void|string type, int|void _ptr) { if(!_data) error("No data string given to FakeFile.\n"); data = _data; ptr = _ptr; mtime = time(); if(type) { type = lower_case(type); if(has_value(type, "r")) r = 1; if(has_value(type, "w")) w = 1; } else r = w = 1; } protected string make_type_str() { string type = ""; if(r) type += "r"; if(w) type += "w"; return type; } //! @seealso //! @[Stdio.File()->dup()] this_program dup() { return this_program(data, make_type_str(), ptr); } //! Always returns 0. //! @seealso //! @[Stdio.File()->errno()] int errno() { return 0; } //! Returns size and the creation time of the string. Stdio.Stat stat() { Stdio.Stat st = Stdio.Stat(); st->size = sizeof(data); st->mtime=st->ctime=mtime; st->atime=time(); return st; } //! @seealso //! @[Stdio.File()->line_iterator()] String.SplitIterator line_iterator(int|void trim) { if(trim) return String.SplitIterator( data-"\r", '\n' ); return String.SplitIterator( data, '\n' ); } protected mixed id; //! @seealso //! @[Stdio.File()->query_id()] mixed query_id() { return id; } //! @seealso //! @[Stdio.File()->set_id()] void set_id(mixed _id) { id = _id; } //! @seealso //! @[Stdio.File()->read_function()] function(:string) read_function(int nbytes) { return lambda() { return read(nbytes); }; } //! @seealso //! @[Stdio.File()->peek()] int(-1..1) peek(int|float|void timeout) { if(!r) return -1; if(ptr >= sizeof(data)) return 0; return 1; } //! Always returns 0. //! @seealso //! @[Stdio.File()->query_address()] string query_address(void|int(0..1) is_local) { return 0; } //! @seealso //! @[Stdio.File()->read()] string read(void|int(0..) len, void|int(0..1) not_all) { if(!r) return 0; if (len < 0) error("Cannot read negative number of characters.\n"); int start=ptr; ptr += len; if(zero_type(len) || ptr>sizeof(data)) ptr = sizeof(data); // FIXME: read callback return data[start..ptr-1]; } //! @seealso //! @[Stdio.FILE()->gets()] string gets() { if(!r) return 0; string ret; sscanf(data,"%*"+(string)ptr+"s%[^\n]",ret); if(ret) { ptr+=sizeof(ret)+1; if(ptr>sizeof(data)) { ptr=sizeof(data); if(!sizeof(ret)) ret = 0; } } // FIXME: read callback return ret; } //! @seealso //! @[Stdio.FILE()->getchar()] int getchar() { if(!r) return 0; int c; if(catch(c=data[ptr])) c=-1; else ptr++; // FIXME: read callback return c; } //! @seealso //! @[Stdio.FILE()->unread()] void unread(string s) { if(!r) return; if(data[ptr-sizeof(s)..ptr-1]==s) ptr-=sizeof(s); else { data=s+data[ptr..]; ptr=0; } } //! @seealso //! @[Stdio.File()->seek()] int seek(int pos, void|int mult, void|int add) { if(mult) pos = pos*mult+add; if(pos<0) { pos = sizeof(data)+pos; if( pos < 0 ) pos = 0; } ptr = pos; if( ptr > strlen( data ) ) ptr = strlen(data); return ptr; } //! Always returns 1. //! @seealso //! @[Stdio.File()->sync()] int(1..1) sync() { return 1; } //! @seealso //! @[Stdio.File()->tell()] int tell() { return ptr; } //! @seealso //! @[Stdio.File()->truncate()] int(0..1) truncate(int length) { data = data[..length-1]; return sizeof(data)==length; } //! @seealso //! @[Stdio.File()->write()] int(-1..) write(string|array(string) str, mixed ... extra) { if(!w) return -1; if(arrayp(str)) str=str*""; if(sizeof(extra)) str=sprintf(str, @extra); if(ptr==sizeof(data)) { data += str; ptr = sizeof(data); } else if(sizeof(str)==1) data[ptr++] = str[0]; else { data = data[..ptr-1] + str + data[ptr+sizeof(str)..]; ptr += sizeof(str); } // FIXME: write callback return sizeof(str); } //! @seealso //! @[Stdio.File()->set_blocking] void set_blocking() { close_cb = 0; read_cb = 0; read_oob_cb = 0; write_cb = 0; write_oob_cb = 0; } //! @seealso //! @[Stdio.File()->set_blocking_keep_callbacks] void set_blocking_keep_callbacks() { } //! @seealso //! @[Stdio.File()->set_blocking] void set_nonblocking(function rcb, function wcb, function ccb, function rocb, function wocb) { read_cb = rcb; write_cb = wcb; close_cb = ccb; read_oob_cb = rocb; write_oob_cb = wocb; } //! @seealso //! @[Stdio.File()->set_blocking_keep_callbacks] void set_nonblocking_keep_callbacks() { } //! @seealso //! @[Stdio.File()->set_close_callback] void set_close_callback(function cb) { close_cb = cb; } //! @seealso //! @[Stdio.File()->set_read_callback] void set_read_callback(function cb) { read_cb = cb; } //! @seealso //! @[Stdio.File()->set_read_oob_callback] void set_read_oob_callback(function cb) { read_oob_cb = cb; } //! @seealso //! @[Stdio.File()->set_write_callback] void set_write_callback(function cb) { write_cb = cb; } //! @seealso //! @[Stdio.File()->set_write_oob_callback] void set_write_oob_callback(function cb) { write_oob_cb = cb; } //! @seealso //! @[Stdio.File()->query_close_callback] function query_close_callback() { return close_cb; } //! @seealso //! @[Stdio.File()->query_read_callback] function query_read_callback() { return read_cb; } //! @seealso //! @[Stdio.File()->query_read_oob_callback] function query_read_oob_callback() { return read_oob_cb; } //! @seealso //! @[Stdio.File()->query_write_callback] function query_write_callback() { return write_cb; } //! @seealso //! @[Stdio.File()->query_write_oob_callback] function query_write_oob_callback() { return write_oob_cb; } string _sprintf(int t) { return t=='O' && sprintf("%O(%d,%O)", this_program, sizeof(data), make_type_str()); } // FakeFile specials. //! A FakeFile can be casted to a string. mixed cast(string to) { switch(to) { case "string": return data; case "object": return this; } error("Can not cast object to %O.\n", to); } //! Sizeof on a FakeFile returns the size of its contents. int(0..) _sizeof() { return sizeof(data); } //! @ignore #define NOPE(X) mixed X (mixed ... args) { error("This is a FakeFile. %s is not available.\n", #X); } NOPE(assign); NOPE(async_connect); NOPE(connect); NOPE(connect_unix); NOPE(open); NOPE(open_socket); NOPE(pipe); NOPE(tcgetattr); NOPE(tcsetattr); // Stdio.Fd NOPE(dup2); NOPE(lock); // We could implement this NOPE(mode); // We could implement this NOPE(proxy); // We could implement this NOPE(query_fd); NOPE(read_oob); NOPE(set_close_on_exec); NOPE(set_keepalive); NOPE(trylock); // We could implement this NOPE(write_oob); //! @endignorepygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Get-CommandDefinitionHtml.ps1000066400000000000000000000024501250413007300312470ustar00rootroot00000000000000 function Get-CommandDefinitionHtml { # this tells powershell to allow advanced features, # like the [validatenotnullorempty()] attribute below. [CmdletBinding()] param( [ValidateNotNullOrEmpty()] [string]$name ) $command = get-command $name # Look mom! I'm a cmdlet! $PSCmdlet.WriteVerbose("Dumping HTML for " + $command) @" $($command.name) $( $command.parametersets | % { @" "@ } )
$($_.name) $( $count = 0 $_.parameters | % { if (0 -eq ($count % 8)) { @' '@ } @" "@ $count++ } )
Parameters
$($_.name)
"@ } Get-CommandDefinitionHtml get-item > out.html # show in browser invoke-item out.html pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/IPDispatchC.nc000066400000000000000000000066231250413007300263140ustar00rootroot00000000000000/* * "Copyright (c) 2008-2011 The Regents of the University of California. * All rights reserved." * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * */ /** * * */ #include "IPDispatch.h" #include "BlipStatistics.h" configuration IPDispatchC { provides { interface SplitControl; interface IPLower; interface BlipStatistics; } } implementation { components MainC; components NoLedsC as LedsC; /* IPDispatchP wiring -- fragment rassembly and lib6lowpan bindings */ components IPDispatchP; components CC2420RadioC as MessageC; components ReadLqiC; components new TimerMilliC(); SplitControl = IPDispatchP.SplitControl; IPLower = IPDispatchP; BlipStatistics = IPDispatchP; IPDispatchP.Boot -> MainC; /* #else */ /* components ResourceSendP; */ /* ResourceSendP.SubSend -> MessageC; */ /* ResourceSendP.Resource -> MessageC.SendResource[unique("RADIO_SEND_RESOURCE")]; */ /* IPDispatchP.Ieee154Send -> ResourceSendP.Ieee154Send; */ /* #endif */ IPDispatchP.RadioControl -> MessageC; IPDispatchP.BarePacket -> MessageC.BarePacket; IPDispatchP.Ieee154Send -> MessageC.BareSend; IPDispatchP.Ieee154Receive -> MessageC.BareReceive; #ifdef LOW_POWER_LISTENING IPDispatchP.LowPowerListening -> MessageC; #endif MainC.SoftwareInit -> IPDispatchP.Init; IPDispatchP.PacketLink -> MessageC; IPDispatchP.ReadLqi -> ReadLqiC; IPDispatchP.Leds -> LedsC; IPDispatchP.ExpireTimer -> TimerMilliC; components new PoolC(message_t, N_FRAGMENTS) as FragPool; components new PoolC(struct send_entry, N_FRAGMENTS) as SendEntryPool; components new QueueC(struct send_entry *, N_FRAGMENTS); components new PoolC(struct send_info, N_CONCURRENT_SENDS) as SendInfoPool; IPDispatchP.FragPool -> FragPool; IPDispatchP.SendEntryPool -> SendEntryPool; IPDispatchP.SendInfoPool -> SendInfoPool; IPDispatchP.SendQueue -> QueueC; components IPNeighborDiscoveryP; IPDispatchP.NeighborDiscovery -> IPNeighborDiscoveryP; /* components ICMPResponderC; */ /* #ifdef BLIP_MULTICAST */ /* components MulticastP; */ /* components new TrickleTimerMilliC(2, 30, 2, 1); */ /* IP = MulticastP.IP; */ /* MainC.SoftwareInit -> MulticastP.Init; */ /* MulticastP.MulticastRx -> IPDispatchP.Multicast; */ /* MulticastP.HopHeader -> IPExtensionP.HopByHopExt[0]; */ /* MulticastP.TrickleTimer -> TrickleTimerMilliC.TrickleTimer[0]; */ /* MulticastP.IPExtensions -> IPDispatchP; */ /* #endif */ #ifdef DELUGE components NWProgC; #endif } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/IPDispatchP.nc000066400000000000000000000473761250413007300263430ustar00rootroot00000000000000/* * "Copyright (c) 2008 The Regents of the University of California. * All rights reserved." * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * */ #include #include #include #include #include #include #include "blip_printf.h" #include "IPDispatch.h" #include "BlipStatistics.h" #include "table.h" /* * Provides IP layer reception to applications on motes. * * @author Stephen Dawson-Haggerty */ module IPDispatchP { provides { interface SplitControl; // interface for protocols not requiring special hand-holding interface IPLower; interface BlipStatistics; } uses { interface Boot; /* link-layer wiring */ interface SplitControl as RadioControl; interface Packet as BarePacket; interface Send as Ieee154Send; interface Receive as Ieee154Receive; /* context lookup */ interface NeighborDiscovery; interface ReadLqi; interface PacketLink; interface LowPowerListening; /* buffers for outgoing fragments */ interface Pool as FragPool; interface Pool as SendInfoPool; interface Pool as SendEntryPool; interface Queue as SendQueue; /* expire reconstruction */ interface Timer as ExpireTimer; interface Leds; } provides interface Init; } implementation { #define HAVE_LOWPAN_EXTERN_MATCH_CONTEXT int lowpan_extern_read_context(struct in6_addr *addr, int context) { return call NeighborDiscovery.getContext(context, addr); } int lowpan_extern_match_context(struct in6_addr *addr, uint8_t *ctx_id) { return call NeighborDiscovery.matchContext(addr, ctx_id); } // generally including source files like this is a no-no. I'm doing // this in the hope that the optimizer will do a better job when // they're part of a component. #include #include #include #include enum { S_RUNNING, S_STOPPED, S_STOPPING, }; uint8_t state = S_STOPPED; bool radioBusy; uint8_t current_local_label = 0; ip_statistics_t stats; // this in theory could be arbitrarily large; however, it needs to // be large enough to hold all active reconstructions, and any tags // which we are dropping. It's important to keep dropped tags // around for a while, or else there are pathological situations // where you continually allocate buffers for packets which will // never complete. //////////////////////////////////////// // // table_t recon_cache; // table of packets we are currently receiving fragments from, that // are destined to us struct lowpan_reconstruct recon_data[N_RECONSTRUCTIONS]; // // //////////////////////////////////////// // task void sendTask(); void reconstruct_clear(void *ent) { struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)ent; memclr((uint8_t *)&recon->r_meta, sizeof(struct ip6_metadata)); recon->r_timeout = T_UNUSED; recon->r_buf = NULL; } struct send_info *getSendInfo() { struct send_info *ret = call SendInfoPool.get(); if (ret == NULL) return ret; ret->_refcount = 1; ret->upper_data = NULL; ret->failed = FALSE; ret->link_transmissions = 0; ret->link_fragments = 0; ret->link_fragment_attempts = 0; return ret; } #define SENDINFO_INCR(X) ((X)->_refcount)++ void SENDINFO_DECR(struct send_info *si) { if (--(si->_refcount) == 0) { call SendInfoPool.put(si); } } command error_t SplitControl.start() { return call RadioControl.start(); } command error_t SplitControl.stop() { if (!radioBusy) { state = S_STOPPED; return call RadioControl.stop(); } else { // if there's a packet in the radio, wait for it to exit before // stopping state = S_STOPPING; return SUCCESS; } } event void RadioControl.startDone(error_t error) { #ifdef LPL_SLEEP_INTERVAL call LowPowerListening.setLocalWakeupInterval(LPL_SLEEP_INTERVAL); #endif if (error == SUCCESS) { call Leds.led2Toggle(); call ExpireTimer.startPeriodic(FRAG_EXPIRE_TIME); state = S_RUNNING; radioBusy = FALSE; } signal SplitControl.startDone(error); } event void RadioControl.stopDone(error_t error) { signal SplitControl.stopDone(error); } command error_t Init.init() { // ip_malloc_init needs to be in init, not booted, because // context for coap is initialised in init ip_malloc_init(); return SUCCESS; } event void Boot.booted() { call BlipStatistics.clear(); /* set up our reconstruction cache */ table_init(&recon_cache, recon_data, sizeof(struct lowpan_reconstruct), N_RECONSTRUCTIONS); table_map(&recon_cache, reconstruct_clear); call SplitControl.start(); } /* * Receive-side code. */ void deliver(struct lowpan_reconstruct *recon) { struct ip6_hdr *iph = (struct ip6_hdr *)recon->r_buf; // printf("deliver [%i]: ", recon->r_bytes_rcvd); // printf_buf(recon->r_buf, recon->r_bytes_rcvd); /* the payload length field is always compressed, have to put it back here */ iph->ip6_plen = htons(recon->r_bytes_rcvd - sizeof(struct ip6_hdr)); signal IPLower.recv(iph, (void *)(iph + 1), &recon->r_meta); // printf("ip_free(%p)\n", recon->r_buf); ip_free(recon->r_buf); recon->r_timeout = T_UNUSED; recon->r_buf = NULL; } /* * Bulletproof recovery logic is very important to make sure we * don't get wedged with no free buffers. * * The table is managed as follows: * - unused entries are marked T_UNUSED * - entries which * o have a buffer allocated * o have had a fragment reception before we fired * are marked T_ACTIVE * - entries which have not had a fragment reception during the last timer period * and were active are marked T_ZOMBIE * - zombie receptions are deleted: their buffer is freed and table entry marked unused. * - when a fragment is dropped, it is entered into the table as T_FAILED1. * no buffer is allocated * - when the timer fires, T_FAILED1 entries are aged to T_FAILED2. * - T_FAILED2 entries are deleted. Incomming fragments with tags * that are marked either FAILED1 or FAILED2 are dropped; this * prevents us from allocating a buffer for a packet which we * have already dropped fragments from. * */ void reconstruct_age(void *elt) { struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)elt; if (recon->r_timeout != T_UNUSED) printf("recon src: 0x%x tag: 0x%x buf: %p recvd: %i/%i\n", recon->r_source_key, recon->r_tag, recon->r_buf, recon->r_bytes_rcvd, recon->r_size); switch (recon->r_timeout) { case T_ACTIVE: recon->r_timeout = T_ZOMBIE; break; // age existing receptions case T_FAILED1: recon->r_timeout = T_FAILED2; break; // age existing receptions case T_ZOMBIE: case T_FAILED2: // deallocate the space for reconstruction printf("timing out buffer: src: %i tag: %i\n", recon->r_source_key, recon->r_tag); if (recon->r_buf != NULL) { printf("ip_free(%p)\n", recon->r_buf); ip_free(recon->r_buf); } recon->r_timeout = T_UNUSED; recon->r_buf = NULL; break; } } void ip_print_heap() { #ifdef PRINTFUART_ENABLED bndrt_t *cur = (bndrt_t *)heap; while (((uint8_t *)cur) - heap < IP_MALLOC_HEAP_SIZE) { printf ("heap region start: %p length: %u used: %u\n", cur, (*cur & IP_MALLOC_LEN), (*cur & IP_MALLOC_INUSE) >> 15); cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN)); } #endif } event void ExpireTimer.fired() { table_map(&recon_cache, reconstruct_age); printf("Frag pool size: %i\n", call FragPool.size()); printf("SendInfo pool size: %i\n", call SendInfoPool.size()); printf("SendEntry pool size: %i\n", call SendEntryPool.size()); printf("Forward queue length: %i\n", call SendQueue.size()); ip_print_heap(); printfflush(); } /* * allocate a structure for recording information about incomming fragments. */ struct lowpan_reconstruct *get_reconstruct(uint16_t key, uint16_t tag) { struct lowpan_reconstruct *ret = NULL; int i; // printf("get_reconstruct: %x %i\n", key, tag); for (i = 0; i < N_RECONSTRUCTIONS; i++) { struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)&recon_data[i]; if (recon->r_tag == tag && recon->r_source_key == key) { if (recon->r_timeout > T_UNUSED) { recon->r_timeout = T_ACTIVE; ret = recon; goto done; } else if (recon->r_timeout < T_UNUSED) { // if we have already tried and failed to get a buffer, we // need to drop remaining fragments. ret = NULL; goto done; } } if (recon->r_timeout == T_UNUSED) ret = recon; } done: // printf("got%p\n", ret); return ret; } event message_t *Ieee154Receive.receive(message_t *msg, void *msg_payload, uint8_t len) { struct packed_lowmsg lowmsg; struct ieee154_frame_addr frame_address; uint8_t *buf = msg_payload; // printf(" -- RECEIVE -- len : %i\n", len); BLIP_STATS_INCR(stats.rx_total); /* unpack the 802.15.4 address fields */ buf = unpack_ieee154_hdr(msg_payload, &frame_address); len -= buf - (uint8_t *)msg_payload; /* unpack and 6lowpan headers */ lowmsg.data = buf; lowmsg.len = len; lowmsg.headers = getHeaderBitmap(&lowmsg); if (lowmsg.headers == LOWMSG_NALP) { goto fail; } if (hasFrag1Header(&lowmsg) || hasFragNHeader(&lowmsg)) { // start reassembly int rv; struct lowpan_reconstruct *recon; uint16_t tag, source_key; source_key = ieee154_hashaddr(&frame_address.ieee_src); getFragDgramTag(&lowmsg, &tag); recon = get_reconstruct(source_key, tag); if (!recon) { goto fail; } /* fill in metadata: on fragmented packets, it applies to the first fragment only */ memcpy(&recon->r_meta.sender, &frame_address.ieee_src, sizeof(ieee154_addr_t)); recon->r_meta.lqi = call ReadLqi.readLqi(msg); recon->r_meta.rssi = call ReadLqi.readRssi(msg); if (hasFrag1Header(&lowmsg)) { if (recon->r_buf != NULL) goto fail; rv = lowpan_recon_start(&frame_address, recon, buf, len); } else { rv = lowpan_recon_add(recon, buf, len); } if (rv < 0) { recon->r_timeout = T_FAILED1; goto fail; } else { // printf("start recon buf: %p\n", recon->r_buf); recon->r_timeout = T_ACTIVE; recon->r_source_key = source_key; recon->r_tag = tag; } if (recon->r_size == recon->r_bytes_rcvd) { deliver(recon); } } else { /* no fragmentation, just deliver it */ int rv; struct lowpan_reconstruct recon; /* fill in metadata */ memcpy(&recon.r_meta.sender, &frame_address.ieee_src, sizeof(ieee154_addr_t)); recon.r_meta.lqi = call ReadLqi.readLqi(msg); recon.r_meta.rssi = call ReadLqi.readRssi(msg); buf = getLowpanPayload(&lowmsg); if ((rv = lowpan_recon_start(&frame_address, &recon, buf, len)) < 0) { goto fail; } if (recon.r_size == recon.r_bytes_rcvd) { deliver(&recon); } else { // printf("ip_free(%p)\n", recon.r_buf); ip_free(recon.r_buf); } } goto done; fail: BLIP_STATS_INCR(stats.rx_drop); done: return msg; } /* * Send-side functionality */ task void sendTask() { struct send_entry *s_entry; // printf("sendTask() - sending\n"); if (radioBusy || state != S_RUNNING) return; if (call SendQueue.empty()) return; // this does not dequeue s_entry = call SendQueue.head(); #ifdef LPL_SLEEP_INTERVAL call LowPowerListening.setRemoteWakeupInterval(s_entry->msg, call LowPowerListening.getLocalWakeupInterval()); #endif if (s_entry->info->failed) { dbg("Drops", "drops: sendTask: dropping failed fragment\n"); goto fail; } if ((call Ieee154Send.send(s_entry->msg, call BarePacket.payloadLength(s_entry->msg))) != SUCCESS) { dbg("Drops", "drops: sendTask: send failed\n"); goto fail; } else { radioBusy = TRUE; } return; fail: printf("SEND FAIL\n"); post sendTask(); BLIP_STATS_INCR(stats.tx_drop); // deallocate the memory associated with this request. // other fragments associated with this packet will get dropped. s_entry->info->failed = TRUE; SENDINFO_DECR(s_entry->info); call FragPool.put(s_entry->msg); call SendEntryPool.put(s_entry); call SendQueue.dequeue(); } /* * it will pack the message into the fragment pool and enqueue * those fragments for sending * * it will set * - payload length * - version, traffic class and flow label * * the source and destination IP addresses must be set by higher * layers. */ command error_t IPLower.send(struct ieee154_frame_addr *frame_addr, struct ip6_packet *msg, void *data) { struct lowpan_ctx ctx; struct send_info *s_info; struct send_entry *s_entry; message_t *outgoing; int frag_len = 1; error_t rc = SUCCESS; if (state != S_RUNNING) { return EOFF; } /* set version to 6 in case upper layers forgot */ msg->ip6_hdr.ip6_vfc &= ~IPV6_VERSION_MASK; msg->ip6_hdr.ip6_vfc |= IPV6_VERSION; ctx.tag = current_local_label++; ctx.offset = 0; s_info = getSendInfo(); if (s_info == NULL) { rc = ERETRY; goto cleanup_outer; } s_info->upper_data = data; while (frag_len > 0) { s_entry = call SendEntryPool.get(); outgoing = call FragPool.get(); if (s_entry == NULL || outgoing == NULL) { if (s_entry != NULL) call SendEntryPool.put(s_entry); if (outgoing != NULL) call FragPool.put(outgoing); // this will cause any fragments we have already enqueued to // be dropped by the send task. s_info->failed = TRUE; printf("drops: IP send: no fragments\n"); rc = ERETRY; goto done; } call BarePacket.clear(outgoing); frag_len = lowpan_frag_get(call Ieee154Send.getPayload(outgoing, 0), call BarePacket.maxPayloadLength(), msg, frame_addr, &ctx); if (frag_len < 0) { printf(" get frag error: %i\n", frag_len); } printf("fragment length: %i offset: %i\n", frag_len, ctx.offset); call BarePacket.setPayloadLength(outgoing, frag_len); if (frag_len <= 0) { call FragPool.put(outgoing); call SendEntryPool.put(s_entry); goto done; } if (call SendQueue.enqueue(s_entry) != SUCCESS) { BLIP_STATS_INCR(stats.encfail); s_info->failed = TRUE; printf("drops: IP send: enqueue failed\n"); goto done; } s_info->link_fragments++; s_entry->msg = outgoing; s_entry->info = s_info; /* configure the L2 */ if (frame_addr->ieee_dst.ieee_mode == IEEE154_ADDR_SHORT && frame_addr->ieee_dst.i_saddr == IEEE154_BROADCAST_ADDR) { call PacketLink.setRetries(s_entry->msg, 0); } else { call PacketLink.setRetries(s_entry->msg, BLIP_L2_RETRIES); } call PacketLink.setRetryDelay(s_entry->msg, BLIP_L2_DELAY); SENDINFO_INCR(s_info);} // printf("got %i frags\n", s_info->link_fragments); done: BLIP_STATS_INCR(stats.sent); SENDINFO_DECR(s_info); post sendTask(); cleanup_outer: return rc; } event void Ieee154Send.sendDone(message_t *msg, error_t error) { struct send_entry *s_entry = call SendQueue.head(); radioBusy = FALSE; // printf("sendDone: %p %i\n", msg, error); if (state == S_STOPPING) { call RadioControl.stop(); state = S_STOPPED; goto done; } s_entry->info->link_transmissions += (call PacketLink.getRetries(msg)); s_entry->info->link_fragment_attempts++; if (!call PacketLink.wasDelivered(msg)) { printf("sendDone: was not delivered! (%i tries)\n", call PacketLink.getRetries(msg)); s_entry->info->failed = TRUE; signal IPLower.sendDone(s_entry->info); /* if (s_entry->info->policy.dest[0] != 0xffff) */ /* dbg("Drops", "drops: sendDone: frag was not delivered\n"); */ // need to check for broadcast frames // BLIP_STATS_INCR(stats.tx_drop); } else if (s_entry->info->link_fragment_attempts == s_entry->info->link_fragments) { signal IPLower.sendDone(s_entry->info); } done: // kill off any pending fragments SENDINFO_DECR(s_entry->info); call FragPool.put(s_entry->msg); call SendEntryPool.put(s_entry); call SendQueue.dequeue(); post sendTask(); } #if 0 command struct tlv_hdr *IPExtensions.findTlv(struct ip6_ext *ext, uint8_t tlv_val) { int len = ext->len - sizeof(struct ip6_ext); struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1); while (len > 0) { if (tlv->type == tlv_val) return tlv; if (tlv->len == 0) return NULL; tlv = (struct tlv_hdr *)(((uint8_t *)tlv) + tlv->len); len -= tlv->len; } return NULL; } #endif /* * BlipStatistics interface */ command void BlipStatistics.get(ip_statistics_t *statistics) { #ifdef BLIP_STATS_IP_MEM stats.fragpool = call FragPool.size(); stats.sendinfo = call SendInfoPool.size(); stats.sendentry= call SendEntryPool.size(); stats.sndqueue = call SendQueue.size(); stats.heapfree = ip_malloc_freespace(); printf("frag: %i sendinfo: %i sendentry: %i sendqueue: %i heap: %i\n", stats.fragpool, stats.sendinfo, stats.sendentry, stats.sndqueue, stats.heapfree); #endif memcpy(statistics, &stats, sizeof(ip_statistics_t)); } command void BlipStatistics.clear() { memclr((uint8_t *)&stats, sizeof(ip_statistics_t)); } /* default event void IP.recv[uint8_t nxt_hdr](struct ip6_hdr *iph, */ /* void *payload, */ /* struct ip_metadata *meta) { */ /* } */ /* default event void Multicast.recv[uint8_t scope](struct ip6_hdr *iph, */ /* void *payload, */ /* struct ip_metadata *meta) { */ /* } */ } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Intro.java000066400000000000000000001706431250413007300256410ustar00rootroot00000000000000/* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN * IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or intended for * use in the design, construction, operation or maintenance of any nuclear * facility. */ package java2d; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.font.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; import javax.swing.event.*; import java.util.Vector; import java.util.List; import java.util.Arrays; /** * Introduction to the Java2Demo. * * @version @(#)Intro.java 1.19 03/06/26 * @author Brian Lichtenwalter */ public class Intro extends JPanel { static Color black = new Color(20, 20, 20); static Color white = new Color(240, 240, 255); static Color red = new Color(149, 43, 42); static Color blue = new Color(94, 105, 176); static Color yellow = new Color(255, 255, 140); static Surface surface; private ScenesTable scenesTable; private boolean doTable; public Intro() { EmptyBorder eb = new EmptyBorder(80,110,80,110); BevelBorder bb = new BevelBorder(BevelBorder.LOWERED); setBorder(new CompoundBorder(eb,bb)); setLayout(new BorderLayout()); setBackground(Color.gray); setToolTipText("click for scene table"); add(surface = new Surface()); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { removeAll(); if ((doTable = !doTable)) { setToolTipText("click for animation"); surface.stop(); if (scenesTable == null) { scenesTable = new ScenesTable(); } add(scenesTable); } else { setToolTipText("click for scene table"); surface.start(); add(surface); } revalidate(); repaint(); } }); } public void start() { if (!doTable) { surface.start(); } } public void stop() { if (!doTable) { surface.stop(); } } public static void main(String argv[]) { final Intro intro = new Intro(); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} public void windowDeiconified(WindowEvent e) { intro.start(); } public void windowIconified(WindowEvent e) { intro.stop(); } }; JFrame f = new JFrame("Java2D Demo - Intro"); f.addWindowListener(l); f.getContentPane().add("Center", intro); f.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int w = 720; int h = 510; f.setLocation(screenSize.width/2 - w/2, screenSize.height/2 - h/2); f.setSize(w, h); f.setVisible(true); intro.start(); } /** * ScenesTable is the list of scenes known to the Director. * Scene participation, scene name and scene pause amount columns. * Global animation delay for scene's steps. */ static class ScenesTable extends JPanel implements ActionListener, ChangeListener { private JTable table; private TableModel dataModel; public ScenesTable() { setBackground(Color.white); setLayout(new BorderLayout()); final String[] names = { "", "Scenes", "Pause" }; dataModel = new AbstractTableModel() { public int getColumnCount() { return names.length; } public int getRowCount() { return surface.director.size();} public Object getValueAt(int row, int col) { Surface.Scene scene = (Surface.Scene) surface.director.get(row); if (col == 0) { return scene.participate; } else if (col == 1) { return scene.name; } else { return scene.pauseAmt; } } public String getColumnName(int col) {return names[col]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int col) { return col != 1 ? true : false; } public void setValueAt(Object aValue, int row, int col) { Surface.Scene scene = (Surface.Scene) surface.director.get(row); if (col == 0) { scene.participate = aValue; } else if (col == 1) { scene.name = aValue; } else { scene.pauseAmt = aValue; } } }; table = new JTable(dataModel); TableColumn col = table.getColumn(""); col.setWidth(16); col.setMinWidth(16); col.setMaxWidth(20); col = table.getColumn("Pause"); col.setWidth(60); col.setMinWidth(60); col.setMaxWidth(60); table.sizeColumnsToFit(0); JScrollPane scrollpane = new JScrollPane(table); add(scrollpane); JPanel panel = new JPanel(new BorderLayout()); JButton b = new JButton("Unselect All"); b.setHorizontalAlignment(JButton.LEFT); Font font = new Font("serif", Font.PLAIN, 10); b.setFont(font); b.addActionListener(this); panel.add("West", b); JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 200, (int) surface.sleepAmt); slider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle("Anim delay = " + String.valueOf(surface.sleepAmt) + " ms"); slider.setBorder(tb); slider.setPreferredSize(new Dimension(140,40)); slider.setMinimumSize(new Dimension(100,40)); slider.setMaximumSize(new Dimension(180,40)); panel.add("East", slider); add("South", panel); } public void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); b.setSelected(!b.isSelected()); b.setText(b.isSelected() ? "Select All" : "Unselect All"); for (int i = 0; i < surface.director.size(); i++) { Surface.Scene scene = (Surface.Scene) surface.director.get(i); scene.participate = new Boolean(!b.isSelected()); } table.tableChanged(new TableModelEvent(dataModel)); } public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); tb.setTitle("Anim delay = " + String.valueOf(value) + " ms"); surface.sleepAmt = (long) value; slider.repaint(); } } // End ScenesTable class /** * Surface is the stage where the Director plays its scenes. */ static class Surface extends JPanel implements Runnable { static Surface surf; static Image cupanim, java_logo; static BufferedImage bimg; public Director director; public int index; public long sleepAmt = 30; private Thread thread; public Surface() { surf = this; setBackground(black); setLayout(new BorderLayout()); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (thread == null) start(); else stop(); } }); cupanim = DemoImages.getImage("cupanim.gif", this); java_logo = DemoImages.getImage("java_logo.png", this); director = new Director(); } static FontMetrics getMetrics(Font font) { return surf.getFontMetrics(font); } public void paint(Graphics g) { Dimension d = getSize(); if (d.width <= 0 || d.height <= 0) { return; } if (bimg == null || bimg.getWidth() != d.width || bimg.getHeight() != d.height) { bimg = getGraphicsConfiguration().createCompatibleImage(d.width, d.height); // reset future scenes for (int i = index+1; i < director.size(); i++) { ((Scene) director.get(i)).reset(d.width, d.height); } } Scene scene = (Scene) director.get(index); if (scene.index <= scene.length) { if (thread != null) { scene.step(d.width, d.height); } Graphics2D g2 = bimg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setBackground(getBackground()); g2.clearRect(0, 0, d.width, d.height); scene.render(d.width, d.height, g2); if (thread != null) { // increment scene.index after scene.render scene.index++; } g2.dispose(); } g.drawImage(bimg, 0, 0, this); } public void start() { if (thread == null) { thread = new Thread(this); thread.setPriority(Thread.MIN_PRIORITY); thread.setName("Intro"); thread.start(); } } public synchronized void stop() { if (thread != null) { thread.interrupt(); } thread = null; notifyAll(); } public void reset() { index = 0; Dimension d = getSize(); for (int i = 0; i < director.size(); i++) { ((Scene) director.get(i)).reset(d.width, d.height); } } public void run() { Thread me = Thread.currentThread(); while (thread == me && !isShowing() || getSize().width <= 0) { try { thread.sleep(500); } catch (InterruptedException e) { return; } } if (index == 0) { reset(); } while (thread == me) { Scene scene = (Scene) director.get(index); if (((Boolean) scene.participate).booleanValue()) { repaint(); try { thread.sleep(sleepAmt); } catch (InterruptedException e) { break; } if (scene.index > scene.length) { scene.pause(thread); if (++index >= director.size()) { reset(); } } } else { if (++index >= director.size()) { reset(); } } } thread = null; } /** * Part is a piece of the scene. Classes must implement Part * inorder to participate in a scene. */ interface Part { public void reset(int newwidth, int newheight); public void step(int w, int h); public void render(int w, int h, Graphics2D g2); public int getBegin(); public int getEnd(); } /** * Director is the holder of the scenes, their names & pause amounts * between scenes. */ static class Director extends Vector { GradientPaint gp = new GradientPaint(0,40,blue,38,2,black); Font f1 = new Font("serif", Font.PLAIN, 200); Font f2 = new Font("serif", Font.PLAIN, 120); Font f3 = new Font("serif", Font.PLAIN, 72); Object parts[][][] = { { { "J - scale text on gradient", "0" }, { new GpE(GpE.BURI, black, blue, 0, 20), new TxE("J", f1, TxE.SCI, yellow, 2, 20) } }, { { "2 - scale & rotate text on gradient" , "0" }, { new GpE(GpE.BURI, blue, black, 0, 22), new TxE("2", f1, TxE.RI | TxE.SCI, yellow, 2, 22) } }, { { "D - scale text on gradient", "0" }, { new GpE(GpE.BURI, black, blue, 0, 20), new TxE("D", f1, TxE.SCI, yellow, 2, 20) } }, { { "Java2D - scale & rotate text on gradient", "1000" }, { new GpE(GpE.SIH, blue, black, 0, 40), new TxE("Java2D", f2, TxE.RI | TxE.SCI, yellow, 0, 40) }}, { { "Previous scene dither dissolve out", "0"}, { new DdE(0, 20, 1) }}, { { "Graphics Features", "999" }, { new Temp(Temp.RECT, null, 0, 15), new Temp(Temp.IMG, java_logo, 2, 15), new Temp(Temp.RNA | Temp.INA, java_logo, 16, 130), new Features(Features.GRAPHICS, 16, 130) }}, { { "Java2D - texture text on gradient", "1000"}, { new GpE(GpE.WI, blue, black, 0, 20), new GpE(GpE.WD, blue, black, 21, 40), new TpE(TpE.OI | TpE.NF, black, yellow, 4, 0, 10), new TpE(TpE.OD | TpE.NF, black, yellow, 4, 11, 20), new TpE(TpE.OI | TpE.NF | TpE.HAF, black, yellow,5,21,40), new TxE("Java2D", f2, 0, null, 0, 40) }}, { { "Previous scene random close out", "0"}, { new CoE(CoE.RAND, 0, 20) } }, { { "Text Features", "999" }, { new Temp(Temp.RECT, null, 0, 15), new Temp(Temp.IMG, java_logo, 2, 15), new Temp(Temp.RNA | Temp.INA, java_logo, 16, 130), new Features(Features.TEXT, 16, 130) }}, { { "Java2D - composite text on texture", "1000"}, { new TpE(TpE.RI, black, gp, 40, 0, 20), new TpE(TpE.RD, black, gp, 40, 21, 40), new TpE(TpE.RI, black, gp, 40, 41, 60), new TxE("Java2D", f2, TxE.AC, yellow, 0, 60) }}, { { "Previous scene dither dissolve out", "0"}, { new DdE(0, 20, 4) }}, { { "Imaging Features", "999" }, { new Temp(Temp.RECT, null, 0, 15), new Temp(Temp.IMG, java_logo, 2, 15), new Temp(Temp.RNA | Temp.INA, java_logo, 16, 130), new Features(Features.IMAGES, 16, 130) }}, { { "Java2D - text on gradient", "1000" }, { new GpE(GpE.SDH, blue, black, 0, 20), new GpE(GpE.SIH, blue, black, 21, 40), new GpE(GpE.SDH, blue, black, 41, 50), new GpE(GpE.INC | GpE.NF, red, yellow, 0, 50), new TxE("Java2D", f2, TxE.NOP, null, 0, 50) }}, { { "Previous scene ellipse close out", "0"}, { new CoE(CoE.OVAL, 0, 20) } }, { { "Color Features", "999" }, { new Temp(Temp.RECT, null, 0, 15), new Temp(Temp.IMG, java_logo, 2, 15), new Temp(Temp.RNA | Temp.INA, java_logo, 16, 99), new Features(Features.COLOR, 16, 99) }}, { { "Java2D - composite and rotate text on paints", "2000" }, { new GpE(GpE.BURI, black, blue, 0, 20), new GpE(GpE.BURD, black, blue, 21, 30), new TpE(TpE.OI | TpE.HAF, black, blue, 10, 31, 40), new TxE("Java2D", f2, TxE.AC | TxE.RI, yellow, 0, 40) }}, { { "Previous scene subimage transform out", "0" }, { new SiE(60, 60, 0, 40) }}, { { "CREDITS - transform in", "1000" }, { new LnE(LnE.ACI | LnE.ZOOMI | LnE.RI, 0, 60), new TxE("CREDITS", f3, TxE.AC | TxE.SCI, Color.red,20,30), new TxE("CREDITS", f3, TxE.SCXD, Color.red, 31, 38), new TxE("CREDITS", f3, TxE.SCXI, Color.red, 39, 48), new TxE("CREDITS", f3, TxE.SCXD, Color.red, 49, 54), new TxE("CREDITS", f3, TxE.SCXI, Color.red, 55, 60) }}, { { "CREDITS - transform out", "0" }, { new LnE(LnE.ACD | LnE.ZOOMD | LnE.RD, 0, 45), new TxE("CREDITS", f3, 0, Color.red, 0, 9), new TxE("CREDITS", f3, TxE.SCD | TxE.RD, Color.red,10,30)}}, { { "Contributors", "1000" }, { new Temp(Temp.RECT, null, 0, 30), new Temp(Temp.IMG, cupanim, 4, 30), new Temp(Temp.RNA | Temp.INA, cupanim, 31, 200), new Contributors(34, 200) } }, }; public Director() { for (int i = 0; i < parts.length; i++) { Vector v = new Vector(); for (int j = 0; j < parts[i][1].length; j++) { v.addElement(parts[i][1][j]); } addElement(new Scene(v, parts[i][0][0], parts[i][0][1])); } } } /** * Scene is the manager of the parts. */ static class Scene extends Object { public Object name; public Object participate = new Boolean(true); public Object pauseAmt; public Vector parts; public int index; public int length; public Scene(Vector parts, Object name, Object pauseAmt) { this.name = name; this.parts = parts; this.pauseAmt = pauseAmt; for (int i = 0; i < parts.size(); i++) { if (((Part) parts.get(i)).getEnd() > length) { length = ((Part) parts.get(i)).getEnd(); } } } public void reset(int w, int h) { index = 0; for (int i = 0; i < parts.size(); i++) { ((Part) parts.get(i)).reset(w, h); } } public void step(int w, int h) { for (int i = 0; i < parts.size(); i++) { Part part = (Part) parts.get(i); if (index >= part.getBegin() && index <= part.getEnd()) { part.step(w, h); } } } public void render(int w, int h, Graphics2D g2) { for (int i = 0; i < parts.size(); i++) { Part part = (Part) parts.get(i); if (index >= part.getBegin() && index <= part.getEnd()) { part.render(w, h, g2); } } } public void pause(Thread thread) { try { thread.sleep(Long.parseLong((String) pauseAmt)); } catch (Exception e) { } System.gc(); } } // End Scene class /** * Text Effect. Transformation of characters. Clip or fill. */ static class TxE implements Part { static final int INC = 1; static final int DEC = 2; static final int R = 4; // rotate static final int RI = R | INC; static final int RD = R | DEC; static final int SC = 8; // scale static final int SCI = SC | INC; static final int SCD = SC | DEC; static final int SCX = 16; // scale invert x static final int SCXI = SCX | SC | INC; static final int SCXD = SCX | SC | DEC; static final int SCY = 32; // scale invert y static final int SCYI = SCY | SC | INC; static final int SCYD = SCY | SC | DEC; static final int AC = 64; // AlphaComposite static final int CLIP = 128; // Clipping static final int NOP = 512; // No Paint private int beginning, ending; private int type; private double rIncr, sIncr; private double sx, sy, rotate; private Shape shapes[], txShapes[]; private int sw; private int numRev; private Paint paint; public TxE(String text, Font font, int type, Paint paint, int beg, int end) { this.type = type; this.paint = paint; this.beginning = beg; this.ending = end; setIncrements(2); char[] chars = text.toCharArray(); shapes = new Shape[chars.length]; txShapes = new Shape[chars.length]; FontRenderContext frc = new FontRenderContext(null,true,true); TextLayout tl = new TextLayout(text, font, frc); sw = (int) tl.getOutline(null).getBounds().getWidth(); for (int j = 0; j < chars.length; j++) { String s = String.valueOf(chars[j]); shapes[j] = new TextLayout(s, font, frc).getOutline(null); } } public void setIncrements(double numRevolutions) { this.numRev = (int) numRevolutions; rIncr = 360.0 / ((ending - beginning) / numRevolutions); sIncr = 1.0 / (ending - beginning); if ((type & SCX) != 0 || (type & SCY) != 0) { sIncr *= 2; } if ((type & DEC) != 0) { rIncr = -rIncr; sIncr = -sIncr; } } public void reset(int w, int h) { if (type == SCXI) { sx = -1.0; sy = 1.0; } else if (type == SCYI) { sx = 1.0; sy = -1.0; } else { sx = sy = (type & DEC) != 0 ? 1.0 : 0.0; } rotate = 0; } public void step(int w, int h) { float charWidth = w/2-sw/2; for (int i = 0; i < shapes.length; i++) { AffineTransform at = new AffineTransform(); Rectangle2D maxBounds = shapes[i].getBounds(); at.translate(charWidth, h/2+maxBounds.getHeight()/2); charWidth += (float) maxBounds.getWidth() + 1; Shape shape = at.createTransformedShape(shapes[i]); Rectangle2D b1 = shape.getBounds2D(); if ((type & R) != 0) { at.rotate(Math.toRadians(rotate)); } if ((type & SC) != 0) { at.scale(sx, sy); } shape = at.createTransformedShape(shapes[i]); Rectangle2D b2 = shape.getBounds2D(); double xx = (b1.getX()+b1.getWidth()/2) - (b2.getX()+b2.getWidth()/2); double yy = (b1.getY()+b1.getHeight()/2) - (b2.getY()+b2.getHeight()/2); AffineTransform toCenterAT = new AffineTransform(); toCenterAT.translate(xx, yy); toCenterAT.concatenate(at); txShapes[i] = toCenterAT.createTransformedShape(shapes[i]); } // avoid over rotation if (Math.abs(rotate) <= numRev * 360) { rotate += rIncr; if ((type & SCX) != 0) { sx += sIncr; } else if ((type & SCY) != 0) { sy += sIncr; } else { sx += sIncr; sy += sIncr; } } } public void render(int w, int h, Graphics2D g2) { Composite saveAC = null; if ((type & AC) != 0 && sx > 0 && sx < 1) { saveAC = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) sx)); } GeneralPath path = null; if ((type & CLIP) != 0) { path = new GeneralPath(); } if (paint != null) { g2.setPaint(paint); } for (int i = 0; i < txShapes.length; i++) { if ((type & CLIP) != 0) { path.append(txShapes[i], false); } else { g2.fill(txShapes[i]); } } if ((type & CLIP) != 0) { g2.clip(path); } if (saveAC != null) { g2.setComposite(saveAC); } } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End TxE class /** * GradientPaint Effect. Burst, split, horizontal and * vertical gradient fill effects. */ static class GpE implements Part { static final int INC = 1; // increasing static final int DEC = 2; // decreasing static final int CNT = 4; // center static final int WID = 8; // width static final int WI = WID | INC; static final int WD = WID | DEC; static final int HEI = 16; // height static final int HI = HEI | INC; static final int HD = HEI | DEC; static final int SPL = 32 | CNT; // split static final int SIW = SPL | INC | WID; static final int SDW = SPL | DEC | WID; static final int SIH = SPL | INC | HEI; static final int SDH = SPL | DEC | HEI; static final int BUR = 64 | CNT; // burst static final int BURI = BUR | INC; static final int BURD = BUR | DEC; static final int NF = 128; // no fill private Color c1, c2; private int beginning, ending; private float incr, index; private Vector rect = new Vector(); private Vector grad = new Vector(); private int type; public GpE(int type, Color c1, Color c2, int beg, int end) { this.type = type; this.c1 = c1; this.c2 = c2; this.beginning = beg; this.ending = end; } public void reset(int w, int h) { incr = 1.0f / (ending - beginning); if ((type & CNT) != 0) { incr /= 2.3f; } if ((type & CNT) != 0 && (type & INC) != 0) { index = 0.5f; } else if ((type & DEC) != 0) { index = 1.0f; incr = -incr; } else { index = 0.0f; } index += incr; } public void step(int w, int h) { rect.clear(); grad.clear(); if ((type & WID) != 0) { float w2 = 0, x1 = 0, x2 = 0; if ((type & SPL) != 0) { w2 = w * 0.5f; x1 = w * (1.0f - index); x2 = w * index; } else { w2 = w * index; x1 = x2 = w2; } rect.addElement(new Rectangle2D.Float(0, 0, w2, h)); rect.addElement(new Rectangle2D.Float(w2, 0, w-w2, h)); grad.addElement(new GradientPaint(0,0,c1,x1,0,c2)); grad.addElement(new GradientPaint(x2,0,c2,w,0,c1)); } else if ((type & HEI) != 0) { float h2 = 0, y1 = 0, y2 = 0; if ((type & SPL) != 0) { h2 = h * 0.5f; y1 = h * (1.0f - index); y2 = h * index; } else { h2 = h * index; y1 = y2 = h2; } rect.addElement(new Rectangle2D.Float(0, 0, w, h2)); rect.addElement(new Rectangle2D.Float(0, h2, w, h-h2)); grad.addElement(new GradientPaint(0,0,c1,0,y1,c2)); grad.addElement(new GradientPaint(0,y2,c2,0,h,c1)); } else if ((type & BUR) != 0) { float w2 = w/2; float h2 = h/2; rect.addElement(new Rectangle2D.Float(0, 0, w2, h2)); rect.addElement(new Rectangle2D.Float(w2, 0, w2, h2)); rect.addElement(new Rectangle2D.Float(0, h2, w2, h2)); rect.addElement(new Rectangle2D.Float(w2, h2, w2, h2)); float x1 = w * (1.0f - index); float x2 = w * index; float y1 = h * (1.0f - index); float y2 = h * index; grad.addElement(new GradientPaint(0,0,c1,x1,y1,c2)); grad.addElement(new GradientPaint(w,0,c1,x2,y1,c2)); grad.addElement(new GradientPaint(0,h,c1,x1,y2,c2)); grad.addElement(new GradientPaint(w,h,c1,x2,y2,c2)); } else if ((type & NF) != 0) { float x = w * index; float y = h * index; grad.addElement(new GradientPaint(0,0,c1,0,y,c2)); } if ((type & INC) != 0 || (type & DEC) != 0) { index += incr; } } public void render(int w, int h, Graphics2D g2) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); for (int i = 0; i < grad.size(); i++) { g2.setPaint((GradientPaint) grad.get(i)); if ((type & NF) == 0) { g2.fill((Rectangle2D) rect.get(i)); } } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End GpE class /** * TexturePaint Effect. Expand and collapse a texture. */ static class TpE implements Part { static final int INC = 1; // increasing static final int DEC = 2; // decreasing static final int OVAL = 4; // oval static final int RECT = 8; // rectangle static final int HAF = 16; // half oval or rect size static final int OI = OVAL | INC; static final int OD = OVAL | DEC; static final int RI = RECT | INC; static final int RD = RECT | DEC; static final int NF = 32; // no fill private Paint p1, p2; private int beginning, ending; private float incr, index; private TexturePaint texture; private int type; private int size; private BufferedImage bimg; private Rectangle rect; public TpE(int type, Paint p1, Paint p2, int size, int beg, int end) { this.type = type; this.p1 = p1; this.p2 = p2; this.beginning = beg; this.ending = end; setTextureSize(size); } public void setTextureSize(int size) { this.size = size; bimg = new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB); rect = new Rectangle(0,0,size,size); } public void reset(int w, int h) { incr = (float) (size) / (float) (ending - beginning); if ((type & HAF) != 0) { incr /= 2; } if ((type & DEC) != 0) { index = size; if ((type & HAF) != 0) { index /= 2; } incr = -incr; } else { index = 0.0f; } index += incr; } public void step(int w, int h) { Graphics2D g2 = bimg.createGraphics(); g2.setPaint(p1); g2.fillRect(0,0,size,size); g2.setPaint(p2); if ((type & OVAL) != 0) { g2.fill(new Ellipse2D.Float(0,0,index,index)); } else if ((type & RECT) != 0) { g2.fill(new Rectangle2D.Float(0,0,index,index)); } texture = new TexturePaint(bimg, rect); g2.dispose(); index += incr; } public void render(int w, int h, Graphics2D g2) { g2.setPaint(texture); if ((type & NF) == 0) { g2.fillRect(0, 0, w, h); } } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End TpE class /** * Close out effect. Close out the buffered image with different * geometry shapes. */ static class CoE implements Part { static final int WID = 1; static final int HEI = 2; static final int OVAL = 4; static final int RECT = 8; static final int RAND = 16; static final int ARC = 32; private int type; private int beginning, ending; private BufferedImage bimg; private Shape shape; private double zoom, extent; private double zIncr, eIncr; private boolean doRandom; public CoE(int type, int beg, int end) { this.type = type; this.beginning = beg; this.ending = end; zIncr = -(2.0 / (ending - beginning)); eIncr = 360.0 / (ending - beginning); doRandom = (type & RAND) != 0; } public void reset(int w, int h) { if (doRandom) { int num = (int) (Math.random() * 5.0); switch (num) { case 0 : type = OVAL; break; case 1 : type = RECT; break; case 2 : type = RECT | WID; break; case 3 : type = RECT | HEI; break; case 4 : type = ARC; break; default : type = OVAL; } } shape = null; bimg = null; extent = 360.0; zoom = 2.0; } public void step(int w, int h) { if (bimg == null) { int biw = Surface.bimg.getWidth(); int bih = Surface.bimg.getHeight(); bimg = new BufferedImage(biw, bih, BufferedImage.TYPE_INT_RGB); Graphics2D big = bimg.createGraphics(); big.drawImage(Surface.bimg, 0, 0, null); } double z = Math.min(w, h) * zoom; if ((type & OVAL) != 0) { shape = new Ellipse2D.Double(w/2-z/2,h/2-z/2,z,z); } else if ((type & ARC) != 0) { shape = new Arc2D.Double(-100,-100,w+200,h+200,90,extent,Arc2D.PIE); extent -= eIncr; } else if ((type & RECT) != 0) { if ((type & WID) != 0) { shape = new Rectangle2D.Double(w/2-z/2,0,z,h); } else if ((type & HEI) != 0) { shape = new Rectangle2D.Double(0,h/2-z/2,w,z); } else { shape = new Rectangle2D.Double(w/2-z/2,h/2-z/2,z,z); } } zoom += zIncr; } public void render(int w, int h, Graphics2D g2) { g2.clip(shape); g2.drawImage(bimg, 0, 0, null); } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End CoE class /** * Dither Dissolve Effect. For each successive step in the animation, * a pseudo-random starting horizontal position is chosen using list, * and then the corresponding points created from xlist and ylist are * blacked out for the current "chunk". The x and y chunk starting * positions are each incremented by the associated chunk size, and * this process is repeated for the number of "steps" in the * animation, causing an equal number of pseudo-randomly picked * "blocks" to be blacked out during each step of the animation. */ static class DdE implements Part { private int beginning, ending; private BufferedImage bimg; private Graphics2D big; private List list, xlist, ylist; private int xeNum, yeNum; // element number private int xcSize, ycSize; // chunk size private int inc; private int blocksize; public DdE(int beg, int end, int blocksize) { this.beginning = beg; this.ending = end; this.blocksize = blocksize; } private void createShuffledLists() { int width = bimg.getWidth(); int height = bimg.getHeight(); Integer xarray[] = new Integer[width]; Integer yarray[] = new Integer[height]; Integer array[] = new Integer[ending - beginning + 1]; for (int i = 0; i < xarray.length; i++) { xarray[i] = new Integer(i); } for (int j = 0; j < yarray.length; j++) { yarray[j] = new Integer(j); } for (int k = 0; k < array.length; k++) { array[k] = new Integer(k); } java.util.Collections.shuffle(xlist = Arrays.asList(xarray)); java.util.Collections.shuffle(ylist = Arrays.asList(yarray)); java.util.Collections.shuffle(list = Arrays.asList(array)); } public void reset(int w, int h) { bimg = null; } public void step(int w, int h) { if (bimg == null) { int biw = Surface.bimg.getWidth(); int bih = Surface.bimg.getHeight(); bimg = new BufferedImage(biw, bih, BufferedImage.TYPE_INT_RGB); createShuffledLists(); big = bimg.createGraphics(); big.drawImage(Surface.bimg, 0, 0, null); xcSize = (xlist.size() / (ending - beginning)) + 1; ycSize = (ylist.size() / (ending - beginning)) + 1; xeNum = 0; inc = 0; } xeNum = xcSize * ((Integer)list.get(inc)).intValue(); yeNum = -ycSize; inc++; } public void render(int w, int h, Graphics2D g2) { big.setColor(black); for (int k = 0; k <= (ending - beginning); k++) { if ((xeNum + xcSize) > xlist.size()) { xeNum = 0; } else { xeNum += xcSize; } yeNum += ycSize; for (int i = xeNum; i < xeNum+xcSize && i < xlist.size(); i++) { for (int j = yeNum; j < yeNum+ycSize && j < ylist.size(); j++) { int xval = ((Integer)xlist.get(i)).intValue(); int yval = ((Integer)ylist.get(j)).intValue(); if (((xval % blocksize) == 0) && ((yval % blocksize) == 0)) { big.fillRect(xval, yval, blocksize, blocksize); } } } } g2.drawImage(bimg, 0, 0, null); } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End DdE class /** * Subimage effect. Subimage the scene's buffered * image then rotate and scale down the subimages. */ static class SiE implements Part { private int beginning, ending; private BufferedImage bimg; private double rIncr, sIncr; private double scale, rotate; private int siw, sih; private Vector subs = new Vector(20); private Vector pts = new Vector(20); public SiE(int siw, int sih, int beg, int end) { this.siw = siw; this.sih = sih; this.beginning = beg; this.ending = end; rIncr = 360.0 / (ending - beginning); sIncr = 1.0 / (ending - beginning); } public void reset(int w, int h) { scale = 1.0; rotate = 0.0; bimg = null; subs.clear(); pts.clear(); } public void step(int w, int h) { if (bimg == null) { int biw = Surface.bimg.getWidth(); int bih = Surface.bimg.getHeight(); bimg = new BufferedImage(biw, bih, BufferedImage.TYPE_INT_RGB); Graphics2D big = bimg.createGraphics(); big.drawImage(Surface.bimg, 0, 0, null); for (int x = 0; x < w && scale > 0.0; x+=siw) { int ww = x+siw < w ? siw : w-x; for (int y = 0; y < h; y+=sih) { int hh = y+sih < h ? sih : h-y; subs.addElement(bimg.getSubimage(x,y,ww,hh)); pts.addElement(new Point(x, y)); } } } rotate += rIncr; scale -= sIncr; } public void render(int w, int h, Graphics2D g2) { AffineTransform saveTx = g2.getTransform(); g2.setColor(blue); for (int i = 0; i < subs.size() && scale > 0.0; i++) { BufferedImage bi = (BufferedImage) subs.get(i); Point p = (Point) pts.get(i); int ww = bi.getWidth(); int hh = bi.getHeight(); AffineTransform at = new AffineTransform(); at.rotate(Math.toRadians(rotate), p.x+ww/2, p.y+hh/2); at.translate(p.x, p.y); at.scale(scale, scale); Rectangle b1 = new Rectangle(0, 0, ww, hh); Shape shape = at.createTransformedShape(b1); Rectangle2D b2 = shape.getBounds2D(); double xx = (p.x+ww/2) - (b2.getX()+b2.getWidth()/2); double yy = (p.y+hh/2) - (b2.getY()+b2.getHeight()/2); AffineTransform toCenterAT = new AffineTransform(); toCenterAT.translate(xx, yy); toCenterAT.concatenate(at); g2.setTransform(toCenterAT); g2.drawImage(bi, 0, 0, null); g2.draw(b1); } g2.setTransform(saveTx); } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End SiE class /** * Line Effect. Flattened ellipse with lines from the center * to the edge. Expand or collapse the ellipse. Fade in or out * the lines. */ static class LnE implements Part { static final int INC = 1; static final int DEC = 2; static final int R = 4; // rotate static final int RI = R | INC; static final int RD = R | DEC; static final int ZOOM = 8; // zoom static final int ZOOMI = ZOOM | INC; static final int ZOOMD = ZOOM | DEC; static final int AC = 32; // AlphaComposite static final int ACI = 32 | INC; static final int ACD = 32 | DEC; private int beginning, ending; private double rIncr, rotate; private double zIncr, zoom; private Vector pts = new Vector(); private float alpha, aIncr; private int type; public LnE(int type, int beg, int end) { this.type = type; this.beginning = beg; this.ending = end; rIncr = 360.0 / (ending - beginning); aIncr = 0.9f / (ending - beginning); zIncr = 2.0 / (ending - beginning); if ((type & DEC) != 0) { rIncr = -rIncr; aIncr = -aIncr; zIncr = -zIncr; } } public void generatePts(int w, int h, double sizeF) { pts.clear(); double size = Math.min(w, h) * sizeF; Ellipse2D ellipse = new Ellipse2D.Double(w/2-size/2,h/2-size/2,size,size); PathIterator pi = ellipse.getPathIterator(null, 0.8); while ( !pi.isDone() ) { double[] pt = new double[6]; switch ( pi.currentSegment(pt) ) { case FlatteningPathIterator.SEG_MOVETO: case FlatteningPathIterator.SEG_LINETO: pts.addElement(new Point2D.Double(pt[0], pt[1])); } pi.next(); } } public void reset(int w, int h) { if ((type & DEC) != 0) { rotate = 360; alpha = 1.0f; zoom = 2.0; } else { rotate = alpha = 0; zoom = 0; } if ((type & ZOOM) == 0) { generatePts(w, h, 0.5); } } public void step(int w, int h) { if ((type & ZOOM) != 0) { generatePts(w, h, zoom += zIncr); } if ((type & RI) != 0 || (type & RI) != 0) { rotate += rIncr; } if ((type & ACI) != 0 || (type & ACD) != 0) { alpha += aIncr; } } public void render(int w, int h, Graphics2D g2) { Composite saveAC = null; if ((type & AC) != 0 && alpha >= 0 && alpha <= 1) { saveAC = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } AffineTransform saveTx = null; if ((type & R) != 0) { saveTx = g2.getTransform(); AffineTransform at = new AffineTransform(); at.rotate(Math.toRadians(rotate), w/2, h/2); g2.setTransform(at); } Point2D p1 = new Point2D.Double(w/2, h/2); g2.setColor(Color.yellow); for (int i = 0; i < pts.size()-1; i++) { g2.draw(new Line2D.Float(p1, (Point2D) pts.get(i))); } if (saveTx != null) { g2.setTransform(saveTx); } if (saveAC != null) { g2.setComposite(saveAC); } } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End LnE class /** * Template for Features & Contributors consisting of translating * blue and red rectangles and an image going from transparent to * opaque. */ static class Temp implements Part { static final int NOANIM = 1; static final int RECT = 2; static final int RNA = RECT | NOANIM; static final int IMG = 4; static final int INA = IMG | NOANIM; private int beginning, ending; private float alpha, aIncr; private int type; private Rectangle rect1, rect2; private int x, y, xIncr, yIncr; private Image img; public Temp(int type, Image img, int beg, int end) { this.type = type; this.img = img; this.beginning = beg; this.ending = end; aIncr = 0.9f / (ending - beginning); if ((type & NOANIM) != 0) { alpha = 1.0f; } } public void reset(int w, int h) { rect1 = new Rectangle(8, 20, w-20, 30); rect2 = new Rectangle(20, 8, 30, h-20); if ((type & NOANIM) == 0) { alpha = 0.0f; xIncr = w / (ending - beginning); yIncr = h / (ending - beginning); x = w+(int)(xIncr*1.4); y = h+(int)(yIncr*1.4); } } public void step(int w, int h) { if ((type & NOANIM) != 0) { return; } if ((type & RECT) != 0) { rect1.setLocation(x-=xIncr, 20); rect2.setLocation(20, y-=yIncr); } if ((type & IMG) != 0) { alpha += aIncr; } } public void render(int w, int h, Graphics2D g2) { if ((type & RECT) != 0) { g2.setColor(blue); g2.fill(rect1); g2.setColor(red); g2.fill(rect2); } if ((type & IMG) != 0) { Composite saveAC = g2.getComposite(); if (alpha >= 0 && alpha <= 1) { g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } g2.drawImage(img, 30, 30, null); g2.setComposite(saveAC); } } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End Temp class /** * Features of Java2D. Single character advancement effect. */ static class Features implements Part { static final int GRAPHICS = 0; static final int TEXT = 1; static final int IMAGES = 2; static final int COLOR = 3; static Font font1 = new Font("serif", Font.BOLD, 38); static Font font2 = new Font("serif", Font.PLAIN, 24); static FontMetrics fm1 = Surface.getMetrics(font1); static FontMetrics fm2 = Surface.getMetrics(font2); static String table[][] = {{ "Graphics", "Antialiased rendering", "Bezier paths", "Transforms", "Compositing", "Stroking parameters" }, { "Text", "Extended font support", "Advanced text layout", "Dynamic font loading", "AttributeSets for font customization" }, { "Images", "Flexible image layouts", "Extended imaging operations", " Convolutions, Lookup Tables", "RenderableImage interface"}, { "Color", "ICC profile support", "Color conversion", "Arbitrary color spaces"} }; private String list[]; private int beginning, ending; private int strH; private int endIndex, listIndex; private Vector v = new Vector(); public Features(int type, int beg, int end) { list = table[type]; this.beginning = beg; this.ending = end; } public void reset(int w, int h) { strH = (int) (fm2.getAscent()+fm2.getDescent()); endIndex = 1; listIndex = 0; v.clear(); v.addElement(list[listIndex].substring(0,endIndex)); } public void step(int w, int h) { if (listIndex < list.length) { if (++endIndex > list[listIndex].length()) { if (++listIndex < list.length) { endIndex = 1; v.addElement(list[listIndex].substring(0,endIndex)); } } else { v.set(listIndex, list[listIndex].substring(0,endIndex)); } } } public void render(int w, int h, Graphics2D g2) { g2.setColor(white); g2.setFont(font1); g2.drawString((String) v.get(0), 90, 85); g2.setFont(font2); for (int i = 1, y = 90; i < v.size(); i++) { g2.drawString((String) v.get(i), 120, y += strH); } } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End Features class /** * Scrolling text of Java2D contributors. */ static class Contributors implements Part { static String members[] = { "Brian Lichtenwalter", "Jeannette Hung", "Thanh Nguyen", "Jim Graham", "Jerry Evans", "John Raley", "Michael Peirce", "Robert Kim", "Jennifer Ball", "Deborah Adair", "Paul Charlton", "Dmitry Feld", "Gregory Stone", "Richard Blanchard", "Link Perry", "Phil Race", "Vincent Hardy", "Parry Kejriwal", "Doug Felt", "Rekha Rangarajan", "Paula Patel", "Michael Bundschuh", "Joe Warzecha", "Joey Beheler", "Aastha Bhardwaj", "Daniel Rice", "Chris Campbell", "Shinsuke Fukuda", "Dmitri Trembovetski", "Chet Haase", "Jennifer Godinez", "Nicholas Talian", "Raul Vera", "Ankit Patel", "Ilya Bagrak" }; static Font font = new Font("serif", Font.PLAIN, 26); static FontMetrics fm = Surface.getMetrics(font); private int beginning, ending; private int nStrs, strH, index, yh, height; private Vector v = new Vector(); private Vector cast = new Vector(members.length+3); private int counter, cntMod; private GradientPaint gp; public Contributors(int beg, int end) { this.beginning = beg; this.ending = end; java.util.Arrays.sort(members); cast.addElement("CONTRIBUTORS"); cast.addElement(" "); for (int i = 0; i < members.length; i++) { cast.addElement(members[i]); } cast.addElement(" "); cast.addElement(" "); cntMod = (ending - beginning) / cast.size() - 1; } public void reset(int w, int h) { v.clear(); strH = (int) (fm.getAscent()+fm.getDescent()); nStrs = (h-40)/strH + 1; height = strH * (nStrs-1) + 48; index = 0; gp = new GradientPaint(0,h/2,Color.white,0,h+20,Color.black); counter = 0; } public void step(int w, int h) { if (counter++%cntMod == 0) { if (index < cast.size()) { v.addElement(cast.get(index)); } if ((v.size() == nStrs || index >= cast.size()) && v.size() != 0) { v.removeElementAt(0); } ++index; } } public void render(int w, int h, Graphics2D g2) { g2.setPaint(gp); g2.setFont(font); double remainder = counter%cntMod; double incr = 1.0-remainder/cntMod; incr = incr == 1.0 ? 0 : incr; int y = (int) (incr * strH); if (index >= cast.size()) { y = yh + y; } else { y = yh = height - v.size() * strH + y; } for (int i = 0; i < v.size(); i++) { String s = (String) v.get(i); g2.drawString(s, w/2-fm.stringWidth(s)/2, y += strH); } } public int getBegin() { return beginning; } public int getEnd() { return ending; } } // End Contributors class } // End Surface class } // End Intro class pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Makefile000066400000000000000000001126551250413007300253420ustar00rootroot00000000000000# Generated automatically from Makefile.pre by makesetup. # Top-level Makefile for Python # # As distributed, this file is called Makefile.pre.in; it is processed # into the real Makefile by running the script ./configure, which # replaces things like @spam@ with values appropriate for your system. # This means that if you edit Makefile, your changes get lost the next # time you run the configure script. Ideally, you can do: # # ./configure # make # make test # make install # # If you have a previous version of Python installed that you don't # want to overwrite, you can use "make altinstall" instead of "make # install". Refer to the "Installing" section in the README file for # additional details. # # See also the section "Build instructions" in the README file. # === Variables set by makesetup === MODOBJS= Modules/threadmodule.o Modules/signalmodule.o Modules/posixmodule.o Modules/errnomodule.o Modules/pwdmodule.o Modules/_sre.o Modules/_codecsmodule.o Modules/zipimport.o Modules/symtablemodule.o Modules/xxsubtype.o MODLIBS= $(LOCALMODLIBS) $(BASEMODLIBS) # === Variables set by configure VERSION= 2.6 srcdir= . CC= gcc -pthread CXX= g++ -pthread MAINCC= $(CC) LINKCC= $(PURIFY) $(MAINCC) AR= ar RANLIB= ranlib SVNVERSION= svnversion $(srcdir) # Shell used by make (some versions default to the login shell, which is bad) SHELL= /bin/sh # Use this to make a link between python$(VERSION) and python in $(BINDIR) LN= ln # Portable install script (configure doesn't always guess right) INSTALL= /usr/bin/install -c INSTALL_PROGRAM=${INSTALL} INSTALL_SCRIPT= ${INSTALL} INSTALL_DATA= ${INSTALL} -m 644 # Shared libraries must be installed with executable mode on some systems; # rather than figuring out exactly which, we always give them executable mode. # Also, making them read-only seems to be a good idea... INSTALL_SHARED= ${INSTALL} -m 555 MAKESETUP= $(srcdir)/Modules/makesetup # Compiler options OPT= -g -Wall -Wstrict-prototypes BASECFLAGS= -fno-strict-aliasing CFLAGS= $(BASECFLAGS) $(OPT) $(EXTRA_CFLAGS) # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to # be able to build extension modules using the directories specified in the # environment variables CPPFLAGS= -I. -I$(srcdir)/Include LDFLAGS= LDLAST= SGI_ABI= CCSHARED= -fPIC LINKFORSHARED= -Xlinker -export-dynamic # Extra C flags added for building the interpreter object files. CFLAGSFORSHARED= # C flags used for building the interpreter object files PY_CFLAGS= $(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE # Machine-dependent subdirectories MACHDEP= linux2 # Install prefix for architecture-independent files prefix= /usr/local # Install prefix for architecture-dependent files exec_prefix= ${prefix} # Expanded directories BINDIR= $(exec_prefix)/bin LIBDIR= $(exec_prefix)/lib MANDIR= ${prefix}/man INCLUDEDIR= ${prefix}/include CONFINCLUDEDIR= $(exec_prefix)/include SCRIPTDIR= $(prefix)/lib # Detailed destination directories BINLIBDEST= $(LIBDIR)/python$(VERSION) LIBDEST= $(SCRIPTDIR)/python$(VERSION) INCLUDEPY= $(INCLUDEDIR)/python$(VERSION) CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION) LIBP= $(LIBDIR)/python$(VERSION) # Symbols used for using shared libraries SO= .so LDSHARED= $(CC) -shared BLDSHARED= $(CC) -shared DESTSHARED= $(BINLIBDEST)/lib-dynload # Executable suffix (.exe on Windows and Mac OS X) EXE= BUILDEXE= # Short name and location for Mac OS X Python framework UNIVERSALSDK= PYTHONFRAMEWORK= PYTHONFRAMEWORKDIR= no-framework PYTHONFRAMEWORKPREFIX= PYTHONFRAMEWORKINSTALLDIR= # Deployment target selected during configure, to be checked # by distutils. The export statement is needed to ensure that the # deployment target is active during build. MACOSX_DEPLOYMENT_TARGET= #export MACOSX_DEPLOYMENT_TARGET # Options to enable prebinding (for fast startup prior to Mac OS X 10.3) OTHER_LIBTOOL_OPT= # Environment to run shared python without installed libraries RUNSHARED= # Modes for directories, executables and data files created by the # install process. Default to user-only-writable for all file types. DIRMODE= 755 EXEMODE= 755 FILEMODE= 644 # configure script arguments CONFIG_ARGS= '--with-pydebug' # Subdirectories with code SRCDIRS= Parser Grammar Objects Python Modules Mac # Other subdirectories SUBDIRSTOO= Include Lib Misc Demo # Files and directories to be distributed CONFIGFILES= configure configure.in acconfig.h pyconfig.h.in Makefile.pre.in DISTFILES= README ChangeLog $(CONFIGFILES) DISTDIRS= $(SUBDIRS) $(SUBDIRSTOO) Ext-dummy DIST= $(DISTFILES) $(DISTDIRS) LIBRARY= libpython$(VERSION).a LDLIBRARY= libpython$(VERSION).a BLDLIBRARY= $(LDLIBRARY) DLLLIBRARY= LDLIBRARYDIR= INSTSONAME= $(LDLIBRARY) LIBS= -lpthread -ldl -lutil LIBM= -lm LIBC= SYSLIBS= $(LIBM) $(LIBC) SHLIBS= $(LIBS) THREADOBJ= Python/thread.o DLINCLDIR= . DYNLOADFILE= dynload_shlib.o MACHDEP_OBJS= UNICODE_OBJS= Objects/unicodeobject.o Objects/unicodectype.o PYTHON= python$(EXE) BUILDPYTHON= python$(BUILDEXE) # === Definitions added by makesetup === LOCALMODLIBS= BASEMODLIBS= GLHACK=-Dclear=__GLclear PYTHONPATH=$(COREPYTHONPATH) COREPYTHONPATH=$(DESTPATH)$(SITEPATH)$(TESTPATH)$(MACHDEPPATH)$(EXTRAMACHDEPPATH)$(TKPATH) TKPATH=:lib-tk EXTRAMACHDEPPATH= MACHDEPPATH=:plat-$(MACHDEP) TESTPATH= SITEPATH= DESTPATH= MACHDESTLIB=$(BINLIBDEST) DESTLIB=$(LIBDEST) ########################################################################## # Modules MODULE_OBJS= \ Modules/config.o \ Modules/getpath.o \ Modules/main.o \ Modules/gcmodule.o # Used of signalmodule.o is not available SIGNAL_OBJS= ########################################################################## # Grammar GRAMMAR_H= $(srcdir)/Include/graminit.h GRAMMAR_C= $(srcdir)/Python/graminit.c GRAMMAR_INPUT= $(srcdir)/Grammar/Grammar ########################################################################## # Parser PGEN= Parser/pgen$(EXE) POBJS= \ Parser/acceler.o \ Parser/grammar1.o \ Parser/listnode.o \ Parser/node.o \ Parser/parser.o \ Parser/parsetok.o \ Parser/bitset.o \ Parser/metagrammar.o \ Parser/firstsets.o \ Parser/grammar.o \ Parser/pgen.o PARSER_OBJS= $(POBJS) Parser/myreadline.o Parser/tokenizer.o PGOBJS= \ Objects/obmalloc.o \ Python/mysnprintf.o \ Parser/tokenizer_pgen.o \ Parser/printgrammar.o \ Parser/pgenmain.o PGENOBJS= $(PGENMAIN) $(POBJS) $(PGOBJS) ########################################################################## # AST AST_H_DIR= $(srcdir)/Include AST_H= $(AST_H_DIR)/Python-ast.h AST_C_DIR= $(srcdir)/Python AST_C= $(AST_C_DIR)/Python-ast.c AST_ASDL= $(srcdir)/Parser/Python.asdl ASDLGEN_FILES= $(srcdir)/Parser/asdl.py $(srcdir)/Parser/asdl_c.py # XXX Note that a build now requires Python exist before the build starts ASDLGEN= $(srcdir)/Parser/asdl_c.py ########################################################################## # Python PYTHON_OBJS= \ Python/Python-ast.o \ Python/asdl.o \ Python/ast.o \ Python/bltinmodule.o \ Python/ceval.o \ Python/compile.o \ Python/codecs.o \ Python/errors.o \ Python/frozen.o \ Python/frozenmain.o \ Python/future.o \ Python/getargs.o \ Python/getcompiler.o \ Python/getcopyright.o \ Python/getmtime.o \ Python/getplatform.o \ Python/getversion.o \ Python/graminit.o \ Python/import.o \ Python/importdl.o \ Python/marshal.o \ Python/modsupport.o \ Python/mystrtoul.o \ Python/mysnprintf.o \ Python/peephole.o \ Python/pyarena.o \ Python/pyfpe.o \ Python/pystate.o \ Python/pythonrun.o \ Python/structmember.o \ Python/symtable.o \ Python/sysmodule.o \ Python/traceback.o \ Python/getopt.o \ Python/pystrtod.o \ Python/$(DYNLOADFILE) \ $(MACHDEP_OBJS) \ $(THREADOBJ) ########################################################################## # Objects OBJECT_OBJS= \ Objects/abstract.o \ Objects/boolobject.o \ Objects/bufferobject.o \ Objects/cellobject.o \ Objects/classobject.o \ Objects/cobject.o \ Objects/codeobject.o \ Objects/complexobject.o \ Objects/descrobject.o \ Objects/enumobject.o \ Objects/exceptions.o \ Objects/genobject.o \ Objects/fileobject.o \ Objects/floatobject.o \ Objects/frameobject.o \ Objects/funcobject.o \ Objects/intobject.o \ Objects/iterobject.o \ Objects/listobject.o \ Objects/longobject.o \ Objects/dictobject.o \ Objects/methodobject.o \ Objects/moduleobject.o \ Objects/object.o \ Objects/obmalloc.o \ Objects/rangeobject.o \ Objects/setobject.o \ Objects/sliceobject.o \ Objects/stringobject.o \ Objects/structseq.o \ Objects/tupleobject.o \ Objects/typeobject.o \ Objects/weakrefobject.o \ $(UNICODE_OBJS) ########################################################################## # objects that get linked into the Python library LIBRARY_OBJS= \ Modules/_typesmodule.o \ Modules/getbuildinfo.o \ $(PARSER_OBJS) \ $(OBJECT_OBJS) \ $(PYTHON_OBJS) \ $(MODULE_OBJS) \ $(SIGNAL_OBJS) \ $(MODOBJS) ######################################################################### # Rules # Default target all: $(BUILDPYTHON) oldsharedmods sharedmods # Build the interpreter $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ Modules/python.o \ $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) platform: $(BUILDPYTHON) $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform # Build the shared modules sharedmods: $(BUILDPYTHON) @case $$MAKEFLAGS in \ *-s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \ *) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \ esac # Build static library # avoid long command lines, same as LIBRARY_OBJS $(LIBRARY): $(LIBRARY_OBJS) -rm -f $@ $(AR) cr $@ Modules/getbuildinfo.o $(AR) cr $@ Modules/_typesmodule.o $(AR) cr $@ $(PARSER_OBJS) $(AR) cr $@ $(OBJECT_OBJS) $(AR) cr $@ $(PYTHON_OBJS) $(AR) cr $@ $(MODULE_OBJS) $(SIGNAL_OBJS) $(AR) cr $@ $(MODOBJS) $(RANLIB) $@ libpython$(VERSION).so: $(LIBRARY_OBJS) if test $(INSTSONAME) != $(LDLIBRARY); then \ $(LDSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM); \ $(LN) -f $(INSTSONAME) $@; \ else\ $(LDSHARED) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM); \ fi libpython$(VERSION).sl: $(LIBRARY_OBJS) $(LDSHARED) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) # This rule is here for OPENSTEP/Rhapsody/MacOSX. It builds a temporary # minimal framework (not including the Lib directory and such) in the current # directory. RESSRCDIR=$(srcdir)/Mac/Resources/framework $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK): \ $(LIBRARY) \ $(RESSRCDIR)/Info.plist \ $(RESSRCDIR)/version.plist \ $(RESSRCDIR)/English.lproj/InfoPlist.strings $(INSTALL) -d -m $(DIRMODE) $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION) if test "${UNIVERSALSDK}"; then \ $(CC) -o $(LDLIBRARY) -arch i386 -arch ppc -dynamiclib \ -isysroot "${UNIVERSALSDK}" \ -all_load $(LIBRARY) -Wl,-single_module \ -install_name $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/Python \ -compatibility_version $(VERSION) \ -current_version $(VERSION); \ else \ libtool -o $(LDLIBRARY) -dynamic $(OTHER_LIBTOOL_OPT) $(LIBRARY) \ ;\ fi $(INSTALL) -d -m $(DIRMODE) \ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/English.lproj $(INSTALL_DATA) $(RESSRCDIR)/Info.plist \ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/Info.plist $(INSTALL_DATA) $(RESSRCDIR)/version.plist \ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/version.plist $(INSTALL_DATA) $(RESSRCDIR)/English.lproj/InfoPlist.strings \ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/English.lproj/InfoPlist.strings $(LN) -fsn $(VERSION) $(PYTHONFRAMEWORKDIR)/Versions/Current $(LN) -fsn Versions/Current/$(PYTHONFRAMEWORK) $(PYTHONFRAMEWORKDIR)/$(PYTHONFRAMEWORK) $(LN) -fsn Versions/Current/Headers $(PYTHONFRAMEWORKDIR)/Headers $(LN) -fsn Versions/Current/Resources $(PYTHONFRAMEWORKDIR)/Resources # This rule builds the Cygwin Python DLL and import library if configured # for a shared core library; otherwise, this rule is a noop. $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS) if test -n "$(DLLLIBRARY)"; then \ $(LDSHARED) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ $(LIBS) $(MODLIBS) $(SYSLIBS); \ else true; \ fi oldsharedmods: $(SHAREDMODS) Makefile Modules/config.c: Makefile.pre \ $(srcdir)/Modules/config.c.in \ $(MAKESETUP) \ Modules/Setup.config \ Modules/Setup \ Modules/Setup.local $(SHELL) $(MAKESETUP) -c $(srcdir)/Modules/config.c.in \ -s Modules \ Modules/Setup.config \ Modules/Setup.local \ Modules/Setup @mv config.c Modules @echo "The Makefile was updated, you may need to re-run make." Modules/Setup: $(srcdir)/Modules/Setup.dist @if test -f Modules/Setup; then \ echo "-----------------------------------------------"; \ echo "Modules/Setup.dist is newer than Modules/Setup;"; \ echo "check to make sure you have all the updates you"; \ echo "need in your Modules/Setup file."; \ echo "Usually, copying Setup.dist to Setup will work."; \ echo "-----------------------------------------------"; \ fi ############################################################################ # Special rules for object files Modules/getbuildinfo.o: $(PARSER_OBJS) \ $(OBJECT_OBJS) \ $(PYTHON_OBJS) \ $(MODULE_OBJS) \ $(SIGNAL_OBJS) \ $(MODOBJS) \ $(srcdir)/Modules/getbuildinfo.c $(CC) -c $(PY_CFLAGS) -DSVNVERSION=\"`LC_ALL=C $(SVNVERSION)`\" -o $@ $(srcdir)/Modules/getbuildinfo.c Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile $(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ -DPREFIX='"$(prefix)"' \ -DEXEC_PREFIX='"$(exec_prefix)"' \ -DVERSION='"$(VERSION)"' \ -DVPATH='"$(VPATH)"' \ -o $@ $(srcdir)/Modules/getpath.c Modules/python.o: $(srcdir)/Modules/python.c $(MAINCC) -c $(PY_CFLAGS) -o $@ $(srcdir)/Modules/python.c $(GRAMMAR_H) $(GRAMMAR_C): $(PGEN) $(GRAMMAR_INPUT) -$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C) $(PGEN): $(PGENOBJS) $(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) Parser/grammar.o: $(srcdir)/Parser/grammar.c \ $(srcdir)/Include/token.h \ $(srcdir)/Include/grammar.h Parser/metagrammar.o: $(srcdir)/Parser/metagrammar.c Parser/tokenizer_pgen.o: $(srcdir)/Parser/tokenizer.c Parser/pgenmain.o: $(srcdir)/Include/parsetok.h $(AST_H): $(AST_ASDL) $(ASDLGEN_FILES) $(ASDLGEN) -h $(AST_H_DIR) $(AST_ASDL) $(AST_C): $(AST_ASDL) $(ASDLGEN_FILES) $(ASDLGEN) -c $(AST_C_DIR) $(AST_ASDL) Python/compile.o Python/symtable.o: $(GRAMMAR_H) $(AST_H) Python/getplatform.o: $(srcdir)/Python/getplatform.c $(CC) -c $(PY_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c Python/importdl.o: $(srcdir)/Python/importdl.c $(CC) -c $(PY_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c Objects/unicodectype.o: $(srcdir)/Objects/unicodectype.c \ $(srcdir)/Objects/unicodetype_db.h ############################################################################ # Header files PYTHON_HEADERS= \ Include/Python.h \ Include/Python-ast.h \ Include/asdl.h \ Include/abstract.h \ Include/boolobject.h \ Include/bufferobject.h \ Include/ceval.h \ Include/classobject.h \ Include/cobject.h \ Include/code.h \ Include/codecs.h \ Include/compile.h \ Include/complexobject.h \ Include/descrobject.h \ Include/dictobject.h \ Include/enumobject.h \ Include/genobject.h \ Include/fileobject.h \ Include/floatobject.h \ Include/funcobject.h \ Include/import.h \ Include/intobject.h \ Include/intrcheck.h \ Include/iterobject.h \ Include/listobject.h \ Include/longobject.h \ Include/methodobject.h \ Include/modsupport.h \ Include/moduleobject.h \ Include/object.h \ Include/objimpl.h \ Include/parsetok.h \ Include/patchlevel.h \ Include/pyarena.h \ Include/pydebug.h \ Include/pyerrors.h \ Include/pyfpe.h \ Include/pymem.h \ Include/pyport.h \ Include/pystate.h \ Include/pythonrun.h \ Include/rangeobject.h \ Include/setobject.h \ Include/sliceobject.h \ Include/stringobject.h \ Include/structseq.h \ Include/structmember.h \ Include/symtable.h \ Include/sysmodule.h \ Include/traceback.h \ Include/tupleobject.h \ Include/unicodeobject.h \ Include/weakrefobject.h \ pyconfig.h $(LIBRARY_OBJS) $(MODOBJS) Modules/python.o: $(PYTHON_HEADERS) ###################################################################### # Test the interpreter (twice, once without .pyc files, once with) # In the past, we've had problems where bugs in the marshalling or # elsewhere caused bytecode read from .pyc files to behave differently # than bytecode generated directly from a .py source file. Sometimes # the bytecode read from a .pyc file had the bug, somtimes the directly # generated bytecode. This is sometimes a very shy bug needing a lot of # sample data. TESTOPTS= -l $(EXTRATESTOPTS) TESTPROG= $(srcdir)/Lib/test/regrtest.py TESTPYTHON= $(RUNSHARED) ./$(BUILDPYTHON) -E -tt test: all platform -find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f -$(TESTPYTHON) $(TESTPROG) $(TESTOPTS) $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) testall: all platform -find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f -$(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall # Run the unitests for both architectures in a Universal build on OSX # Must be run on an Intel box. testuniversal: all platform if [ `arch` != 'i386' ];then \ echo "This can only be used on OSX/i386" ;\ exit 1 ;\ fi -find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f -$(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall $(RUNSHARED) /usr/libexec/oah/translate ./$(BUILDPYTHON) -E -tt $(TESTPROG) $(TESTOPTS) -uall # Like testall, but with a single pass only buildbottest: all platform $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall -rw QUICKTESTOPTS= $(TESTOPTS) -x test_thread test_signal test_strftime \ test_unicodedata test_re test_sre test_select test_poll \ test_linuxaudiodev test_struct test_sunaudiodev test_zlib quicktest: all platform -find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f -$(TESTPYTHON) $(TESTPROG) $(QUICKTESTOPTS) $(TESTPYTHON) $(TESTPROG) $(QUICKTESTOPTS) MEMTESTOPTS= $(QUICKTESTOPTS) -x test_dl test___all__ test_fork1 \ test_longexp memtest: all platform -rm -f $(srcdir)/Lib/test/*.py[co] -$(TESTPYTHON) $(TESTPROG) $(MEMTESTOPTS) $(TESTPYTHON) $(TESTPROG) $(MEMTESTOPTS) # Install everything install: altinstall bininstall maninstall # Install almost everything without disturbing previous versions altinstall: altbininstall libinstall inclinstall libainstall \ sharedinstall oldsharedinstall # Install shared libraries enabled by Setup DESTDIRS= $(exec_prefix) $(LIBDIR) $(BINLIBDEST) $(DESTSHARED) oldsharedinstall: $(DESTSHARED) $(SHAREDMODS) @for i in X $(SHAREDMODS); do \ if test $$i != X; then \ echo $(INSTALL_SHARED) $$i $(DESTSHARED)/`basename $$i`; \ $(INSTALL_SHARED) $$i $(DESTDIR)$(DESTSHARED)/`basename $$i`; \ fi; \ done $(DESTSHARED): @for i in $(DESTDIRS); \ do \ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done # Install the interpreter (by creating a hard link to python$(VERSION)) bininstall: altbininstall -if test -f $(DESTDIR)$(BINDIR)/$(PYTHON) -o -h $(DESTDIR)$(BINDIR)/$(PYTHON); \ then rm -f $(DESTDIR)$(BINDIR)/$(PYTHON); \ else true; \ fi (cd $(DESTDIR)$(BINDIR); $(LN) python$(VERSION)$(EXE) $(PYTHON)) (cd $(DESTDIR)$(BINDIR); $(LN) -sf python$(VERSION)-config python-config) # Install the interpreter with $(VERSION) affixed # This goes into $(exec_prefix) altbininstall: $(BUILDPYTHON) @for i in $(BINDIR) $(LIBDIR); \ do \ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done $(INSTALL_PROGRAM) $(BUILDPYTHON) $(DESTDIR)$(BINDIR)/python$(VERSION)$(EXE) if test -f libpython$(VERSION)$(SO); then \ if test "$(SO)" = .dll; then \ $(INSTALL_SHARED) libpython$(VERSION)$(SO) $(DESTDIR)$(BINDIR); \ else \ $(INSTALL_SHARED) libpython$(VERSION)$(SO) $(DESTDIR)$(LIBDIR)/$(INSTSONAME); \ if test libpython$(VERSION)$(SO) != $(INSTSONAME); then \ (cd $(DESTDIR)$(LIBDIR); $(LN) -sf $(INSTSONAME) libpython$(VERSION)$(SO)); \ fi \ fi; \ else true; \ fi # Install the manual page maninstall: @for i in $(MANDIR) $(MANDIR)/man1; \ do \ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done $(INSTALL_DATA) $(srcdir)/Misc/python.man \ $(DESTDIR)$(MANDIR)/man1/python.1 # Install the library PLATDIR= plat-$(MACHDEP) EXTRAPLATDIR= EXTRAMACHDEPPATH= MACHDEPS= $(PLATDIR) $(EXTRAPLATDIR) XMLLIBSUBDIRS= xml xml/dom xml/etree xml/parsers xml/sax PLATMACDIRS= plat-mac plat-mac/Carbon plat-mac/lib-scriptpackages \ plat-mac/lib-scriptpackages/_builtinSuites \ plat-mac/lib-scriptpackages/CodeWarrior \ plat-mac/lib-scriptpackages/Explorer \ plat-mac/lib-scriptpackages/Finder \ plat-mac/lib-scriptpackages/Netscape \ plat-mac/lib-scriptpackages/StdSuites \ plat-mac/lib-scriptpackages/SystemEvents \ plat-mac/lib-scriptpackages/Terminal PLATMACPATH=:plat-mac:plat-mac/lib-scriptpackages LIBSUBDIRS= lib-tk site-packages test test/output test/data \ test/decimaltestdata \ encodings compiler hotshot \ email email/mime email/test email/test/data \ sqlite3 sqlite3/test \ logging bsddb bsddb/test csv wsgiref \ ctypes ctypes/test ctypes/macholib idlelib idlelib/Icons \ distutils distutils/command distutils/tests $(XMLLIBSUBDIRS) \ setuptools setuptools/command setuptools/tests setuptools.egg-info \ curses $(MACHDEPS) libinstall: $(BUILDPYTHON) $(srcdir)/Lib/$(PLATDIR) @for i in $(SCRIPTDIR) $(LIBDEST); \ do \ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done @for d in $(LIBSUBDIRS); \ do \ a=$(srcdir)/Lib/$$d; \ if test ! -d $$a; then continue; else true; fi; \ b=$(LIBDEST)/$$d; \ if test ! -d $(DESTDIR)$$b; then \ echo "Creating directory $$b"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$b; \ else true; \ fi; \ done @for i in $(srcdir)/Lib/*.py $(srcdir)/Lib/*.doc $(srcdir)/Lib/*.egg-info ; \ do \ if test -x $$i; then \ $(INSTALL_SCRIPT) $$i $(DESTDIR)$(LIBDEST); \ echo $(INSTALL_SCRIPT) $$i $(LIBDEST); \ else \ $(INSTALL_DATA) $$i $(DESTDIR)$(LIBDEST); \ echo $(INSTALL_DATA) $$i $(LIBDEST); \ fi; \ done @for d in $(LIBSUBDIRS); \ do \ a=$(srcdir)/Lib/$$d; \ if test ! -d $$a; then continue; else true; fi; \ if test `ls $$a | wc -l` -lt 1; then continue; fi; \ b=$(LIBDEST)/$$d; \ for i in $$a/*; \ do \ case $$i in \ *CVS) ;; \ *.py[co]) ;; \ *.orig) ;; \ *~) ;; \ *) \ if test -d $$i; then continue; fi; \ if test -x $$i; then \ echo $(INSTALL_SCRIPT) $$i $$b; \ $(INSTALL_SCRIPT) $$i $(DESTDIR)$$b; \ else \ echo $(INSTALL_DATA) $$i $$b; \ $(INSTALL_DATA) $$i $(DESTDIR)$$b; \ fi;; \ esac; \ done; \ done $(INSTALL_DATA) $(srcdir)/LICENSE $(DESTDIR)$(LIBDEST)/LICENSE.txt PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \ ./$(BUILDPYTHON) -Wi -tt $(DESTDIR)$(LIBDEST)/compileall.py \ -d $(LIBDEST) -f \ -x 'bad_coding|badsyntax|site-packages' $(DESTDIR)$(LIBDEST) PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \ ./$(BUILDPYTHON) -Wi -tt -O $(DESTDIR)$(LIBDEST)/compileall.py \ -d $(LIBDEST) -f \ -x 'bad_coding|badsyntax|site-packages' $(DESTDIR)$(LIBDEST) -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \ ./$(BUILDPYTHON) -Wi -t $(DESTDIR)$(LIBDEST)/compileall.py \ -d $(LIBDEST)/site-packages -f \ -x badsyntax $(DESTDIR)$(LIBDEST)/site-packages -PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \ ./$(BUILDPYTHON) -Wi -t -O $(DESTDIR)$(LIBDEST)/compileall.py \ -d $(LIBDEST)/site-packages -f \ -x badsyntax $(DESTDIR)$(LIBDEST)/site-packages # Create the PLATDIR source directory, if one wasn't distributed.. $(srcdir)/Lib/$(PLATDIR): mkdir $(srcdir)/Lib/$(PLATDIR) cp $(srcdir)/Lib/plat-generic/regen $(srcdir)/Lib/$(PLATDIR)/regen export PATH; PATH="`pwd`:$$PATH"; \ export PYTHONPATH; PYTHONPATH="`pwd`/Lib"; \ export DYLD_FRAMEWORK_PATH; DYLD_FRAMEWORK_PATH="`pwd`"; \ export EXE; EXE="$(BUILDEXE)"; \ cd $(srcdir)/Lib/$(PLATDIR); ./regen # Install the include files INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY) inclinstall: @for i in $(INCLDIRSTOMAKE); \ do \ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done @for i in $(srcdir)/Include/*.h; \ do \ echo $(INSTALL_DATA) $$i $(INCLUDEPY); \ $(INSTALL_DATA) $$i $(DESTDIR)$(INCLUDEPY); \ done $(INSTALL_DATA) pyconfig.h $(DESTDIR)$(CONFINCLUDEPY)/pyconfig.h # Install the library and miscellaneous stuff needed for extending/embedding # This goes into $(exec_prefix) LIBPL= $(LIBP)/config libainstall: all @for i in $(LIBDIR) $(LIBP) $(LIBPL); \ do \ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done @if test -d $(LIBRARY); then :; else \ if test "$(PYTHONFRAMEWORKDIR)" = no-framework; then \ if test "$(SO)" = .dll; then \ $(INSTALL_DATA) $(LDLIBRARY) $(DESTDIR)$(LIBPL) ; \ else \ $(INSTALL_DATA) $(LIBRARY) $(DESTDIR)$(LIBPL)/$(LIBRARY) ; \ $(RANLIB) $(DESTDIR)$(LIBPL)/$(LIBRARY) ; \ fi; \ else \ echo Skip install of $(LIBRARY) - use make frameworkinstall; \ fi; \ fi $(INSTALL_DATA) Modules/config.c $(DESTDIR)$(LIBPL)/config.c $(INSTALL_DATA) Modules/python.o $(DESTDIR)$(LIBPL)/python.o $(INSTALL_DATA) $(srcdir)/Modules/config.c.in $(DESTDIR)$(LIBPL)/config.c.in $(INSTALL_DATA) Makefile $(DESTDIR)$(LIBPL)/Makefile $(INSTALL_DATA) Modules/Setup $(DESTDIR)$(LIBPL)/Setup $(INSTALL_DATA) Modules/Setup.local $(DESTDIR)$(LIBPL)/Setup.local $(INSTALL_DATA) Modules/Setup.config $(DESTDIR)$(LIBPL)/Setup.config $(INSTALL_SCRIPT) $(srcdir)/Modules/makesetup $(DESTDIR)$(LIBPL)/makesetup $(INSTALL_SCRIPT) $(srcdir)/install-sh $(DESTDIR)$(LIBPL)/install-sh # Substitution happens here, as the completely-expanded BINDIR # is not available in configure sed -e "s,@EXENAME@,$(BINDIR)/python$(VERSION)$(EXE)," < $(srcdir)/Misc/python-config.in >python-config $(INSTALL_SCRIPT) python-config $(DESTDIR)$(BINDIR)/python$(VERSION)-config rm python-config @if [ -s Modules/python.exp -a \ "`echo $(MACHDEP) | sed 's/^\(...\).*/\1/'`" = "aix" ]; then \ echo; echo "Installing support files for building shared extension modules on AIX:"; \ $(INSTALL_DATA) Modules/python.exp \ $(DESTDIR)$(LIBPL)/python.exp; \ echo; echo "$(LIBPL)/python.exp"; \ $(INSTALL_SCRIPT) $(srcdir)/Modules/makexp_aix \ $(DESTDIR)$(LIBPL)/makexp_aix; \ echo "$(LIBPL)/makexp_aix"; \ $(INSTALL_SCRIPT) $(srcdir)/Modules/ld_so_aix \ $(DESTDIR)$(LIBPL)/ld_so_aix; \ echo "$(LIBPL)/ld_so_aix"; \ echo; echo "See Misc/AIX-NOTES for details."; \ else true; \ fi @case "$(MACHDEP)" in beos*) \ echo; echo "Installing support files for building shared extension modules on BeOS:"; \ $(INSTALL_DATA) Misc/BeOS-NOTES $(DESTDIR)$(LIBPL)/README; \ echo; echo "$(LIBPL)/README"; \ $(INSTALL_SCRIPT) Modules/ar_beos $(DESTDIR)$(LIBPL)/ar_beos; \ echo "$(LIBPL)/ar_beos"; \ $(INSTALL_SCRIPT) Modules/ld_so_beos $(DESTDIR)$(LIBPL)/ld_so_beos; \ echo "$(LIBPL)/ld_so_beos"; \ echo; echo "See Misc/BeOS-NOTES for details."; \ ;; \ esac # Install the dynamically loadable modules # This goes into $(exec_prefix) sharedinstall: $(RUNSHARED) ./$(BUILDPYTHON) -E $(srcdir)/setup.py install \ --prefix=$(prefix) \ --install-scripts=$(BINDIR) \ --install-platlib=$(DESTSHARED) \ --root=/$(DESTDIR) # Here are a couple of targets for MacOSX again, to install a full # framework-based Python. frameworkinstall installs everything, the # subtargets install specific parts. Much of the actual work is offloaded to # the Makefile in Mac # # # This target is here for backward compatiblity, previous versions of Python # hadn't integrated framework installation in the normal install process. frameworkinstall: install # On install, we re-make the framework # structure in the install location, /Library/Frameworks/ or the argument to # --enable-framework. If --enable-framework has been specified then we have # automatically set prefix to the location deep down in the framework, so we # only have to cater for the structural bits of the framework. frameworkinstallframework: frameworkinstallstructure install frameworkinstallmaclib frameworkinstallstructure: $(LDLIBRARY) @if test "$(PYTHONFRAMEWORKDIR)" = no-framework; then \ echo Not configured with --enable-framework; \ exit 1; \ else true; \ fi @for i in $(prefix)/Resources/English.lproj $(prefix)/lib; do\ if test ! -d $(DESTDIR)$$i; then \ echo "Creating directory $(DESTDIR)$$i"; \ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$$i; \ else true; \ fi; \ done $(LN) -fsn include/python$(VERSION) $(DESTDIR)$(prefix)/Headers $(INSTALL_DATA) $(RESSRCDIR)/Info.plist $(DESTDIR)$(prefix)/Resources/Info.plist $(INSTALL_DATA) $(RESSRCDIR)/version.plist $(DESTDIR)$(prefix)/Resources/version.plist $(INSTALL_DATA) $(RESSRCDIR)/English.lproj/InfoPlist.strings \ $(DESTDIR)$(prefix)/Resources/English.lproj/InfoPlist.strings $(LN) -fsn $(VERSION) $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Versions/Current $(LN) -fsn Versions/Current/Python $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Python $(LN) -fsn Versions/Current/Headers $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Headers $(LN) -fsn Versions/Current/Resources $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Resources $(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(PYTHONFRAMEWORKPREFIX)/$(LDLIBRARY) # This installs Mac/Lib into the framework # Install a number of symlinks to keep software that expects a normal unix # install (which includes python-config) happy. frameworkinstallmaclib: ln -fs "../../../Python" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config/libpython$(VERSION).a" cd Mac && $(MAKE) installmacsubtree DESTDIR="$(DESTDIR)" # This installs the IDE, the Launcher and other apps into /Applications frameworkinstallapps: cd Mac && $(MAKE) installapps DESTDIR="$(DESTDIR)" # This install the unix python and pythonw tools in /usr/local/bin frameworkinstallunixtools: cd Mac && $(MAKE) installunixtools DESTDIR="$(DESTDIR)" frameworkaltinstallunixtools: cd Mac && $(MAKE) altinstallunixtools DESTDIR="$(DESTDIR)" # This installs the Demos and Tools into the applications directory. # It is not part of a normal frameworkinstall frameworkinstallextras: cd Mac && Make installextras DESTDIR="$(DESTDIR)" # This installs a few of the useful scripts in Tools/scripts scriptsinstall: SRCDIR=$(srcdir) $(RUNSHARED) \ ./$(BUILDPYTHON) $(srcdir)/Tools/scripts/setup.py install \ --prefix=$(prefix) \ --install-scripts=$(BINDIR) \ --root=/$(DESTDIR) # Build the toplevel Makefile Makefile.pre: Makefile.pre.in config.status CONFIG_FILES=Makefile.pre CONFIG_HEADERS= $(SHELL) config.status $(MAKE) -f Makefile.pre Makefile # Run the configure script. config.status: $(srcdir)/configure $(SHELL) $(srcdir)/configure $(CONFIG_ARGS) .PRECIOUS: config.status $(BUILDPYTHON) Makefile Makefile.pre # Some make's put the object file in the current directory .c.o: $(CC) -c $(PY_CFLAGS) -o $@ $< # Run reindent on the library reindent: ./python$(EXEEXT) $(srcdir)/Tools/scripts/reindent.py -r $(srcdir)/Lib # Rerun configure with the same options as it was run last time, # provided the config.status script exists recheck: $(SHELL) config.status --recheck $(SHELL) config.status # Rebuild the configure script from configure.in; also rebuild pyconfig.h.in autoconf: (cd $(srcdir); autoconf) (cd $(srcdir); autoheader) # Create a tags file for vi tags:: cd $(srcdir); \ ctags -w -t Include/*.h; \ for i in $(SRCDIRS); do ctags -w -t -a $$i/*.[ch]; \ done; \ sort -o tags tags # Create a tags file for GNU Emacs TAGS:: cd $(srcdir); \ etags Include/*.h; \ for i in $(SRCDIRS); do etags -a $$i/*.[ch]; done # Sanitation targets -- clean leaves libraries, executables and tags # files, which clobber removes those as well pycremoval: find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' clean: pycremoval find . -name '*.o' -exec rm -f {} ';' find . -name '*.s[ol]' -exec rm -f {} ';' find $(srcdir)/build -name 'fficonfig.h' -exec rm -f {} ';' || true find $(srcdir)/build -name 'fficonfig.py' -exec rm -f {} ';' || true clobber: clean -rm -f $(BUILDPYTHON) $(PGEN) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \ tags TAGS \ config.cache config.log pyconfig.h Modules/config.c -rm -rf build platform -rm -rf $(PYTHONFRAMEWORKDIR) # Make things extra clean, before making a distribution: # remove all generated files, even Makefile[.pre] # Keep configure and Python-ast.[ch], it's possible they can't be generated distclean: clobber -rm -f core Makefile Makefile.pre config.status \ Modules/Setup Modules/Setup.local Modules/Setup.config find $(srcdir) '(' -name '*.fdc' -o -name '*~' \ -o -name '[@,#]*' -o -name '*.old' \ -o -name '*.orig' -o -name '*.rej' \ -o -name '*.bak' ')' \ -exec rm -f {} ';' # Check for smelly exported symbols (not starting with Py/_Py) smelly: all nm -p $(LIBRARY) | \ sed -n "/ [TDB] /s/.* //p" | grep -v "^_*Py" | sort -u; \ # Find files with funny names funny: find $(DISTDIRS) -type d \ -o -name '*.[chs]' \ -o -name '*.py' \ -o -name '*.doc' \ -o -name '*.sty' \ -o -name '*.bib' \ -o -name '*.dat' \ -o -name '*.el' \ -o -name '*.fd' \ -o -name '*.in' \ -o -name '*.tex' \ -o -name '*,[vpt]' \ -o -name 'Setup' \ -o -name 'Setup.*' \ -o -name README \ -o -name Makefile \ -o -name ChangeLog \ -o -name Repository \ -o -name Root \ -o -name Entries \ -o -name Tag \ -o -name tags \ -o -name TAGS \ -o -name .cvsignore \ -o -name MANIFEST \ -o -print # Dependencies Python/thread.o: $(srcdir)/Python/thread_atheos.h $(srcdir)/Python/thread_beos.h $(srcdir)/Python/thread_cthread.h $(srcdir)/Python/thread_foobar.h $(srcdir)/Python/thread_lwp.h $(srcdir)/Python/thread_nt.h $(srcdir)/Python/thread_os2.h $(srcdir)/Python/thread_pth.h $(srcdir)/Python/thread_pthread.h $(srcdir)/Python/thread_sgi.h $(srcdir)/Python/thread_solaris.h $(srcdir)/Python/thread_wince.h # Declare targets that aren't real files .PHONY: all sharedmods oldsharedmods test quicktest memtest .PHONY: install altinstall oldsharedinstall bininstall altbininstall .PHONY: maninstall libinstall inclinstall libainstall sharedinstall .PHONY: frameworkinstall frameworkinstallframework frameworkinstallstructure .PHONY: frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools .PHONY: frameworkaltinstallunixtools recheck autoconf clean clobber distclean .PHONY: smelly funny # IF YOU PUT ANYTHING HERE IT WILL GO AWAY # Rules appended by makedepend Modules/threadmodule.o: $(srcdir)/Modules/threadmodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/threadmodule.c -o Modules/threadmodule.o Modules/threadmodule$(SO): Modules/threadmodule.o; $(LDSHARED) Modules/threadmodule.o -o Modules/threadmodule$(SO) Modules/signalmodule.o: $(srcdir)/Modules/signalmodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/signalmodule.c -o Modules/signalmodule.o Modules/signalmodule$(SO): Modules/signalmodule.o; $(LDSHARED) Modules/signalmodule.o -o Modules/signalmodule$(SO) Modules/posixmodule.o: $(srcdir)/Modules/posixmodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/posixmodule.c -o Modules/posixmodule.o Modules/posixmodule$(SO): Modules/posixmodule.o; $(LDSHARED) Modules/posixmodule.o -o Modules/posixmodule$(SO) Modules/errnomodule.o: $(srcdir)/Modules/errnomodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/errnomodule.c -o Modules/errnomodule.o Modules/errnomodule$(SO): Modules/errnomodule.o; $(LDSHARED) Modules/errnomodule.o -o Modules/errnomodule$(SO) Modules/pwdmodule.o: $(srcdir)/Modules/pwdmodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/pwdmodule.c -o Modules/pwdmodule.o Modules/pwdmodule$(SO): Modules/pwdmodule.o; $(LDSHARED) Modules/pwdmodule.o -o Modules/pwdmodule$(SO) Modules/_sre.o: $(srcdir)/Modules/_sre.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/_sre.c -o Modules/_sre.o Modules/_sre$(SO): Modules/_sre.o; $(LDSHARED) Modules/_sre.o -o Modules/_sre$(SO) Modules/_codecsmodule.o: $(srcdir)/Modules/_codecsmodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/_codecsmodule.c -o Modules/_codecsmodule.o Modules/_codecsmodule$(SO): Modules/_codecsmodule.o; $(LDSHARED) Modules/_codecsmodule.o -o Modules/_codecsmodule$(SO) Modules/zipimport.o: $(srcdir)/Modules/zipimport.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/zipimport.c -o Modules/zipimport.o Modules/zipimport$(SO): Modules/zipimport.o; $(LDSHARED) Modules/zipimport.o -o Modules/zipimport$(SO) Modules/symtablemodule.o: $(srcdir)/Modules/symtablemodule.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/symtablemodule.c -o Modules/symtablemodule.o Modules/_symtablemodule$(SO): Modules/symtablemodule.o; $(LDSHARED) Modules/symtablemodule.o -o Modules/_symtablemodule$(SO) Modules/xxsubtype.o: $(srcdir)/Modules/xxsubtype.c; $(CC) $(PY_CFLAGS) -c $(srcdir)/Modules/xxsubtype.c -o Modules/xxsubtype.o Modules/xxsubtype$(SO): Modules/xxsubtype.o; $(LDSHARED) Modules/xxsubtype.o -o Modules/xxsubtype$(SO) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Object.st000066400000000000000000004617711250413007300254660ustar00rootroot00000000000000!ProtoObject subclass: #Object instanceVariableNames: '' classVariableNames: 'DependentsFields' poolDictionaries: '' category: 'Kernel-Objects'! !Object methodsFor: '*39Deprecated' stamp: 'gk 2/24/2004 08:49'! beep "Deprecated." self deprecated: 'Use Beeper class>>beep instead.'. Beeper beep! ! !Object methodsFor: '*39Deprecated' stamp: 'gk 2/24/2004 08:50'! beepPrimitive "Deprecated. Beep in the absence of sound support." self deprecated: 'Use Beeper class>>beep or Beeper class>>beepPrimitive instead.'. Beeper beepPrimitive! ! !Object methodsFor: '*39Deprecated' stamp: 'md 12/12/2003 17:02'! beep: soundName "Make the given sound, unless the making of sound is disabled in Preferences." self deprecated: 'Use SampledSound>>playSoundNamed: instead.'. Preferences soundsEnabled ifTrue: [self playSoundNamed: soundName] ! ! !Object methodsFor: '*39Deprecated' stamp: 'sd 11/19/2004 16:57'! contentsGetz: x self deprecated: 'there is no method named contents in object and in addition only one sender in a method not called'. self contents: x! ! !Object methodsFor: '*39Deprecated' stamp: 'sd 11/13/2003 21:10'! deprecatedExplanation: aString "This method is OBSOLETE. Use #deprecated: instead." self deprecated: 'Use Object>>deprecated: instead of deprecatedExplanation:.'. Preferences showDeprecationWarnings ifTrue: [Deprecation signal: ('{1} has been deprecated. {2}' translated format: {thisContext sender printString. aString})]! ! !Object methodsFor: '*39Deprecated' stamp: 'sd 11/13/2003 21:11'! deprecated: aBlock explanation: aString "This method is OBSOLETE. Use #deprecated:block: instead." self deprecated: 'Use Object>>deprecated:block: instead of deprecated:explanation:.'. Preferences showDeprecationWarnings ifTrue: [Deprecation signal: ('{1} has been deprecated. {2}' translated format: {thisContext sender printString. aString})]. ^ aBlock value. ! ! !Object methodsFor: '*39Deprecated' stamp: 'md 12/12/2003 16:25'! doIfNotNil: aBlock self deprecated: 'use ifNotNilDo:'. ^ self ifNotNilDo: aBlock ! ! !Object methodsFor: '*39Deprecated' stamp: 'md 11/27/2004 12:20'! ifKindOf: aClass thenDo: aBlock self deprecated: 'Deprecated. Just use #isKindOf:'. ^ (self isKindOf: aClass) ifTrue: [aBlock value: self]! ! !Object methodsFor: '*39Deprecated' stamp: 'gk 2/23/2004 20:51'! playSoundNamed: soundName "Deprecated. Play the sound with the given name." self deprecated: 'Use "SoundService default playSoundNamed: aName" instead.'. SoundService default playSoundNamed: soundName! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:23'! aidaCanBeLocked "can we get an exclusive lock on that object (not already locked)?" ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:23'! aidaDontCache "don't cache web content in a browser. Appropriate header is added to http response" ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:24'! aidaIsLocked "is object locked exclusively?" ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:24'! aidaLock "get an exclusive lock on that object. Until unlocked, noon else can get that lock. Return false if already locked, true if successfull" ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:24'! aidaUnlock "release an exclusive lock if any" ^true! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:24'! app "fastest and most convinient way to find a web app for that object" ^self webAppFor: self firstSessionFromStack! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:25'! contentType "Janko Mivsek, apr98" "return 'text/html' as content type for web pages" ^'text/html'! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:25'! deepSearchOfClass: aClassName "finf all objects of that class down in object hierarchy" | objectDictionary class | objectDictionary := IdentityDictionary new. self deepCopyNotIn: objectDictionary. class := aClassName asSymbol. ^objectDictionary keys select: [:each | each class name = class].! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:26'! deepSearchOfObsoleteClasses "find all objects of obsolete classes down in object hierarchy" | objectDictionary | objectDictionary := IdentityDictionary new. self deepCopyNotIn: objectDictionary. ^objectDictionary keys select: [:each | each class isObsolete].! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:26'! expiresTimestamp "until when content of this object wont be changed" "used in http response, override if you like to be included" ^self modifiedTimestamp "to reload pages immediately"! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:26'! firstAppFromStack "try to find a first sender up in calling stack, who is WebApplication" | context | context := thisContext. [context notNil] whileTrue: [ (context receiver isKindOf: WebApplication) ifTrue: [^context receiver]. context := context sender]. ^self firstSessionFromStack lastApp! ! !Object methodsFor: '*Aida' stamp: 'JM 4/25/2007 21:34'! firstSessionFromStack "try to find a first sender up in calling stack, who is AIDASite and get session if that call" | context | context := thisContext. [context notNil] whileTrue: [ (context receiver isKindOf: AIDASite) ifTrue: [^(context at: 3) "always?"]. context := context sender]. ^nil! ! !Object methodsFor: '*Aida' stamp: 'mivsek 1/10/2008 18:14'! forLanguage: aLanguageCodeSymbol "for multilingual support: returns an apropriate instance of itself for that language. Langage is defined by ISO 639 2-letter language code, see http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" ^false! ! !Object methodsFor: '*Aida' stamp: 'mivsek 1/10/2008 18:14'! isMultilingual "for multilingual support: override this if your domain object responds to #forLanguage: and returns an apropriate instance of itself for that language" ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:27'! isVersionedObject ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:27'! isWebApplication ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:27'! isWebStyle ^false! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:27'! modifiedTimestamp "when this object was last modified" "used in http response, override if you like to be included" ^nil! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:28'! preferedUrl "override with a suggestion for url of this method!! If not already used, it will be considered by URLResolver during automatic url generation" ^nil! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:28'! printWebAppNotFoundFor: aSession | page | page := WebPage new. page addText: 'Cannot find aWebApplication for object a', self class name. ^page! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:28'! printWebPageFor: aSession "find appropriate web application to represent self as web page" | webApp | webApp := self webAppFor: aSession. ^webApp notNil ifTrue: [webApp printWebPage] ifFalse: [self printWebAppNotFoundFor: aSession]! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:29'! sendOver: aStream "from Wiki rendering" self printOn: aStream! ! !Object methodsFor: '*Aida' stamp: 'JM 4/22/2007 15:29'! webAppFor: aSession | webApp | aSession isNil ifTrue: [^nil]. webApp := aSession webAppFor: self. webApp notNil ifTrue: [^webApp]. webApp := WebApplication newFor: self on: aSession. webApp notNil ifTrue: [aSession addWebApp: webApp for: self]. ^webApp! ! !Object methodsFor: '*DynamicBindings' stamp: 'svp 3/6/2003 16:08'! binding "Answer the DynamicBinding for the receiver (if any)" ^Bindings bindingFor: self ifNotBound: [nil]! ! !Object methodsFor: '*DynamicBindings' stamp: 'svp 4/29/2003 00:35'! binding: anObject "Set the dynamic binding for the receiver, if anObject is nil, then remove the receiver's dynamic binding (if any)" ^anObject ifNil: [self removeBinding] ifNotNil: [Bindings bind: self to: anObject]! ! !Object methodsFor: '*DynamicBindings' stamp: 'svp 3/6/2003 16:09'! hasBinding "Answer whether or not the receiver has a dynamic binding" ^Bindings includesKey: self! ! !Object methodsFor: '*DynamicBindings' stamp: 'svp 3/6/2003 16:09'! removeBinding "Remove the dynamic binding associated with the receiver" ^Bindings removeKey: self ifAbsent: []! ! !Object methodsFor: '*KomHttpServer' stamp: 'SVP 8/23/1999 19:17'! asHtmlDocumentForRequest: aNetworkRequest self error: ('The requested object (', self asString, '), could not be converted into HTML for your browser.')! ! !Object methodsFor: '*KomHttpServer' stamp: 'SVP 8/23/1999 19:23'! asHttpResponseTo: anHttpRequest ^(self asHtmlDocumentForRequest: anHttpRequest) asHttpResponseTo: anHttpRequest ! ! !Object methodsFor: '*KomHttpServer' stamp: 'svp 5/16/2003 12:47'! isComancheModule ^false! ! !Object methodsFor: '*KomHttpServer' stamp: 'SVP 8/17/1999 17:51'! mimeType ^MIMEDocument defaultContentType! ! !Object methodsFor: '*Morphic-NewCurve-testing''' stamp: 'wiz 12/31/2005 21:31'! isNonZero "Overriden in Number. This returns the backstop answer for non-numbers" ^false.! ! !Object methodsFor: '*Pinesoft-EventEnhancements' stamp: 'gvc 10/25/2006 18:18'! when: anEventSelector send: aMessageSelector to: anObject exclusive: aValueHolder self when: anEventSelector evaluate: ((ExclusiveWeakMessageSend receiver: anObject selector: aMessageSelector) basicExecuting: aValueHolder)! ! !Object methodsFor: '*Pinesoft-EventEnhancements' stamp: 'gvc 10/25/2006 18:17'! when: anEventSelector send: aMessageSelector to: anObject with: anArg exclusive: aValueHolder self when: anEventSelector evaluate: ((ExclusiveWeakMessageSend receiver: anObject selector: aMessageSelector arguments: (Array with: anArg)) basicExecuting: aValueHolder)! ! !Object methodsFor: '*Pinesoft-EventEnhancements' stamp: 'gvc 10/25/2006 18:17'! when: anEventSelector send: aMessageSelector to: anObject withArguments: anArgArray exclusive: aValueHolder self when: anEventSelector evaluate: ((ExclusiveWeakMessageSend receiver: anObject selector: aMessageSelector arguments: anArgArray) basicExecuting: aValueHolder)! ! !Object methodsFor: '*Pinesoft-EventEnhancements' stamp: 'gvc 10/24/2006 11:50'! when: anEventSelector sendOnce: aMessageSelector to: anObject self when: anEventSelector evaluate: (NonReentrantWeakMessageSend receiver: anObject selector: aMessageSelector)! ! !Object methodsFor: '*Pinesoft-EventEnhancements' stamp: 'gvc 10/24/2006 11:49'! when: anEventSelector sendOnce: aMessageSelector to: anObject with: anArg self when: anEventSelector evaluate: (NonReentrantWeakMessageSend receiver: anObject selector: aMessageSelector arguments: (Array with: anArg))! ! !Object methodsFor: '*Pinesoft-EventEnhancements' stamp: 'gvc 10/24/2006 11:49'! when: anEventSelector sendOnce: aMessageSelector to: anObject withArguments: anArgArray self when: anEventSelector evaluate: (NonReentrantWeakMessageSend receiver: anObject selector: aMessageSelector arguments: anArgArray)! ! !Object methodsFor: '*Pinesoft-Widgets' stamp: 'gvc 1/10/2007 11:41'! okToClose "Sent to models when a window closing. Allows this check to be independent of okToChange." ^true! ! !Object methodsFor: '*Pinesoft-Widgets' stamp: 'gvc 4/17/2007 17:41'! taskbarIcon "Answer the icon for the receiver in a task bar or nil for the default." ^self class taskbarIcon! ! !Object methodsFor: '*Pinesoft-Widgets-override' stamp: 'gvc 9/4/2007 12:32'! windowActiveOnFirstClick "Return true if my window should be active on first click." ^true! ! !Object methodsFor: '*SeasideAdaptersCompatibility' stamp: 'pmm 11/25/2007 14:17'! toString ^self! ! !Object methodsFor: '*Tools-Explorer' stamp: 'stephaneducasse 9/17/2005 21:52'! exploreAndYourself "i.e. explore; yourself. Thisway i can peek w/o typing all the parentheses" self explore. ^self! ! !Object methodsFor: '*Tools-Explorer' stamp: 'stephaneducasse 9/17/2005 21:48'! exploreWithLabel: label ^ ObjectExplorer new openExplorerFor: self withLabel: label! ! !Object methodsFor: '*kernel-extensions-flagging' stamp: 'mtf 1/26/2008 23:34'! deprecated "Warn that the sending method has been deprecated." Preferences showDeprecationWarnings ifTrue: [Deprecation signal: thisContext sender printString, ' has been deprecated.']! ! !Object methodsFor: '*kernel-extensions-flexibility' stamp: 'kph 1/27/2008 19:21'! askFor: selector "returns true or false" ^ (self askFor: selector ifAbsent: nil) == true! ! !Object methodsFor: '*kernel-extensions-flexibility' stamp: 'kph 10/17/2007 14:01'! askFor: selector ifAbsent: aBlock "enables a default value to be specified in order to be tolerant of potentially missing methods e.g. (myPoint askFor: #originOffset) ifAbsent: [ 0@0 ]. " ^ (self class canUnderstand: selector) ifFalse: [ aBlock value ] ifTrue: [self perform: selector]! ! !Object methodsFor: '*kernel-extensions-logging' stamp: 'mtf 1/26/2008 23:52'! log "This method provides the univeral entry point fo all logging mechanisms" "Options: 1. Null for null logging 2. A LogRouter instance wih a FrameworkAdaptor. 3. CurrentLog a process local variable supplying a LogRouter" ^ (Smalltalk at: #CurrentLog ifAbsent: [ Null default ]) value sender: thisContext sender; beginEntry; yourself! ! !Object methodsFor: '*magritte-model-accessing' stamp: 'lr 3/9/2006 11:31'! description "Return the description of the reciever. Subclasses might override this message to return instance-based descriptions." ^ self class description! ! !Object methodsFor: '*magritte-model-accessing' stamp: 'lr 3/9/2006 11:31'! mementoClass "Return a class to be used to remember or cache the receiver, namely a memento object." ^ MACheckedMemento! ! !Object methodsFor: '*magritte-model-model' stamp: 'lr 3/9/2006 11:31'! readUsing: aDescription "Dispatch the read-access to the receiver using the accessor of aDescription." ^ aDescription accessor read: self! ! !Object methodsFor: '*magritte-model-model' stamp: 'lr 3/9/2006 11:31'! write: anObject using: aDescription "Dispatch the write-access to the receiver of anObject using the accessor of aDescription." aDescription accessor write: anObject to: self! ! !Object methodsFor: '*magritte-model-testing' stamp: 'lr 3/9/2006 11:31'! isDescription ^ false! ! !Object methodsFor: '*magritte-morph-converting' stamp: 'lr 3/9/2006 11:33'! asMorph ^ self description asMorphOn: self! ! !Object methodsFor: '*magritte-seaside-converting' stamp: 'lr 3/9/2006 11:33'! asComponent ^ self description asComponentOn: self! ! !Object methodsFor: '*monticello' stamp: 'dvf 8/10/2004 23:25'! isConflict ^false! ! !Object methodsFor: '*null' stamp: 'kph 9/6/2007 23:31'! ifNull: aBlock ^ self! ! !Object methodsFor: '*null' stamp: 'kph 9/6/2007 23:33'! isNull ^ false! ! !Object methodsFor: '*null' stamp: 'kph 4/12/2007 08:27'! orNull ^ self! ! !Object methodsFor: '*ob-tools-inspector' stamp: 'lr 6/5/2008 11:07'! basicInspectorNodes | nodes | nodes := OrderedCollection new: self class instSize + self basicSize + 5. nodes add: self selfInspectorNode. self class allInstVarNames withIndexDo: [ :name :index | nodes add: (OTNamedVariableNode on: self index: index name: name) ]. 1 to: self basicSize do: [ :index | nodes add: (OTIndexedVariableNode on: self index: index) ]. ^ nodes! ! !Object methodsFor: '*ob-tools-inspector' stamp: 'lr 6/5/2008 11:07'! protocolInspectorNodes ^ self class allSelectors asArray sort collect: [ :each | OTProtocolInspectorNode on: self selector: each ]! ! !Object methodsFor: '*ob-tools-inspector' stamp: 'lr 6/5/2008 09:58'! selfInspectorNode ^ OTDerivedInspectorNode on: self label: 'self' block: [ :obj | obj ]! ! !Object methodsFor: '*omnibrowser-converting' stamp: 'cwp 4/17/2006 12:16'! asAnnouncement ^ self! ! !Object methodsFor: '*pier-model' stamp: 'lr 3/9/2006 11:29'! accept: aVisitor self subclassResponsibility! ! !Object methodsFor: '*pier-model' stamp: 'lr 3/9/2006 11:29'! acceptDecorated: aVisitor self accept: aVisitor! ! !Object methodsFor: '*rio-kernel' stamp: 'kph 3/8/2007 21:25'! isRio ^ false! ! !Object methodsFor: '*scriptaculous' stamp: 'lr 1/4/2007 17:20'! asFunction ^ self asFunction: #()! ! !Object methodsFor: '*scriptaculous' stamp: 'lr 1/4/2007 17:21'! asFunction: aCollection ^ SUFunction new add: self; arguments: aCollection! ! !Object methodsFor: '*scriptaculous' stamp: 'lr 4/11/2006 19:49'! asJavascript ^ String streamContents: [ :stream | self javascriptOn: stream ]! ! !Object methodsFor: '*scriptaculous-printing' stamp: 'lr 4/20/2006 21:10'! javascriptOn: aStream self printOn: aStream! ! !Object methodsFor: '*seaside2' stamp: 'lr 6/5/2007 21:35'! deprecatedApi self deprecatedApi: thisContext sender displayString! ! !Object methodsFor: '*seaside2' stamp: 'lr 6/5/2007 21:35'! deprecatedApi: aString WADeprecatedApi raiseSignal: aString! ! !Object methodsFor: '*seaside2' stamp: 'lr 5/9/2007 08:47'! inspectorFields | members | members := Array new writeStream. self class allInstVarNames withIndexDo: [ :each :index | members nextPut: each -> (self instVarAt: index) ]. self class isVariable ifTrue: [ 1 to: self size do: [ :index | members nextPut: index -> (self at: index) ] ]. ^ members contents! ! !Object methodsFor: '*seaside2' stamp: 'avi 3/14/2005 15:19'! labelForSelector: aSymbol ^ aSymbol asCapitalizedPhrase! ! !Object methodsFor: '*seaside2' stamp: 'pmm 4/7/2007 17:14'! renderOn: aRenderer "Override this method to customize how objects (not components) are rendered when passed as an argument to #render:. The default is the return value of #displayString. Just remember that you can not use #callback:, #on:of:, or #call:" aRenderer text: self! ! !Object methodsFor: '*seaside2' stamp: 'lr 3/19/2007 23:13'! restoreFromSnapshot: anObject self copyFrom: anObject! ! !Object methodsFor: '*seaside2' stamp: 'avi 9/1/2004 21:20'! snapshotCopy ^ self shallowCopy! ! !Object methodsFor: '*seaside2' stamp: 'lr 10/28/2007 14:42'! validationError: message ^WAValidationNotification raiseSignal: message! ! !Object methodsFor: '*seaside2-encoding' stamp: 'lr 3/26/2007 20:16'! encodeOn: aDocument aDocument print: self displayString! ! !Object methodsFor: '*seaside2-squeak' stamp: 'pmm 5/22/2007 22:10'! beMutable "for VW compatibility, a hack that allows to cache a value in a literal array"! ! !Object methodsFor: '*seaside2-squeak' stamp: 'lr 7/12/2005 17:01'! displayString ^ self asString! ! !Object methodsFor: '*services-base' stamp: 'rr 3/21/2006 11:54'! requestor "returns the focused window's requestor" "SystemWindow focusedWindow ifNotNilDo: [:w | ^ w requestor]." "triggers an infinite loop" ^ Requestor default! ! !Object methodsFor: '*system-support' stamp: 'dvf 8/23/2003 12:27'! systemNavigation ^ SystemNavigation default! ! !Object methodsFor: '*tools-browser' stamp: 'mu 3/6/2004 15:13'! browse self systemNavigation browseClass: self class! ! !Object methodsFor: '*tools-browser' stamp: 'mu 3/11/2004 16:00'! browseHierarchy self systemNavigation browseHierarchy: self class! ! !Object methodsFor: '*universes' stamp: 'ls 11/26/2006 12:33'! isUPackage ^false! ! !Object methodsFor: '*universes' stamp: 'ls 11/26/2006 12:33'! isUPackageCategory ^false! ! !Object methodsFor: 'accessing' stamp: 'sw 4/30/1998 12:18'! addInstanceVarNamed: aName withValue: aValue "Add an instance variable named aName and give it value aValue" self class addInstVarName: aName asString. self instVarAt: self class instSize put: aValue! ! !Object methodsFor: 'accessing' stamp: 'yo 6/29/2004 11:39'! at: index "Primitive. Assumes receiver is indexable. Answer the value of an indexable element in the receiver. Fail if the argument index is not an Integer or is out of bounds. Essential. See Object documentation whatIsAPrimitive." index isInteger ifTrue: [self class isVariable ifTrue: [self errorSubscriptBounds: index] ifFalse: [self errorNotIndexable]]. index isNumber ifTrue: [^self at: index asInteger] ifFalse: [self errorNonIntegerIndex]! ! !Object methodsFor: 'accessing'! at: index modify: aBlock "Replace the element of the collection with itself transformed by the block" ^ self at: index put: (aBlock value: (self at: index))! ! !Object methodsFor: 'accessing' stamp: 'yo 6/29/2004 13:08'! at: index put: value "Primitive. Assumes receiver is indexable. Store the argument value in the indexable element of the receiver indicated by index. Fail if the index is not an Integer or is out of bounds. Or fail if the value is not of the right type for this kind of collection. Answer the value that was stored. Essential. See Object documentation whatIsAPrimitive." index isInteger ifTrue: [self class isVariable ifTrue: [(index >= 1 and: [index <= self size]) ifTrue: [self errorImproperStore] ifFalse: [self errorSubscriptBounds: index]] ifFalse: [self errorNotIndexable]]. index isNumber ifTrue: [^self at: index asInteger put: value] ifFalse: [self errorNonIntegerIndex]! ! !Object methodsFor: 'accessing' stamp: 'yo 9/20/2004 10:22'! basicAddInstanceVarNamed: aName withValue: aValue "Add an instance variable named aName and give it value aValue" self class addInstVarName: aName asString. self instVarAt: self class instSize put: aValue! ! !Object methodsFor: 'accessing'! basicAt: index "Primitive. Assumes receiver is indexable. Answer the value of an indexable element in the receiver. Fail if the argument index is not an Integer or is out of bounds. Essential. Do not override in a subclass. See Object documentation whatIsAPrimitive." index isInteger ifTrue: [self errorSubscriptBounds: index]. index isNumber ifTrue: [^self basicAt: index asInteger] ifFalse: [self errorNonIntegerIndex]! ! !Object methodsFor: 'accessing'! basicAt: index put: value "Primitive. Assumes receiver is indexable. Store the second argument value in the indexable element of the receiver indicated by index. Fail if the index is not an Integer or is out of bounds. Or fail if the value is not of the right type for this kind of collection. Answer the value that was stored. Essential. Do not override in a subclass. See Object documentation whatIsAPrimitive." index isInteger ifTrue: [(index >= 1 and: [index <= self size]) ifTrue: [self errorImproperStore] ifFalse: [self errorSubscriptBounds: index]]. index isNumber ifTrue: [^self basicAt: index asInteger put: value] ifFalse: [self errorNonIntegerIndex]! ! !Object methodsFor: 'accessing'! basicSize "Primitive. Answer the number of indexable variables in the receiver. This value is the same as the largest legal subscript. Essential. Do not override in any subclass. See Object documentation whatIsAPrimitive." "The number of indexable fields of fixed-length objects is 0" ^0 ! ! !Object methodsFor: 'accessing'! bindWithTemp: aBlock ^ aBlock value: self value: nil! ! !Object methodsFor: 'accessing' stamp: 'md 10/7/2004 15:43'! ifNil: nilBlock ifNotNilDo: aBlock "Evaluate aBlock with the receiver as its argument." ^ aBlock value: self ! ! !Object methodsFor: 'accessing' stamp: 'di 11/8/2000 21:04'! ifNotNilDo: aBlock "Evaluate the given block with the receiver as its argument." ^ aBlock value: self ! ! !Object methodsFor: 'accessing' stamp: 'md 10/7/2004 15:43'! ifNotNilDo: aBlock ifNil: nilBlock "Evaluate aBlock with the receiver as its argument." ^ aBlock value: self ! ! !Object methodsFor: 'accessing' stamp: 'ajh 1/21/2003 12:59'! in: aBlock "Evaluate the given block with the receiver as its argument." ^ aBlock value: self ! ! !Object methodsFor: 'accessing' stamp: 'sw 10/17/2000 11:15'! presenter "Answer the presenter object associated with the receiver. For morphs, there is in effect a clear containment hierarchy of presenters (accessed via their association with PasteUpMorphs); for arbitrary objects the hook is simply via the current world, at least at present." ^ self currentWorld presenter! ! !Object methodsFor: 'accessing'! readFromString: aString "Create an object based on the contents of aString." ^self readFrom: (ReadStream on: aString)! ! !Object methodsFor: 'accessing' stamp: 'di 3/29/1999 13:10'! size "Primitive. Answer the number of indexable variables in the receiver. This value is the same as the largest legal subscript. Essential. See Object documentation whatIsAPrimitive." self class isVariable ifFalse: [self errorNotIndexable]. ^ 0! ! !Object methodsFor: 'accessing' stamp: 'md 5/16/2006 12:34'! yourself "Answer self." ^self! ! !Object methodsFor: 'associating' stamp: 'md 7/22/2005 16:03'! -> anObject "Answer an Association between self and anObject" ^Association basicNew key: self value: anObject! ! !Object methodsFor: 'binding'! bindingOf: aString ^nil! ! !Object methodsFor: 'breakpoint' stamp: 'bkv 7/1/2003 12:33'! break "This is a simple message to use for inserting breakpoints during debugging. The debugger is opened by sending a signal. This gives a chance to restore invariants related to multiple processes." BreakPoint signal. "nil break."! ! !Object methodsFor: 'casing'! caseOf: aBlockAssociationCollection "The elements of aBlockAssociationCollection are associations between blocks. Answer the evaluated value of the first association in aBlockAssociationCollection whose evaluated key equals the receiver. If no match is found, report an error." ^ self caseOf: aBlockAssociationCollection otherwise: [self caseError] "| z | z _ {[#a]->[1+1]. ['b' asSymbol]->[2+2]. [#c]->[3+3]}. #b caseOf: z" "| z | z _ {[#a]->[1+1]. ['d' asSymbol]->[2+2]. [#c]->[3+3]}. #b caseOf: z" "The following are compiled in-line:" "#b caseOf: {[#a]->[1+1]. ['b' asSymbol]->[2+2]. [#c]->[3+3]}" "#b caseOf: {[#a]->[1+1]. ['d' asSymbol]->[2+2]. [#c]->[3+3]}"! ! !Object methodsFor: 'casing'! caseOf: aBlockAssociationCollection otherwise: aBlock "The elements of aBlockAssociationCollection are associations between blocks. Answer the evaluated value of the first association in aBlockAssociationCollection whose evaluated key equals the receiver. If no match is found, answer the result of evaluating aBlock." aBlockAssociationCollection associationsDo: [:assoc | (assoc key value = self) ifTrue: [^assoc value value]]. ^ aBlock value "| z | z _ {[#a]->[1+1]. ['b' asSymbol]->[2+2]. [#c]->[3+3]}. #b caseOf: z otherwise: [0]" "| z | z _ {[#a]->[1+1]. ['d' asSymbol]->[2+2]. [#c]->[3+3]}. #b caseOf: z otherwise: [0]" "The following are compiled in-line:" "#b caseOf: {[#a]->[1+1]. ['b' asSymbol]->[2+2]. [#c]->[3+3]} otherwise: [0]" "#b caseOf: {[#a]->[1+1]. ['d' asSymbol]->[2+2]. [#c]->[3+3]} otherwise: [0]"! ! !Object methodsFor: 'class membership'! class "Primitive. Answer the object which is the receiver's class. Essential. See Object documentation whatIsAPrimitive." self primitiveFailed! ! !Object methodsFor: 'class membership' stamp: 'sw 9/27/2001 15:51'! inheritsFromAnyIn: aList "Answer whether the receiver inherits from any class represented by any element in the list. The elements of the list can be classes, class name symbols, or strings representing possible class names. This allows speculative membership tests to be made even when some of the classes may not be known to the current image, and even when their names are not interned symbols." | aClass | aList do: [:elem | Symbol hasInterned: elem asString ifTrue: [:elemSymbol | (((aClass _ Smalltalk at: elemSymbol ifAbsent: [nil]) isKindOf: Class) and: [self isKindOf: aClass]) ifTrue: [^ true]]]. ^ false " {3. true. 'olive'} do: [:token | {{#Number. #Boolean}. {Number. Boolean }. {'Number'. 'Boolean'}} do: [:list | Transcript cr; show: token asString, ' list element provided as a ', list first class name, ' - ', (token inheritsFromAnyIn: list) asString]] "! ! !Object methodsFor: 'class membership'! isKindOf: aClass "Answer whether the class, aClass, is a superclass or class of the receiver." self class == aClass ifTrue: [^true] ifFalse: [^self class inheritsFrom: aClass]! ! !Object methodsFor: 'class membership' stamp: 'sw 2/16/98 02:08'! isKindOf: aClass orOf: anotherClass "Answer whether either of the classes, aClass or anotherClass,, is a superclass or class of the receiver. A convenience; could be somewhat optimized" ^ (self isKindOf: aClass) or: [self isKindOf: anotherClass]! ! !Object methodsFor: 'class membership'! isMemberOf: aClass "Answer whether the receiver is an instance of the class, aClass." ^self class == aClass! ! !Object methodsFor: 'class membership'! respondsTo: aSymbol "Answer whether the method dictionary of the receiver's class contains aSymbol as a message selector." ^self class canUnderstand: aSymbol! ! !Object methodsFor: 'class membership' stamp: 'tk 10/21/1998 12:38'! xxxClass "For subclasses of nil, such as ObjectOut" ^ self class! ! !Object methodsFor: 'comparing' stamp: 'tk 4/16/1999 18:26'! closeTo: anObject "Answer whether the receiver and the argument represent the same object. If = is redefined in any subclass, consider also redefining the message hash." | ans | [ans _ self = anObject] ifError: [:aString :aReceiver | ^ false]. ^ ans! ! !Object methodsFor: 'comparing'! hash "Answer a SmallInteger whose value is related to the receiver's identity. May be overridden, and should be overridden in any classes that define = " ^ self identityHash! ! !Object methodsFor: 'comparing' stamp: 'pm 9/23/97 09:36'! hashMappedBy: map "Answer what my hash would be if oops changed according to map." ^map newHashFor: self! ! !Object methodsFor: 'comparing' stamp: 'di 9/27/97 20:23'! identityHashMappedBy: map "Answer what my hash would be if oops changed according to map." ^map newHashFor: self! ! !Object methodsFor: 'comparing' stamp: 'sw 8/20/1998 12:34'! identityHashPrintString "'fred' identityHashPrintString" ^ '(', self identityHash printString, ')'! ! !Object methodsFor: 'comparing' stamp: 'ajh 2/2/2002 15:02'! literalEqual: other ^ self class == other class and: [self = other]! ! !Object methodsFor: 'comparing'! = anObject "Answer whether the receiver and the argument represent the same object. If = is redefined in any subclass, consider also redefining the message hash." ^self == anObject! ! !Object methodsFor: 'comparing'! ~= anObject "Answer whether the receiver and the argument do not represent the same object." ^self = anObject == false! ! !Object methodsFor: 'converting' stamp: 'di 11/9/1998 12:15'! adaptToFloat: rcvr andSend: selector "If no method has been provided for adapting an object to a Float, then it may be adequate to simply adapt it to a number." ^ self adaptToNumber: rcvr andSend: selector! ! !Object methodsFor: 'converting' stamp: 'di 11/9/1998 12:14'! adaptToFraction: rcvr andSend: selector "If no method has been provided for adapting an object to a Fraction, then it may be adequate to simply adapt it to a number." ^ self adaptToNumber: rcvr andSend: selector! ! !Object methodsFor: 'converting' stamp: 'di 11/9/1998 12:15'! adaptToInteger: rcvr andSend: selector "If no method has been provided for adapting an object to a Integer, then it may be adequate to simply adapt it to a number." ^ self adaptToNumber: rcvr andSend: selector! ! !Object methodsFor: 'converting' stamp: 'rw 4/27/2002 07:48'! asActionSequence ^WeakActionSequence with: self! ! !Object methodsFor: 'converting' stamp: 'rw 7/20/2003 16:03'! asActionSequenceTrappingErrors ^WeakActionSequenceTrappingErrors with: self! ! !Object methodsFor: 'converting' stamp: 'svp 5/16/2000 18:14'! asDraggableMorph ^(StringMorph contents: self printString) color: Color white; yourself! ! !Object methodsFor: 'converting' stamp: 'sma 5/12/2000 17:39'! asOrderedCollection "Answer an OrderedCollection with the receiver as its only element." ^ OrderedCollection with: self! ! !Object methodsFor: 'converting'! asString "Answer a string that represents the receiver." ^ self printString ! ! !Object methodsFor: 'converting' stamp: 'ajh 3/11/2003 10:27'! asStringOrText "Answer a string that represents the receiver." ^ self printString ! ! !Object methodsFor: 'converting'! as: aSimilarClass "Create an object of class aSimilarClass that has similar contents to the receiver." ^ aSimilarClass newFrom: self! ! !Object methodsFor: 'converting' stamp: 'RAA 8/2/1999 12:41'! complexContents ^self! ! !Object methodsFor: 'converting' stamp: 'ajh 7/6/2003 20:37'! mustBeBoolean "Catches attempts to test truth of non-Booleans. This message is sent from the VM. The sending context is rewound to just before the jump causing this exception." ^ self mustBeBooleanIn: thisContext sender! ! !Object methodsFor: 'converting' stamp: 'ajh 7/6/2003 20:40'! mustBeBooleanIn: context "context is the where the non-boolean error occurred. Rewind context to before jump then raise error." | proceedValue | context skipBackBeforeJump. proceedValue _ NonBooleanReceiver new object: self; signal: 'proceed for truth.'. ^ proceedValue ~~ false! ! !Object methodsFor: 'converting' stamp: 'sw 3/26/2001 12:12'! printDirectlyToDisplay "For debugging: write the receiver's printString directly to the display at (0, 100); senders of this are detected by the check-for-slips mechanism." self asString displayAt: 0@100 "StringMorph someInstance printDirectlyToDisplay"! ! !Object methodsFor: 'converting' stamp: 'RAA 3/31/1999 12:13'! withoutListWrapper ^self! ! !Object methodsFor: 'copying'! clone self primitiveFailed! ! !Object methodsFor: 'copying' stamp: 'ajh 8/18/2001 21:25'! copy "Answer another instance just like the receiver. Subclasses typically override postCopy; they typically do not override shallowCopy." ^self shallowCopy postCopy! ! !Object methodsFor: 'copying' stamp: 'tk 8/20/1998 16:01'! copyAddedStateFrom: anotherObject "Copy over the values of instance variables added by the receiver's class from anotherObject to the receiver. These will be remapped in mapUniClasses, if needed." self class superclass instSize + 1 to: self class instSize do: [:index | self instVarAt: index put: (anotherObject instVarAt: index)]! ! !Object methodsFor: 'copying' stamp: 'tpr 2/14/2004 21:53'! copyFrom: anotherObject "Copy to myself all instance variables I have in common with anotherObject. This is dangerous because it ignores an object's control over its own inst vars. " | mine his | mine _ self class allInstVarNames. his _ anotherObject class allInstVarNames. 1 to: (mine size min: his size) do: [:ind | (mine at: ind) = (his at: ind) ifTrue: [ self instVarAt: ind put: (anotherObject instVarAt: ind)]]. self class isVariable & anotherObject class isVariable ifTrue: [ 1 to: (self basicSize min: anotherObject basicSize) do: [:ind | self basicAt: ind put: (anotherObject basicAt: ind)]].! ! !Object methodsFor: 'copying' stamp: 'ajh 5/23/2002 00:38'! copySameFrom: otherObject "Copy to myself all instance variables named the same in otherObject. This ignores otherObject's control over its own inst vars." | myInstVars otherInstVars match | myInstVars _ self class allInstVarNames. otherInstVars _ otherObject class allInstVarNames. myInstVars doWithIndex: [:each :index | (match _ otherInstVars indexOf: each) > 0 ifTrue: [self instVarAt: index put: (otherObject instVarAt: match)]]. 1 to: (self basicSize min: otherObject basicSize) do: [:i | self basicAt: i put: (otherObject basicAt: i)]. ! ! !Object methodsFor: 'copying' stamp: 'tk 4/20/1999 14:44'! copyTwoLevel "one more level than a shallowCopy" | newObject class index | class _ self class. newObject _ self clone. newObject == self ifTrue: [^ self]. class isVariable ifTrue: [index _ self basicSize. [index > 0] whileTrue: [newObject basicAt: index put: (self basicAt: index) shallowCopy. index _ index - 1]]. index _ class instSize. [index > 0] whileTrue: [newObject instVarAt: index put: (self instVarAt: index) shallowCopy. index _ index - 1]. ^newObject! ! !Object methodsFor: 'copying'! deepCopy "Answer a copy of the receiver with its own copy of each instance variable." | newObject class index | class _ self class. (class == Object) ifTrue: [^self]. class isVariable ifTrue: [index _ self basicSize. newObject _ class basicNew: index. [index > 0] whileTrue: [newObject basicAt: index put: (self basicAt: index) deepCopy. index _ index - 1]] ifFalse: [newObject _ class basicNew]. index _ class instSize. [index > 0] whileTrue: [newObject instVarAt: index put: (self instVarAt: index) deepCopy. index _ index - 1]. ^newObject! ! !Object methodsFor: 'copying' stamp: 'hg 11/23/1999 13:43'! initialDeepCopierSize "default value is 4096; other classes may override this, esp. for smaller (=faster) sizes" ^4096! ! !Object methodsFor: 'copying' stamp: 'ajh 1/27/2003 18:45'! postCopy "self is a shallow copy, subclasses should copy fields as necessary to complete the full copy" ^ self! ! !Object methodsFor: 'copying' stamp: 'jm 11/14/97 11:08'! shallowCopy "Answer a copy of the receiver which shares the receiver's instance variables." | class newObject index | class _ self class. class isVariable ifTrue: [index _ self basicSize. newObject _ class basicNew: index. [index > 0] whileTrue: [newObject basicAt: index put: (self basicAt: index). index _ index - 1]] ifFalse: [newObject _ class basicNew]. index _ class instSize. [index > 0] whileTrue: [newObject instVarAt: index put: (self instVarAt: index). index _ index - 1]. ^ newObject! ! !Object methodsFor: 'copying' stamp: 'tk 3/11/2003 13:58'! veryDeepCopy "Do a complete tree copy using a dictionary. An object in the tree twice is only copied once. All references to the object in the copy of the tree will point to the new copy." | copier new | copier _ DeepCopier new initialize: self initialDeepCopierSize. new _ self veryDeepCopyWith: copier. copier mapUniClasses. copier references associationsDo: [:assoc | assoc value veryDeepFixupWith: copier]. copier fixDependents. ^ new! ! !Object methodsFor: 'copying' stamp: 'tk 3/11/2003 13:58'! veryDeepCopySibling "Do a complete tree copy using a dictionary. Substitute a clone of oldPlayer for the root. Normally, a Player or non systemDefined object would have a new class. We do not want one this time. An object in the tree twice, is only copied once. All references to the object in the copy of the tree will point to the new copy." | copier new | copier _ DeepCopier new initialize: self initialDeepCopierSize. copier newUniClasses: false. new _ self veryDeepCopyWith: copier. copier mapUniClasses. copier references associationsDo: [:assoc | assoc value veryDeepFixupWith: copier]. copier fixDependents. ^ new! ! !Object methodsFor: 'copying' stamp: 'tk 5/13/2003 19:39'! veryDeepCopyUsing: copier "Do a complete tree copy using a dictionary. An object in the tree twice is only copied once. All references to the object in the copy of the tree will point to the new copy. Same as veryDeepCopy except copier (with dictionary) is supplied. ** do not delete this method, even if it has no callers **" | new refs newDep newModel | new _ self veryDeepCopyWith: copier. copier mapUniClasses. copier references associationsDo: [:assoc | assoc value veryDeepFixupWith: copier]. "Fix dependents" refs _ copier references. DependentsFields associationsDo: [:pair | pair value do: [:dep | (newDep _ refs at: dep ifAbsent: [nil]) ifNotNil: [ newModel _ refs at: pair key ifAbsent: [pair key]. newModel addDependent: newDep]]]. ^ new! ! !Object methodsFor: 'copying' stamp: 'tk 3/11/2003 14:12'! veryDeepCopyWith: deepCopier "Copy me and the entire tree of objects I point to. An object in the tree twice is copied once, and both references point to him. deepCopier holds a dictionary of objects we have seen. Some classes refuse to be copied. Some classes are picky about which fields get deep copied." | class index sub subAss new uc sup has mine | deepCopier references at: self ifPresent: [:newer | ^ newer]. "already did him" class _ self class. class isMeta ifTrue: [^ self]. "a class" new _ self clone. (class isSystemDefined not and: [deepCopier newUniClasses "allowed"]) ifTrue: [ uc _ deepCopier uniClasses at: class ifAbsent: [nil]. uc ifNil: [ deepCopier uniClasses at: class put: (uc _ self copyUniClassWith: deepCopier). deepCopier references at: class put: uc]. "remember" new _ uc new. new copyFrom: self]. "copy inst vars in case any are weak" deepCopier references at: self put: new. "remember" (class isVariable and: [class isPointers]) ifTrue: [index _ self basicSize. [index > 0] whileTrue: [sub _ self basicAt: index. (subAss _ deepCopier references associationAt: sub ifAbsent: [nil]) ifNil: [new basicAt: index put: (sub veryDeepCopyWith: deepCopier)] ifNotNil: [new basicAt: index put: subAss value]. index _ index - 1]]. "Ask each superclass if it wants to share (weak copy) any inst vars" new veryDeepInner: deepCopier. "does super a lot" "other superclasses want all inst vars deep copied" sup _ class. index _ class instSize. [has _ sup compiledMethodAt: #veryDeepInner: ifAbsent: [nil]. has _ has ifNil: [class isSystemDefined not "is a uniClass"] ifNotNil: [true]. mine _ sup instVarNames. has ifTrue: [index _ index - mine size] "skip inst vars" ifFalse: [1 to: mine size do: [:xx | sub _ self instVarAt: index. (subAss _ deepCopier references associationAt: sub ifAbsent: [nil]) "use association, not value, so nil is an exceptional value" ifNil: [new instVarAt: index put: (sub veryDeepCopyWith: deepCopier)] ifNotNil: [new instVarAt: index put: subAss value]. index _ index - 1]]. (sup _ sup superclass) == nil] whileFalse. new rehash. "force Sets and Dictionaries to rehash" ^ new ! ! !Object methodsFor: 'copying' stamp: 'tk 1/6/1999 17:39'! veryDeepFixupWith: deepCopier "I have no fields and no superclass. Catch the super call." ! ! !Object methodsFor: 'copying' stamp: 'tk 9/4/2001 10:30'! veryDeepInner: deepCopier "No special treatment for inst vars of my superclasses. Override when some need to be weakly copied. Object>>veryDeepCopyWith: will veryDeepCopy any inst var whose class does not actually define veryDeepInner:" ! ! !Object methodsFor: 'creation' stamp: 'nk 2/26/2004 13:35'! asStringMorph "Open a StringMorph, as best one can, on the receiver" ^ self asStringOrText asStringMorph ! ! !Object methodsFor: 'creation' stamp: 'nk 2/26/2004 13:35'! asTextMorph "Open a TextMorph, as best one can, on the receiver" ^ TextMorph new contentsAsIs: self asStringOrText ! ! !Object methodsFor: 'creation' stamp: 'sw 1/29/2002 21:45'! openAsMorph "Open a morph, as best one can, on the receiver" ^ self asMorph openInHand " 234 openAsMorph (ScriptingSystem formAtKey: #TinyMenu) openAsMorph 'fred' openAsMorph "! ! !Object methodsFor: 'debugging' stamp: 'md 11/24/2004 11:45'! haltIf: condition "This is the typical message to use for inserting breakpoints during debugging. Param can be a block or expression, halt if true. If the Block has one arg, the receiver is bound to that. If the condition is a selector, we look up in the callchain. Halt if any method's selector equals selector." | cntxt | condition isSymbol ifTrue:[ "only halt if a method with selector symbol is in callchain" cntxt := thisContext. [cntxt sender isNil] whileFalse: [ cntxt := cntxt sender. (cntxt selector = condition) ifTrue: [Halt signal]. ]. ^self. ]. (condition isBlock ifTrue: [condition valueWithPossibleArgument: self] ifFalse: [condition] ) ifTrue: [ Halt signal ].! ! !Object methodsFor: 'debugging'! needsWork! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:26'! checkHaltCountExpired | counter | counter _ Smalltalk at: #HaltCount ifAbsent: [0]. ^counter = 0! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:04'! clearHaltOnce "Turn on the halt once flag." Smalltalk at: #HaltOnce put: false! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:30'! decrementAndCheckHaltCount self decrementHaltCount. ^self checkHaltCountExpired! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:28'! decrementHaltCount | counter | counter := Smalltalk at: #HaltCount ifAbsent: [0]. counter > 0 ifTrue: [ counter _ counter - 1. self setHaltCountTo: counter]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:42'! doExpiredHaltCount self clearHaltOnce. self removeHaltCount. self halt! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:44'! doExpiredHaltCount: aString self clearHaltOnce. self removeHaltCount. self halt: aString! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:45'! doExpiredInspectCount self clearHaltOnce. self removeHaltCount. self inspect! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:43'! haltOnCount: int self haltOnceEnabled ifTrue: [self hasHaltCount ifTrue: [self decrementAndCheckHaltCount ifTrue: [self doExpiredHaltCount]] ifFalse: [int = 1 ifTrue: [self doExpiredHaltCount] ifFalse: [self setHaltCountTo: int - 1]]]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:05'! haltOnce "Halt unless we have already done it once." self haltOnceEnabled ifTrue: [self clearHaltOnce. ^ self halt]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:04'! haltOnceEnabled ^ Smalltalk at: #HaltOnce ifAbsent: [false]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:05'! haltOnce: aString "Halt unless we have already done it once." self haltOnceEnabled ifTrue: [self clearHaltOnce. ^ self halt: aString]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:45'! halt: aString onCount: int self haltOnceEnabled ifTrue: [self hasHaltCount ifTrue: [self decrementAndCheckHaltCount ifTrue: [self doExpiredHaltCount: aString]] ifFalse: [int = 1 ifTrue: [self doExpiredHaltCount: aString] ifFalse: [self setHaltCountTo: int - 1]]]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:36'! hasHaltCount ^Smalltalk includesKey: #HaltCount! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:46'! inspectOnCount: int self haltOnceEnabled ifTrue: [self hasHaltCount ifTrue: [self decrementAndCheckHaltCount ifTrue: [self doExpiredInspectCount]] ifFalse: [int = 1 ifTrue: [self doExpiredInspectCount] ifFalse: [self setHaltCountTo: int - 1]]]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:05'! inspectOnce "Inspect unless we have already done it once." self haltOnceEnabled ifTrue: [self clearHaltOnce. ^ self inspect]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 13:20'! inspectUntilCount: int self haltOnceEnabled ifTrue: [self hasHaltCount ifTrue: [self decrementAndCheckHaltCount ifTrue: [self doExpiredInspectCount] ifFalse: [self inspect]] ifFalse: [int = 1 ifTrue: [self doExpiredInspectCount] ifFalse: [self setHaltCountTo: int - 1]]]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:49'! removeHaltCount (Smalltalk includesKey: #HaltCount) ifTrue: [ Smalltalk removeKey: #HaltCount]! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 6/2/2004 08:25'! setHaltCountTo: int Smalltalk at: #HaltCount put: int! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:04'! setHaltOnce "Turn on the halt once flag." Smalltalk at: #HaltOnce put: true! ! !Object methodsFor: 'debugging-haltOnce' stamp: 'sbw 5/19/2004 19:04'! toggleHaltOnce self haltOnceEnabled ifTrue: [self clearHaltOnce] ifFalse: [self setHaltOnce]! ! !Object methodsFor: 'dependents access' stamp: 'ar 2/11/2001 01:55'! addDependent: anObject "Make the given object one of the receiver's dependents." | dependents | dependents _ self dependents. (dependents includes: anObject) ifFalse: [self myDependents: (dependents copyWithDependent: anObject)]. ^ anObject! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 19:53'! breakDependents "Remove all of the receiver's dependents." self myDependents: nil! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 19:26'! canDiscardEdits "Answer true if none of the views on this model has unaccepted edits that matter." self dependents do: [:each | each canDiscardEdits ifFalse: [^ false]] without: self. ^ true! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 19:58'! dependents "Answer a collection of objects that are 'dependent' on the receiver; that is, all objects that should be notified if the receiver changes." ^ self myDependents ifNil: [#()]! ! !Object methodsFor: 'dependents access'! evaluate: actionBlock wheneverChangeIn: aspectBlock | viewerThenObject objectThenViewer | objectThenViewer _ self. viewerThenObject _ ObjectViewer on: objectThenViewer. objectThenViewer become: viewerThenObject. "--- Then ---" objectThenViewer xxxViewedObject: viewerThenObject evaluate: actionBlock wheneverChangeIn: aspectBlock! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 19:59'! hasUnacceptedEdits "Answer true if any of the views on this object has unaccepted edits." self dependents do: [:each | each hasUnacceptedEdits ifTrue: [^ true]] without: self. ^ false! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 19:55'! myDependents "Private. Answer a list of all the receiver's dependents." ^ DependentsFields at: self ifAbsent: []! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 19:52'! myDependents: aCollectionOrNil "Private. Set (or remove) the receiver's dependents list." aCollectionOrNil ifNil: [DependentsFields removeKey: self ifAbsent: []] ifNotNil: [DependentsFields at: self put: aCollectionOrNil]! ! !Object methodsFor: 'dependents access' stamp: 'reThink 2/18/2001 17:06'! release "Remove references to objects that may refer to the receiver. This message should be overridden by subclasses with any cycles, in which case the subclass should also include the expression super release." self releaseActionMap! ! !Object methodsFor: 'dependents access' stamp: 'sma 2/29/2000 20:23'! removeDependent: anObject "Remove the given object as one of the receiver's dependents." | dependents | dependents _ self dependents reject: [:each | each == anObject]. self myDependents: (dependents isEmpty ifFalse: [dependents]). ^ anObject! ! !Object methodsFor: 'drag and drop' stamp: 'bh 9/16/2001 18:10'! acceptDroppingMorph: transferMorph event: evt inMorph: dstListMorph ^false.! ! !Object methodsFor: 'drag and drop' stamp: 'mir 5/16/2000 11:35'! dragAnimationFor: item transferMorph: transferMorph "Default do nothing"! ! !Object methodsFor: 'drag and drop' stamp: 'panda 4/28/2000 16:20'! dragPassengerFor: item inMorph: dragSource ^item! ! !Object methodsFor: 'drag and drop' stamp: 'panda 4/28/2000 16:11'! dragTransferType ^nil! ! !Object methodsFor: 'drag and drop' stamp: 'panda 4/28/2000 16:05'! dragTransferTypeForMorph: dragSource ^nil! ! !Object methodsFor: 'drag and drop' stamp: 'mir 5/8/2000 17:19'! wantsDroppedMorph: aMorph event: anEvent inMorph: destinationLM ^false! ! !Object methodsFor: 'error handling' stamp: 'sma 5/6/2000 19:35'! assert: aBlock "Throw an assertion error if aBlock does not evaluates to true." aBlock value ifFalse: [AssertionFailure signal: 'Assertion failed']! ! !Object methodsFor: 'error handling' stamp: 'nk 1/15/2004 10:54'! assert: aBlock descriptionBlock: descriptionBlock "Throw an assertion error if aBlock does not evaluate to true." aBlock value ifFalse: [AssertionFailure signal: descriptionBlock value asString ]! ! !Object methodsFor: 'error handling' stamp: 'nk 10/25/2003 16:47'! assert: aBlock description: aString "Throw an assertion error if aBlock does not evaluates to true." aBlock value ifFalse: [AssertionFailure signal: aString ]! ! !Object methodsFor: 'error handling' stamp: 'md 10/13/2004 15:59'! backwardCompatibilityOnly: anExplanationString "Warn that the sending method has been deprecated. Methods that are tagt with #backwardCompatibility: are kept for compatibility." Preferences showDeprecationWarnings ifTrue: [Deprecation signal: thisContext sender printString, ' has been deprecated (but will be kept for compatibility). ', anExplanationString]! ! !Object methodsFor: 'error handling'! caseError "Report an error from an in-line or explicit case statement." self error: 'Case not found, and no otherwise clause'! ! !Object methodsFor: 'error handling' stamp: 'rbb 3/1/2005 09:26'! confirm: queryString "Put up a yes/no menu with caption queryString. Answer true if the response is yes, false if no. This is a modal question--the user must respond yes or no." "nil confirm: 'Are you hungry?'" ^ UIManager default confirm: queryString! ! !Object methodsFor: 'error handling' stamp: 'rbb 3/1/2005 09:27'! confirm: aString orCancel: cancelBlock "Put up a yes/no/cancel menu with caption aString. Answer true if the response is yes, false if no. If cancel is chosen, evaluate cancelBlock. This is a modal question--the user must respond yes or no." ^ UIManager default confirm: aString orCancel: cancelBlock! ! !Object methodsFor: 'error handling' stamp: 'dew 10/6/2003 18:20'! deprecated: anExplanationString "Warn that the sending method has been deprecated." Preferences showDeprecationWarnings ifTrue: [Deprecation signal: thisContext sender printString, ' has been deprecated. ', anExplanationString]! ! !Object methodsFor: 'error handling' stamp: 'dew 10/7/2003 00:26'! deprecated: anExplanationString block: aBlock "Warn that the sender has been deprecated. Answer the value of aBlock on resumption. (Note that #deprecated: is usually the preferred method.)" Preferences showDeprecationWarnings ifTrue: [Deprecation signal: thisContext sender printString, ' has been deprecated. ', anExplanationString]. ^ aBlock value. ! ! !Object methodsFor: 'error handling' stamp: 'md 2/22/2006 21:21'! doesNotUnderstand: aMessage "Handle the fact that there was an attempt to send the given message to the receiver but the receiver does not understand this message (typically sent from the machine when a message is sent to the receiver and no method is defined for that selector)." "Testing: (3 activeProcess)" MessageNotUnderstood new message: aMessage; receiver: self; signal. ^ aMessage sentTo: self. ! ! !Object methodsFor: 'error handling' stamp: 'TRee 11/4/2003 16:47'! dpsTrace: reportObject Transcript myDependents isNil ifTrue: [^self]. self dpsTrace: reportObject levels: 1 withContext: thisContext " nil dpsTrace: 'sludder'. "! ! !Object methodsFor: 'error handling' stamp: 'TRee 11/4/2003 16:49'! dpsTrace: reportObject levels: anInt self dpsTrace: reportObject levels: anInt withContext: thisContext "(1 to: 3) do: [:int | nil dpsTrace: int levels: 5.]"! ! !Object methodsFor: 'error handling' stamp: 'TRee 11/4/2003 17:02'! dpsTrace: reportObject levels: anInt withContext: currentContext | reportString context displayCount | reportString := (reportObject respondsTo: #asString) ifTrue: [reportObject asString] ifFalse: [reportObject printString]. (Smalltalk at: #Decompiler ifAbsent: [nil]) ifNil: [Transcript cr; show: reportString] ifNotNil: [context := currentContext. displayCount := anInt > 1. 1 to: anInt do: [:count | Transcript cr. displayCount ifTrue: [Transcript show: count printString, ': ']. reportString notNil ifTrue: [Transcript show: context home class name , '/' , context sender selector, ' (' , reportString , ')'. context := context sender. reportString := nil] ifFalse: [(context notNil and: [(context := context sender) notNil]) ifTrue: [Transcript show: context receiver class name , '/' , context selector]]]. "Transcript cr"].! ! !Object methodsFor: 'error handling' stamp: 'md 8/2/2005 22:17'! error "Throw a generic Error exception." ^self error: 'Error!!'.! ! !Object methodsFor: 'error handling' stamp: 'tfei 4/12/1999 12:55'! error: aString "Throw a generic Error exception." ^Error new signal: aString! ! !Object methodsFor: 'error handling' stamp: 'al 9/16/2005 14:12'! explicitRequirement self error: 'Explicitly required method'! ! !Object methodsFor: 'error handling' stamp: 'al 2/13/2006 22:20'! halt "This is the typical message to use for inserting breakpoints during debugging. It behaves like halt:, but does not call on halt: in order to avoid putting this message on the stack. Halt is especially useful when the breakpoint message is an arbitrary one." Halt signal! ! !Object methodsFor: 'error handling' stamp: 'tfei 4/12/1999 12:59'! halt: aString "This is the typical message to use for inserting breakpoints during debugging. It creates and schedules a Notifier with the argument, aString, as the label." Halt new signal: aString! ! !Object methodsFor: 'error handling' stamp: 'md 1/20/2006 16:24'! handles: exception "This method exists in case a non exception class is the first arg in an on:do: (for instance using a exception class that is not loaded). We prefer this to raising an error during error handling itself. Also, semantically it makes sense that the exception handler is not active if its exception class is not loaded" ^ false! ! !Object methodsFor: 'error handling' stamp: 'ar 9/27/2005 20:24'! notifyWithLabel: aString "Create and schedule a Notifier with aString as the window label as well as the contents of the window, in order to request confirmation before a process can proceed." ToolSet debugContext: thisContext label: aString contents: aString "nil notifyWithLabel: 'let us see if this works'"! ! !Object methodsFor: 'error handling' stamp: 'hg 10/2/2001 20:49'! notify: aString "Create and schedule a Notifier with the argument as the message in order to request confirmation before a process can proceed." Warning signal: aString "nil notify: 'confirmation message'"! ! !Object methodsFor: 'error handling'! notify: aString at: location "Create and schedule a Notifier with the argument as the message in order to request confirmation before a process can proceed. Subclasses can override this and insert an error message at location within aString." self notify: aString "nil notify: 'confirmation message' at: 12"! ! !Object methodsFor: 'error handling'! primitiveFailed "Announce that a primitive has failed and there is no appropriate Smalltalk code to run." self error: 'a primitive has failed'! ! !Object methodsFor: 'error handling' stamp: 'al 9/16/2005 14:12'! requirement self error: 'Implicitly required method'! ! !Object methodsFor: 'error handling' stamp: 'AFi 2/8/2003 22:52'! shouldBeImplemented "Announce that this message should be implemented" self error: 'This message should be implemented'! ! !Object methodsFor: 'error handling'! shouldNotImplement "Announce that, although the receiver inherits this message, it should not implement it." self error: 'This message is not appropriate for this object'! ! !Object methodsFor: 'error handling' stamp: 'md 2/17/2006 12:02'! subclassResponsibility "This message sets up a framework for the behavior of the class' subclasses. Announce that the subclass should have implemented this message." self error: 'My subclass should have overridden ', thisContext sender selector printString! ! !Object methodsFor: 'error handling' stamp: 'al 12/16/2003 16:16'! traitConflict self error: 'A class or trait does not properly resolve a conflict between multiple traits it uses.'! ! !Object methodsFor: 'evaluating' stamp: 'reThink 3/12/2001 18:14'! value ^self! ! !Object methodsFor: 'evaluating' stamp: 'reThink 2/18/2001 15:23'! valueWithArguments: aSequenceOfArguments ^self! ! !Object methodsFor: 'events' stamp: 'nk 8/27/2003 16:23'! actionsWithReceiver: anObject forEvent: anEventSelector ^(self actionSequenceForEvent: anEventSelector) select: [:anAction | anAction receiver == anObject ]! ! !Object methodsFor: 'events' stamp: 'nk 8/27/2003 17:45'! renameActionsWithReceiver: anObject forEvent: anEventSelector toEvent: newEvent | oldActions newActions | oldActions _ Set new. newActions _ Set new. (self actionSequenceForEvent: anEventSelector) do: [ :action | action receiver == anObject ifTrue: [ oldActions add: anObject ] ifFalse: [ newActions add: anObject ]]. self setActionSequence: (ActionSequence withAll: newActions) forEvent: anEventSelector. oldActions do: [ :act | self when: newEvent evaluate: act ].! ! !Object methodsFor: 'events-accessing' stamp: 'nk 12/20/2002 17:48'! actionForEvent: anEventSelector "Answer the action to be evaluated when has been triggered." | actions | actions := self actionMap at: anEventSelector asSymbol ifAbsent: [nil]. actions ifNil: [^nil]. ^ actions asMinimalRepresentation! ! !Object methodsFor: 'events-accessing' stamp: 'nk 12/20/2002 17:48'! actionForEvent: anEventSelector ifAbsent: anExceptionBlock "Answer the action to be evaluated when has been triggered." | actions | actions := self actionMap at: anEventSelector asSymbol ifAbsent: [nil]. actions ifNil: [^anExceptionBlock value]. ^ actions asMinimalRepresentation! ! !Object methodsFor: 'events-accessing' stamp: 'reThink 2/18/2001 14:43'! actionMap ^EventManager actionMapFor: self! ! !Object methodsFor: 'events-accessing' stamp: 'rw 4/27/2002 08:35'! actionSequenceForEvent: anEventSelector ^(self actionMap at: anEventSelector asSymbol ifAbsent: [^WeakActionSequence new]) asActionSequence! ! !Object methodsFor: 'events-accessing' stamp: 'SqR 6/28/2001 13:19'! actionsDo: aBlock self actionMap do: aBlock! ! !Object methodsFor: 'events-accessing' stamp: 'rw 2/10/2002 13:05'! createActionMap ^IdentityDictionary new! ! !Object methodsFor: 'events-accessing' stamp: 'SqR 2/19/2001 14:04'! hasActionForEvent: anEventSelector "Answer true if there is an action associated with anEventSelector" ^(self actionForEvent: anEventSelector) notNil! ! !Object methodsFor: 'events-accessing' stamp: 'reThink 2/18/2001 15:29'! setActionSequence: actionSequence forEvent: anEventSelector | action | action := actionSequence asMinimalRepresentation. action == nil ifTrue: [self removeActionsForEvent: anEventSelector] ifFalse: [self updateableActionMap at: anEventSelector asSymbol put: action]! ! !Object methodsFor: 'events-accessing' stamp: 'reThink 2/25/2001 08:50'! updateableActionMap ^EventManager updateableActionMapFor: self! ! !Object methodsFor: 'events-registering' stamp: 'reThink 2/18/2001 15:04'! when: anEventSelector evaluate: anAction | actions | actions := self actionSequenceForEvent: anEventSelector. (actions includes: anAction) ifTrue: [^ self]. self setActionSequence: (actions copyWith: anAction) forEvent: anEventSelector! ! !Object methodsFor: 'events-registering' stamp: 'rww 12/30/2002 10:37'! when: anEventSelector send: aMessageSelector to: anObject self when: anEventSelector evaluate: (WeakMessageSend receiver: anObject selector: aMessageSelector)! ! !Object methodsFor: 'events-registering' stamp: 'rww 12/30/2002 10:37'! when: anEventSelector send: aMessageSelector to: anObject withArguments: anArgArray self when: anEventSelector evaluate: (WeakMessageSend receiver: anObject selector: aMessageSelector arguments: anArgArray)! ! !Object methodsFor: 'events-registering' stamp: 'rww 12/30/2002 10:37'! when: anEventSelector send: aMessageSelector to: anObject with: anArg self when: anEventSelector evaluate: (WeakMessageSend receiver: anObject selector: aMessageSelector arguments: (Array with: anArg))! ! !Object methodsFor: 'events-removing' stamp: 'reThink 2/18/2001 15:33'! releaseActionMap EventManager releaseActionMapFor: self! ! !Object methodsFor: 'events-removing' stamp: 'reThink 2/18/2001 15:33'! removeActionsForEvent: anEventSelector | map | map := self actionMap. map removeKey: anEventSelector asSymbol ifAbsent: []. map isEmpty ifTrue: [self releaseActionMap]! ! !Object methodsFor: 'events-removing' stamp: 'nk 8/25/2003 21:46'! removeActionsSatisfying: aBlock self actionMap keys do: [:eachEventSelector | self removeActionsSatisfying: aBlock forEvent: eachEventSelector ]! ! !Object methodsFor: 'events-removing' stamp: 'reThink 2/18/2001 15:31'! removeActionsSatisfying: aOneArgBlock forEvent: anEventSelector self setActionSequence: ((self actionSequenceForEvent: anEventSelector) reject: [:anAction | aOneArgBlock value: anAction]) forEvent: anEventSelector! ! !Object methodsFor: 'events-removing' stamp: 'rw 7/29/2003 17:18'! removeActionsWithReceiver: anObject self actionMap copy keysDo: [:eachEventSelector | self removeActionsSatisfying: [:anAction | anAction receiver == anObject] forEvent: eachEventSelector ]! ! !Object methodsFor: 'events-removing' stamp: 'reThink 2/18/2001 15:36'! removeActionsWithReceiver: anObject forEvent: anEventSelector self removeActionsSatisfying: [:anAction | anAction receiver == anObject] forEvent: anEventSelector! ! !Object methodsFor: 'events-removing' stamp: 'reThink 2/18/2001 15:31'! removeAction: anAction forEvent: anEventSelector self removeActionsSatisfying: [:action | action = anAction] forEvent: anEventSelector! ! !Object methodsFor: 'events-triggering' stamp: 'reThink 2/18/2001 15:22'! triggerEvent: anEventSelector "Evaluate all actions registered for . Return the value of the last registered action." ^(self actionForEvent: anEventSelector) value! ! !Object methodsFor: 'events-triggering' stamp: 'reThink 2/18/2001 17:09'! triggerEvent: anEventSelector ifNotHandled: anExceptionBlock "Evaluate all actions registered for . Return the value of the last registered action." ^(self actionForEvent: anEventSelector ifAbsent: [^anExceptionBlock value]) value ! ! !Object methodsFor: 'events-triggering' stamp: 'reThink 2/18/2001 15:21'! triggerEvent: anEventSelector withArguments: anArgumentList ^(self actionForEvent: anEventSelector) valueWithArguments: anArgumentList! ! !Object methodsFor: 'events-triggering' stamp: 'reThink 2/18/2001 15:21'! triggerEvent: anEventSelector withArguments: anArgumentList ifNotHandled: anExceptionBlock ^(self actionForEvent: anEventSelector ifAbsent: [^anExceptionBlock value]) valueWithArguments: anArgumentList! ! !Object methodsFor: 'events-triggering' stamp: 'reThink 2/18/2001 14:59'! triggerEvent: anEventSelector with: anObject ^self triggerEvent: anEventSelector withArguments: (Array with: anObject)! ! !Object methodsFor: 'events-triggering' stamp: 'reThink 2/18/2001 14:59'! triggerEvent: anEventSelector with: anObject ifNotHandled: anExceptionBlock ^self triggerEvent: anEventSelector withArguments: (Array with: anObject) ifNotHandled: anExceptionBlock! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 00:42'! byteEncode:aStream self flattenOnStream:aStream. ! ! !Object methodsFor: 'filter streaming'! drawOnCanvas:aStream self flattenOnStream:aStream. ! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 01:31'! elementSeparator ^nil.! ! !Object methodsFor: 'filter streaming'! encodePostscriptOn:aStream self byteEncode:aStream. ! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 00:07'! flattenOnStream:aStream self writeOnFilterStream:aStream. ! ! !Object methodsFor: 'filter streaming' stamp: 'mpw 6/22/1930 22:56'! fullDrawPostscriptOn:aStream ^aStream fullDraw:self. ! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 01:51'! printOnStream:aStream self byteEncode:aStream. ! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 00:49'! putOn:aStream ^aStream nextPut:self. ! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 01:53'! storeOnStream:aStream self printOnStream:aStream. ! ! !Object methodsFor: 'filter streaming' stamp: 'MPW 1/1/1901 00:06'! writeOnFilterStream:aStream aStream writeObject:self. ! ! !Object methodsFor: 'finalization' stamp: 'ar 3/21/98 16:26'! actAsExecutor "Prepare the receiver to act as executor for any resources associated with it" self breakDependents! ! !Object methodsFor: 'finalization' stamp: 'ar 3/20/98 22:19'! executor "Return an object which can act as executor for finalization of the receiver" ^self shallowCopy actAsExecutor! ! !Object methodsFor: 'finalization' stamp: 'ar 5/19/2003 20:10'! finalizationRegistry "Answer the finalization registry associated with the receiver." ^WeakRegistry default! ! !Object methodsFor: 'finalization' stamp: 'ar 3/21/98 16:27'! finalize "Finalize the resource associated with the receiver. This message should only be sent during the finalization process. There is NO garantuee that the resource associated with the receiver hasn't been free'd before so take care that you don't run into trouble - this all may happen with interrupt priority."! ! !Object methodsFor: 'finalization' stamp: 'ar 3/21/98 18:38'! retryWithGC: execBlock until: testBlock "Retry execBlock as long as testBlock returns false. Do an incremental GC after the first try, a full GC after the second try." | blockValue | blockValue := execBlock value. (testBlock value: blockValue) ifTrue:[^blockValue]. Smalltalk garbageCollectMost. blockValue := execBlock value. (testBlock value: blockValue) ifTrue:[^blockValue]. Smalltalk garbageCollect. ^execBlock value.! ! !Object methodsFor: 'finalization' stamp: 'ar 5/19/2003 20:14'! toFinalizeSend: aSelector to: aFinalizer with: aResourceHandle "When I am finalized (e.g., garbage collected) close the associated resource handle by sending aSelector to the appropriate finalizer (the guy who knows how to get rid of the resource). WARNING: Neither the finalizer nor the resource handle are allowed to reference me. If they do, then I will NEVER be garbage collected. Since this cannot be validated here, it is up to the client to make sure this invariant is not broken." self == aFinalizer ifTrue:[self error: 'I cannot finalize myself']. self == aResourceHandle ifTrue:[self error: 'I cannot finalize myself']. ^self finalizationRegistry add: self executor: (ObjectFinalizer new receiver: aFinalizer selector: aSelector argument: aResourceHandle)! ! !Object methodsFor: 'flagging' stamp: 'sw 8/4/97 16:49'! isThisEverCalled ^ self isThisEverCalled: thisContext sender printString! ! !Object methodsFor: 'flagging'! isThisEverCalled: msg "Send this message, with some useful printable argument, from methods or branches of methods which you believe are never reached. 2/5/96 sw" self halt: 'This is indeed called: ', msg printString! ! !Object methodsFor: 'flagging' stamp: 'jm 3/18/98 17:23'! logEntry Transcript show: 'Entered ', thisContext sender printString; cr. ! ! !Object methodsFor: 'flagging' stamp: 'jm 3/18/98 17:23'! logExecution Transcript show: 'Executing ', thisContext sender printString; cr. ! ! !Object methodsFor: 'flagging' stamp: 'jm 3/18/98 17:22'! logExit Transcript show: 'Exited ', thisContext sender printString; cr. ! ! !Object methodsFor: 'graph model' stamp: 'dgd 9/18/2004 15:07'! addModelYellowButtonMenuItemsTo: aCustomMenu forMorph: aMorph hand: aHandMorph "The receiver serves as the model for aMorph; a menu is being constructed for the morph, and here the receiver is able to add its own items" Preferences cmdGesturesEnabled ifTrue: [ "build mode" aCustomMenu add: 'inspect model' translated target: self action: #inspect. ]. ^aCustomMenu ! ! !Object methodsFor: 'graph model' stamp: 'nk 1/23/2004 14:35'! hasModelYellowButtonMenuItems ^Preferences cmdGesturesEnabled! ! !Object methodsFor: 'inspecting' stamp: 'ar 9/27/2005 18:31'! basicInspect "Create and schedule an Inspector in which the user can examine the receiver's variables. This method should not be overriden." ^ToolSet basicInspect: self! ! !Object methodsFor: 'inspecting' stamp: 'md 1/18/2006 19:09'! inspect "Create and schedule an Inspector in which the user can examine the receiver's variables." ToolSet inspect: self! ! !Object methodsFor: 'inspecting' stamp: 'apb 7/14/2004 12:19'! inspectorClass "Answer the class of the inspector to be used on the receiver. Called by inspect; use basicInspect to get a normal (less useful) type of inspector." ^ Inspector! ! !Object methodsFor: 'locales' stamp: 'tak 8/4/2005 14:55'! localeChanged self shouldBeImplemented! ! !Object methodsFor: 'macpal' stamp: 'sw 5/7/1998 23:00'! codeStrippedOut: messageString "When a method is stripped out for external release, it is replaced by a method that calls this" self halt: 'Code stripped out -- ', messageString, '-- do not proceed.'! ! !Object methodsFor: 'macpal' stamp: 'sw 1/28/1999 17:31'! contentsChanged self changed: #contents! ! !Object methodsFor: 'macpal' stamp: 'ar 3/18/2001 00:03'! currentEvent "Answer the current Morphic event. This method never returns nil." ^ActiveEvent ifNil:[self currentHand lastEvent]! ! !Object methodsFor: 'macpal' stamp: 'nk 9/1/2004 10:41'! currentHand "Return a usable HandMorph -- the one associated with the object's current environment. This method will always return a hand, even if it has to conjure one up as a last resort. If a particular hand is actually handling events at the moment (such as a remote hand or a ghost hand), it will be returned." ^ActiveHand ifNil: [ self currentWorld primaryHand ]! ! !Object methodsFor: 'macpal' stamp: 'sw 5/17/2001 12:08'! currentVocabulary "Answer the currently-prevailing default vocabulary." ^ Smalltalk isMorphic ifTrue: [ActiveWorld currentVocabulary] ifFalse: [Vocabulary fullVocabulary]! ! !Object methodsFor: 'macpal' stamp: 'ar 3/18/2001 00:08'! currentWorld "Answer a morphic world that is the current UI focus. If in an embedded world, it's that world. If in a morphic project, it's that project's world. If in an mvc project, it is the topmost morphic-mvc-window's worldMorph. If in an mvc project that has no morphic-mvc-windows, then it's just some existing worldmorph instance. If in an mvc project in a Squeak that has NO WorldMorph instances, one is created. This method will never return nil, it will always return its best effort at returning a relevant world morph, but if need be -- if there are no worlds anywhere, it will create a new one." | aView aSubview | ActiveWorld ifNotNil:[^ActiveWorld]. World ifNotNil:[^World]. aView _ ScheduledControllers controllerSatisfying: [:ctrl | (aSubview _ ctrl view firstSubView) notNil and: [aSubview model isMorph and: [aSubview model isWorldMorph]]]. ^aView ifNotNil: [aSubview model] ifNil: [MVCWiWPasteUpMorph newWorldForProject: nil].! ! !Object methodsFor: 'macpal' stamp: 'jm 5/6/1998 22:35'! flash "Do nothing." ! ! !Object methodsFor: 'macpal' stamp: 'sw 6/16/1998 15:07'! instanceVariableValues "Answer a collection whose elements are the values of those instance variables of the receiver which were added by the receiver's class" | c | c _ OrderedCollection new. self class superclass instSize + 1 to: self class instSize do: [:i | c add: (self instVarAt: i)]. ^ c! ! !Object methodsFor: 'macpal' stamp: 'sw 3/20/2001 13:29'! isUniversalTiles "Return true if I (my world) uses universal tiles. This message can be called in places where the current World is not known, such as when writing out a project. For more information about the project-writing subtlety addressed by this protocol, kindly contact Ted Kaehler." ^ Preferences universalTiles! ! !Object methodsFor: 'macpal' stamp: 'sw 10/24/2000 07:04'! objectRepresented "most objects represent themselves; this provides a hook for aliases to grab on to" ^ self! ! !Object methodsFor: 'macpal' stamp: 'sw 5/22/2001 18:31'! refusesToAcceptCode "Answer whether the receiver is a code-bearing instrument which at the moment refuses to allow its contents to be submitted" ^ false ! ! !Object methodsFor: 'macpal' stamp: 'jm 2/24/1999 12:40'! scriptPerformer ^ self ! ! !Object methodsFor: 'macpal' stamp: 'sw 3/20/2001 13:40'! slotInfo "Answer a list of slot-information objects. Initally only provides useful info for players" ^ Dictionary new! ! !Object methodsFor: 'message handling' stamp: 'md 1/20/2006 16:28'! executeMethod: compiledMethod "Execute compiledMethod against the receiver with no args" "" "uncomment once prim 189 is in VM" ^ self withArgs: #() executeMethod: compiledMethod! ! !Object methodsFor: 'message handling' stamp: 'di 3/26/1999 07:52'! perform: aSymbol "Send the unary selector, aSymbol, to the receiver. Fail if the number of arguments expected by the selector is not zero. Primitive. Optional. See Object documentation whatIsAPrimitive." ^ self perform: aSymbol withArguments: (Array new: 0)! ! !Object methodsFor: 'message handling' stamp: 'st 11/5/2004 16:19'! perform: selector orSendTo: otherTarget "If I wish to intercept and handle selector myself, do it; else send it to otherTarget" ^ (self respondsTo: selector) ifTrue: [self perform: selector] ifFalse: [otherTarget perform: selector]! ! !Object methodsFor: 'message handling' stamp: 'di 3/26/1999 07:55'! perform: selector withArguments: argArray "Send the selector, aSymbol, to the receiver with arguments in argArray. Fail if the number of arguments expected by the selector does not match the size of argArray. Primitive. Optional. See Object documentation whatIsAPrimitive." ^ self perform: selector withArguments: argArray inSuperclass: self class! ! !Object methodsFor: 'message handling' stamp: 'ar 4/25/2005 13:35'! perform: selector withArguments: argArray inSuperclass: lookupClass "NOTE: This is just like perform:withArguments:, except that the message lookup process begins, not with the receivers's class, but with the supplied superclass instead. It will fail if lookupClass cannot be found among the receiver's superclasses. Primitive. Essential. See Object documentation whatIsAPrimitive." (selector isSymbol) ifFalse: [^ self error: 'selector argument must be a Symbol']. (selector numArgs = argArray size) ifFalse: [^ self error: 'incorrect number of arguments']. (self class == lookupClass or: [self class inheritsFrom: lookupClass]) ifFalse: [^ self error: 'lookupClass is not in my inheritance chain']. self primitiveFailed! ! !Object methodsFor: 'message handling' stamp: 'nk 4/11/2002 14:13'! perform: selector withEnoughArguments: anArray "Send the selector, aSymbol, to the receiver with arguments in argArray. Only use enough arguments for the arity of the selector; supply nils for missing ones." | numArgs args | numArgs _ selector numArgs. anArray size == numArgs ifTrue: [ ^self perform: selector withArguments: anArray asArray ]. args _ Array new: numArgs. args replaceFrom: 1 to: (anArray size min: args size) with: anArray startingAt: 1. ^ self perform: selector withArguments: args! ! !Object methodsFor: 'message handling' stamp: 'di 3/26/1999 07:52'! perform: aSymbol with: anObject "Send the selector, aSymbol, to the receiver with anObject as its argument. Fail if the number of arguments expected by the selector is not one. Primitive. Optional. See Object documentation whatIsAPrimitive." ^ self perform: aSymbol withArguments: (Array with: anObject)! ! !Object methodsFor: 'message handling' stamp: 'di 3/26/1999 07:52'! perform: aSymbol with: firstObject with: secondObject "Send the selector, aSymbol, to the receiver with the given arguments. Fail if the number of arguments expected by the selector is not two. Primitive. Optional. See Object documentation whatIsAPrimitive." ^ self perform: aSymbol withArguments: (Array with: firstObject with: secondObject)! ! !Object methodsFor: 'message handling' stamp: 'di 3/26/1999 07:51'! perform: aSymbol with: firstObject with: secondObject with: thirdObject "Send the selector, aSymbol, to the receiver with the given arguments. Fail if the number of arguments expected by the selector is not three. Primitive. Optional. See Object documentation whatIsAPrimitive." ^ self perform: aSymbol withArguments: (Array with: firstObject with: secondObject with: thirdObject)! ! !Object methodsFor: 'message handling' stamp: 'NS 1/28/2004 11:19'! withArgs: argArray executeMethod: compiledMethod "Execute compiledMethod against the receiver and args in argArray" | selector | selector _ Symbol new. self class addSelectorSilently: selector withMethod: compiledMethod. ^ [self perform: selector withArguments: argArray] ensure: [self class basicRemoveSelector: selector]! ! !Object methodsFor: 'message handling' stamp: 'md 1/20/2006 16:28'! with: arg1 executeMethod: compiledMethod "Execute compiledMethod against the receiver and arg1" "" "uncomment once prim 189 is in VM" ^ self withArgs: {arg1} executeMethod: compiledMethod! ! !Object methodsFor: 'message handling' stamp: 'md 1/20/2006 16:28'! with: arg1 with: arg2 executeMethod: compiledMethod "Execute compiledMethod against the receiver and arg1 & arg2" "" "uncomment once prim 189 is in VM" ^ self withArgs: {arg1. arg2} executeMethod: compiledMethod! ! !Object methodsFor: 'message handling' stamp: 'md 1/20/2006 16:28'! with: arg1 with: arg2 with: arg3 executeMethod: compiledMethod "Execute compiledMethod against the receiver and arg1, arg2, & arg3" "" "uncomment once prim 189 is in VM" ^ self withArgs: {arg1. arg2. arg3} executeMethod: compiledMethod! ! !Object methodsFor: 'message handling' stamp: 'md 1/20/2006 16:28'! with: arg1 with: arg2 with: arg3 with: arg4 executeMethod: compiledMethod "Execute compiledMethod against the receiver and arg1, arg2, arg3, & arg4" "" "uncomment once prim 189 is in VM" ^ self withArgs: {arg1. arg2. arg3. arg4} executeMethod: compiledMethod! ! !Object methodsFor: 'objects from disk' stamp: 'tk 4/8/1999 12:46'! comeFullyUpOnReload: smartRefStream "Normally this read-in object is exactly what we want to store. 7/26/96 tk" ^ self! ! !Object methodsFor: 'objects from disk' stamp: 'RAA 12/20/2000 16:51'! convertToCurrentVersion: varDict refStream: smartRefStrm "subclasses should implement if they wish to convert old instances to modern ones"! ! !Object methodsFor: 'objects from disk' stamp: 'tk 11/29/2004 15:04'! fixUponLoad: aProject seg: anImageSegment "change the object due to conventions that have changed on the project level. (sent to all objects in the incoming project). Specific classes should reimplement this."! ! !Object methodsFor: 'objects from disk' stamp: 'RAA 1/10/2001 14:02'! indexIfCompact ^0 "helps avoid a #respondsTo: in publishing"! ! !Object methodsFor: 'objects from disk' stamp: 'tk 2/24/1999 11:08'! objectForDataStream: refStrm "Return an object to store on an external data stream." ^ self! ! !Object methodsFor: 'objects from disk' stamp: 'tk 4/8/1999 12:05'! readDataFrom: aDataStream size: varsOnDisk "Fill in the fields of self based on the contents of aDataStream. Return self. Read in the instance-variables written by Object>>storeDataOn:. NOTE: This method must send beginReference: before reading any objects from aDataStream that might reference it. Allow aDataStream to have fewer inst vars. See SmartRefStream." | cntInstVars cntIndexedVars | cntInstVars _ self class instSize. self class isVariable ifTrue: [cntIndexedVars _ varsOnDisk - cntInstVars. cntIndexedVars < 0 ifTrue: [ self error: 'Class has changed too much. Define a convertxxx method']] ifFalse: [cntIndexedVars _ 0. cntInstVars _ varsOnDisk]. "OK if fewer than now" aDataStream beginReference: self. 1 to: cntInstVars do: [:i | self instVarAt: i put: aDataStream next]. 1 to: cntIndexedVars do: [:i | self basicAt: i put: aDataStream next]. "Total number read MUST be equal to varsOnDisk!!" ^ self "If we ever return something other than self, fix calls on (super readDataFrom: aDataStream size: anInteger)"! ! !Object methodsFor: 'objects from disk' stamp: 'CdG 10/17/2005 20:32'! saveOnFile "Ask the user for a filename and save myself on a SmartReferenceStream file. Writes out the version and class structure. The file is fileIn-able. Does not file out the class of the object. tk 6/26/97 13:48" | aFileName fileStream | aFileName := self class name asFileName. "do better?" aFileName := UIManager default request: 'File name?' translated initialAnswer: aFileName. aFileName size == 0 ifTrue: [^ Beeper beep]. fileStream := FileStream newFileNamed: aFileName asFileName. fileStream fileOutClass: nil andObject: self.! ! !Object methodsFor: 'objects from disk' stamp: 'tk 8/9/2001 15:40'! storeDataOn: aDataStream "Store myself on a DataStream. Answer self. This is a low-level DataStream/ReferenceStream method. See also objectToStoreOnDataStream. NOTE: This method must send 'aDataStream beginInstance:size:' and then (nextPut:/nextPutWeak:) its subobjects. readDataFrom:size: reads back what we write here." | cntInstVars cntIndexedVars | cntInstVars _ self class instSize. cntIndexedVars _ self basicSize. aDataStream beginInstance: self class size: cntInstVars + cntIndexedVars. 1 to: cntInstVars do: [:i | aDataStream nextPut: (self instVarAt: i)]. "Write fields of a variable length object. When writing to a dummy stream, don't bother to write the bytes" ((aDataStream byteStream class == DummyStream) and: [self class isBits]) ifFalse: [ 1 to: cntIndexedVars do: [:i | aDataStream nextPut: (self basicAt: i)]]. ! ! !Object methodsFor: 'parts bin' stamp: 'sw 10/24/2001 16:34'! descriptionForPartsBin "If the receiver is a member of a class that would like to be represented in a parts bin, answer the name by which it should be known, and a documentation string to be provided, for example, as balloon help. When the 'nativitySelector' is sent to the 'globalReceiver', it is expected that some kind of Morph will result. The parameters used in the implementation below are for documentation purposes only!!" ^ DescriptionForPartsBin formalName: 'PutFormalNameHere' categoryList: #(PutACategoryHere MaybePutAnotherCategoryHere) documentation: 'Put the balloon help here' globalReceiverSymbol: #PutAGlobalHere nativitySelector: #PutASelectorHere! ! !Object methodsFor: 'printing' stamp: 'di 6/20/97 08:57'! fullPrintString "Answer a String whose characters are a description of the receiver." ^ String streamContents: [:s | self printOn: s]! ! !Object methodsFor: 'printing'! isLiteral "Answer whether the receiver has a literal text form recognized by the compiler." ^false! ! !Object methodsFor: 'printing' stamp: 'sma 6/1/2000 09:28'! longPrintOn: aStream "Append to the argument, aStream, the names and values of all of the receiver's instance variables." self class allInstVarNames doWithIndex: [:title :index | aStream nextPutAll: title; nextPut: $:; space; tab; print: (self instVarAt: index); cr]! ! !Object methodsFor: 'printing' stamp: 'tk 10/19/2001 11:18'! longPrintOn: aStream limitedTo: sizeLimit indent: indent "Append to the argument, aStream, the names and values of all of the receiver's instance variables. Limit is the length limit for each inst var." self class allInstVarNames doWithIndex: [:title :index | indent timesRepeat: [aStream tab]. aStream nextPutAll: title; nextPut: $:; space; tab; nextPutAll: ((self instVarAt: index) printStringLimitedTo: (sizeLimit -3 -title size max: 1)); cr]! ! !Object methodsFor: 'printing' stamp: 'tk 10/16/2001 19:41'! longPrintString "Answer a String whose characters are a description of the receiver." | str | str _ String streamContents: [:aStream | self longPrintOn: aStream]. "Objects without inst vars should return something" ^ str isEmpty ifTrue: [self printString, String cr] ifFalse: [str]! ! !Object methodsFor: 'printing' stamp: 'BG 11/7/2004 13:39'! longPrintStringLimitedTo: aLimitValue "Answer a String whose characters are a description of the receiver." | str | str _ String streamContents: [:aStream | self longPrintOn: aStream limitedTo: aLimitValue indent: 0]. "Objects without inst vars should return something" ^ str isEmpty ifTrue: [self printString, String cr] ifFalse: [str]! ! !Object methodsFor: 'printing' stamp: 'sw 3/7/2001 13:14'! nominallyUnsent: aSelectorSymbol "From within the body of a method which is not formally sent within the system, but which you intend to have remain in the system (for potential manual invocation, or for documentation, or perhaps because it's sent by commented-out-code that you anticipate uncommenting out someday, send this message, with the selector itself as the argument. This will serve two purposes: (1) The method will not be returned by searches for unsent selectors (because it, in a manner of speaking, sends itself). (2) You can locate all such methods by browsing senders of #nominallyUnsent:" false ifTrue: [self flag: #nominallyUnsent:] "So that this method itself will appear to be sent" ! ! !Object methodsFor: 'printing' stamp: 'sma 6/1/2000 09:31'! printOn: aStream "Append to the argument, aStream, a sequence of characters that identifies the receiver." | title | title _ self class name. aStream nextPutAll: (title first isVowel ifTrue: ['an '] ifFalse: ['a ']); nextPutAll: title! ! !Object methodsFor: 'printing' stamp: 'sma 6/1/2000 09:22'! printString "Answer a String whose characters are a description of the receiver. If you want to print without a character limit, use fullPrintString." ^ self printStringLimitedTo: 50000! ! !Object methodsFor: 'printing' stamp: 'tk 5/7/1999 16:20'! printStringLimitedTo: limit "Answer a String whose characters are a description of the receiver. If you want to print without a character limit, use fullPrintString." | limitedString | limitedString _ String streamContents: [:s | self printOn: s] limitedTo: limit. limitedString size < limit ifTrue: [^ limitedString]. ^ limitedString , '...etc...'! ! !Object methodsFor: 'printing' stamp: 'MPW 1/1/1901 00:30'! propertyList "Answer a String whose characters are a property-list description of the receiver." ^ PropertyListEncoder process:self. ! ! !Object methodsFor: 'printing' stamp: 'sw 10/17/2000 11:16'! reportableSize "Answer a string that reports the size of the receiver -- useful for showing in a list view, for example" ^ (self basicSize + self class instSize) printString! ! !Object methodsFor: 'printing'! storeOn: aStream "Append to the argument aStream a sequence of characters that is an expression whose evaluation creates an object similar to the receiver." aStream nextPut: $(. self class isVariable ifTrue: [aStream nextPutAll: '(', self class name, ' basicNew: '; store: self basicSize; nextPutAll: ') '] ifFalse: [aStream nextPutAll: self class name, ' basicNew']. 1 to: self class instSize do: [:i | aStream nextPutAll: ' instVarAt: '; store: i; nextPutAll: ' put: '; store: (self instVarAt: i); nextPut: $;]. 1 to: self basicSize do: [:i | aStream nextPutAll: ' basicAt: '; store: i; nextPutAll: ' put: '; store: (self basicAt: i); nextPut: $;]. aStream nextPutAll: ' yourself)' ! ! !Object methodsFor: 'printing' stamp: 'di 6/20/97 09:12'! storeString "Answer a String representation of the receiver from which the receiver can be reconstructed." ^ String streamContents: [:s | self storeOn: s]! ! !Object methodsFor: 'printing' stamp: 'sw 5/2/1998 13:55'! stringForReadout ^ self stringRepresentation! ! !Object methodsFor: 'printing'! stringRepresentation "Answer a string that represents the receiver. For most objects this is simply its printString, but for strings themselves, it's themselves. 6/12/96 sw" ^ self printString ! ! !Object methodsFor: 'scripting' stamp: 'ar 3/17/2001 20:11'! adaptedToWorld: aWorld "If I refer to a world or a hand, return the corresponding items in the new world." ^self! ! !Object methodsFor: 'scripting' stamp: 'sw 3/10/2000 13:57'! defaultFloatPrecisionFor: aGetSelector "Answer a number indicating the default float precision to be used in a numeric readout for which the receiver is the model." ^ 1! ! !Object methodsFor: 'scripting' stamp: 'RAA 3/9/2001 17:08'! evaluateUnloggedForSelf: aCodeString ^Compiler evaluate: aCodeString for: self logged: false! ! !Object methodsFor: 'scripting' stamp: 'yo 12/25/2003 16:43'! methodInterfacesForCategory: aCategorySymbol inVocabulary: aVocabulary limitClass: aLimitClass "Return a list of methodInterfaces for the receiver in the given category, given a vocabulary. aCategorySymbol is the inherent category symbol, not necessarily the wording as expressed in the vocabulary." | categorySymbol | categorySymbol _ aCategorySymbol asSymbol. (categorySymbol == ScriptingSystem nameForInstanceVariablesCategory) ifTrue: [ "user-defined instance variables" ^ self methodInterfacesForInstanceVariablesCategoryIn: aVocabulary]. (categorySymbol == ScriptingSystem nameForScriptsCategory) ifTrue: [ "user-defined scripts" ^ self methodInterfacesForScriptsCategoryIn: aVocabulary]. "all others" ^ self usableMethodInterfacesIn: (aVocabulary methodInterfacesInCategory: categorySymbol forInstance: self ofClass: self class limitClass: aLimitClass) ! ! !Object methodsFor: 'scripting' stamp: 'sw 8/3/2001 13:54'! methodInterfacesForInstanceVariablesCategoryIn: aVocabulary "Return a collection of methodInterfaces for the instance-variables category. The vocabulary parameter, at present anyway, is not used. And for non-players, the method is at present vacuous in any case" ^ OrderedCollection new! ! !Object methodsFor: 'scripting' stamp: 'sw 8/3/2001 13:53'! methodInterfacesForScriptsCategoryIn: aVocabulary "Answer a list of method interfaces for the category #scripts, as seen in a viewer or other tool. The vocabulary argument is not presently used. Also, at present, only Players really do anyting interesting here." ^ OrderedCollection new! ! !Object methodsFor: 'scripting' stamp: 'RAA 2/16/2001 19:37'! selfWrittenAsIll ^self! ! !Object methodsFor: 'scripting' stamp: 'RAA 2/16/2001 19:38'! selfWrittenAsIm ^self! ! !Object methodsFor: 'scripting' stamp: 'RAA 2/16/2001 19:37'! selfWrittenAsMe ^self! ! !Object methodsFor: 'scripting' stamp: 'RAA 2/16/2001 19:37'! selfWrittenAsMy ^self! ! !Object methodsFor: 'scripting' stamp: 'RAA 2/16/2001 19:38'! selfWrittenAsThis ^self! ! !Object methodsFor: 'scripts-kernel' stamp: 'nk 10/14/2004 10:55'! universalTilesForGetterOf: aMethodInterface "Return universal tiles for a getter on the given method interface." | ms argTile argArray itsSelector | itsSelector _ aMethodInterface selector. argArray _ #(). "Four gratuituous special cases..." (itsSelector == #color:sees:) ifTrue: [argTile _ ScriptingSystem tileForArgType: #Color. argArray _ Array with: argTile colorSwatch color with: argTile colorSwatch color copy]. itsSelector == #seesColor: ifTrue: [argTile _ ScriptingSystem tileForArgType: #Color. argArray _ Array with: argTile colorSwatch color]. (#(touchesA: overlaps: overlapsAny:) includes: itsSelector) ifTrue: [argTile _ ScriptingSystem tileForArgType: #Player. argArray _ Array with: argTile actualObject]. ms _ MessageSend receiver: self selector: itsSelector arguments: argArray. ^ ms asTilesIn: self class globalNames: (self class officialClass ~~ CardPlayer) "For CardPlayers, use 'self'. For others, name it, and use its name."! ! !Object methodsFor: 'scripts-kernel' stamp: 'tk 9/28/2001 13:30'! universalTilesForInterface: aMethodInterface "Return universal tiles for the given method interface. Record who self is." | ms argTile itsSelector aType argList | itsSelector _ aMethodInterface selector. argList _ OrderedCollection new. aMethodInterface argumentVariables doWithIndex: [:anArgumentVariable :anIndex | argTile _ ScriptingSystem tileForArgType: (aType _ aMethodInterface typeForArgumentNumber: anIndex). argList add: (aType == #Player ifTrue: [argTile actualObject] ifFalse: [argTile literal]). "default value for each type"]. ms _ MessageSend receiver: self selector: itsSelector arguments: argList asArray. ^ ms asTilesIn: self class globalNames: (self class officialClass ~~ CardPlayer) "For CardPlayers, use 'self'. For others, name it, and use its name."! ! !Object methodsFor: 'self evaluating' stamp: 'sd 7/31/2005 21:47'! isSelfEvaluating ^ self isLiteral! ! !Object methodsFor: 'system primitives'! asOop "Primitive. Answer a SmallInteger whose value is half of the receiver's object pointer (interpreting object pointers as 16-bit signed quantities). Fail if the receiver is a SmallInteger. Essential. See Object documentation whatIsAPrimitive." self primitiveFailed! ! !Object methodsFor: 'system primitives' stamp: 'di 1/9/1999 15:19'! becomeForward: otherObject "Primitive. All variables in the entire system that used to point to the receiver now point to the argument. Fails if either argument is a SmallInteger." (Array with: self) elementsForwardIdentityTo: (Array with: otherObject)! ! !Object methodsFor: 'system primitives' stamp: 'zz 3/3/2004 23:53'! becomeForward: otherObject copyHash: copyHash "Primitive. All variables in the entire system that used to point to the receiver now point to the argument. If copyHash is true, the argument's identity hash bits will be set to those of the receiver. Fails if either argument is a SmallInteger." (Array with: self) elementsForwardIdentityTo: (Array with: otherObject) copyHash: copyHash! ! !Object methodsFor: 'system primitives' stamp: 'sw 10/16/2000 10:59'! className "Answer a string characterizing the receiver's class, for use in list views for example" ^ self class name asString! ! !Object methodsFor: 'system primitives' stamp: 'sw 10/16/2000 11:04'! creationStamp "Answer a string which reports the creation particulars of the receiver. Intended perhaps for list views, but this is presently a feature not easily accessible" ^ ''! ! !Object methodsFor: 'system primitives'! instVarAt: index "Primitive. Answer a fixed variable in an object. The numbering of the variables corresponds to the named instance variables. Fail if the index is not an Integer or is not the index of a fixed variable. Essential. See Object documentation whatIsAPrimitive." "Access beyond fixed variables." ^self basicAt: index - self class instSize ! ! !Object methodsFor: 'system primitives'! instVarAt: anInteger put: anObject "Primitive. Store a value into a fixed variable in the receiver. The numbering of the variables corresponds to the named instance variables. Fail if the index is not an Integer or is not the index of a fixed variable. Answer the value stored as the result. Using this message violates the principle that each object has sovereign control over the storing of values into its instance variables. Essential. See Object documentation whatIsAPrimitive." "Access beyond fixed fields" ^self basicAt: anInteger - self class instSize put: anObject! ! !Object methodsFor: 'system primitives' stamp: 'sw 10/16/2000 11:09'! instVarNamed: aString "Return the value of the instance variable in me with that name. Slow and unclean, but very useful. " ^ self instVarAt: (self class allInstVarNames indexOf: aString asString) ! ! !Object methodsFor: 'system primitives' stamp: 'sw 10/16/2000 11:10'! instVarNamed: aString put: aValue "Store into the value of the instance variable in me of that name. Slow and unclean, but very useful. " ^ self instVarAt: (self class allInstVarNames indexOf: aString asString) put: aValue ! ! !Object methodsFor: 'system primitives' stamp: 'sw 10/17/2000 11:12'! oopString "Answer a string that represents the oop of the receiver" ^ self asOop printString! ! !Object methodsFor: 'system primitives' stamp: 'ar 3/2/2001 01:34'! primitiveChangeClassTo: anObject "Primitive. Change the class of the receiver into the class of the argument given that the format of the receiver matches the format of the argument's class. Fail if receiver or argument are SmallIntegers, or the receiver is an instance of a compact class and the argument isn't, or when the argument's class is compact and the receiver isn't, or when the format of the receiver is different from the format of the argument's class, or when the arguments class is fixed and the receiver's size differs from the size that an instance of the argument's class should have. Note: The primitive will fail in most cases that you think might work. This is mostly because of a) the difference between compact and non-compact classes, and b) because of differences in the format. As an example, '(Array new: 3) primitiveChangeClassTo: Morph basicNew' would fail for three of the reasons mentioned above. Array is compact, Morph is not (failure #1). Array is variable and Morph is fixed (different format - failure #2). Morph is a fixed-field-only object and the array is too short (failure #3). The facility is really provided for certain, very specific applications (mostly related to classes changing shape) and not for casual use." self primitiveFailed! ! !Object methodsFor: 'system primitives' stamp: 'di 3/27/1999 12:21'! rootStubInImageSegment: imageSegment ^ ImageSegmentRootStub new xxSuperclass: nil format: nil segment: imageSegment! ! !Object methodsFor: 'system primitives'! someObject "Primitive. Answer the first object in the enumeration of all objects." self primitiveFailed.! ! !Object methodsFor: 'testing' stamp: 'sw 9/26/2001 11:58'! basicType "Answer a symbol representing the inherent type of the receiver" ^ #Object! ! !Object methodsFor: 'testing' stamp: 'sw 5/3/2001 16:19'! beViewed "Open up a viewer on the receiver. The Presenter is invited to decide just how to present this viewer" self uniqueNameForReference. "So the viewer will have something nice to refer to" self presenter viewObject: self! ! !Object methodsFor: 'testing' stamp: 'sw 10/16/2000 11:01'! costumes "Answer a list of costumes associated with the receiver. The appearance of this method in class Object serves only as a backstop, probably only transitionally" ^ nil! ! !Object methodsFor: 'testing' stamp: 'sw 1/12/98 18:09'! haltIfNil! ! !Object methodsFor: 'testing' stamp: 'md 1/20/2006 17:09'! hasLiteralSuchThat: testBlock "This is the end of the imbedded structure path so return false." ^ false! ! !Object methodsFor: 'testing' stamp: 'md 1/20/2006 17:10'! hasLiteralThorough: literal "Answer true if literal is identical to any literal in this array, even if imbedded in further structures. This is the end of the imbedded structure path so return false." ^ false! ! !Object methodsFor: 'testing' stamp: 'sw 1/30/2001 22:24'! haveFullProtocolBrowsed "Open up a Lexicon on the receiver" ^ self haveFullProtocolBrowsedShowingSelector: nil "(2@3) haveFullProtocolBrowsed" ! ! !Object methodsFor: 'testing' stamp: 'ar 9/27/2005 21:04'! haveFullProtocolBrowsedShowingSelector: aSelector "Open up a Lexicon on the receiver, having it open up showing aSelector, which may be nil" | aBrowser | aBrowser := (Smalltalk at: #InstanceBrowser ifAbsent:[^nil]) new useVocabulary: Vocabulary fullVocabulary. aBrowser openOnObject: self inWorld: ActiveWorld showingSelector: aSelector "(2@3) haveFullProtocolBrowsed"! ! !Object methodsFor: 'testing' stamp: 'md 7/30/2005 21:21'! isArray ^false! ! !Object methodsFor: 'testing' stamp: 'ar 7/9/1999 18:18'! isBehavior "Return true if the receiver is a behavior. Note: Do not override in any class except behavior." ^false! ! !Object methodsFor: 'testing' stamp: 'ajh 1/21/2003 13:15'! isBlock ^ false! ! !Object methodsFor: 'testing' stamp: 'md 11/21/2003 12:14'! isBlockClosure ^ false! ! !Object methodsFor: 'testing' stamp: 'yo 8/28/2002 13:41'! isCharacter ^ false. ! ! !Object methodsFor: 'testing' stamp: 'ar 8/17/1999 19:43'! isCollection "Return true if the receiver is some sort of Collection and responds to basic collection messages such as #size and #do:" ^false! ! !Object methodsFor: 'testing'! isColor "Answer true if receiver is a Color. False by default." ^ false ! ! !Object methodsFor: 'testing' stamp: 'nk 4/17/2004 19:43'! isColorForm ^false! ! !Object methodsFor: 'testing' stamp: 'md 11/21/2003 12:14'! isCompiledMethod ^ false! ! !Object methodsFor: 'testing' stamp: 'mk 10/27/2003 17:33'! isComplex "Answer true if receiver is a Complex number. False by default." ^ false ! ! !Object methodsFor: 'testing' stamp: 'md 8/11/2005 16:45'! isDictionary ^false! ! !Object methodsFor: 'testing' stamp: 'di 11/9/1998 09:38'! isFloat "Overridden to return true in Float, natch" ^ false! ! !Object methodsFor: 'testing' stamp: 'ar 10/30/2000 23:22'! isForm ^false! ! !Object methodsFor: 'testing' stamp: 'len 1/13/98 21:18'! isFraction "Answer true if the receiver is a Fraction." ^ false! ! !Object methodsFor: 'testing' stamp: 'rhi 8/14/2003 08:51'! isHeap ^ false! ! !Object methodsFor: 'testing'! isInteger "Overridden to return true in Integer." ^ false! ! !Object methodsFor: 'testing' stamp: 'rhi 8/12/2003 09:52'! isInterval ^ false! ! !Object methodsFor: 'testing' stamp: 'nk 4/25/2002 08:04'! isMessageSend ^false ! ! !Object methodsFor: 'testing' stamp: 'md 2/19/2006 11:24'! isMethodProperties ^false! ! !Object methodsFor: 'testing'! isMorph ^ false! ! !Object methodsFor: 'testing' stamp: 'ar 9/13/2000 15:37'! isMorphicEvent ^false! ! !Object methodsFor: 'testing' stamp: 'gm 2/22/2003 12:56'! isMorphicModel "Return true if the receiver is a morphic model" ^false ! ! !Object methodsFor: 'testing'! isNumber "Overridden to return true in Number, natch" ^ false! ! !Object methodsFor: 'testing' stamp: 'di 11/6/1998 08:04'! isPoint "Overridden to return true in Point." ^ false! ! !Object methodsFor: 'testing' stamp: 'ikp 9/26/97 14:45'! isPseudoContext ^false! ! !Object methodsFor: 'testing' stamp: 'md 10/2/2005 21:52'! isRectangle ^false! ! !Object methodsFor: 'testing' stamp: 'nk 6/14/2004 16:49'! isSketchMorph ^false! ! !Object methodsFor: 'testing' stamp: 'ar 12/23/1999 15:43'! isStream "Return true if the receiver responds to the stream protocol" ^false ! ! !Object methodsFor: 'testing' stamp: 'sma 6/15/2000 15:48'! isString "Overridden to return true in String, natch" ^ false! ! !Object methodsFor: 'testing' stamp: 'md 4/30/2003 15:30'! isSymbol ^ false ! ! !Object methodsFor: 'testing' stamp: 'jam 3/9/2003 15:10'! isSystemWindow "answer whatever the receiver is a SystemWindow" ^ false! ! !Object methodsFor: 'testing'! isText ^ false! ! !Object methodsFor: 'testing' stamp: 'pmm 7/6/2006 20:46'! isTrait "Return true if the receiver is a trait. Note: Do not override in any class except TraitBehavior." ^false! ! !Object methodsFor: 'testing' stamp: 'tk 10/21/97 12:45'! isTransparent ^ false! ! !Object methodsFor: 'testing' stamp: 'ar 8/14/2001 23:19'! isVariableBinding "Return true if I represent a literal variable binding" ^false ! ! !Object methodsFor: 'testing' stamp: 'ls 7/14/1998 21:45'! isWebBrowser "whether this object is a web browser. See class: Scamper" ^false! ! !Object methodsFor: 'testing' stamp: 'sw 10/27/2000 06:58'! knownName "If a formal name has been handed out for this object, answer it, else nil" ^ Preferences capitalizedReferences ifTrue: [References keyAtValue: self ifAbsent: [nil]] ifFalse: [nil]! ! !Object methodsFor: 'testing' stamp: 'sw 9/27/96'! name "Answer a name for the receiver. This is used generically in the title of certain inspectors, such as the referred-to inspector, and specificially by various subsystems. By default, we let the object just print itself out.. " ^ self printString! ! !Object methodsFor: 'testing' stamp: 'sw 11/19/2001 13:28'! nameForViewer "Answer a name to be shown in a Viewer that is viewing the receiver" | aName | (aName _ self uniqueNameForReferenceOrNil) ifNotNil: [^ aName]. (aName _ self knownName) ifNotNil: [^ aName]. ^ [(self asString copyWithout: Character cr) truncateTo: 27] ifError: [:msg :rcvr | ^ self class name printString]! ! !Object methodsFor: 'testing'! notNil "Coerces nil to false and everything else to true." ^true! ! !Object methodsFor: 'testing' stamp: 'tk 9/6/2001 19:15'! openInstanceBrowserWithTiles "Open up an instance browser on me with tiles as the code type, and with the search level as desired." | aBrowser | aBrowser _ InstanceBrowser new. aBrowser useVocabulary: Vocabulary fullVocabulary. aBrowser limitClass: self class. aBrowser contentsSymbol: #tiles. "preset it to make extra buttons (tile menus)" aBrowser openOnObject: self inWorld: ActiveWorld showingSelector: nil. aBrowser contentsSymbol: #source. aBrowser toggleShowingTiles. " (2@3) openInstanceBrowserWithTiles. WatchMorph new openInstanceBrowserWithTiles "! ! !Object methodsFor: 'testing' stamp: 'tk 7/28/2005 04:50'! renameInternal: newName "Change the internal name (because of a conflict) but leave the external name unchanged. Change Player class name, but do not change the names that appear in tiles. Any object that might be pointed to in the References dictionary might get this message sent to it upon reload" ^ nil "caller will renameTo:. new name may be different"! ! !Object methodsFor: 'testing' stamp: 'sw 2/27/2002 14:55'! renameTo: newName "If the receiver has an inherent idea about its own name, it should take action here. Any object that might be pointed to in the References dictionary might get this message sent to it upon reload"! ! !Object methodsFor: 'testing' stamp: 'sw 1/18/2001 13:43'! showDiffs "Answer whether the receiver, serving as the model of a text-bearing entity, is 'showing differences' -- if it is, the editor may wish to show special feedback" ^ false! ! !Object methodsFor: 'testing' stamp: 'sw 10/20/1999 14:52'! stepAt: millisecondClockValue in: aWindow ^ self stepIn: aWindow! ! !Object methodsFor: 'testing' stamp: 'sw 10/19/1999 08:16'! stepIn: aWindow ^ self step! ! !Object methodsFor: 'testing' stamp: 'sw 10/19/1999 08:21'! stepTime ^ 1000 "milliseconds -- default backstop for objects serving as models of system windows"! ! !Object methodsFor: 'testing' stamp: 'sw 10/19/1999 08:22'! stepTimeIn: aSystemWindow ^ 1000 "milliseconds -- default backstop for objects serving as models of system windows"! ! !Object methodsFor: 'testing' stamp: 'sw 5/3/2001 18:22'! vocabularyDemanded "Answer a vocabulary that the receiver insists be used when it is looked at in a Viewer. This allows specific classes to insist on specific custom vocabularies" ^ nil! ! !Object methodsFor: 'testing' stamp: 'sw 11/13/2001 07:26'! wantsDiffFeedback "Answer whether the receiver, serving as the model of a text-bearing entity, would like for 'diffs' green pane-border feedback to be shown" ^ false! ! !Object methodsFor: 'testing' stamp: 'di 1/8/1999 15:04'! wantsSteps "Overridden by morphic classes whose instances want to be stepped, or by model classes who want their morphic views to be stepped." ^ false! ! !Object methodsFor: 'testing' stamp: 'sw 10/19/1999 08:26'! wantsStepsIn: aSystemWindow ^ self wantsSteps! ! !Object methodsFor: 'thumbnail' stamp: 'dgd 9/25/2004 23:17'! iconOrThumbnailOfSize: aNumberOrPoint "Answer an appropiate form to represent the receiver" ^ nil! ! !Object methodsFor: 'translation support'! inline: inlineFlag "For translation only; noop when running in Smalltalk."! ! !Object methodsFor: 'translation support'! var: varSymbol declareC: declString "For translation only; noop when running in Smalltalk."! ! !Object methodsFor: 'undo' stamp: 'di 9/11/2000 20:32'! capturedState "May be overridden in subclasses." ^ self shallowCopy ! ! !Object methodsFor: 'undo' stamp: 'di 9/11/2000 20:29'! commandHistory "Return the command history for the receiver" | w | (w _ self currentWorld) ifNotNil: [^ w commandHistory]. ^ CommandHistory new. "won't really record anything but prevent breaking things"! ! !Object methodsFor: 'undo' stamp: 'di 12/12/2000 15:01'! purgeAllCommands "Purge all commands for this object" Preferences useUndo ifFalse: [^ self]. "get out quickly" self commandHistory purgeAllCommandsSuchThat: [:cmd | cmd undoTarget == self]. ! ! !Object methodsFor: 'undo' stamp: 'di 9/12/2000 08:15'! redoFromCapturedState: st "May be overridden in subclasses. See also capturedState" self undoFromCapturedState: st "Simple cases are symmetric" ! ! !Object methodsFor: 'undo' stamp: 'sw 11/16/2000 14:42'! refineRedoTarget: target selector: aSymbol arguments: arguments in: refineBlock "Any object can override this method to refine its redo specification" ^ refineBlock value: target value: aSymbol value: arguments! ! !Object methodsFor: 'undo' stamp: 'sw 11/16/2000 14:42'! refineUndoTarget: target selector: aSymbol arguments: arguments in: refineBlock "Any object can override this method to refine its undo specification" ^ refineBlock value: target value: aSymbol value: arguments! ! !Object methodsFor: 'undo' stamp: 'di 9/11/2000 20:30'! rememberCommand: aCommand "Remember the given command for undo" Preferences useUndo ifFalse: [^ self]. "get out quickly" ^ self commandHistory rememberCommand: aCommand! ! !Object methodsFor: 'undo' stamp: 'di 9/11/2000 20:30'! rememberUndoableAction: actionBlock named: caption | cmd result | cmd _ Command new cmdWording: caption. cmd undoTarget: self selector: #undoFromCapturedState: argument: self capturedState. result _ actionBlock value. cmd redoTarget: self selector: #redoFromCapturedState: argument: self capturedState. self rememberCommand: cmd. ^ result! ! !Object methodsFor: 'undo' stamp: 'di 9/11/2000 20:32'! undoFromCapturedState: st "May be overridden in subclasses. See also capturedState" self copyFrom: st ! ! !Object methodsFor: 'updating'! changed "Receiver changed in a general way; inform all the dependents by sending each dependent an update: message." self changed: self! ! !Object methodsFor: 'updating'! changed: aParameter "Receiver changed. The change is denoted by the argument aParameter. Usually the argument is a Symbol that is part of the dependent's change protocol. Inform all of the dependents." self dependents do: [:aDependent | aDependent update: aParameter]! ! !Object methodsFor: 'updating' stamp: 'nk 2/17/2004 11:12'! changed: anAspect with: anObject "Receiver changed. The change is denoted by the argument anAspect. Usually the argument is a Symbol that is part of the dependent's change protocol. Inform all of the dependents. Also pass anObject for additional information." self dependents do: [:aDependent | aDependent update: anAspect with: anObject]! ! !Object methodsFor: 'updating' stamp: 'sw 10/12/1999 18:15'! handledListVerification "When a self-updating PluggableListMorph lazily checks to see the state of affairs, it first gives its model an opportunity to handle the list verification itself (this is appropriate for some models, such as VersionsBrowser); if a list's model has indeed handled things itself, it returns true here" ^ false! ! !Object methodsFor: 'updating' stamp: 'sw 10/31/1999 00:15'! noteSelectionIndex: anInteger for: aSymbol "backstop"! ! !Object methodsFor: 'updating'! okToChange "Allows a controller to ask this of any model" ^ true! ! !Object methodsFor: 'updating' stamp: 'sw 10/19/1999 14:39'! updateListsAndCodeIn: aWindow self canDiscardEdits ifFalse: [^ self]. aWindow updatablePanes do: [:aPane | aPane verifyContents]! ! !Object methodsFor: 'updating' stamp: 'sma 2/29/2000 20:05'! update: aParameter "Receive a change notice from an object of whom the receiver is a dependent. The default behavior is to do nothing; a subclass might want to change itself in some way." ^ self! ! !Object methodsFor: 'updating' stamp: 'nk 2/17/2004 11:13'! update: anAspect with: anObject "Receive a change notice from an object of whom the receiver is a dependent. The default behavior is to call update:, which by default does nothing; a subclass might want to change itself in some way." ^ self update: anAspect! ! !Object methodsFor: 'updating' stamp: 'jm 8/20/1998 18:26'! windowIsClosing "This message is used to inform a models that its window is closing. Most models do nothing, but some, such as the Debugger, must do some cleanup. Note that this mechanism must be used with care by models that support multiple views, since one view may be closed while others left open." ! ! !Object methodsFor: 'user interface' stamp: 'sw 10/4/1999 08:13'! addModelItemsToWindowMenu: aMenu "aMenu is being constructed to be presented to the user in response to the user's pressing on the menu widget in the title bar of a morphic window. Here, the model is given the opportunity to add any model-specific items to the menu, whose default target is the SystemWindow itself."! ! !Object methodsFor: 'user interface' stamp: 'sw 10/5/1998 14:39'! addModelMenuItemsTo: aCustomMenu forMorph: aMorph hand: aHandMorph "The receiver serves as the model for aMorph; a menu is being constructed for the morph, and here the receiver is able to add its own items" ! ! !Object methodsFor: 'user interface' stamp: 'sma 11/12/2000 11:43'! asExplorerString ^ self printString! ! !Object methodsFor: 'user interface' stamp: 'sw 7/13/1999 15:53'! defaultBackgroundColor "Answer the color to be used as the base window color for a window whose model is an object of the receiver's class" ^ Preferences windowColorFor: self class name! ! !Object methodsFor: 'user interface'! defaultLabelForInspector "Answer the default label to be used for an Inspector window on the receiver." ^ self class name! ! !Object methodsFor: 'user interface' stamp: 'RAA 7/10/2000 08:11'! eToyStreamedRepresentationNotifying: aWidget | outData | [ outData _ SmartRefStream streamedRepresentationOf: self ] on: ProgressInitiationException do: [ :ex | ex sendNotificationsTo: [ :min :max :curr | aWidget ifNotNil: [aWidget flashIndicator: #working]. ]. ]. ^outData ! ! !Object methodsFor: 'user interface' stamp: 'ar 9/27/2005 20:29'! explore ^ToolSet explore: self! ! !Object methodsFor: 'user interface' stamp: 'sw 8/15/97 17:25'! fullScreenSize "Answer the size to which a window displaying the receiver should be set" | adj | adj _ (3 * Preferences scrollBarWidth) @ 0. ^ Rectangle origin: adj extent: (DisplayScreen actualScreenSize - adj)! ! !Object methodsFor: 'user interface' stamp: 'RAA 6/21/1999 11:27'! hasContentsInExplorer ^self basicSize > 0 or: [self class allInstVarNames isEmpty not] ! ! !Object methodsFor: 'user interface' stamp: 'rbb 3/1/2005 09:28'! inform: aString "Display a message for the user to read and then dismiss. 6/9/96 sw" aString isEmptyOrNil ifFalse: [UIManager default inform: aString]! ! !Object methodsFor: 'user interface'! initialExtent "Answer the desired extent for the receiver when a view on it is first opened on the screen. 5/22/96 sw: in the absence of any override, obtain from RealEstateAgent" ^ RealEstateAgent standardWindowExtent! ! !Object methodsFor: 'user interface' stamp: 'ar 9/27/2005 20:30'! inspectWithLabel: aLabel "Create and schedule an Inspector in which the user can examine the receiver's variables." ^ToolSet inspect: self label: aLabel! ! !Object methodsFor: 'user interface' stamp: 'sw 6/12/2001 11:09'! launchPartVia: aSelector "Obtain a morph by sending aSelector to self, and attach it to the morphic hand. This provides a general protocol for parts bins" | aMorph | aMorph _ self perform: aSelector. aMorph setProperty: #beFullyVisibleAfterDrop toValue: true. aMorph openInHand! ! !Object methodsFor: 'user interface' stamp: 'sw 6/17/2004 01:47'! launchPartVia: aSelector label: aString "Obtain a morph by sending aSelector to self, and attach it to the morphic hand. This provides a general protocol for parts bins" | aMorph | aMorph _ self perform: aSelector. aMorph setNameTo: (ActiveWorld unusedMorphNameLike: aString). aMorph setProperty: #beFullyVisibleAfterDrop toValue: true. aMorph openInHand! ! !Object methodsFor: 'user interface' stamp: 'sw 10/16/2000 11:11'! launchTileToRefer "Create a tile to reference the receiver, and attach it to the hand" self currentHand attachMorph: self tileToRefer! ! !Object methodsFor: 'user interface' stamp: 'di 5/11/1999 22:26'! modelSleep "A window with me as model is being exited or collapsed or closed. Default response is no-op" ! ! !Object methodsFor: 'user interface' stamp: 'di 5/11/1999 22:01'! modelWakeUp "A window with me as model is being entered or expanded. Default response is no-op" ! ! !Object methodsFor: 'user interface' stamp: 'sw 10/16/1999 22:45'! modelWakeUpIn: aWindow "A window with me as model is being entered or expanded. Default response is no-op" self modelWakeUp! ! !Object methodsFor: 'user interface' stamp: 'sw 3/8/1999 15:27'! mouseUpBalk: evt "A button I own got a mouseDown, but the user moved out before letting up. Certain kinds of objects (so-called 'radio buttons', for example, and other structures that must always have some selection, e.g. PaintBoxMorph) wish to take special action in this case; this default does nothing." ! ! !Object methodsFor: 'user interface' stamp: 'sw 8/22/97 13:14'! newTileMorphRepresentative ^ TileMorph new setLiteral: self! ! !Object methodsFor: 'user interface' stamp: 'jcg 11/1/2001 13:13'! notYetImplemented self inform: 'Not yet implemented (', thisContext sender printString, ')'! ! !Object methodsFor: 'user interface' stamp: 'di 6/10/1998 15:06'! windowReqNewLabel: labelString "My window's title has been edited. Return true if this is OK, and override for further behavior." ^ true! ! !Object methodsFor: 'viewer' stamp: 'sw 10/16/2000 10:35'! assureUniClass "If the receiver is not yet an instance of a uniclass, create a uniclass for it and make the receiver become an instance of that class." | anInstance | self belongsToUniClass ifTrue: [^ self]. anInstance _ self class instanceOfUniqueClass. self become: (self as: anInstance class). ^ anInstance! ! !Object methodsFor: 'viewer' stamp: 'sw 10/16/2000 10:41'! belongsToUniClass "Answer whether the receiver belongs to a uniclass. For the moment (this is not entirely satisfactory) this is precisely equated with the classname ending in a digit" ^ self class name endsWithDigit! ! !Object methodsFor: 'viewer' stamp: 'sw 12/11/2000 15:37'! browseOwnClassSubProtocol "Open up a ProtocolBrowser on the subprotocol of the receiver" ProtocolBrowser openSubProtocolForClass: self class ! ! !Object methodsFor: 'viewer' stamp: 'sw 8/4/2001 00:51'! categoriesForViewer: aViewer "Answer a list of categories to offer in the given viewer" ^ aViewer currentVocabulary categoryListForInstance: self ofClass: self class limitClass: aViewer limitClass! ! !Object methodsFor: 'viewer' stamp: 'sw 8/3/2001 22:08'! categoriesForVocabulary: aVocabulary limitClass: aLimitClass "Answer a list of categories of methods for the receiver when using the given vocabulary, given that one considers only methods that are implemented not further away than aLimitClass" ^ aVocabulary categoryListForInstance: self ofClass: self class limitClass: aLimitClass! ! !Object methodsFor: 'viewer' stamp: 'sw 10/25/2000 07:20'! chooseNewNameForReference "Offer an opportunity for the receiver, presumed already to be known in the References registry, to be renamed" | nameSym current newName | current _ References keyAtValue: self ifAbsent: [^ self error: 'not found in References']. newName _ FillInTheBlank request: 'Please enter new name' initialAnswer: current. "Want to user some better way of determining the validity of the chosen identifier, and also want to give more precise diagnostic if the string the user types in is not acceptable. Work to be done here." newName isEmpty ifTrue: [^ nil]. ((Scanner isLiteralSymbol: newName) and: [(newName includes: $:) not]) ifTrue: [nameSym _ newName capitalized asSymbol. (((References includesKey: nameSym) not and: [(Smalltalk includesKey: nameSym) not]) and: [(ScriptingSystem allKnownClassVariableNames includes: nameSym) not]) ifTrue: [(References associationAt: current) key: nameSym. References rehash. ^ nameSym]]. self inform: 'Sorry, that name is not available.'. ^ nil! ! !Object methodsFor: 'viewer' stamp: 'sw 8/3/2001 21:22'! defaultLimitClassForVocabulary: aVocabulary "Answer the class to use, by default, as the limit class on a protocol browser or viewer opened up on the receiver, within the purview of the Vocabulary provided" ^ (aVocabulary isKindOf: FullVocabulary) ifTrue: [self class superclass == Object ifTrue: [self class] ifFalse: [self class superclass]] ifFalse: [ProtoObject]! ! !Object methodsFor: 'viewer' stamp: 'sw 2/14/2000 14:24'! defaultNameStemForInstances "Answer a basis for names of default instances of the receiver. The default is to let the class specify, but certain instances will want to override. (PasteUpMorphs serving as Worlds come to mind" ^ self class defaultNameStemForInstances! ! !Object methodsFor: 'viewer' stamp: 'sw 5/22/2001 16:53'! elementTypeFor: aStringOrSymbol vocabulary: aVocabulary "Answer a symbol characterizing what kind of element aStringOrSymbol represents. Realistically, at present, this always just returns #systemScript; a prototyped but not-incorporated architecture supported use of a leading colon to characterize an inst var of a system class, and for the moment we still see its remnant here." self flag: #deferred. "a loose end in the non-player case" ^ #systemScript! ! !Object methodsFor: 'viewer' stamp: 'sw 5/4/2001 07:04'! externalName "Answer an external name by which the receiver is known. Generic implementation here is a transitional backstop. probably" ^ self nameForViewer! ! !Object methodsFor: 'viewer' stamp: 'sw 5/4/2001 07:06'! graphicForViewerTab "When a Viewer is open on the receiver, its tab needs some graphic to show to the user. Answer a form or a morph to serve that purpose. A generic image is used for arbitrary objects, but note my reimplementors" ^ ScriptingSystem formAtKey: 'Image'! ! !Object methodsFor: 'viewer' stamp: 'sw 5/4/2001 07:08'! hasUserDefinedSlots "Answer whether the receiver has any user-defined slots, in the omniuser sense of the term. This is needed to allow Viewers to look at any object, not just at Players." ^ false! ! !Object methodsFor: 'viewer' stamp: 'sw 8/22/2002 14:07'! infoFor: anElement inViewer: aViewer "The user made a gesture asking for info/menu relating to me. Some of the messages dispatched here are not yet available in this image" | aMenu elementType | elementType _ self elementTypeFor: anElement vocabulary: aViewer currentVocabulary. ((elementType = #systemSlot) | (elementType == #userSlot)) ifTrue: [^ self slotInfoButtonHitFor: anElement inViewer: aViewer]. self flag: #deferred. "Use a traditional MenuMorph, and reinstate the pacify thing" aMenu _ MenuMorph new defaultTarget: aViewer. #( ('implementors' browseImplementorsOf:) ('senders' browseSendersOf:) ('versions' browseVersionsOf:) - ('browse full' browseMethodFull:) ('inheritance' browseMethodInheritance:) - ('about this method' aboutMethod:)) do: [:pair | pair = '-' ifTrue: [aMenu addLine] ifFalse: [aMenu add: pair first target: aViewer selector: pair second argument: anElement]]. aMenu addLine. aMenu defaultTarget: self. #( ('destroy script' removeScript:) ('rename script' renameScript:) ('pacify script' pacifyScript:)) do: [:pair | aMenu add: pair first target: self selector: pair second argument: anElement]. aMenu addLine. aMenu add: 'show categories....' target: aViewer selector: #showCategoriesFor: argument: anElement. aMenu items size == 0 ifTrue: "won't happen at the moment a/c the above" [aMenu add: 'ok' action: nil]. "in case it was a slot -- weird, transitional" aMenu addTitle: anElement asString, ' (', elementType, ')'. aMenu popUpInWorld: self currentWorld. ! ! !Object methodsFor: 'viewer' stamp: 'sw 9/26/2001 11:58'! initialTypeForSlotNamed: aName "Answer the initial type to be ascribed to the given instance variable" ^ #Object! ! !Object methodsFor: 'viewer' stamp: 'ar 5/26/2001 16:13'! isPlayerLike "Return true if the receiver is a player-like object" ^false! ! !Object methodsFor: 'viewer' stamp: 'nk 9/11/2004 16:53'! methodInterfacesInPresentationOrderFrom: interfaceList forCategory: aCategory "Answer the interface list sorted in desired presentation order, using a static master-ordering list, q.v. The category parameter allows an escape in case one wants to apply different order strategies in different categories, but for now a single master-priority-ordering is used -- see the comment in method EToyVocabulary.masterOrderingOfPhraseSymbols" | masterOrder ordered unordered index | masterOrder := Vocabulary eToyVocabulary masterOrderingOfPhraseSymbols. ordered := SortedCollection sortBlock: [:a :b | a key < b key]. unordered := SortedCollection sortBlock: [:a :b | a wording < b wording]. interfaceList do: [:interface | index := masterOrder indexOf: interface elementSymbol. index isZero ifTrue: [unordered add: interface] ifFalse: [ordered add: index -> interface]]. ^ Array streamContents: [:stream | ordered do: [:assoc | stream nextPut: assoc value]. stream nextPutAll: unordered]! ! !Object methodsFor: 'viewer' stamp: 'sw 10/24/2000 11:36'! newScriptorAround: aPhraseTileMorph "Sprout a scriptor around aPhraseTileMorph, thus making a new script. This is where generalized scriptors will be threaded in" ^ nil! ! !Object methodsFor: 'viewer' stamp: 'sw 10/25/2000 17:42'! offerViewerMenuForEvt: anEvent morph: aMorph "Offer the viewer's primary menu to the user. aMorph is some morph within the viewer itself, the one within which a mousedown triggered the need for this menu, and it is used only to retrieve the Viewer itself" self offerViewerMenuFor: (aMorph ownerThatIsA: StandardViewer) event: anEvent! ! !Object methodsFor: 'viewer' stamp: 'sw 8/11/2002 02:03'! offerViewerMenuFor: aViewer event: evt "Offer the primary Viewer menu to the user. Copied up from Player code, but most of the functions suggested here don't work for non-Player objects, many aren't even defined, some relate to exploratory sw work not yet reflected in the current corpus. We are early in the life cycle of this method..." | aMenu | aMenu _ MenuMorph new defaultTarget: self. aMenu addStayUpItem. aMenu title: '**CAUTION -- UNDER CONSTRUCTION!!** Many things may not work!! ', self nameForViewer. (aViewer affordsUniclass and: [self belongsToUniClass not]) ifTrue: [aMenu add: 'give me a Uniclass' action: #assureUniClass. aMenu addLine]. aMenu add: 'choose vocabulary...' target: aViewer action: #chooseVocabulary. aMenu add: 'choose limit class...' target: aViewer action: #chooseLimitClass. aMenu add: 'add search pane' target: aViewer action: #addSearchPane. aMenu balloonTextForLastItem: 'Specify which class should be the most generic one to have its methods shown in this Viewer'. aMenu addLine. self belongsToUniClass ifTrue: [aMenu add: 'add a new instance variable' target: self selector: #addInstanceVariableIn: argument: aViewer. aMenu add: 'add a new script' target: aViewer selector: #newPermanentScriptIn: argument: aViewer. aMenu addLine. aMenu add: 'make my class be first-class' target: self selector: #makeFirstClassClassIn: argument: aViewer. aMenu add: 'move my changes up to my superclass' target: self action: #promoteChangesToSuperclass. aMenu addLine]. aMenu add: 'tear off a tile' target: self selector: #launchTileToRefer. aMenu addLine. aMenu add: 'inspect me' target: self selector: #inspect. aMenu add: 'inspect my class' target: self class action: #inspect. aMenu addLine. aMenu add: 'browse vocabulary' action: #haveFullProtocolBrowsed. aMenu add: 'inspect this Viewer' target: aViewer action: #inspect. aMenu popUpEvent: evt in: aViewer currentWorld " aMenu add: 'references to me' target: aViewer action: #browseReferencesToObject. aMenu add: 'toggle scratch pane' target: aViewer selector: #toggleScratchPane. aMenu add: 'make a nascent script for me' target: aViewer selector: #makeNascentScript. aMenu add: 'rename me' target: aViewer selector: #chooseNewNameForReference. aMenu add: 'browse full' action: #browseOwnClassFull. aMenu add: 'browse hierarchy' action: #browseOwnClassHierarchy. aMenu add: 'set user level...' target: aViewer action: #setUserLevel. aMenu add: 'browse sub-protocol' action: #browseOwnClassSubProtocol. aMenu addLine. "! ! !Object methodsFor: 'viewer' stamp: 'sw 1/22/2001 15:20'! renameScript: oldSelector "prompt the user for a new selector and apply it. Presently only works for players" self notYetImplemented! ! !Object methodsFor: 'viewer' stamp: 'sw 8/10/2004 11:53'! tilePhrasesForCategory: aCategorySymbol inViewer: aViewer "Return a collection of phrases for the category." | interfaces | interfaces _ self methodInterfacesForCategory: aCategorySymbol inVocabulary: aViewer currentVocabulary limitClass: aViewer limitClass. interfaces _ self methodInterfacesInPresentationOrderFrom: interfaces forCategory: aCategorySymbol. ^ self tilePhrasesForMethodInterfaces: interfaces inViewer: aViewer! ! !Object methodsFor: 'viewer' stamp: 'sw 8/10/2004 11:53'! tilePhrasesForMethodInterfaces: methodInterfaceList inViewer: aViewer "Return a collection of ViewerLine objects corresponding to the method-interface list provided. The resulting list will be in the same order as the incoming list, but may be smaller if the viewer's vocbulary suppresses some of the methods, or if, in classic tiles mode, the selector requires more arguments than can be handled." | toSuppress interfaces resultType itsSelector | toSuppress _ aViewer currentVocabulary phraseSymbolsToSuppress. interfaces _ methodInterfaceList reject: [:int | toSuppress includes: int selector]. Preferences universalTiles ifFalse: "Classic tiles have their limitations..." [interfaces _ interfaces select: [:int | itsSelector _ int selector. itsSelector numArgs < 2 or: "The lone two-arg loophole in classic tiles" [#(color:sees:) includes: itsSelector]]]. ^ interfaces collect: [:aMethodInterface | ((resultType _ aMethodInterface resultType) notNil and: [resultType ~~ #unknown]) ifTrue: [aViewer phraseForVariableFrom: aMethodInterface] ifFalse: [aViewer phraseForCommandFrom: aMethodInterface]]! ! !Object methodsFor: 'viewer' stamp: 'sw 8/10/2004 12:23'! tilePhrasesForSelectorList: aList inViewer: aViewer "Particular to the search facility in viewers. Answer a list, in appropriate order, of ViewerLine objects to put into the viewer." | interfaces aVocab | aVocab _ aViewer currentVocabulary. interfaces _ self methodInterfacesInPresentationOrderFrom: (aList collect: [:aSel | aVocab methodInterfaceForSelector: aSel class: self class]) forCategory: #search. ^ self tilePhrasesForMethodInterfaces: interfaces inViewer: aViewer! ! !Object methodsFor: 'viewer' stamp: 'sw 5/4/2001 04:51'! tileToRefer "Answer a reference tile that comprises an alias to me" ^ TileMorph new setToReferTo: self! ! !Object methodsFor: 'viewer' stamp: 'sd 3/30/2005 22:04'! uniqueInstanceVariableNameLike: aString excluding: takenNames "Answer a nice instance-variable name to be added to the receiver which resembles aString, making sure it does not coincide with any element in takenNames" | okBase uniqueName usedNames | usedNames _ self class allInstVarNamesEverywhere. usedNames removeAllFoundIn: self class instVarNames. usedNames addAll: takenNames. okBase _ Scanner wellFormedInstanceVariableNameFrom: aString. uniqueName _ Utilities keyLike: okBase satisfying: [:aKey | (usedNames includes: aKey) not]. ^ uniqueName! ! !Object methodsFor: 'viewer' stamp: 'sw 11/21/2001 15:16'! uniqueNameForReference "Answer a nice name by which the receiver can be referred to by other objects. At present this uses a global References dictionary to hold the database of references, but in due course this will need to acquire some locality" | aName nameSym stem knownClassVars | (aName _ self uniqueNameForReferenceOrNil) ifNotNil: [^ aName]. (stem _ self knownName) ifNil: [stem _ self defaultNameStemForInstances asString]. stem _ stem select: [:ch | ch isLetter or: [ch isDigit]]. stem size == 0 ifTrue: [stem _ 'A']. stem first isLetter ifFalse: [stem _ 'A', stem]. stem _ stem capitalized. knownClassVars _ ScriptingSystem allKnownClassVariableNames. aName _ Utilities keyLike: stem satisfying: [:jinaLake | nameSym _ jinaLake asSymbol. ((References includesKey: nameSym) not and: [(Smalltalk includesKey: nameSym) not]) and: [(knownClassVars includes: nameSym) not]]. References at: (aName _ aName asSymbol) put: self. ^ aName! ! !Object methodsFor: 'viewer' stamp: 'md 1/17/2006 17:58'! uniqueNameForReferenceFrom: proposedName "Answer a satisfactory symbol, similar to the proposedName but obeying the rules, to represent the receiver" | aName nameSym stem okay | proposedName = self uniqueNameForReferenceOrNil ifTrue: [^ proposedName]. "No change" stem _ proposedName select: [:ch | ch isLetter or: [ch isDigit]]. stem size == 0 ifTrue: [stem _ 'A']. stem first isLetter ifFalse: [stem _ 'A', stem]. stem _ stem capitalized. aName _ Utilities keyLike: stem satisfying: [:jinaLake | nameSym _ jinaLake asSymbol. okay _ true. (self class bindingOf: nameSym) ifNotNil: [okay _ false "don't use it"]. okay]. ^ aName asSymbol! ! !Object methodsFor: 'viewer' stamp: 'sw 3/15/2004 23:01'! uniqueNameForReferenceOrNil "If the receiver has a unique name for reference, return it here, else return nil" ^ References keyAtValue: self ifAbsent: [nil]! ! !Object methodsFor: 'viewer' stamp: 'ar 5/16/2001 01:40'! updateThresholdForGraphicInViewerTab "When a Viewer is open on the receiver, its tab needs some graphic to show to the user. Computing this graphic can take quite some time so we want to make the update frequency depending on how long it takes to compute the thumbnail. The threshold returned by this method defines that the viewer will update at most every 'threshold * timeItTakesToDraw' milliseconds. Thus, if the time for computing the receiver's thumbnail is 200 msecs and the the threshold is 10, the viewer will update at most every two seconds." ^20 "seems to be a pretty good general choice"! ! !Object methodsFor: 'viewer' stamp: 'sw 3/9/2001 13:48'! usableMethodInterfacesIn: aListOfMethodInterfaces "Filter aList, returning a subset list of apt phrases" ^ aListOfMethodInterfaces ! ! !Object methodsFor: 'world hacking' stamp: 'ar 3/17/2001 23:45'! couldOpenInMorphic "is there an obvious morphic world in which to open a new morph?" ^World notNil or: [ActiveWorld notNil]! ! !Object methodsFor: 'private'! errorImproperStore "Create an error notification that an improper store was attempted." self error: 'Improper store into indexable object'! ! !Object methodsFor: 'private'! errorNonIntegerIndex "Create an error notification that an improper object was used as an index." self error: 'only integers should be used as indices'! ! !Object methodsFor: 'private' stamp: 'yo 6/29/2004 11:37'! errorNotIndexable "Create an error notification that the receiver is not indexable." self error: ('Instances of {1} are not indexable' translated format: {self class name})! ! !Object methodsFor: 'private'! errorSubscriptBounds: index "Create an error notification that an improper integer was used as an index." self error: 'subscript is out of bounds: ' , index printString! ! !Object methodsFor: 'private' stamp: 'ar 2/6/2004 14:47'! primitiveError: aString "This method is called when the error handling results in a recursion in calling on error: or halt or halt:." | context | (String streamContents: [:s | s nextPutAll: '***System error handling failed***'. s cr; nextPutAll: aString. context _ thisContext sender sender. 20 timesRepeat: [context == nil ifFalse: [s cr; print: (context _ context sender)]]. s cr; nextPutAll: '-------------------------------'. s cr; nextPutAll: 'Type CR to enter an emergency evaluator.'. s cr; nextPutAll: 'Type any other character to restart.']) displayAt: 0 @ 0. [Sensor keyboardPressed] whileFalse. Sensor keyboard = Character cr ifTrue: [Transcripter emergencyEvaluator]. Smalltalk isMorphic ifTrue: [World install "init hands and redisplay"] ifFalse: [ScheduledControllers searchForActiveController]! ! !Object methodsFor: 'private'! species "Answer the preferred class for reconstructing the receiver. For example, collections create new collections whenever enumeration messages such as collect: or select: are invoked. The new kind of collection is determined by the species of the original collection. Species and class are not always the same. For example, the species of Interval is Array." ^self class! ! !Object methodsFor: 'private'! storeAt: offset inTempFrame: aContext "This message had to get sent to an expression already on the stack as a Block argument being accessed by the debugger. Just re-route it to the temp frame." ^ aContext tempAt: offset put: self! ! "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "! Object class instanceVariableNames: ''! !Object class methodsFor: '*Pinesoft-Widgets' stamp: 'gvc 4/17/2007 17:40'! taskbarIcon "Answer the icon for an instance of the receiver in a task bar or nil for the default." ^nil! ! !Object class methodsFor: '*magritte-model-accessing' stamp: 'lr 3/27/2006 15:47'! description ^ MADescriptionBuilder for: self! ! !Object class methodsFor: 'class initialization' stamp: 'ar 2/11/2001 02:00'! flushDependents DependentsFields keysAndValuesDo:[:key :dep| key ifNotNil:[key removeDependent: nil]. ]. DependentsFields finalizeValues.! ! !Object class methodsFor: 'class initialization' stamp: 'rw 2/10/2002 13:09'! flushEvents "Object flushEvents" EventManager flushEvents. ! ! !Object class methodsFor: 'class initialization' stamp: 'rww 10/2/2001 07:35'! initialize "Object initialize" DependentsFields ifNil:[self initializeDependentsFields].! ! !Object class methodsFor: 'class initialization' stamp: 'ar 2/11/2001 01:41'! initializeDependentsFields "Object initialize" DependentsFields _ WeakIdentityKeyDictionary new. ! ! !Object class methodsFor: 'class initialization' stamp: 'ar 2/11/2001 01:45'! reInitializeDependentsFields "Object reInitializeDependentsFields" | oldFields | oldFields _ DependentsFields. DependentsFields _ WeakIdentityKeyDictionary new. oldFields keysAndValuesDo:[:obj :deps| deps do:[:d| obj addDependent: d]]. ! ! !Object class methodsFor: 'documentation'! howToModifyPrimitives "You are allowed to write methods which specify primitives, but please use caution. If you make a subclass of a class which contains a primitive method, the subclass inherits the primitive. The message which is implemented primitively may be overridden in the subclass (E.g., see at:put: in String's subclass Symbol). The primitive behavior can be invoked using super (see Symbol string:). A class which attempts to mimic the behavior of another class without being its subclass may or may not be able to use the primitives of the original class. In general, if the instance variables read or written by a primitive have the same meanings and are in the same fields in both classes, the primitive will work. For certain frequently used 'special selectors', the compiler emits a send-special-selector bytecode instead of a send-message bytecode. Special selectors were created because they offer two advantages. Code which sends special selectors compiles into fewer bytes than normal. For some pairs of receiver classes and special selectors, the interpreter jumps directly to a primitive routine without looking up the method in the class. This is much faster than a normal message lookup. A selector which is a special selector solely in order to save space has a normal behavior. Methods whose selectors are special in order to gain speed contain the comment, 'No Lookup'. When the interpreter encounters a send-special-selector bytecode, it checks the class of the receiver and the selector. If the class-selector pair is a no-lookup pair, then the interpreter swiftly jumps to the routine which implements the corresponding primitive. (A special selector whose receiver is not of the right class to make a no-lookup pair, is looked up normally). The pairs are listed below. No-lookup methods contain a primitive number specification, , which is redundant. Since the method is not normally looked up, deleting the primitive number specification cannot prevent this primitive from running. If a no-lookup primitive fails, the method is looked up normally, and the expressions in it are executed. No Lookup pairs of (class, selector) SmallInteger with any of + - * / \\ bitOr: bitShift: bitAnd: // SmallInteger with any of = ~= > < >= <= Any class with == Any class with @ Point with either of x y ContextPart with blockCopy: BlockContext with either of value value: " self error: 'comment only'! ! !Object class methodsFor: 'documentation'! whatIsAPrimitive "Some messages in the system are responded to primitively. A primitive response is performed directly by the interpreter rather than by evaluating expressions in a method. The methods for these messages indicate the presence of a primitive response by including before the first expression in the method. Primitives exist for several reasons. Certain basic or 'primitive' operations cannot be performed in any other way. Smalltalk without primitives can move values from one variable to another, but cannot add two SmallIntegers together. Many methods for arithmetic and comparison between numbers are primitives. Some primitives allow Smalltalk to communicate with I/O devices such as the disk, the display, and the keyboard. Some primitives exist only to make the system run faster; each does the same thing as a certain Smalltalk method, and its implementation as a primitive is optional. When the Smalltalk interpreter begins to execute a method which specifies a primitive response, it tries to perform the primitive action and to return a result. If the routine in the interpreter for this primitive is successful, it will return a value and the expressions in the method will not be evaluated. If the primitive routine is not successful, the primitive 'fails', and the Smalltalk expressions in the method are executed instead. These expressions are evaluated as though the primitive routine had not been called. The Smalltalk code that is evaluated when a primitive fails usually anticipates why that primitive might fail. If the primitive is optional, the expressions in the method do exactly what the primitive would have done (See Number @). If the primitive only works on certain classes of arguments, the Smalltalk code tries to coerce the argument or appeals to a superclass to find a more general way of doing the operation (see SmallInteger +). If the primitive is never supposed to fail, the expressions signal an error (see SmallInteger asFloat). Each method that specifies a primitive has a comment in it. If the primitive is optional, the comment will say 'Optional'. An optional primitive that is not implemented always fails, and the Smalltalk expressions do the work instead. If a primitive is not optional, the comment will say, 'Essential'. Some methods will have the comment, 'No Lookup'. See Object howToModifyPrimitives for an explanation of special selectors which are not looked up. For the primitives for +, -, *, and bitShift: in SmallInteger, and truncated in Float, the primitive constructs and returns a 16-bit LargePositiveInteger when the result warrants it. Returning 16-bit LargePositiveIntegers from these primitives instead of failing is optional in the same sense that the LargePositiveInteger arithmetic primitives are optional. The comments in the SmallInteger primitives say, 'Fails if result is not a SmallInteger', even though the implementor has the option to construct a LargePositiveInteger. For further information on primitives, see the 'Primitive Methods' part of the chapter on the formal specification of the interpreter in the Smalltalk book." self error: 'comment only'! ! !Object class methodsFor: 'file list services' stamp: 'nk 6/12/2004 11:41'! fileReaderServicesForDirectory: aFileDirectory "Backstop" ^#()! ! !Object class methodsFor: 'file list services' stamp: 'nk 6/12/2004 11:30'! fileReaderServicesForFile: fullName suffix: suffix "Backstop" ^#()! ! !Object class methodsFor: 'file list services' stamp: 'md 2/15/2006 17:20'! services "Backstop" ^#()! ! !Object class methodsFor: 'instance creation' stamp: 'sw 1/23/2003 09:45'! categoryForUniclasses "Answer the default system category into which to place unique-class instances" ^ 'UserObjects'! ! !Object class methodsFor: 'instance creation' stamp: 'sw 7/28/97 15:56'! chooseUniqueClassName | i className | i _ 1. [className _ (self name , i printString) asSymbol. Smalltalk includesKey: className] whileTrue: [i _ i + 1]. ^ className! ! !Object class methodsFor: 'instance creation' stamp: 'tk 8/22/1998 08:22'! initialInstance "Answer the first instance of the receiver, generate an error if there is one already" "self instanceCount > 0 ifTrue: [self error: 'instance(s) already exist.']." "Debugging test that is very slow" ^ self new! ! !Object class methodsFor: 'instance creation' stamp: 'sw 5/5/2000 09:30'! initializedInstance ^ self new! ! !Object class methodsFor: 'instance creation' stamp: 'sw 10/16/2000 10:58'! instanceOfUniqueClass "Answer an instance of a unique subclass of the receiver" ^ self instanceOfUniqueClassWithInstVarString: '' andClassInstVarString: ''! ! !Object class methodsFor: 'instance creation' stamp: 'tk 8/22/1998 08:27'! instanceOfUniqueClassWithInstVarString: instVarString andClassInstVarString: classInstVarString "Create a unique class for the receiver, and answer an instance of it" ^ (self newUniqueClassInstVars: instVarString classInstVars: classInstVarString) initialInstance! ! !Object class methodsFor: 'instance creation' stamp: 'sw 10/23/1999 22:51'! isUniClass ^ false! ! !Object class methodsFor: 'instance creation' stamp: 'ajh 5/23/2002 00:35'! newFrom: aSimilarObject "Create an object that has similar contents to aSimilarObject. If the classes have any instance varaibles with the same names, copy them across. If this is bad for a class, override this method." ^ (self isVariable ifTrue: [self basicNew: aSimilarObject basicSize] ifFalse: [self basicNew] ) copySameFrom: aSimilarObject! ! !Object class methodsFor: 'instance creation' stamp: 'tk 6/29/1998 12:11'! newUniqueClassInstVars: instVarString classInstVars: classInstVarString "Create a unique class for the receiver" | aName aClass | self isSystemDefined ifFalse: [^ superclass newUniqueClassInstVars: instVarString classInstVars: classInstVarString]. aName _ self chooseUniqueClassName. aClass _ self subclass: aName instanceVariableNames: instVarString classVariableNames: '' poolDictionaries: '' category: self categoryForUniclasses. classInstVarString size > 0 ifTrue: [aClass class instanceVariableNames: classInstVarString]. ^ aClass! ! !Object class methodsFor: 'instance creation' stamp: 'sw 7/28/97 15:56'! newUserInstance "Answer an instance of an appropriate class to serve as a user object in the containment hierarchy" ^ self instanceOfUniqueClass! ! !Object class methodsFor: 'instance creation' stamp: 'nk 8/30/2004 07:57'! readCarefullyFrom: textStringOrStream "Create an object based on the contents of textStringOrStream. Return an error instead of putting up a SyntaxError window." | object | (Compiler couldEvaluate: textStringOrStream) ifFalse: [^ self error: 'expected String, Stream, or Text']. object _ Compiler evaluate: textStringOrStream for: nil notifying: #error: "signal we want errors" logged: false. (object isKindOf: self) ifFalse: [self error: self name, ' expected']. ^object! ! !Object class methodsFor: 'instance creation' stamp: 'nk 8/30/2004 07:57'! readFrom: textStringOrStream "Create an object based on the contents of textStringOrStream." | object | (Compiler couldEvaluate: textStringOrStream) ifFalse: [^ self error: 'expected String, Stream, or Text']. object _ Compiler evaluate: textStringOrStream. (object isKindOf: self) ifFalse: [self error: self name, ' expected']. ^object! ! !Object class methodsFor: 'objects from disk' stamp: 'tk 1/8/97'! createFrom: aSmartRefStream size: varsOnDisk version: instVarList "Create an instance of me so objects on the disk can be read in. Tricky part is computing the size if variable. Inst vars will be filled in later. " ^ self isVariable ifFalse: [self basicNew] ifTrue: ["instVarList is names of old class's inst vars plus a version number" self basicNew: (varsOnDisk - (instVarList size - 1))] ! ! !Object class methodsFor: 'window color' stamp: 'nk 6/10/2004 08:10'! windowColorSpecification "Answer a WindowColorSpec object that declares my preference. This is a backstop for classes that don't otherwise define a preference." ^ WindowColorSpec classSymbol: self name wording: 'Default' brightColor: #white pastelColor: #white helpMessage: 'Other windows without color preferences.'! ! !Object class methodsFor: 'private' stamp: 'mir 8/22/2001 15:20'! releaseExternalSettings "Do nothing as a default"! ! Object initialize! pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/OrderedMap.hx000066400000000000000000000311711250413007300262560ustar00rootroot00000000000000package util; import util.Map; import util.Collection; import util.Set; import util.Option; import util.Debug; import util.Throwable; using util.StringFormat; /** * An ordered map of (key,value) pairs. The key ordering is defined by * a comparison function specified at construction. Duplicate keys * are not allowed. * * Worst Case Time and Space Complexities: * [operation] [time] [space] * insert O(lg(n)) O(lg(n)) * find O(lg(n)) O(1) * delete O(lg(n)) O(lg(n)) * range-query O(lg(n))* O(lg(n)) * iteration O(n)** O(lg(n)) * *range-query returns an iterator over elements in the range * **total cost of iterating over the entire map * * The map is backed by a Left-Leaning Red-Black 2-3 Tree * adapted from Robert Sedgewick (2008) (http://www.cs.princeton.edu/~rs/) * * Implementation choices (let size of tree be n) * - Parent Pointers * - This implementation omits parent pointers. * - Omitting parent pointers saves n words of persistent memory * at the expense of lg(n) stack space per operation. * - Without parent pointers, most operations in the tree must * either use recursion, or simulate recursion by saving a history * of nodes via a stack. For example, each iterator will require * lg(n) extra space to track progress through the tree. Insertions * and deletions into the tree will also invalidate any existing * iterators. * - Node Size Information * - This implementation omits the size of each node. * - Omitting size information saves n words of long-term memory at * the expense of not providing a find-kth operation. * - This seems like a reasonable trade-off as range queries are * generally more common than find-kth operations. The implementation * used below could easily be modified to provide a version with * size information should find-kth be of specific interest. * - Recursive vs. Iterative * - This implementation uses recursive algorithms. * - The recursive implementations allow the code to remain compact and * understandable. Since the height of LLRB 2-3 Trees is gaurenteed * to be at most 2lg(n), stack overflow is typically not a concern. * Unlike the standard single-rotation red-black algorithm, LLRB * operations are not tail-recursive, so even an iterative * version will require lg(n) extra memory. */ class OrderedMap { private var root :Null>; private var nodeCount :Int; private var comp :K -> K -> Int; public function new( keyComp :K -> K -> Int ) { root = null; comp = keyComp; nodeCount = 0; assertInvariants(); } /** * @returns Some(v) if (\key,v) is in the map, None otherwise. */ public function get(key :K) :Option { //normal BST search var n = root; while( n != null ) { var cmp = comp(key,n.key); if( cmp < 0 ) { n = n.left; } else if ( cmp > 0 ) { n = n.right; } else { return Some(n.val); } } return None; } /** * Puts (\key,\val) into the map or replaces the current value of \key * with \val. * * @return None if \key currently is not in the map, or Some(v) if (\key,v) * was in the map before the put operation. */ public function set(key :K, val :V) :Option { var ret = new Ref(null); root = insertNode(root,key,val,ret); root.color = black; assertInvariants(); if( ret.r == null ) { return None; } return Some(ret.r); } private function insertNode(n :Node, key :K, val :V, ret :Ref) { //do the insertion at the leaf level if( n == null ) { ++nodeCount; return new Node(key,val); } //normal BST search var cmp = comp(key,n.key); if( cmp < 0 ) { n.left = insertNode(n.left,key,val,ret); } else if( cmp > 0 ) { n.right = insertNode(n.right,key,val,ret); } else { //the key is already in the map, update the value ret.r = n.val; n.val = val; } return fixInvariants(n); } /** * Removes (\key,v) from the map if it exists. * * @return None if (\key,v) wasn't in the map, Some(v) otherwise. */ public function remove(key :K) :Option { var ret = new Ref(null); if( root != null ) { root = deleteNode(root,key,ret); if( root != null ) { root.color = black; } } assertInvariants(); if( ret.r == null ) { return None; } return Some(ret.r); } private function deleteNode( n :Node, key :K, ret :Ref ) { if( comp(key,n.key) < 0 ) { if( isBlack(n.left) && isBlack(n.left.left) ) { //ensure we move into a 3-node n = moveRedLeft(n); } n.left = deleteNode(n.left,key,ret); } else { if( isRed(n.left) ) { //ensure we move into a 3-node n = rotateRight(n); } if( comp(key,n.key) == 0 && n.right == null ) { //delete the node ret.r = n.val; --nodeCount; return null; } if( isBlack(n.right) && isBlack(n.right.left) ) { //ensure we move into a 3-node n = moveRedRight(n); } if( comp(key,n.key) == 0 ) { Debug.assert(n.right != null); ret.r = n.val; //ensure we are deleting a node with at most one child var min = minNode(n.right); n.val = min.val; n.key = min.key; n.right = deleteMinNode(n.right); } else { n.right = deleteNode(n.right,key,ret); } } return fixInvariants(n); } /** returns a view of the set of keys in this TreeMap **/ public function keys() :SetView { var _this = this; return { size: function() return _this.size(), iterator: function() return IterTools.mapIter(new NodeIterator(_this.root),function(x) return x.key), exists: function(x) { return switch(_this.get(x)) { case None: false; case Some(_): true; }; }, }; } /** returns a view of the collection of values in this TreeMap **/ public function values() :CollectionView { var _this = this; return { size: function() return _this.size(), iterator: function() return IterTools.mapIter(new NodeIterator(_this.root),function(x) return x.val), }; } /** returns a view of the (key,value) pairs in this TreeMap **/ public function entries() :CollectionView> { var _this = this; return { size: function() { return _this.size(); }, iterator: function() { return cast new NodeIterator(_this.root); }, }; } /** returns the number of (key,value) pairs in the map **/ public function size() :Int { return nodeCount; } public function toString() :String { var sb = new StringBuf(); sb.add("{"); for( entry in this.entries() ) { sb.add("%y => %y, ".sprintf([entry.key,entry.val])); } sb.add("}"); return sb.toString(); } private static function isRed( n :Node ) { if( n == null ) return false; return switch(n.color) { case red: true; case black: false; }; } private static inline function isBlack( n :Node ) { return !isRed(n); } private static function colorFlip( n :Node ) { n.color = oppositeColor(n.color); n.left.color = oppositeColor(n.left.color); n.right.color = oppositeColor(n.right.color); } private static inline function oppositeColor( c :Color ) { return switch(c) { case red: black; case black: red; }; } private static function rotateLeft( n :Node ) { Debug.assert(n != null); Debug.assert(n.right != null); /* n x / \ / \ a x => n c / \ / \ b c a b */ var x = n.right; n.right = x.left; x.left = n; x.color = n.color; n.color = red; return x; } private static function rotateRight( n :Node ) { Debug.assert( n != null ); Debug.assert( n.left != null ); /* n x / \ / \ x c => a n / \ / \ a b b c */ var x = n.left; n.left = x.right; x.right = n; x.color = n.color; n.color = red; return x; } private static function moveRedLeft( n :Node ) { //borrow extra node from right child (which is a 3-node) colorFlip(n); if( isRed(n.right.left) ) { n.right = rotateRight(n.right); n = rotateLeft(n); colorFlip(n); } return n; } private static function moveRedRight( n :Node ) { //borrow extra node from left child (which is a 3-node) colorFlip(n); if( isRed(n.left.left) ) { n = rotateRight(n); colorFlip(n); } return n; } private static function fixInvariants( n :Node ) { if( isRed(n.right) && isBlack(n.left) ) { //ensure left-leaning property n = rotateLeft(n); } if( isRed(n.left) && isRed(n.left.left) ) { //balance 4-node n = rotateRight(n); } if( isRed(n.left) && isRed(n.right) ) { //split 4-node colorFlip(n); } return n; } private function deleteMinNode( n :Node ) { if( n.left == null ) { //delete --nodeCount; return null; } if( isBlack(n.left) && isBlack(n.left.left) ) { n = moveRedLeft(n); } n.left = deleteMinNode(n.left); return fixInvariants(n); } private static function minNode( n :Node ) { Debug.assert(n != null); while( n.left != null ) { n = n.left; } return n; } private static function maxNode( n :Node ) { Debug.assert(n != null); while( n.right != null ) { n = n.right; } return n; } /** Used to verify that the invariants of the tree hold **/ private inline function assertInvariants() { #if DEBUG Debug.assert( isBlack(root), "root is black: " + root ); assertIsTree(root,new List>()); assertBlackNodeCount(root); assertBSTOrdering(root,comp); #end } private static function assertIsTree( n: Node, visited :List> ) { if( n == null ) { return; } for( r in visited ) { Debug.assert( n != r ); } visited.push(n); assertIsTree(n.left,visited); assertIsTree(n.right,visited); } private static function assertBlackNodeCount( n: Node ) :Int { if( n == null ) { return 1; } var leftCount = assertBlackNodeCount(n.left); var rightCount = assertBlackNodeCount(n.right); Debug.assert( leftCount == rightCount, "num of black nodes in all paths for left and right child not equal" + n ); return leftCount + switch(n.color) { case red: 0; case black: 1; } } private static function assertBSTOrdering( n: Node, compK :K -> K -> Int ) :Void { if( n == null ) { return; } if( n.left != null && n.left.val != null ) { Debug.assert( compK(n.left.key,n.key) < 0, "left child not less than its parent" + n ); assertBSTOrdering(n.left,compK); } if( n.right != null && n.right.val != null ) { Debug.assert( compK(n.key,n.right.key) < 0, "parent not less than its right child" + n ); assertBSTOrdering(n.right,compK); } } } private enum Color { red; black; } private class Node /*implements Entry*/ { public var left :Null>; public var right :Null>; public var color :Color; public var key :K; public var val :V; public function new(k :K, v :V) { key = k; val = v; color = red; } } private class NodeIterator { private var curr :Node; private var fringe :Array>; public function new( root :Node ) { fringe = new Array>(); traverseToMin(root); curr = fringe.pop(); } public inline function hasNext() :Bool { return curr != null; } public function next() :Node { if( !hasNext() ) { throw new NoSuchElement(); } var ret = curr; if( fringe.length > 0 ) { curr = fringe.pop(); traverseToMin(curr.right); } else { curr = null; } return ret; } private function traverseToMin( n :Node ) { while( n != null ) { fringe.push(n); n = n.left; } } }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/RoleQ.pm6000066400000000000000000000013611250413007300253370ustar00rootroot00000000000000role q { token stopper { \' } token escape:sym<\\> { } token backslash:sym { } token backslash:sym<\\> { } token backslash:sym { } token backslash:sym { {} . } method tweak_q($v) { self.panic("Too late for :q") } method tweak_qq($v) { self.panic("Too late for :qq") } } role qq does b1 does c1 does s1 does a1 does h1 does f1 { token stopper { \" } token backslash:sym { {} (\w) { self.throw_unrecog_backslash_seq: $/[0].Str } } token backslash:sym { \W } method tweak_q($v) { self.panic("Too late for :q") } method tweak_qq($v) { self.panic("Too late for :qq") } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/SmallCheck.hs000066400000000000000000000261661250413007300262450ustar00rootroot00000000000000--------------------------------------------------------------------- -- SmallCheck: another lightweight testing library. -- Colin Runciman, August 2006 -- Version 0.2 (November 2006) -- -- After QuickCheck, by Koen Claessen and John Hughes (2000-2004). --------------------------------------------------------------------- module SmallCheck ( smallCheck, depthCheck, Property, Testable, forAll, forAllElem, exists, existsDeeperBy, thereExists, thereExistsElem, (==>), Series, Serial(..), (\/), (><), two, three, four, cons0, cons1, cons2, cons3, cons4, alts0, alts1, alts2, alts3, alts4, N(..), Nat, Natural, depth, inc, dec ) where import Data.List (intersperse) import Control.Monad (when) import System.IO (stdout, hFlush) ------------------ ----------------- -- Series arguments should be interpreted as a depth bound (>=0) -- Series results should have finite length type Series a = Int -> [a] -- sum infixr 7 \/ (\/) :: Series a -> Series a -> Series a s1 \/ s2 = \d -> s1 d ++ s2 d -- product infixr 8 >< (><) :: Series a -> Series b -> Series (a,b) s1 >< s2 = \d -> [(x,y) | x <- s1 d, y <- s2 d] ------------------- ------------------ -- enumerated data values should be finite and fully defined -- enumerated functional values should be total and strict -- bounds: -- for data values, the depth of nested constructor applications -- for functional values, both the depth of nested case analysis -- and the depth of results class Serial a where series :: Series a coseries :: Serial b => Series (a->b) instance Serial () where series _ = [()] coseries d = [ \() -> b | b <- series d ] instance Serial Int where series d = [(-d)..d] coseries d = [ \i -> if i > 0 then f (N (i - 1)) else if i < 0 then g (N (abs i - 1)) else z | z <- alts0 d, f <- alts1 d, g <- alts1 d ] instance Serial Integer where series d = [ toInteger (i :: Int) | i <- series d ] coseries d = [ f . (fromInteger :: Integer->Int) | f <- series d ] newtype N a = N a instance Show a => Show (N a) where show (N i) = show i instance (Integral a, Serial a) => Serial (N a) where series d = map N [0..d'] where d' = fromInteger (toInteger d) coseries d = [ \(N i) -> if i > 0 then f (N (i - 1)) else z | z <- alts0 d, f <- alts1 d ] type Nat = N Int type Natural = N Integer instance Serial Float where series d = [ encodeFloat sig exp | (sig,exp) <- series d, odd sig || sig==0 && exp==0 ] coseries d = [ f . decodeFloat | f <- series d ] instance Serial Double where series d = [ frac (x :: Float) | x <- series d ] coseries d = [ f . (frac :: Double->Float) | f <- series d ] frac :: (Real a, Fractional a, Real b, Fractional b) => a -> b frac = fromRational . toRational instance Serial Char where series d = take (d+1) ['a'..'z'] coseries d = [ \c -> f (N (fromEnum c - fromEnum 'a')) | f <- series d ] instance (Serial a, Serial b) => Serial (a,b) where series = series >< series coseries = map uncurry . coseries instance (Serial a, Serial b, Serial c) => Serial (a,b,c) where series = \d -> [(a,b,c) | (a,(b,c)) <- series d] coseries = map uncurry3 . coseries instance (Serial a, Serial b, Serial c, Serial d) => Serial (a,b,c,d) where series = \d -> [(a,b,c,d) | (a,(b,(c,d))) <- series d] coseries = map uncurry4 . coseries uncurry3 :: (a->b->c->d) -> ((a,b,c)->d) uncurry3 f (x,y,z) = f x y z uncurry4 :: (a->b->c->d->e) -> ((a,b,c,d)->e) uncurry4 f (w,x,y,z) = f w x y z two :: Series a -> Series (a,a) two s = s >< s three :: Series a -> Series (a,a,a) three s = \d -> [(x,y,z) | (x,(y,z)) <- (s >< s >< s) d] four :: Series a -> Series (a,a,a,a) four s = \d -> [(w,x,y,z) | (w,(x,(y,z))) <- (s >< s >< s >< s) d] cons0 :: a -> Series a cons0 c _ = [c] cons1 :: Serial a => (a->b) -> Series b cons1 c d = [c z | d > 0, z <- series (d-1)] cons2 :: (Serial a, Serial b) => (a->b->c) -> Series c cons2 c d = [c y z | d > 0, (y,z) <- series (d-1)] cons3 :: (Serial a, Serial b, Serial c) => (a->b->c->d) -> Series d cons3 c d = [c x y z | d > 0, (x,y,z) <- series (d-1)] cons4 :: (Serial a, Serial b, Serial c, Serial d) => (a->b->c->d->e) -> Series e cons4 c d = [c w x y z | d > 0, (w,x,y,z) <- series (d-1)] alts0 :: Serial a => Series a alts0 d = series d alts1 :: (Serial a, Serial b) => Series (a->b) alts1 d = if d > 0 then series (dec d) else [\_ -> x | x <- series d] alts2 :: (Serial a, Serial b, Serial c) => Series (a->b->c) alts2 d = if d > 0 then series (dec d) else [\_ _ -> x | x <- series d] alts3 :: (Serial a, Serial b, Serial c, Serial d) => Series (a->b->c->d) alts3 d = if d > 0 then series (dec d) else [\_ _ _ -> x | x <- series d] alts4 :: (Serial a, Serial b, Serial c, Serial d, Serial e) => Series (a->b->c->d->e) alts4 d = if d > 0 then series (dec d) else [\_ _ _ _ -> x | x <- series d] instance Serial Bool where series = cons0 True \/ cons0 False coseries d = [ \x -> if x then b1 else b2 | (b1,b2) <- series d ] instance Serial a => Serial (Maybe a) where series = cons0 Nothing \/ cons1 Just coseries d = [ \m -> case m of Nothing -> z Just x -> f x | z <- alts0 d , f <- alts1 d ] instance (Serial a, Serial b) => Serial (Either a b) where series = cons1 Left \/ cons1 Right coseries d = [ \e -> case e of Left x -> f x Right y -> g y | f <- alts1 d , g <- alts1 d ] instance Serial a => Serial [a] where series = cons0 [] \/ cons2 (:) coseries d = [ \xs -> case xs of [] -> y (x:xs') -> f x xs' | y <- alts0 d , f <- alts2 d ] -- Warning: the coseries instance here may generate duplicates. instance (Serial a, Serial b) => Serial (a->b) where series = coseries coseries d = [ \f -> g [f x | x <- series d] | g <- series d ] -- For customising the depth measure. Use with care! depth :: Int -> Int -> Int depth d d' | d >= 0 = d'+1-d | otherwise = error "SmallCheck.depth: argument < 0" dec :: Int -> Int dec d | d > 0 = d-1 | otherwise = error "SmallCheck.dec: argument <= 0" inc :: Int -> Int inc d = d+1 -- show the extension of a function (in part, bounded both by -- the number and depth of arguments) instance (Serial a, Show a, Show b) => Show (a->b) where show f = if maxarheight == 1 && sumarwidth + length ars * length "->;" < widthLimit then "{"++( concat $ intersperse ";" $ [a++"->"++r | (a,r) <- ars] )++"}" else concat $ [a++"->\n"++indent r | (a,r) <- ars] where ars = take lengthLimit [ (show x, show (f x)) | x <- series depthLimit ] maxarheight = maximum [ max (height a) (height r) | (a,r) <- ars ] sumarwidth = sum [ length a + length r | (a,r) <- ars] indent = unlines . map (" "++) . lines height = length . lines (widthLimit,lengthLimit,depthLimit) = (80,20,3)::(Int,Int,Int) ---------------- ------------------ -- adapted from QuickCheck originals: here results come in lists, -- properties have depth arguments, stamps (for classifying random -- tests) are omitted, existentials are introduced newtype PR = Prop [Result] data Result = Result {ok :: Maybe Bool, arguments :: [String]} nothing :: Result nothing = Result {ok = Nothing, arguments = []} result :: Result -> PR result res = Prop [res] newtype Property = Property (Int -> PR) class Testable a where property :: a -> Int -> PR instance Testable Bool where property b _ = Prop [Result (Just b) []] instance Testable PR where property prop _ = prop instance (Serial a, Show a, Testable b) => Testable (a->b) where property f = f' where Property f' = forAll series f instance Testable Property where property (Property f) d = f d evaluate :: Testable a => a -> Series Result evaluate x d = rs where Prop rs = property x d forAll :: (Show a, Testable b) => Series a -> (a->b) -> Property forAll xs f = Property $ \d -> Prop $ [ r{arguments = show x : arguments r} | x <- xs d, r <- evaluate (f x) d ] forAllElem :: (Show a, Testable b) => [a] -> (a->b) -> Property forAllElem xs = forAll (const xs) thereExists :: Testable b => Series a -> (a->b) -> Property thereExists xs f = Property $ \d -> Prop $ [ Result ( Just $ or [ all pass (evaluate (f x) d) | x <- xs d ] ) [] ] where pass (Result Nothing _) = True pass (Result (Just b) _) = b thereExistsElem :: Testable b => [a] -> (a->b) -> Property thereExistsElem xs = thereExists (const xs) exists :: (Serial a, Testable b) => (a->b) -> Property exists = thereExists series existsDeeperBy :: (Serial a, Testable b) => (Int->Int) -> (a->b) -> Property existsDeeperBy f = thereExists (series . f) infixr 0 ==> (==>) :: Testable a => Bool -> a -> Property True ==> x = Property (property x) False ==> x = Property (const (result nothing)) --------------------- ---------------------- -- similar in spirit to QuickCheck but with iterative deepening -- test for values of depths 0..d stopping when a property -- fails or when it has been checked for all these values smallCheck :: Testable a => Int -> a -> IO String smallCheck d = iterCheck 0 (Just d) depthCheck :: Testable a => Int -> a -> IO String depthCheck d = iterCheck d (Just d) iterCheck :: Testable a => Int -> Maybe Int -> a -> IO String iterCheck dFrom mdTo t = iter dFrom where iter :: Int -> IO String iter d = do let Prop results = property t d (ok,s) <- check (mdTo==Nothing) 0 0 True results maybe (iter (d+1)) (\dTo -> if ok && d < dTo then iter (d+1) else return s) mdTo check :: Bool -> Int -> Int -> Bool -> [Result] -> IO (Bool, String) check i n x ok rs | null rs = do let s = " Completed "++show n++" test(s)" y = if i then "." else " without failure." z | x > 0 = " But "++show x++" did not meet ==> condition." | otherwise = "" return (ok, s ++ y ++ z) check i n x ok (Result Nothing _ : rs) = do progressReport i n x check i (n+1) (x+1) ok rs check i n x f (Result (Just True) _ : rs) = do progressReport i n x check i (n+1) x f rs check i n x f (Result (Just False) args : rs) = do let s = " Failed test no. "++show (n+1)++". Test values follow." s' = s ++ ": " ++ concat (intersperse ", " args) if i then check i (n+1) x False rs else return (False, s') progressReport :: Bool -> Int -> Int -> IO () progressReport _ _ _ = return () pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Sorting.mod000066400000000000000000000272421250413007300260250ustar00rootroot00000000000000IMPLEMENTATION MODULE Sorting; (* J. Andrea, Dec.16/91 *) (* This code may be freely used and distributed, it may not be sold. *) (* Adapted to ISO Module-2 by Frank Schoonjans Feb 2004 *) FROM Storage IMPORT ALLOCATE; CONST max_stack = 20; n_small = 6; (* use a simple sort for this size and smaller *) VAR rtemp :REAL; ctemp :CARDINAL; L, R, n :INTEGER; top, bottom, lastflip :INTEGER; tos :CARDINAL; Lstack, Rstack :ARRAY [1..max_stack] OF INTEGER; (* --------------------------------------------------- *) PROCEDURE CardQSortIndex( x :ARRAY OF CARDINAL; array_len :CARDINAL; VAR index :ARRAY OF CARDINAL ); VAR median : CARDINAL; i,j : INTEGER; BEGIN n := VAL(INTEGER,array_len) - 1; (* back to zero offset *) (* initialize the index *) FOR i := 0 TO n DO index[i] := VAL(CARDINAL,i); END; tos := 0; L := 0; R := n; (* PUSH very first set *) tos := tos + 1; Lstack[tos] := L; Rstack[tos] := R; REPEAT (* POP *) L := Lstack[tos]; R := Rstack[tos]; tos := tos - 1; IF R - L + 1 > n_small THEN REPEAT i := L; j := R; median := x[index[( L + R ) DIV 2]]; REPEAT WHILE x[index[i]] < median DO i := i + 1; END; WHILE median < x[index[j]] DO j := j - 1; END; IF i <= j THEN (* swap *) ctemp := index[i]; index[i] := index[j]; index[j] := ctemp; i := i + 1; j := j - 1; END; UNTIL i > j; IF j - L < R - i THEN IF i < R THEN (* PUSH *) tos := tos + 1; Lstack[tos] := i; Rstack[tos] := R; END; R := j; ELSE IF L < j THEN (* push *) tos := tos + 1; Lstack[tos] := L; Rstack[tos] := j; END; L := i; END; UNTIL L >= R; ELSE (* small sort for small number of values *) FOR i := L TO R - 1 DO FOR j := i TO R DO IF x[index[i]] > x[index[j]] THEN ctemp := index[i]; index[i] := index[j]; index[j] := ctemp END; END; END; END; (* check for small *) UNTIL tos = 0; END CardQSortIndex; (* --------------------------------------------------- *) PROCEDURE RealQSortIndex( x :ARRAY OF REAL; array_len :CARDINAL; VAR index :ARRAY OF CARDINAL ); VAR median :REAL; i,j :INTEGER; BEGIN n := VAL(INTEGER,array_len) - 1; (* back to zero offset *) (* initialize the index *) FOR i := 0 TO n DO index[i] := VAL(CARDINAL,i); END; tos := 0; L := 0; R := n; (* PUSH very first set *) tos := tos + 1; Lstack[tos] := L; Rstack[tos] := R; REPEAT (* POP *) L := Lstack[tos]; R := Rstack[tos]; tos := tos - 1; IF R - L + 1 > n_small THEN REPEAT i := L; j := R; median := x[index[( L + R ) DIV 2]]; REPEAT WHILE x[index[i]] < median DO i := i + 1; END; WHILE median < x[index[j]] DO j := j - 1; END; IF i <= j THEN (* swap *) ctemp := index[i]; index[i] := index[j]; index[j] := ctemp; i := i + 1; j := j - 1; END; UNTIL i > j; IF j - L < R - i THEN IF i < R THEN (* PUSH *) tos := tos + 1; Lstack[tos] := i; Rstack[tos] := R; END; R := j; ELSE IF L < j THEN (* push *) tos := tos + 1; Lstack[tos] := L; Rstack[tos] := j; END; L := i; END; UNTIL L >= R; ELSE (* small sort for small number of values *) FOR i := L TO R - 1 DO FOR j := i TO R DO IF x[index[i]] > x[index[j]] THEN ctemp := index[i]; index[i] := index[j]; index[j] := ctemp END; END; END; END; (* check for small *) UNTIL tos = 0; END RealQSortIndex; (* --------------------------------------------------- *) PROCEDURE CardQSort( VAR x :ARRAY OF CARDINAL; array_len :CARDINAL ); VAR median : CARDINAL; n,i,j : INTEGER; BEGIN n := VAL(INTEGER,array_len) - 1; (* back to zero offset *) tos := 0; L := 0; R := n; (* PUSH very first set *) tos := tos + 1; Lstack[tos] := L; Rstack[tos] := R; REPEAT (* POP *) L := Lstack[tos]; R := Rstack[tos]; tos := tos - 1; IF R - L + 1 > n_small THEN REPEAT i := L; j := R; median := x[( L + R ) DIV 2]; REPEAT WHILE x[i] < median DO i := i + 1; END; WHILE median < x[j] DO j := j - 1; END; IF i <= j THEN (* swap *) ctemp := x[i]; x[i] := x[j]; x[j] := ctemp; i := i + 1; j := j - 1; END; UNTIL i > j; IF j - L < R - i THEN IF i < R THEN (* PUSH *) tos := tos + 1; Lstack[tos] := i; Rstack[tos] := R; END; R := j; ELSE IF L < j THEN (* push *) tos := tos + 1; Lstack[tos] := L; Rstack[tos] := j; END; L := i; END; UNTIL L >= R; ELSE (* small sort for small number of values *) FOR i := L TO R - 1 DO FOR j := i TO R DO IF x[i] > x[j] THEN ctemp := x[i]; x[i] := x[j]; x[j] := ctemp END; END; END; END; (* check for small *) UNTIL tos = 0; END CardQSort; (* ----------------------------------------------------- *) PROCEDURE CardBSort( VAR x :ARRAY OF CARDINAL; array_len :CARDINAL ); VAR i,j : INTEGER; BEGIN top := 0; (* open arrays are zero offset *) bottom := VAL(INTEGER,array_len) - 1; WHILE top < bottom DO lastflip := top; FOR i := top TO bottom-1 DO IF x[i] > x[i+1] THEN (* flip *) ctemp := x[i]; x[i] := x[i+1]; x[i+1] := ctemp; lastflip := i; END; END; bottom := lastflip; IF bottom > top THEN i := bottom - 1; FOR j := top TO bottom-1 DO IF x[i] > x[i+1] THEN (* flip *) ctemp := x[i]; x[i] := x[i+1]; x[i+1] := ctemp; lastflip := i; END; i := i - 1; END; top := lastflip + 1; ELSE (* force a loop failure *) top := bottom + 1; END; END; END CardBSort; (* ----------------------------------------------------- *) PROCEDURE RealBSort( VAR x :ARRAY OF REAL; array_len :CARDINAL ); VAR bottom,top : INTEGER; i,j : INTEGER; BEGIN top := 0; (* open arrays are zero offset *) bottom := VAL(INTEGER,array_len) - 1; WHILE top < bottom DO lastflip := top; FOR i := top TO bottom-1 DO IF x[i] > x[i+1] THEN (* flip *) rtemp := x[i]; x[i] := x[i+1]; x[i+1] := rtemp; lastflip := i; END; END; bottom := lastflip; IF bottom > top THEN i := bottom - 1; FOR j := top TO bottom-1 DO IF x[i] > x[i+1] THEN (* flip *) rtemp := x[i]; x[i] := x[i+1]; x[i+1] := rtemp; lastflip := i; END; i := i - 1; END; top := lastflip + 1; ELSE (* force a loop failure *) top := bottom + 1; END; END; END RealBSort; (* ----------------------------------------------------- *) PROCEDURE TopoSort( x, y :ARRAY OF CARDINAL; n_pairs :CARDINAL; VAR solution :ARRAY OF CARDINAL; VAR n_solution :CARDINAL; VAR error, sorted :BOOLEAN ); (* This procedure needs some garbage collection added, i've tried but will little success. J. Andrea, Dec.18/91 *) TYPE LPtr = POINTER TO Leader; TPtr = POINTER TO Trailer; Leader = RECORD key :CARDINAL; count :INTEGER; trail :TPtr; next :LPtr; END; Trailer = RECORD id :LPtr; next :TPtr; END; VAR p, q, head, tail :LPtr; t :TPtr; i, max_solutions :CARDINAL; (* -------------------------------------------- *) PROCEDURE Find( w :CARDINAL ) :LPtr; VAR h :LPtr; BEGIN h := head; tail^.key := w; (* sentinel *) WHILE h^.key # w DO h := h^.next; END; IF h = tail THEN NEW( tail ); n := n + 1; h^.count := 0; h^.trail := NIL; h^.next := tail; END; RETURN h; END Find; BEGIN error := FALSE; n_solution := 0; IF n_pairs < 2 THEN error := TRUE; ELSE max_solutions := HIGH( solution ) + 1; NEW( head ); tail := head; n := 0; (* add all of the given pairs *) FOR i := 0 TO n_pairs - 1 DO p := Find( x[i] ); q := Find( y[i] ); NEW(t); t^.id := q; t^.next := p^.trail; p^.trail := t; q^.count := q^.count + 1; END; (* search for leaders without predecessors *) p := head; head := NIL; WHILE p # tail DO q := p; p := q^.next; IF q^.count = 0 THEN (* insert q^ in new chain *) q^.next := head; head := q; END; END; (* output phase *) q := head; WHILE ( NOT error ) & ( q # NIL ) DO n_solution := n_solution + 1; IF n_solution > max_solutions THEN error := TRUE; ELSE solution[n_solution-1] := q^.key; n := n - 1; t := q^.trail; q := q^.next; WHILE t # NIL DO p := t^.id; p^.count := p^.count - 1; IF p^.count = 0 THEN (* insert p^ in leader list *) p^.next := q; q := p; END; t := t^.next; END; END; END; IF n # 0 THEN sorted := FALSE; ELSE sorted := TRUE; END; END; END TopoSort; BEGIN END Sorting. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/Sudoku.lhs000066400000000000000000000327561250413007300256670ustar00rootroot00000000000000% Copyright 2005 Brian Alliet \documentclass[11pt]{article} \usepackage{palatino} \usepackage{fullpage} \usepackage{parskip} \usepackage{lhs} \begin{document} \title{Sudoku Solver} \author{Brian Alliet} \maketitle \ignore{ \begin{code} module Sudoku ( Sudoku, makeSudoku, solve, eliminate, analyze, backtrack, main ) where import Array import Monad import List (union,intersperse,transpose,(\\),nub,nubBy) \end{code} } \section{Introduction} This Haskell module implements a solver for Sudoku~\footnote{http://en.wikipedia.org/wiki/Sudoku} puzzles. It can solve any Sudoku puzzle, even those that require backtracking. \section{Data Types} \begin{code} data CellState a = Known a | Unknown [a] | Impossible deriving Eq \end{code} Each cell in a Sudoku grid can be in one of three states: ``Known'' if it has a known correct value~\footnote{Actually this doesn't always means it is correct. While we are in the backtracking stage we make our guesses ``Known''.}, ``Unknown'' if there is still more than one possible correct value, or ``Impossible'' if there is no value that can possibly fit the cell. Sudoku grids with ``Impossible'' cells are quickly discarded by the {\tt solve} function. \begin{code} type Coords = (Int,Int) type Grid a = Array Coords (CellState a) newtype Sudoku a = Sudoku { unSudoku :: Grid a } deriving Eq \end{code} We represent a Sudoku grid as an Array indexed by integer coordinates. We additionally define a newtype wrapper for the grid. The smart constructor, {\tt makeSudoku} verifies some invariants before creating the Sudoku value. All the public API functions operate on the Sudoku type. \begin{code} instance Show a => Show (Sudoku a) where showsPrec p = showParen (p>0) . showsGrid . unSudoku instance Show a => Show (CellState a) where showsPrec _ = showsCell \end{code} We define {\tt Show} instances for the above types. \section{Internal Functions} \begin{code} size :: Grid a -> Int size = (+1).fst.snd.bounds \end{code} {\tt size} returns the size (the width, height, and number of subboxes) for a Sudoku grid. We ensure Grid's are always square and indexed starting at $(0,0)$ so simply incrementing either of the array's upper bounds is correct. \begin{code} getRow,getCol,getBox :: Grid a -> Int -> [(Coords,CellState a)] getRow grid r = [let l = (r,c) in (l,grid!l)|c <- [0..size grid - 1]] getCol grid c = [let l = (r,c) in (l,grid!l)|r <- [0..size grid - 1]] getBox grid b = [let l = (r,c) in (l,grid!l)|r <- [boxR..boxR+boxN-1],c <- [boxC..boxC+boxN-1]] where boxN = intSqrt (size grid); boxR = b `quot` boxN * boxN; boxC = b `rem` boxN * boxN getBoxOf :: Grid a -> Coords -> [(Coords,CellState a)] getBoxOf grid (r,c) = grid `getBox` ((r `quot` boxN * boxN) + (c `quot` boxN)) where boxN = intSqrt (size grid) \end{code} {\tt getRow}, {\tt getCol}, and {\tt getBox} return the coordinates and values of the cell in row, column, or box number {\tt n}, {\tt r}, or {\tt b}. \begin{code} getNeighbors :: Eq a => Grid a -> Coords -> [(Coords,CellState a)] getNeighbors grid l@(r,c) = filter ((/=l).fst) $ foldr (union.($grid)) [] [(`getRow`r),(`getCol`c),(`getBoxOf`l)] \end{code} {\tt getNeighbors} returns the coordinates and values of all the neighbors of this cell. \begin{code} impossible :: Eq a => Grid a -> Coords -> [a] impossible grid l = map snd $ justKnowns $ grid `getNeighbors` l \end{code} {\tt impossible} returns a list of impossible values for a given cell. The impossible values consist of the values any ``Known'' neighbors. \begin{code} justUnknowns :: [(Coords,CellState a)] -> [(Coords,[a])] justUnknowns = foldr (\c -> case c of (p,Unknown xs) -> ((p,xs):); _ -> id) [] justKnowns :: [(Coords,CellState a)] -> [(Coords,a)] justKnowns = foldr (\c -> case c of (p,Known x) -> ((p,x):); _ -> id) [] \end{code} {\tt justUnknowns} and {\tt justKnowns} return only the Known or Unknown values (with the constructor stripped off) from a list of cells. \begin{code} updateGrid :: Grid a -> [(Coords,CellState a)] -> Maybe (Grid a) updateGrid _ [] = Nothing updateGrid grid xs = Just $ grid // nubBy (\(x,_) (y,_) -> x==y) xs \end{code} {\tt updateGrid} applies a set of updates to a grid and returns the new grid only if it was updated. \section{Public API} \begin{code} makeSudoku :: (Num a, Ord a, Enum a) => [[a]] -> Sudoku a makeSudoku xs | not (all ((==size).length) xs) = error "error not a square" | (intSqrt size)^(2::Int) /= size = error "error dims aren't perfect squares" | any (\x -> x < 0 || x > fromIntegral size) (concat xs) = error "value out of range" | otherwise = Sudoku (listArray ((0,0),(size-1,size-1)) states) where size = length xs states = map f (concat xs) f 0 = Unknown [1..fromIntegral size] f x = Known x \end{code} {\tt makeSudoku} makes a {\tt Sudoku} value from a list of numbers. The given matrix must be square and have dimensions that are a perfect square. The possible values for each cell range from 1 to the dimension of the square with ``0'' representing unknown values.\footnote{The rest of the code doesn't depend on any of this weird ``0'' is unknown representation. In fact, it doesn't depend on numeric values at all. ``0'' is just used here because it makes representing grids in Haskell source code easier.} \begin{code} eliminate :: Eq a => Sudoku a -> Maybe (Sudoku a) eliminate (Sudoku grid) = fmap Sudoku $ updateGrid grid changes >>= sanitize where changes = concatMap findChange $ assocs grid findChange (l,Unknown xs) = map ((,) l) $ case filter (not.(`elem`impossible grid l)) xs of [] -> return Impossible [x] -> return $ Known x xs' | xs' /= xs -> return $ Unknown xs' | otherwise -> mzero findChange _ = mzero sanitize grid = return $ grid // [(l,Impossible) | (l,x) <- justKnowns changes, x `elem` impossible grid l] \end{code} The {\tt eliminate} phase tries to remove possible choices for ``Unknowns'' based on ``Known'' values in the same row, column, or box as the ``Unknown'' value. For each cell on the grid we find its ``neighbors'', that is, cells in the same row, column, or box. Out of those neighbors we get a list of all the ``Known'' values. We can eliminate all of these from our list of candidates for this cell. If we're lucky enough to eliminate all the candidates but one we have a new ``Known'' value. If we're unlucky enough to have eliminates {\bf all} the possible candidates we have a new ``Impossible'' value. After iterating though every cell we make one more pass looking for conflicting changes. {\tt sanitize} marks cells as ``Impossible'' if we have conflicting ``Known'' values. \begin{code} analyze :: Eq a => Sudoku a -> Maybe (Sudoku a) analyze (Sudoku grid) = fmap Sudoku $ updateGrid grid $ nub [u | f <- map ($grid) [getRow,getCol,getBox], n <- [0..size grid - 1], u <- unique (f n)] where unique xs = foldr f [] $ foldr (union.snd) [] unknowns \\ map snd (justKnowns xs) where unknowns = justUnknowns xs f c = case filter ((c`elem`).snd) unknowns of [(p,_)] -> ((p,Known c):) _ -> id \end{code} The {\tt analyze} phase tries to turn ``Unknowns'' into ``Knowns'' when a certain ``Unknown'' is the only cell that contains a value needed in a given row, column, or box. We apply each of the functions {\tt getRow}, {\tt getCol}, and {\tt getBox} to all the indices on the grid, apply {\tt unique} to each group, and update the array with the results. {\tt unique} gets a list of all the unknown cells in the group and finds all the unknown values in each of those cells. Each of these values are iterated though looking for a value that is only contained in one cell. If such a value is found the cell containing it must be that value. \begin{code} backtrack :: (MonadPlus m, Eq a) => Sudoku a -> m (Sudoku a) backtrack (Sudoku grid) = case (justUnknowns (assocs grid)) of [] -> return $ Sudoku grid ((p,xs):_) -> msum $ map (\x -> solve $ Sudoku $ grid // [(p,Known x)]) xs \end{code} Sometimes the above two phases still aren't enough to solve a puzzle. For these rare puzzles backtracking is required. We attempt to solve the puzzle by replacing the first ``Unknown'' value with each of the candidate values and solving the resulting puzzles. Hopefully at least one of our choices will result in a solvable puzzle. We could actually solve any puzzle using backtracking alone, although this would be very inefficient. The above functions simplify most puzzles enough that the backtracking phase has to do hardly any work. \begin{code} solve :: (MonadPlus m, Eq a) => Sudoku a -> m (Sudoku a) solve sudoku = case eliminate sudoku of Just new | any (==Impossible) (elems (unSudoku new))-> mzero | otherwise -> solve new Nothing -> case analyze sudoku of Just new -> solve new Nothing -> backtrack sudoku \end{code} {\tt solve} glues all the above phases together. First we run the {\tt eliminate} phase. If that found the puzzle to be unsolvable we abort immediately. If {\tt eliminate} changed the grid we go though the {\tt eliminate} phase again hoping to eliminate more. Once {\tt eliminate} can do no more work we move on to the {\tt analyze} phase. If this succeeds in doing some work we start over again with the {\tt eliminate} phase. Once {\tt analyze} can do no more work we have no choice but to resort to backtracking. (However in most cases backtracking won't actually do anything because the puzzle is already solved.) \begin{code} showsCell :: Show a => CellState a -> ShowS showsCell (Known x) = shows x showsCell (Impossible) = showChar 'X' showsCell (Unknown xs) = \rest -> ('(':) $ foldr id (')':rest) $ intersperse (showChar ' ') $ map shows xs \end{code} {\tt showCell} shows a cell. \begin{code} showsGrid :: Show a => Grid a -> ShowS showsGrid grid = showsTable [[grid!(r,c) | c <- [0..size grid-1]] | r <- [0..size grid-1]] \end{code} {\tt showGrid} show a grid. \begin{code} -- FEATURE: This is pretty inefficient showsTable :: Show a => [[a]] -> ShowS showsTable xs = (showChar '\n' .) $ showString $ unlines $ map (concat . intersperse " ") xs'' where xs' = (map.map) show xs colWidths = map (max 2 . maximum . map length) (transpose xs') xs'' = map (zipWith (\n s -> s ++ (replicate (n - length s) ' ')) colWidths) xs' \end{code} {\tt showsTable} shows a table (or matrix). Every column has the same width so things line up. \begin{code} intSqrt :: Integral a => a -> a intSqrt n | n < 0 = error "intSqrt: negative n" | otherwise = f n where f x = if y < x then f y else x where y = (x + (n `quot` x)) `quot` 2 \end{code} {\tt intSqrt} is Newton`s Iteration for finding integral square roots. \ignore{ \begin{code} test :: Sudoku Int test = makeSudoku [ [0,6,0,1,0,4,0,5,0], [0,0,8,3,0,5,6,0,0], [2,0,0,0,0,0,0,0,1], [8,0,0,4,0,7,0,0,6], [0,0,6,0,0,0,3,0,0], [7,0,0,9,0,1,0,0,4], [5,0,0,0,0,0,0,0,2], [0,0,7,2,0,6,9,0,0], [0,4,0,5,0,8,0,7,0]] test2 :: Sudoku Int test2 = makeSudoku [ [0,7,0,0,0,0,8,0,0], [0,0,0,2,0,4,0,0,0], [0,0,6,0,0,0,0,3,0], [0,0,0,5,0,0,0,0,6], [9,0,8,0,0,2,0,4,0], [0,5,0,0,3,0,9,0,0], [0,0,2,0,8,0,0,6,0], [0,6,0,9,0,0,7,0,1], [4,0,0,0,0,3,0,0,0]] testSmall :: Sudoku Int testSmall = makeSudoku [ [1,0,0,0,0,0,0,0,0], [0,0,2,7,4,0,0,0,0], [0,0,0,5,0,0,0,0,4], [0,3,0,0,0,0,0,0,0], [7,5,0,0,0,0,0,0,0], [0,0,0,0,0,9,6,0,0], [0,4,0,0,0,6,0,0,0], [0,0,0,0,0,0,0,7,1], [0,0,0,0,0,1,0,3,0]] testHard :: Sudoku Int testHard = makeSudoku [ [0,0,0,8,0,2,0,0,0], [5,0,0,0,0,0,0,0,1], [0,0,6,0,5,0,3,0,0], [0,0,9,0,1,0,8,0,0], [1,0,0,0,0,0,0,0,2], [0,0,0,9,0,7,0,0,0], [0,6,1,0,3,0,7,8,0], [0,5,0,0,0,0,0,4,0], [0,7,2,0,4,0,1,5,0]] testHard2 :: Sudoku Int testHard2 = makeSudoku [ [3,0,0,2,0,0,9,0,0], [0,0,0,0,0,0,0,0,5], [0,7,0,1,0,4,0,0,0], [0,0,9,0,0,0,8,0,0], [5,0,0,0,7,0,0,0,6], [0,0,1,0,0,0,2,0,0], [0,0,0,3,0,9,0,4,0], [8,0,0,0,0,0,0,0,0], [0,0,6,0,0,5,0,0,7]] testHW :: Sudoku Int testHW = makeSudoku [ [0,0,0,1,0,0,7,0,2], [0,3,0,9,5,0,0,0,0], [0,0,1,0,0,2,0,0,3], [5,9,0,0,0,0,3,0,1], [0,2,0,0,0,0,0,7,0], [7,0,3,0,0,0,0,9,8], [8,0,0,2,0,0,1,0,0], [0,0,0,0,8,5,0,6,0], [6,0,5,0,0,9,0,0,0]] testTough :: Sudoku Int testTough = makeSudoku $ map (map read . words) $ lines $ "8 3 0 0 0 0 0 4 6\n"++ "0 2 0 1 0 4 0 3 0\n"++ "0 0 0 0 0 0 0 0 0\n"++ "0 0 2 9 0 6 5 0 0\n"++ "1 4 0 0 0 0 0 2 3\n"++ "0 0 5 4 0 3 1 0 0\n"++ "0 0 0 0 0 0 0 0 0\n"++ "0 6 0 3 0 8 0 7 0\n"++ "9 5 0 0 0 0 0 6 2\n" testDiabolical :: Sudoku Int testDiabolical = makeSudoku $ map (map read . words) $ lines $ "8 0 0 7 0 1 0 0 2\n"++ "0 0 6 0 0 0 7 0 0\n"++ "0 1 7 0 0 0 8 9 0\n"++ "0 0 0 1 7 3 0 0 0\n"++ "7 0 0 0 0 0 0 0 6\n"++ "0 0 0 9 5 6 0 0 0\n"++ "0 9 5 0 0 0 4 1 0\n"++ "0 0 8 0 0 0 5 0 0\n"++ "3 0 0 6 0 5 0 0 7\n" main :: IO () main = do let solve' p = case solve p of [] -> fail $ "couldn't solve: " ++ show p sols -> return sols mapM_ (\p -> solve' p >>= putStrLn.show) [test,test2,testSmall,testHard,testHard2,testHW,testTough,testDiabolical] return () \end{code} } \end{document} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/addressbook.proto000066400000000000000000000011751250413007300272610ustar00rootroot00000000000000// See README.txt for information and build instructions. package tutorial; option java_package = "com.example.tutorial"; option java_outer_classname = "AddressBookProtos"; message Person { required string name = 1; required int32 id = 2; // Unique ID number for this person. optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; } // Our address book file is just one of these. message AddressBook { repeated Person person = 1; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/antlr_ANTLRv3.g000066400000000000000000000327711250413007300264030ustar00rootroot00000000000000/* [The "BSD licence"] Copyright (c) 2005-2007 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** ANTLR v3 grammar written in ANTLR v3 with AST construction */ grammar ANTLRv3; options { output=AST; ASTLabelType=CommonTree; } tokens { DOC_COMMENT; PARSER; LEXER; RULE; BLOCK; OPTIONAL; CLOSURE; POSITIVE_CLOSURE; SYNPRED; RANGE; CHAR_RANGE; EPSILON; ALT; EOR; EOB; EOA; // end of alt ID; ARG; ARGLIST; RET; LEXER_GRAMMAR; PARSER_GRAMMAR; TREE_GRAMMAR; COMBINED_GRAMMAR; INITACTION; LABEL; // $x used in rewrite rules TEMPLATE; SCOPE='scope'; SEMPRED; GATED_SEMPRED; // {p}? => SYN_SEMPRED; // (...) => it's a manually-specified synpred converted to sempred BACKTRACK_SEMPRED; // auto backtracking mode syn pred converted to sempred FRAGMENT='fragment'; TREE_BEGIN='^('; ROOT='^'; BANG='!'; RANGE='..'; REWRITE='->'; } @members { int gtype; } grammarDef : DOC_COMMENT? ( 'lexer' {gtype=LEXER_GRAMMAR;} // pure lexer | 'parser' {gtype=PARSER_GRAMMAR;} // pure parser | 'tree' {gtype=TREE_GRAMMAR;} // a tree parser | {gtype=COMBINED_GRAMMAR;} // merged parser/lexer ) g='grammar' id ';' optionsSpec? tokensSpec? attrScope* action* rule+ EOF -> ^( {adaptor.create(gtype,$g)} id DOC_COMMENT? optionsSpec? tokensSpec? attrScope* action* rule+ ) ; tokensSpec : TOKENS tokenSpec+ '}' -> ^(TOKENS tokenSpec+) ; tokenSpec : TOKEN_REF ( '=' (lit=STRING_LITERAL|lit=CHAR_LITERAL) -> ^('=' TOKEN_REF $lit) | -> TOKEN_REF ) ';' ; attrScope : 'scope' id ACTION -> ^('scope' id ACTION) ; /** Match stuff like @parser::members {int i;} */ action : '@' (actionScopeName '::')? id ACTION -> ^('@' actionScopeName? id ACTION) ; /** Sometimes the scope names will collide with keywords; allow them as * ids for action scopes. */ actionScopeName : id | l='lexer' -> ID[$l] | p='parser' -> ID[$p] ; optionsSpec : OPTIONS (option ';')+ '}' -> ^(OPTIONS option+) ; option : id '=' optionValue -> ^('=' id optionValue) ; optionValue : id | STRING_LITERAL | CHAR_LITERAL | INT | s='*' -> STRING_LITERAL[$s] // used for k=* ; rule scope { String name; } : DOC_COMMENT? ( modifier=('protected'|'public'|'private'|'fragment') )? id {$rule::name = $id.text;} '!'? ( arg=ARG_ACTION )? ( 'returns' rt=ARG_ACTION )? throwsSpec? optionsSpec? ruleScopeSpec? ruleAction* ':' altList ';' exceptionGroup? -> ^( RULE id {modifier!=null?adaptor.create(modifier):null} ^(ARG $arg)? ^(RET $rt)? optionsSpec? ruleScopeSpec? ruleAction* altList exceptionGroup? EOR["EOR"] ) ; /** Match stuff like @init {int i;} */ ruleAction : '@' id ACTION -> ^('@' id ACTION) ; throwsSpec : 'throws' id ( ',' id )* -> ^('throws' id+) ; ruleScopeSpec : 'scope' ACTION -> ^('scope' ACTION) | 'scope' id (',' id)* ';' -> ^('scope' id+) | 'scope' ACTION 'scope' id (',' id)* ';' -> ^('scope' ACTION id+ ) ; block : lp='(' ( (opts=optionsSpec)? ':' )? a1=alternative rewrite ( '|' a2=alternative rewrite )* rp=')' -> ^( BLOCK[$lp,"BLOCK"] optionsSpec? alternative+ EOB[$rp,"EOB"] ) ; altList @init { // must create root manually as it's used by invoked rules in real antlr tool. // leave here to demonstrate use of {...} in rewrite rule // it's really BLOCK[firstToken,"BLOCK"]; set line/col to previous ( or : token. CommonTree blkRoot = (CommonTree)adaptor.create(BLOCK,input.LT(-1),"BLOCK"); } : a1=alternative rewrite ( '|' a2=alternative rewrite )* -> ^( {blkRoot} (alternative rewrite?)+ EOB["EOB"] ) ; alternative @init { Token firstToken = input.LT(1); Token prevToken = input.LT(-1); // either : or | I think } : element+ -> ^(ALT[firstToken,"ALT"] element+ EOA["EOA"]) | -> ^(ALT[prevToken,"ALT"] EPSILON[prevToken,"EPSILON"] EOA["EOA"]) ; exceptionGroup : ( exceptionHandler )+ ( finallyClause )? | finallyClause ; exceptionHandler : 'catch' ARG_ACTION ACTION -> ^('catch' ARG_ACTION ACTION) ; finallyClause : 'finally' ACTION -> ^('finally' ACTION) ; element : elementNoOptionSpec ; elementNoOptionSpec : id (labelOp='='|labelOp='+=') atom ( ebnfSuffix -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] ^($labelOp id atom) EOA["EOA"]) EOB["EOB"])) | -> ^($labelOp id atom) ) | id (labelOp='='|labelOp='+=') block ( ebnfSuffix -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] ^($labelOp id block) EOA["EOA"]) EOB["EOB"])) | -> ^($labelOp id block) ) | atom ( ebnfSuffix -> ^(BLOCK["BLOCK"] ^(ALT["ALT"] atom EOA["EOA"]) EOB["EOB"]) | -> atom ) | ebnf | ACTION | SEMPRED ( '=>' -> GATED_SEMPRED | -> SEMPRED ) | treeSpec ; atom: range ( (op='^'|op='!') -> ^($op range) | -> range ) | terminal | notSet ( (op='^'|op='!') -> ^($op notSet) | -> notSet ) | RULE_REF ( arg=ARG_ACTION )? ( (op='^'|op='!') )? -> {$arg!=null&&op!=null}? ^($op RULE_REF $arg) -> {$arg!=null}? ^(RULE_REF $arg) -> {$op!=null}? ^($op RULE_REF) -> RULE_REF ; notSet : '~' ( notTerminal -> ^('~' notTerminal) | block -> ^('~' block) ) ; treeSpec : '^(' element ( element )+ ')' -> ^(TREE_BEGIN element+) ; /** Matches ENBF blocks (and token sets via block rule) */ ebnf @init { Token firstToken = input.LT(1); } @after { $ebnf.tree.getToken().setLine(firstToken.getLine()); $ebnf.tree.getToken().setCharPositionInLine(firstToken.getCharPositionInLine()); } : block {Token op=input.LT(1);} ( '?' -> ^(OPTIONAL[op] block) | '*' -> ^(CLOSURE[op] block) | '+' -> ^(POSITIVE_CLOSURE[op] block) | '^' -> ^('^' block) | '!' -> ^('!' block) | '=>' // syntactic predicate -> {gtype==COMBINED_GRAMMAR && Character.isUpperCase($rule::name.charAt(0))}? // if lexer rule in combined, leave as pred for lexer ^(SYNPRED["=>"] block) // in real antlr tool, text for SYN_SEMPRED is predname -> SYN_SEMPRED | -> block ) ; range! : c1=CHAR_LITERAL RANGE c2=CHAR_LITERAL -> ^(CHAR_RANGE[$c1,".."] $c1 $c2) ; terminal : ( CHAR_LITERAL -> CHAR_LITERAL // Args are only valid for lexer rules | TOKEN_REF ( ARG_ACTION -> ^(TOKEN_REF ARG_ACTION) | -> TOKEN_REF ) | STRING_LITERAL -> STRING_LITERAL | '.' -> '.' ) ( '^' -> ^('^' $terminal) | '!' -> ^('!' $terminal) )? ; notTerminal : CHAR_LITERAL | TOKEN_REF | STRING_LITERAL ; ebnfSuffix @init { Token op = input.LT(1); } : '?' -> OPTIONAL[op] | '*' -> CLOSURE[op] | '+' -> POSITIVE_CLOSURE[op] ; // R E W R I T E S Y N T A X rewrite @init { Token firstToken = input.LT(1); } : (rew+='->' preds+=SEMPRED predicated+=rewrite_alternative)* rew2='->' last=rewrite_alternative -> ^($rew $preds $predicated)* ^($rew2 $last) | ; rewrite_alternative : rewrite_template | rewrite_tree_alternative | /* empty rewrite */ -> ^(ALT["ALT"] EPSILON["EPSILON"] EOA["EOA"]) ; rewrite_template_block : lp='(' rewrite_template ')' -> ^(BLOCK[$lp,"BLOCK"] rewrite_template EOB[$lp,"EOB"]) ; rewrite_tree_block : lp='(' rewrite_tree_alternative ')' -> ^(BLOCK[$lp,"BLOCK"] rewrite_tree_alternative EOB[$lp,"EOB"]) ; rewrite_tree_alternative : rewrite_tree_element+ -> ^(ALT["ALT"] rewrite_tree_element+ EOA["EOA"]) ; rewrite_tree_element : rewrite_tree_atom | rewrite_tree_atom ebnfSuffix -> ^( ebnfSuffix ^(BLOCK["BLOCK"] ^(ALT["ALT"] rewrite_tree_atom EOA["EOA"]) EOB["EOB"])) | rewrite_tree ( ebnfSuffix -> ^(BLOCK["BLOCK"] ^(ALT["ALT"] rewrite_tree EOA["EOA"]) EOB["EOB"]) | -> rewrite_tree ) | rewrite_tree_ebnf ; rewrite_tree_atom : CHAR_LITERAL | TOKEN_REF ARG_ACTION? -> ^(TOKEN_REF ARG_ACTION?) // for imaginary nodes | RULE_REF | STRING_LITERAL | d='$' id -> LABEL[$d,$id.text] // reference to a label in a rewrite rule | ACTION ; rewrite_tree_ebnf @init { Token firstToken = input.LT(1); } @after { $rewrite_tree_ebnf.tree.getToken().setLine(firstToken.getLine()); $rewrite_tree_ebnf.tree.getToken().setCharPositionInLine(firstToken.getCharPositionInLine()); } : rewrite_tree_block ebnfSuffix -> ^(ebnfSuffix rewrite_tree_block) ; rewrite_tree : '^(' rewrite_tree_atom rewrite_tree_element* ')' -> ^(TREE_BEGIN rewrite_tree_atom rewrite_tree_element* ) ; /** Build a tree for a template rewrite: ^(TEMPLATE (ID|ACTION) ^(ARGLIST ^(ARG ID ACTION) ...) ) where ARGLIST is always there even if no args exist. ID can be "template" keyword. If first child is ACTION then it's an indirect template ref -> foo(a={...}, b={...}) -> ({string-e})(a={...}, b={...}) // e evaluates to template name -> {%{$ID.text}} // create literal template from string (done in ActionTranslator) -> {st-expr} // st-expr evaluates to ST */ rewrite_template : // -> template(a={...},...) "..." inline template {input.LT(1).getText().equals("template")}? id lp='(' rewrite_template_args ')' st=( DOUBLE_QUOTE_STRING_LITERAL | DOUBLE_ANGLE_STRING_LITERAL ) -> ^(TEMPLATE[$lp,"TEMPLATE"] id rewrite_template_args $st) | // -> foo(a={...}, ...) rewrite_template_ref | // -> ({expr})(a={...}, ...) rewrite_indirect_template_head | // -> {...} ACTION ; /** -> foo(a={...}, ...) */ rewrite_template_ref : id lp='(' rewrite_template_args ')' -> ^(TEMPLATE[$lp,"TEMPLATE"] id rewrite_template_args) ; /** -> ({expr})(a={...}, ...) */ rewrite_indirect_template_head : lp='(' ACTION ')' '(' rewrite_template_args ')' -> ^(TEMPLATE[$lp,"TEMPLATE"] ACTION rewrite_template_args) ; rewrite_template_args : rewrite_template_arg (',' rewrite_template_arg)* -> ^(ARGLIST rewrite_template_arg+) | -> ARGLIST ; rewrite_template_arg : id '=' ACTION -> ^(ARG[$id.start] id ACTION) ; id : TOKEN_REF -> ID[$TOKEN_REF] | RULE_REF -> ID[$RULE_REF] ; // L E X I C A L R U L E S SL_COMMENT : '//' ( ' $ANTLR ' SRC // src directive | ~('\r'|'\n')* ) '\r'? '\n' {$channel=HIDDEN;} ; ML_COMMENT : '/*' {if (input.LA(1)=='*') $type=DOC_COMMENT; else $channel=HIDDEN;} .* '*/' ; CHAR_LITERAL : '\'' LITERAL_CHAR '\'' ; STRING_LITERAL : '\'' LITERAL_CHAR LITERAL_CHAR* '\'' ; fragment LITERAL_CHAR : ESC | ~('\''|'\\') ; DOUBLE_QUOTE_STRING_LITERAL : '"' LITERAL_CHAR* '"' ; DOUBLE_ANGLE_STRING_LITERAL : '<<' .* '>>' ; fragment ESC : '\\' ( 'n' | 'r' | 't' | 'b' | 'f' | '"' | '\'' | '\\' | '>' | 'u' XDIGIT XDIGIT XDIGIT XDIGIT | . // unknown, leave as it is ) ; fragment XDIGIT : '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ; INT : '0'..'9'+ ; ARG_ACTION : NESTED_ARG_ACTION ; fragment NESTED_ARG_ACTION : '[' ( options {greedy=false; k=1;} : NESTED_ARG_ACTION | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | . )* ']' {setText(getText().substring(1, getText().length()-1));} ; ACTION : NESTED_ACTION ( '?' {$type = SEMPRED;} )? ; fragment NESTED_ACTION : '{' ( options {greedy=false; k=3;} : NESTED_ACTION | SL_COMMENT | ML_COMMENT | ACTION_STRING_LITERAL | ACTION_CHAR_LITERAL | . )* '}' {$channel = DEFAULT_TOKEN_CHANNEL;} ; fragment ACTION_CHAR_LITERAL : '\'' (ACTION_ESC|~('\\'|'\'')) '\'' ; fragment ACTION_STRING_LITERAL : '"' (ACTION_ESC|~('\\'|'"'))+ '"' ; fragment ACTION_ESC : '\\\'' | '\\"' | '\\' ~('\''|'"') ; TOKEN_REF : 'A'..'Z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')* ; RULE_REF : 'a'..'z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')* ; /** Match the start of an options section. Don't allow normal * action processing on the {...} as it's not a action. */ OPTIONS : 'options' WS_LOOP '{' {$channel=DEFAULT_TOKEN_CHANNEL;} // WS_LOOP sets channel ; TOKENS : 'tokens' WS_LOOP '{' {$channel=DEFAULT_TOKEN_CHANNEL;} ; /** Reset the file and line information; useful when the grammar * has been generated so that errors are shown relative to the * original file like the old C preprocessor used to do. */ fragment SRC : 'src' ' ' file=ACTION_STRING_LITERAL ' ' line=INT {$channel=HIDDEN;} ; WS : ( ' ' | '\t' | '\r'? '\n' )+ {$channel=HIDDEN;} ; fragment WS_LOOP : ( WS | SL_COMMENT | ML_COMMENT )* {$channel=HIDDEN;} ; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/antlr_throws000066400000000000000000000000361250413007300263400ustar00rootroot00000000000000public f throws a, b, c : x ; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/apache2.conf000066400000000000000000000303021250413007300260400ustar00rootroot00000000000000# Based upon the NCSA server configuration files originally by Rob McCool. # Changed extensively for the Debian package by Daniel Stone # and also by Thom May . # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the LockFile documentation # (available at ); # you will save yourself a lot of trouble. ServerRoot "/etc/apache2" # The LockFile directive sets the path to the lockfile used when Apache # is compiled with either USE_FCNTL_SERIALIZED_ACCEPT or # USE_FLOCK_SERIALIZED_ACCEPT. This directive should normally be left at # its default value. The main reason for changing it is if the logs # directory is NFS mounted, since the lockfile MUST BE STORED ON A LOCAL # DISK. The PID of the main server process is automatically appended to # the filename. LockFile /var/lock/apache2/accept.lock # PidFile: The file in which the server should record its process # identification number when it starts. PidFile /var/run/apache2.pid # Timeout: The number of seconds before receives and sends time out. Timeout 300 # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. KeepAlive On # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. MaxKeepAliveRequests 100 # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. KeepAliveTimeout 15 ## ## Server-Pool Size Regulation (MPM specific) ## # prefork MPM # StartServers ......... number of server processes to start # MinSpareServers ...... minimum number of server processes which are kept spare # MaxSpareServers ...... maximum number of server processes which are kept spare # MaxClients ........... maximum number of server processes allowed to start # MaxRequestsPerChild .. maximum number of requests a server process serves StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 20 MaxRequestsPerChild 0 # pthread MPM # StartServers ......... initial number of server processes to start # MaxClients ........... maximum number of server processes allowed to start # MinSpareThreads ...... minimum number of worker threads which are kept spare # MaxSpareThreads ...... maximum number of worker threads which are kept spare # ThreadsPerChild ...... constant number of worker threads in each server process # MaxRequestsPerChild .. maximum number of requests a server process serves StartServers 2 MaxClients 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxRequestsPerChild 0 # perchild MPM # NumServers ........... constant number of server processes # StartThreads ......... initial number of worker threads in each server process # MinSpareThreads ...... minimum number of worker threads which are kept spare # MaxSpareThreads ...... maximum number of worker threads which are kept spare # MaxThreadsPerChild ... maximum number of worker threads in each server process # MaxRequestsPerChild .. maximum number of connections per server process (then it dies) NumServers 5 StartThreads 5 MinSpareThreads 5 MaxSpareThreads 10 MaxThreadsPerChild 20 MaxRequestsPerChild 0 AcceptMutex fcntl User www-data Group www-data # The following directives define some format nicknames for use with # a CustomLog directive (see below). LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # Global error log. ErrorLog /var/log/apache2/error.log # Include module configuration: Include /etc/apache2/mods-enabled/*.load Include /etc/apache2/mods-enabled/*.conf # Include all the user configurations: Include /etc/apache2/httpd.conf # Include ports listing Include /etc/apache2/ports.conf # Include generic snippets of statements Include /etc/apache2/conf.d/[^.#]* #Let's have some Icons, shall we? Alias /icons/ "/usr/share/apache2/icons/" Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all # Set up the default error docs. # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # Putting this all together, we can Internationalize error responses. # # We use Alias to redirect any /error/HTTP_.html.var response to # our collection of by-error message multi-language collections. We use # includes to substitute the appropriate text. # # You can modify the messages' appearance without changing any of the # default HTTP_.html.var files by adding the line; # # Alias /error/include/ "/your/include/path/" # # which allows you to create your own set of files by starting with the # /usr/local/apache2/error/include/ files and # copying them to /your/include/path/, even on a per-VirtualHost basis. # Alias /error/ "/usr/share/apache2/error/" AllowOverride None Options IncludesNoExec AddOutputFilter Includes html AddHandler type-map var Order allow,deny Allow from all LanguagePriority en es de fr ForceLanguagePriority Prefer Fallback ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var ErrorDocument 410 /error/HTTP_GONE.html.var ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var ErrorDocument 415 /error/HTTP_SERVICE_UNAVAILABLE.html.var ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var DirectoryIndex index.html index.cgi index.pl index.php index.xhtml # UserDir is now a module #UserDir public_html #UserDir disabled root # # AllowOverride FileInfo AuthConfig Limit # Options Indexes SymLinksIfOwnerMatch IncludesNoExec # AccessFileName .htaccess Order allow,deny Deny from all UseCanonicalName Off TypesConfig /etc/mime.types DefaultType text/plain HostnameLookups Off IndexOptions FancyIndexing VersionSort AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip AddIconByType (TXT,/icons/text.gif) text/* AddIconByType (IMG,/icons/image2.gif) image/* AddIconByType (SND,/icons/sound2.gif) audio/* AddIconByType (VID,/icons/movie.gif) video/* # This really should be .jpg. AddIcon /icons/binary.gif .bin .exe AddIcon /icons/binhex.gif .hqx AddIcon /icons/tar.gif .tar AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip AddIcon /icons/a.gif .ps .ai .eps AddIcon /icons/layout.gif .html .shtml .htm .pdf AddIcon /icons/text.gif .txt AddIcon /icons/c.gif .c AddIcon /icons/p.gif .pl .py AddIcon /icons/f.gif .for AddIcon /icons/dvi.gif .dvi AddIcon /icons/uuencoded.gif .uu AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl AddIcon /icons/tex.gif .tex AddIcon /icons/bomb.gif core AddIcon /icons/back.gif .. AddIcon /icons/hand.right.gif README AddIcon /icons/folder.gif ^^DIRECTORY^^ AddIcon /icons/blank.gif ^^BLANKICON^^ # This is from Matty J's patch. Anyone want to make the icons? #AddIcon /icons/dirsymlink.jpg ^^SYMDIR^^ #AddIcon /icons/symlink.jpg ^^SYMLINK^^ DefaultIcon /icons/unknown.gif ReadmeName README.html HeaderName HEADER.html IndexIgnore .??* *~ *# HEADER* RCS CVS *,t AddEncoding x-compress Z AddEncoding x-gzip gz tgz AddLanguage da .dk AddLanguage nl .nl AddLanguage en .en AddLanguage et .et AddLanguage fr .fr AddLanguage de .de AddLanguage el .el AddLanguage it .it AddLanguage ja .ja AddLanguage pl .po AddLanguage ko .ko AddLanguage pt .pt AddLanguage no .no AddLanguage pt-br .pt-br AddLanguage ltz .ltz AddLanguage ca .ca AddLanguage es .es AddLanguage sv .se AddLanguage cz .cz AddLanguage ru .ru AddLanguage tw .tw AddLanguage zh-tw .tw LanguagePriority en da nl et fr de el it ja ko no pl pt pt-br ltz ca es sv tw #AddDefaultCharset ISO-8859-1 AddCharset ISO-8859-1 .iso8859-1 .latin1 AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen AddCharset ISO-8859-3 .iso8859-3 .latin3 AddCharset ISO-8859-4 .iso8859-4 .latin4 AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk AddCharset ISO-2022-JP .iso2022-jp .jis AddCharset ISO-2022-KR .iso2022-kr .kis AddCharset ISO-2022-CN .iso2022-cn .cis AddCharset Big5 .Big5 .big5 # For russian, more than one charset is used (depends on client, mostly): AddCharset WINDOWS-1251 .cp-1251 .win-1251 AddCharset CP866 .cp866 AddCharset KOI8-r .koi8-r .koi8-ru AddCharset KOI8-ru .koi8-uk .ua AddCharset ISO-10646-UCS-2 .ucs2 AddCharset ISO-10646-UCS-4 .ucs4 AddCharset UTF-8 .utf8 AddCharset GB2312 .gb2312 .gb AddCharset utf-7 .utf7 AddCharset utf-8 .utf8 AddCharset big5 .big5 .b5 AddCharset EUC-TW .euc-tw AddCharset EUC-JP .euc-jp AddCharset EUC-KR .euc-kr AddCharset shift_jis .sjis #AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps AddType application/x-tar .tgz # To use CGI scripts outside /cgi-bin/: # #AddHandler cgi-script .cgi # To use server-parsed HTML files # SetOutputFilter INCLUDES # If you wish to use server-parsed imagemap files, use # #AddHandler imap-file map BrowserMatch "Mozilla/2" nokeepalive BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 BrowserMatch "RealPlayer 4\.0" force-response-1.0 BrowserMatch "Java/1\.0" force-response-1.0 BrowserMatch "JDK/1\.0" force-response-1.0 # # The following directive disables redirects on non-GET requests for # a directory that does not include the trailing slash. This fixes a # problem with Microsoft WebFolders which does not appropriately handle # redirects for folders with DAV methods. # BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully BrowserMatch "^WebDrive" redirect-carefully BrowserMatch "^gnome-vfs" redirect-carefully BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully # Allow server status reports, with the URL of http://servername/server-status # Change the ".your_domain.com" to match your domain to enable. # # # SetHandler server-status # Order deny,allow # Deny from all # Allow from .your_domain.com # # Allow remote server configuration reports, with the URL of # http://servername/server-info (requires that mod_info.c be loaded). # Change the ".your_domain.com" to match your domain to enable. # # # SetHandler server-info # Order deny,allow # Deny from all # Allow from .your_domain.com # # Include the virtual host configurations: Include /etc/apache2/sites-enabled/[^.#]* pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/as3_test.as000066400000000000000000000077741250413007300257610ustar00rootroot00000000000000 import flash.events.MouseEvent; import com.example.programmingas3.playlist.PlayList; import com.example.programmingas3.playlist.Song; import com.example.programmingas3.playlist.SortProperty; // constants for the different "states" of the song form private static const ADD_SONG:uint = 1; private static const SONG_DETAIL:uint = 2; private var playList:PlayList = new PlayList.(); private function initApp():void { // set the initial state of the song form, for adding a new song setFormState(ADD_SONG); // prepopulate the list with a few songs playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"])); playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"])); playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"])); playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"])); songList.dataProvider = playList.songList; } private function sortList(sortField:SortProperty.):void { // Make all the sort type buttons enabled. // The active one will be grayed-out below sortByTitle.selected = false; sortByArtist.selected = false; sortByYear.selected = false; switch (sortField) { case SortProperty.TITLE: sortByTitle.selected = true; break; case SortProperty.ARTIST: sortByArtist.selected = true; break; case SortProperty.YEAR: sortByYear.selected = true; break; } playList.sortList(sortField); refreshList(); } private function refreshList():void { // remember which song was selected var selectedSong:Song = Song(songList.selectedItem); // re-assign the song list as the dataprovider to get the newly sorted list // and force the List control to refresh itself songList.dataProvider = playList.songList; // reset the song selection if (selectedSong != null) { songList.selectedItem = selectedSong; } } private function songSelectionChange():void { if (songList.selectedIndex != -1) { setFormState(SONG_DETAIL); } else { setFormState(ADD_SONG); } } private function addNewSong():void { // gather the values from the form and add the new song var title:String = newSongTitle.text; var artist:String = newSongArtist.text; var year:uint = newSongYear.value; var filename:String = newSongFilename.text; var genres:Array = newSongGenres.selectedItems; playList.addSong(new Song(title, artist, year, filename, genres)); refreshList(); // clear out the "add song" form fields setFormState(ADD_SONG); } private function songListLabel(item:Object):String { return item.toString(); } private function setFormState(state:uint):void { // set the form title and control state switch (state) { case ADD_SONG: formTitle.text = "Add New Song"; // show the submit button submitSongData.visible = true; showAddControlsBtn.visible = false; // clear the form fields newSongTitle.text = ""; newSongArtist.text = ""; newSongYear.value = (new Date()).fullYear; newSongFilename.text = ""; newSongGenres.selectedIndex = -1; // deselect the currently selected song (if any) songList.selectedIndex = -1; break; case SONG_DETAIL: formTitle.text = "Song Details"; // populate the form with the selected item's data var selectedSong:Song = Song(songList.selectedItem); newSongTitle.text = selectedSong.title; newSongArtist.text = selectedSong.artist; newSongYear.value = selectedSong.year; newSongFilename.text = selectedSong.filename; newSongGenres.selectedItems = selectedSong.genres; // hide the submit button submitSongData.visible = false; showAddControlsBtn.visible = true; break; } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/as3_test2.as000066400000000000000000000027371250413007300260350ustar00rootroot00000000000000package ru.dfls.events { import flash.events.Event; import flash.events.ErrorEvent; /** * This event is usually dispatched if some error was thrown from an asynchronous code, i.e. there * is no relevant user stack part to process the error. There is only one type of such event: * ErrorEvent.ERROR which is same as flash.events.ErrorEvent.ERROR. * The only difference between flash.events.ErrorEvent and * ru.dfls.events.ErrorEvent is the capability of the latter to store the underlying cause * (the Error). * * @see flash.events.ErrorEvent * @see Error * @author dragonfly */ public class ErrorEvent extends flash.events.ErrorEvent { public static var ERROR : String = flash.events.ErrorEvent.ERROR; private var _error : Error; public function ErrorEvent(type : String, bubbles : Boolean = false, cancelable : Boolean = false, text : String = "", error : Error = null) { super(type, bubbles, cancelable, text); _error = error; } public function get error() : Error { return _error; } public function set error(value : Error) : void { _error = value; } public override function toString() : String { return formatToString("ErrorEvent", "type", "bubbles", "cancelable", "eventPhase", "text", "error"); } public override function clone() : Event { return new ru.dfls.events.ErrorEvent(type, bubbles, cancelable, text, error); } } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/as3_test3.as000066400000000000000000000001331250413007300260220ustar00rootroot00000000000000protected function remote(method : String, ...args : Array) : Boolean { return true; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/aspx-cs_example000066400000000000000000000011121250413007300266770ustar00rootroot00000000000000<%@ Page Language="C#" %> Sample page
The current time is:
pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/autoit_submit.au3000066400000000000000000000012641250413007300271750ustar00rootroot00000000000000#include ;http://msdn.microsoft.com/en-us/library/Aa752084.aspx $ourl="http://localhost:5000/" $oIE = _IEAttach ($ourl,"url") If @error = $_IEStatus_NoMatch Then $oIE = _IECreate ($ourl & "sample.html") endIf $oForm = _IEFormGetObjByName ($oIE, "form1") ;username, call DOM directly $oIE.document.getElementById("username").value="helloAutoIT" ;state select $oSelect = _IEFormElementGetObjByName ($oForm, "state") _IEFormElementOptionSelect ($oSelect, "S2", 1, "byText") ;options raido _IEFormElementRadioSelect($oForm, "2nd", "type", 1, "byValue") ConsoleWrite(@Error) Sleep(10000) _IEFormSubmit($oForm, 0) _IELoadWait($oIE) Sleep(60000) _IEQuit($oIE) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/badcase.java000066400000000000000000000001061250413007300261120ustar00rootroot00000000000000// this used to take ages void foo() throws xxxxxxxxxxxxxxxxxxxxxx{ } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/batchfile.bat000066400000000000000000000017301250413007300263020ustar00rootroot00000000000000rem this is a demo file. @rem @echo off call c:\temp.bat somearg call :lab somearg rem This next one is wrong in the vim lexer! call c:temp.bat echo "Hi!" echo hi echo on echo off echo. @echo off if exist *.log echo The log file has arrived. rem These are all escapes, also done incorrectly by the vim lexer echo ^^ ^> ^< ^| x=beginning setlocal x = new text endlocal echo testrem x echo test rem x for %%var in (*.jpg) do echo %%var for /D %%var in (a b c) do echo %%var for /R C:\temp %%var in (*.jpg) do iexplore.exe %%var rem Vim has this one wrong too. for /L %%var in (10,-1,1) do echo %%var for /F %%var in ("hi!") do echo %%var for /F "eol=c,skip=1,usebackq" %%var in (`command`) do echo %%var %~l %~fl %~dl %~pl %~nl %~xl %~sl %~al %~tl %~zl %~$PATH:l %~dpl %~dp$PATH:l %~ftzal echo some file ?! > somefile.txt set PATH=%PATH%;c:\windows goto answer%errorlevel% :answer0 echo Hi it's zero :answer1 echo New if exist a del a else echo A is missing! pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/bigtest.nsi000066400000000000000000000167571250413007300260640ustar00rootroot00000000000000; bigtest.nsi ; ; This script attempts to test most of the functionality of the NSIS exehead. ;-------------------------------- !ifdef HAVE_UPX !packhdr tmp.dat "upx\upx -9 tmp.dat" !endif !ifdef NOCOMPRESS SetCompress off !endif ;-------------------------------- Name "BigNSISTest" Caption "NSIS Big Test" Icon "${NSISDIR}\Contrib\Graphics\Icons\nsis1-install.ico" OutFile "bigtest.exe" SetDateSave on SetDatablockOptimize on CRCCheck on SilentInstall normal BGGradient 000000 800000 FFFFFF InstallColors FF8080 000030 XPStyle on InstallDir "$PROGRAMFILES\NSISTest\BigNSISTest" InstallDirRegKey HKLM "Software\NSISTest\BigNSISTest" "Install_Dir" CheckBitmap "${NSISDIR}\Contrib\Graphics\Checks\classic-cross.bmp" LicenseText "A test text, make sure it's all there" LicenseData "bigtest.nsi" RequestExecutionLevel admin ;-------------------------------- Page license Page components Page directory Page instfiles UninstPage uninstConfirm UninstPage instfiles ;-------------------------------- !ifndef NOINSTTYPES ; only if not defined InstType "Most" InstType "Full" InstType "More" InstType "Base" ;InstType /NOCUSTOM ;InstType /COMPONENTSONLYONCUSTOM !endif AutoCloseWindow false ShowInstDetails show ;-------------------------------- Section "" ; empty string makes it hidden, so would starting with - ; write reg info StrCpy $1 "POOOOOOOOOOOP" DetailPrint "I like to be able to see what is going on (debug) $1" WriteRegStr HKLM SOFTWARE\NSISTest\BigNSISTest "Install_Dir" "$INSTDIR" ; write uninstall strings WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\BigNSISTest" "DisplayName" "BigNSISTest (remove only)" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\BigNSISTest" "UninstallString" '"$INSTDIR\bt-uninst.exe"' SetOutPath $INSTDIR File /a "silent.nsi" CreateDirectory "$INSTDIR\MyProjectFamily\MyProject" ; 2 recursively create a directory for fun. WriteUninstaller "bt-uninst.exe" Nop ; for fun SectionEnd Section "TempTest" SectionIn 1 2 3 Start: MessageBox MB_OK "Start:" MessageBox MB_YESNO "Goto MyLabel" IDYES MyLabel MessageBox MB_OK "Right before MyLabel:" MyLabel: MessageBox MB_OK "MyLabel:" MessageBox MB_OK "Right after MyLabel:" MessageBox MB_YESNO "Goto Start:?" IDYES Start SectionEnd SectionGroup /e SectionGroup1 Section "Test Registry/INI functions" SectionIn 1 4 3 WriteRegStr HKLM SOFTWARE\NSISTest\BigNSISTest "StrTest_INSTDIR" "$INSTDIR" WriteRegDword HKLM SOFTWARE\NSISTest\BigNSISTest "DwordTest_0xDEADBEEF" 0xdeadbeef WriteRegDword HKLM SOFTWARE\NSISTest\BigNSISTest "DwordTest_123456" 123456 WriteRegDword HKLM SOFTWARE\NSISTest\BigNSISTest "DwordTest_0123" 0123 WriteRegBin HKLM SOFTWARE\NSISTest\BigNSISTest "BinTest_deadbeef01f00dbeef" "DEADBEEF01F00DBEEF" StrCpy $8 "$SYSDIR\IniTest" WriteINIStr "$INSTDIR\test.ini" "MySection" "Value1" $8 WriteINIStr "$INSTDIR\test.ini" "MySectionIni" "Value1" $8 WriteINIStr "$INSTDIR\test.ini" "MySectionIni" "Value2" $8 WriteINIStr "$INSTDIR\test.ini" "IniOn" "Value1" $8 Call MyFunctionTest DeleteINIStr "$INSTDIR\test.ini" "IniOn" "Value1" DeleteINISec "$INSTDIR\test.ini" "MySectionIni" ReadINIStr $1 "$INSTDIR\test.ini" "MySectionIni" "Value1" StrCmp $1 "" INIDelSuccess MessageBox MB_OK "DeleteINISec failed" INIDelSuccess: ClearErrors ReadRegStr $1 HKCR "software\microsoft" xyz_cc_does_not_exist IfErrors 0 NoError MessageBox MB_OK "could not read from HKCR\software\microsoft\xyz_cc_does_not_exist" Goto ErrorYay NoError: MessageBox MB_OK "read '$1' from HKCR\software\microsoft\xyz_cc_does_not_exist" ErrorYay: SectionEnd Section "Test CreateShortCut" SectionIn 1 2 3 Call CSCTest SectionEnd SectionGroup Group2 Section "Test Branching" BeginTestSection: SectionIn 1 2 3 SetOutPath $INSTDIR IfFileExists "$INSTDIR\LogicLib.nsi" 0 BranchTest69 MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to overwrite $INSTDIR\LogicLib.nsi?" IDNO NoOverwrite ; skipped if file doesn't exist BranchTest69: SetOverwrite ifnewer ; NOT AN INSTRUCTION, NOT COUNTED IN SKIPPINGS NoOverwrite: File "LogicLib.nsi" ; skipped if answered no SetOverwrite try ; NOT AN INSTRUCTION, NOT COUNTED IN SKIPPINGS MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to skip the rest of this section?" IDYES EndTestBranch MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to go back to the beginning of this section?" IDYES BeginTestSection MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to hide the installer and wait five seconds?" IDNO NoHide HideWindow Sleep 5000 BringToFront NoHide: MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to call the function 5 times?" IDNO NoRecurse StrCpy $1 "x" LoopTest: Call myfunc StrCpy $1 "x$1" StrCmp $1 "xxxxxx" 0 LoopTest NoRecurse: EndTestBranch: SectionEnd SectionGroupEnd Section "Test CopyFiles" SectionIn 1 2 3 SetOutPath $INSTDIR\cpdest CopyFiles "$WINDIR\*.ini" "$INSTDIR\cpdest" 0 SectionEnd SectionGroupEnd Section "Test Exec functions" TESTIDX SectionIn 1 2 3 SearchPath $1 notepad.exe MessageBox MB_OK "notepad.exe=$1" Exec '"$1"' ExecShell "open" '"$INSTDIR"' Sleep 500 BringToFront SectionEnd Section "Test ActiveX control registration" SectionIn 2 UnRegDLL "$SYSDIR\spin32.ocx" Sleep 1000 RegDLL "$SYSDIR\spin32.ocx" Sleep 1000 SectionEnd ;-------------------------------- Function "CSCTest" CreateDirectory "$SMPROGRAMS\Big NSIS Test" SetOutPath $INSTDIR ; for working directory CreateShortCut "$SMPROGRAMS\Big NSIS Test\Uninstall BIG NSIS Test.lnk" "$INSTDIR\bt-uninst.exe" ; use defaults for parameters, icon, etc. ; this one will use notepad's icon, start it minimized, and give it a hotkey (of Ctrl+Shift+Q) CreateShortCut "$SMPROGRAMS\Big NSIS Test\silent.nsi.lnk" "$INSTDIR\silent.nsi" "" "$WINDIR\notepad.exe" 0 SW_SHOWMINIMIZED CONTROL|SHIFT|Q CreateShortCut "$SMPROGRAMS\Big NSIS Test\TheDir.lnk" "$INSTDIR\" "" "" 0 SW_SHOWMAXIMIZED CONTROL|SHIFT|Z FunctionEnd Function myfunc StrCpy $2 "MyTestVar=$1" MessageBox MB_OK "myfunc: $2" FunctionEnd Function MyFunctionTest ReadINIStr $1 "$INSTDIR\test.ini" "MySectionIni" "Value1" StrCmp $1 $8 NoFailedMsg MessageBox MB_OK "WriteINIStr failed" NoFailedMsg: FunctionEnd Function .onSelChange SectionGetText ${TESTIDX} $0 StrCmp $0 "" e SectionSetText ${TESTIDX} "" Goto e2 e: SectionSetText ${TESTIDX} "TextInSection" e2: FunctionEnd ;-------------------------------- ; Uninstaller UninstallText "This will uninstall example2. Hit next to continue." UninstallIcon "${NSISDIR}\Contrib\Graphics\Icons\nsis1-uninstall.ico" Section "Uninstall" DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\BigNSISTest" DeleteRegKey HKLM "SOFTWARE\NSISTest\BigNSISTest" Delete "$INSTDIR\silent.nsi" Delete "$INSTDIR\LogicLib.nsi" Delete "$INSTDIR\bt-uninst.exe" Delete "$INSTDIR\test.ini" Delete "$SMPROGRAMS\Big NSIS Test\*.*" RMDir "$SMPROGRAMS\BiG NSIS Test" MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to remove the directory $INSTDIR\cpdest?" IDNO NoDelete Delete "$INSTDIR\cpdest\*.*" RMDir "$INSTDIR\cpdest" ; skipped if no NoDelete: RMDir "$INSTDIR\MyProjectFamily\MyProject" RMDir "$INSTDIR\MyProjectFamily" RMDir "$INSTDIR" IfFileExists "$INSTDIR" 0 NoErrorMsg MessageBox MB_OK "Note: $INSTDIR could not be removed!" IDOK 0 ; skipped if file doesn't exist NoErrorMsg: SectionEnd pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/boot-9.scm000066400000000000000000001314401250413007300255100ustar00rootroot00000000000000;;; installed-scm-file ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2, or (at your option) ;;;; any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this software; see the file COPYING. If not, write to ;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ;;;; Boston, MA 02111-1307 USA ;;;; ;;;; As a special exception, the Free Software Foundation gives permission ;;;; for additional uses of the text contained in its release of GUILE. ;;;; ;;;; The exception is that, if you link the GUILE library with other files ;;;; to produce an executable, this does not by itself cause the ;;;; resulting executable to be covered by the GNU General Public License. ;;;; Your use of that executable is in no way restricted on account of ;;;; linking the GUILE library code into it. ;;;; ;;;; This exception does not however invalidate any other reasons why ;;;; the executable file might be covered by the GNU General Public License. ;;;; ;;;; This exception applies only to the code released by the ;;;; Free Software Foundation under the name GUILE. If you copy ;;;; code from other Free Software Foundation releases into a copy of ;;;; GUILE, as the General Public License permits, the exception does ;;;; not apply to the code that you add in this way. To avoid misleading ;;;; anyone as to the status of such modified files, you must delete ;;;; this exception notice from them. ;;;; ;;;; If you write modifications of your own for GUILE, it is your choice ;;;; whether to permit this exception to apply to your modifications. ;;;; If you do not wish that, delete this exception notice. ;;;; ;;; Commentary: ;;; This file is the first thing loaded into Guile. It adds many mundane ;;; definitions and a few that are interesting. ;;; ;;; The module system (hence the hierarchical namespace) are defined in this ;;; file. ;;; ;;; Code: ;;; {Deprecation} ;;; ;; We don't have macros here, but we do want to define ;; `begin-deprecated' early. (define begin-deprecated (procedure->memoizing-macro (lambda (exp env) (if (include-deprecated-features) `(begin ,@(cdr exp)) `#f)))) ;;; {Features} ;; (define (provide sym) (if (not (memq sym *features*)) (set! *features* (cons sym *features*)))) ;;; Return #t iff FEATURE is available to this Guile interpreter. ;;; In SLIB, provided? also checks to see if the module is available. ;;; We should do that too, but don't. (define (provided? feature) (and (memq feature *features*) #t)) (begin-deprecated (define (feature? sym) (issue-deprecation-warning "`feature?' is deprecated. Use `provided?' instead.") (provided? sym))) ;;; let format alias simple-format until the more complete version is loaded (define format simple-format) ;;; {R4RS compliance} (primitive-load-path "ice-9/r4rs.scm") ;;; {Simple Debugging Tools} ;; ;; peek takes any number of arguments, writes them to the ;; current ouput port, and returns the last argument. ;; It is handy to wrap around an expression to look at ;; a value each time is evaluated, e.g.: ;; ;; (+ 10 (troublesome-fn)) ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn))) ;; (define (peek . stuff) (newline) (display ";;; ") (write stuff) (newline) (car (last-pair stuff))) (define pk peek) (define (warn . stuff) (with-output-to-port (current-error-port) (lambda () (newline) (display ";;; WARNING ") (display stuff) (newline) (car (last-pair stuff))))) ;;; {Trivial Functions} ;;; (define (identity x) x) (define (1+ n) (+ n 1)) (define (1- n) (+ n -1)) (define (and=> value procedure) (and value (procedure value))) (define (make-hash-table k) (make-vector k '())) (begin-deprecated (define (id x) (issue-deprecation-warning "`id' is deprecated. Use `identity' instead.") (identity x)) (define (-1+ n) (issue-deprecation-warning "`-1+' is deprecated. Use `1-' instead.") (1- n)) (define (return-it . args) (issue-deprecation-warning "`return-it' is deprecated. Use `noop' instead.") (apply noop args))) ;;; apply-to-args is functionally redundant with apply and, worse, ;;; is less general than apply since it only takes two arguments. ;;; ;;; On the other hand, apply-to-args is a syntacticly convenient way to ;;; perform binding in many circumstances when the "let" family of ;;; of forms don't cut it. E.g.: ;;; ;;; (apply-to-args (return-3d-mouse-coords) ;;; (lambda (x y z) ;;; ...)) ;;; (define (apply-to-args args fn) (apply fn args)) ;;; {Integer Math} ;;; (define (ipow-by-squaring x k acc proc) (cond ((zero? k) acc) ((= 1 k) (proc acc x)) (else (ipow-by-squaring (proc x x) (quotient k 2) (if (even? k) acc (proc acc x)) proc)))) (begin-deprecated (define (string-character-length s) (issue-deprecation-warning "`string-character-length' is deprecated. Use `string-length' instead.") (string-length s)) (define (flags . args) (issue-deprecation-warning "`flags' is deprecated. Use `logior' instead.") (apply logior args))) ;;; {Symbol Properties} ;;; (define (symbol-property sym prop) (let ((pair (assoc prop (symbol-pref sym)))) (and pair (cdr pair)))) (define (set-symbol-property! sym prop val) (let ((pair (assoc prop (symbol-pref sym)))) (if pair (set-cdr! pair val) (symbol-pset! sym (acons prop val (symbol-pref sym)))))) (define (symbol-property-remove! sym prop) (let ((pair (assoc prop (symbol-pref sym)))) (if pair (symbol-pset! sym (delq! pair (symbol-pref sym)))))) ;;; {General Properties} ;;; ;; This is a more modern interface to properties. It will replace all ;; other property-like things eventually. (define (make-object-property) (let ((prop (primitive-make-property #f))) (make-procedure-with-setter (lambda (obj) (primitive-property-ref prop obj)) (lambda (obj val) (primitive-property-set! prop obj val))))) ;;; {Arrays} ;;; (if (provided? 'array) (primitive-load-path "ice-9/arrays.scm")) ;;; {Keywords} ;;; (define (symbol->keyword symbol) (make-keyword-from-dash-symbol (symbol-append '- symbol))) (define (keyword->symbol kw) (let ((sym (symbol->string (keyword-dash-symbol kw)))) (string->symbol (substring sym 1 (string-length sym))))) (define (kw-arg-ref args kw) (let ((rem (member kw args))) (and rem (pair? (cdr rem)) (cadr rem)))) ;;; {Structs} (define (struct-layout s) (struct-ref (struct-vtable s) vtable-index-layout)) ;;; Environments (define the-environment (procedure->syntax (lambda (x e) e))) (define the-root-environment (the-environment)) (define (environment-module env) (let ((closure (and (pair? env) (car (last-pair env))))) (and closure (procedure-property closure 'module)))) ;;; {Records} ;;; ;; Printing records: by default, records are printed as ;; ;; # ;; ;; You can change that by giving a custom printing function to ;; MAKE-RECORD-TYPE (after the list of field symbols). This function ;; will be called like ;; ;; ( object port) ;; ;; It should print OBJECT to PORT. (define (inherit-print-state old-port new-port) (if (get-print-state old-port) (port-with-print-state new-port (get-print-state old-port)) new-port)) ;; 0: type-name, 1: fields (define record-type-vtable (make-vtable-vtable "prpr" 0 (lambda (s p) (cond ((eq? s record-type-vtable) (display "#" p)) (else (display "#" p)))))) (define (record-type? obj) (and (struct? obj) (eq? record-type-vtable (struct-vtable obj)))) (define (make-record-type type-name fields . opt) (let ((printer-fn (and (pair? opt) (car opt)))) (let ((struct (make-struct record-type-vtable 0 (make-struct-layout (apply string-append (map (lambda (f) "pw") fields))) (or printer-fn (lambda (s p) (display "#<" p) (display type-name p) (let loop ((fields fields) (off 0)) (cond ((not (null? fields)) (display " " p) (display (car fields) p) (display ": " p) (display (struct-ref s off) p) (loop (cdr fields) (+ 1 off))))) (display ">" p))) type-name (copy-tree fields)))) ;; Temporary solution: Associate a name to the record type descriptor ;; so that the object system can create a wrapper class for it. (set-struct-vtable-name! struct (if (symbol? type-name) type-name (string->symbol type-name))) struct))) (define (record-type-name obj) (if (record-type? obj) (struct-ref obj vtable-offset-user) (error 'not-a-record-type obj))) (define (record-type-fields obj) (if (record-type? obj) (struct-ref obj (+ 1 vtable-offset-user)) (error 'not-a-record-type obj))) (define (record-constructor rtd . opt) (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd)))) (local-eval `(lambda ,field-names (make-struct ',rtd 0 ,@(map (lambda (f) (if (memq f field-names) f #f)) (record-type-fields rtd)))) the-root-environment))) (define (record-predicate rtd) (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj))))) (define (record-accessor rtd field-name) (let* ((pos (list-index (record-type-fields rtd) field-name))) (if (not pos) (error 'no-such-field field-name)) (local-eval `(lambda (obj) (and (eq? ',rtd (record-type-descriptor obj)) (struct-ref obj ,pos))) the-root-environment))) (define (record-modifier rtd field-name) (let* ((pos (list-index (record-type-fields rtd) field-name))) (if (not pos) (error 'no-such-field field-name)) (local-eval `(lambda (obj val) (and (eq? ',rtd (record-type-descriptor obj)) (struct-set! obj ,pos val))) the-root-environment))) (define (record? obj) (and (struct? obj) (record-type? (struct-vtable obj)))) (define (record-type-descriptor obj) (if (struct? obj) (struct-vtable obj) (error 'not-a-record obj))) (provide 'record) ;;; {Booleans} ;;; (define (->bool x) (not (not x))) ;;; {Symbols} ;;; (define (symbol-append . args) (string->symbol (apply string-append (map symbol->string args)))) (define (list->symbol . args) (string->symbol (apply list->string args))) (define (symbol . args) (string->symbol (apply string args))) ;;; {Lists} ;;; (define (list-index l k) (let loop ((n 0) (l l)) (and (not (null? l)) (if (eq? (car l) k) n (loop (+ n 1) (cdr l)))))) (define (make-list n . init) (if (pair? init) (set! init (car init))) (let loop ((answer '()) (n n)) (if (<= n 0) answer (loop (cons init answer) (- n 1))))) ;;; {and-map and or-map} ;;; ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...) ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...) ;;; ;; and-map f l ;; ;; Apply f to successive elements of l until exhaustion or f returns #f. ;; If returning early, return #f. Otherwise, return the last value returned ;; by f. If f has never been called because l is empty, return #t. ;; (define (and-map f lst) (let loop ((result #t) (l lst)) (and result (or (and (null? l) result) (loop (f (car l)) (cdr l)))))) ;; or-map f l ;; ;; Apply f to successive elements of l until exhaustion or while f returns #f. ;; If returning early, return the return value of f. ;; (define (or-map f lst) (let loop ((result #f) (l lst)) (or result (and (not (null? l)) (loop (f (car l)) (cdr l)))))) (if (provided? 'posix) (primitive-load-path "ice-9/posix.scm")) (if (provided? 'socket) (primitive-load-path "ice-9/networking.scm")) (define file-exists? (if (provided? 'posix) (lambda (str) (->bool (false-if-exception (stat str)))) (lambda (str) (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ)) (lambda args #f)))) (if port (begin (close-port port) #t) #f))))) (define file-is-directory? (if (provided? 'posix) (lambda (str) (eq? (stat:type (stat str)) 'directory)) (lambda (str) (let ((port (catch 'system-error (lambda () (open-file (string-append str "/.") OPEN_READ)) (lambda args #f)))) (if port (begin (close-port port) #t) #f))))) (define (has-suffix? str suffix) (let ((sufl (string-length suffix)) (sl (string-length str))) (and (> sl sufl) (string=? (substring str (- sl sufl) sl) suffix)))) (define (system-error-errno args) (if (eq? (car args) 'system-error) (car (list-ref args 4)) #f)) ;;; {Error Handling} ;;; (define (error . args) (save-stack) (if (null? args) (scm-error 'misc-error #f "?" #f #f) (let loop ((msg "~A") (rest (cdr args))) (if (not (null? rest)) (loop (string-append msg " ~S") (cdr rest)) (scm-error 'misc-error #f msg args #f))))) ;; bad-throw is the hook that is called upon a throw to a an unhandled ;; key (unless the throw has four arguments, in which case ;; it's usually interpreted as an error throw.) ;; If the key has a default handler (a throw-handler-default property), ;; it is applied to the throw. ;; (define (bad-throw key . args) (let ((default (symbol-property key 'throw-handler-default))) (or (and default (apply default key args)) (apply error "unhandled-exception:" key args)))) (define (tm:sec obj) (vector-ref obj 0)) (define (tm:min obj) (vector-ref obj 1)) (define (tm:hour obj) (vector-ref obj 2)) (define (tm:mday obj) (vector-ref obj 3)) (define (tm:mon obj) (vector-ref obj 4)) (define (tm:year obj) (vector-ref obj 5)) (define (tm:wday obj) (vector-ref obj 6)) (define (tm:yday obj) (vector-ref obj 7)) (define (tm:isdst obj) (vector-ref obj 8)) (define (tm:gmtoff obj) (vector-ref obj 9)) (define (tm:zone obj) (vector-ref obj 10)) (define (set-tm:sec obj val) (vector-set! obj 0 val)) (define (set-tm:min obj val) (vector-set! obj 1 val)) (define (set-tm:hour obj val) (vector-set! obj 2 val)) (define (set-tm:mday obj val) (vector-set! obj 3 val)) (define (set-tm:mon obj val) (vector-set! obj 4 val)) (define (set-tm:year obj val) (vector-set! obj 5 val)) (define (set-tm:wday obj val) (vector-set! obj 6 val)) (define (set-tm:yday obj val) (vector-set! obj 7 val)) (define (set-tm:isdst obj val) (vector-set! obj 8 val)) (define (set-tm:gmtoff obj val) (vector-set! obj 9 val)) (define (set-tm:zone obj val) (vector-set! obj 10 val)) (define (tms:clock obj) (vector-ref obj 0)) (define (tms:utime obj) (vector-ref obj 1)) (define (tms:stime obj) (vector-ref obj 2)) (define (tms:cutime obj) (vector-ref obj 3)) (define (tms:cstime obj) (vector-ref obj 4)) (define file-position ftell) (define (file-set-position port offset . whence) (let ((whence (if (eq? whence '()) SEEK_SET (car whence)))) (seek port offset whence))) (define (move->fdes fd/port fd) (cond ((integer? fd/port) (dup->fdes fd/port fd) (close fd/port) fd) (else (primitive-move->fdes fd/port fd) (set-port-revealed! fd/port 1) fd/port))) (define (release-port-handle port) (let ((revealed (port-revealed port))) (if (> revealed 0) (set-port-revealed! port (- revealed 1))))) (define (dup->port port/fd mode . maybe-fd) (let ((port (fdopen (apply dup->fdes port/fd maybe-fd) mode))) (if (pair? maybe-fd) (set-port-revealed! port 1)) port)) (define (dup->inport port/fd . maybe-fd) (apply dup->port port/fd "r" maybe-fd)) (define (dup->outport port/fd . maybe-fd) (apply dup->port port/fd "w" maybe-fd)) (define (dup port/fd . maybe-fd) (if (integer? port/fd) (apply dup->fdes port/fd maybe-fd) (apply dup->port port/fd (port-mode port/fd) maybe-fd))) (define (duplicate-port port modes) (dup->port port modes)) (define (fdes->inport fdes) (let loop ((rest-ports (fdes->ports fdes))) (cond ((null? rest-ports) (let ((result (fdopen fdes "r"))) (set-port-revealed! result 1) result)) ((input-port? (car rest-ports)) (set-port-revealed! (car rest-ports) (+ (port-revealed (car rest-ports)) 1)) (car rest-ports)) (else (loop (cdr rest-ports)))))) (define (fdes->outport fdes) (let loop ((rest-ports (fdes->ports fdes))) (cond ((null? rest-ports) (let ((result (fdopen fdes "w"))) (set-port-revealed! result 1) result)) ((output-port? (car rest-ports)) (set-port-revealed! (car rest-ports) (+ (port-revealed (car rest-ports)) 1)) (car rest-ports)) (else (loop (cdr rest-ports)))))) (define (port->fdes port) (set-port-revealed! port (+ (port-revealed port) 1)) (fileno port)) (define (setenv name value) (if value (putenv (string-append name "=" value)) (putenv name))) ;;; {Load Paths} ;;; ;;; Here for backward compatability ;; (define scheme-file-suffix (lambda () ".scm")) (define (in-vicinity vicinity file) (let ((tail (let ((len (string-length vicinity))) (if (zero? len) #f (string-ref vicinity (- len 1)))))) (string-append vicinity (if (or (not tail) (eq? tail #\/)) "" "/") file))) ;;; {Help for scm_shell} ;;; The argument-processing code used by Guile-based shells generates ;;; Scheme code based on the argument list. This page contains help ;;; functions for the code it generates. (define (command-line) (program-arguments)) ;; This is mostly for the internal use of the code generated by ;; scm_compile_shell_switches. (define (load-user-init) (let* ((home (or (getenv "HOME") (false-if-exception (passwd:dir (getpwuid (getuid)))) "/")) ;; fallback for cygwin etc. (init-file (in-vicinity home ".guile"))) (if (file-exists? init-file) (primitive-load init-file)))) ;;; {Loading by paths} ;;; Load a Scheme source file named NAME, searching for it in the ;;; directories listed in %load-path, and applying each of the file ;;; name extensions listed in %load-extensions. (define (load-from-path name) (start-stack 'load-stack (primitive-load-path name))) ;;; {Transcendental Functions} ;;; ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM. ;;; Written by Jerry D. Hedden, (C) FSF. ;;; See the file `COPYING' for terms applying to this program. ;;; (define (exp z) (if (real? z) ($exp z) (make-polar ($exp (real-part z)) (imag-part z)))) (define (log z) (if (and (real? z) (>= z 0)) ($log z) (make-rectangular ($log (magnitude z)) (angle z)))) (define (sqrt z) (if (real? z) (if (negative? z) (make-rectangular 0 ($sqrt (- z))) ($sqrt z)) (make-polar ($sqrt (magnitude z)) (/ (angle z) 2)))) (define expt (let ((integer-expt integer-expt)) (lambda (z1 z2) (cond ((integer? z2) (if (negative? z2) (/ 1 (integer-expt z1 (- z2))) (integer-expt z1 z2))) ((and (real? z2) (real? z1) (>= z1 0)) ($expt z1 z2)) (else (exp (* z2 (log z1)))))))) (define (sinh z) (if (real? z) ($sinh z) (let ((x (real-part z)) (y (imag-part z))) (make-rectangular (* ($sinh x) ($cos y)) (* ($cosh x) ($sin y)))))) (define (cosh z) (if (real? z) ($cosh z) (let ((x (real-part z)) (y (imag-part z))) (make-rectangular (* ($cosh x) ($cos y)) (* ($sinh x) ($sin y)))))) (define (tanh z) (if (real? z) ($tanh z) (let* ((x (* 2 (real-part z))) (y (* 2 (imag-part z))) (w (+ ($cosh x) ($cos y)))) (make-rectangular (/ ($sinh x) w) (/ ($sin y) w))))) (define (asinh z) (if (real? z) ($asinh z) (log (+ z (sqrt (+ (* z z) 1)))))) (define (acosh z) (if (and (real? z) (>= z 1)) ($acosh z) (log (+ z (sqrt (- (* z z) 1)))))) (define (atanh z) (if (and (real? z) (> z -1) (< z 1)) ($atanh z) (/ (log (/ (+ 1 z) (- 1 z))) 2))) (define (sin z) (if (real? z) ($sin z) (let ((x (real-part z)) (y (imag-part z))) (make-rectangular (* ($sin x) ($cosh y)) (* ($cos x) ($sinh y)))))) (define (cos z) (if (real? z) ($cos z) (let ((x (real-part z)) (y (imag-part z))) (make-rectangular (* ($cos x) ($cosh y)) (- (* ($sin x) ($sinh y))))))) (define (tan z) (if (real? z) ($tan z) (let* ((x (* 2 (real-part z))) (y (* 2 (imag-part z))) (w (+ ($cos x) ($cosh y)))) (make-rectangular (/ ($sin x) w) (/ ($sinh y) w))))) (define (asin z) (if (and (real? z) (>= z -1) (<= z 1)) ($asin z) (* -i (asinh (* +i z))))) (define (acos z) (if (and (real? z) (>= z -1) (<= z 1)) ($acos z) (+ (/ (angle -1) 2) (* +i (asinh (* +i z)))))) (define (atan z . y) (if (null? y) (if (real? z) ($atan z) (/ (log (/ (- +i z) (+ +i z))) +2i)) ($atan2 z (car y)))) (define (log10 arg) (/ (log arg) (log 10))) ;;; {Reader Extensions} ;;; ;;; Reader code for various "#c" forms. ;;; (read-hash-extend #\' (lambda (c port) (read port))) (define read-eval? (make-fluid)) (fluid-set! read-eval? #f) (read-hash-extend #\. (lambda (c port) (if (fluid-ref read-eval?) (eval (read port) (interaction-environment)) (error "#. read expansion found and read-eval? is #f.")))) ;;; {Command Line Options} ;;; (define (get-option argv kw-opts kw-args return) (cond ((null? argv) (return #f #f argv)) ((or (not (eq? #\- (string-ref (car argv) 0))) (eq? (string-length (car argv)) 1)) (return 'normal-arg (car argv) (cdr argv))) ((eq? #\- (string-ref (car argv) 1)) (let* ((kw-arg-pos (or (string-index (car argv) #\=) (string-length (car argv)))) (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos))) (kw-opt? (member kw kw-opts)) (kw-arg? (member kw kw-args)) (arg (or (and (not (eq? kw-arg-pos (string-length (car argv)))) (substring (car argv) (+ kw-arg-pos 1) (string-length (car argv)))) (and kw-arg? (begin (set! argv (cdr argv)) (car argv)))))) (if (or kw-opt? kw-arg?) (return kw arg (cdr argv)) (return 'usage-error kw (cdr argv))))) (else (let* ((char (substring (car argv) 1 2)) (kw (symbol->keyword char))) (cond ((member kw kw-opts) (let* ((rest-car (substring (car argv) 2 (string-length (car argv)))) (new-argv (if (= 0 (string-length rest-car)) (cdr argv) (cons (string-append "-" rest-car) (cdr argv))))) (return kw #f new-argv))) ((member kw kw-args) (let* ((rest-car (substring (car argv) 2 (string-length (car argv)))) (arg (if (= 0 (string-length rest-car)) (cadr argv) rest-car)) (new-argv (if (= 0 (string-length rest-car)) (cddr argv) (cdr argv)))) (return kw arg new-argv))) (else (return 'usage-error kw argv))))))) (define (for-next-option proc argv kw-opts kw-args) (let loop ((argv argv)) (get-option argv kw-opts kw-args (lambda (opt opt-arg argv) (and opt (proc opt opt-arg argv loop)))))) (define (display-usage-report kw-desc) (for-each (lambda (kw) (or (eq? (car kw) #t) (eq? (car kw) 'else) (let* ((opt-desc kw) (help (cadr opt-desc)) (opts (car opt-desc)) (opts-proper (if (string? (car opts)) (cdr opts) opts)) (arg-name (if (string? (car opts)) (string-append "<" (car opts) ">") "")) (left-part (string-append (with-output-to-string (lambda () (map (lambda (x) (display (keyword->symbol x)) (display " ")) opts-proper))) arg-name)) (middle-part (if (and (< (string-length left-part) 30) (< (string-length help) 40)) (make-string (- 30 (string-length left-part)) #\ ) "\n\t"))) (display left-part) (display middle-part) (display help) (newline)))) kw-desc)) (define (transform-usage-lambda cases) (let* ((raw-usage (delq! 'else (map car cases))) (usage-sans-specials (map (lambda (x) (or (and (not (list? x)) x) (and (symbol? (car x)) #t) (and (boolean? (car x)) #t) x)) raw-usage)) (usage-desc (delq! #t usage-sans-specials)) (kw-desc (map car usage-desc)) (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc))) (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc))) (transmogrified-cases (map (lambda (case) (cons (let ((opts (car case))) (if (or (boolean? opts) (eq? 'else opts)) opts (cond ((symbol? (car opts)) opts) ((boolean? (car opts)) opts) ((string? (caar opts)) (cdar opts)) (else (car opts))))) (cdr case))) cases))) `(let ((%display-usage (lambda () (display-usage-report ',usage-desc)))) (lambda (%argv) (let %next-arg ((%argv %argv)) (get-option %argv ',kw-opts ',kw-args (lambda (%opt %arg %new-argv) (case %opt ,@ transmogrified-cases)))))))) ;;; {Low Level Modules} ;;; ;;; These are the low level data structures for modules. ;;; ;;; !!! warning: The interface to lazy binder procedures is going ;;; to be changed in an incompatible way to permit all the basic ;;; module ops to be virtualized. ;;; ;;; (make-module size use-list lazy-binding-proc) => module ;;; module-{obarray,uses,binder}[|-set!] ;;; (module? obj) => [#t|#f] ;;; (module-locally-bound? module symbol) => [#t|#f] ;;; (module-bound? module symbol) => [#t|#f] ;;; (module-symbol-locally-interned? module symbol) => [#t|#f] ;;; (module-symbol-interned? module symbol) => [#t|#f] ;;; (module-local-variable module symbol) => [# | #f] ;;; (module-variable module symbol) => [# | #f] ;;; (module-symbol-binding module symbol opt-value) ;;; => [ | opt-value | an error occurs ] ;;; (module-make-local-var! module symbol) => # ;;; (module-add! module symbol var) => unspecified ;;; (module-remove! module symbol) => unspecified ;;; (module-for-each proc module) => unspecified ;;; (make-scm-module) => module ; a lazy copy of the symhash module ;;; (set-current-module module) => unspecified ;;; (current-module) => # ;;; ;;; ;;; {Printing Modules} ;; This is how modules are printed. You can re-define it. ;; (Redefining is actually more complicated than simply redefining ;; %print-module because that would only change the binding and not ;; the value stored in the vtable that determines how record are ;; printed. Sigh.) (define (%print-module mod port) ; unused args: depth length style table) (display "#<" port) (display (or (module-kind mod) "module") port) (let ((name (module-name mod))) (if name (begin (display " " port) (display name port)))) (display " " port) (display (number->string (object-address mod) 16) port) (display ">" port)) ;; module-type ;; ;; A module is characterized by an obarray in which local symbols ;; are interned, a list of modules, "uses", from which non-local ;; bindings can be inherited, and an optional lazy-binder which ;; is a (CLOSURE module symbol) which, as a last resort, can provide ;; bindings that would otherwise not be found locally in the module. ;; ;; NOTE: If you change here, you also need to change libguile/modules.h. ;; (define module-type (make-record-type 'module '(obarray uses binder eval-closure transformer name kind observers weak-observers observer-id) %print-module)) ;; make-module &opt size uses binder ;; ;; Create a new module, perhaps with a particular size of obarray, ;; initial uses list, or binding procedure. ;; (define make-module (lambda args (define (parse-arg index default) (if (> (length args) index) (list-ref args index) default)) (if (> (length args) 3) (error "Too many args to make-module." args)) (let ((size (parse-arg 0 1021)) (uses (parse-arg 1 '())) (binder (parse-arg 2 #f))) (if (not (integer? size)) (error "Illegal size to make-module." size)) (if (not (and (list? uses) (and-map module? uses))) (error "Incorrect use list." uses)) (if (and binder (not (procedure? binder))) (error "Lazy-binder expected to be a procedure or #f." binder)) (let ((module (module-constructor (make-vector size '()) uses binder #f #f #f #f '() (make-weak-value-hash-table 31) 0))) ;; We can't pass this as an argument to module-constructor, ;; because we need it to close over a pointer to the module ;; itself. (set-module-eval-closure! module (standard-eval-closure module)) module)))) (define module-constructor (record-constructor module-type)) (define module-obarray (record-accessor module-type 'obarray)) (define set-module-obarray! (record-modifier module-type 'obarray)) (define module-uses (record-accessor module-type 'uses)) (define set-module-uses! (record-modifier module-type 'uses)) (define module-binder (record-accessor module-type 'binder)) (define set-module-binder! (record-modifier module-type 'binder)) ;; NOTE: This binding is used in libguile/modules.c. (define module-eval-closure (record-accessor module-type 'eval-closure)) (define module-transformer (record-accessor module-type 'transformer)) (define set-module-transformer! (record-modifier module-type 'transformer)) (define module-name (record-accessor module-type 'name)) (define set-module-name! (record-modifier module-type 'name)) (define module-kind (record-accessor module-type 'kind)) (define set-module-kind! (record-modifier module-type 'kind)) (define module-observers (record-accessor module-type 'observers)) (define set-module-observers! (record-modifier module-type 'observers)) (define module-weak-observers (record-accessor module-type 'weak-observers)) (define module-observer-id (record-accessor module-type 'observer-id)) (define set-module-observer-id! (record-modifier module-type 'observer-id)) (define module? (record-predicate module-type)) (define set-module-eval-closure! (let ((setter (record-modifier module-type 'eval-closure))) (lambda (module closure) (setter module closure) ;; Make it possible to lookup the module from the environment. ;; This implementation is correct since an eval closure can belong ;; to maximally one module. (set-procedure-property! closure 'module module)))) (begin-deprecated (define (eval-in-module exp mod) (issue-deprecation-warning "`eval-in-module' is deprecated. Use `eval' instead.") (eval exp mod))) ;;; {Observer protocol} ;;; (define (module-observe module proc) (set-module-observers! module (cons proc (module-observers module))) (cons module proc)) (define (module-observe-weak module proc) (let ((id (module-observer-id module))) (hash-set! (module-weak-observers module) id proc) (set-module-observer-id! module (+ 1 id)) (cons module id))) (define (module-unobserve token) (let ((module (car token)) (id (cdr token))) (if (integer? id) (hash-remove! (module-weak-observers module) id) (set-module-observers! module (delq1! id (module-observers module))))) *unspecified*) (define (module-modified m) (for-each (lambda (proc) (proc m)) (module-observers m)) (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m))) ;;; {Module Searching in General} ;;; ;;; We sometimes want to look for properties of a symbol ;;; just within the obarray of one module. If the property ;;; holds, then it is said to hold ``locally'' as in, ``The symbol ;;; DISPLAY is locally rebound in the module `safe-guile'.'' ;;; ;;; ;;; Other times, we want to test for a symbol property in the obarray ;;; of M and, if it is not found there, try each of the modules in the ;;; uses list of M. This is the normal way of testing for some ;;; property, so we state these properties without qualification as ;;; in: ``The symbol 'fnord is interned in module M because it is ;;; interned locally in module M2 which is a member of the uses list ;;; of M.'' ;;; ;; module-search fn m ;; ;; return the first non-#f result of FN applied to M and then to ;; the modules in the uses of m, and so on recursively. If all applications ;; return #f, then so does this function. ;; (define (module-search fn m v) (define (loop pos) (and (pair? pos) (or (module-search fn (car pos) v) (loop (cdr pos))))) (or (fn m v) (loop (module-uses m)))) ;;; {Is a symbol bound in a module?} ;;; ;;; Symbol S in Module M is bound if S is interned in M and if the binding ;;; of S in M has been set to some well-defined value. ;;; ;; module-locally-bound? module symbol ;; ;; Is a symbol bound (interned and defined) locally in a given module? ;; (define (module-locally-bound? m v) (let ((var (module-local-variable m v))) (and var (variable-bound? var)))) ;; module-bound? module symbol ;; ;; Is a symbol bound (interned and defined) anywhere in a given module ;; or its uses? ;; (define (module-bound? m v) (module-search module-locally-bound? m v)) ;;; {Is a symbol interned in a module?} ;;; ;;; Symbol S in Module M is interned if S occurs in ;;; of S in M has been set to some well-defined value. ;;; ;;; It is possible to intern a symbol in a module without providing ;;; an initial binding for the corresponding variable. This is done ;;; with: ;;; (module-add! module symbol (make-undefined-variable)) ;;; ;;; In that case, the symbol is interned in the module, but not ;;; bound there. The unbound symbol shadows any binding for that ;;; symbol that might otherwise be inherited from a member of the uses list. ;;; (define (module-obarray-get-handle ob key) ((if (symbol? key) hashq-get-handle hash-get-handle) ob key)) (define (module-obarray-ref ob key) ((if (symbol? key) hashq-ref hash-ref) ob key)) (define (module-obarray-set! ob key val) ((if (symbol? key) hashq-set! hash-set!) ob key val)) (define (module-obarray-remove! ob key) ((if (symbol? key) hashq-remove! hash-remove!) ob key)) ;; module-symbol-locally-interned? module symbol ;; ;; is a symbol interned (not neccessarily defined) locally in a given module ;; or its uses? Interned symbols shadow inherited bindings even if ;; they are not themselves bound to a defined value. ;; (define (module-symbol-locally-interned? m v) (not (not (module-obarray-get-handle (module-obarray m) v)))) ;; module-symbol-interned? module symbol ;; ;; is a symbol interned (not neccessarily defined) anywhere in a given module ;; or its uses? Interned symbols shadow inherited bindings even if ;; they are not themselves bound to a defined value. ;; (define (module-symbol-interned? m v) (module-search module-symbol-locally-interned? m v)) ;;; {Mapping modules x symbols --> variables} ;;; ;; module-local-variable module symbol ;; return the local variable associated with a MODULE and SYMBOL. ;; ;;; This function is very important. It is the only function that can ;;; return a variable from a module other than the mutators that store ;;; new variables in modules. Therefore, this function is the location ;;; of the "lazy binder" hack. ;;; ;;; If symbol is defined in MODULE, and if the definition binds symbol ;;; to a variable, return that variable object. ;;; ;;; If the symbols is not found at first, but the module has a lazy binder, ;;; then try the binder. ;;; ;;; If the symbol is not found at all, return #f. ;;; (define (module-local-variable m v) ; (caddr ; (list m v (let ((b (module-obarray-ref (module-obarray m) v))) (or (and (variable? b) b) (and (module-binder m) ((module-binder m) m v #f))))) ;)) ;; module-variable module symbol ;; ;; like module-local-variable, except search the uses in the ;; case V is not found in M. ;; ;; NOTE: This function is superseded with C code (see modules.c) ;;; when using the standard eval closure. ;; (define (module-variable m v) (module-search module-local-variable m v)) ;;; {Mapping modules x symbols --> bindings} ;;; ;;; These are similar to the mapping to variables, except that the ;;; variable is dereferenced. ;;; ;; module-symbol-binding module symbol opt-value ;; ;; return the binding of a variable specified by name within ;; a given module, signalling an error if the variable is unbound. ;; If the OPT-VALUE is passed, then instead of signalling an error, ;; return OPT-VALUE. ;; (define (module-symbol-local-binding m v . opt-val) (let ((var (module-local-variable m v))) (if var (variable-ref var) (if (not (null? opt-val)) (car opt-val) (error "Locally unbound variable." v))))) ;; module-symbol-binding module symbol opt-value ;; ;; return the binding of a variable specified by name within ;; a given module, signalling an error if the variable is unbound. ;; If the OPT-VALUE is passed, then instead of signalling an error, ;; return OPT-VALUE. ;; (define (module-symbol-binding m v . opt-val) (let ((var (module-variable m v))) (if var (variable-ref var) (if (not (null? opt-val)) (car opt-val) (error "Unbound variable." v))))) ;;; {Adding Variables to Modules} ;;; ;;; ;; module-make-local-var! module symbol ;; ;; ensure a variable for V in the local namespace of M. ;; If no variable was already there, then create a new and uninitialzied ;; variable. ;; (define (module-make-local-var! m v) (or (let ((b (module-obarray-ref (module-obarray m) v))) (and (variable? b) (begin (module-modified m) b))) (and (module-binder m) ((module-binder m) m v #t)) (begin (let ((answer (make-undefined-variable))) (variable-set-name-hint! answer v) (module-obarray-set! (module-obarray m) v answer) (module-modified m) answer)))) ;; module-ensure-local-variable! module symbol ;; ;; Ensure that there is a local variable in MODULE for SYMBOL. If ;; there is no binding for SYMBOL, create a new uninitialized ;; variable. Return the local variable. ;; (define (module-ensure-local-variable! module symbol) (or (module-local-variable module symbol) (let ((var (make-undefined-variable))) (variable-set-name-hint! var symbol) (module-add! module symbol var) var))) ;; module-add! module symbol var ;; ;; ensure a particular variable for V in the local namespace of M. ;; (define (module-add! m v var) (if (not (variable? var)) (error "Bad variable to module-add!" var)) (module-obarray-set! (module-obarray m) v var) (module-modified m)) ;; module-remove! ;; ;; make sure that a symbol is undefined in the local namespace of M. ;; (define (module-remove! m v) (module-obarray-remove! (module-obarray m) v) (module-modified m)) (define (module-clear! m) (vector-fill! (module-obarray m) '()) (module-modified m)) ;; MODULE-FOR-EACH -- exported ;; ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE). ;; (define (module-for-each proc module) (let ((obarray (module-obarray module))) (do ((index 0 (+ index 1)) (end (vector-length obarray))) ((= index end)) (for-each (lambda (bucket) (proc (car bucket) (cdr bucket))) (vector-ref obarray index))))) (define (module-map proc module) (let* ((obarray (module-obarray module)) (end (vector-length obarray))) (let loop ((i 0) (answer '())) (if (= i end) answer (loop (+ 1 i) (append! (map (lambda (bucket) (proc (car bucket) (cdr bucket))) (vector-ref obarray i)) answer)))))) ;;; {Low Level Bootstrapping} ;;; ;; make-root-module ;; A root module uses the pre-modules-obarray as its obarray. This ;; special obarray accumulates all bindings that have been established ;; before the module system is fully booted. ;; ;; (The obarray continues to be used by code that has been closed over ;; before the module system has been booted.) (define (make-root-module) (let ((m (make-module 0))) (set-module-obarray! m (%get-pre-modules-obarray)) m)) ;; make-scm-module ;; The root interface is a module that uses the same obarray as the ;; root module. It does not allow new definitions, tho. (define (make-scm-module) (let ((m (make-module 0))) (set-module-obarray! m (%get-pre-modules-obarray)) (set-module-eval-closure! m (standard-interface-eval-closure m)) m)) ;;; {Module-based Loading} ;;; (define (save-module-excursion thunk) (let ((inner-module (current-module)) (outer-module #f)) (dynamic-wind (lambda () (set! outer-module (current-module)) (set-current-module inner-module) (set! inner-module #f)) thunk (lambda () (set! inner-module (current-module)) (set-current-module outer-module) (set! outer-module #f))))) (define basic-load load) (define (load-module filename) (save-module-excursion (lambda () (let ((oldname (and (current-load-port) (port-filename (current-load-port))))) (basic-load (if (and oldname (> (string-length filename) 0) (not (char=? (string-ref filename 0) #\/)) (not (string=? (dirname oldname) "."))) (string-append (dirname oldname) "/" filename) filename)))))) ;;; {MODULE-REF -- exported} ;; ;; Returns the value of a variable called NAME in MODULE or any of its ;; used modules. If there is no such variable, then if the optional third ;; argument DEFAULT is present, it is returned; otherwise an error is signaled. ;; (define (module-ref module name . rest) (let ((variable (module-variable module name))) (if (and variable (variable-bound? variable)) (variable-ref variable) (if (null? rest) (error "No variable named" name 'in module) (car rest) ; default value )))) ;; MODULE-SET! -- exported ;; ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses) ;; to VALUE; if there is no such variable, an error is signaled. ;; (define (module-set! module name value) (let ((variable (module-variable module name))) (if variable (variable-set! variable value) (error "No variable named" name 'in module)))) ;; MODULE-DEFINE! -- exported ;; ;; Sets the variable called NAME in MODULE to VALUE; if there is no such ;; variable, it is added first. ;; (define (module-define! module name value) (let ((variable (module-local-variable module name))) (if variable (begin (variable-set! variable value) (module-modified module)) (let ((variable (make-variable value))) (variable-set-name-hint! variable name) (module-add! module name variable))))) ;; MODULE-DEFINED? -- exported ;; ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE ;; uses) ;; (define (module-defined? module name) (let ((variable (module-variable module name))) (and variable (variable-bound? variable)))) ;; MODULE-USE! module interface ;; ;; Add INTERFACE to the list of interfaces used by MODULE. ;; (define (module-use! module interface) (set-module-uses! module (cons interface (delq! interface (module-uses module)))) (module-modified module)) ;;; {Recursive Namespaces} ;;; ;;; ;;; A hierarchical namespace emerges if we consider some module to be ;;; root, and variables bound to modules as nested namespaces. ;;; ;;; The routines in this file manage variable names in hierarchical namespace. ;;; Each variable name is a list of elements, looked up in successively nested ;;; modules. ;;; ;;; (nested-ref some-root-module '(foo bar baz)) ;;; => ;;; ;;; ;;; There are: ;;; ;;; ;; a-root is a module ;;; ;; name is a list of symbols ;;; ;;; nested-ref a-root name ;;; nested-set! a-root name val ;;; nested-define! a-root name val ;;; nested-remove! a-root name ;;; ;;; ;;; (current-module) is a natural choice for a-root so for convenience there are ;;; also: ;;; ;;; local-ref name == nested-ref (current-module) name ;;; local-set! name val == nested-set! (current-module) name val ;;; local-define! name val == nested-define! (current-module) name val ;;; local-remove! name == nested-remove! (current-module) name ;;; (define (nested-ref root names) (let loop ((cur root) (elts names)) (cond ((null? elts) cur) ((not (module? cur)) #f) (else (loop (module-ref cur (car elts) #f) (cdr elts)))))) (define (nested-set! root names val) (let loop ((cur root) (elts names)) (if (null? (cdr elts)) (module-set! cur (car elts) val) (loop (module-ref cur (car elts)) (cdr elts))))) (define (nested-define! root names val) (let loop ((cur root) (elts names)) (if (null? (cdr elts)) (module-define! cur (car elts) val) (loop (module-ref cur (car elts)) (cdr elts))))) (define (nested-remove! root names) (let loop ((cur root) (elts names)) (if (null? (cdr elts)) (module-remove! cur (car elts)) (loop (module-ref cur (car elts)) (cdr elts))))) (define (local-ref names) (nested-ref (current-module) names)) (define (local-set! names val) (nested-set! (current-module) names val)) (define (local-define names val) (nested-define! (current-module) names val)) (define (local-remove names) (nested-remove! (current-module) names)) ;;; boot-9.scm ends here pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ca65_example000066400000000000000000000112631250413007300260670ustar00rootroot00000000000000;-------------------------------------- ; Lychrel numbers. ; ; :author: Marc 'BlackJack' Rintsch ; :date: 2008-03-07 ; :version: 0.1 ; ; Prints all `Lychrel numbers`_ between 1 and 100000. ; ; The numbers are stored as array of "digits" in little endian ; order. Each digit is a byte with a value between 0 and 9. ; ; Runtime on C64: 00:21:01 ; ; .. _Lychrel numbers: http://en.wikipedia.org/wiki/Lychrel_number ; ; .. cl65 -l -tnone -C simple.cfg lychrel.s -o lychrel.prg ;-------------------------------------- ;-------------------------------------- ; External addresses. ;-------------------------------------- chrout = $ffd2 ;-------------------------------------- ; Constants. ;-------------------------------------- TO = 100000 TO_DIGITS = 10 ITERATIONS = 100 MAX_DIGITS = TO_DIGITS + ITERATIONS ;-------------------------------------- ; Global variables. ;-------------------------------------- .zeropage ; ; Length of the currently tested `n` in digits. ; n_length: .res 1 ; ; Length of the number(s) `xa` and `xb` while testing. ; length: .res 1 .bss ; ; Number to be tested as digits i.e. bytes with values between ; 0 and 9. The length is stored in `n_length`. ; n: .res TO_DIGITS ; ; Space for calculating the reversed and added values. ; In the `main` code the current number is copied into `xa` ; and then repeatedly `reverse_add`\ed to itself with the ; result of that adding stored in `xb`. ; xa: .res MAX_DIGITS xb: .res MAX_DIGITS ;-------------------------------------- ; BASIC header. ;-------------------------------------- .code .word 0800h ; Load address. .byte 0 .word @line_end .word 2008 ; Line number. .byte $9e ; SYS token. .byte "2080 " ; SYS argument. .byte "LYCHREL NUMBERS/BJ" @line_end: .byte 0, 0, 0 ; Line and program end marker. ;-------------------------------------- ; Main program. ;-------------------------------------- .proc main .zeropage ; ; Three byte counter for `TO` iterations (100000 = $0186a0). ; i: .res 3 .code ; ; Clear and set `n` and `i` to 1. ; lda #0 ; n := 0; n := 1; i := 1 sta i+1 sta i+2 ldx #TO_DIGITS clear_n: sta n-1,x dex bne clear_n inx stx i stx n stx n_length mainloop: jsr is_lychrel bcc no_lychrel jsr print_n no_lychrel: jsr increase_n inc i ; INC(i) bne skip inc i+1 bne skip inc i+2 skip: lda i cmp #TO bne mainloop lda i+2 cmp #^TO bne mainloop rts .endproc ;-------------------------------------- ; Print `n` and a trailing newline. ; ; :in: `n_length`, `n` ;-------------------------------------- .proc print_n ldy n_length L1: lda n-1,y ora #%110000 ; = '0' jsr chrout dey bne L1 lda #13 jmp chrout .endproc ;-------------------------------------- ; Increase `n` by one. ; ; This procedure expects n[n_length] == 0 in case the number gets ; one digit longer. ; ; :in: `n`, `n_length` ; :out: `n`, `n_length` ;-------------------------------------- .proc increase_n ldx #0 L1: inc n,x ; Increase digit. lda n,x cmp #10 ; If "carry", store 0 and go to next digit. bne return lda #0 sta n,x inx bne L1 return: cpx n_length ; If "carry" after last digit, increase length. bcc skip inc n_length skip: rts .endproc ;-------------------------------------- ; Tests if `n` is a Lychrel number. ; ; :in: `n`, `n_length` ; :out: C is set if yes, cleared otherwise. ; :uses: `length`, `xa`, `xb` ;-------------------------------------- .proc is_lychrel .zeropage i: .res 1 .code ldx n_length ; xa := n; length := n_length stx length L1: lda n-1,x sta xa-1,x dex bne L1 lda #ITERATIONS ; i := ITERATIONS sta i L2: jsr reverse_add jsr is_palindrome bne no_palindrome clc rts no_palindrome: ldx length ; a := b L3: lda xb-1,x sta xa-1,x dex bne L3 dec i ; Loop body end. bne L2 sec rts .endproc ;-------------------------------------- ; Add the reverse to `xa` to itself and store the result in `xb`. ; ; :in: `length`, `xa` ; :out: `length`, `xb` ;-------------------------------------- .proc reverse_add .code ldx #0 ldy length clc L1: lda xa,x adc xa-1,y cmp #10 bcc no_adjust sbc #10 no_adjust: sta xb,x dey inx txa ; ``eor`` instead of ``cpx`` to keep the carry flag eor length ; of the addition above. bne L1 bcc no_carry lda #1 sta xb,x inc length no_carry: rts .endproc ;-------------------------------------- ; Checks if `xb` is a palindrome. ; ; :in: `length`, `xb` ; :out: Z flag set if `xb` is a palindrome, cleared otherwise. ;-------------------------------------- .proc is_palindrome .code ldx #0 lda length tay lsr sta L1+1 ; Self modifying code! L1: cpx #0 ; <<< 0 replaced by (`length` / 2). beq return lda xb,x cmp xb-1,y bne return dey inx bne L1 return: rts .endproc pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/cbmbas_example000066400000000000000000000004771250413007300265650ustar00rootroot0000000000000010 rem cbm basic v2 example 20 rem comment with keywords: for, data 30 dim a$(20) 35 rem the typical space efficient form of leaving spaces out: 40 fort=0to15:poke646,t:print"{revers on} ";:next 50 geta$:ifa$=chr$(0):goto40 55 rem it is legal to omit the closing " on line end 60 print"{white}":print"bye... 70 end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/cells.ps000066400000000000000000000207101250413007300253360ustar00rootroot00000000000000%!PS-Adobe-2.0 %%Creator: PS_Write.F %%Title: cells.ps %%Pages: 1 %%Document-Fonts: Times-Roman %%CreationDate: 09/29/99 %%BoundingBox: 36 36 576 756 %%EndComments %%BeginProlog %%EndProlog /inch {72 mul} def /Palatino-Roman findfont 1.00 inch scalefont setfont 0.0000 0.0000 0.0000 setrgbcolor %%Page: 1 1 save 0.7000 0.7000 0.7000 setrgbcolor newpath 497 294 moveto 500 297 lineto 503 300 lineto 506 303 lineto 510 307 lineto 513 310 lineto 516 313 lineto 519 316 lineto 522 319 lineto 526 323 lineto 529 326 lineto 532 329 lineto 535 332 lineto 538 335 lineto 541 338 lineto 545 342 lineto 548 345 lineto 551 348 lineto 554 351 lineto 557 354 lineto 561 358 lineto 0.7000 0.7000 0.7000 setrgbcolor stroke newpath 51 358 moveto 65 385 lineto 84 408 lineto 109 425 lineto 138 433 lineto 168 436 lineto 198 435 lineto 226 436 lineto 252 442 lineto 279 451 lineto 306 463 lineto 335 472 lineto 365 475 lineto 394 470 lineto 421 455 lineto 444 436 lineto 465 414 lineto 485 395 lineto 508 380 lineto 533 369 lineto 561 358 lineto 0.7000 0.7000 0.7000 setrgbcolor stroke newpath 115 294 moveto 112 297 lineto 109 300 lineto 106 303 lineto 102 307 lineto 99 310 lineto 96 313 lineto 93 316 lineto 90 319 lineto 86 323 lineto 83 326 lineto 80 329 lineto 77 332 lineto 74 335 lineto 71 338 lineto 67 342 lineto 64 345 lineto 61 348 lineto 58 351 lineto 55 354 lineto 51 358 lineto 0.7000 0.7000 0.7000 setrgbcolor stroke newpath 115 294 moveto 131 308 lineto 147 321 lineto 165 333 lineto 183 344 lineto 203 352 lineto 223 360 lineto 243 366 lineto 264 370 lineto 285 372 lineto 306 373 lineto 327 372 lineto 348 370 lineto 369 366 lineto 389 360 lineto 409 352 lineto 429 344 lineto 447 333 lineto 465 321 lineto 481 308 lineto 497 294 lineto 0.7000 0.7000 0.7000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 171 337 moveto 164 348 lineto 158 360 lineto 151 371 lineto 145 383 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 145 383 moveto 126 372 lineto 109 359 lineto 95 343 lineto 83 326 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 83 326 moveto 91 318 lineto 99 310 lineto 107 302 lineto 115 294 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 115 294 moveto 128 306 lineto 142 317 lineto 156 327 lineto 171 337 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 236 364 moveto 234 373 lineto 231 382 lineto 229 391 lineto 226 400 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 226 400 moveto 206 397 lineto 185 394 lineto 165 390 lineto 145 383 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 145 383 moveto 151 371 lineto 158 360 lineto 164 348 lineto 171 337 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 171 337 moveto 187 345 lineto 203 352 lineto 219 359 lineto 236 364 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 306 373 moveto 306 384 lineto 306 396 lineto 306 407 lineto 306 418 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 306 418 moveto 286 413 lineto 266 408 lineto 246 403 lineto 226 400 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 226 400 moveto 229 391 lineto 231 382 lineto 234 373 lineto 236 364 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 236 364 moveto 253 368 lineto 271 371 lineto 288 372 lineto 306 373 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 376 364 moveto 379 377 lineto 383 389 lineto 386 402 lineto 390 415 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 390 415 moveto 369 421 lineto 348 423 lineto 327 422 lineto 306 418 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 306 418 moveto 306 407 lineto 306 396 lineto 306 384 lineto 306 373 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 306 373 moveto 324 372 lineto 341 371 lineto 359 368 lineto 376 364 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 441 337 moveto 446 345 lineto 450 353 lineto 455 361 lineto 460 369 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 460 369 moveto 443 381 lineto 427 394 lineto 409 406 lineto 390 415 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 390 415 moveto 386 402 lineto 383 389 lineto 379 377 lineto 376 364 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 376 364 moveto 393 359 lineto 409 352 lineto 425 345 lineto 441 337 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 497 294 moveto 505 302 lineto 513 310 lineto 521 318 lineto 529 326 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 529 326 moveto 511 336 lineto 493 347 lineto 476 357 lineto 460 369 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 460 369 moveto 455 361 lineto 450 353 lineto 446 345 lineto 441 337 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 441 337 moveto 456 327 lineto 470 317 lineto 484 306 lineto 497 294 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 145 383 moveto 138 394 lineto 131 405 lineto 125 417 lineto 118 428 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 118 428 moveto 96 417 lineto 77 401 lineto 63 380 lineto 51 358 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 51 358 moveto 59 350 lineto 67 342 lineto 75 334 lineto 83 326 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 83 326 moveto 95 343 lineto 109 359 lineto 126 372 lineto 145 383 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 226 400 moveto 224 409 lineto 222 418 lineto 219 427 lineto 217 436 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 217 436 moveto 193 435 lineto 168 436 lineto 143 434 lineto 118 428 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 118 428 moveto 125 417 lineto 131 405 lineto 138 394 lineto 145 383 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 145 383 moveto 165 390 lineto 185 394 lineto 206 397 lineto 226 400 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 306 418 moveto 306 429 lineto 306 441 lineto 306 452 lineto 306 463 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 306 463 moveto 283 453 lineto 261 444 lineto 239 438 lineto 217 436 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 217 436 moveto 219 427 lineto 222 418 lineto 224 409 lineto 226 400 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 226 400 moveto 246 403 lineto 266 408 lineto 286 413 lineto 306 418 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 390 415 moveto 393 428 lineto 396 440 lineto 400 453 lineto 403 466 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 403 466 moveto 380 474 lineto 355 475 lineto 330 471 lineto 306 463 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 306 463 moveto 306 452 lineto 306 441 lineto 306 429 lineto 306 418 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 306 418 moveto 327 422 lineto 348 423 lineto 369 421 lineto 390 415 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 460 369 moveto 464 377 lineto 469 385 lineto 474 393 lineto 478 401 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 478 401 moveto 461 418 lineto 444 436 lineto 425 452 lineto 403 466 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 403 466 moveto 400 453 lineto 396 440 lineto 393 428 lineto 390 415 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 390 415 moveto 409 406 lineto 427 394 lineto 443 381 lineto 460 369 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke 0.0000 0.0000 0.4000 setrgbcolor newpath 529 326 moveto 537 334 lineto 545 342 lineto 553 350 lineto 561 358 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 561 358 moveto 537 367 lineto 516 376 lineto 496 387 lineto 478 401 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 478 401 moveto 474 393 lineto 469 385 lineto 464 377 lineto 460 369 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke newpath 460 369 moveto 476 357 lineto 493 347 lineto 511 336 lineto 529 326 lineto 0.0000 0.0000 0.4000 setrgbcolor stroke restore showpage %%Trailer %%Pages: 1 %%EOF pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ceval.c000066400000000000000000001673471250413007300251500ustar00rootroot00000000000000 /* Execute compiled code */ /* XXX TO DO: XXX speed up searching for keywords by using a dictionary XXX document it! */ /* enable more aggressive intra-module optimizations, where available */ #define PY_LOCAL_AGGRESSIVE #include "Python.h" #include "code.h" #include "frameobject.h" #include "eval.h" #include "opcode.h" #include "structmember.h" #include #ifndef WITH_TSC #define READ_TIMESTAMP(var) #else typedef unsigned long long uint64; #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this section should work for GCC on any PowerPC platform, irrespective of OS. POWER? Who knows :-) */ #define READ_TIMESTAMP(var) ppc_getcounter(&var) static void ppc_getcounter(uint64 *v) { register unsigned long tbu, tb, tbu2; loop: asm volatile ("mftbu %0" : "=r" (tbu) ); asm volatile ("mftb %0" : "=r" (tb) ); asm volatile ("mftbu %0" : "=r" (tbu2)); if (__builtin_expect(tbu != tbu2, 0)) goto loop; /* The slightly peculiar way of writing the next lines is compiled better by GCC than any other way I tried. */ ((long*)(v))[0] = tbu; ((long*)(v))[1] = tb; } #else /* this is for linux/x86 (and probably any other GCC/x86 combo) */ #define READ_TIMESTAMP(val) \ __asm__ __volatile__("rdtsc" : "=A" (val)) #endif void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) { uint64 intr, inst, loop; PyThreadState *tstate = PyThreadState_Get(); if (!tstate->interp->tscdump) return; intr = intr1 - intr0; inst = inst1 - inst0 - intr; loop = loop1 - loop0 - intr; fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", opcode, ticked, inst, loop); } #endif /* Turn this on if your compiler chokes on the big switch: */ /* #define CASE_TOO_BIG 1 */ #ifdef Py_DEBUG /* For debugging the interpreter: */ #define LLTRACE 1 /* Low-level trace feature */ #define CHECKEXC 1 /* Double-check exception checking */ #endif typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *); /* Forward declarations */ #ifdef WITH_TSC static PyObject * call_function(PyObject ***, int, uint64*, uint64*); #else static PyObject * call_function(PyObject ***, int); #endif static PyObject * fast_function(PyObject *, PyObject ***, int, int, int); static PyObject * do_call(PyObject *, PyObject ***, int, int); static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); static PyObject * update_keyword_args(PyObject *, int, PyObject ***,PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 #define CALL_FLAG_KW 2 #ifdef LLTRACE static int lltrace; static int prtrace(PyObject *, char *); #endif static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *, int, PyObject *); static void call_trace_protected(Py_tracefunc, PyObject *, PyFrameObject *, int, PyObject *); static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *); static int maybe_call_line_trace(Py_tracefunc, PyObject *, PyFrameObject *, int *, int *, int *); static PyObject * apply_slice(PyObject *, PyObject *, PyObject *); static int assign_slice(PyObject *, PyObject *, PyObject *, PyObject *); static PyObject * cmp_outcome(int, PyObject *, PyObject *); static PyObject * import_from(PyObject *, PyObject *); static int import_all_from(PyObject *, PyObject *); static PyObject * build_class(PyObject *, PyObject *, PyObject *); static int exec_statement(PyFrameObject *, PyObject *, PyObject *, PyObject *); static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *); static void reset_exc_info(PyThreadState *); static void format_exc_check_arg(PyObject *, char *, PyObject *); static PyObject * string_concatenate(PyObject *, PyObject *, PyFrameObject *, unsigned char *); #define NAME_ERROR_MSG \ "name '%.200s' is not defined" #define GLOBAL_NAME_ERROR_MSG \ "global name '%.200s' is not defined" #define UNBOUNDLOCAL_ERROR_MSG \ "local variable '%.200s' referenced before assignment" #define UNBOUNDFREE_ERROR_MSG \ "free variable '%.200s' referenced before assignment" \ " in enclosing scope" /* Dynamic execution profile */ #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS static long dxpairs[257][256]; #define dxp dxpairs[256] #else static long dxp[256]; #endif #endif /* Function call profile */ #ifdef CALL_PROFILE #define PCALL_NUM 11 static int pcall[PCALL_NUM]; #define PCALL_ALL 0 #define PCALL_FUNCTION 1 #define PCALL_FAST_FUNCTION 2 #define PCALL_FASTER_FUNCTION 3 #define PCALL_METHOD 4 #define PCALL_BOUND_METHOD 5 #define PCALL_CFUNCTION 6 #define PCALL_TYPE 7 #define PCALL_GENERATOR 8 #define PCALL_OTHER 9 #define PCALL_POP 10 /* Notes about the statistics PCALL_FAST stats FAST_FUNCTION means no argument tuple needs to be created. FASTER_FUNCTION means that the fast-path frame setup code is used. If there is a method call where the call can be optimized by changing the argument tuple and calling the function directly, it gets recorded twice. As a result, the relationship among the statistics appears to be PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD + PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION PCALL_METHOD > PCALL_BOUND_METHOD */ #define PCALL(POS) pcall[POS]++ PyObject * PyEval_GetCallStats(PyObject *self) { return Py_BuildValue("iiiiiiiiii", pcall[0], pcall[1], pcall[2], pcall[3], pcall[4], pcall[5], pcall[6], pcall[7], pcall[8], pcall[9]); } #else #define PCALL(O) PyObject * PyEval_GetCallStats(PyObject *self) { Py_INCREF(Py_None); return Py_None; } #endif #ifdef WITH_THREAD #ifdef HAVE_ERRNO_H #include #endif #include "pythread.h" static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */ static long main_thread = 0; int PyEval_ThreadsInitialized(void) { return interpreter_lock != 0; } void PyEval_InitThreads(void) { if (interpreter_lock) return; interpreter_lock = PyThread_allocate_lock(); PyThread_acquire_lock(interpreter_lock, 1); main_thread = PyThread_get_thread_ident(); } void PyEval_AcquireLock(void) { PyThread_acquire_lock(interpreter_lock, 1); } void PyEval_ReleaseLock(void) { PyThread_release_lock(interpreter_lock); } void PyEval_AcquireThread(PyThreadState *tstate) { if (tstate == NULL) Py_FatalError("PyEval_AcquireThread: NULL new thread state"); /* Check someone has called PyEval_InitThreads() to create the lock */ assert(interpreter_lock); PyThread_acquire_lock(interpreter_lock, 1); if (PyThreadState_Swap(tstate) != NULL) Py_FatalError( "PyEval_AcquireThread: non-NULL old thread state"); } void PyEval_ReleaseThread(PyThreadState *tstate) { if (tstate == NULL) Py_FatalError("PyEval_ReleaseThread: NULL thread state"); if (PyThreadState_Swap(NULL) != tstate) Py_FatalError("PyEval_ReleaseThread: wrong thread state"); PyThread_release_lock(interpreter_lock); } /* This function is called from PyOS_AfterFork to ensure that newly created child processes don't hold locks referring to threads which are not running in the child process. (This could also be done using pthread_atfork mechanism, at least for the pthreads implementation.) */ void PyEval_ReInitThreads(void) { if (!interpreter_lock) return; /*XXX Can't use PyThread_free_lock here because it does too much error-checking. Doing this cleanly would require adding a new function to each thread_*.h. Instead, just create a new lock and waste a little bit of memory */ interpreter_lock = PyThread_allocate_lock(); PyThread_acquire_lock(interpreter_lock, 1); main_thread = PyThread_get_thread_ident(); } #endif /* Functions save_thread and restore_thread are always defined so dynamically loaded modules needn't be compiled separately for use with and without threads: */ PyThreadState * PyEval_SaveThread(void) { PyThreadState *tstate = PyThreadState_Swap(NULL); if (tstate == NULL) Py_FatalError("PyEval_SaveThread: NULL tstate"); #ifdef WITH_THREAD if (interpreter_lock) PyThread_release_lock(interpreter_lock); #endif return tstate; } void PyEval_RestoreThread(PyThreadState *tstate) { if (tstate == NULL) Py_FatalError("PyEval_RestoreThread: NULL tstate"); #ifdef WITH_THREAD if (interpreter_lock) { int err = errno; PyThread_acquire_lock(interpreter_lock, 1); errno = err; } #endif PyThreadState_Swap(tstate); } /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX signal handlers or Mac I/O completion routines) can schedule calls to a function to be called synchronously. The synchronous function is called with one void* argument. It should return 0 for success or -1 for failure -- failure should be accompanied by an exception. If registry succeeds, the registry function returns 0; if it fails (e.g. due to too many pending calls) it returns -1 (without setting an exception condition). Note that because registry may occur from within signal handlers, or other asynchronous events, calling malloc() is unsafe! #ifdef WITH_THREAD Any thread can schedule pending calls, but only the main thread will execute them. #endif XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE! There are two possible race conditions: (1) nested asynchronous registry calls; (2) registry calls made while pending calls are being processed. While (1) is very unlikely, (2) is a real possibility. The current code is safe against (2), but not against (1). The safety against (2) is derived from the fact that only one thread (the main thread) ever takes things out of the queue. XXX Darn! With the advent of thread state, we should have an array of pending calls per thread in the thread state! Later... */ #define NPENDINGCALLS 32 static struct { int (*func)(void *); void *arg; } pendingcalls[NPENDINGCALLS]; static volatile int pendingfirst = 0; static volatile int pendinglast = 0; static volatile int things_to_do = 0; int Py_AddPendingCall(int (*func)(void *), void *arg) { static volatile int busy = 0; int i, j; /* XXX Begin critical section */ /* XXX If you want this to be safe against nested XXX asynchronous calls, you'll have to work harder! */ if (busy) return -1; busy = 1; i = pendinglast; j = (i + 1) % NPENDINGCALLS; if (j == pendingfirst) { busy = 0; return -1; /* Queue full */ } pendingcalls[i].func = func; pendingcalls[i].arg = arg; pendinglast = j; _Py_Ticker = 0; things_to_do = 1; /* Signal main loop */ busy = 0; /* XXX End critical section */ return 0; } int Py_MakePendingCalls(void) { static int busy = 0; #ifdef WITH_THREAD if (main_thread && PyThread_get_thread_ident() != main_thread) return 0; #endif if (busy) return 0; busy = 1; things_to_do = 0; for (;;) { int i; int (*func)(void *); void *arg; i = pendingfirst; if (i == pendinglast) break; /* Queue empty */ func = pendingcalls[i].func; arg = pendingcalls[i].arg; pendingfirst = (i + 1) % NPENDINGCALLS; if (func(arg) < 0) { busy = 0; things_to_do = 1; /* We're not done yet */ return -1; } } busy = 0; return 0; } /* The interpreter's recursion limit */ #ifndef Py_DEFAULT_RECURSION_LIMIT #define Py_DEFAULT_RECURSION_LIMIT 1000 #endif static int recursion_limit = Py_DEFAULT_RECURSION_LIMIT; int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT; int Py_GetRecursionLimit(void) { return recursion_limit; } void Py_SetRecursionLimit(int new_limit) { recursion_limit = new_limit; _Py_CheckRecursionLimit = recursion_limit; } /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall() if the recursion_depth reaches _Py_CheckRecursionLimit. If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit to guarantee that _Py_CheckRecursiveCall() is regularly called. Without USE_STACKCHECK, there is no need for this. */ int _Py_CheckRecursiveCall(char *where) { PyThreadState *tstate = PyThreadState_GET(); #ifdef USE_STACKCHECK if (PyOS_CheckStack()) { --tstate->recursion_depth; PyErr_SetString(PyExc_MemoryError, "Stack overflow"); return -1; } #endif if (tstate->recursion_depth > recursion_limit) { --tstate->recursion_depth; PyErr_Format(PyExc_RuntimeError, "maximum recursion depth exceeded%s", where); return -1; } _Py_CheckRecursionLimit = recursion_limit; return 0; } /* Status code for main loop (reason for stack unwind) */ enum why_code { WHY_NOT = 0x0001, /* No error */ WHY_EXCEPTION = 0x0002, /* Exception occurred */ WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ WHY_RETURN = 0x0008, /* 'return' statement */ WHY_BREAK = 0x0010, /* 'break' statement */ WHY_CONTINUE = 0x0020, /* 'continue' statement */ WHY_YIELD = 0x0040 /* 'yield' operator */ }; static enum why_code do_raise(PyObject *, PyObject *, PyObject *); static int unpack_iterable(PyObject *, int, PyObject **); /* for manipulating the thread switch and periodic "stuff" - used to be per thread, now just a pair o' globals */ int _Py_CheckInterval = 100; volatile int _Py_Ticker = 100; PyObject * PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) { /* XXX raise SystemError if globals is NULL */ return PyEval_EvalCodeEx(co, globals, locals, (PyObject **)NULL, 0, (PyObject **)NULL, 0, (PyObject **)NULL, 0, NULL); } /* Interpreter main loop */ PyObject * PyEval_EvalFrame(PyFrameObject *f) { /* This is for backward compatibility with extension modules that used this API; core interpreter code should call PyEval_EvalFrameEx() */ return PyEval_EvalFrameEx(f, 0); } PyObject * PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { #ifdef DXPAIRS int lastopcode = 0; #endif register PyObject **stack_pointer; /* Next free slot in value stack */ register unsigned char *next_instr; register int opcode; /* Current opcode */ register int oparg; /* Current opcode argument, if any */ register enum why_code why; /* Reason for block stack unwind */ register int err; /* Error status -- nonzero if error */ register PyObject *x; /* Result object -- NULL if error */ register PyObject *v; /* Temporary objects popped off stack */ register PyObject *w; register PyObject *u; register PyObject *t; register PyObject *stream = NULL; /* for PRINT opcodes */ register PyObject **fastlocals, **freevars; PyObject *retval = NULL; /* Return value */ PyThreadState *tstate = PyThreadState_GET(); PyCodeObject *co; /* when tracing we set things up so that not (instr_lb <= current_bytecode_offset < instr_ub) is true when the line being executed has changed. The initial values are such as to make this false the first time it is tested. */ int instr_ub = -1, instr_lb = 0, instr_prev = -1; unsigned char *first_instr; PyObject *names; PyObject *consts; #if defined(Py_DEBUG) || defined(LLTRACE) /* Make it easier to find out where we are with a debugger */ char *filename; #endif /* Tuple access macros */ #ifndef Py_DEBUG #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i)) #else #define GETITEM(v, i) PyTuple_GetItem((v), (i)) #endif #ifdef WITH_TSC /* Use Pentium timestamp counter to mark certain events: inst0 -- beginning of switch statement for opcode dispatch inst1 -- end of switch statement (may be skipped) loop0 -- the top of the mainloop loop1 -- place where control returns again to top of mainloop (may be skipped) intr1 -- beginning of long interruption intr2 -- end of long interruption Many opcodes call out to helper C functions. In some cases, the time in those functions should be counted towards the time for the opcode, but not in all cases. For example, a CALL_FUNCTION opcode calls another Python function; there's no point in charge all the bytecode executed by the called function to the caller. It's hard to make a useful judgement statically. In the presence of operator overloading, it's impossible to tell if a call will execute new Python code or not. It's a case-by-case judgement. I'll use intr1 for the following cases: EXEC_STMT IMPORT_STAR IMPORT_FROM CALL_FUNCTION (and friends) */ uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; int ticked = 0; READ_TIMESTAMP(inst0); READ_TIMESTAMP(inst1); READ_TIMESTAMP(loop0); READ_TIMESTAMP(loop1); /* shut up the compiler */ opcode = 0; #endif /* Code access macros */ #define INSTR_OFFSET() ((int)(next_instr - first_instr)) #define NEXTOP() (*next_instr++) #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) #define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) #define JUMPTO(x) (next_instr = first_instr + (x)) #define JUMPBY(x) (next_instr += (x)) /* OpCode prediction macros Some opcodes tend to come in pairs thus making it possible to predict the second code when the first is run. For example, COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often followed by a POP_TOP. Verifying the prediction costs a single high-speed test of register variable against a constant. If the pairing was good, then the processor has a high likelihood of making its own successful branch prediction which results in a nearly zero overhead transition to the next opcode. A successful prediction saves a trip through the eval-loop including its two unpredictable branches, the HASARG test and the switch-case. If collecting opcode statistics, turn off prediction so that statistics are accurately maintained (the predictions bypass the opcode frequency counter updates). */ #ifdef DYNAMIC_EXECUTION_PROFILE #define PREDICT(op) if (0) goto PRED_##op #else #define PREDICT(op) if (*next_instr == op) goto PRED_##op #endif #define PREDICTED(op) PRED_##op: next_instr++ #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 /* Stack manipulation macros */ /* The stack can grow at most MAXINT deep, as co_nlocals and co_stacksize are ints. */ #define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) #define EMPTY() (STACK_LEVEL() == 0) #define TOP() (stack_pointer[-1]) #define SECOND() (stack_pointer[-2]) #define THIRD() (stack_pointer[-3]) #define FOURTH() (stack_pointer[-4]) #define SET_TOP(v) (stack_pointer[-1] = (v)) #define SET_SECOND(v) (stack_pointer[-2] = (v)) #define SET_THIRD(v) (stack_pointer[-3] = (v)) #define SET_FOURTH(v) (stack_pointer[-4] = (v)) #define BASIC_STACKADJ(n) (stack_pointer += n) #define BASIC_PUSH(v) (*stack_pointer++ = (v)) #define BASIC_POP() (*--stack_pointer) #ifdef LLTRACE #define PUSH(v) { (void)(BASIC_PUSH(v), \ lltrace && prtrace(TOP(), "push")); \ assert(STACK_LEVEL() <= co->co_stacksize); } #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP()) #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ lltrace && prtrace(TOP(), "stackadj")); \ assert(STACK_LEVEL() <= co->co_stacksize); } #define EXT_POP(STACK_POINTER) (lltrace && prtrace(*(STACK_POINTER), "ext_pop"), *--(STACK_POINTER)) #else #define PUSH(v) BASIC_PUSH(v) #define POP() BASIC_POP() #define STACKADJ(n) BASIC_STACKADJ(n) #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER)) #endif /* Local variable macros */ #define GETLOCAL(i) (fastlocals[i]) /* The SETLOCAL() macro must not DECREF the local variable in-place and then store the new value; it must copy the old value to a temporary value, then store the new value, and then DECREF the temporary value. This is because it is possible that during the DECREF the frame is accessed by other code (e.g. a __del__ method or gc.collect()) and the variable would be pointing to already-freed memory. */ #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ GETLOCAL(i) = value; \ Py_XDECREF(tmp); } while (0) /* Start of code */ if (f == NULL) return NULL; /* push frame */ if (Py_EnterRecursiveCall("")) return NULL; tstate->frame = f; if (tstate->use_tracing) { if (tstate->c_tracefunc != NULL) { /* tstate->c_tracefunc, if defined, is a function that will be called on *every* entry to a code block. Its return value, if not None, is a function that will be called at the start of each executed line of code. (Actually, the function must return itself in order to continue tracing.) The trace functions are called with three arguments: a pointer to the current frame, a string indicating why the function is called, and an argument which depends on the situation. The global trace function is also called whenever an exception is detected. */ if (call_trace(tstate->c_tracefunc, tstate->c_traceobj, f, PyTrace_CALL, Py_None)) { /* Trace function raised an error */ goto exit_eval_frame; } } if (tstate->c_profilefunc != NULL) { /* Similar for c_profilefunc, except it needn't return itself and isn't called for "line" events */ if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, f, PyTrace_CALL, Py_None)) { /* Profile function raised an error */ goto exit_eval_frame; } } } co = f->f_code; names = co->co_names; consts = co->co_consts; fastlocals = f->f_localsplus; freevars = f->f_localsplus + co->co_nlocals; first_instr = (unsigned char*) PyString_AS_STRING(co->co_code); /* An explanation is in order for the next line. f->f_lasti now refers to the index of the last instruction executed. You might think this was obvious from the name, but this wasn't always true before 2.3! PyFrame_New now sets f->f_lasti to -1 (i.e. the index *before* the first instruction) and YIELD_VALUE doesn't fiddle with f_lasti any more. So this does work. Promise. */ next_instr = first_instr + f->f_lasti + 1; stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ #ifdef LLTRACE lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; #endif #if defined(Py_DEBUG) || defined(LLTRACE) filename = PyString_AsString(co->co_filename); #endif why = WHY_NOT; err = 0; x = Py_None; /* Not a reference, just anything non-NULL */ w = NULL; if (throwflag) { /* support for generator.throw() */ why = WHY_EXCEPTION; goto on_error; } for (;;) { #ifdef WITH_TSC if (inst1 == 0) { /* Almost surely, the opcode executed a break or a continue, preventing inst1 from being set on the way out of the loop. */ READ_TIMESTAMP(inst1); loop1 = inst1; } dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, intr0, intr1); ticked = 0; inst1 = 0; intr0 = 0; intr1 = 0; READ_TIMESTAMP(loop0); #endif assert(stack_pointer >= f->f_valuestack); /* else underflow */ assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ /* Do periodic things. Doing this every time through the loop would add too much overhead, so we do it only every Nth instruction. We also do it if ``things_to_do'' is set, i.e. when an asynchronous event needs attention (e.g. a signal handler or async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. */ if (--_Py_Ticker < 0) { if (*next_instr == SETUP_FINALLY) { /* Make the last opcode before a try: finally: block uninterruptable. */ goto fast_next_opcode; } _Py_Ticker = _Py_CheckInterval; tstate->tick_counter++; #ifdef WITH_TSC ticked = 1; #endif if (things_to_do) { if (Py_MakePendingCalls() < 0) { why = WHY_EXCEPTION; goto on_error; } if (things_to_do) /* MakePendingCalls() didn't succeed. Force early re-execution of this "periodic" code, possibly after a thread switch */ _Py_Ticker = 0; } #ifdef WITH_THREAD if (interpreter_lock) { /* Give another thread a chance */ if (PyThreadState_Swap(NULL) != tstate) Py_FatalError("ceval: tstate mix-up"); PyThread_release_lock(interpreter_lock); /* Other threads may run now */ PyThread_acquire_lock(interpreter_lock, 1); if (PyThreadState_Swap(tstate) != NULL) Py_FatalError("ceval: orphan tstate"); /* Check for thread interrupts */ if (tstate->async_exc != NULL) { x = tstate->async_exc; tstate->async_exc = NULL; PyErr_SetNone(x); Py_DECREF(x); why = WHY_EXCEPTION; goto on_error; } } #endif } fast_next_opcode: f->f_lasti = INSTR_OFFSET(); /* line-by-line tracing support */ if (tstate->c_tracefunc != NULL && !tstate->tracing) { /* see maybe_call_line_trace for expository comments */ f->f_stacktop = stack_pointer; err = maybe_call_line_trace(tstate->c_tracefunc, tstate->c_traceobj, f, &instr_lb, &instr_ub, &instr_prev); /* Reload possibly changed frame fields */ JUMPTO(f->f_lasti); if (f->f_stacktop != NULL) { stack_pointer = f->f_stacktop; f->f_stacktop = NULL; } if (err) { /* trace function raised an exception */ goto on_error; } } /* Extract opcode and argument */ opcode = NEXTOP(); oparg = 0; /* allows oparg to be stored in a register because it doesn't have to be remembered across a full loop */ if (HAS_ARG(opcode)) oparg = NEXTARG(); dispatch_opcode: #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS dxpairs[lastopcode][opcode]++; lastopcode = opcode; #endif dxp[opcode]++; #endif #ifdef LLTRACE /* Instruction tracing */ if (lltrace) { if (HAS_ARG(opcode)) { printf("%d: %d, %d\n", f->f_lasti, opcode, oparg); } else { printf("%d: %d\n", f->f_lasti, opcode); } } #endif /* Main switch on opcode */ READ_TIMESTAMP(inst0); switch (opcode) { /* BEWARE! It is essential that any operation that fails sets either x to NULL, err to nonzero, or why to anything but WHY_NOT, and that no operation that succeeds does this! */ /* case STOP_CODE: this is an error! */ case NOP: goto fast_next_opcode; case LOAD_FAST: x = GETLOCAL(oparg); if (x != NULL) { Py_INCREF(x); PUSH(x); goto fast_next_opcode; } format_exc_check_arg(PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, PyTuple_GetItem(co->co_varnames, oparg)); break; case LOAD_CONST: x = GETITEM(consts, oparg); Py_INCREF(x); PUSH(x); goto fast_next_opcode; PREDICTED_WITH_ARG(STORE_FAST); case STORE_FAST: v = POP(); SETLOCAL(oparg, v); goto fast_next_opcode; PREDICTED(POP_TOP); case POP_TOP: v = POP(); Py_DECREF(v); goto fast_next_opcode; case ROT_TWO: v = TOP(); w = SECOND(); SET_TOP(w); SET_SECOND(v); goto fast_next_opcode; case ROT_THREE: v = TOP(); w = SECOND(); x = THIRD(); SET_TOP(w); SET_SECOND(x); SET_THIRD(v); goto fast_next_opcode; case ROT_FOUR: u = TOP(); v = SECOND(); w = THIRD(); x = FOURTH(); SET_TOP(v); SET_SECOND(w); SET_THIRD(x); SET_FOURTH(u); goto fast_next_opcode; case DUP_TOP: v = TOP(); Py_INCREF(v); PUSH(v); goto fast_next_opcode; case DUP_TOPX: if (oparg == 2) { x = TOP(); Py_INCREF(x); w = SECOND(); Py_INCREF(w); STACKADJ(2); SET_TOP(x); SET_SECOND(w); goto fast_next_opcode; } else if (oparg == 3) { x = TOP(); Py_INCREF(x); w = SECOND(); Py_INCREF(w); v = THIRD(); Py_INCREF(v); STACKADJ(3); SET_TOP(x); SET_SECOND(w); SET_THIRD(v); goto fast_next_opcode; } Py_FatalError("invalid argument to DUP_TOPX" " (bytecode corruption?)"); break; case UNARY_POSITIVE: v = TOP(); x = PyNumber_Positive(v); Py_DECREF(v); SET_TOP(x); if (x != NULL) continue; break; case UNARY_NEGATIVE: v = TOP(); x = PyNumber_Negative(v); Py_DECREF(v); SET_TOP(x); if (x != NULL) continue; break; case UNARY_NOT: v = TOP(); err = PyObject_IsTrue(v); Py_DECREF(v); if (err == 0) { Py_INCREF(Py_True); SET_TOP(Py_True); continue; } else if (err > 0) { Py_INCREF(Py_False); SET_TOP(Py_False); err = 0; continue; } STACKADJ(-1); break; case UNARY_CONVERT: v = TOP(); x = PyObject_Repr(v); Py_DECREF(v); SET_TOP(x); if (x != NULL) continue; break; case UNARY_INVERT: v = TOP(); x = PyNumber_Invert(v); Py_DECREF(v); SET_TOP(x); if (x != NULL) continue; break; case BINARY_POWER: w = POP(); v = TOP(); x = PyNumber_Power(v, w, Py_None); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_MULTIPLY: w = POP(); v = TOP(); x = PyNumber_Multiply(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_DIVIDE: if (!_Py_QnewFlag) { w = POP(); v = TOP(); x = PyNumber_Divide(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; } /* -Qnew is in effect: fall through to BINARY_TRUE_DIVIDE */ case BINARY_TRUE_DIVIDE: w = POP(); v = TOP(); x = PyNumber_TrueDivide(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_FLOOR_DIVIDE: w = POP(); v = TOP(); x = PyNumber_FloorDivide(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_MODULO: w = POP(); v = TOP(); x = PyNumber_Remainder(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_ADD: w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int + int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a + b; if ((i^a) < 0 && (i^b) < 0) goto slow_add; x = PyInt_FromLong(i); } else if (PyString_CheckExact(v) && PyString_CheckExact(w)) { x = string_concatenate(v, w, f, next_instr); /* string_concatenate consumed the ref to v */ goto skip_decref_vx; } else { slow_add: x = PyNumber_Add(v, w); } Py_DECREF(v); skip_decref_vx: Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_SUBTRACT: w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int - int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a - b; if ((i^a) < 0 && (i^~b) < 0) goto slow_sub; x = PyInt_FromLong(i); } else { slow_sub: x = PyNumber_Subtract(v, w); } Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_SUBSCR: w = POP(); v = TOP(); if (PyList_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: list[int] */ Py_ssize_t i = PyInt_AsSsize_t(w); if (i < 0) i += PyList_GET_SIZE(v); if (i >= 0 && i < PyList_GET_SIZE(v)) { x = PyList_GET_ITEM(v, i); Py_INCREF(x); } else goto slow_get; } else slow_get: x = PyObject_GetItem(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_LSHIFT: w = POP(); v = TOP(); x = PyNumber_Lshift(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_RSHIFT: w = POP(); v = TOP(); x = PyNumber_Rshift(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_AND: w = POP(); v = TOP(); x = PyNumber_And(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_XOR: w = POP(); v = TOP(); x = PyNumber_Xor(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case BINARY_OR: w = POP(); v = TOP(); x = PyNumber_Or(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case LIST_APPEND: w = POP(); v = POP(); err = PyList_Append(v, w); Py_DECREF(v); Py_DECREF(w); if (err == 0) { PREDICT(JUMP_ABSOLUTE); continue; } break; case INPLACE_POWER: w = POP(); v = TOP(); x = PyNumber_InPlacePower(v, w, Py_None); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_MULTIPLY: w = POP(); v = TOP(); x = PyNumber_InPlaceMultiply(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_DIVIDE: if (!_Py_QnewFlag) { w = POP(); v = TOP(); x = PyNumber_InPlaceDivide(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; } /* -Qnew is in effect: fall through to INPLACE_TRUE_DIVIDE */ case INPLACE_TRUE_DIVIDE: w = POP(); v = TOP(); x = PyNumber_InPlaceTrueDivide(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_FLOOR_DIVIDE: w = POP(); v = TOP(); x = PyNumber_InPlaceFloorDivide(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_MODULO: w = POP(); v = TOP(); x = PyNumber_InPlaceRemainder(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_ADD: w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int + int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a + b; if ((i^a) < 0 && (i^b) < 0) goto slow_iadd; x = PyInt_FromLong(i); } else if (PyString_CheckExact(v) && PyString_CheckExact(w)) { x = string_concatenate(v, w, f, next_instr); /* string_concatenate consumed the ref to v */ goto skip_decref_v; } else { slow_iadd: x = PyNumber_InPlaceAdd(v, w); } Py_DECREF(v); skip_decref_v: Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_SUBTRACT: w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int - int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a - b; if ((i^a) < 0 && (i^~b) < 0) goto slow_isub; x = PyInt_FromLong(i); } else { slow_isub: x = PyNumber_InPlaceSubtract(v, w); } Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_LSHIFT: w = POP(); v = TOP(); x = PyNumber_InPlaceLshift(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_RSHIFT: w = POP(); v = TOP(); x = PyNumber_InPlaceRshift(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_AND: w = POP(); v = TOP(); x = PyNumber_InPlaceAnd(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_XOR: w = POP(); v = TOP(); x = PyNumber_InPlaceXor(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case INPLACE_OR: w = POP(); v = TOP(); x = PyNumber_InPlaceOr(v, w); Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case SLICE+0: case SLICE+1: case SLICE+2: case SLICE+3: if ((opcode-SLICE) & 2) w = POP(); else w = NULL; if ((opcode-SLICE) & 1) v = POP(); else v = NULL; u = TOP(); x = apply_slice(u, v, w); Py_DECREF(u); Py_XDECREF(v); Py_XDECREF(w); SET_TOP(x); if (x != NULL) continue; break; case STORE_SLICE+0: case STORE_SLICE+1: case STORE_SLICE+2: case STORE_SLICE+3: if ((opcode-STORE_SLICE) & 2) w = POP(); else w = NULL; if ((opcode-STORE_SLICE) & 1) v = POP(); else v = NULL; u = POP(); t = POP(); err = assign_slice(u, v, w, t); /* u[v:w] = t */ Py_DECREF(t); Py_DECREF(u); Py_XDECREF(v); Py_XDECREF(w); if (err == 0) continue; break; case DELETE_SLICE+0: case DELETE_SLICE+1: case DELETE_SLICE+2: case DELETE_SLICE+3: if ((opcode-DELETE_SLICE) & 2) w = POP(); else w = NULL; if ((opcode-DELETE_SLICE) & 1) v = POP(); else v = NULL; u = POP(); err = assign_slice(u, v, w, (PyObject *)NULL); /* del u[v:w] */ Py_DECREF(u); Py_XDECREF(v); Py_XDECREF(w); if (err == 0) continue; break; case STORE_SUBSCR: w = TOP(); v = SECOND(); u = THIRD(); STACKADJ(-3); /* v[w] = u */ err = PyObject_SetItem(v, w, u); Py_DECREF(u); Py_DECREF(v); Py_DECREF(w); if (err == 0) continue; break; case DELETE_SUBSCR: w = TOP(); v = SECOND(); STACKADJ(-2); /* del v[w] */ err = PyObject_DelItem(v, w); Py_DECREF(v); Py_DECREF(w); if (err == 0) continue; break; case PRINT_EXPR: v = POP(); w = PySys_GetObject("displayhook"); if (w == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.displayhook"); err = -1; x = NULL; } if (err == 0) { x = PyTuple_Pack(1, v); if (x == NULL) err = -1; } if (err == 0) { w = PyEval_CallObject(w, x); Py_XDECREF(w); if (w == NULL) err = -1; } Py_DECREF(v); Py_XDECREF(x); break; case PRINT_ITEM_TO: w = stream = POP(); /* fall through to PRINT_ITEM */ case PRINT_ITEM: v = POP(); if (stream == NULL || stream == Py_None) { w = PySys_GetObject("stdout"); if (w == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); err = -1; } } /* PyFile_SoftSpace() can exececute arbitrary code if sys.stdout is an instance with a __getattr__. If __getattr__ raises an exception, w will be freed, so we need to prevent that temporarily. */ Py_XINCREF(w); if (w != NULL && PyFile_SoftSpace(w, 0)) err = PyFile_WriteString(" ", w); if (err == 0) err = PyFile_WriteObject(v, w, Py_PRINT_RAW); if (err == 0) { /* XXX move into writeobject() ? */ if (PyString_Check(v)) { char *s = PyString_AS_STRING(v); Py_ssize_t len = PyString_GET_SIZE(v); if (len == 0 || !isspace(Py_CHARMASK(s[len-1])) || s[len-1] == ' ') PyFile_SoftSpace(w, 1); } #ifdef Py_USING_UNICODE else if (PyUnicode_Check(v)) { Py_UNICODE *s = PyUnicode_AS_UNICODE(v); Py_ssize_t len = PyUnicode_GET_SIZE(v); if (len == 0 || !Py_UNICODE_ISSPACE(s[len-1]) || s[len-1] == ' ') PyFile_SoftSpace(w, 1); } #endif else PyFile_SoftSpace(w, 1); } Py_XDECREF(w); Py_DECREF(v); Py_XDECREF(stream); stream = NULL; if (err == 0) continue; break; case PRINT_NEWLINE_TO: w = stream = POP(); /* fall through to PRINT_NEWLINE */ case PRINT_NEWLINE: if (stream == NULL || stream == Py_None) { w = PySys_GetObject("stdout"); if (w == NULL) PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); } if (w != NULL) { err = PyFile_WriteString("\n", w); if (err == 0) PyFile_SoftSpace(w, 0); } Py_XDECREF(stream); stream = NULL; break; #ifdef CASE_TOO_BIG default: switch (opcode) { #endif case RAISE_VARARGS: u = v = w = NULL; switch (oparg) { case 3: u = POP(); /* traceback */ /* Fallthrough */ case 2: v = POP(); /* value */ /* Fallthrough */ case 1: w = POP(); /* exc */ case 0: /* Fallthrough */ why = do_raise(w, v, u); break; default: PyErr_SetString(PyExc_SystemError, "bad RAISE_VARARGS oparg"); why = WHY_EXCEPTION; break; } break; case LOAD_LOCALS: if ((x = f->f_locals) != NULL) { Py_INCREF(x); PUSH(x); continue; } PyErr_SetString(PyExc_SystemError, "no locals"); break; case RETURN_VALUE: retval = POP(); why = WHY_RETURN; goto fast_block_end; case YIELD_VALUE: retval = POP(); f->f_stacktop = stack_pointer; why = WHY_YIELD; goto fast_yield; case EXEC_STMT: w = TOP(); v = SECOND(); u = THIRD(); STACKADJ(-3); READ_TIMESTAMP(intr0); err = exec_statement(f, u, v, w); READ_TIMESTAMP(intr1); Py_DECREF(u); Py_DECREF(v); Py_DECREF(w); break; case POP_BLOCK: { PyTryBlock *b = PyFrame_BlockPop(f); while (STACK_LEVEL() > b->b_level) { v = POP(); Py_DECREF(v); } } continue; case END_FINALLY: v = POP(); if (PyInt_Check(v)) { why = (enum why_code) PyInt_AS_LONG(v); assert(why != WHY_YIELD); if (why == WHY_RETURN || why == WHY_CONTINUE) retval = POP(); } else if (PyExceptionClass_Check(v) || PyString_Check(v)) { w = POP(); u = POP(); PyErr_Restore(v, w, u); why = WHY_RERAISE; break; } else if (v != Py_None) { PyErr_SetString(PyExc_SystemError, "'finally' pops bad exception"); why = WHY_EXCEPTION; } Py_DECREF(v); break; case BUILD_CLASS: u = TOP(); v = SECOND(); w = THIRD(); STACKADJ(-2); x = build_class(u, v, w); SET_TOP(x); Py_DECREF(u); Py_DECREF(v); Py_DECREF(w); break; case STORE_NAME: w = GETITEM(names, oparg); v = POP(); if ((x = f->f_locals) != NULL) { if (PyDict_CheckExact(x)) err = PyDict_SetItem(x, w, v); else err = PyObject_SetItem(x, w, v); Py_DECREF(v); if (err == 0) continue; break; } PyErr_Format(PyExc_SystemError, "no locals found when storing %s", PyObject_REPR(w)); break; case DELETE_NAME: w = GETITEM(names, oparg); if ((x = f->f_locals) != NULL) { if ((err = PyObject_DelItem(x, w)) != 0) format_exc_check_arg(PyExc_NameError, NAME_ERROR_MSG ,w); break; } PyErr_Format(PyExc_SystemError, "no locals when deleting %s", PyObject_REPR(w)); break; PREDICTED_WITH_ARG(UNPACK_SEQUENCE); case UNPACK_SEQUENCE: v = POP(); if (PyTuple_CheckExact(v) && PyTuple_GET_SIZE(v) == oparg) { PyObject **items = ((PyTupleObject *)v)->ob_item; while (oparg--) { w = items[oparg]; Py_INCREF(w); PUSH(w); } Py_DECREF(v); continue; } else if (PyList_CheckExact(v) && PyList_GET_SIZE(v) == oparg) { PyObject **items = ((PyListObject *)v)->ob_item; while (oparg--) { w = items[oparg]; Py_INCREF(w); PUSH(w); } } else if (unpack_iterable(v, oparg, stack_pointer + oparg)) stack_pointer += oparg; else { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_SetString(PyExc_TypeError, "unpack non-sequence"); why = WHY_EXCEPTION; } Py_DECREF(v); break; case STORE_ATTR: w = GETITEM(names, oparg); v = TOP(); u = SECOND(); STACKADJ(-2); err = PyObject_SetAttr(v, w, u); /* v.w = u */ Py_DECREF(v); Py_DECREF(u); if (err == 0) continue; break; case DELETE_ATTR: w = GETITEM(names, oparg); v = POP(); err = PyObject_SetAttr(v, w, (PyObject *)NULL); /* del v.w */ Py_DECREF(v); break; case STORE_GLOBAL: w = GETITEM(names, oparg); v = POP(); err = PyDict_SetItem(f->f_globals, w, v); Py_DECREF(v); if (err == 0) continue; break; case DELETE_GLOBAL: w = GETITEM(names, oparg); if ((err = PyDict_DelItem(f->f_globals, w)) != 0) format_exc_check_arg( PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); break; case LOAD_NAME: w = GETITEM(names, oparg); if ((v = f->f_locals) == NULL) { PyErr_Format(PyExc_SystemError, "no locals when loading %s", PyObject_REPR(w)); break; } if (PyDict_CheckExact(v)) { x = PyDict_GetItem(v, w); Py_XINCREF(x); } else { x = PyObject_GetItem(v, w); if (x == NULL && PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_KeyError)) break; PyErr_Clear(); } } if (x == NULL) { x = PyDict_GetItem(f->f_globals, w); if (x == NULL) { x = PyDict_GetItem(f->f_builtins, w); if (x == NULL) { format_exc_check_arg( PyExc_NameError, NAME_ERROR_MSG ,w); break; } } Py_INCREF(x); } PUSH(x); continue; case LOAD_GLOBAL: w = GETITEM(names, oparg); if (PyString_CheckExact(w)) { /* Inline the PyDict_GetItem() calls. WARNING: this is an extreme speed hack. Do not try this at home. */ long hash = ((PyStringObject *)w)->ob_shash; if (hash != -1) { PyDictObject *d; PyDictEntry *e; d = (PyDictObject *)(f->f_globals); e = d->ma_lookup(d, w, hash); if (e == NULL) { x = NULL; break; } x = e->me_value; if (x != NULL) { Py_INCREF(x); PUSH(x); continue; } d = (PyDictObject *)(f->f_builtins); e = d->ma_lookup(d, w, hash); if (e == NULL) { x = NULL; break; } x = e->me_value; if (x != NULL) { Py_INCREF(x); PUSH(x); continue; } goto load_global_error; } } /* This is the un-inlined version of the code above */ x = PyDict_GetItem(f->f_globals, w); if (x == NULL) { x = PyDict_GetItem(f->f_builtins, w); if (x == NULL) { load_global_error: format_exc_check_arg( PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); break; } } Py_INCREF(x); PUSH(x); continue; case DELETE_FAST: x = GETLOCAL(oparg); if (x != NULL) { SETLOCAL(oparg, NULL); continue; } format_exc_check_arg( PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, PyTuple_GetItem(co->co_varnames, oparg) ); break; case LOAD_CLOSURE: x = freevars[oparg]; Py_INCREF(x); PUSH(x); if (x != NULL) continue; break; case LOAD_DEREF: x = freevars[oparg]; w = PyCell_Get(x); if (w != NULL) { PUSH(w); continue; } err = -1; /* Don't stomp existing exception */ if (PyErr_Occurred()) break; if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { v = PyTuple_GET_ITEM(co->co_cellvars, oparg); format_exc_check_arg( PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, v); } else { v = PyTuple_GET_ITEM( co->co_freevars, oparg - PyTuple_GET_SIZE(co->co_cellvars)); format_exc_check_arg( PyExc_NameError, UNBOUNDFREE_ERROR_MSG, v); } break; case STORE_DEREF: w = POP(); x = freevars[oparg]; PyCell_Set(x, w); Py_DECREF(w); continue; case BUILD_TUPLE: x = PyTuple_New(oparg); if (x != NULL) { for (; --oparg >= 0;) { w = POP(); PyTuple_SET_ITEM(x, oparg, w); } PUSH(x); continue; } break; case BUILD_LIST: x = PyList_New(oparg); if (x != NULL) { for (; --oparg >= 0;) { w = POP(); PyList_SET_ITEM(x, oparg, w); } PUSH(x); continue; } break; case BUILD_MAP: x = PyDict_New(); PUSH(x); if (x != NULL) continue; break; case LOAD_ATTR: w = GETITEM(names, oparg); v = TOP(); x = PyObject_GetAttr(v, w); Py_DECREF(v); SET_TOP(x); if (x != NULL) continue; break; case COMPARE_OP: w = POP(); v = TOP(); if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) { /* INLINE: cmp(int, int) */ register long a, b; register int res; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); switch (oparg) { case PyCmp_LT: res = a < b; break; case PyCmp_LE: res = a <= b; break; case PyCmp_EQ: res = a == b; break; case PyCmp_NE: res = a != b; break; case PyCmp_GT: res = a > b; break; case PyCmp_GE: res = a >= b; break; case PyCmp_IS: res = v == w; break; case PyCmp_IS_NOT: res = v != w; break; default: goto slow_compare; } x = res ? Py_True : Py_False; Py_INCREF(x); } else { slow_compare: x = cmp_outcome(oparg, v, w); } Py_DECREF(v); Py_DECREF(w); SET_TOP(x); if (x == NULL) break; PREDICT(JUMP_IF_FALSE); PREDICT(JUMP_IF_TRUE); continue; case IMPORT_NAME: w = GETITEM(names, oparg); x = PyDict_GetItemString(f->f_builtins, "__import__"); if (x == NULL) { PyErr_SetString(PyExc_ImportError, "__import__ not found"); break; } v = POP(); u = TOP(); if (PyInt_AsLong(u) != -1 || PyErr_Occurred()) w = PyTuple_Pack(5, w, f->f_globals, f->f_locals == NULL ? Py_None : f->f_locals, v, u); else w = PyTuple_Pack(4, w, f->f_globals, f->f_locals == NULL ? Py_None : f->f_locals, v); Py_DECREF(v); Py_DECREF(u); if (w == NULL) { u = POP(); x = NULL; break; } READ_TIMESTAMP(intr0); x = PyEval_CallObject(x, w); READ_TIMESTAMP(intr1); Py_DECREF(w); SET_TOP(x); if (x != NULL) continue; break; case IMPORT_STAR: v = POP(); PyFrame_FastToLocals(f); if ((x = f->f_locals) == NULL) { PyErr_SetString(PyExc_SystemError, "no locals found during 'import *'"); break; } READ_TIMESTAMP(intr0); err = import_all_from(x, v); READ_TIMESTAMP(intr1); PyFrame_LocalsToFast(f, 0); Py_DECREF(v); if (err == 0) continue; break; case IMPORT_FROM: w = GETITEM(names, oparg); v = TOP(); READ_TIMESTAMP(intr0); x = import_from(v, w); READ_TIMESTAMP(intr1); PUSH(x); if (x != NULL) continue; break; case JUMP_FORWARD: JUMPBY(oparg); goto fast_next_opcode; PREDICTED_WITH_ARG(JUMP_IF_FALSE); case JUMP_IF_FALSE: w = TOP(); if (w == Py_True) { PREDICT(POP_TOP); goto fast_next_opcode; } if (w == Py_False) { JUMPBY(oparg); goto fast_next_opcode; } err = PyObject_IsTrue(w); if (err > 0) err = 0; else if (err == 0) JUMPBY(oparg); else break; continue; PREDICTED_WITH_ARG(JUMP_IF_TRUE); case JUMP_IF_TRUE: w = TOP(); if (w == Py_False) { PREDICT(POP_TOP); goto fast_next_opcode; } if (w == Py_True) { JUMPBY(oparg); goto fast_next_opcode; } err = PyObject_IsTrue(w); if (err > 0) { err = 0; JUMPBY(oparg); } else if (err == 0) ; else break; continue; PREDICTED_WITH_ARG(JUMP_ABSOLUTE); case JUMP_ABSOLUTE: JUMPTO(oparg); continue; case GET_ITER: /* before: [obj]; after [getiter(obj)] */ v = TOP(); x = PyObject_GetIter(v); Py_DECREF(v); if (x != NULL) { SET_TOP(x); PREDICT(FOR_ITER); continue; } STACKADJ(-1); break; PREDICTED_WITH_ARG(FOR_ITER); case FOR_ITER: /* before: [iter]; after: [iter, iter()] *or* [] */ v = TOP(); x = (*v->ob_type->tp_iternext)(v); if (x != NULL) { PUSH(x); PREDICT(STORE_FAST); PREDICT(UNPACK_SEQUENCE); continue; } if (PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_StopIteration)) break; PyErr_Clear(); } /* iterator ended normally */ x = v = POP(); Py_DECREF(v); JUMPBY(oparg); continue; case BREAK_LOOP: why = WHY_BREAK; goto fast_block_end; case CONTINUE_LOOP: retval = PyInt_FromLong(oparg); if (!retval) { x = NULL; break; } why = WHY_CONTINUE; goto fast_block_end; case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: /* NOTE: If you add any new block-setup opcodes that are not try/except/finally handlers, you may need to update the PyGen_NeedsFinalizing() function. */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); continue; case WITH_CLEANUP: { /* TOP is the context.__exit__ bound method. Below that are 1-3 values indicating how/why we entered the finally clause: - SECOND = None - (SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval - SECOND = WHY_*; no retval below it - (SECOND, THIRD, FOURTH) = exc_info() In the last case, we must call TOP(SECOND, THIRD, FOURTH) otherwise we must call TOP(None, None, None) In addition, if the stack represents an exception, *and* the function call returns a 'true' value, we "zap" this information, to prevent END_FINALLY from re-raising the exception. (But non-local gotos should still be resumed.) */ x = TOP(); u = SECOND(); if (PyInt_Check(u) || u == Py_None) { u = v = w = Py_None; } else { v = THIRD(); w = FOURTH(); } /* XXX Not the fastest way to call it... */ x = PyObject_CallFunctionObjArgs(x, u, v, w, NULL); if (x == NULL) break; /* Go to error exit */ if (u != Py_None && PyObject_IsTrue(x)) { /* There was an exception and a true return */ Py_DECREF(x); x = TOP(); /* Again */ STACKADJ(-3); Py_INCREF(Py_None); SET_TOP(Py_None); Py_DECREF(x); Py_DECREF(u); Py_DECREF(v); Py_DECREF(w); } else { /* Let END_FINALLY do its thing */ Py_DECREF(x); x = POP(); Py_DECREF(x); } break; } case CALL_FUNCTION: { PyObject **sp; PCALL(PCALL_ALL); sp = stack_pointer; #ifdef WITH_TSC x = call_function(&sp, oparg, &intr0, &intr1); #else x = call_function(&sp, oparg); #endif stack_pointer = sp; PUSH(x); if (x != NULL) continue; break; } case CALL_FUNCTION_VAR: case CALL_FUNCTION_KW: case CALL_FUNCTION_VAR_KW: { int na = oparg & 0xff; int nk = (oparg>>8) & 0xff; int flags = (opcode - CALL_FUNCTION) & 3; int n = na + 2 * nk; PyObject **pfunc, *func, **sp; PCALL(PCALL_ALL); if (flags & CALL_FLAG_VAR) n++; if (flags & CALL_FLAG_KW) n++; pfunc = stack_pointer - n - 1; func = *pfunc; if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { PyObject *self = PyMethod_GET_SELF(func); Py_INCREF(self); func = PyMethod_GET_FUNCTION(func); Py_INCREF(func); Py_DECREF(*pfunc); *pfunc = self; na++; n++; } else Py_INCREF(func); sp = stack_pointer; READ_TIMESTAMP(intr0); x = ext_do_call(func, &sp, flags, na, nk); READ_TIMESTAMP(intr1); stack_pointer = sp; Py_DECREF(func); while (stack_pointer > pfunc) { w = POP(); Py_DECREF(w); } PUSH(x); if (x != NULL) continue; break; } case MAKE_FUNCTION: v = POP(); /* code object */ x = PyFunction_New(v, f->f_globals); Py_DECREF(v); /* XXX Maybe this should be a separate opcode? */ if (x != NULL && oparg > 0) { v = PyTuple_New(oparg); if (v == NULL) { Py_DECREF(x); x = NULL; break; } while (--oparg >= 0) { w = POP(); PyTuple_SET_ITEM(v, oparg, w); } err = PyFunction_SetDefaults(x, v); Py_DECREF(v); } PUSH(x); break; case MAKE_CLOSURE: { v = POP(); /* code object */ x = PyFunction_New(v, f->f_globals); Py_DECREF(v); if (x != NULL) { v = POP(); err = PyFunction_SetClosure(x, v); Py_DECREF(v); } if (x != NULL && oparg > 0) { v = PyTuple_New(oparg); if (v == NULL) { Py_DECREF(x); x = NULL; break; } while (--oparg >= 0) { w = POP(); PyTuple_SET_ITEM(v, oparg, w); } err = PyFunction_SetDefaults(x, v); Py_DECREF(v); } PUSH(x); break; } case BUILD_SLICE: if (oparg == 3) w = POP(); else w = NULL; v = POP(); u = TOP(); x = PySlice_New(u, v, w); Py_DECREF(u); Py_DECREF(v); Py_XDECREF(w); SET_TOP(x); if (x != NULL) continue; break; case EXTENDED_ARG: opcode = NEXTOP(); oparg = oparg<<16 | NEXTARG(); goto dispatch_opcode; default: fprintf(stderr, "XXX lineno: %d, opcode: %d\n", PyCode_Addr2Line(f->f_code, f->f_lasti), opcode); PyErr_SetString(PyExc_SystemError, "unknown opcode"); why = WHY_EXCEPTION; break; #ifdef CASE_TOO_BIG } #endif } /* switch */ on_error: READ_TIMESTAMP(inst1); /* Quickly continue if no error occurred */ if (why == WHY_NOT) { if (err == 0 && x != NULL) { #ifdef CHECKEXC /* This check is expensive! */ if (PyErr_Occurred()) fprintf(stderr, "XXX undetected error\n"); else { #endif READ_TIMESTAMP(loop1); continue; /* Normal, fast path */ #ifdef CHECKEXC } #endif } why = WHY_EXCEPTION; x = Py_None; err = 0; } /* Double-check exception status */ if (why == WHY_EXCEPTION || why == WHY_RERAISE) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_SystemError, "error return without exception set"); why = WHY_EXCEPTION; } } #ifdef CHECKEXC else { /* This check is expensive! */ if (PyErr_Occurred()) { char buf[1024]; sprintf(buf, "Stack unwind with exception " "set and why=%d", why); Py_FatalError(buf); } } #endif /* Log traceback info if this is a real exception */ if (why == WHY_EXCEPTION) { PyTraceBack_Here(f); if (tstate->c_tracefunc != NULL) call_exc_trace(tstate->c_tracefunc, tstate->c_traceobj, f); } /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ if (why == WHY_RERAISE) why = WHY_EXCEPTION; /* Unwind stacks if a (pseudo) exception occurred */ fast_block_end: while (why != WHY_NOT && f->f_iblock > 0) { PyTryBlock *b = PyFrame_BlockPop(f); assert(why != WHY_YIELD); if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { /* For a continue inside a try block, don't pop the block for the loop. */ PyFrame_BlockSetup(f, b->b_type, b->b_handler, b->b_level); why = WHY_NOT; JUMPTO(PyInt_AS_LONG(retval)); Py_DECREF(retval); break; } while (STACK_LEVEL() > b->b_level) { v = POP(); Py_XDECREF(v); } if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { why = WHY_NOT; JUMPTO(b->b_handler); break; } if (b->b_type == SETUP_FINALLY || (b->b_type == SETUP_EXCEPT && why == WHY_EXCEPTION)) { if (why == WHY_EXCEPTION) { PyObject *exc, *val, *tb; PyErr_Fetch(&exc, &val, &tb); if (val == NULL) { val = Py_None; Py_INCREF(val); } /* Make the raw exception data available to the handler, so a program can emulate the Python main loop. Don't do this for 'finally'. */ if (b->b_type == SETUP_EXCEPT) { PyErr_NormalizeException( &exc, &val, &tb); set_exc_info(tstate, exc, val, tb); } if (tb == NULL) { Py_INCREF(Py_None); PUSH(Py_None); } else PUSH(tb); PUSH(val); PUSH(exc); } else { if (why & (WHY_RETURN | WHY_CONTINUE)) PUSH(retval); v = PyInt_FromLong((long)why); PUSH(v); } why = WHY_NOT; JUMPTO(b->b_handler); break; } } /* unwind stack */ /* End the loop if we still have an error (or return) */ if (why != WHY_NOT) break; READ_TIMESTAMP(loop1); } /* main loop */ assert(why != WHY_YIELD); /* Pop remaining stack entries. */ while (!EMPTY()) { v = POP(); Py_XDECREF(v); } if (why != WHY_RETURN) retval = NULL; fast_yield: if (tstate->use_tracing) { if (tstate->c_tracefunc) { if (why == WHY_RETURN || why == WHY_YIELD) { if (call_trace(tstate->c_tracefunc, tstate->c_traceobj, f, PyTrace_RETURN, retval)) { Py_XDECREF(retval); retval = NULL; why = WHY_EXCEPTION; } } else if (why == WHY_EXCEPTION) { call_trace_protected(tstate->c_tracefunc, tstate->c_traceobj, f, PyTrace_RETURN, NULL); } } if (tstate->c_profilefunc) { if (why == WHY_EXCEPTION) call_trace_protected(tstate->c_profilefunc, tstate->c_profileobj, f, PyTrace_RETURN, NULL); else if (call_trace(tstate->c_profilefunc, tstate->c_profileobj, f, PyTrace_RETURN, retval)) { Py_XDECREF(retval); retval = NULL; why = WHY_EXCEPTION; } } } if (tstate->frame->f_exc_type != NULL) reset_exc_info(tstate); else { assert(tstate->frame->f_exc_value == NULL); assert(tstate->frame->f_exc_traceback == NULL); } /* pop frame */ exit_eval_frame: Py_LeaveRecursiveCall(); tstate->frame = f->f_back; return retval; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/cheetah_example.html000066400000000000000000000004331250413007300276720ustar00rootroot00000000000000 $title #for $client in $clients #end for
$client.surname, $client.firstname $client.email
pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/classes.dylan000066400000000000000000000052221250413007300263570ustar00rootroot00000000000000module: sample comment: for make sure that does not highlight per word. and it continues on to the next line. define class () slot serial-number :: = unique-serial-number(); constant slot model-name :: , required-init-keyword: model:; each-subclass slot has-sunroof? :: , init-keyword: sunroof?:, init-value: #f; keyword foo:; required keyword bar:; end class ; define class () end class ; let flying-car = make(); let car? :: = #f; let prefixed-car :: = #f; let model :: = #f; define constant $empty-string = ""; define constant $escaped-backslash = '\\'; define constant $escaped-single-quote = '\''; define variable *unique-serial-number* = 0; define function unique-serial-number() => (usn :: ) let serial = *unique-serial-number*; *unique-serial-number* := *unique-serial-number* + 1; serial; end function; define constant $blue-car = make(, model: "Viper"); define constant $black-car = make(, model: "Town Car", sunroof?: #t); define constant $red-car = make(, model: "F40", sunroof?: #f); define method foo() => _ :: #t end method; define method foo() => _ :: ; #t end method; define method \+ (offset1 :: , offset2 :: ) => (sum :: ) let sum = offset1.total-seconds + offset2.total-seconds; make(, total-seconds: sum); end method \+; define method bar () 1 | 2 & 3 end if (bar) 1 elseif (foo) 2 else 3 end if; select (foo by instance?) => 1 otherwise => 3 end select; /* multi line comment */ /* multi line comments /* can be */ nested */ define constant $symbol = #"hello"; define variable *vector* = #[3.5, 5] define constant $list = #(1, 2); define constant $pair = #(1 . "foo") let octal-number = #o238; let hex-number = #x3890ADEF; let binary-number = #b1010; let float-exponent = 3.5e10; block (return) with-lock (lock) return(); end; exception (e :: ) format-out("Oh no"); cleanup return(); afterwards format-out("Hello"); end; define macro repeat { repeat ?:body end } => { block (?=stop!) local method again() ?body; again() end; again(); end } end macro repeat; define macro with-decoded-seconds { with-decoded-seconds (?max:variable, ?min:variable, ?sec:variable = ?time:expression) ?:body end } => { let (?max, ?min, ?sec) = decode-total-seconds(?time); ?body } end macro; let x = "This size call should be seen as a builtin despite the odd case.".siZe; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/clojure-weird-keywords.clj000066400000000000000000000004621250413007300310040ustar00rootroot00000000000000; Note, clojure lexer is here (and is a good deal more liberal than the language spec: ; https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/LispReader.java#L62 (defn valid [#^java.lang.reflect.Method meth] [:keyword :#initial-hash :h#sh-in-middle :hash-at-end# #js {:keyword "value"}]) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/condensed_ruby.rb000066400000000000000000000013671250413007300272270ustar00rootroot00000000000000# Server: ruby p2p.rb password server server-uri merge-servers # Sample: ruby p2p.rb foobar server druby://localhost:1337 druby://foo.bar:1337 # Client: ruby p2p.rb password client server-uri download-pattern # Sample: ruby p2p.rb foobar client druby://localhost:1337 *.rb require'drb';F,D,C,P,M,U,*O=File,Class,Dir,*ARGV;def s(p)F.split(p[/[^|].*/])[-1 ]end;def c(u);DRbObject.new((),u)end;def x(u)[P,u].hash;end;M=="client"&&c(U).f( x(U)).each{|n|p,c=x(n),c(n);(c.f(p,O[0],0).map{|f|s f}-D["*"]).each{|f|F.open(f, "w"){|o|o< R x y -> False. (** Opaque for proof-search. *) Typeclasses Opaque complement. (** These are convertible. *) Lemma complement_inverse : forall A (R : relation A), complement (inverse R) = inverse (complement R). Proof. reflexivity. Qed. (** We rebind relations in separate classes to be able to overload each proof. *) Set Implicit Arguments. Unset Strict Implicit. Class Reflexive {A} (R : relation A) := reflexivity : forall x, R x x. Class Irreflexive {A} (R : relation A) := irreflexivity : Reflexive (complement R). Hint Extern 1 (Reflexive (complement _)) => class_apply @irreflexivity : typeclass_instances. Class Symmetric {A} (R : relation A) := symmetry : forall x y, R x y -> R y x. Class Asymmetric {A} (R : relation A) := asymmetry : forall x y, R x y -> R y x -> False. Class Transitive {A} (R : relation A) := transitivity : forall x y z, R x y -> R y z -> R x z. Hint Resolve @irreflexivity : ord. Unset Implicit Arguments. (** A HintDb for relations. *) Ltac solve_relation := match goal with | [ |- ?R ?x ?x ] => reflexivity | [ H : ?R ?x ?y |- ?R ?y ?x ] => symmetry ; exact H end. Hint Extern 4 => solve_relation : relations. (** We can already dualize all these properties. *) Generalizable Variables A B C D R S T U l eqA eqB eqC eqD. Lemma flip_Reflexive `{Reflexive A R} : Reflexive (flip R). Proof. tauto. Qed. Hint Extern 3 (Reflexive (flip _)) => apply flip_Reflexive : typeclass_instances. Program Definition flip_Irreflexive `(Irreflexive A R) : Irreflexive (flip R) := irreflexivity (R:=R). Program Definition flip_Symmetric `(Symmetric A R) : Symmetric (flip R) := fun x y H => symmetry (R:=R) H. Program Definition flip_Asymmetric `(Asymmetric A R) : Asymmetric (flip R) := fun x y H H' => asymmetry (R:=R) H H'. Program Definition flip_Transitive `(Transitive A R) : Transitive (flip R) := fun x y z H H' => transitivity (R:=R) H' H. Hint Extern 3 (Irreflexive (flip _)) => class_apply flip_Irreflexive : typeclass_instances. Hint Extern 3 (Symmetric (flip _)) => class_apply flip_Symmetric : typeclass_instances. Hint Extern 3 (Asymmetric (flip _)) => class_apply flip_Asymmetric : typeclass_instances. Hint Extern 3 (Transitive (flip _)) => class_apply flip_Transitive : typeclass_instances. Definition Reflexive_complement_Irreflexive `(Reflexive A (R : relation A)) : Irreflexive (complement R). Proof. firstorder. Qed. Definition complement_Symmetric `(Symmetric A (R : relation A)) : Symmetric (complement R). Proof. firstorder. Qed. Hint Extern 3 (Symmetric (complement _)) => class_apply complement_Symmetric : typeclass_instances. Hint Extern 3 (Irreflexive (complement _)) => class_apply Reflexive_complement_Irreflexive : typeclass_instances. (** * Standard instances. *) Ltac reduce_hyp H := match type of H with | context [ _ <-> _ ] => fail 1 | _ => red in H ; try reduce_hyp H end. Ltac reduce_goal := match goal with | [ |- _ <-> _ ] => fail 1 | _ => red ; intros ; try reduce_goal end. Tactic Notation "reduce" "in" hyp(Hid) := reduce_hyp Hid. Ltac reduce := reduce_goal. Tactic Notation "apply" "*" constr(t) := first [ refine t | refine (t _) | refine (t _ _) | refine (t _ _ _) | refine (t _ _ _ _) | refine (t _ _ _ _ _) | refine (t _ _ _ _ _ _) | refine (t _ _ _ _ _ _ _) ]. Ltac simpl_relation := unfold flip, impl, arrow ; try reduce ; program_simpl ; try ( solve [ intuition ]). Local Obligation Tactic := simpl_relation. (** Logical implication. *) Program Instance impl_Reflexive : Reflexive impl. Program Instance impl_Transitive : Transitive impl. (** Logical equivalence. *) Program Instance iff_Reflexive : Reflexive iff. Program Instance iff_Symmetric : Symmetric iff. Program Instance iff_Transitive : Transitive iff. (** Leibniz equality. *) Instance eq_Reflexive {A} : Reflexive (@eq A) := @eq_refl A. Instance eq_Symmetric {A} : Symmetric (@eq A) := @eq_sym A. Instance eq_Transitive {A} : Transitive (@eq A) := @eq_trans A. (** Various combinations of reflexivity, symmetry and transitivity. *) (** A [PreOrder] is both Reflexive and Transitive. *) Class PreOrder {A} (R : relation A) : Prop := { PreOrder_Reflexive :> Reflexive R ; PreOrder_Transitive :> Transitive R }. (** A partial equivalence relation is Symmetric and Transitive. *) Class PER {A} (R : relation A) : Prop := { PER_Symmetric :> Symmetric R ; PER_Transitive :> Transitive R }. (** Equivalence relations. *) Class Equivalence {A} (R : relation A) : Prop := { Equivalence_Reflexive :> Reflexive R ; Equivalence_Symmetric :> Symmetric R ; Equivalence_Transitive :> Transitive R }. (** An Equivalence is a PER plus reflexivity. *) Instance Equivalence_PER `(Equivalence A R) : PER R | 10 := { PER_Symmetric := Equivalence_Symmetric ; PER_Transitive := Equivalence_Transitive }. (** We can now define antisymmetry w.r.t. an equivalence relation on the carrier. *) Class Antisymmetric A eqA `{equ : Equivalence A eqA} (R : relation A) := antisymmetry : forall {x y}, R x y -> R y x -> eqA x y. Program Definition flip_antiSymmetric `(Antisymmetric A eqA R) : Antisymmetric A eqA (flip R). Proof. firstorder. Qed. (** Leibinz equality [eq] is an equivalence relation. The instance has low priority as it is always applicable if only the type is constrained. *) Program Instance eq_equivalence : Equivalence (@eq A) | 10. (** Logical equivalence [iff] is an equivalence relation. *) Program Instance iff_equivalence : Equivalence iff. (** We now develop a generalization of results on relations for arbitrary predicates. The resulting theory can be applied to homogeneous binary relations but also to arbitrary n-ary predicates. *) Local Open Scope list_scope. (* Notation " [ ] " := nil : list_scope. *) (* Notation " [ x ; .. ; y ] " := (cons x .. (cons y nil) ..) (at level 1) : list_scope. *) (** A compact representation of non-dependent arities, with the codomain singled-out. *) Fixpoint arrows (l : list Type) (r : Type) : Type := match l with | nil => r | A :: l' => A -> arrows l' r end. (** We can define abbreviations for operation and relation types based on [arrows]. *) Definition unary_operation A := arrows (A::nil) A. Definition binary_operation A := arrows (A::A::nil) A. Definition ternary_operation A := arrows (A::A::A::nil) A. (** We define n-ary [predicate]s as functions into [Prop]. *) Notation predicate l := (arrows l Prop). (** Unary predicates, or sets. *) Definition unary_predicate A := predicate (A::nil). (** Homogeneous binary relations, equivalent to [relation A]. *) Definition binary_relation A := predicate (A::A::nil). (** We can close a predicate by universal or existential quantification. *) Fixpoint predicate_all (l : list Type) : predicate l -> Prop := match l with | nil => fun f => f | A :: tl => fun f => forall x : A, predicate_all tl (f x) end. Fixpoint predicate_exists (l : list Type) : predicate l -> Prop := match l with | nil => fun f => f | A :: tl => fun f => exists x : A, predicate_exists tl (f x) end. (** Pointwise extension of a binary operation on [T] to a binary operation on functions whose codomain is [T]. For an operator on [Prop] this lifts the operator to a binary operation. *) Fixpoint pointwise_extension {T : Type} (op : binary_operation T) (l : list Type) : binary_operation (arrows l T) := match l with | nil => fun R R' => op R R' | A :: tl => fun R R' => fun x => pointwise_extension op tl (R x) (R' x) end. (** Pointwise lifting, equivalent to doing [pointwise_extension] and closing using [predicate_all]. *) Fixpoint pointwise_lifting (op : binary_relation Prop) (l : list Type) : binary_relation (predicate l) := match l with | nil => fun R R' => op R R' | A :: tl => fun R R' => forall x, pointwise_lifting op tl (R x) (R' x) end. (** The n-ary equivalence relation, defined by lifting the 0-ary [iff] relation. *) Definition predicate_equivalence {l : list Type} : binary_relation (predicate l) := pointwise_lifting iff l. (** The n-ary implication relation, defined by lifting the 0-ary [impl] relation. *) Definition predicate_implication {l : list Type} := pointwise_lifting impl l. (** Notations for pointwise equivalence and implication of predicates. *) Infix "<∙>" := predicate_equivalence (at level 95, no associativity) : predicate_scope. Infix "-∙>" := predicate_implication (at level 70, right associativity) : predicate_scope. Open Local Scope predicate_scope. (** The pointwise liftings of conjunction and disjunctions. Note that these are [binary_operation]s, building new relations out of old ones. *) Definition predicate_intersection := pointwise_extension and. Definition predicate_union := pointwise_extension or. Infix "/∙\" := predicate_intersection (at level 80, right associativity) : predicate_scope. Infix "\∙/" := predicate_union (at level 85, right associativity) : predicate_scope. (** The always [True] and always [False] predicates. *) Fixpoint true_predicate {l : list Type} : predicate l := match l with | nil => True | A :: tl => fun _ => @true_predicate tl end. Fixpoint false_predicate {l : list Type} : predicate l := match l with | nil => False | A :: tl => fun _ => @false_predicate tl end. Notation "∙⊤∙" := true_predicate : predicate_scope. Notation "∙⊥∙" := false_predicate : predicate_scope. (** Predicate equivalence is an equivalence, and predicate implication defines a preorder. *) Program Instance predicate_equivalence_equivalence : Equivalence (@predicate_equivalence l). Next Obligation. induction l ; firstorder. Qed. Next Obligation. induction l ; firstorder. Qed. Next Obligation. fold pointwise_lifting. induction l. firstorder. intros. simpl in *. pose (IHl (x x0) (y x0) (z x0)). firstorder. Qed. Program Instance predicate_implication_preorder : PreOrder (@predicate_implication l). Next Obligation. induction l ; firstorder. Qed. Next Obligation. induction l. firstorder. unfold predicate_implication in *. simpl in *. intro. pose (IHl (x x0) (y x0) (z x0)). firstorder. Qed. (** We define the various operations which define the algebra on binary relations, from the general ones. *) Definition relation_equivalence {A : Type} : relation (relation A) := @predicate_equivalence (_::_::nil). Class subrelation {A:Type} (R R' : relation A) : Prop := is_subrelation : @predicate_implication (A::A::nil) R R'. Implicit Arguments subrelation [[A]]. Definition relation_conjunction {A} (R : relation A) (R' : relation A) : relation A := @predicate_intersection (A::A::nil) R R'. Definition relation_disjunction {A} (R : relation A) (R' : relation A) : relation A := @predicate_union (A::A::nil) R R'. (** Relation equivalence is an equivalence, and subrelation defines a partial order. *) Set Automatic Introduction. Instance relation_equivalence_equivalence (A : Type) : Equivalence (@relation_equivalence A). Proof. exact (@predicate_equivalence_equivalence (A::A::nil)). Qed. Instance relation_implication_preorder A : PreOrder (@subrelation A). Proof. exact (@predicate_implication_preorder (A::A::nil)). Qed. (** *** Partial Order. A partial order is a preorder which is additionally antisymmetric. We give an equivalent definition, up-to an equivalence relation on the carrier. *) Class PartialOrder {A} eqA `{equ : Equivalence A eqA} R `{preo : PreOrder A R} := partial_order_equivalence : relation_equivalence eqA (relation_conjunction R (inverse R)). (** The equivalence proof is sufficient for proving that [R] must be a morphism for equivalence (see Morphisms). It is also sufficient to show that [R] is antisymmetric w.r.t. [eqA] *) Instance partial_order_antisym `(PartialOrder A eqA R) : ! Antisymmetric A eqA R. Proof with auto. reduce_goal. pose proof partial_order_equivalence as poe. do 3 red in poe. apply <- poe. firstorder. Qed. (** The partial order defined by subrelation and relation equivalence. *) Program Instance subrelation_partial_order : ! PartialOrder (relation A) relation_equivalence subrelation. Next Obligation. Proof. unfold relation_equivalence in *. firstorder. Qed. Typeclasses Opaque arrows predicate_implication predicate_equivalence relation_equivalence pointwise_lifting. (** Rewrite relation on a given support: declares a relation as a rewrite relation for use by the generalized rewriting tactic. It helps choosing if a rewrite should be handled by the generalized or the regular rewriting tactic using leibniz equality. Users can declare an [RewriteRelation A RA] anywhere to declare default relations. This is also done automatically by the [Declare Relation A RA] commands. *) Class RewriteRelation {A : Type} (RA : relation A). Instance: RewriteRelation impl. Instance: RewriteRelation iff. Instance: RewriteRelation (@relation_equivalence A). (** Any [Equivalence] declared in the context is automatically considered a rewrite relation. *) Instance equivalence_rewrite_relation `(Equivalence A eqA) : RewriteRelation eqA. (** Strict Order *) Class StrictOrder {A : Type} (R : relation A) := { StrictOrder_Irreflexive :> Irreflexive R ; StrictOrder_Transitive :> Transitive R }. Instance StrictOrder_Asymmetric `(StrictOrder A R) : Asymmetric R. Proof. firstorder. Qed. (** Inversing a [StrictOrder] gives another [StrictOrder] *) Lemma StrictOrder_inverse `(StrictOrder A R) : StrictOrder (inverse R). Proof. firstorder. Qed. (** Same for [PartialOrder]. *) Lemma PreOrder_inverse `(PreOrder A R) : PreOrder (inverse R). Proof. firstorder. Qed. Hint Extern 3 (StrictOrder (inverse _)) => class_apply StrictOrder_inverse : typeclass_instances. Hint Extern 3 (PreOrder (inverse _)) => class_apply PreOrder_inverse : typeclass_instances. Lemma PartialOrder_inverse `(PartialOrder A eqA R) : PartialOrder eqA (inverse R). Proof. firstorder. Qed. Hint Extern 3 (PartialOrder (inverse _)) => class_apply PartialOrder_inverse : typeclass_instances. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/core.cljs000066400000000000000000000030231250413007300254730ustar00rootroot00000000000000 (ns bounder.core (:require [bounder.html :as html] [domina :refer [value set-value! single-node]] [domina.css :refer [sel]] [lowline.functions :refer [debounce]] [enfocus.core :refer [at]] [cljs.reader :as reader] [clojure.string :as s]) (:require-macros [enfocus.macros :as em])) (def filter-input (single-node (sel ".search input"))) (defn project-matches [query project] (let [words (cons (:name project) (map name (:categories project))) to-match (->> words (s/join "") (s/lower-case))] (<= 0 (.indexOf to-match (s/lower-case query))))) (defn apply-filter-for [projects] (let [query (value filter-input)] (html/render-projects (filter (partial project-matches query) projects)))) (defn filter-category [projects evt] (let [target (.-currentTarget evt)] (set-value! filter-input (.-innerHTML target)) (apply-filter-for projects))) (defn init-listeners [projects] (at js/document ["input"] (em/listen :keyup (debounce (partial apply-filter-for projects) 500)) [".category-links li"] (em/listen :click (partial filter-category projects)))) (defn init [projects-edn] (let [projects (reader/read-string projects-edn)] (init-listeners projects) (html/render-projects projects) (html/loaded))) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/database.pytb000066400000000000000000000017111250413007300263340ustar00rootroot00000000000000Text before Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/trac/web/main.py", line 314, in dispatch_request dispatcher.dispatch(req) File "/usr/lib/python2.3/site-packages/trac/web/main.py", line 186, in dispatch req.session = Session(self.env, req) File "/usr/lib/python2.3/site-packages/trac/web/session.py", line 52, in __init__ self.promote_session(sid) File "/usr/lib/python2.3/site-packages/trac/web/session.py", line 125, in promote_session "AND authenticated=0", (sid,)) File "/usr/lib/python2.3/site-packages/trac/db/util.py", line 47, in execute return self.cursor.execute(sql_escape_percent(sql), args) File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 44, in execute args or []) File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 36, in _rollback_on_error return function(self, *args, **kwargs) OperationalError: database is locked Text after pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/de.MoinMoin.po000066400000000000000000002123021250413007300263440ustar00rootroot00000000000000## Please edit system and help pages ONLY in the moinmaster wiki! For more ## information, please see MoinMaster:MoinPagesEditorGroup. ##master-page:None ##master-date:None #acl MoinPagesEditorGroup:read,write,delete,revert All:read #format gettext #language de # # MoinMoin de system text translation # msgid "" msgstr "" "Project-Id-Version: MoinMoin 1.6\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2007-05-26 23:12+0200\n" "PO-Revision-Date: 2005-09-21 00:00+0100\n" "Last-Translator: Thomas Waldmann \n" "Language-Team: German \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Language: Deutsch\n" "X-Language-in-English: German\n" "X-HasWikiMarkup: True\n" "X-Direction: ltr\n" msgid "" "This wiki is not enabled for mail processing.\n" "Contact the owner of the wiki, who can enable email." msgstr "" "In diesem Wiki ist Mail-Verarbeitung nicht eingeschaltet.\n" "Bitte kontaktieren Sie den Eigentümer des Wiki, der die Mailfunktionen " "einschalten kann." msgid "Please provide a valid email address!" msgstr "Bitte eine gültige E-Mail-Adresse angeben!" #, python-format msgid "Found no account matching the given email address '%(email)s'!" msgstr "" "Es wurde kein Benutzerkonto mit der E-Mail-Adresse '%(email)s' gefunden!" msgid "Use UserPreferences to change your settings or create an account." msgstr "" "Benutzen Sie BenutzerEinstellungen, um Ihre Einstellungen zu ändern oder ein " "Konto zu erzeugen." msgid "Empty user name. Please enter a user name." msgstr "Leerer Benutzername, bitte geben Sie einen Benutzernamen ein." #, python-format msgid "" "Invalid user name {{{'%s'}}}.\n" "Name may contain any Unicode alpha numeric character, with optional one\n" "space between words. Group page name is not allowed." msgstr "" "Ungültiger Benutzername {{{'%s'}}}.\n" "Der Name darf beliebige alphanumerische Unicode-Zeichen enthalten, mit " "optional einem\n" "Leerzeichen zwischen den Worten. Gruppennamen sind nicht erlaubt." msgid "This user name already belongs to somebody else." msgstr "Dieser Benutzername gehört bereits jemand anderem." msgid "Passwords don't match!" msgstr "Die Passworte sind nicht gleich!" msgid "Please specify a password!" msgstr "Bitte geben Sie ein Passwort an!" msgid "" "Please provide your email address. If you lose your login information, you " "can get it by email." msgstr "" "Bitte geben Sie Ihre E-Mail-Adresse an. Wenn Sie Ihre Login-Informationen " "verlieren können Sie sie per E-Mail wieder bekommen." msgid "This email already belongs to somebody else." msgstr "Diese E-Mail-Adresse gehört bereits jemand anderem." msgid "User account created! You can use this account to login now..." msgstr "" "Es wurde ein Benutzerkonto für Sie angelegt. Sie können sich nun anmelden..." msgid "Use UserPreferences to change settings of the selected user account" msgstr "" "Benutzen Sie BenutzerEinstellungen, um die Einstellungen des ausgewählten " "Benutzers zu ändern." #, python-format msgid "The theme '%(theme_name)s' could not be loaded!" msgstr "Das Theme '%(theme_name)s' konnte nicht geladen werden!" msgid "User preferences saved!" msgstr "Persönliche Einstellungen gespeichert!" msgid "Default" msgstr "Standardeinstellung" msgid "" msgstr "" msgid "the one preferred" msgstr "der Bevorzugte" msgid "free choice" msgstr "Freie Auswahl" msgid "Select User" msgstr "Benutzer auswählen" msgid "Save" msgstr "Speichern" msgid "Cancel" msgstr "Abbrechen" msgid "Preferred theme" msgstr "Bevorzugter Stil" msgid "Editor Preference" msgstr "Bevorzugter Editor" msgid "Editor shown on UI" msgstr "Angezeigter Editor" msgid "Time zone" msgstr "Zeitzone" msgid "Your time is" msgstr "Die lokale Zeit ist" msgid "Server time is" msgstr "Die Zeit des Servers ist" msgid "Date format" msgstr "Datumsformat" msgid "Preferred language" msgstr "Bevorzugte Sprache" msgid "General options" msgstr "Allgemeine Optionen" msgid "Quick links" msgstr "Expressverweise" msgid "This list does not work, unless you have entered a valid email address!" msgstr "" "Änderungsnachrichten werden nur versandt, wenn eine gültige E-Mail-Adresse " "eingegeben wurde!" msgid "Subscribed wiki pages (one regex per line)" msgstr "Abonnierte Wiki-Seiten (ein regulärer Ausdruck pro Zeile)" msgid "Create Profile" msgstr "Benutzer anlegen" msgid "Mail me my account data" msgstr "E-Mail mit den Zugangsdaten senden" msgid "Email" msgstr "E-Mail" #, python-format msgid "" "To create an account, see the %(userprefslink)s page. To recover a lost " "password, go to %(sendmypasswordlink)s." msgstr "" "Siehe Seite %(userprefslink)s, um einen Account anzulegen. Um ein verlorenes " "Passwort wieder zu erhalten, siehe %(sendmypasswordlink)s." msgid "Name" msgstr "Name" msgid "Password" msgstr "Passwort" msgid "Login" msgstr "Anmelden" msgid "Action" msgstr "Aktion" #, python-format msgid "Expected \"=\" to follow \"%(token)s\"" msgstr "\"=\" fehlt hinter dem Attribut \"%(token)s\"" #, python-format msgid "Expected a value for key \"%(token)s\"" msgstr "Attribut \"%(token)s\" wurde kein Wert zugewiesen" msgid "You are not allowed to edit this page." msgstr "Sie dürfen diese Seite nicht editieren." msgid "Page is immutable!" msgstr "Die Seite ist gegen Änderungen geschützt!" msgid "Cannot edit old revisions!" msgstr "Alte Versionen können nicht editiert werden!" msgid "The lock you held timed out. Be prepared for editing conflicts!" msgstr "" "Die von Ihnen gehaltene Sperre ist abgelaufen. Das Auftreten von " "Änderungskonflikten ist wahrscheinlich!" #, python-format msgid "Draft of \"%(pagename)s\"" msgstr "Entwurf von \"%(pagename)s\"" #, python-format msgid "Edit \"%(pagename)s\"" msgstr "\"%(pagename)s\" editieren" #, python-format msgid "Preview of \"%(pagename)s\"" msgstr "Vorschau für \"%(pagename)s\"" #, python-format msgid "Your edit lock on %(lock_page)s has expired!" msgstr "Ihre Sperre der Seite %(lock_page)s ist abgelaufen!" #, python-format msgid "Your edit lock on %(lock_page)s will expire in # minutes." msgstr "Ihre Sperre der Seite %(lock_page)s läuft in # Minuten ab." #, python-format msgid "Your edit lock on %(lock_page)s will expire in # seconds." msgstr "Ihre Sperre der Seite %(lock_page)s läuft in # Sekunden ab." msgid "Someone else deleted this page while you were editing!" msgstr "Ein anderer Benutzer hat diese Seite inzwischen gelöscht!" msgid "Someone else changed this page while you were editing!" msgstr "Ein anderer Benutzer hat diese Seite inzwischen geändert!" msgid "" "Someone else saved this page while you were editing!\n" "Please review the page and save then. Do not save this page as it is!" msgstr "" "Ein anderer Benutzer hat gespeichert, während Sie editiert haben!\n" "Bitte schauen Sie die Seite nochmal durch und speichern Sie dann. Speichern " "Sie die Seite nicht so, wie sie ist!" msgid "[Content loaded from draft]" msgstr "[Inhalt der Seite mit dem Entwurf geladen]" #, python-format msgid "[Content of new page loaded from %s]" msgstr "[Inhalt der neuen Seite auf Basis der Vorlage %s]" #, python-format msgid "[Template %s not found]" msgstr "[Vorlage %s nicht gefunden]" #, python-format msgid "[You may not read %s]" msgstr "[Sie dürfen %s nicht lesen]" #, python-format msgid "" "'''[[BR]]Your draft based on revision %(draft_rev)d (saved %" "(draft_timestamp_str)s) can be loaded instead of the current revision %" "(page_rev)d by using the load draft button - in case you lost your last edit " "somehow without saving it.''' A draft gets saved for you when you do a " "preview, cancel an edit or unsuccessfully save." msgstr "" "'''[[BR]]Ihr Entwurf basierend auf Revision %(draft_rev)d (gespeichert %" "(draft_timestamp_str)s kann anstatt der aktuellen Revision %(page_rev)d " "geladen werden, indem Sie den Knopf ''Entwurf laden'' drücken (falls Sie " "Ihre letzten Änderungen verloren haben, bevor Sie sie gespeichert " "hatten).''' Ein Entwurf wird für Sie gespeichert, wenn Sie auf Vorschau oder " "Abbrechen drücken oder das Speichern nicht funktioniert." #, python-format msgid "Describe %s here." msgstr "%s hier beschreiben..." msgid "Check Spelling" msgstr "Rechtschreibung prüfen" msgid "Save Changes" msgstr "Änderungen speichern" #, python-format msgid "" "By hitting '''%(save_button_text)s''' you put your changes under the %" "(license_link)s.\n" "If you don't want that, hit '''%(cancel_button_text)s''' to cancel your " "changes." msgstr "" "Durch Anklicken von '''%(save_button_text)s''' stellen Sie Ihre Änderungen " "unter die %(license_link)s.\n" "Wenn Sie das nicht wollen, klicken Sie auf '''%(cancel_button_text)s''', um " "Ihre Änderungen zu verwerfen." msgid "Preview" msgstr "Vorschau anzeigen" msgid "Text mode" msgstr "Text-Modus" msgid "Load Draft" msgstr "Entwurf laden" msgid "Comment:" msgstr "Kommentar:" msgid "" msgstr "" #, python-format msgid "Add to: %(category)s" msgstr "Zu %(category)s hinzufügen:" msgid "Trivial change" msgstr "Triviale Änderung" msgid "Remove trailing whitespace from each line" msgstr "Leerzeichen am Ende jeder Zeile entfernen" msgid "The wiki is currently not reachable." msgstr "Das Wiki ist derzeit nicht erreichbar." msgid "" "The remote version of MoinMoin is too old, version 1.6 is required at least." msgstr "" "Die ferne MoinMoin-Version ist zu alt, mindestens Version 1.6 wird benötigt." msgid "Invalid username or password." msgstr "Ungültiger Username oder Passwort." #, python-format msgid "" "The remote wiki uses a different InterWiki name (%(remotename)s) internally " "than you specified (%(localname)s)." msgstr "" "Das ferne Wiki benutzt intern einen anderen InterWiki-Namen (%(remotename)s) " "als Sie angegeben haben (%(localname)s)." #, python-format msgid "The package needs a newer version of MoinMoin (at least %s)." msgstr "Das Paket erfordert eine neuere Version von MoinMoin (mindestens %s)." msgid "The theme name is not set." msgstr "Theme-Name ist nicht gesetzt." msgid "Installing theme files is only supported for standalone type servers." msgstr "" "Das Installieren von Theme-Dateien wird nur für Server-Typ standalone " "unterstützt." #, python-format msgid "Installation of '%(filename)s' failed." msgstr "Installation von '%(filename)s' fehlgeschlagen." #, python-format msgid "The file %s is not a MoinMoin package file." msgstr "Die Datei %s ist keine MoinMoin-Paket-Datei." #, python-format msgid "The page %s does not exist." msgstr "Die Seite %s existiert nicht." msgid "Invalid package file header." msgstr "Ungültiger Paket-Datei-Header." msgid "Package file format unsupported." msgstr "Paket-Datei-Format nicht unterstützt." #, python-format msgid "Unknown function %(func)s in line %(lineno)i." msgstr "Unbekannte Funktion %(func)s in Zeile %(lineno)i." #, python-format msgid "The file %s was not found in the package." msgstr "Die Datei %s wurde im Paket nicht gefunden." msgid "Your changes are not saved!" msgstr "Ihre Änderungen sind nicht gesichert!" msgid "Page name is too long, try shorter name." msgstr "Seitenname ist zu lang, bitte kürzen." msgid "GUI Mode" msgstr "GUI-Modus" msgid "Edit was cancelled." msgstr "Editierung wurde abgebrochen." msgid "You can't copy to an empty pagename." msgstr "Sie können eine Seite nicht auf einen leeren Seitennamen kopieren." msgid "You are not allowed to copy this page!" msgstr "Sie dürfen diese Seite nicht kopieren!" #, python-format msgid "" "'''A page with the name {{{'%s'}}} already exists.'''\n" "Try a different name." msgstr "" "'''Es gibt bereits eine Seite mit dem Namen {{{'%s'}}}.'''\n" "Versuchen Sie es mit einem anderen Namen." #, python-format msgid "Could not copy page because of file system error: %s." msgstr "" "Konnte die Seite nicht kopieren wegen eines Dateisystem-Fehlercodes: %s." msgid "You are not allowed to rename this page!" msgstr "Sie dürfen diese Seite nicht umbenennen!" msgid "You can't rename to an empty pagename." msgstr "Sie können eine Seite nicht auf einen leeren Seitennamen umbenennen." #, python-format msgid "" "'''A page with the name {{{'%s'}}} already exists.'''\n" "\n" "Try a different name." msgstr "" "'''Es gibt bereits eine Seite mit dem Namen {{{'%s'}}}.'''\n" "Versuchen Sie es mit einem anderen Namen." #, python-format msgid "Could not rename page because of file system error: %s." msgstr "" "Konnte die Seite nicht umbenennen wegen eines Dateisystem-Fehlercodes: %s." msgid "You are not allowed to delete this page!" msgstr "Sie dürfen diese Seite nicht löschen!" msgid "Thank you for your changes. Your attention to detail is appreciated." msgstr "Danke für die Änderung und die Sorgfalt beim Editieren." #, python-format msgid "Page \"%s\" was successfully deleted!" msgstr "Seite \"%s\" wurde erfolgreich gelöscht!" #, python-format msgid "" "Dear Wiki user,\n" "\n" "You have subscribed to a wiki page or wiki category on \"%(sitename)s\" for " "change notification.\n" "\n" "The following page has been changed by %(editor)s:\n" "%(pagelink)s\n" "\n" msgstr "" "Sehr geehrter Wikibenutzer,\n" "\n" "Sie haben die Änderungen einer Wikiseite oder Kategorie von \"%(sitename)s\" " "abonniert.\n" "\n" "Die folgende Seite wurde durch %(editor)s verändert:\n" "%(pagelink)s\n" "\n" #, python-format msgid "" "The comment on the change is:\n" "%(comment)s\n" "\n" msgstr "" "Der Kommentar zur Änderung ist:\n" "%(comment)s\n" "\n" msgid "New page:\n" msgstr "Neue Seite:\n" msgid "No differences found!\n" msgstr "Es wurden keine Änderungen gefunden!\n" #, python-format msgid "[%(sitename)s] %(trivial)sUpdate of \"%(pagename)s\" by %(username)s" msgstr "" "[%(sitename)s] %(trivial)sÄnderung von \"%(pagename)s\" von %(username)s" msgid "Trivial " msgstr "Triviale " msgid "Status of sending notification mails:" msgstr "Status des Versands der Änderungsnachrichten:" #, python-format msgid "[%(lang)s] %(recipients)s: %(status)s" msgstr "[%(lang)s] %(recipients)s: %(status)s" #, python-format msgid "Page could not get locked. Unexpected error (errno=%d)." msgstr "Seite konnte nicht gesperrt werden. Unerwarteter Fehler (errno=%d)." msgid "Page could not get locked. Missing 'current' file?" msgstr "Seite konnte nicht gesperrt werden. Fehlende Datei 'current'?" msgid "You are not allowed to edit this page!" msgstr "Sie dürfen diese Seite nicht editieren!" msgid "You cannot save empty pages." msgstr "Leere Seiten können nicht gespeichert werden!" msgid "You already saved this page!" msgstr "Sie haben diese Seite bereits gesichert!" msgid "You already edited this page! Please do not use the back button." msgstr "" "Sie haben diese Seite bereits editiert! Bitte benutzen Sie nicht den Zurück-" "Button." msgid "You did not change the page content, not saved!" msgstr "Der Seiteninhalt wurde nicht verändert und folglich nicht gesichert!" msgid "" "You can't change ACLs on this page since you have no admin rights on it!" msgstr "" "Sie dürfen keine ACLs auf dieser Seite ändern, weil Sie keine admin-Rechte " "auf ihr haben!" #, python-format msgid "" "The lock of %(owner)s timed out %(mins_ago)d minute(s) ago, and you were " "granted the lock for this page." msgstr "" "Die Sperre von %(owner)s ist vor %(mins_ago)d Minute(n) abgelaufen und wurde " "an Sie übertragen." #, python-format msgid "" "Other users will be ''blocked'' from editing this page until %(bumptime)s." msgstr "" "Anderen Benutzern wird die Editierung dieser Seite bis %(bumptime)s " "''verweigert''." #, python-format msgid "" "Other users will be ''warned'' until %(bumptime)s that you are editing this " "page." msgstr "" "Andere Benutzer erhalten bis %(bumptime)s eine ''Warnung'', dass Sie diese " "Seite editieren." msgid "Use the Preview button to extend the locking period." msgstr "Mit \"Vorschau anzeigen\" können Sie diesen Zeitraum verlängern." #, python-format msgid "" "This page is currently ''locked'' for editing by %(owner)s until %(timestamp)" "s, i.e. for %(mins_valid)d minute(s)." msgstr "" "Diese Seite ist derzeit zur Editierung durch %(owner)s gegen Änderungen " "''gesperrt'' bis %(timestamp)s, also weitere %(mins_valid)d Minute(n)." #, python-format msgid "" "This page was opened for editing or last previewed at %(timestamp)s by %" "(owner)s.[[BR]]\n" "'''You should ''refrain from editing'' this page for at least another %" "(mins_valid)d minute(s),\n" "to avoid editing conflicts.'''[[BR]]\n" "To leave the editor, press the Cancel button." msgstr "" "Diese Seite wurde zum letzten Mal um %(timestamp)s durch %(owner)s zum " "Editieren geöffnet\n" "oder in der Vorschau angezeigt.[[BR]]\n" "'''Sie sollten diese Seite für mindestens weitere %(mins_valid)d Minute(n) " "''nicht editieren'', um Konflikte auszuschließen.'''[[BR]]\n" "Benutzen Sie \"Abbrechen\" zum Verlassen des Editors." msgid "" msgstr "" #, python-format msgid "" "Login Name: %s\n" "\n" "Login Password: %s\n" "\n" "Login URL: %s/%s?action=login\n" msgstr "" "Anmelde-Name: %s\n" "\n" "Anmelde-Passwort: %s\n" "\n" "Anmelde-URL: %s/%s?action=login\n" msgid "" "Somebody has requested to submit your account data to this email address.\n" "\n" "If you lost your password, please use the data below and just enter the\n" "password AS SHOWN into the wiki's password form field (use copy and paste\n" "for that).\n" "\n" "After successfully logging in, it is of course a good idea to set a new and " "known password.\n" msgstr "" "Jemand hat angefordert, Ihre Accountdaten an diese E-Mail-Adresse zu " "senden.\n" "\n" "Wenn Sie Ihr Passwort vergessen haben, benutzen Sie bitte die Daten unten " "und\n" "geben Sie das Passwort GENAUSO WIE ANGEZEIGT in das Passwort-Feld des Wikis " "ein (benutzen Sie kopieren und einfügen dazu).\n" "\n" "Nachdem Sie sich erfolgreich angemeldet haben, setzen Sie bitte Ihr Passwort " "neu.\n" #, python-format msgid "[%(sitename)s] Your wiki account data" msgstr "[%(sitename)s] Ihre Wiki-Acount-Daten" msgid "" "The backed up content of this page is deprecated and will not be included in " "search results!" msgstr "" "Der Inhalt der letzten Sicherungskopie ist veraltet und wird von der " "Volltextsuche ignoriert!" #, python-format msgid "Revision %(rev)d as of %(date)s" msgstr "Revision %(rev)d vom %(date)s" #, python-format msgid "Redirected from page \"%(page)s\"" msgstr "Hierher umgeleitet von Seite \"%(page)s\"" #, python-format msgid "This page redirects to page \"%(page)s\"" msgstr "Diese Seite wird umgeleitet auf \"%(page)s\"" msgid "Create New Page" msgstr "Neue Seite anlegen" msgid "You are not allowed to view this page." msgstr "Sie dürfen diese Seite nicht ansehen." #, python-format msgid "" "Results %(bs)s%(hitsFrom)d - %(hitsTo)d%(be)s of %(aboutHits)s %(bs)s%(hits)d" "%(be)s results out of about %(pages)d pages." msgstr "" "Ergebnisse %(bs)s%(hitsFrom)d - %(hitsTo)d%(be)s von %(aboutHits)s %(bs)s%" "(hits)d%(be)s Ergebnisse aus ungefähr %(pages)d Seiten." msgid "seconds" msgstr "Sekunden" msgid "Previous" msgstr "Vorherige" msgid "Next" msgstr "Nächste" msgid "current" msgstr "aktuelle" #, python-format msgid "last modified: %s" msgstr "zuletzt geändert: %s" msgid "match" msgstr "Treffer" msgid "matches" msgstr "Treffer" msgid "Go To Page" msgstr "Gehe zu Seite" msgid "Include system pages" msgstr "Systemseiten einschließen" msgid "Exclude system pages" msgstr "Systemseiten ausschließen" #, python-format msgid "Please use a more selective search term instead of {{{\"%s\"}}}" msgstr "" "Bitte verwenden Sie einen selektiveren Suchbegriff anstatt {{{\"%s\"}}}" #, python-format msgid "ERROR in regex '%s'" msgstr "FEHLER in regulärem Ausdruck '%s'" #, python-format msgid "Bad timestamp '%s'" msgstr "Ungültige Zeitangabe '%s'" #, python-format msgid "Unsupported navigation scheme '%(scheme)s'!" msgstr "Nicht bekanntes Navigationsschema '%(scheme)s'!" msgid "No parent page found!" msgstr "Diese Seite ist keine Unterseite!" msgid "Wiki" msgstr "Wiki" msgid "Edit" msgstr "Editieren" msgid "Slideshow" msgstr "Diaschau" msgid "Start" msgstr "Start" #, python-format msgid "Slide %(pos)d of %(size)d" msgstr "Seite %(pos)d von %(size)d" msgid "Search Titles" msgstr "Titel durchsuchen" msgid "Display context of search results" msgstr "Umgebung der Treffer anzeigen" msgid "Case-sensitive searching" msgstr "Groß-/Kleinschreibung beachten" msgid "Search Text" msgstr "Text durchsuchen" #, python-format msgid "Not supported mimetype of file: %s" msgstr "MIME-Typ der Datei wird nicht unterstützt: %s" msgid "Embedded" msgstr "Eingebettet" #, python-format msgid "Upload new attachment \"%(filename)s\"" msgstr "Neuen Dateianhang \"%(filename)s\" hochladen" #, python-format msgid "Invalid MonthCalendar calparms \"%s\"!" msgstr "Ungültige MonthCalendaer calparms \"%s\"!" #, python-format msgid "Invalid MonthCalendar arguments \"%s\"!" msgstr "Ungültige MonthCalendar-Argumente: \"%s\"!" msgid "No orphaned pages in this wiki." msgstr "Es existieren keine verwaisten Seiten in diesem Wiki." msgid "Python Version" msgstr "Python Version" msgid "MoinMoin Version" msgstr "MoinMoin Version" #, python-format msgid "Release %s [Revision %s]" msgstr "Version %s [Revision %s]" msgid "4Suite Version" msgstr "4Suite Version" msgid "Number of pages" msgstr "Seitenanzahl" msgid "Number of system pages" msgstr "Anzahl der Systemseiten" msgid "Accumulated page sizes" msgstr "Kumulierte Seitengrößen" #, python-format msgid "Disk usage of %(data_dir)s/pages/" msgstr "Plattenbelegung von %(data_dir)s/pages/" #, python-format msgid "Disk usage of %(data_dir)s/" msgstr "Plattenbelegung von %(data_dir)s/" msgid "Entries in edit log" msgstr "Einträge in der Änderungshistorie" msgid "NONE" msgstr "KEINE" msgid "Global extension macros" msgstr "Globale Erweiterungsmakros" msgid "Local extension macros" msgstr "Lokale Erweiterungsmakros" msgid "Global extension actions" msgstr "Globale Erweiterungsaktionen" msgid "Local extension actions" msgstr "Lokale Erweiterungsaktionen" msgid "Global parsers" msgstr "Globale Parser" msgid "Local extension parsers" msgstr "Lokale Erweiterungsparser" msgid "Disabled" msgstr "Deaktiviert" msgid "Enabled" msgstr "Aktiviert" msgid "index available" msgstr "Index verfügbar" msgid "index unavailable" msgstr "Index nicht verfügbar" msgid "N/A" msgstr "k.A." msgid "Xapian and/or Python Xapian bindings not installed" msgstr "Xapian und/oder Python-Xapian-Bindings nicht installiert" msgid "Xapian search" msgstr "Xapian-Suche" msgid "Xapian Version" msgstr "Xapian-Version" msgid "Xapian stemming" msgstr "Xapian-Wortstamm-Bildung" msgid "Active threads" msgstr "Aktive Threads" #, python-format msgid "No quotes on %(pagename)s." msgstr "Keine Zitate auf Seite %(pagename)s gefunden." #, python-format msgid "Upload of attachment '%(filename)s'." msgstr "Dateianhang '%(filename)s' wurde angelegt." #, python-format msgid "Attachment '%(filename)s' deleted." msgstr "Dateianhang '%(filename)s' wurde gelöscht." #, python-format msgid "Drawing '%(filename)s' saved." msgstr "Zeichnung '%(filename)s' wurde gesichert." #, python-format msgid "Revert to revision %(rev)d." msgstr "Revision %(rev)d restauriert." #, python-format msgid "Renamed from '%(oldpagename)s'." msgstr "Umbenannt von '%(oldpagename)s'." #, python-format msgid "%(mins)dm ago" msgstr "vor %(mins)dm" msgid "(no bookmark set)" msgstr "(kein Lesezeichen gesetzt)" #, python-format msgid "(currently set to %s)" msgstr "(derzeit %s)" msgid "Delete bookmark" msgstr "Lesezeichen löschen" msgid "Set bookmark" msgstr "Lesezeichen setzen" msgid "[Bookmark reached]" msgstr "[Lesezeichen erreicht]" #, python-format msgid "Invalid include arguments \"%s\"!" msgstr "Ungültige \"Include\"-Argumente: \"%s\"!" #, python-format msgid "Nothing found for \"%s\"!" msgstr "Textmarkierung \"%s\" nicht gefunden!" msgid "edit" msgstr "ändern" msgid "Contents" msgstr "Inhaltsverzeichnis" msgid "You need to provide a chart type!" msgstr "Es muss ein Diagrammtyp angegeben werden!" #, python-format msgid "Bad chart type \"%s\"!" msgstr "Unbekannter Diagrammtyp \"%s\"!" msgid "Search for items" msgstr "Nach Items suchen" msgid "containing all the following terms" msgstr "die alle folgenden Ausdrücke enthalten" msgid "containing one or more of the following terms" msgstr "die einen oder mehrere der folgenden Ausdrücke enthalten" msgid "not containing the following terms" msgstr "die folgende Ausdrücke nicht enthalten" msgid "belonging to one of the following categories" msgstr "die einer der folgenden Kategorien angehören" msgid "last modified since (e.g. last 2 weeks)" msgstr "die zuletzt geändert wurden seit (z.B. 'last 2 weeks')" msgid "any language" msgstr "jede Sprache" msgid "any mimetype" msgstr "jeder MIME-Typ" msgid "Language" msgstr "Sprache" msgid "File Type" msgstr "Dateityp" msgid "Search only in titles" msgstr "Nur Titel durchsuchen" msgid "Case-sensitive search" msgstr "Groß-/Kleinschreibung bei der Suche beachten" msgid "Exclude underlay" msgstr "Underlay ausschließen" msgid "No system items" msgstr "Keine System-Items" msgid "Search in all page revisions" msgstr "In allen Seitenrevisionen suchen" msgid "Go get it!" msgstr "Los geht's" #, python-format msgid "Check your argument %s" msgstr "Überprüfen Sie das Argument %s" msgid "Markup" msgstr "Notation" msgid "Display" msgstr "Anzeige" msgid "No wanted pages in this wiki." msgstr "Es existieren keine gewünschten Seiten in diesem Wiki." #, python-format msgid "Connection to mailserver '%(server)s' failed: %(reason)s" msgstr "Verbindung zum Mailserver '%(server)s' gestört: %(reason)s" msgid "Mail not sent" msgstr "E-Mail wurde nicht versandt" msgid "Mail sent OK" msgstr "E-Mail wurde erfolgreich versandt" msgid "Date" msgstr "Datum" msgid "From" msgstr "Von" msgid "To" msgstr "An" msgid "Content" msgstr "Inhalt" msgid "Attachments" msgstr "Dateianhänge" msgid "XSLT option disabled, please look at HelpOnConfiguration." msgstr "XSLT-Option ist abgeschaltet, siehe HelpOnConfiguration." msgid "XSLT processing is not available, please install 4suite 1.x." msgstr "" "Die Verarbeitung von XSLT-Stylesheets ist nicht verfügbar, bitte 4suite 1.x " "installieren." #, python-format msgid "%(errortype)s processing error" msgstr "Verarbeitungsfehler vom Typ \"%(errortype)s\"" #, python-format msgid "Expected \"%(wanted)s\" after \"%(key)s\", got \"%(token)s\"" msgstr "Erwartete \"%(wanted)s\" nach \"%(key)s\", bekam \"%(token)s\"" #, python-format msgid "Expected an integer \"%(key)s\" before \"%(token)s\"" msgstr "Erwartete eine Ganzzahl \"%(key)s\" vor \"%(token)s\"" #, python-format msgid "Expected an integer \"%(arg)s\" after \"%(key)s\"" msgstr "Erwartete eine Ganzzahl \"%(arg)s\" nach \"%(key)s\"" #, python-format msgid "Expected a color value \"%(arg)s\" after \"%(key)s\"" msgstr "Erwartete einen Farbwert \"%(arg)s\" nach \"%(key)s\"" msgid "" "Rendering of reStructured text is not possible, please install Docutils." msgstr "" "Anzeigen von reStructured Text ist nicht möglich, bitte installieren Sie " "Docutils." msgid "**Maximum number of allowed includes exceeded**" msgstr "**Maximale Anzahl erlaubter Includes überschritten**" #, python-format msgid "**Could not find the referenced page: %s**" msgstr "**Konnte die referenzierte Seite nicht finden: %s**" #, python-format msgid "Inlined image: %(url)s" msgstr "Eingebettetes Bild: %(url)s" #, python-format msgid "Create new drawing \"%(filename)s (opens in new window)\"" msgstr "Neue Zeichnung \"%(filename)s\" anlegen (öffnet ein neues Fenster)" #, python-format msgid "Edit drawing %(filename)s (opens in new window)" msgstr "Zeichnung %(filename)s bearbeiten (öffnet ein neues Fenster)" #, python-format msgid "Clickable drawing: %(filename)s" msgstr "Anklickbare Zeichnung %(filename)s" msgid "Toggle line numbers" msgstr "Zeilennummern ein/ausschalten" msgid "[all]" msgstr "[alle]" msgid "[not empty]" msgstr "[nicht leer]" msgid "[empty]" msgstr "[leer]" msgid "filter" msgstr "Filter" msgid "Line" msgstr "Zeile" msgid "No differences found!" msgstr "Es wurden keine Änderungen gefunden!" msgid "Deletions are marked like this." msgstr "Gelöschter Text ist auf diese Art markiert." msgid "Additions are marked like this." msgstr "Hinzugefügter Text ist auf diese Art markiert." #, python-format msgid "" "Sorry, can not save page because \"%(content)s\" is not allowed in this wiki." msgstr "" "Kann die Seite nicht speichern, weil der Inhalt \"%(content)s\" in diesem " "Wiki nicht erlaubt ist." msgid "Page" msgstr "Seite" msgid "User" msgstr "Benutzer" msgid "Diffs" msgstr "DifferenzAnzeige" msgid "Info" msgstr "Info" msgid "Unsubscribe" msgstr "Nicht abonnieren" msgid "Subscribe" msgstr "Abonnieren" msgid "Raw" msgstr "Rohform" msgid "XML" msgstr "XML" msgid "Print" msgstr "Druckansicht" msgid "View" msgstr "Anzeigen" msgid "Home" msgstr "Heim" msgid "Up" msgstr "Hoch" msgid "[RSS]" msgstr "[RSS]" msgid "[DELETED]" msgstr "[GELÖSCHT]" msgid "[UPDATED]" msgstr "[AKTUALISIERT]" msgid "[RENAMED]" msgstr "[UMBENANNT]" msgid "[CONFLICT]" msgstr "[KONFLIKT]" msgid "[NEW]" msgstr "[NEU]" msgid "[DIFF]" msgstr "[DIFF]" msgid "[BOTTOM]" msgstr "[FUSS]" msgid "[TOP]" msgstr "[KOPF]" msgid "Click to do a full-text search for this title" msgstr "Hier klicken für eine Liste der Seiten, die auf diese verweisen" msgid "Preferences" msgstr "Einstellungen" msgid "Logout" msgstr "Abmelden" msgid "Clear message" msgstr "Nachricht löschen" #, python-format msgid "last edited %(time)s by %(editor)s" msgstr "zuletzt geändert am %(time)s durch %(editor)s" #, python-format msgid "last modified %(time)s" msgstr "zuletzt geändert %(time)s" msgid "Search:" msgstr "Suchen:" msgid "Text" msgstr "Text" msgid "Titles" msgstr "Titel" msgid "Search" msgstr "Suche" msgid "More Actions:" msgstr "Weitere Aktionen:" msgid "------------------------" msgstr "------------------------" msgid "Raw Text" msgstr "Rohform" msgid "Print View" msgstr "Druckansicht" msgid "Delete Cache" msgstr "Cache löschen" msgid "Rename Page" msgstr "Seite umbenennen" msgid "Copy Page" msgstr "Seite kopieren" msgid "Delete Page" msgstr "Seite löschen" msgid "Like Pages" msgstr "Ähnliche Seiten" msgid "Local Site Map" msgstr "ÜbersichtsKarte" msgid "My Pages" msgstr "Meine Seiten" msgid "Subscribe User" msgstr "Abo für Benutzer" msgid "Remove Spam" msgstr "Spam entfernen" msgid "Revert to this revision" msgstr "Diese Revision restaurieren" msgid "Package Pages" msgstr "Seiten paketieren" msgid "Render as Docbook" msgstr "Docbook ausgeben" msgid "Sync Pages" msgstr "Seiten synchronisieren" msgid "Do" msgstr "Los!" msgid "Comments" msgstr "Kommentare" msgid "Edit (Text)" msgstr "Editieren (Text)" msgid "Edit (GUI)" msgstr "Editieren (GUI)" msgid "Immutable Page" msgstr "Geschützte Seite" msgid "Remove Link" msgstr "Verweis entfernen" msgid "Add Link" msgstr "Verweis hinzufügen" #, python-format msgid "Show %s days." msgstr "%s Tage anzeigen." msgid "Wiki Markup" msgstr "Wiki Quelltext" msgid "DeleteCache" msgstr "CacheLöschen" #, python-format msgid "(cached %s)" msgstr "(gecached %s)" msgid "Or try one of these actions:" msgstr "Oder benutze eine dieser Aktionen:" msgid "FrontPage" msgstr "StartSeite" msgid "RecentChanges" msgstr "AktuelleÄnderungen" msgid "TitleIndex" msgstr "TitelIndex" msgid "WordIndex" msgstr "WortIndex" msgid "FindPage" msgstr "SeiteFinden" msgid "SiteNavigation" msgstr "WegWeiser" msgid "HelpContents" msgstr "HilfeInhalt" msgid "HelpOnFormatting" msgstr "HilfeZumFormatieren" msgid "UserPreferences" msgstr "BenutzerEinstellungen" msgid "WikiLicense" msgstr "WikiLizenz" msgid "MissingPage" msgstr "FehlendeSeite" msgid "MissingHomePage" msgstr "FehlendePersönlicheSeite" msgid "Mon" msgstr "Mo" msgid "Tue" msgstr "Di" msgid "Wed" msgstr "Mi" msgid "Thu" msgstr "Do" msgid "Fri" msgstr "Fr" msgid "Sat" msgstr "Sa" msgid "Sun" msgstr "So" msgid "AttachFile" msgstr "DateiAnhänge" msgid "DeletePage" msgstr "SeiteLöschen" msgid "LikePages" msgstr "ÄhnlicheSeiten" msgid "LocalSiteMap" msgstr "ÜbersichtsKarte" msgid "RenamePage" msgstr "SeiteUmbenennen" msgid "SpellCheck" msgstr "RechtSchreibung" #, python-format msgid "Unknown action %(action_name)s." msgstr "Unbekannte Aktion %(action_name)s." #, python-format msgid "You are not allowed to do %(action_name)s on this page." msgstr "Sie dürfen die Aktion %(action_name)s auf dieser Seite nicht benutzen!" msgid "Login and try again." msgstr "Melden Sie sich an und probieren Sie es noch einmal." msgid "Charts are not available!" msgstr "Die Diagrammoption ist nicht verfügbar!" msgid "Page Size Distribution" msgstr "Verteilung der Seitengrößen" msgid "page size upper bound [bytes]" msgstr "Obere Grenze der Seitengröße [bytes]" msgid "# of pages of this size" msgstr "Anzahl der Seiten in dieser Größenklasse" msgid "User agent" msgstr "Browsertyp" msgid "Others" msgstr "Sonstige" msgid "Distribution of User-Agent Types" msgstr "Verteilung der Zugriffe auf Browsertypen" msgid "Views/day" msgstr "Lesezugriffe/Tag" msgid "Edits/day" msgstr "Schreibzugriffe/Tag" msgid "Page hits and edits" msgstr "Seitenzugriffe und Änderungen" #, python-format msgid "%(chart_title)s for %(filterpage)s" msgstr "%(chart_title)s für %(filterpage)s" msgid "" "green=view\n" "red=edit" msgstr "" "grün=Anzeigen\n" "rot=Änderungen" msgid "date" msgstr "Datum" msgid "# of hits" msgstr "Anzahl der Zugriffe" msgid "" " Emphasis:: [[Verbatim('')]]''italics''[[Verbatim('')]]; [[Verbatim" "(''')]]'''bold'''[[Verbatim(''')]]; [[Verbatim(''''')]]'''''bold " "italics'''''[[Verbatim(''''')]]; [[Verbatim('')]]''mixed ''[[Verbatim" "(''')]]'''''bold'''[[Verbatim(''')]] and italics''[[Verbatim('')]]; " "[[Verbatim(----)]] horizontal rule.\n" " Headings:: [[Verbatim(=)]] Title 1 [[Verbatim(=)]]; [[Verbatim(==)]] Title " "2 [[Verbatim(==)]]; [[Verbatim(===)]] Title 3 [[Verbatim(===)]]; [[Verbatim" "(====)]] Title 4 [[Verbatim(====)]]; [[Verbatim(=====)]] Title 5 [[Verbatim" "(=====)]].\n" " Lists:: space and one of: * bullets; 1., a., A., i., I. numbered items; 1." "#n start numbering at n; space alone indents.\n" " Links:: [[Verbatim(JoinCapitalizedWords)]]; [[Verbatim([\"brackets and " "double quotes\"])]]; url; [url]; [url label].\n" " Tables:: || cell text |||| cell text spanning 2 columns ||; no trailing " "white space allowed after tables or titles.\n" "\n" "(!) For more help, see HelpOnEditing or SyntaxReference.\n" msgstr "" " Betonung:: [[Verbatim('')]]''kursiv''[[Verbatim('')]]; [[Verbatim" "(''')]]'''fett'''[[Verbatim(''')]]; [[Verbatim(''''')]]'''''fett und " "kursiv'''''[[Verbatim(''''')]]; [[Verbatim('')]]''gemischt ''[[Verbatim" "(''')]]'''''fett'''[[Verbatim(''')]] und kursiv''[[Verbatim('')]]; [[Verbatim" "(----)]] horizontaler Balken.\n" " Überschriften:: [[Verbatim(=)]] Überschrift 1 [[Verbatim(=)]]; [[Verbatim" "(==)]] Überschrift 2 [[Verbatim(==)]]; [[Verbatim(===)]] Ü 3 [[Verbatim" "(===)]]; [[Verbatim(====)]] Ü 4 [[Verbatim(====)]]; [[Verbatim(=====)]] Ü " "5 [[Verbatim(=====)]].\n" " Listen:: Leerzeichen und eins von: * Punkte; 1., a., A., i., I. nummerierte " "Punkte; 1.#n starte Nummerierung bei n; nur Leerzeichen rückt ein.\n" " Links:: [[Verbatim(ZusammenGeschriebeneGroßeWorte)]]; [[Verbatim" "([\"Klammern und doppelte Anführungszeichen\"])]]; url; [url]; [url " "label].\n" " Tabellen:: || Zellentext |||| Zellentext, 2 Zellen überspannend ||; " "keine anhängenden Leerzeichen nach Überschriften oder Tabellen.\n" "\n" "(!) Weitere Hilfe finden Sie unter HilfeZumEditieren oder SyntaxReferenz.\n" msgid "" "Emphasis: *italic* **bold** ``monospace``
\n" "
\n"
"Headings: Heading 1  Heading 2  Heading 3\n"
"          =========  ---------  ~~~~~~~~~\n"
"\n"
"Horizontal rule: ---- \n"
"Links: TrailingUnderscore_ `multi word with backticks`_ external_ \n"
"\n"
".. _external: http://external-site.net/foo/\n"
"\n"
"Lists: * bullets; 1., a. numbered items.\n"
"
\n" "
\n" "(!) For more help, see the \n" "\n" "reStructuredText Quick Reference\n" ".\n" msgstr "" "Betonung: *kursiv* **fett** ``gleiche Zeichenbreite``
\n" "
\n"
"Überschriften: Überschrift 1  Überschrift 2  Überschrift 3\n"
"               =============  -------------  ~~~~~~~~~~~~~\n"
"\n"
"Horizontale Linie: ---- \n"
"Links: AngehängterUnterstrich_ `mehrere Worte mit Rückwärtsapostroph`_ "
"extern_ \n"
"\n"
".. _extern: http://externe-seite.de/\n"
"\n"
"Listen: * Punkte; 1., a. nummerierte Punkte.\n"
"
\n" "
\n" "(!) Für mehr Hilfe siehe die \n" "\n" "reStructuredText Quick Reference\n" ".\n" msgid "UnSubscribe" msgstr "Nicht abonnieren" msgid "Publish my email (not my wiki homepage) in author info" msgstr "" "Veröffentliche meine E-Mail-Adresse (nicht meine Wiki-Homepage) in der " "Autoren-Info" msgid "Open editor on double click" msgstr "Editor per Doppelklick öffnen" msgid "After login, jump to last visited page" msgstr "Nach dem Anmelden zur zuletzt besuchten Seite springen" msgid "Show comment sections" msgstr "Kommentarabschnitte anzeigen" msgid "Show question mark for non-existing pagelinks" msgstr "Verweise auf unbekannte Seiten mit Fragezeichen markieren" msgid "Show page trail" msgstr "Kürzlich besuchte Seiten anzeigen (Verlauf)" msgid "Show icon toolbar" msgstr "Werkzeugleiste mit Bildsymbolen anzeigen" msgid "Show top/bottom links in headings" msgstr "Verweise zum Anfang und Ende der Seite in Überschriften anzeigen" msgid "Show fancy diffs" msgstr "Unterschiede farbig markiert anzeigen" msgid "Add spaces to displayed wiki names" msgstr "Angezeigte Wikinamen mit Leerzeichen trennen" msgid "Remember login information" msgstr "Speichere Login-Informationen" msgid "Subscribe to trivial changes" msgstr "Triviale Änderungen abonnieren" msgid "Disable this account forever" msgstr "Dieses Benutzerkonto für immer deaktivieren" msgid "(Use Firstname''''''Lastname)" msgstr "(Vorname''''''Nachname verwenden)" msgid "Alias-Name" msgstr "Alias-Name" msgid "Password repeat" msgstr "Passwort wiederholen" msgid "(Only for password change or new account)" msgstr "(Nur für Passwort-Änderung oder neue Benutzerkonten)" msgid "User CSS URL" msgstr "Benutzer CSS URL" msgid "(Leave it empty for disabling user CSS)" msgstr "Leer lassen, um benutzerdefiniertes CSS auszuschalten)" msgid "Editor size" msgstr "Größe des Texteingabefelds" msgid "Do it." msgstr "Ausführen" #, python-format msgid "Execute action %(actionname)s?" msgstr "Aktion %(actionname)s ausführen?" #, python-format msgid "Action %(actionname)s is excluded in this wiki!" msgstr "Aktion %(actionname)s ist ausgeschlossen in diesem Wiki!" #, python-format msgid "You are not allowed to use action %(actionname)s on this page!" msgstr "Sie dürfen die Aktion %(actionname)s auf dieser Seite nicht benutzen!" #, python-format msgid "Please use the interactive user interface to use action %(actionname)s!" msgstr "" "Für die Aktion %(actionname)s bitte nur die vorgesehenen Webseiten benutzen!" msgid "You must login to add a quicklink." msgstr "Sie müssen sich anmelden, um einen Expressverweis hinzuzufügen." msgid "Your quicklink to this page has been removed." msgstr "Ihr Expressverweis für diese Seite wurde entfernt." msgid "Your quicklink to this page could not be removed." msgstr "Ihr Expressverweis für diese Seite konnte nicht entfernt werden." msgid "A quicklink to this page has been added for you." msgstr "Ein Expressverweis für diese Seite wurde hinzugefügt." msgid "A quicklink to this page could not be added for you." msgstr "Ein Expressverweis für diese Seite konnte nicht hinzugefügt werden." msgid "Missing password. Please enter user name and password." msgstr "Fehlendes Passwort. Bitte geben Sie Benutzername und Passwort ein." msgid "Sorry, login failed." msgstr "Login fehlgeschlagen." #, python-format msgid "[%d attachments]" msgstr "[%d Anhänge]" #, python-format msgid "" "There are %(count)s attachment(s) stored for this " "page." msgstr "" "Es sind %(count)s Anhänge für diese Seite " "gespeichert." #, python-format msgid "Attachment '%(target)s' already exists." msgstr "Dateianhang '%(target)s' existiert bereits." msgid "Filename of attachment not specified!" msgstr "Dateiname des Anhangs fehlt oder ist leer!" #, python-format msgid "Attachment '%(filename)s' does not exist!" msgstr "Dateianhang '%(filename)s' existiert nicht!" msgid "" "To refer to attachments on a page, use '''{{{attachment:filename}}}''', \n" "as shown below in the list of files. \n" "Do '''NOT''' use the URL of the {{{[get]}}} link, \n" "since this is subject to change and can break easily." msgstr "" "Um Dateianhänge in eine Seite einzufügen sollte unbedingt eine Angabe \n" "wie '''{{{attachment:dateiname}}}''' benutzt werden, \n" "wie sie auch in der folgenden Liste der Dateien erscheint. \n" "Es sollte '''niemals''' die URL des Verweises (\"laden\") kopiert werden, \n" "da sich diese jederzeit ändern kann und damit der Verweis auf die Datei " "brechen würde." msgid "del" msgstr "löschen" msgid "move" msgstr "verschieben" msgid "get" msgstr "laden" msgid "view" msgstr "anzeigen" msgid "unzip" msgstr "auspacken" msgid "install" msgstr "installieren" #, python-format msgid "No attachments stored for %(pagename)s" msgstr "Es wurden keine Anhänge für die Seite %(pagename)s gespeichert." msgid "Edit drawing" msgstr "Zeichnung editieren" msgid "New Attachment" msgstr "Neuer Dateianhang" msgid "" "An upload will never overwrite an existing file. If there is a name\n" "conflict, you have to rename the file that you want to upload.\n" "Otherwise, if \"Rename to\" is left blank, the original filename will be " "used." msgstr "" "Ein neuer Anhang überschreibt niemals einen bereits vorhandenen gleichen " "Namens.\n" "Besteht ein Namenskonflikt, muss dem neuen Anhang ein alternativer Name " "zugewiesen werden.\n" "Ansonsten kann das Feld \"Umbenennen auf\" leer bleiben und es wird der " "originale Dateiname benutzt." msgid "File to upload" msgstr "Neuer Dateianhang" msgid "Rename to" msgstr "Umbenennen auf" msgid "Overwrite existing attachment of same name" msgstr "Anhänge gleichen Namens überschreiben" msgid "Upload" msgstr "Datei hochladen" msgid "Attached Files" msgstr "Gespeicherte Dateianhänge" msgid "You are not allowed to attach a file to this page." msgstr "Sie dürfen keine Anhänge an diese Seite anhängen!" msgid "File attachments are not allowed in this wiki!" msgstr "Dateianhänge sind in diesem Wiki nicht erlaubt!" msgid "You are not allowed to save a drawing on this page." msgstr "Sie dürfen auf dieser Seite keine Zeichnung speichern." msgid "" "No file content. Delete non ASCII characters from the file name and try " "again." msgstr "" "Kein Dateiinhalt. Löschen Sie nicht-ASCII-Zeichen aus dem Dateinamen und " "probieren Sie es noch einmal." msgid "You are not allowed to delete attachments on this page." msgstr "Sie dürfen keine Anhänge dieser Seite löschen!" msgid "You are not allowed to move attachments from this page." msgstr "Sie dürfen keine Anhänge von dieser Seite verschieben." msgid "Move aborted!" msgstr "Verschieben abgebrochen!" msgid "Please use the interactive user interface to move attachments!" msgstr "" "Für die das Verschieben von Anhängen bitte nur die vorgesehenen Webseiten " "benutzen!" msgid "You are not allowed to get attachments from this page." msgstr "Sie dürfen auf keine Anhänge dieser Seite zugreifen." msgid "You are not allowed to unzip attachments of this page." msgstr "Sie dürfen keine Anhänge dieser Seite auspacken." msgid "You are not allowed to install files." msgstr "Sie dürfen keine Dateien installieren." msgid "You are not allowed to view attachments of this page." msgstr "Sie dürfen keine Anhänge dieser Seite ansehen." #, python-format msgid "Unsupported upload action: %s" msgstr "Unbekannte Aktion für Dateianhang: %s" #, python-format msgid "Attachments for \"%(pagename)s\"" msgstr "Dateianhänge für \"%(pagename)s\"" #, python-format msgid "" "Attachment '%(target)s' (remote name '%(filename)s') with %(bytes)d bytes " "saved." msgstr "" "Dateianhang '%(target)s' (ursprünglicher Name '%(filename)s') mit %(bytes)d " "Bytes gesichert." #, python-format msgid "Attachment '%(target)s' (remote name '%(filename)s') already exists." msgstr "" "Dateianhang '%(target)s' (ursprünglicher Name '%(filename)s') existiert " "bereits." #, python-format msgid "Attachment '%(filename)s' already exists." msgstr "Dateianhang '%(filename)s' existiert bereits." #, python-format msgid "Attachment '%(filename)s' moved to %(page)s." msgstr "Dateianhang '%(filename)s' auf Seite %(page)s verschoben." msgid "Nothing changed" msgstr "Keine Änderung." #, python-format msgid "Page %(newpagename)s does not exists or you don't have enough rights." msgstr "" "Seite %(newpagename)s existiert nicht oder Sie haben nicht ausreichend " "Rechte." msgid "Move aborted because empty page name" msgstr "Sie können eine Seite nicht auf einen leeren Seitennamen umbenennen." #, python-format msgid "Please use a valid filename for attachment '%(filename)s'." msgstr "" "Bitte benutzen Sie einen gültigen Dateinamen für Dateianhang '%(filename)s'." msgid "Move aborted because empty attachment name" msgstr "Verschieben wegen eines leeren Anhangsnamens abgebrochen" msgid "Move" msgstr "Verschieben" msgid "New page name" msgstr "Neuer Seitenname" msgid "New attachment name" msgstr "Neuer Name des Dateianhangs" #, python-format msgid "Attachment '%(filename)s' installed." msgstr "Dateianhang '%(filename)s' wurde installiert." #, python-format msgid "" "Attachment '%(filename)s' could not be unzipped because the resulting files " "would be too large (%(space)d kB missing)." msgstr "" "Dateianhang '%(filename)s' konnte nicht ausgepackt werden, weil die " "ausgepackten Dateien zu groß wären (%(space)d kB fehlen)." #, python-format msgid "" "Attachment '%(filename)s' could not be unzipped because the resulting files " "would be too many (%(count)d missing)." msgstr "" "Dateianhang '%(filename)s' konnte nicht ausgepackt werden, weil die " "ausgepackten Dateien zu viele wären (%(count)d fehlen)." #, python-format msgid "Attachment '%(filename)s' unzipped." msgstr "Dateianhang '%(filename)s' wurde ausgepackt." #, python-format msgid "" "Attachment '%(filename)s' not unzipped because the files are too big, .zip " "files only, exist already or reside in folders." msgstr "" "Dateianhang '%(filename)s' wurde nicht ausgepackt, weil die Datei zu groß " "sind, weil nur .zip-Dateien erlaubt sind, weil sie bereits existieren oder " "weil Dateien in Ordnern enthalten sind." #, python-format msgid "The file %(filename)s is not a .zip file." msgstr "Die Datei %(filename)s ist keine .zip-Datei." #, python-format msgid "Attachment '%(filename)s'" msgstr "Dateianhang '%(filename)s'" msgid "Package script:" msgstr "Paket-Skript:" msgid "File Name" msgstr "Dateiname" msgid "Modified" msgstr "Modifiziert" msgid "Size" msgstr "Größe" msgid "Unknown file type, cannot display this attachment inline." msgstr "" "Dieser Anhang besitzt einen unbekannten Dateityp und kann deshalb nicht " "direkt angezeigt werden." #, python-format msgid "attachment:%(filename)s of %(pagename)s" msgstr "[[Verbatim(attachment:)]]%(filename)s für %(pagename)s" msgid "This page is already deleted or was never created!" msgstr "Diese Seite wurde bereits gelöscht oder wurde bisher nicht angelegt!" msgid "Rename all /subpages too?" msgstr "Alle /UnterSeiten auch umbenennen?" msgid "New name" msgstr "Neuer Name" msgid "Optional reason for the renaming" msgstr "Optionale Begründung für das Umbenennen" msgid "Really rename this page?" msgstr "Diese Seite wirklich umbenennen?" #, python-format msgid "Full Link List for \"%s\"" msgstr "Liste aller Seitenverweise für \"%s\"" msgid "Editor" msgstr "Autor" msgid "Pages" msgstr "Seiten" msgid "Select Author" msgstr "Autor auswählen" msgid "Revert all!" msgstr "Alle restaurieren!" msgid "You are not allowed to use this action." msgstr "Sie dürfen diese Aktion nicht ausführen." #, python-format msgid "Rolled back changes to the page %s." msgstr "Änderungen an der Seite %s rückgängig gemacht" msgid "Exception while calling rollback function:" msgstr "Fehler beim Aufrufen der Rollback-Funktion:" msgid "" "Please enter your password of your account at the remote wiki below. " "[[BR]] /!\\ You should trust both wikis because the password could be read " "by the particular administrators." msgstr "" "Bitte geben Sie das Passwort Ihres Accounts im fernen Wiki unten ein. " "[[BR]] /!\\ Sie sollten beiden Wikis vertrauen, weil das Passwort von den " "entsprechenden Administratoren gelesen werden könnte." msgid "Operation was canceled." msgstr "Operation wurde abgebrochen." msgid "The only supported directions are BOTH and DOWN." msgstr "Es werden nur die Richtungen BOTH und DOWN unterstützt." msgid "" "Please set an interwikiname in your wikiconfig (see HelpOnConfiguration) to " "be able to use this action." msgstr "" "Bitte setzen Sie interwikiname in Ihrer wikiconfig (siehe " "HilfeZurKonfiguration), um diese Aktion benutzen zu können." msgid "" "Incorrect parameters. Please supply at least the ''remoteWiki'' parameter. " "Refer to HelpOnSynchronisation for help." msgstr "" "Ungültige Parameter, bitte geben Sie mindestens den ''remoteWiki''-Parameter " "an. Siehe HilfeZurSynchronisation für weitere Informationen." msgid "The ''remoteWiki'' is unknown." msgstr "Das ''remoteWiki'' ist nicht bekannt." msgid "A severe error occured:" msgstr "Ein schwerwiegender Fehler ist aufgetreten:" msgid "Synchronisation finished. Look below for the status messages." msgstr "Synchronisierung beendet, siehe Status-Nachrichten unten." msgid "Synchronisation started -" msgstr "Synchronisierung gestartet -" #, python-format msgid "" "Got a list of %s local and %s remote pages. This results in %s different " "pages over-all." msgstr "" "%s lokale und %s ferne Seiten, resultierend in insgesamt %s " "unterschiedlichen Seiten." #, python-format msgid "After filtering: %s pages" msgstr "Nach dem Filtern: %s Seiten" #, python-format msgid "Skipped page %s because of no write access to local page." msgstr "" "Seite %s wurde wegen fehlenden Schreibrechten auf die lokale Seite " "übersprungen." #, python-format msgid "Deleted page %s locally." msgstr "Lokale Seite %s gelöscht." #, python-format msgid "Error while deleting page %s locally:" msgstr "Fehler beim lokalen Löschen der Seite %s:" #, python-format msgid "Deleted page %s remotely." msgstr "Ferne Seite %s gelöscht." #, python-format msgid "Error while deleting page %s remotely:" msgstr "Fehler beim fernen Löschen der Seite %s:" #, python-format msgid "" "The item %s cannot be merged automatically but was changed in both wikis. " "Please delete it in one of both wikis and try again." msgstr "" "Das Objekt %s kann nicht automatisch zusammengeführt werden, wurde aber in " "beiden Wikis geändert. Bitte löschen Sie es in einem der beiden Wikis und " "versuchen Sie es erneut." #, python-format msgid "" "The item %s has different mime types in both wikis and cannot be merged. " "Please delete it in one of both wikis or unify the mime type, and try again." msgstr "" "Das Objekt %s hat einen unterschiedlichen Mime-Typ in beiden Wikis und kann " "nicht zusammengeführt werden. Bitte löschen Sie es in einem der beiden Wikis " "oder vereinheitlichen Sie den Mime-Typ und probieren Sie es nochmal." #, python-format msgid "" "The item %s was renamed locally. This is not implemented yet. Therefore the " "full synchronisation history is lost for this page." msgstr "" "Seite %s wurde lokal umbenannt. Dies wird noch nicht unterstützt, daher geht " "für diese Seite die ganze Synchronisierungs-Historie verloren." #, python-format msgid "Synchronising page %s with remote page %s ..." msgstr "Synchronisiere Seite %s mit der entfernten Seite %s ..." #, python-format msgid "The page %s was deleted remotely but changed locally." msgstr "Seite %s wurde lokal geändert, aber ferne gelöscht." #, python-format msgid "" "The page %s could not be synced. The remote page was renamed. This is not " "supported yet. You may want to delete one of the pages to get it synced." msgstr "" "Seite %s konnte nicht synchronisiert werden. Die entfernte Seite wurde " "umbenannt, was bis jetzt noch nicht unterstützt wird. Vielleicht möchten Sie " "eine der Seiten löschen, um die Seite erfolgreich zu synchronisieren." #, python-format msgid "Skipped page %s because of a locally or remotely unresolved conflict." msgstr "" "Seite %s wurde wegen eines lokalen oder entfernten nicht beseitigten " "Konflikts übersprungen." #, python-format msgid "" "This is the first synchronisation between the local and the remote wiki for " "the page %s." msgstr "" "Dies ist die erste Synchronisation zwischen dem lokalen und fernen Wiki für " "die Seite %s." #, python-format msgid "" "The page %s could not be merged because you are not allowed to modify the " "page in the remote wiki." msgstr "" "Die Seite %s konnte nicht zusammengeführt werden, weil Sie die Seite im " "fernen Wiki nicht ändern dürfen." #, python-format msgid "Page %s successfully merged." msgstr "Seite \"%s\" wurde erfolgreich zusammengeführt." #, python-format msgid "Page %s contains conflicts that were introduced on the remote side." msgstr "Seite %s enthält von der fernen Seite eingeführte Konflikte." #, python-format msgid "Page %s merged with conflicts." msgstr "Seite %s wurde mit Konflikten zusammengeführt." msgid "Load" msgstr "Laden" msgid "New Page or New Attachment" msgstr "Neue Seite oder neuer Dateianhang" msgid "" "You can upload a file to a new page or choose to upload a file as attachment " "for the current page" msgstr "" "Sie können eine Datei in eine neue Seite hochladen oder eine Datei als " "Dateianhang an die aktuelle Seite hochladen" msgid "attachment" msgstr "Dateianhang" msgid "overwrite" msgstr "überschreiben" msgid "New Name" msgstr "Neuer Name" #, python-format msgid "(including %(localwords)d %(pagelink)s)" msgstr "(inklusive %(localwords)d %(pagelink)s)" #, python-format msgid "" "The following %(badwords)d words could not be found in the dictionary of %" "(totalwords)d words%(localwords)s and are highlighted below:" msgstr "" "Die nachfolgenden %(badwords)d Worte konnten nicht im Wörterbuch mit %" "(totalwords)d Worten%(localwords)s gefunden werden und sind im Text " "hervorgehoben:" msgid "Add checked words to dictionary" msgstr "Markierte Wörter zum Wörterbuch hinzufügen" msgid "No spelling errors found!" msgstr "Keine Rechtschreibfehler gefunden!" msgid "You can't save spelling words." msgstr "Sie können keine Rechtschreibkorrektur-Wörter abspeichern." msgid "You can't check spelling on a page you can't read." msgstr "" "Sie dürfen keine Seite auf Rechtschreibung prüfen, die Sie nicht lesen " "können." msgid "You are now logged out." msgstr "Sie sind nun abgemeldet." msgid "You are not allowed to subscribe to a page you can't read." msgstr "Sie dürfen keine Seiten abonnieren, die Sie nicht lesen dürfen." msgid "This wiki is not enabled for mail processing." msgstr "In diesem Wiki ist Mail-Verarbeitung nicht eingeschaltet." msgid "You must log in to use subscriptions." msgstr "Sie müssen sich anmelden, um Abonnements verwenden zu können." msgid "Add your email address in your UserPreferences to use subscriptions." msgstr "" "Fügen Sie Ihre E-Mail-Adresse in den BenutzerEinstellungen hinzu, um " "Abonnements benutzen zu können." msgid "Your subscription to this page has been removed." msgstr "Ihr Abonnementsfür diese Seite wurde entfernt." msgid "Can't remove regular expression subscription!" msgstr "Kann nicht Abonnement mit regulärem Ausdruck entfernen." msgid "Edit the subscription regular expressions in your UserPreferences." msgstr "" "Editieren Sie die regulären Ausdrücke für Abonnements in Ihren " "BenutzerEinstellungen." msgid "You have been subscribed to this page." msgstr "Die Seite wurde zur Liste abonnierter Seiten hinzugefügt." msgid "You could not get subscribed to this page." msgstr "" "Die Seite konnte nicht zur Liste abonnierter Seiten hinzugefügt werden." msgid "General Information" msgstr "Allgemeine Informationen" #, python-format msgid "Page size: %d" msgstr "Seitengröße: %d" msgid "SHA digest of this page's content is:" msgstr "Signatur des Seiteninhalts nach dem SHA-Verfahren:" msgid "The following users subscribed to this page:" msgstr "Nachfolgende Benutzer haben diese Seite abonniert:" msgid "This page links to the following pages:" msgstr "Diese Seite verweist auf die folgenden Seiten:" msgid "Diff" msgstr "Differenz" msgid "Comment" msgstr "Kommentar" msgid "Revision History" msgstr "Versionshistorie" msgid "No log entries found." msgstr "Keine Log-Einträge gefunden." #, python-format msgid "Info for \"%s\"" msgstr "Info für \"%s\"" #, python-format msgid "Show \"%(title)s\"" msgstr "\"%(title)s\" anzeigen" msgid "General Page Infos" msgstr "Allgemeine Seiten-Informationen" msgid "Please log in first." msgstr "Bitte melden Sie sich vorher an." msgid "Please first create a homepage before creating additional pages." msgstr "" "Bitte erzeugen Sie zuerst eine Homepage, bevor Sie weitere Seiten anlegen." #, python-format msgid "" "You can add some additional sub pages to your already existing homepage " "here.\n" "\n" "You can choose how open to other readers or writers those pages shall be,\n" "access is controlled by group membership of the corresponding group page.\n" "\n" "Just enter the sub page's name and click on the button to create a new " "page.\n" "\n" "Before creating access protected pages, make sure the corresponding group " "page\n" "exists and has the appropriate members in it. Use HomepageGroupsTemplate for " "creating\n" "the group pages.\n" "\n" "||'''Add a new personal page:'''||'''Related access control list " "group:'''||\n" "||[[NewPage(HomepageReadWritePageTemplate,read-write page,%(username)s)]]||" "[\"%(username)s/ReadWriteGroup\"]||\n" "||[[NewPage(HomepageReadPageTemplate,read-only page,%(username)s)]]||[\"%" "(username)s/ReadGroup\"]||\n" "||[[NewPage(HomepagePrivatePageTemplate,private page,%(username)s)]]||%" "(username)s only||\n" "\n" msgstr "" "Hier können Sie zusätzliche Unterseiten zu Ihrer bereits existierenden " "Homepage hinzufügen.\n" "\n" "Sie können wählen, wie offen diese Seiten für andere Leser oder Autoren sein " "sollen,\n" "der Zugriff wird über Gruppenmitgliedschaft in der entsprechenden Gruppe " "kontrolliert.\n" "\n" "Geben Sie einfach den Namen der Unterseite ein und klicken Sie auf den " "Knopf, um eine neue Seite zu erzeugen.\n" "\n" "Bevor Sie zugriffsgeschützte Seiten erzeugen, stellen Sie sicher, dass die " "entsprechende Gruppenseite existiert und die richtigen Mitglieder hat. " "Benutzen Sie HomepageGroupsTemplate für das Erzeugen der Gruppenseiten.\n" "\n" "||'''Neue persönliche Seite hinzufügen:'''||'''Zugeordnete ACL-Gruppe:'''||\n" "||[[NewPage(HomepageReadWritePageTemplate,Seite (read/write),%(username)" "s)]]||[\"%(username)s/ReadWriteGroup\"]||\n" "||[[NewPage(HomepageReadPageTemplate,Seite (read-only),%(username)s)]]||[\"%" "(username)s/ReadGroup\"]||\n" "||[[NewPage(HomepagePrivatePageTemplate,Seite (privat),%(username)s)]]||nur %" "(username)s||\n" "\n" msgid "MyPages management" msgstr "Verwaltung meiner Seiten" #, python-format msgid "Subscribe users to the page %s" msgstr "Seite %s für Benutzer abonnieren" #, python-format msgid "Subscribed for %s:" msgstr "Abonnenten von %s:" msgid "Not a user:" msgstr "Kein Benutzer:" msgid "You are not allowed to perform this action." msgstr "Sie dürfen diese Aktion nicht ausführen." #, python-format msgid "(!) Only pages changed since '''%s''' are being displayed!" msgstr "(!) Nur Seiten, die seit '''%s''' geändert wurden, werden angezeigt!" msgid "" "/!\\ The modification date you entered was not recognized and is therefore " "not considered for the search results!" msgstr "" "/!\\ Das eingegebene Änderungsdatum wurde nicht erkannt und wird deshalb " "nicht bei der Suche berücksichtigt." #, python-format msgid "Title Search: \"%s\"" msgstr "Titelsuche: \"%s\"" #, python-format msgid "Advanced Search: \"%s\"" msgstr "Erweiterte Suche: \"%s\"" #, python-format msgid "Full Text Search: \"%s\"" msgstr "Volltextsuche: \"%s\"" #, python-format msgid "" "Your search query {{{\"%s\"}}} is invalid. Please refer to HelpOnSearching " "for more information." msgstr "" "Ihre Suchanfrage {{{\"%s\"}}} ist ungültig. Siehe HilfeZumSuchen für weitere " "Informationen." #, python-format msgid "" "Your search query {{{\"%s\"}}} didn't return any results. Please change some " "terms and refer to HelpOnSearching for more information.%s" msgstr "" "Ihre Suche nach {{{\"%s\"}}} hat keine Resultate ergeben. Bitte ändern Sie " "einige Suchbegriffe und lesen Sie für weitere Informationen auf " "HilfeZumSuchen nach. %s" msgid "(!) Consider performing a" msgstr "(!) Erwägen Sie eine" msgid "full-text search with your search terms" msgstr "Volltextsuche mit Ihren Suchbegriffen" msgid "" "(!) You're performing a title search that might not include all related " "results of your search query in this wiki. [[BR]]" msgstr "" "(!) Sie führen eine Titelsuche durch, die möglicherweise nicht alle " "relevanten Ergebnisse Ihrer Sucheanfrage in diesem Wiki enthält. [[BR]]" msgid "Click here to perform a full-text search with your search terms!" msgstr "Hier klicken für eine Volltextsuche mit diesen Suchbegriffen!" #, python-format msgid "" "Restored Backup: %(filename)s to target dir: %(targetdir)s.\n" "Files: %(filecount)d, Directories: %(dircount)d" msgstr "" "Wiederhergestelltes Backup: %(filename)s nach Zielverzeichnis: %(targetdir)" "s.\n" "Dateien: %(filecount)d, Verzeichnisse: %(dircount)d" #, python-format msgid "Restoring backup: %(filename)s to target dir: %(targetdir)s failed." msgstr "" "Wiederherstellen von Backup %(filename)s in das Zielverzeichnis %(targetdir)" "s fehlgeschlagen." msgid "Wiki Backup / Restore" msgstr "Wiki Sicherung / Wiederherstellung" msgid "" "Some hints:\n" " * To restore a backup:\n" " * Restoring a backup will overwrite existing data, so be careful.\n" " * Rename it to .tar. (remove the --date--time--UTC " "stuff).\n" " * Put the backup file into the backup_storage_dir (use scp, ftp, ...).\n" " * Hit the [[GetText(Restore)]] button below.\n" "\n" " * To make a backup, just hit the [[GetText(Backup)]] button and save the " "file\n" " you get to a secure place.\n" "\n" "Please make sure your wiki configuration backup_* values are correct and " "complete.\n" "\n" msgstr "" "Hinweise:\n" " * Um ein Backup wiederherzustellen:\n" " * Das Wiederherstellen eines Backups wird bestehende Daten überschreiben, " "also seien Sie vorsichtig.\n" " * Benennen Sie es auf .tar. um (entfernen Sie --date--" "time--UTC).\n" " * Legen Sie die Backupdatei in das backup_storage_dir (mit scp, " "ftp, ...).\n" " * Drücken Sie unten auf [[GetText(Restore)]]-Knopf unten.\n" "\n" " * Um ein Backup zu erstellen, drücken Sie einfach auf den [[GetText" "(Backup)]]-Knopf und sichern Sie die Datei,\n" " die Sie erhalten an eine sichere Stelle.\n" "\n" "Bitte stellen Sie sicher, dass die backup_* Werte in Ihrer Wiki-" "Konfiguration korrekt und vollständig sind.\n" msgid "Backup" msgstr "Datensicherung" msgid "Restore" msgstr "Datenwiederherstellung" msgid "You are not allowed to do remote backup." msgstr "Sie dürfen kein Remote-Backup ausführen." #, python-format msgid "Unknown backup subaction: %s." msgstr "Unbekannte backup Unteraktion: %s." msgid "You are not allowed to revert this page!" msgstr "Sie dürfen diese Seite nicht restaurieren!" msgid "" "You were viewing the current revision of this page when you called the " "revert action. If you want to revert to an older revision, first view that " "older revision and then call revert to this (older) revision again." msgstr "" "Sie haben die aktuelle Revision dieser Seite angeschaut als Sie die " "Restaurieren-Funktion aufgerufen haben. Wenn Sie eine ältere Revision " "restaurieren wollen, betrachten Sie erst diese ältere Revision und rufen Sie " "dann die Restaurieren-Funktion für diese ältere Revision erneut auf." #, python-format msgid "Local Site Map for \"%s\"" msgstr "Lokale Seitenverweise für \"%s\"" #, python-format msgid "No pages like \"%s\"!" msgstr "Keine Seite ähnlich wie \"%s\"!" #, python-format msgid "Invalid filename \"%s\"!" msgstr "Ungültiger Dateiname \"%s\"!" #, python-format msgid "Created the package %s containing the pages %s." msgstr "Paket %s, das die Seiten %s enthält wurde erzeugt." msgid "Package pages" msgstr "Seiten paketieren" msgid "Package name" msgstr "Paketname" msgid "List of page names - separated by a comma" msgstr "Liste von Seitennamen - getrennt durch ein Komma" msgid "No older revisions available!" msgstr "Es sind keine älteren Versionen dieser Seite verfügbar!" #, python-format msgid "Diff for \"%s\"" msgstr "Änderungen von \"%s\"" #, python-format msgid "Differences between revisions %d and %d" msgstr "Unterschiede zwischen den Revisionen %d und %d" #, python-format msgid "(spanning %d versions)" msgstr "(über %d Versionen hinweg)" #, python-format msgid "The page was saved %(count)d times, though!" msgstr "Die Seite wurde jedoch %(count)d mal gespeichert!" msgid "(ignoring whitespace)" msgstr "(ignoriere Leerraum)" msgid "Ignore changes in the amount of whitespace" msgstr "Ausschließlich Leerraum betreffende Änderungen ignorieren" #, python-format msgid "Exactly one page like \"%s\" found, redirecting to page." msgstr "Genau eine Seite wie \"%s\" gefunden, leite dorthin weiter." #, python-format msgid "Pages like \"%s\"" msgstr "Seiten ähnlich wie \"%s\"" #, python-format msgid "%(matchcount)d %(matches)s for \"%(title)s\"" msgstr "%(matchcount)d %(matches)s passen zu \"%(title)s\"" msgid "Copy all /subpages too?" msgstr "Alle /UnterSeiten auch kopieren?" msgid "Optional reason for the copying" msgstr "Optionale Begründung für das Kopieren" msgid "Really copy this page?" msgstr "Diese Seite wirklich kopieren?" msgid "" "Cannot create a new page without a page name. Please specify a page name." msgstr "" "Kann keine neue Seite ohne Seitennamen anlegen - bitte geben Sie einen " "Seitennamen an." msgid "Delete" msgstr "Löschen" msgid "Delete all /subpages too?" msgstr "Alle /UnterSeiten auch löschen?" msgid "Optional reason for the deletion" msgstr "Optionale Begründung für die Löschung" msgid "Really delete this page?" msgstr "Diese Seite wirklich löschen?" #~ msgid "filename" #~ msgstr "Dateiname" #~ msgid "" #~ "~-If you submit this form, the submitted values will be displayed.\n" #~ "To use this form on other pages, insert a\n" #~ "[[BR]][[BR]]'''{{{ [[Form(\"%(pagename)s\")]]}}}'''[[BR]][[BR]]\n" #~ "macro call.-~\n" #~ msgstr "" #~ "~-Das Absenden dieses Formulars zeigt die eingegebenen Werte an.\n" #~ "Um das Formular auf anderen Seiten zu benutzen, muss folgender " #~ "Makroaufruf\n" #~ "[[BR]][[BR]]'''{{{ [[Form(\"%(pagename)s\")]]}}}'''[[BR]][[BR]]\n" #~ "auf diesen Seiten platziert werden.-~\n" #~ msgid "" #~ "Unknown user name: {{{\"%s\"}}}. Please enter user name and password." #~ msgstr "" #~ "Unbekannter Benutzername: {{{\"%s\"}}}. Bitte geben Sie Benutzername und " #~ "Passwort ein." pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/demo.ahk000066400000000000000000000072251250413007300253070ustar00rootroot00000000000000/* multiline comment msgbox(comment) */ send, key[pgdn] string := "hello" . x . "world!" string := "hello ""world""! " string := "hello `"world""! " ; single line comment1 ;;; single line comment2 ::stopi::viper_off() a::send, ^a mylabel:send, ^{space} ;; set mark e::send, ^e n:: send, ^n return !i:: viper("iviper") ; stdlib x = "viper"" " ; escaped quote Return #If WinExist("iviper" ) indexdir = %A_ScriptDir%\%dir% FileCreateDir, % indexdir fileindex = %indexdir%\_files FileSelectFile, file,,, Select an image:, Images (*.gif; *.jpg; *.bmp; *.png; *.tif; *.ico; *.cur; *.ani; *.exe; *.dll) ; viper i::viper_off() #If ;; keybindings #If WinExist("iviper") and WinActive("ahk_class Emacs") p:: k:: send, ^p return ,::send, +!, ;; beginning of page .::send, +!. ;; end of page [::send, !a ]::send, !e d:: ^k ;; kill line x:: send ^d \:: ^!k ;; kill next word or sexp #IfWinActive #Persistent F2:: ;; hotkey start: ;; label start2: ; label ppm := ppm_new(50, 50, 255) ppm_fill(ppm, 80, 90, 95) msgbox % getPixel(ppm, 1, 1) setPixel(90, 90, 90, ppm, 1, 1) msgbox % getPixel(ppm, 1, 1) ListVars ; command msgbox % ppm return ppm_read(file) { fileread, ppm, % file return ppm } ::hotstring:: ::hot3:: ppm_width(ppm) { regexmatch(ppm, "\R(\d+)\s(\d+)", dim) return dim1 } ppm_height(ppm) { regexmatch(ppm, "\R(\d+)\s(\d+)", dim) return dim2 } ppm_colors(ppm) { regexmatch(ppm, "\R(\d+)\D*\R", colors) ; \R stands for any return colors1 } ppm_data(ppm) { pos := regexmatch(ppm, "\R(\d+)\D*\R", colors) ; \R stands for any newline stringtrimleft, data, ppm, pos + strlen(colors1) return data } ppm_header(ppm) { pos := regexmatch(ppm, "\R(\d+)\D*\R", colors) ; \R stands for any newline stringleft, header, ppm, pos + strlen(colors1) return header } ppm_fill(ByRef ppm, r, g, b) { width := ppm_width(ppm) height := ppm_height(ppm) header := ppm_header(ppm) headerLength := strlen(header) varsetcapacity(data, width * height, 0) loop, % (width * height) { if r numput(r, data, (A_Index - 1) * 3, "uchar") if g numput(g, data, (A_Index - 1) * 3 + 1, "uchar") if b numput(b, data, (A_Index - 1) * 3 + 2, "uchar") } VarCopy(&ppm + headerLength, &data, width * height) } ppm_new(width, height, colors) { header = P6`n%width% %height%`n%colors%`n headerLength := strlen(header) varsetcapacity(ppm, width * height + headerLength, 1) varsetcapacity(data, width * height, 0) VarCopy(&ppm, &header, headerLength) VarCopy(&ppm + headerLength, &data, width * height) return ppm } heredoc = ( P6 # lasdjkf 87 09 255 color data... ) ; Example: Simple image viewer: Gui, +Resize Gui, Add, Button, default, &Load New Image Gui, Add, Radio, ym+5 x+10 vRadio checked, Load &actual size Gui, Add, Radio, ym+5 x+10, Load to &fit screen Gui, Add, Pic, xm vPic Gui, Show return ButtonLoadNewImage: FileSelectFile, file,,, Select an image:, Images (*.gif; *.jpg; *.bmp; *.png; *.tif; *.ico; *.cur; *.ani; *.exe; *.dll) if file = return Gui, Submit, NoHide ; Save the values of the radio buttons. if Radio = 1 ; Display image at its actual size. { Width = 0 Height = 0 } else ; Second radio is selected: Resize the image to fit the screen. { Width := A_ScreenWidth - 28 ; Minus 28 to allow room for borders and margins inside. Height = -1 ; "Keep aspect ratio" seems best. } GuiControl,, Pic, *w%width% *h%height% %file% ; Load the image. Gui, Show, xCenter y0 AutoSize, %file% ; Resize the window to match the picture size. return GuiClose: ExitApp ; Example: Simple text editor with menu bar. ; Create the sub-menus for the menu bar: Menu, FileMenu, Add, &New, FileNew pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/demo.cfm000066400000000000000000000016511250413007300253060ustar00rootroot00000000000000 ---> ---> Date Functions #RightNow#
#DateFormat(RightNow)#
#DateFormat(RightNow,"mm/dd/yy")#
#TimeFormat(RightNow)#
#TimeFormat(RightNow,"hh:mm tt")#
#IsDate(RightNow)#
#IsDate("January 31, 2007")#
#IsDate("foo")#
#DaysInMonth(RightNow)#
#x# #y# #z# ---> comment ---> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/demo.hbs000066400000000000000000000003531250413007300253130ustar00rootroot00000000000000
{{intro}}
{{#if isExpanded}}
{{body}}
{{else}} {{/if}} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/django_sample.html+django000066400000000000000000000067021250413007300306240ustar00rootroot00000000000000{% extends "admin/base_site.html" %} {% load i18n admin_modify adminmedia %} {% block extrahead %}{{ block.super }} {% for js in javascript_imports %}{% include_admin_script js %}{% endfor %} {% endblock %} {% block stylesheet %}{% admin_media_prefix %}css/forms.css{% endblock %} {% block coltype %}{% if ordered_objects %}colMS{% else %}colM{% endif %}{% endblock %} {% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %} {% block userlinks %}{% trans 'Documentation' %} / {% trans 'Change password' %} / {% trans 'Log out' %}{% endblock %} {% block breadcrumbs %}{% if not is_popup %} {% endif %}{% endblock %} {% block content %}
{% if change %}{% if not is_popup %} {% endif %}{% endif %}
{% block form_top %}{% endblock %}
{% if is_popup %}{% endif %} {% if opts.admin.save_on_top %}{% submit_row %}{% endif %} {% if form.error_dict %}

{% blocktrans count form.error_dict.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}

{% endif %} {% for bound_field_set in bound_field_sets %}
{% if bound_field_set.name %}

{{ bound_field_set.name }}

{% endif %} {% if bound_field_set.description %}
{{ bound_field_set.description }}
{% endif %} {% for bound_field_line in bound_field_set %} {% admin_field_line bound_field_line %} {% for bound_field in bound_field_line %} {% filter_interface_script_maybe bound_field %} {% endfor %} {% endfor %}
{% endfor %} {% block after_field_sets %}{% endblock %} {% if change %} {% if ordered_objects %}

{% trans "Ordering" %}

{% if form.order_.errors %}{{ form.order_.html_error_list }}{% endif %}

{{ form.order_ }}

{% endif %} {% endif %} {% for related_object in inline_related_objects %}{% edit_inline related_object %}{% endfor %} {% block after_related_objects %}{% endblock %} {% submit_row %} {% if add %} {% endif %} {% if auto_populated_fields %} {% endif %}
{% endblock %} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/dwarf.cw000066400000000000000000000014761250413007300253360ustar00rootroot00000000000000;redcode ;name Dwarf ;author A. K. Dewdney ;version 94.1 ;date April 29, 1993 ;strategy Bombs every fourth instruction. ORG start ; Indicates the instruction with ; the label "start" should be the ; first to execute. step EQU 4 ; Replaces all occurrences of "step" ; with the character "4". target DAT.F #0, #0 ; Pointer to target instruction. start ADD.AB #step, target ; Increments pointer by step. MOV.AB #0, @target ; Bombs target instruction. JMP.A start ; Same as JMP.A -2. Loops back to ; the instruction labelled "start". END pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ember.handlebars000066400000000000000000000021431250413007300270070ustar00rootroot00000000000000{{#view EmberFirebaseChat.ChatView class="chat-container"}}
    {{#each message in content}}
  • [{{formatTimestamp "message.timestamp" fmtString="h:mm:ss A"}}] {{message.sender}}: {{message.content}}
  • {{/each}}
{{! Comment }} {{{unescaped value}}} {{#view EmberFirebaseChat.InputView class="chat-input-container"}}
{{#if "auth.authed"}} {{#if "auth.hasName"}} {{else}} {{/if}} {{else}} {{/if}}
{{/view}} {{/view}} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/erl_session000066400000000000000000000002211250413007300261330ustar00rootroot000000000000001> io:format("Hello\n"). Hello ok 2> fun(X) -> X + 1 end. #Fun 3> 123 + 234. 357 4> X = Y. * 1: variable 'Y' is unbound 5> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/escape_semicolon.clj000066400000000000000000000000561250413007300276730ustar00rootroot00000000000000(= c (int \;)) (do (.readLine s) :line-start) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/evil_regex.js000066400000000000000000000020451250413007300263600ustar00rootroot00000000000000/regexp/.test(foo) || x = [/regexp/,/regexp/, /regexp/, // comment // comment /regexp/]; if (/regexp/.test(string)) {/regexp/.test(string);}; x =/regexp/; x = /regexp/; if (0/regexp/.exec(string)) x = { u:/regexp/, v: /regexp/ }; foo();/regexp/.test(string); /regexp/.test(string); if (!/regexp/) foobar(); x = u %/regexp/.exec(string) */regexp/.exec(string) / /regexp/.exec(string); x = u?/regexp/.exec(string) : v +/regexp/.exec(string) -/regexp/.exec(string); a = u^/regexp/.exec(string) &/regexp/.exec(string) |/regexp/.exec(string) +~/regexp/.exec(string); x = /regexp/ /* a comment */ ; x = /[reg/exp]/; x = 4/2/i; x = (a == b) ?/* this is a comment */ c : d; /// a comment // a = /regex//2/1; //syntactically correct, returns NaN /* original examples */ // regex blah(/abc/); x = /abc/; x = /abc/.match; // math blah(1/2); //comment x = 1 / 2 / 3; x = 1/1/.1; // broken x=/1/; x=1/a/g; x=a/a/g; // real-world var x = 1/(1+Math.sqrt(sum)); // convert to number between 1-0 return Math.round((num / den) * 100)/100; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.Rd000066400000000000000000000031361250413007300256150ustar00rootroot00000000000000\name{foo} \alias{foo} % I'm a comment \title{The foo function} \description{It doesn't do much} \usage{ foo(x, y) } \arguments{ \item{x}{A number} \item{y}{Another number} } \details{ I just adds \code{x} and \code{y}, } \value{\code{numeric}. The sum of \code{x} and \code{y}.} \references{ \href{http://en.wikipedia.org/wiki/Sum}{Sum} } \author{ Anonymous } \note{ Lorem ipsum \dots \R \emph{emp}, \strong{strong}, \bold{bold}, \sQuote{single quotes}, \dQuote{double quotes}, \code{code}, \preformatted{x <- 2 + 2}, \kbd{type this}, \samp{literal seq}, \pkg{base}, \file{foo.txt}, \email{email@hostname}, \url{http://cran.r-project.org/}, \var{foo}, \env{HOME}, \option{-d}, \dfn{something new}, \acronym{GNU}. Escaped symbols: \\ \{ \} \% not comment. \\NotAMacro. \tabular{rlll}{ [,1] \tab alpha \tab numeric \tab A (ppb)\cr [,2] \tab bravo \tab integer \tab B \cr [,3] \tab charlie \tab character \tab C \cr } \enumerate{ \item delta \item echo } \itemize{ \item foxtrot \item golf } \deqn{p(x; \mu, \sigma^2) = \frac{1}{\sigma \sqrt{2 \pi}} \exp \frac{-(x - \mu)^2}{2 \sigma}{% p(\mu; x) = 1/\sigma (2 \pi)^(-1/2) exp( -(x - \mu)^2 / (2 \sigma)) } for \eqn{x = 0, 1, 2, \ldots}. \if{latex}{\out{\beta}}\ifelse{html}{\out{β}}{beta} #ifdef unix Now windows #endif #ifndef windows Using windows #endif } \section{Misc}{ Stuff. } \seealso{ \code{\link{sum}} } \examples{ x <- 1 y <- 2 z <- foo(x, y) \dontrun{plot(z)} \dontshow{log(x)} } \keyword{arith} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.als000066400000000000000000000146631250413007300260360ustar00rootroot00000000000000module examples/systems/views /* * Model of views in object-oriented programming. * * Two object references, called the view and the backing, * are related by a view mechanism when changes to the * backing are automatically propagated to the view. Note * that the state of a view need not be a projection of the * state of the backing; the keySet method of Map, for * example, produces two view relationships, and for the * one in which the map is modified by changes to the key * set, the value of the new map cannot be determined from * the key set. Note that in the iterator view mechanism, * the iterator is by this definition the backing object, * since changes are propagated from iterator to collection * and not vice versa. Oddly, a reference may be a view of * more than one backing: there can be two iterators on the * same collection, eg. A reference cannot be a view under * more than one view type. * * A reference is made dirty when it is a backing for a view * with which it is no longer related by the view invariant. * This usually happens when a view is modified, either * directly or via another backing. For example, changing a * collection directly when it has an iterator invalidates * it, as does changing the collection through one iterator * when there are others. * * More work is needed if we want to model more closely the * failure of an iterator when its collection is invalidated. * * As a terminological convention, when there are two * complementary view relationships, we will give them types * t and t'. For example, KeySetView propagates from map to * set, and KeySetView' propagates from set to map. * * author: Daniel Jackson */ open util/ordering[State] as so open util/relation as rel sig Ref {} sig Object {} -- t->b->v in views when v is view of type t of backing b -- dirty contains refs that have been invalidated sig State { refs: set Ref, obj: refs -> one Object, views: ViewType -> refs -> refs, dirty: set refs -- , anyviews: Ref -> Ref -- for visualization } -- {anyviews = ViewType.views} sig Map extends Object { keys: set Ref, map: keys -> one Ref }{all s: State | keys + Ref.map in s.refs} sig MapRef extends Ref {} fact {State.obj[MapRef] in Map} sig Iterator extends Object { left, done: set Ref, lastRef: lone done }{all s: State | done + left + lastRef in s.refs} sig IteratorRef extends Ref {} fact {State.obj[IteratorRef] in Iterator} sig Set extends Object { elts: set Ref }{all s: State | elts in s.refs} sig SetRef extends Ref {} fact {State.obj[SetRef] in Set} abstract sig ViewType {} one sig KeySetView, KeySetView', IteratorView extends ViewType {} fact ViewTypes { State.views[KeySetView] in MapRef -> SetRef State.views[KeySetView'] in SetRef -> MapRef State.views[IteratorView] in IteratorRef -> SetRef all s: State | s.views[KeySetView] = ~(s.views[KeySetView']) } /** * mods is refs modified directly or by view mechanism * doesn't handle possibility of modifying an object and its view at once? * should we limit frame conds to non-dirty refs? */ pred modifies [pre, post: State, rs: set Ref] { let vr = pre.views[ViewType], mods = rs.*vr { all r: pre.refs - mods | pre.obj[r] = post.obj[r] all b: mods, v: pre.refs, t: ViewType | b->v in pre.views[t] => viewFrame [t, pre.obj[v], post.obj[v], post.obj[b]] post.dirty = pre.dirty + {b: pre.refs | some v: Ref, t: ViewType | b->v in pre.views[t] && !viewFrame [t, pre.obj[v], post.obj[v], post.obj[b]] } } } pred allocates [pre, post: State, rs: set Ref] { no rs & pre.refs post.refs = pre.refs + rs } /** * models frame condition that limits change to view object from v to v' when backing object changes to b' */ pred viewFrame [t: ViewType, v, v', b': Object] { t in KeySetView => v'.elts = dom [b'.map] t in KeySetView' => b'.elts = dom [v'.map] t in KeySetView' => (b'.elts) <: (v.map) = (b'.elts) <: (v'.map) t in IteratorView => v'.elts = b'.left + b'.done } pred MapRef.keySet [pre, post: State, setRefs: SetRef] { post.obj[setRefs].elts = dom [pre.obj[this].map] modifies [pre, post, none] allocates [pre, post, setRefs] post.views = pre.views + KeySetView->this->setRefs + KeySetView'->setRefs->this } pred MapRef.put [pre, post: State, k, v: Ref] { post.obj[this].map = pre.obj[this].map ++ k->v modifies [pre, post, this] allocates [pre, post, none] post.views = pre.views } pred SetRef.iterator [pre, post: State, iterRef: IteratorRef] { let i = post.obj[iterRef] { i.left = pre.obj[this].elts no i.done + i.lastRef } modifies [pre,post,none] allocates [pre, post, iterRef] post.views = pre.views + IteratorView->iterRef->this } pred IteratorRef.remove [pre, post: State] { let i = pre.obj[this], i' = post.obj[this] { i'.left = i.left i'.done = i.done - i.lastRef no i'.lastRef } modifies [pre,post,this] allocates [pre, post, none] pre.views = post.views } pred IteratorRef.next [pre, post: State, ref: Ref] { let i = pre.obj[this], i' = post.obj[this] { ref in i.left i'.left = i.left - ref i'.done = i.done + ref i'.lastRef = ref } modifies [pre, post, this] allocates [pre, post, none] pre.views = post.views } pred IteratorRef.hasNext [s: State] { some s.obj[this].left } assert zippishOK { all ks, vs: SetRef, m: MapRef, ki, vi: IteratorRef, k, v: Ref | let s0=so/first, s1=so/next[s0], s2=so/next[s1], s3=so/next[s2], s4=so/next[s3], s5=so/next[s4], s6=so/next[s5], s7=so/next[s6] | ({ precondition [s0, ks, vs, m] no s0.dirty ks.iterator [s0, s1, ki] vs.iterator [s1, s2, vi] ki.hasNext [s2] vi.hasNext [s2] ki.this/next [s2, s3, k] vi.this/next [s3, s4, v] m.put [s4, s5, k, v] ki.remove [s5, s6] vi.remove [s6, s7] } => no State.dirty) } pred precondition [pre: State, ks, vs, m: Ref] { // all these conditions and other errors discovered in scope of 6 but 8,3 // in initial state, must have view invariants hold (all t: ViewType, b, v: pre.refs | b->v in pre.views[t] => viewFrame [t, pre.obj[v], pre.obj[v], pre.obj[b]]) // sets are not aliases -- ks != vs // sets are not views of map -- no (ks+vs)->m & ViewType.pre.views // no iterator currently on either set -- no Ref->(ks+vs) & ViewType.pre.views } check zippishOK for 6 but 8 State, 3 ViewType expect 1 /** * experiment with controlling heap size */ fact {all s: State | #s.obj < 5} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.bug000066400000000000000000000032341250413007300260240ustar00rootroot00000000000000# Alligators: multinomial - logistic regression # http://www.openbugs.info/Examples/Aligators.html model { # PRIORS alpha[1] <- 0; # zero contrast for baseline food for (k in 2 : K) { alpha[k] ~ dnorm(0, 0.00001) # vague priors } # Loop around lakes: for (k in 1 : K){ beta[1, k] <- 0 } # corner-point contrast with first lake for (i in 2 : I) { beta[i, 1] <- 0 ; # zero contrast for baseline food for (k in 2 : K){ beta[i, k] ~ dnorm(0, 0.00001) # vague priors } } # Loop around sizes: for (k in 1 : K){ gamma[1, k] <- 0 # corner-point contrast with first size } for (j in 2 : J) { gamma[j, 1] <- 0 ; # zero contrast for baseline food for ( k in 2 : K){ gamma[j, k] ~ dnorm(0, 0.00001) # vague priors } } # LIKELIHOOD for (i in 1 : I) { # loop around lakes for (j in 1 : J) { # loop around sizes # Fit standard Poisson regressions relative to baseline lambda[i, j] ~ dflat() # vague priors for (k in 1 : K) { # loop around foods X[i, j, k] ~ dpois(mu[i, j, k]) log(mu[i, j, k]) <- lambda[i, j] + alpha[k] + beta[i, k] + gamma[j, k] culmative.X[i, j, k] <- culmative(X[i, j, k], X[i, j, k]) } } } # TRANSFORM OUTPUT TO ENABLE COMPARISON # WITH AGRESTI'S RESULTS for (k in 1 : K) { # loop around foods for (i in 1 : I) { # loop around lakes b[i, k] <- beta[i, k] - mean(beta[, k]); # sum to zero constraint } for (j in 1 : J) { # loop around sizes g[j, k] <- gamma[j, k] - mean(gamma[, k]); # sum to zero constraint } } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.c000066400000000000000000001342451250413007300255000ustar00rootroot00000000000000#include #include #include #include "codegen.h" #include "symboltable.h" #include "stringbuffer.h" extern void yyerror(char* msg); static stringBuffer* staticVariableBuffer; static stringBuffer* classInitBuffer; static stringBuffer* currentMethodBuffer; static stringBuffer* finishedMethodsBuffer; static stringBuffer* mainBuffer; static int currentMethodBufferIndex; static int currentMethodStackSize; static int currentMethodStackSizeMax; static int currentMethodNumberOfLocals; static int classInitBufferIndex; static int classInitStackSize; static int classInitStackSizeMax; static int labelCounter = 0; static int global = 1; char tempString[MAX_LENGTH_OF_COMMAND]; extern char* className; /* from minako-syntax.y */ /* forward declarations */ static void increaseStackby(int stackdiff); char convertType(int type); void codegenInit() { staticVariableBuffer = newStringBuffer(); classInitBuffer = newStringBuffer(); currentMethodBuffer = 0; finishedMethodsBuffer = newStringBuffer(); mainBuffer = newStringBuffer(); stringBufferAppend(mainBuffer, "; ------- Header --------------------------------------------"); sprintf(tempString, ".class public synchronized %s", className); stringBufferAppend(mainBuffer, tempString); stringBufferAppend(mainBuffer, ".super java/lang/Object"); stringBufferAppend(mainBuffer, "; -----------------------------------------------------------"); stringBufferAppend(mainBuffer, ""); stringBufferAppend(finishedMethodsBuffer, "; ------- Constructor ---------------------------------------"); stringBufferAppend(finishedMethodsBuffer, ".method public ()V"); stringBufferAppend(finishedMethodsBuffer, "\t.limit stack 1"); stringBufferAppend(finishedMethodsBuffer, "\t.limit locals 1"); stringBufferAppend(finishedMethodsBuffer, "\taload_0"); stringBufferAppend(finishedMethodsBuffer, "\tinvokenonvirtual java/lang/Object/()V"); stringBufferAppend(finishedMethodsBuffer, "\treturn"); stringBufferAppend(finishedMethodsBuffer, ".end method"); stringBufferAppend(finishedMethodsBuffer, "; -----------------------------------------------------------"); stringBufferAppend(finishedMethodsBuffer, ""); stringBufferAppend(staticVariableBuffer, "; ------- Class Variables -----------------------------------"); stringBufferAppend(classInitBuffer, "; ------- Class Initializer ---------------------------------"); stringBufferAppend(classInitBuffer, ".method static ()V"); classInitBufferIndex = classInitBuffer->numberOfNextElement; stringBufferAppend(classInitBuffer, "\t.limit locals 0"); } void codegenAppendCommand(char* cmd, int stackdiff) { char tempString[MAX_LENGTH_OF_COMMAND]; sprintf(tempString, "\t%s", cmd); if (global) stringBufferAppend(classInitBuffer, tempString); else stringBufferAppend(currentMethodBuffer, tempString); increaseStackby(stackdiff); } void codegenInsertCommand(int address, char* cmd, int stackdiff) { char tempString[MAX_LENGTH_OF_COMMAND]; sprintf(tempString, "\t%s", cmd); if (global) stringBufferInsert(classInitBuffer, address, tempString); else stringBufferInsert(currentMethodBuffer, address, tempString); increaseStackby(stackdiff); } void codegenAppendLabel(int label) { char tempString[MAX_LENGTH_OF_COMMAND]; sprintf(tempString, "Label%d:", label); if (global) stringBufferAppend(classInitBuffer, tempString); else stringBufferAppend(currentMethodBuffer, tempString); } void codegenAddVariable(char* name, int type) { /*fprintf(stderr, "add variable %s(%d) global=%d ", name, convertType(type), global);*/ if (global) { if (type == TYPE_INT) sprintf(tempString, ".field static %s %c", name, 'I'); else if (type == TYPE_FLOAT) sprintf(tempString, ".field static %s %c", name, 'F'); else if (type == TYPE_BOOLEAN) sprintf(tempString, ".field static %s %c", name, 'Z'); else yyerror("compiler-intern error in codegenAddGlobalVariable().\n"); stringBufferAppend(staticVariableBuffer, tempString); } else { currentMethodNumberOfLocals++; } } int codegenGetNextLabel() { return labelCounter++; } int codegenGetCurrentAddress() { if (global) return classInitBuffer->numberOfNextElement; else return currentMethodBuffer->numberOfNextElement; } void codegenEnterFunction(symtabEntry* entry) { currentMethodBuffer = newStringBuffer(); currentMethodStackSize = 0; currentMethodStackSizeMax = 0; labelCounter = 1; global = 0; if (strcmp(entry->name, "main") == 0) { if (entry->idtype != TYPE_VOID) yyerror("main has to be void.\n"); currentMethodNumberOfLocals = 1; symtabInsert(strdup("#main-param#"), TYPE_VOID, CLASS_FUNC); stringBufferAppend(currentMethodBuffer, "; ------- Methode ---- void main() --------------------------"); stringBufferAppend(currentMethodBuffer, ".method public static main([Ljava/lang/String;)V"); } else { int i; currentMethodNumberOfLocals = entry->paramIndex; stringBufferAppend(currentMethodBuffer, "; ------- Methode -------------------------------------------"); sprintf(tempString, ".method public static %s(", entry->name); for (i=entry->paramIndex-1; i>=0; i--) { int type = entry->params[i]->idtype; tempString[strlen(tempString)+1] = 0; tempString[strlen(tempString)] = convertType(type); } tempString[strlen(tempString)+2] = 0; tempString[strlen(tempString)+1] = convertType(entry->idtype); tempString[strlen(tempString)] = ')'; stringBufferAppend(currentMethodBuffer, tempString); } currentMethodBufferIndex = currentMethodBuffer->numberOfNextElement; } void codegenLeaveFunction() { global = 1; sprintf(tempString, "\t.limit locals %d", currentMethodNumberOfLocals); stringBufferInsert(currentMethodBuffer, currentMethodBufferIndex, tempString); sprintf(tempString, "\t.limit stack %d", currentMethodStackSizeMax); stringBufferInsert(currentMethodBuffer, currentMethodBufferIndex, tempString); stringBufferAppend(currentMethodBuffer, "\treturn"); stringBufferAppend(currentMethodBuffer, ".end method"); stringBufferAppend(currentMethodBuffer, "; -----------------------------------------------------------"); stringBufferAppend(currentMethodBuffer, ""); stringBufferConcatenate(finishedMethodsBuffer, currentMethodBuffer); } void codegenFinishCode() { stringBufferAppend(staticVariableBuffer, "; -----------------------------------------------------------"); stringBufferAppend(staticVariableBuffer, ""); sprintf(tempString, "\t.limit stack %d", classInitStackSizeMax); stringBufferInsert(classInitBuffer, classInitBufferIndex, tempString); stringBufferAppend(classInitBuffer, "\treturn"); stringBufferAppend(classInitBuffer, ".end method"); stringBufferAppend(classInitBuffer, "; -----------------------------------------------------------"); stringBufferConcatenate(mainBuffer, staticVariableBuffer); stringBufferConcatenate(mainBuffer, finishedMethodsBuffer); stringBufferConcatenate(mainBuffer, classInitBuffer); stringBufferPrint(mainBuffer); } static void increaseStackby(int stackdiff) { if (global) { classInitStackSize += stackdiff; if (classInitStackSize > classInitStackSizeMax) classInitStackSizeMax = classInitStackSize; } else { currentMethodStackSize += stackdiff; if (currentMethodStackSize > currentMethodStackSizeMax) currentMethodStackSizeMax = currentMethodStackSize; } } char convertType(int type) { switch(type) { case TYPE_VOID: return 'V'; case TYPE_INT: return 'I'; case TYPE_FLOAT: return 'F'; case TYPE_BOOLEAN: return 'Z'; default : yyerror("compiler-intern error in convertType().\n"); } return 0; /* to avoid compiler-warning */ } //#include //#include int main() { int a = 12, b = 44; while (a != b) { if (a > b) a -= b; else b -= a; } printf("%d\n%d", a, 0X0);\ } /********************************************************************** array.c - $Author: murphy $ $Date: 2005-11-05 04:33:55 +0100 (Sa, 05 Nov 2005) $ created at: Fri Aug 6 09:46:12 JST 1993 Copyright (C) 1993-2003 Yukihiro Matsumoto Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan **********************************************************************/ #include "ruby.h" #include "util.h" #include "st.h" #include "node.h" VALUE rb_cArray, rb_cValues; static ID id_cmp; #define ARY_DEFAULT_SIZE 16 void rb_mem_clear(mem, size) register VALUE *mem; register long size; { while (size--) { *mem++ = Qnil; } } static inline void memfill(mem, size, val) register VALUE *mem; register long size; register VALUE val; { while (size--) { *mem++ = val; } } #define ARY_TMPLOCK FL_USER1 static inline void rb_ary_modify_check(ary) VALUE ary; { if (OBJ_FROZEN(ary)) rb_error_frozen("array"); if (FL_TEST(ary, ARY_TMPLOCK)) rb_raise(rb_eRuntimeError, "can't modify array during iteration"); if (!OBJ_TAINTED(ary) && rb_safe_level() >= 4) rb_raise(rb_eSecurityError, "Insecure: can't modify array"); } static void rb_ary_modify(ary) VALUE ary; { VALUE *ptr; rb_ary_modify_check(ary); if (FL_TEST(ary, ELTS_SHARED)) { ptr = ALLOC_N(VALUE, RARRAY(ary)->len); FL_UNSET(ary, ELTS_SHARED); RARRAY(ary)->aux.capa = RARRAY(ary)->len; MEMCPY(ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); RARRAY(ary)->ptr = ptr; } } VALUE rb_ary_freeze(ary) VALUE ary; { return rb_obj_freeze(ary); } /* * call-seq: * array.frozen? -> true or false * * Return true if this array is frozen (or temporarily frozen * while being sorted). */ static VALUE rb_ary_frozen_p(ary) VALUE ary; { if (OBJ_FROZEN(ary)) return Qtrue; if (FL_TEST(ary, ARY_TMPLOCK)) return Qtrue; return Qfalse; } static VALUE ary_alloc(VALUE); static VALUE ary_alloc(klass) VALUE klass; { NEWOBJ(ary, struct RArray); OBJSETUP(ary, klass, T_ARRAY); ary->len = 0; ary->ptr = 0; ary->aux.capa = 0; return (VALUE)ary; } static VALUE ary_new(klass, len) VALUE klass; long len; { VALUE ary; if (len < 0) { rb_raise(rb_eArgError, "negative array size (or size too big)"); } if (len > 0 && len * sizeof(VALUE) <= len) { rb_raise(rb_eArgError, "array size too big"); } if (len == 0) len++; ary = ary_alloc(klass); RARRAY(ary)->ptr = ALLOC_N(VALUE, len); RARRAY(ary)->aux.capa = len; return ary; } VALUE rb_ary_new2(len) long len; { return ary_new(rb_cArray, len); } VALUE rb_ary_new() { return rb_ary_new2(ARY_DEFAULT_SIZE); } #ifdef HAVE_STDARG_PROTOTYPES #include #define va_init_list(a,b) va_start(a,b) #else #include #define va_init_list(a,b) va_start(a) #endif VALUE #ifdef HAVE_STDARG_PROTOTYPES rb_ary_new3(long n, ...) #else rb_ary_new3(n, va_alist) long n; va_dcl #endif { va_list ar; VALUE ary; long i; ary = rb_ary_new2(n); va_init_list(ar, n); for (i=0; iptr[i] = va_arg(ar, VALUE); } va_end(ar); RARRAY(ary)->len = n; return ary; } VALUE rb_ary_new4(n, elts) long n; const VALUE *elts; { VALUE ary; ary = rb_ary_new2(n); if (n > 0 && elts) { MEMCPY(RARRAY(ary)->ptr, elts, VALUE, n); } RARRAY(ary)->len = n; return ary; } VALUE #ifdef HAVE_STDARG_PROTOTYPES rb_values_new(long n, ...) #else rb_values_new(n, va_alist) long n; va_dcl #endif { va_list ar; VALUE val; long i; val = ary_new(rb_cValues, n); va_init_list(ar, n); for (i=0; iptr[i] = va_arg(ar, VALUE); } va_end(ar); RARRAY(val)->len = n; return val; } VALUE rb_values_new2(n, elts) long n; const VALUE *elts; { VALUE val; val = ary_new(rb_cValues, n); if (n > 0 && elts) { RARRAY(val)->len = n; MEMCPY(RARRAY(val)->ptr, elts, VALUE, n); } return val; } static VALUE ary_make_shared(ary) VALUE ary; { if (!FL_TEST(ary, ELTS_SHARED)) { NEWOBJ(shared, struct RArray); OBJSETUP(shared, rb_cArray, T_ARRAY); shared->len = RARRAY(ary)->len; shared->ptr = RARRAY(ary)->ptr; shared->aux.capa = RARRAY(ary)->aux.capa; RARRAY(ary)->aux.shared = (VALUE)shared; FL_SET(ary, ELTS_SHARED); OBJ_FREEZE(shared); return (VALUE)shared; } else { return RARRAY(ary)->aux.shared; } } static VALUE ary_shared_array(klass, ary) VALUE klass, ary; { VALUE val = ary_alloc(klass); ary_make_shared(ary); RARRAY(val)->ptr = RARRAY(ary)->ptr; RARRAY(val)->len = RARRAY(ary)->len; RARRAY(val)->aux.shared = RARRAY(ary)->aux.shared; FL_SET(val, ELTS_SHARED); return val; } VALUE rb_values_from_ary(ary) VALUE ary; { return ary_shared_array(rb_cValues, ary); } VALUE rb_ary_from_values(val) VALUE val; { return ary_shared_array(rb_cArray, val); } VALUE rb_assoc_new(car, cdr) VALUE car, cdr; { return rb_values_new(2, car, cdr); } static VALUE to_ary(ary) VALUE ary; { return rb_convert_type(ary, T_ARRAY, "Array", "to_ary"); } static VALUE to_a(ary) VALUE ary; { return rb_convert_type(ary, T_ARRAY, "Array", "to_a"); } VALUE rb_check_array_type(ary) VALUE ary; { return rb_check_convert_type(ary, T_ARRAY, "Array", "to_ary"); } static VALUE rb_ary_replace _((VALUE, VALUE)); /* * call-seq: * Array.new(size=0, obj=nil) * Array.new(array) * Array.new(size) {|index| block } * * Returns a new array. In the first form, the new array is * empty. In the second it is created with _size_ copies of _obj_ * (that is, _size_ references to the same * _obj_). The third form creates a copy of the array * passed as a parameter (the array is generated by calling * to_ary on the parameter). In the last form, an array * of the given size is created. Each element in this array is * calculated by passing the element's index to the given block and * storing the return value. * * Array.new * Array.new(2) * Array.new(5, "A") * * # only one copy of the object is created * a = Array.new(2, Hash.new) * a[0]['cat'] = 'feline' * a * a[1]['cat'] = 'Felix' * a * * # here multiple copies are created * a = Array.new(2) { Hash.new } * a[0]['cat'] = 'feline' * a * * squares = Array.new(5) {|i| i*i} * squares * * copy = Array.new(squares) */ static VALUE rb_ary_initialize(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long len; VALUE size, val; if (rb_scan_args(argc, argv, "02", &size, &val) == 0) { RARRAY(ary)->len = 0; if (rb_block_given_p()) { rb_warning("given block not used"); } return ary; } if (argc == 1 && !FIXNUM_P(size)) { val = rb_check_array_type(size); if (!NIL_P(val)) { rb_ary_replace(ary, val); return ary; } } len = NUM2LONG(size); if (len < 0) { rb_raise(rb_eArgError, "negative array size"); } if (len > 0 && len * (long)sizeof(VALUE) <= len) { rb_raise(rb_eArgError, "array size too big"); } rb_ary_modify(ary); if (len > RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, len); RARRAY(ary)->aux.capa = len; } if (rb_block_given_p()) { long i; if (argc == 2) { rb_warn("block supersedes default value argument"); } for (i=0; ilen = i + 1; } } else { memfill(RARRAY(ary)->ptr, len, val); RARRAY(ary)->len = len; } return ary; } /* * Returns a new array populated with the given objects. * * Array.[]( 1, 'a', /^A/ ) * Array[ 1, 'a', /^A/ ] * [ 1, 'a', /^A/ ] */ static VALUE rb_ary_s_create(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { VALUE ary = ary_alloc(klass); if (argc > 0) { RARRAY(ary)->ptr = ALLOC_N(VALUE, argc); MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc); } RARRAY(ary)->len = RARRAY(ary)->aux.capa = argc; return ary; } void rb_ary_store(ary, idx, val) VALUE ary; long idx; VALUE val; { if (idx < 0) { idx += RARRAY(ary)->len; if (idx < 0) { rb_raise(rb_eIndexError, "index %ld out of array", idx - RARRAY(ary)->len); } } rb_ary_modify(ary); if (idx >= RARRAY(ary)->aux.capa) { long new_capa = RARRAY(ary)->aux.capa / 2; if (new_capa < ARY_DEFAULT_SIZE) { new_capa = ARY_DEFAULT_SIZE; } new_capa += idx; if (new_capa * (long)sizeof(VALUE) <= new_capa) { rb_raise(rb_eArgError, "index too big"); } REALLOC_N(RARRAY(ary)->ptr, VALUE, new_capa); RARRAY(ary)->aux.capa = new_capa; } if (idx > RARRAY(ary)->len) { rb_mem_clear(RARRAY(ary)->ptr + RARRAY(ary)->len, idx-RARRAY(ary)->len + 1); } if (idx >= RARRAY(ary)->len) { RARRAY(ary)->len = idx + 1; } RARRAY(ary)->ptr[idx] = val; } static VALUE ary_shared_first(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE nv, result; long n; rb_scan_args(argc, argv, "1", &nv); n = NUM2LONG(nv); if (n > RARRAY(ary)->len) { n = RARRAY(ary)->len; } else if (n < 0) { rb_raise(rb_eArgError, "negative array size"); } result = ary_shared_array(rb_cArray, ary); RARRAY(result)->len = n; return result; } static VALUE ary_shared_last(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE result = ary_shared_first(argc, argv, ary); RARRAY(result)->ptr += RARRAY(ary)->len - RARRAY(result)->len; return result; } /* * call-seq: * array << obj -> array * * Append---Pushes the given object on to the end of this array. This * expression returns the array itself, so several appends * may be chained together. * * [ 1, 2 ] << "c" << "d" << [ 3, 4 ] * #=> [ 1, 2, "c", "d", [ 3, 4 ] ] * */ VALUE rb_ary_push(ary, item) VALUE ary; VALUE item; { rb_ary_store(ary, RARRAY(ary)->len, item); return ary; } /* * call-seq: * array.push(obj, ... ) -> array * * Append---Pushes the given object(s) on to the end of this array. This * expression returns the array itself, so several appends * may be chained together. * * a = [ "a", "b", "c" ] * a.push("d", "e", "f") * #=> ["a", "b", "c", "d", "e", "f"] */ static VALUE rb_ary_push_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { while (argc--) { rb_ary_push(ary, *argv++); } return ary; } VALUE rb_ary_pop(ary) VALUE ary; { rb_ary_modify_check(ary); if (RARRAY(ary)->len == 0) return Qnil; if (!FL_TEST(ary, ELTS_SHARED) && RARRAY(ary)->len * 2 < RARRAY(ary)->aux.capa && RARRAY(ary)->aux.capa > ARY_DEFAULT_SIZE) { RARRAY(ary)->aux.capa = RARRAY(ary)->len * 2; REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa); } return RARRAY(ary)->ptr[--RARRAY(ary)->len]; } /* * call-seq: * array.pop -> obj or nil * * Removes the last element from self and returns it, or * nil if the array is empty. * * a = [ "a", "b", "c", "d" ] * a.pop #=> "d" * a.pop(2) #=> ["b", "c"] * a #=> ["a"] */ static VALUE rb_ary_pop_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE result; if (argc == 0) { return rb_ary_pop(ary); } rb_ary_modify_check(ary); result = ary_shared_last(argc, argv, ary); RARRAY(ary)->len -= RARRAY(result)->len; return result; } VALUE rb_ary_shift(ary) VALUE ary; { VALUE top; rb_ary_modify_check(ary); if (RARRAY(ary)->len == 0) return Qnil; top = RARRAY(ary)->ptr[0]; ary_make_shared(ary); RARRAY(ary)->ptr++; /* shift ptr */ RARRAY(ary)->len--; return top; } /* * call-seq: * array.shift -> obj or nil * * Returns the first element of self and removes it (shifting all * other elements down by one). Returns nil if the array * is empty. * * args = [ "-m", "-q", "filename" ] * args.shift #=> "-m" * args #=> ["-q", "filename"] * * args = [ "-m", "-q", "filename" ] * args.shift(2) #=> ["-m", "-q"] * args #=> ["filename"] */ static VALUE rb_ary_shift_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE result; long n; if (argc == 0) { return rb_ary_shift(ary); } rb_ary_modify_check(ary); result = ary_shared_first(argc, argv, ary); n = RARRAY(result)->len; RARRAY(ary)->ptr += n; RARRAY(ary)->len -= n; return result; } VALUE rb_ary_unshift(ary, item) VALUE ary, item; { rb_ary_modify(ary); if (RARRAY(ary)->len == RARRAY(ary)->aux.capa) { long capa_inc = RARRAY(ary)->aux.capa / 2; if (capa_inc < ARY_DEFAULT_SIZE) { capa_inc = ARY_DEFAULT_SIZE; } RARRAY(ary)->aux.capa += capa_inc; REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa); } /* sliding items */ MEMMOVE(RARRAY(ary)->ptr + 1, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); RARRAY(ary)->len++; RARRAY(ary)->ptr[0] = item; return ary; } /* * call-seq: * array.unshift(obj, ...) -> array * * Prepends objects to the front of array. * other elements up one. * * a = [ "b", "c", "d" ] * a.unshift("a") #=> ["a", "b", "c", "d"] * a.unshift(1, 2) #=> [ 1, 2, "a", "b", "c", "d"] */ static VALUE rb_ary_unshift_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long len = RARRAY(ary)->len; if (argc == 0) return ary; /* make rooms by setting the last item */ rb_ary_store(ary, len + argc - 1, Qnil); /* sliding items */ MEMMOVE(RARRAY(ary)->ptr + argc, RARRAY(ary)->ptr, VALUE, len); MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc); return ary; } /* faster version - use this if you don't need to treat negative offset */ static inline VALUE rb_ary_elt(ary, offset) VALUE ary; long offset; { if (RARRAY(ary)->len == 0) return Qnil; if (offset < 0 || RARRAY(ary)->len <= offset) { return Qnil; } return RARRAY(ary)->ptr[offset]; } VALUE rb_ary_entry(ary, offset) VALUE ary; long offset; { if (offset < 0) { offset += RARRAY(ary)->len; } return rb_ary_elt(ary, offset); } static VALUE rb_ary_subseq(ary, beg, len) VALUE ary; long beg, len; { VALUE klass, ary2, shared; VALUE *ptr; if (beg > RARRAY(ary)->len) return Qnil; if (beg < 0 || len < 0) return Qnil; if (beg + len > RARRAY(ary)->len) { len = RARRAY(ary)->len - beg; if (len < 0) len = 0; } klass = rb_obj_class(ary); if (len == 0) return ary_new(klass, 0); shared = ary_make_shared(ary); ptr = RARRAY(ary)->ptr; ary2 = ary_alloc(klass); RARRAY(ary2)->ptr = ptr + beg; RARRAY(ary2)->len = len; RARRAY(ary2)->aux.shared = shared; FL_SET(ary2, ELTS_SHARED); return ary2; } /* * call-seq: * array[index] -> obj or nil * array[start, length] -> an_array or nil * array[range] -> an_array or nil * array.slice(index) -> obj or nil * array.slice(start, length) -> an_array or nil * array.slice(range) -> an_array or nil * * Element Reference---Returns the element at _index_, * or returns a subarray starting at _start_ and * continuing for _length_ elements, or returns a subarray * specified by _range_. * Negative indices count backward from the end of the * array (-1 is the last element). Returns nil if the index * (or starting index) are out of range. * * a = [ "a", "b", "c", "d", "e" ] * a[2] + a[0] + a[1] #=> "cab" * a[6] #=> nil * a[1, 2] #=> [ "b", "c" ] * a[1..3] #=> [ "b", "c", "d" ] * a[4..7] #=> [ "e" ] * a[6..10] #=> nil * a[-3, 3] #=> [ "c", "d", "e" ] * # special cases * a[5] #=> nil * a[5, 1] #=> [] * a[5..10] #=> [] * */ VALUE rb_ary_aref(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE arg; long beg, len; if (argc == 2) { beg = NUM2LONG(argv[0]); len = NUM2LONG(argv[1]); if (beg < 0) { beg += RARRAY(ary)->len; } return rb_ary_subseq(ary, beg, len); } if (argc != 1) { rb_scan_args(argc, argv, "11", 0, 0); } arg = argv[0]; /* special case - speeding up */ if (FIXNUM_P(arg)) { return rb_ary_entry(ary, FIX2LONG(arg)); } /* check if idx is Range */ switch (rb_range_beg_len(arg, &beg, &len, RARRAY(ary)->len, 0)) { case Qfalse: break; case Qnil: return Qnil; default: return rb_ary_subseq(ary, beg, len); } return rb_ary_entry(ary, NUM2LONG(arg)); } /* * call-seq: * array.at(index) -> obj or nil * * Returns the element at _index_. A * negative index counts from the end of _self_. Returns +nil+ * if the index is out of range. See also Array#[]. * (Array#at is slightly faster than Array#[], * as it does not accept ranges and so on.) * * a = [ "a", "b", "c", "d", "e" ] * a.at(0) #=> "a" * a.at(-1) #=> "e" */ static VALUE rb_ary_at(ary, pos) VALUE ary, pos; { return rb_ary_entry(ary, NUM2LONG(pos)); } /* * call-seq: * array.first -> obj or nil * array.first(n) -> an_array * * Returns the first element of the array. If the array is empty, * returns nil. * * a = [ "q", "r", "s", "t" ] * a.first #=> "q" * a.first(2) #=> ["q", "r"] */ static VALUE rb_ary_first(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { if (argc == 0) { if (RARRAY(ary)->len == 0) return Qnil; return RARRAY(ary)->ptr[0]; } else { return ary_shared_first(argc, argv, ary); } } /* * call-seq: * array.last -> obj or nil * array.last(n) -> an_array * * Returns the last element(s) of self. If the array is empty, * the first form returns nil. * * a = [ "w", "x", "y", "z" ] * a.last #=> "z" * a.last(2) #=> ["y", "z"] */ static VALUE rb_ary_last(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { if (argc == 0) { if (RARRAY(ary)->len == 0) return Qnil; return RARRAY(ary)->ptr[RARRAY(ary)->len-1]; } else { return ary_shared_last(argc, argv, ary); } } /* * call-seq: * array.fetch(index) -> obj * array.fetch(index, default ) -> obj * array.fetch(index) {|index| block } -> obj * * Tries to return the element at position index. If the index * lies outside the array, the first form throws an * IndexError exception, the second form returns * default, and the third form returns the value of invoking * the block, passing in the index. Negative values of index * count from the end of the array. * * a = [ 11, 22, 33, 44 ] * a.fetch(1) #=> 22 * a.fetch(-1) #=> 44 * a.fetch(4, 'cat') #=> "cat" * a.fetch(4) { |i| i*i } #=> 16 */ static VALUE rb_ary_fetch(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE pos, ifnone; long block_given; long idx; rb_scan_args(argc, argv, "11", &pos, &ifnone); block_given = rb_block_given_p(); if (block_given && argc == 2) { rb_warn("block supersedes default value argument"); } idx = NUM2LONG(pos); if (idx < 0) { idx += RARRAY(ary)->len; } if (idx < 0 || RARRAY(ary)->len <= idx) { if (block_given) return rb_yield(pos); if (argc == 1) { rb_raise(rb_eIndexError, "index %ld out of array", idx); } return ifnone; } return RARRAY(ary)->ptr[idx]; } /* * call-seq: * array.index(obj) -> int or nil * array.index {|item| block} -> int or nil * * Returns the index of the first object in self such that is * == to obj. If a block is given instead of an * argument, returns first object for which block is true. * Returns nil if no match is found. * * a = [ "a", "b", "c" ] * a.index("b") #=> 1 * a.index("z") #=> nil * a.index{|x|x=="b"} #=> 1 */ static VALUE rb_ary_index(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE val; long i; if (rb_scan_args(argc, argv, "01", &val) == 0) { for (i=0; ilen; i++) { if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) { return LONG2NUM(i); } } } else { for (i=0; ilen; i++) { if (rb_equal(RARRAY(ary)->ptr[i], val)) return LONG2NUM(i); } } return Qnil; } /* * call-seq: * array.rindex(obj) -> int or nil * * Returns the index of the last object in array * == to obj. If a block is given instead of an * argument, returns first object for which block is * true. Returns nil if no match is found. * * a = [ "a", "b", "b", "b", "c" ] * a.rindex("b") #=> 3 * a.rindex("z") #=> nil * a.rindex{|x|x=="b"} #=> 3 */ static VALUE rb_ary_rindex(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE val; long i = RARRAY(ary)->len; if (rb_scan_args(argc, argv, "01", &val) == 0) { while (i--) { if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) return LONG2NUM(i); if (i > RARRAY(ary)->len) { i = RARRAY(ary)->len; } } } else { while (i--) { if (rb_equal(RARRAY(ary)->ptr[i], val)) return LONG2NUM(i); if (i > RARRAY(ary)->len) { i = RARRAY(ary)->len; } } } return Qnil; } VALUE rb_ary_to_ary(obj) VALUE obj; { if (TYPE(obj) == T_ARRAY) { return obj; } if (rb_respond_to(obj, rb_intern("to_ary"))) { return to_ary(obj); } return rb_ary_new3(1, obj); } static void rb_ary_splice(ary, beg, len, rpl) VALUE ary; long beg, len; VALUE rpl; { long rlen; if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len); if (beg < 0) { beg += RARRAY(ary)->len; if (beg < 0) { beg -= RARRAY(ary)->len; rb_raise(rb_eIndexError, "index %ld out of array", beg); } } if (beg + len > RARRAY(ary)->len) { len = RARRAY(ary)->len - beg; } if (rpl == Qundef) { rlen = 0; } else { rpl = rb_ary_to_ary(rpl); rlen = RARRAY(rpl)->len; } rb_ary_modify(ary); if (beg >= RARRAY(ary)->len) { len = beg + rlen; if (len >= RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, len); RARRAY(ary)->aux.capa = len; } rb_mem_clear(RARRAY(ary)->ptr + RARRAY(ary)->len, beg - RARRAY(ary)->len); if (rlen > 0) { MEMCPY(RARRAY(ary)->ptr + beg, RARRAY(rpl)->ptr, VALUE, rlen); } RARRAY(ary)->len = len; } else { long alen; if (beg + len > RARRAY(ary)->len) { len = RARRAY(ary)->len - beg; } alen = RARRAY(ary)->len + rlen - len; if (alen >= RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, alen); RARRAY(ary)->aux.capa = alen; } if (len != rlen) { MEMMOVE(RARRAY(ary)->ptr + beg + rlen, RARRAY(ary)->ptr + beg + len, VALUE, RARRAY(ary)->len - (beg + len)); RARRAY(ary)->len = alen; } if (rlen > 0) { MEMMOVE(RARRAY(ary)->ptr + beg, RARRAY(rpl)->ptr, VALUE, rlen); } } } /* * call-seq: * array[index] = obj -> obj * array[start, length] = obj or an_array or nil -> obj or an_array or nil * array[range] = obj or an_array or nil -> obj or an_array or nil * * Element Assignment---Sets the element at _index_, * or replaces a subarray starting at _start_ and * continuing for _length_ elements, or replaces a subarray * specified by _range_. If indices are greater than * the current capacity of the array, the array grows * automatically. A negative indices will count backward * from the end of the array. Inserts elements if _length_ is * zero. An +IndexError+ is raised if a negative index points * past the beginning of the array. See also * Array#push, and Array#unshift. * * a = Array.new * a[4] = "4"; #=> [nil, nil, nil, nil, "4"] * a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"] * a[1..2] = [ 1, 2 ] #=> ["a", 1, 2, nil, "4"] * a[0, 2] = "?" #=> ["?", 2, nil, "4"] * a[0..2] = "A" #=> ["A", "4"] * a[-1] = "Z" #=> ["A", "Z"] * a[1..-1] = nil #=> ["A", nil] * a[1..-1] = [] #=> ["A"] */ static VALUE rb_ary_aset(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long offset, beg, len; if (argc == 3) { rb_ary_splice(ary, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]); return argv[2]; } if (argc != 2) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc); } if (FIXNUM_P(argv[0])) { offset = FIX2LONG(argv[0]); goto fixnum; } if (rb_range_beg_len(argv[0], &beg, &len, RARRAY(ary)->len, 1)) { /* check if idx is Range */ rb_ary_splice(ary, beg, len, argv[1]); return argv[1]; } offset = NUM2LONG(argv[0]); fixnum: rb_ary_store(ary, offset, argv[1]); return argv[1]; } /* * call-seq: * array.insert(index, obj...) -> array * * Inserts the given values before the element with the given index * (which may be negative). * * a = %w{ a b c d } * a.insert(2, 99) #=> ["a", "b", 99, "c", "d"] * a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"] */ static VALUE rb_ary_insert(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long pos; if (argc < 1) { rb_raise(rb_eArgError, "wrong number of arguments (at least 1)"); } pos = NUM2LONG(argv[0]); if (pos == -1) { pos = RARRAY(ary)->len; } else if (pos < 0) { pos++; } if (argc == 1) return ary; rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1)); return ary; } /* * call-seq: * array.each {|item| block } -> array * * Calls block once for each element in self, passing that * element as a parameter. * * a = [ "a", "b", "c" ] * a.each {|x| print x, " -- " } * * produces: * * a -- b -- c -- */ VALUE rb_ary_each(ary) VALUE ary; { long i; for (i=0; ilen; i++) { rb_yield(RARRAY(ary)->ptr[i]); } return ary; } /* * call-seq: * array.each_index {|index| block } -> array * * Same as Array#each, but passes the index of the element * instead of the element itself. * * a = [ "a", "b", "c" ] * a.each_index {|x| print x, " -- " } * * produces: * * 0 -- 1 -- 2 -- */ static VALUE rb_ary_each_index(ary) VALUE ary; { long i; for (i=0; ilen; i++) { rb_yield(LONG2NUM(i)); } return ary; } /* * call-seq: * array.reverse_each {|item| block } * * Same as Array#each, but traverses self in reverse * order. * * a = [ "a", "b", "c" ] * a.reverse_each {|x| print x, " " } * * produces: * * c b a */ static VALUE rb_ary_reverse_each(ary) VALUE ary; { long len = RARRAY(ary)->len; while (len--) { rb_yield(RARRAY(ary)->ptr[len]); if (RARRAY(ary)->len < len) { len = RARRAY(ary)->len; } } return ary; } /* * call-seq: * array.length -> int * * Returns the number of elements in self. May be zero. * * [ 1, 2, 3, 4, 5 ].length #=> 5 */ static VALUE rb_ary_length(ary) VALUE ary; { return LONG2NUM(RARRAY(ary)->len); } /* * call-seq: * array.empty? -> true or false * * Returns true if self array contains no elements. * * [].empty? #=> true */ static VALUE rb_ary_empty_p(ary) VALUE ary; { if (RARRAY(ary)->len == 0) return Qtrue; return Qfalse; } VALUE rb_ary_dup(ary) VALUE ary; { VALUE dup = rb_ary_new2(RARRAY(ary)->len); DUPSETUP(dup, ary); MEMCPY(RARRAY(dup)->ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); RARRAY(dup)->len = RARRAY(ary)->len; return dup; } extern VALUE rb_output_fs; static VALUE recursive_join(ary, arg, recur) VALUE ary; VALUE *arg; int recur; { if (recur) { return rb_str_new2("[...]"); } return rb_ary_join(arg[0], arg[1]); } VALUE rb_ary_join(ary, sep) VALUE ary, sep; { long len = 1, i; int taint = Qfalse; VALUE result, tmp; if (RARRAY(ary)->len == 0) return rb_str_new(0, 0); if (OBJ_TAINTED(ary) || OBJ_TAINTED(sep)) taint = Qtrue; for (i=0; ilen; i++) { tmp = rb_check_string_type(RARRAY(ary)->ptr[i]); len += NIL_P(tmp) ? 10 : RSTRING(tmp)->len; } if (!NIL_P(sep)) { StringValue(sep); len += RSTRING(sep)->len * (RARRAY(ary)->len - 1); } result = rb_str_buf_new(len); for (i=0; ilen; i++) { tmp = RARRAY(ary)->ptr[i]; switch (TYPE(tmp)) { case T_STRING: break; case T_ARRAY: { VALUE args[2]; args[0] = tmp; args[1] = sep; tmp = rb_exec_recursive(recursive_join, ary, (VALUE)args); } break; default: tmp = rb_obj_as_string(tmp); } if (i > 0 && !NIL_P(sep)) rb_str_buf_append(result, sep); rb_str_buf_append(result, tmp); if (OBJ_TAINTED(tmp)) taint = Qtrue; } if (taint) OBJ_TAINT(result); return result; } /* * call-seq: * array.join(sep=$,) -> str * * Returns a string created by converting each element of the array to * a string, separated by sep. * * [ "a", "b", "c" ].join #=> "abc" * [ "a", "b", "c" ].join("-") #=> "a-b-c" */ static VALUE rb_ary_join_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE sep; rb_scan_args(argc, argv, "01", &sep); if (NIL_P(sep)) sep = rb_output_fs; return rb_ary_join(ary, sep); } /* * call-seq: * array.to_s -> string * * Returns _self_.join. * * [ "a", "e", "i", "o" ].to_s #=> "aeio" * */ VALUE rb_ary_to_s(ary) VALUE ary; { if (RARRAY(ary)->len == 0) return rb_str_new(0, 0); return rb_ary_join(ary, rb_output_fs); } static VALUE inspect_ary(ary, dummy, recur) VALUE ary; VALUE dummy; int recur; { int tainted = OBJ_TAINTED(ary); long i; VALUE s, str; if (recur) return rb_tainted_str_new2("[...]"); str = rb_str_buf_new2("["); for (i=0; ilen; i++) { s = rb_inspect(RARRAY(ary)->ptr[i]); if (OBJ_TAINTED(s)) tainted = Qtrue; if (i > 0) rb_str_buf_cat2(str, ", "); rb_str_buf_append(str, s); } rb_str_buf_cat2(str, "]"); if (tainted) OBJ_TAINT(str); return str; } /* * call-seq: * array.inspect -> string * * Create a printable version of array. */ static VALUE rb_ary_inspect(ary) VALUE ary; { if (RARRAY(ary)->len == 0) return rb_str_new2("[]"); return rb_exec_recursive(inspect_ary, ary, 0); } /* * call-seq: * array.to_a -> array * * Returns _self_. If called on a subclass of Array, converts * the receiver to an Array object. */ static VALUE rb_ary_to_a(ary) VALUE ary; { if (rb_obj_class(ary) != rb_cArray) { VALUE dup = rb_ary_new2(RARRAY(ary)->len); rb_ary_replace(dup, ary); return dup; } return ary; } /* * call-seq: * array.to_ary -> array * * Returns _self_. */ static VALUE rb_ary_to_ary_m(ary) VALUE ary; { return ary; } VALUE rb_ary_reverse(ary) VALUE ary; { VALUE *p1, *p2; VALUE tmp; rb_ary_modify(ary); if (RARRAY(ary)->len > 1) { p1 = RARRAY(ary)->ptr; p2 = p1 + RARRAY(ary)->len - 1; /* points last item */ while (p1 < p2) { tmp = *p1; *p1++ = *p2; *p2-- = tmp; } } return ary; } /* * call-seq: * array.reverse! -> array * * Reverses _self_ in place. * * a = [ "a", "b", "c" ] * a.reverse! #=> ["c", "b", "a"] * a #=> ["c", "b", "a"] */ static VALUE rb_ary_reverse_bang(ary) VALUE ary; { return rb_ary_reverse(ary); } /* * call-seq: * array.reverse -> an_array * * Returns a new array containing self's elements in reverse order. * * [ "a", "b", "c" ].reverse #=> ["c", "b", "a"] * [ 1 ].reverse #=> [1] */ static VALUE rb_ary_reverse_m(ary) VALUE ary; { return rb_ary_reverse(rb_ary_dup(ary)); } struct ary_sort_data { VALUE ary; VALUE *ptr; long len; }; static void ary_sort_check(data) struct ary_sort_data *data; { if (RARRAY(data->ary)->ptr != data->ptr || RARRAY(data->ary)->len != data->len) { rb_raise(rb_eRuntimeError, "array modified during sort"); } } static int sort_1(a, b, data) VALUE *a, *b; struct ary_sort_data *data; { VALUE retval = rb_yield_values(2, *a, *b); int n; n = rb_cmpint(retval, *a, *b); ary_sort_check(data); return n; } static int sort_2(ap, bp, data) VALUE *ap, *bp; struct ary_sort_data *data; { VALUE retval; VALUE a = *ap, b = *bp; int n; if (FIXNUM_P(a) && FIXNUM_P(b)) { if ((long)a > (long)b) return 1; if ((long)a < (long)b) return -1; return 0; } if (TYPE(a) == T_STRING && TYPE(b) == T_STRING) { return rb_str_cmp(a, b); } retval = rb_funcall(a, id_cmp, 1, b); n = rb_cmpint(retval, a, b); ary_sort_check(data); return n; } static VALUE sort_internal(ary) VALUE ary; { struct ary_sort_data data; data.ary = ary; data.ptr = RARRAY(ary)->ptr; data.len = RARRAY(ary)->len; qsort(RARRAY(ary)->ptr, RARRAY(ary)->len, sizeof(VALUE), rb_block_given_p()?sort_1:sort_2, &data); return ary; } static VALUE sort_unlock(ary) VALUE ary; { FL_UNSET(ary, ARY_TMPLOCK); return ary; } /* * call-seq: * array.sort! -> array * array.sort! {| a,b | block } -> array * * Sorts _self_. Comparisons for * the sort will be done using the <=> operator or using * an optional code block. The block implements a comparison between * a and b, returning -1, 0, or +1. See also * Enumerable#sort_by. * * a = [ "d", "a", "e", "c", "b" ] * a.sort #=> ["a", "b", "c", "d", "e"] * a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"] */ VALUE rb_ary_sort_bang(ary) VALUE ary; { rb_ary_modify(ary); if (RARRAY(ary)->len > 1) { FL_SET(ary, ARY_TMPLOCK); /* prohibit modification during sort */ rb_ensure(sort_internal, ary, sort_unlock, ary); } return ary; } /* * call-seq: * array.sort -> an_array * array.sort {| a,b | block } -> an_array * * Returns a new array created by sorting self. Comparisons for * the sort will be done using the <=> operator or using * an optional code block. The block implements a comparison between * a and b, returning -1, 0, or +1. See also * Enumerable#sort_by. * * a = [ "d", "a", "e", "c", "b" ] * a.sort #=> ["a", "b", "c", "d", "e"] * a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"] */ VALUE rb_ary_sort(ary) VALUE ary; { ary = rb_ary_dup(ary); rb_ary_sort_bang(ary); return ary; } /* * call-seq: * array.collect {|item| block } -> an_array * array.map {|item| block } -> an_array * * Invokes block once for each element of self. Creates a * new array containing the values returned by the block. * See also Enumerable#collect. * * a = [ "a", "b", "c", "d" ] * a.collect {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"] * a #=> ["a", "b", "c", "d"] */ static VALUE rb_ary_collect(ary) VALUE ary; { long i; VALUE collect; if (!rb_block_given_p()) { return rb_ary_new4(RARRAY(ary)->len, RARRAY(ary)->ptr); } collect = rb_ary_new2(RARRAY(ary)->len); for (i = 0; i < RARRAY(ary)->len; i++) { rb_ary_push(collect, rb_yield(RARRAY(ary)->ptr[i])); } return collect; } /* * call-seq: * array.collect! {|item| block } -> array * array.map! {|item| block } -> array * * Invokes the block once for each element of _self_, replacing the * element with the value returned by _block_. * See also Enumerable#collect. * * a = [ "a", "b", "c", "d" ] * a.collect! {|x| x + "!" } * a #=> [ "a!", "b!", "c!", "d!" ] */ static VALUE rb_ary_collect_bang(ary) VALUE ary; { long i; rb_ary_modify(ary); for (i = 0; i < RARRAY(ary)->len; i++) { rb_ary_store(ary, i, rb_yield(RARRAY(ary)->ptr[i])); } return ary; } VALUE rb_get_values_at(obj, olen, argc, argv, func) VALUE obj; long olen; int argc; VALUE *argv; VALUE (*func) _((VALUE,long)); { VALUE result = rb_ary_new2(argc); long beg, len, i, j; for (i=0; i an_array * * Returns an array containing the elements in * _self_ corresponding to the given selector(s). The selectors * may be either integer indices or ranges. * See also Array#select. * * a = %w{ a b c d e f } * a.values_at(1, 3, 5) * a.values_at(1, 3, 5, 7) * a.values_at(-1, -3, -5, -7) * a.values_at(1..3, 2...5) */ static VALUE rb_ary_values_at(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { return rb_get_values_at(ary, RARRAY(ary)->len, argc, argv, rb_ary_entry); } /* * call-seq: * array.select {|item| block } -> an_array * * Invokes the block passing in successive elements from array, * returning an array containing those elements for which the block * returns a true value (equivalent to Enumerable#select). * * a = %w{ a b c d e f } * a.select {|v| v =~ /[aeiou]/} #=> ["a", "e"] */ static VALUE rb_ary_select(ary) VALUE ary; { VALUE result; long i; result = rb_ary_new2(RARRAY(ary)->len); for (i = 0; i < RARRAY(ary)->len; i++) { if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) { rb_ary_push(result, rb_ary_elt(ary, i)); } } return result; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.ceylon000066400000000000000000000025531250413007300265430ustar00rootroot00000000000000import ceylon.language { parseInteger } doc "A top-level function, with multi-line documentation." void topLevel(String? a, Integer b=5, String* seqs) { function nested(String s) { print(s[1..2]); return true; } for (s in seqs.filter((String x) => x.size > 2)) { nested(s); } value uppers = seqs.map((String x) { return x.uppercased; }); String|Null z = a; {Integer+} ints = { 1, 2, 3, 4, 5 }; value numbers = [ 1, #ffff, #ffff_ffff, $10101010, $1010_1010_1010_1010, 123_456_789 ]; value chars = ['a', '\{#ffff}' ]; } shared class Example_1(name, element) satisfies Comparable> given Element satisfies Comparable { shared String name; shared Element element; shared [Integer,String] tuple = [1, "2"]; shared late String lastName; variable Integer cnt = 0; shared Integer count => cnt; assign count { assert(count >= cnt); cnt = count; } shared actual Comparison compare(Example_1 other) { return element <=> other.element; } shared actual String string { return "Example with ``element.string``"; } } Example_1 instance = Example_1 { element = 5; name = "Named args call \{#0060}"; }; object example1 extends Example_1("object", 5) { }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.chai000066400000000000000000000002551250413007300261530ustar00rootroot00000000000000var f = fun(x) { x + 2; } // comment puts(someFunc(2 + 2 - 1 * 5 / 4)); var x = "str"; def dosomething(lhs, rhs) { print("lhs: ${lhs}, rhs: ${rhs}"); } callfunc(`+`, 1, 4); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.clay000066400000000000000000000014151250413007300261760ustar00rootroot00000000000000 /// @section StringLiteralRef record StringLiteralRef ( sizep : Pointer[SizeT], ); /// @section predicates overload ContiguousSequence?(#StringLiteralRef) : Bool = true; [s when StringLiteral?(s)] overload ContiguousSequence?(#Static[s]) : Bool = true; /// @section size, begin, end, index forceinline overload size(a:StringLiteralRef) = a.sizep^; forceinline overload begin(a:StringLiteralRef) : Pointer[Char] = Pointer[Char](a.sizep + 1); forceinline overload end(a:StringLiteralRef) = begin(a) + size(a); [I when Integer?(I)] forceinline overload index(a:StringLiteralRef, i:I) : ByRef[Char] { assert["boundsChecks"](i >= 0 and i < size(a), "StringLiteralRef index out of bounds"); return ref (begin(a) + i)^; } foo() = """ long\tlong story """ pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.cls000066400000000000000000000004761250413007300260350ustar00rootroot00000000000000USING Progress.Lang.*. CLASS Test INHERITS Progress.Sucks: DEFINE PRIVATE VARIABLE cTest AS CHAR NO-UNDO. CONSTRUCTOR PUBLIC Test(): SUPER(). MESSAGE "Why are you punishing yourself by coding in this language?". END CONSTRUCTOR. METHOD PUBLIC LOGICAL Blowup(INPUT iTime AS INT): END. END CLASS. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.cob000066400000000000000000004534021250413007300260200ustar00rootroot00000000000000 IDENTIFICATION DIVISION. PROGRAM-ID. OCic. ***************************************************************** ** This program provides a Textual User Interface (TUI) to the ** ** process of compiling and (optionally) executing an OpenCOBOL** ** program. ** ** ** ** This programs execution syntax is as follows: ** ** ** ** ocic [ ... ] ** ** ** ** Once executed, a display screen will be presented showing ** ** the compilation options that will be used. The user will ** ** have the opportunity to change options, specify new ones ** ** and specify any program execution arguments to be used if ** ** you select the "Execute" option. When you press the Enter ** ** key the program will be compiled. ** ** ** ** The SCREEN SECTION contains an image of the screen. ** ** ** ** The "010-Parse-Args" section in the PROCEDURE DIVISION has ** ** documentation on switches and their function. ** ***************************************************************** ** ** ** AUTHOR: GARY L. CUTLER ** ** CutlerGL@gmail.com ** ** Copyright (C) 2009-2010, Gary L. Cutler, GPL ** ** ** ** DATE-WRITTEN: June 14, 2009 ** ** ** ***************************************************************** ** Note: Depending on which extended DISPLAY handler you're ** ** using (PDCurses, Curses, ...), you may need to un- ** ** comment any source lines tagged with "SCROLL" in cols ** ** 1-6 in order to have error messages scroll properly ** ** in the OCic shell window. ** ***************************************************************** ** DATE CHANGE DESCRIPTION ** ** ====== ==================================================== ** ** GC0609 Don't display compiler messages file if compilation ** ** Is successful. Also don't display messages if the ** ** output file is busy (just put a message on the ** ** screen, leave the OC screen up & let the user fix ** ** the problem & resubmit. ** ** GC0709 When 'EXECUTE' is selected, a 'FILE BUSY' error will ** ** still cause the (old) executable to be launched. ** ** Also, the 'EXTRA SWITCHES' field is being ignored. ** ** Changed the title bar to lowlighted reverse video & ** ** the message area to highlighted reverse-video. ** ** GC0809 Add a SPACE in from of command-line args when ** ** executing users program. Add a SPACE after the ** ** -ftraceall switch when building cobc command. ** ** GC0909 Convert to work on Cygwin/Linux as well as MinGW ** ** GC0310 Virtualized the key codes for S-F1 thru S-F7 as they ** ** differ depending upon whether PDCurses or NCurses is ** ** being used. ** ** GC0410 Introduced the cross-reference and source listing ** ** features. Also fixed a bug in @EXTRA switch proces- ** ** sing where garbage will result if more than the ** ** @EXTRA switch is specified. ** ***************************************************************** ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Bat-File ASSIGN TO Bat-File-Name ORGANIZATION IS LINE SEQUENTIAL. SELECT Cobc-Output ASSIGN TO Cobc-Output-File ORGANIZATION IS LINE SEQUENTIAL. SELECT Source-Code ASSIGN TO File-Name ORGANIZATION IS LINE SEQUENTIAL FILE STATUS IS FSM-Status. DATA DIVISION. FILE SECTION. FD Bat-File. 01 Bat-File-Rec PIC X(2048). FD Cobc-Output. 01 Cobc-Output-Rec PIC X(256). FD Source-Code. 01 Source-Code-Record PIC X(80). WORKING-STORAGE SECTION. COPY screenio. 01 Bat-File-Name PIC X(256). GC0909 01 Cmd PIC X(512). 01 Cobc-Cmd PIC X(256). 01 Cobc-Output-File PIC X(256). 01 Command-Line-Args PIC X(256). 01 Config-File PIC X(12). GC0310 01 Config-Keys. GC0310 05 CK-S-F1 PIC 9(4). GC0310 05 CK-S-F2 PIC 9(4). GC0310 05 CK-S-F3 PIC 9(4). GC0310 05 CK-S-F4 PIC 9(4). GC0310 05 CK-S-F5 PIC 9(4). GC0310 05 CK-S-F6 PIC 9(4). GC0310 05 CK-S-F7 PIC 9(4). GC0909 01 Dir-Char PIC X(1). 01 Dummy PIC X(1). 01 Env-TEMP PIC X(256). 01 File-Name. 05 FN-Char OCCURS 256 TIMES PIC X(1). 01 File-Status-Message. 05 FILLER PIC X(13) VALUE 'Status Code: '. 05 FSM-Status PIC 9(2). 05 FILLER PIC X(11) VALUE ', Meaning: '. 05 FSM-Msg PIC X(25). 01 Flags. 05 F-Compilation-Succeeded PIC X(1). 88 88-Compile-OK VALUE 'Y'. GC0909 88 88-Compile-OK-Warn VALUE 'W'. 88 88-Compile-Failed VALUE 'N'. GC0609 05 F-Complete PIC X(1). GC0609 88 88-Complete VALUE 'Y'. GC0609 88 88-Not-Complete VALUE 'N'. GC0809 05 F-IDENT-DIVISION PIC X(1). GC0809 88 88-1st-Prog-Complete VALUE 'Y'. GC0809 88 88-More-To-1st-Prog VALUE 'N'. 05 F-LINKAGE-SECTION PIC X(1). 88 88-Compile-As-Subpgm VALUE 'Y'. 88 88-Compile-As-Mainpgm VALUE 'N'. 05 F-No-Switch-Changes PIC X(1). 88 88-No-Switch-Changes VALUE 'Y'. 88 88-Switch-Changes VALUE 'N'. GC0709 05 F-Output-File-Busy PIC X(1). GC0709 88 88-Output-File-Busy VALUE 'Y'. GC0709 88 88-Output-File-Avail VALUE 'N'. GC0809 05 F-Source-Record-Type PIC X(1). GC0809 88 88-Source-Rec-Linkage VALUE 'L'. GC0809 88 88-Source-Rec-Ident VALUE 'I'. GC0809 88 88-Source-Rec-IgnoCOB-COLOR-RED VALUE ' '. 05 F-Switch-Error PIC X(1). 88 88-Switch-Is-Bad VALUE 'Y'. 88 88-Switch-Is-Good VALUE 'N'. GC0909 01 Horizontal-Line PIC X(80). GC0909 01 I USAGE BINARY-LONG. 01 J USAGE BINARY-LONG. GC0909 01 MS USAGE BINARY-LONG. GC0909 01 ML USAGE BINARY-LONG. 01 OC-Compiled PIC XXXX/XX/XXBXX/XX. GC0909 01 OS-Type USAGE BINARY-LONG. GC0909 88 OS-Unknown VALUE 0. GC0909 88 OS-Windows VALUE 1. GC0909 88 OS-Cygwin VALUE 2. GC0909 88 OS-UNIX VALUE 3. GC0909 01 OS-Type-Literal PIC X(7). 01 Output-Message PIC X(80). 01 Path-Delimiter PIC X(1). 01 Prog-Folder PIC X(256). 01 Prog-Extension PIC X(30). 01 Prog-File-Name PIC X(40). 01 Prog-Name PIC X(31). 78 Selection-Char VALUE '>'. 01 Switch-Display. 05 SD-Switch-And-Value PIC X(19). 05 FILLER PIC X(1). 05 SD-Description PIC X(60). 01 Switch-Keyword PIC X(12). GC0410 88 Switch-Is-CONFIG VALUE '@CONFIG', '@C'. GC0410 88 Switch-Is-DEBUG VALUE '@DEBUG', '@D'. GC0410 88 Switch-Is-DLL VALUE '@DLL'. GC0410 88 Switch-Is-EXECUTE VALUE '@EXECUTE', '@E'. GC0410 88 Switch-Is-EXTRA VALUE '@EXTRA', '@EX'. GC0410 88 Switch-Is-NOTRUNC VALUE '@NOTRUNC', '@N'. GC0410 88 Switch-Is-TRACE VALUE '@TRACE', '@T'. GC0410 88 Switch-Is-SOURCE VALUE '@SOURCE', '@S'. GC0410 88 Switch-Is-XREF VALUE '@XREF', '@X'. 01 Switch-Keyword-And-Value PIC X(256). 01 Switch-Value. 05 SV-1 PIC X(1). 05 FILLER PIC X(255). 01 Switch-Value-Alt REDEFINES Switch-Value PIC X(256). 88 Valid-Config-Filename VALUE 'BS2000', 'COBOL85', 'COBOL2002', 'DEFAULT', 'IBM', 'MF', 'MVS'. 01 Switches. 05 S-ARGS PIC X(75) VALUE SPACES. 05 S-CfgS. 10 S-Cfg-BS2000 PIC X(1) VALUE ' '. 10 S-Cfg-COBOL85 PIC X(1) VALUE ' '. 10 S-Cfg-COBOL2002 PIC X(1) VALUE ' '. 10 S-Cfg-DEFAULT PIC X(1) VALUE Selection-Char. 10 S-Cfg-IBM PIC X(1) VALUE ' '. 10 S-Cfg-MF PIC X(1) VALUE ' '. 10 S-Cfg-MVS PIC X(1) VALUE ' '. 05 S-EXTRA PIC X(75) VALUE SPACES. 05 S-Yes-No-Switches. 10 S-DEBUG PIC X(1) VALUE 'N'. 10 S-DLL PIC X(1) VALUE 'N'. GC0410 10 S-XREF PIC X(1) VALUE 'N'. GC0410 10 S-SOURCE PIC X(1) VALUE 'N'. 10 S-EXECUTE PIC X(1) VALUE 'N'. 10 S-NOTRUNC PIC X(1) VALUE 'Y'. 10 S-SUBROUTINE PIC X(1) VALUE 'A'. 10 S-TRACE PIC X(1) VALUE 'N'. 10 S-TRACEALL PIC X(1) VALUE 'N'. 01 Tally USAGE BINARY-LONG. SCREEN SECTION. *> *> Here is the layout of the OCic screen. *> *> Note that this program can utilize the traditional PC line-drawing characters, *> if they are available. *> *> If this program is run on Windows, it must run with codepage 437 activated to *> display the line-drawing characters. With a native Windows build or a *> Windows/MinGW build, one could use the command "chcp 437" to set that codepage *> for display within a Windows console window (that should be the default, though). *> With a Windows/Cygwin build, set the environment variable CYGWIN to a value of *> "codepage:oem" (this cannot be done from within the program though - you will *> have to use the "Computer/Advanced System Settings/Environment Variables" (Vista or *> Windows 7) function to define the variable. XP Users: use "My Computer/Properties/ *> Advanced/Environment Variables". *> *> To use OCic without the line-drawing characters, comment-out the first set of *> 78 "LD" items and uncomment the second. *> *> The following sample screen layout shows how the screen looks with line-drawing *> characters disabled. *> *>=================================================================================== *> OCic (2010/04/02 11:36) - OpenCOBOL V1.1 Interactive Compilation Windows 01 *> +-----------------------------------------------------------------------------+ 02 *> | Program: OCic F-Key: Select Opt | 03 *> | Folder: E:\OpenCOBOL\Samples Enter: Compile | 04 *> | Filename: OCic.cbl Esc: Quit | 05 *> +-----------------------------------------------------------------------------+ 06 *> On/Off Switches: Configuration: 07 *> +---------------------------------------------------------+-------------------+ 08 *> | F1 Compile debug lines F8 Produce source listing | S-F1 BS2000 | 09 *> | F2 Always make DLLs F9 Produce xref listing | S-F2 COBOL85 | 10 *> | F3 Pgm is a SUBROUTINE | S-F3 COBOL2002 | 11 *> | F4 Execute if compile OK | S-F4 > Default | 12 *> | F5 > No COMP/BINARY trunc | S-F5 IBM | 13 *> | F6 Trace procedures | S-F6 MicroFocus | 14 *> | F7 Trace proc + stmnts | S-F7 MVS | 15 *> +---------------------------------------------------------+-------------------+ 16 *> Additional "cobc" Switches (if any): 17 *> +-----------------------------------------------------------------------------+ 18 *> | -O2________________________________________________________________________ | 19 *> +-----------------------------------------------------------------------------+ 20 *> Program Execution Arguments (if any): 21 *> +-----------------------------------------------------------------------------+ 22 *> | ___________________________________________________________________________ | 23 *> +-----------------------------------------------------------------------------+ 24 *> OCic Copyright (C) 2009-2010, Gary L. Cutler, GPL 25 *>=================================================================================== *>12345678901234567890123456789012345678901234567890123456789012345678901234567890 *> 1 2 3 4 5 6 7 8 *> *> USE THESE CHARS FOR LINE-DRAWING IF YOU HAVE ACCESS TO PC-DOS CODEPAGE 437: *> 78 LD-UL-Corner VALUE X"DA". 78 LD-LL-Corner VALUE X"C0". 78 LD-UR-Corner VALUE X"BF". 78 LD-LR-Corner VALUE X"D9". 78 LD-Upper-T VALUE X"C2". 78 LD-Lower-T VALUE X"C1". 78 LD-Horiz-Line VALUE X"C4". 78 LD-Vert-Line VALUE X"B3". *> *> USE THESE CHARS FOR LINE-DRAWING IF YOU DO NOT HAVE ACCESS TO PC-DOS CODEPAGE 437: *> *> 78 LD-UL-Corner VALUE '+'. *> 78 LD-LL-Corner VALUE '+'. *> 78 LD-UR-Corner VALUE '+'. *> 78 LD-LR-Corner VALUE '+'. *> 78 LD-Upper-T VALUE '+'. *> 78 LD-Lower-T VALUE '+'. *> 78 LD-Horiz-Line VALUE '-'. *> 78 LD-Vert-Line VALUE '|'. *> 01 Blank-Screen LINE 1 COLUMN 1 BLANK SCREEN. 01 Switches-Screen BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-WHITE AUTO. *> *> GENERAL SCREEN FRAMEWORK *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-BLUE HIGHLIGHT. 05 LINE 02 COL 02 VALUE LD-UL-Corner. 05 PIC X(77) FROM Horizontal-Line. 05 COL 80 VALUE LD-UR-Corner. 05 LINE 03 COL 02 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 04 COL 02 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 05 COL 02 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 06 COL 02 VALUE LD-LL-Corner. 05 PIC X(77) FROM Horizontal-Line. 05 COL 80 VALUE LD-LR-Corner. 05 LINE 08 COL 02 VALUE LD-UL-Corner. 05 PIC X(57) FROM Horizontal-Line. 05 COL 60 VALUE LD-Upper-T. 05 PIC X(19) FROM Horizontal-Line. 05 COL 80 VALUE LD-UR-Corner. 05 LINE 09 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 10 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 11 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 12 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 13 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 14 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 15 COL 02 VALUE LD-Vert-Line. 05 COL 60 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 16 COL 02 VALUE LD-LL-Corner. 05 PIC X(57) FROM Horizontal-Line. 05 COL 60 VALUE LD-Lower-T. 05 PIC X(19) FROM Horizontal-Line. 05 COL 80 VALUE LD-LR-Corner. 05 LINE 18 COL 02 VALUE LD-UL-Corner. 05 PIC X(77) FROM Horizontal-Line. 05 COL 80 VALUE LD-UR-Corner. 05 LINE 19 COL 02 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 20 COL 02 VALUE LD-LL-Corner. 05 PIC X(77) FROM Horizontal-Line. 05 COL 80 VALUE LD-LR-Corner. 05 LINE 22 COL 02 VALUE LD-UL-Corner. 05 PIC X(77) FROM Horizontal-Line. 05 COL 80 VALUE LD-UR-Corner. 05 LINE 23 COL 02 VALUE LD-Vert-Line. 05 COL 80 VALUE LD-Vert-Line. 05 LINE 24 COL 02 VALUE LD-LL-Corner. 05 PIC X(77) FROM Horizontal-Line. 05 COL 80 VALUE LD-LR-Corner. *> *> TOP AND BOTTOM LINES *> 03 BACKGROUND-COLOR COB-COLOR-BLUE BLINK FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT. GC0410 05 LINE 01 COL 01 VALUE ' OCic ('. GC0410 05 PIC X(16) FROM OC-Compiled. GC0410 05 VALUE ') OpenCOBOL V1.1 06FEB2009 ' & GC0410 'Interactive Compilation '. GC0410 05 LINE 25 COL 01 PIC X(81) FROM Output-Message. *> *> LABELS *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-CYAN HIGHLIGHT. 05 LINE 07 COL 04 VALUE 'On/Off Switches:'. 05 COL 62 VALUE 'Configuration:'. 05 LINE 17 COL 04 VALUE 'Additional "cobc" Switches (if any - '):'. 05 LINE 21 COL 04 VALUE 'Program Execution Arguments (if an - 'y):'. *> *> TOP SECTION BACKGROUND *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-CYAN LOWLIGHT. 05 LINE 03 COL 04 VALUE 'Program: '. 05 LINE 04 COL 04 VALUE 'Folder: '. 05 LINE 05 COL 04 VALUE 'Filename: '. 05 LINE 03 COL 62 VALUE 'F-Key: Select Opt'. 05 LINE 04 COL 62 VALUE 'Enter: Compile '. 05 LINE 05 COL 62 VALUE 'Esc: Quit '. *> *> TOP SECTION PROGRAM INFO *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT. 05 LINE 03 COL 14 PIC X(47) FROM Prog-Name. 05 LINE 04 COL 14 PIC X(47) FROM Prog-Folder. 05 LINE 05 COL 14 PIC X(47) FROM Prog-File-Name. *> *> MIDDLE LEFT SECTION F-KEYS *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT. 05 LINE 09 COL 04 VALUE 'F1'. 05 LINE 10 COL 04 VALUE 'F2'. 05 LINE 11 COL 04 VALUE 'F3'. 05 LINE 12 COL 04 VALUE 'F4'. 05 LINE 13 COL 04 VALUE 'F5'. 05 LINE 14 COL 04 VALUE 'F6'. 05 LINE 15 COL 04 VALUE 'F7'. 05 LINE 09 COL 32 VALUE 'F8'. 05 LINE 10 COL 32 VALUE 'F9'. *> *> MIDDLE LEFT SECTION SWITCHES *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-RED HIGHLIGHT. 05 LINE 09 COL 07 PIC X(1) FROM S-DEBUG. 05 LINE 10 COL 07 PIC X(1) FROM S-DLL. 05 LINE 11 COL 07 PIC X(1) FROM S-SUBROUTINE. 05 LINE 12 COL 07 PIC X(1) FROM S-EXECUTE. 05 LINE 13 COL 07 PIC X(1) FROM S-NOTRUNC. 05 LINE 14 COL 07 PIC X(1) FROM S-TRACE. 05 LINE 15 COL 07 PIC X(1) FROM S-TRACEALL. 05 LINE 09 COL 35 PIC X(1) FROM S-SOURCE. 05 LINE 10 COL 35 PIC X(1) FROM S-XREF. *> *> MIDDLE LEFT SECTION BACKGROUND *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-CYAN LOWLIGHT. 05 LINE 09 COL 09 VALUE 'Compile debug lines '. 05 LINE 10 COL 09 VALUE 'Always make DLLs '. 05 LINE 11 COL 09 VALUE 'Pgm is a SUBROUTINE '. 05 LINE 12 COL 09 VALUE 'Execute if compile OK '. 05 LINE 13 COL 09 VALUE 'No COMP/BINARY trunc '. 05 LINE 14 COL 09 VALUE 'Trace procedures '. 05 LINE 15 COL 09 VALUE 'Trace proc + stmnts '. 05 LINE 09 COL 37 VALUE 'Produce source listing'. 05 LINE 10 COL 37 VALUE 'Produce xref listing '. *> *> MIDDLE RIGHT SECTION F-KEYS *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT. 05 LINE 09 COL 62 VALUE 'S-F1'. 05 LINE 10 COL 62 VALUE 'S-F2'. 05 LINE 11 COL 62 VALUE 'S-F3'. 05 LINE 12 COL 62 VALUE 'S-F4'. 05 LINE 13 COL 62 VALUE 'S-F5'. 05 LINE 14 COL 62 VALUE 'S-F6'. 05 LINE 15 COL 62 VALUE 'S-F7'. *> *> MIDDLE RIGHT SECTION SWITCHES *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-RED HIGHLIGHT. 05 LINE 09 COL 67 PIC X(1) FROM S-Cfg-BS2000. 05 LINE 10 COL 67 PIC X(1) FROM S-Cfg-COBOL85. 05 LINE 11 COL 67 PIC X(1) FROM S-Cfg-COBOL2002. 05 LINE 12 COL 67 PIC X(1) FROM S-Cfg-DEFAULT. 05 LINE 13 COL 67 PIC X(1) FROM S-Cfg-IBM. 05 LINE 14 COL 67 PIC X(1) FROM S-Cfg-MF. 05 LINE 15 COL 67 PIC X(1) FROM S-Cfg-MVS. *> *> MIDDLE RIGHT SECTION BACKGROUND *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-CYAN LOWLIGHT. 05 LINE 09 COL 69 VALUE 'BS2000 '. 05 LINE 10 COL 69 VALUE 'COBOL85 '. 05 LINE 11 COL 69 VALUE 'COBOL2002 '. 05 LINE 12 COL 69 VALUE 'Default '. 05 LINE 13 COL 69 VALUE 'IBM '. 05 LINE 14 COL 69 VALUE 'MicroFocus'. 05 LINE 15 COL 69 VALUE 'MVS '. *> *> FREE-FORM OPTIONS FIELDS *> 03 BACKGROUND-COLOR COB-COLOR-BLACK FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT. 05 LINE 19 COL 04 PIC X(75) USING S-EXTRA. 05 LINE 23 COL 04 PIC X(75) USING S-ARGS. / PROCEDURE DIVISION. ***************************************************************** ** Legend to procedure names: ** ** ** ** 00x-xxx All MAIN driver procedures ** ** 0xx-xxx All GLOBAL UTILITY procedures ** ** 1xx-xxx All INITIALIZATION procedures ** ** 2xx-xxx All CORE PROCESSING procedures ** ** 9xx-xxx All TERMINATION procedures ** ***************************************************************** DECLARATIVES. 000-File-Error SECTION. USE AFTER STANDARD ERROR PROCEDURE ON Source-Code. 000-Handle-Error. COPY FileStat-Msgs REPLACING STATUS BY FSM-Status MSG BY FSM-Msg. MOVE SPACES TO Output-Message IF FSM-Status = 35 DISPLAY 'File not found: "' TRIM(File-Name,TRAILING) '"' END-DISPLAY ELSE DISPLAY 'Error accessing file: "' TRIM(File-Name,TRAILING) '"' END-DISPLAY END-IF GOBACK . END DECLARATIVES. / 000-Main SECTION. PERFORM 100-Initialization GC0609 SET 88-Not-Complete TO TRUE GC0609 PERFORM UNTIL 88-Complete GC0609 PERFORM 200-Let-User-Set-Switches GC0609 PERFORM 210-Run-Compiler GC0410 IF (88-Compile-OK OR 88-Compile-OK-Warn) GC0410 AND (S-XREF NOT = SPACE OR S-SOURCE NOT = SPACE) GC0410 PERFORM 220-Make-Listing GC0410 END-IF GC0709 IF (S-EXECUTE NOT = SPACES) GC0709 AND (88-Output-File-Avail) GC0609 PERFORM 230-Run-Program GC0609 END-IF GC0609 END-PERFORM . 009-Done. PERFORM 900-Terminate . * -- Control will NOT return / 010-Parse-Args SECTION. ***************************************************************** ** Process a sequence of KEYWORD=VALUE items. These are items ** ** specified on the command-line to provide the initial ** ** options shown selected on the screen. When integrating ** ** OCic into an edirot or framework, include these switches on ** ** the ocic.exe command the editor/framework executes. Any ** ** underlined choice is the default value for that switch. ** ** ** ** @CONFIG=BS2000|COBOL85|COBOL2002|DEFAULT|IBM|MF|MVS ** ** ======= ** ** This switch specifies the default cobc compiler configura- ** ** tion file to be used ** ** ** ** @DEBUG=YES|NO ** ** == ** ** This switch specifies whether (YES) or not (NO) debugging ** ** lines (those with a "D" in column 7) will be compiled. ** ** ** ** @DLL=YES|NO ** ** == ** ** Use this switch to force ALL compiled programs to be built ** ** as DLLs ("@DLL=YES"). When main programs are built as DLLs ** ** they must be executed using the cobcrun utility. When ** ** "@DLL=NO" is in effect, main programs are generated as ** ** actual "exe" files and only subprograms will be generated ** ** as DLLs. ** ** ** ** @EXECUTE=YES|NO ** ** == ** ** This switch specifies whether ("@EXECUTE=YES") or not ** ** ("@EXECUTE=NO") the program will be executed after it is ** ** successfully compiled. ** ** ** ** @EXTRA=extra cobc argument(s) ** ** ** ** This switch allows you to specify additional cobc arguments ** ** that aren't managed by the other OC switches. If used, ** ** this must be the last switch specified on the command line, ** ** as everything that follows the "=" will be placed on the ** ** cobc command generated by OC. ** ** ** ** @NOTRUNC=YES|NO ** ** === ** ** This switch specifies whether (YES) or not (NO) the sup- ** ** pression of binary field truncation will occur. If a PIC ** ** 99 COMP field (one byte of storage), for example, is given ** ** the value 123, it may have its value truncated to 23 when ** ** DISPLAYed. Regardless of the NOTRUNC setting, internally ** ** the full precision of the field (allowing a maximum value ** ** of 255) will be preserved. Even though truncation - if it ** ** does occur - would appear to have a minimal disruption on ** ** program operation, it has a significant effect on program ** ** run-time speed. ** ** ** ** @TRACE=YES|NO|ALL ** ** == ** ** This switch controls whether or not code will be added to ** ** the object program to produce execution-time logic traces. ** ** A specification of "@TRACE=NO" means no such code will be ** ** produced. By specifying "@TRACE=YES", code will be genera- ** ** ted to display procedure names as they are entered. A ** ** "@TRACE=ALL" specification will generate not only procedure ** ** traces (as "@TRACE=YES" would) but also statement-level ** ** traces too! All trace output is written to STDERR, so ** ** adding a "2>file" to the execution of the program will pipe ** ** the trace output to a file. You may find it valuable to ** ** add your own DISPLAY statements to the debugging output via ** ** "DISPLAY xx UPON SYSERR" The SYSERR device corresponds to ** ** the Windows or UNIX STDERR device and will therefore honor ** ** any "2>file" placed at the end of your program's execution. ** ** Add a "D" in column 7 and you can control the generation or ** ** ignoring of these DISPLAY statements via the "@DEBUG" ** ** switch. ** ** ** GC0410** @SOURCE=YES|NO ** GC0410** == ** GC0410** Use this switch to produce a source listing of the program, ** GC0410** PROVIDED it compiles without errors. ** ** ** GC0410** @XREF=YES|NO ** GC0410** == ** GC0410** Use this switch to produce a cross-reference listing of the ** GC0410** program, PROVIDED it compiles without errors. ** ***************************************************************** 011-Init. MOVE 1 TO I . 012-Extract-Kwd-And-Value. PERFORM UNTIL I NOT < LENGTH(Command-Line-Args) MOVE I TO J UNSTRING Command-Line-Args DELIMITED BY ALL SPACES INTO Switch-Keyword-And-Value WITH POINTER I END-UNSTRING IF Switch-Keyword-And-Value NOT = SPACES UNSTRING Switch-Keyword-And-Value DELIMITED BY '=' INTO Switch-Keyword, Switch-Value END-UNSTRING PERFORM 030-Process-Keyword END-IF END-PERFORM . 019-Done. EXIT. ***************************************************************** ** Since this program uses the SCREEN SECTION, it cannot do ** ** conventional console DISPLAY operations. This routine ** ** (which, I admit, is like using an H-bomb to hunt rabbits) ** ** will submit an "ECHO" command to the system to simulate a ** ** DISPLAY. ** ***************************************************************** 021-Build-And-Issue-Command. DISPLAY Output-Message END-DISPLAY . 029-Done. EXIT. / 030-Process-Keyword SECTION. ***************************************************************** ** Process a single KEYWORD=VALUE item. ** ***************************************************************** 031-Init. MOVE UPPER-CASE(Switch-Keyword) TO Switch-Keyword SET 88-Switch-Is-Good TO TRUE . 032-Process. EVALUATE TRUE WHEN Switch-Is-EXTRA GC0410 MOVE J TO I UNSTRING Command-Line-Args DELIMITED BY '=' INTO Dummy, S-EXTRA GC0410 WITH POINTER I GC0410 END-UNSTRING MOVE LENGTH(Command-Line-Args) TO I WHEN Switch-Is-CONFIG MOVE 'CONFIG' TO Switch-Keyword MOVE UPPER-CASE(Switch-Value) TO Switch-Value EVALUATE Switch-Value WHEN 'BS2000' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-BS2000 WHEN 'COBOL85' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-COBOL85 WHEN 'COBOL2002' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-COBOL2002 WHEN 'DEFAULT' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-DEFAULT WHEN 'IBM' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-IBM WHEN 'MF' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-MF WHEN 'MVS' MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-MVS WHEN OTHER MOVE 'An invalid /CONFIG switch value ' & 'was specified on the command line ' & '- ignored' TO Output-Message END-EVALUATE WHEN Switch-Is-DEBUG MOVE 'DEBUG' TO Switch-Keyword MOVE UPPER-CASE(Switch-Value) TO Switch-Value PERFORM 040-Process-Yes-No-Value IF 88-Switch-Is-Good MOVE SV-1 TO S-DEBUG END-IF GC0410 WHEN Switch-Is-DLL GC0410 MOVE 'DLL' TO Switch-Keyword GC0410 MOVE UPPER-CASE(Switch-Value) GC0410 TO Switch-Value GC0410 PERFORM 040-Process-Yes-No-Value GC0410 IF 88-Switch-Is-Good GC0410 MOVE SV-1 TO S-DLL GC0410 END-IF WHEN Switch-Is-EXECUTE MOVE 'EXECUTE' TO Switch-Keyword MOVE UPPER-CASE(Switch-Value) TO Switch-Value PERFORM 040-Process-Yes-No-Value IF 88-Switch-Is-Good MOVE SV-1 TO S-EXECUTE END-IF WHEN Switch-Is-NOTRUNC MOVE 'NOTRUNC' TO Switch-Keyword MOVE UPPER-CASE(Switch-Value) TO Switch-Value PERFORM 040-Process-Yes-No-Value IF 88-Switch-Is-Good MOVE SV-1 TO S-NOTRUNC END-IF GC0410 WHEN Switch-Is-SOURCE GC0410 MOVE 'SOURCE' TO Switch-Keyword GC0410 MOVE UPPER-CASE(Switch-Value) GC0410 TO Switch-Value GC0410 PERFORM 050-Process-Yes-No-All GC0410 IF 88-Switch-Is-Good GC0410 MOVE SV-1 TO S-SOURCE GC0410 END-IF WHEN Switch-Is-TRACE MOVE 'TRACE' TO Switch-Keyword MOVE UPPER-CASE(Switch-Value) TO Switch-Value PERFORM 050-Process-Yes-No-All IF 88-Switch-Is-Good MOVE SV-1 TO S-TRACE END-IF GC0410 WHEN Switch-Is-XREF GC0410 MOVE 'XREF' TO Switch-Keyword GC0410 MOVE UPPER-CASE(Switch-Value) GC0410 TO Switch-Value GC0410 PERFORM 050-Process-Yes-No-All GC0410 IF 88-Switch-Is-Good GC0410 MOVE SV-1 TO S-XREF GC0410 END-IF WHEN OTHER MOVE SPACES TO Output-Message STRING '"' TRIM(Switch-Keyword) '" is not a valid switch ' & '- ignored' DELIMITED SIZE INTO Output-Message END-STRING SET 88-Switch-Is-Bad TO TRUE END-EVALUATE . 039-Done. EXIT. / 040-Process-Yes-No-Value SECTION. ***************************************************************** ** Process a switch value of YES or NO ** ***************************************************************** 042-Process. EVALUATE SV-1 WHEN 'Y' MOVE 'YES' TO Switch-Value WHEN 'N' MOVE 'NO' To Switch-Value WHEN OTHER MOVE SPACES TO Output-Message STRING '*ERROR: "' TRIM(Switch-Value) '" is not a valid value for the "' TRIM(Switch-Keyword) '" switch' DELIMITED SPACES INTO Output-Message END-STRING SET 88-Switch-Is-Bad TO TRUE END-EVALUATE . 049-Done. EXIT. / 050-Process-Yes-No-All SECTION. ***************************************************************** ** Process a switch value of YES, NO or ALL ** ***************************************************************** 052-Process. IF SV-1 = 'A' MOVE 'ALL' TO Switch-Value ELSE PERFORM 040-Process-Yes-No-Value END-IF . 059-Done. EXIT. / 060-Process-Yes-No-Auto SECTION. ***************************************************************** ** Process a switch value of YES, NO or AUTO ** ***************************************************************** 061-Init. IF SV-1 = 'A' PERFORM 070-Find-LINKAGE-SECTION IF 88-Compile-As-Subpgm MOVE 'Y' TO Switch-Value ELSE MOVE 'N' TO Switch-Value END-IF ELSE PERFORM 040-Process-Yes-No-Value END-IF . / 070-Find-LINKAGE-SECTION SECTION. ***************************************************************** ** Determine if the program being compiled is a MAIN program ** ***************************************************************** 071-Init. OPEN INPUT Source-Code SET 88-Compile-As-Mainpgm TO TRUE SET 88-More-To-1st-Prog TO TRUE PERFORM UNTIL 88-1st-Prog-Complete READ Source-Code AT END CLOSE Source-Code EXIT SECTION END-READ CALL 'CHECKSOURCE' USING Source-Code-Record F-Source-Record-Type END-CALL IF 88-Source-Rec-Ident SET 88-1st-Prog-Complete TO TRUE END-IF END-PERFORM . 072-Process-Source. SET 88-Source-Rec-IgnoCOB-COLOR-RED TO TRUE PERFORM UNTIL 88-Source-Rec-Linkage OR 88-Source-Rec-Ident READ Source-Code AT END CLOSE Source-Code EXIT SECTION END-READ CALL 'CHECKSOURCE' USING Source-Code-Record F-Source-Record-Type END-CALL END-PERFORM CLOSE Source-Code IF 88-Source-Rec-Linkage SET 88-Compile-As-Subpgm TO TRUE END-IF . 079-Done. EXIT. / 100-Initialization SECTION. ***************************************************************** ** Perform all program-wide initialization operations ** ***************************************************************** GC0909 101-Determine-OS-Type. GC0909 CALL 'GETOSTYPE' GC0909 END-CALL GC0909 MOVE RETURN-CODE TO OS-Type GC0909 EVALUATE TRUE GC0909 WHEN OS-Unknown GC0909 MOVE '\' TO Dir-Char GC0909 MOVE 'Unknown' TO OS-Type-Literal GC0310 MOVE COB-SCR-F11 TO CK-S-F1 GC0310 MOVE COB-SCR-F12 TO CK-S-F2 GC0310 MOVE COB-SCR-F13 TO CK-S-F3 GC0310 MOVE COB-SCR-F14 TO CK-S-F4 GC0310 MOVE COB-SCR-F15 TO CK-S-F5 GC0310 MOVE COB-SCR-F16 TO CK-S-F6 GC0310 MOVE COB-SCR-F17 TO CK-S-F7 GC0909 WHEN OS-Windows GC0909 MOVE '\' TO Dir-Char GC0909 MOVE 'Windows' TO OS-Type-Literal GC0310 MOVE COB-SCR-F13 TO CK-S-F1 GC0310 MOVE COB-SCR-F14 TO CK-S-F2 GC0310 MOVE COB-SCR-F15 TO CK-S-F3 GC0310 MOVE COB-SCR-F16 TO CK-S-F4 GC0310 MOVE COB-SCR-F17 TO CK-S-F5 GC0310 MOVE COB-SCR-F18 TO CK-S-F6 GC0310 MOVE COB-SCR-F19 TO CK-S-F7 GC0909 WHEN OS-Cygwin GC0909 MOVE '/' TO Dir-Char GC0410 MOVE 'Cygwin' TO OS-Type-Literal GC0310 MOVE COB-SCR-F11 TO CK-S-F1 GC0310 MOVE COB-SCR-F12 TO CK-S-F2 GC0310 MOVE COB-SCR-F13 TO CK-S-F3 GC0310 MOVE COB-SCR-F14 TO CK-S-F4 GC0310 MOVE COB-SCR-F15 TO CK-S-F5 GC0310 MOVE COB-SCR-F16 TO CK-S-F6 GC0310 MOVE COB-SCR-F17 TO CK-S-F7 GC0909 WHEN OS-UNIX GC0909 MOVE '/' TO Dir-Char GC0410 MOVE 'UNIX ' TO OS-Type-Literal GC0310 MOVE COB-SCR-F11 TO CK-S-F1 GC0310 MOVE COB-SCR-F12 TO CK-S-F2 GC0310 MOVE COB-SCR-F13 TO CK-S-F3 GC0310 MOVE COB-SCR-F14 TO CK-S-F4 GC0310 MOVE COB-SCR-F15 TO CK-S-F5 GC0310 MOVE COB-SCR-F16 TO CK-S-F6 GC0310 MOVE COB-SCR-F17 TO CK-S-F7 GC0909 END-EVALUATE GC0909 . 102-Set-Environment-Vars. SET ENVIRONMENT 'COB_SCREEN_EXCEPTIONS' TO 'Y' SET ENVIRONMENT 'COB_SCREEN_ESC' TO 'Y' . 103-Generate-Cobc-Output-Fn. ACCEPT Env-TEMP FROM ENVIRONMENT "TEMP" END-ACCEPT MOVE SPACES TO Cobc-Output-File STRING TRIM(Env-TEMP,TRAILING) GC0909 Dir-Char GC0909 'OC-Messages.TXT' DELIMITED SIZE INTO Cobc-Output-File END-STRING . 104-Generate-Banner-Line-Info. MOVE WHEN-COMPILED (1:12) TO OC-Compiled INSPECT OC-Compiled REPLACING ALL '/' BY ':' AFTER INITIAL SPACE . 105-Establish-Switch-Settings. ACCEPT Command-Line-Args FROM COMMAND-LINE END-ACCEPT MOVE TRIM(Command-Line-Args, Leading) TO Command-Line-Args MOVE 0 TO Tally GC0410 INSPECT Command-Line-Args TALLYING Tally FOR ALL '@' IF Tally = 0 MOVE Command-Line-Args TO File-Name MOVE SPACES TO Command-Line-Args ELSE GC0410 UNSTRING Command-Line-Args DELIMITED BY '@' INTO File-Name, Dummy END-UNSTRING INSPECT Command-Line-Args GC0410 REPLACING FIRST '@' BY LOW-VALUES UNSTRING Command-Line-Args DELIMITED BY LOW-VALUES INTO Dummy, Cmd END-UNSTRING MOVE SPACES TO Command-Line-Args GC0410 STRING '@' Cmd DELIMITED SIZE INTO Command-Line-Args END-STRING END-IF IF File-Name = SPACES DISPLAY 'No program filename was specified' END-DISPLAY PERFORM 900-Terminate END-IF PERFORM 010-Parse-Args IF S-SUBROUTINE = 'A' MOVE 'S' TO Switch-Keyword MOVE 'A' TO Switch-Value PERFORM 070-Find-LINKAGE-SECTION IF 88-Compile-As-Subpgm MOVE 'Y' TO S-SUBROUTINE ELSE MOVE 'N' TO S-SUBROUTINE END-IF END-IF INSPECT S-Yes-No-Switches REPLACING ALL 'Y' BY Selection-Char INSPECT S-Yes-No-Switches REPLACING ALL 'N' BY ' ' . 106-Determine-Folder-Path. Move 256 TO I GC0909 IF OS-Cygwin AND File-Name (2:1) = ':' GC0909 MOVE '\' TO Dir-Char GC0909 END-IF PERFORM UNTIL I = 0 OR FN-Char (I) = Dir-Char SUBTRACT 1 FROM I END-PERFORM IF I = 0 MOVE SPACES TO Prog-Folder MOVE File-Name TO Prog-File-Name ELSE MOVE '*' TO FN-Char (I) UNSTRING File-Name DELIMITED BY '*' INTO Prog-Folder Prog-File-Name END-UNSTRING MOVE Dir-Char TO FN-Char (I) END-IF UNSTRING Prog-File-Name DELIMITED BY '.' INTO Prog-Name, Prog-Extension END-UNSTRING IF Prog-Folder = SPACES ACCEPT Prog-Folder FROM ENVIRONMENT 'CD' END-ACCEPT GC0909 ELSE GC0909 CALL "CBL_CHANGE_DIR" GC0909 USING TRIM(Prog-Folder,TRAILING) GC0909 END-CALL END-IF GC0909 IF OS-Cygwin AND File-Name (2:1) = ':' GC0909 MOVE '/' TO Dir-Char GC0909 END-IF . GC0909 107-Other. GC0909 MOVE ALL LD-Horiz-Line TO Horizontal-Line. GC0410 MOVE CONCATENATE(' OCic for ', GC0410 TRIM(OS-Type-Literal,Trailing), GC0410 ' Copyright (C) 2009-2010, Gary L. Cutler,', GC0410 ' GPL') GC0410 TO Output-Message. GC0909 . GC0909 109-Done. EXIT. / 200-Let-User-Set-Switches SECTION. ***************************************************************** ** Show the user the current switch settings and allow them to ** ** be changed. ** ***************************************************************** 201-Init. SET 88-Switch-Changes TO TRUE . 202-Show-And-Change-Switches. PERFORM UNTIL 88-No-Switch-Changes ACCEPT Switches-Screen END-ACCEPT IF COB-CRT-STATUS > 0 EVALUATE COB-CRT-STATUS WHEN COB-SCR-F1 IF S-DEBUG = SPACE MOVE Selection-Char TO S-DEBUG ELSE MOVE ' ' TO S-DEBUG END-IF WHEN COB-SCR-F2 IF S-DLL = SPACE MOVE Selection-Char TO S-DLL ELSE MOVE ' ' TO S-DLL END-IF WHEN COB-SCR-F3 IF S-SUBROUTINE = SPACE MOVE Selection-Char TO S-SUBROUTINE MOVE ' ' TO S-EXECUTE ELSE MOVE ' ' TO S-SUBROUTINE END-IF WHEN COB-SCR-F4 IF S-EXECUTE = SPACE AND S-SUBROUTINE = SPACE MOVE Selection-Char TO S-EXECUTE ELSE MOVE ' ' TO S-EXECUTE END-IF WHEN COB-SCR-F5 IF S-NOTRUNC = SPACE MOVE Selection-Char TO S-NOTRUNC ELSE MOVE ' ' TO S-NOTRUNC END-IF WHEN COB-SCR-F6 IF S-TRACE = SPACE MOVE Selection-Char TO S-TRACE MOVE ' ' TO S-TRACEALL ELSE MOVE ' ' TO S-TRACE END-IF WHEN COB-SCR-F7 IF S-TRACEALL = SPACE MOVE Selection-Char TO S-TRACEALL MOVE ' ' TO S-TRACE ELSE MOVE ' ' TO S-TRACEALL END-IF GC0410 WHEN COB-SCR-F8 GC0410 IF S-SOURCE = SPACE GC0410 MOVE Selection-Char TO S-SOURCE GC0410 ELSE GC0410 MOVE ' ' TO S-SOURCE GC0410 END-IF GC0410 WHEN COB-SCR-F9 GC0410 IF S-XREF = SPACE GC0410 MOVE Selection-Char TO S-XREF GC0410 ELSE GC0410 MOVE ' ' TO S-XREF GC0410 END-IF WHEN COB-SCR-ESC PERFORM 900-Terminate GC0310 WHEN CK-S-F1 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-BS2000 GC0310 WHEN CK-S-F2 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-COBOL85 GC0310 WHEN CK-S-F3 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-COBOL2002 GC0310 WHEN CK-S-F4 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-DEFAULT GC0310 WHEN CK-S-F5 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-IBM GC0310 WHEN CK-S-F6 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-MF GC0310 WHEN CK-S-F7 MOVE SPACES TO S-CfgS MOVE Selection-Char TO S-Cfg-MVS WHEN OTHER MOVE 'An unsupported key was pressed' TO Output-Message END-EVALUATE ELSE SET 88-No-Switch-Changes TO TRUE END-IF END-PERFORM . 209-Done. EXIT. / 210-Run-Compiler SECTION. ***************************************************************** ** Run the compiler using the switch settings we've prepared. ** ***************************************************************** 211-Init. MOVE SPACES TO Cmd Cobc-Cmd Output-Message DISPLAY Switches-Screen END-DISPLAY MOVE 1 TO I EVALUATE TRUE WHEN S-Cfg-BS2000 NOT = SPACES MOVE 'bs2000' TO Config-File WHEN S-Cfg-COBOL85 NOT = SPACES MOVE 'cobol85' TO Config-File WHEN S-Cfg-COBOL2002 NOT = SPACES MOVE 'cobol2002' TO Config-File WHEN S-Cfg-IBM NOT = SPACES MOVE 'ibm' TO Config-File WHEN S-Cfg-MF NOT = SPACES MOVE 'mf' TO Config-File WHEN S-Cfg-MVS NOT = SPACES MOVE 'mvs' TO Config-File WHEN OTHER MOVE 'default' TO Config-File END-EVALUATE . 212-Build-Compile-Command. GC0909 MOVE SPACES TO Cobc-Cmd GC0909 STRING 'cobc -std=' GC0909 TRIM(Config-File,TRAILING) GC0909 ' ' GC0909 INTO Cobc-Cmd GC0909 WITH POINTER I GC0909 END-STRING IF S-SUBROUTINE NOT = ' ' STRING '-m ' DELIMITED SIZE INTO Cobc-Cmd WITH POINTER I END-STRING ELSE STRING '-x ' DELIMITED SIZE INTO Cobc-Cmd WITH POINTER I END-STRING END-IF IF S-DEBUG NOT = ' ' STRING '-fdebugging-line ' DELIMITED SIZE INTO Cobc-Cmd WITH POINTER I END-STRING END-IF IF S-NOTRUNC NOT = ' ' STRING '-fnotrunc ' DELIMITED SIZE INTO Cobc-Cmd WITH POINTER I END-STRING END-IF IF S-TRACEALL NOT = ' ' GC0809 STRING '-ftraceall ' DELIMITED SIZE INTO Cobc-Cmd WITH POINTER I END-STRING END-IF IF S-TRACE NOT = ' ' STRING '-ftrace ' DELIMITED SIZE INTO Cobc-Cmd WITH POINTER I END-STRING END-IF GC0709 IF S-EXTRA > SPACES GC0709 STRING ' ' GC0709 TRIM(S-Extra,TRAILING) GC0709 ' ' GC0709 DELIMITED SIZE INTO Cobc-Cmd GC0709 WITH POINTER I GC0709 END-STRING GC0709 END-IF GC0909 STRING TRIM(Prog-File-Name,TRAILING) GC0909 DELIMITED SIZE INTO Cobc-Cmd GC0909 WITH POINTER I GC0909 END-STRING . 213-Run-Compiler. GC0410 MOVE ' Compiling...' TO Output-Message GC0410 DISPLAY GC0410 Switches-Screen GC0410 END-DISPLAY GC0609 SET 88-Output-File-Avail TO TRUE MOVE SPACES TO Cmd STRING TRIM(Cobc-Cmd,TRAILING) ' 2>' TRIM(Cobc-Output-File,TRAILING) DELIMITED SIZE INTO Cmd END-STRING CALL 'SYSTEM' USING TRIM(Cmd,TRAILING) END-CALL GC0909 IF RETURN-CODE = 0 GC0909 SET 88-Compile-OK TO TRUE GC0909 ELSE GC0909 SET 88-Compile-Failed TO TRUE GC0909 END-IF GC0909 IF 88-Compile-OK GC0909 OPEN INPUT Cobc-Output GC0909 READ Cobc-Output GC0909 AT END GC0909 CONTINUE GC0909 NOT AT END GC0909 SET 88-Compile-OK-Warn TO TRUE GC0909 END-READ GC0909 CLOSE Cobc-Output GC0909 END-IF GC0909 MOVE SPACES TO Output-Message IF 88-Compile-OK GC0909 MOVE ' Compilation Was Successful' TO Output-Message GC0909 DISPLAY GC0909 Switches-Screen GC0909 END-DISPLAY GC0909 CALL 'C$SLEEP' GC0909 USING 2 GC0909 END-CALL GC0909 MOVE SPACES TO Output-Message GC0609 SET 88-Complete TO TRUE ELSE GC0909 DISPLAY GC0909 Blank-Screen GC0909 END-DISPLAY GC0909 IF 88-Compile-OK-Warn GC0909 DISPLAY ' Compilation was successful, but ' & GC0909 'warnings were generated:' SCROLL* AT LINE 24 COLUMN 1 SCROLL* WITH SCROLL UP 1 LINE GC0909 END-DISPLAY GC0909 ELSE GC0909 DISPLAY 'Compilation Failed:' SCROLL* AT LINE 24 COLUMN 1 SCROLL* WITH SCROLL UP 1 LINE GC0909 END-DISPLAY GC0909 END-IF GC0609 SET 88-Compile-Failed TO TRUE GC0609 SET 88-Complete TO TRUE GC0909 DISPLAY ' ' SCROLL* AT LINE 24 COLUMN 1 SCROLL* WITH SCROLL UP 1 LINE GC0909 END-DISPLAY GC0909 OPEN INPUT Cobc-Output GC0909 PERFORM FOREVER GC0909 READ Cobc-Output AT END GC0909 EXIT PERFORM GC0909 END-READ GC0909 DISPLAY TRIM(Cobc-Output-Rec,TRAILING) SCROLL* AT LINE 24 COLUMN 1 SCROLL* WITH SCROLL UP 1 LINE GC0909 END-DISPLAY GC0909 END-PERFORM GC0909 CLOSE Cobc-Output GC0909 DISPLAY ' ' SCROLL* AT LINE 24 COLUMN 1 SCROLL* WITH SCROLL UP 2 LINES GC0909 END-DISPLAY GC0909 DISPLAY 'Press ENTER to close:' SCROLL* AT LINE 24 COLUMN 1 SCROLL* WITH SCROLL UP 1 LINE GC0909 END-DISPLAY GC0909 ACCEPT Dummy GC0909 FROM CONSOLE GC0909 END-ACCEPT GC0909 DISPLAY GC0909 Blank-Screen GC0909 END-DISPLAY END-IF . 219-Done. IF 88-Compile-Failed PERFORM 900-Terminate END-IF . / GC0410 220-Make-Listing SECTION. GC0410***************************************************************** GC0410** Generate a source and/or xref listing using XREF ** GC0410***************************************************************** GC0410 GC0410 221-Init. GC0410 MOVE ' Generating cross-reference listing...' GC0410 TO Output-Message GC0410 DISPLAY GC0410 Switches-Screen GC0410 END-DISPLAY GC0410 CALL "CBL_DELETE_FILE" GC0410 USING CONCATENATE(TRIM(Prog-Name,Trailing),".lst") GC0410 END-CALL GC0410 MOVE 0 TO RETURN-CODE GC0410 . GC0410 GC0410 213-Run-OCXref. GC0410 MOVE SPACES TO Output-Message GC0410 CALL 'LISTING' GC0410 USING S-SOURCE GC0410 S-XREF GC0410 File-Name GC0410 ON EXCEPTION GC0410 MOVE ' LISTING module is not available' GC0410 TO Output-Message GC0410 MOVE 1 TO RETURN-CODE GC0410 END-CALL GC0410 IF RETURN-CODE = 0 GC0410 MOVE ' Listing generated' GC0410 TO Output-Message GC0410 IF OS-Windows OR OS-Cygwin GC0410 MOVE SPACES TO Cmd GC0410 STRING GC0410 'cmd /c ' GC0410 TRIM(Prog-Name,TRAILING) GC0410 '.lst' GC0410 DELIMITED SIZE INTO Cmd GC0410 END-STRING GC0410 CALL 'SYSTEM' GC0410 USING TRIM(Cmd,TRAILING) GC0410 END-CALL GC0410 END-IF GC0410 ELSE GC0410 IF Output-Message = SPACES GC0410 MOVE ' Listing generation failed' GC0410 TO Output-Message GC0410 END-IF GC0410 END-IF GC0410 DISPLAY GC0410 Switches-Screen GC0410 END-DISPLAY GC0410 CALL 'C$SLEEP' GC0410 USING 2 GC0410 END-CALL GC0410 . / 230-Run-Program SECTION. ***************************************************************** ** Run the compiled program ** ***************************************************************** 232-Build-Command. GC0909 MOVE SPACES TO Cmd GC0909 MOVE 1 TO I IF S-SUBROUTINE NOT = ' ' OR S-DLL NOT = ' ' STRING 'cobcrun ' DELIMITED SIZE INTO Cmd WITH POINTER I END-STRING END-IF IF Prog-Folder NOT = SPACES GC0909 IF OS-Cygwin AND Prog-Folder (2:1) = ':' GC0909 STRING '/cygdrive/' GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 STRING LOWER-CASE(Prog-Folder (1:1)) GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 PERFORM VARYING J FROM 3 BY 1 GC0909 UNTIL J > LENGTH(TRIM(Prog-Folder)) GC0909 IF Prog-Folder (J:1) = '\' GC0909 STRING '/' GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 ELSE GC0909 STRING Prog-Folder (J:1) GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 END-IF GC0909 END-PERFORM GC0909 ELSE GC0410 STRING '"' TRIM(Prog-Folder,TRAILING) GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 END-IF GC0909 STRING Dir-Char GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 ELSE GC0909 IF OS-Cygwin OR OS-UNIX GC0909 STRING './' GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 END-IF END-IF GC0909 STRING TRIM(Prog-Name,TRAILING) GC0909 INTO Cmd GC0909 WITH POINTER I GC0909 END-STRING GC0909 IF S-SUBROUTINE = ' ' GC0909 AND S-DLL NOT = ' ' GC0909 STRING '.exe' DELIMITED SIZE INTO Cmd WITH POINTER I END-STRING END-IF IF S-ARGS NOT = SPACES GC0809 STRING ' ' TRIM(S-ARGS,TRAILING) INTO Cmd WITH POINTER I END-STRING END-IF IF OS-Unknown OR OS-Windows GC0410 STRING '"&&pause' INTO Cmd WITH POINTER I END-STRING ELSE STRING ';echo "Press ENTER to close...";read' INTO Cmd WITH POINTER I END-STRING END-IF . 233-Run-Program. GC0909 DISPLAY GC0909 Blank-Screen GC0909 END-DISPLAY CALL 'SYSTEM' USING TRIM(Cmd,TRAILING) END-CALL PERFORM 900-Terminate . 239-Done. EXIT. / 900-Terminate SECTION. ***************************************************************** ** Display a message and halt the program ** ***************************************************************** 901-Display-Message. GC0909 IF Output-Message > SPACES GC0909 DISPLAY GC0909 Switches-Screen GC0909 END-DISPLAY GC0909 CALL 'C$SLEEP' GC0909 USING 2 GC0909 END-CALL GC0909 END-IF DISPLAY Blank-Screen END-DISPLAY . 909-Done. GOBACK . END PROGRAM OCic. IDENTIFICATION DIVISION. PROGRAM-ID. GETOSTYPE. ***************************************************************** ** This subprogram determine the OS type the program is run- ** ** ning under, passing that result back in RETURN-CODE as fol- ** ** lows: ** ** ** ** 0: Cannot be determined ** ** 1: Native Windows or Windows/MinGW ** ** 2: Cygwin ** ** 3: UNIX/Linux/MacOS ** ***************************************************************** ** DATE CHANGE DESCRIPTION ** ** ====== ==================================================== ** ** GC0909 Initial coding. ** ***************************************************************** ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. DATA DIVISION. WORKING-STORAGE SECTION. 01 Env-Path PIC X(1024). 01 Tally USAGE BINARY-LONG. PROCEDURE DIVISION. 000-Main SECTION. 010-Get-TEMP-Var. MOVE SPACES TO Env-Path ACCEPT Env-Path FROM ENVIRONMENT "PATH" ON EXCEPTION MOVE 0 TO RETURN-CODE GOBACK END-ACCEPT IF Env-Path = SPACES MOVE 0 TO RETURN-CODE ELSE MOVE 0 TO Tally INSPECT Env-Path TALLYING Tally FOR ALL ";" IF Tally = 0 *> Must be some form of UNIX MOVE 0 TO Tally INSPECT Env-Path TALLYING TALLY FOR ALL "/cygdrive/" IF Tally = 0 *> UNIX/MacOS MOVE 3 TO RETURN-CODE ELSE *> Cygwin MOVE 2 TO RETURN-CODE END-IF ELSE *> Assume Windows[/MinGW] MOVE 1 TO RETURN-CODE END-IF END-IF GOBACK . END PROGRAM GETOSTYPE. IDENTIFICATION DIVISION. PROGRAM-ID. CHECKSOURCE. ***************************************************************** ** This subprogram will scan a line of source code it is given ** ** looking for "LINKAGE SECTION" or "IDENTIFICATION DIVISION". ** ** ** ** ****NOTE**** ****NOTE**** ****NOTE**** ****NOTE*** ** ** ** ** These two strings must be found IN THEIR ENTIRETY within ** ** the 1st 80 columns of program source records, and cannot ** ** follow either a "*>" sequence OR a "*" in col 7. ** ***************************************************************** ** DATE CHANGE DESCRIPTION ** ** ====== ==================================================== ** ** GC0809 Initial coding. ** ***************************************************************** ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. DATA DIVISION. WORKING-STORAGE SECTION. 01 Compressed-Src. 05 CS-Char OCCURS 80 TIMES PIC X(1). 01 Flags. 05 F-Found-SPACE PIC X(1). 88 88-Skipping-SPACE VALUE 'Y'. 88 88-Not-Skipping-SPACE VALUE 'N'. 01 I USAGE BINARY-CHAR. 01 J USAGE BINARY-CHAR. LINKAGE SECTION. 01 Argument-1. 02 A1-Char OCCURS 80 TIMES PIC X(1). 01 Argument-2 PIC X(1). 88 88-A2-LINKAGE-SECTION VALUE 'L'. 88 88-A2-IDENTIFICATION-DIVISION VALUE 'I'. 88 88-A2-Nothing-Special VALUE ' '. PROCEDURE DIVISION USING Argument-1, Argument-2. 000-Main SECTION. 010-Initialize. SET 88-A2-Nothing-Special TO TRUE IF A1-Char (7) = '*' GOBACK END-IF . 020-Compress-Multiple-SPACES. SET 88-Not-Skipping-SPACE TO TRUE MOVE 0 TO J MOVE SPACES TO Compressed-Src PERFORM VARYING I FROM 1 BY 1 UNTIL I > 80 IF A1-Char (I) = SPACE IF 88-Not-Skipping-SPACE ADD 1 TO J MOVE UPPER-CASE(A1-Char (I)) TO CS-Char (J) SET 88-Skipping-SPACE TO TRUE END-IF ELSE SET 88-Not-Skipping-SPACE TO TRUE ADD 1 TO J MOVE A1-Char (I) TO CS-Char (J) END-IF END-PERFORM . 030-Scan-Compressed-Src. PERFORM VARYING I FROM 1 BY 1 UNTIL I > 66 EVALUATE TRUE WHEN CS-Char (I) = '*' IF Compressed-Src (I : 2) = '*>' GOBACK END-IF WHEN (CS-Char (I) = 'L') AND (I < 66) IF Compressed-Src (I : 15) = 'LINKAGE SECTION' SET 88-A2-LINKAGE-SECTION TO TRUE GOBACK END-IF WHEN (CS-Char (I) = 'I') AND (I < 58) IF Compressed-Src (I : 23) = 'IDENTIFICATION ' & 'DIVISION' SET 88-A2-IDENTIFICATION-DIVISION TO TRUE GOBACK END-IF END-EVALUATE END-PERFORM . 099-Never-Found-Either-One. GOBACK . END PROGRAM CHECKSOURCE. IDENTIFICATION DIVISION. PROGRAM-ID. LISTING. ***************************************************************** ** This subprogram generates a cross-reference listing of an ** ** OpenCOBOL program. ** ** ** ** Linkage: CALL "LISTING" USING ** ** ** ** ** ** ** ** Where: ** ** is a PIC X(1) flag indicating ** ** whether or not a source listing ** ** should be produced (space=NO, ** ** non-space=yes) ** ** is a PIC X(1) flag indicating ** ** whether or not an xref listing ** ** should be produced (space=NO, ** ** non-space=yes) ** ** is the [path]filename of the ** ** program being listed and/or ** ** xreffed in a PIC X(256) form. ** ***************************************************************** ** ** ** AUTHOR: GARY L. CUTLER ** ** CutlerGL@gmail.com ** ** Copyright (C) 2010, Gary L. Cutler, GPL ** ** ** ** DATE-WRITTEN: April 1, 2010 ** ** ** ***************************************************************** ** DATE CHANGE DESCRIPTION ** ** ====== ==================================================== ** ** GC0410 Initial coding ** ** GC0710 Handle duplicate data names (i.e. "CORRESPONDING" or ** ** qualified items) better; ignore "END PROGRAM" recs ** ** so program name doesn't appear in listing. ** ***************************************************************** ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Expand-Code ASSIGN TO Expanded-Src-Filename ORGANIZATION IS LINE SEQUENTIAL. SELECT Report-File ASSIGN TO Report-Filename ORGANIZATION IS LINE SEQUENTIAL. SELECT Sort-File ASSIGN TO DISK. SELECT Source-Code ASSIGN TO Src-Filename ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD Expand-Code. 01 Expand-Code-Rec. 05 ECR-1 PIC X. 05 ECR-2-256 PIC X(256). 01 Expand-Code-Rec-Alt. 05 ECR-1-128 PIC X(128). 05 ECR-129-256 PIC X(128). FD Report-File. 01 Report-Rec PIC X(135). SD Sort-File. 01 Sort-Rec. 05 SR-Prog-ID PIC X(15). 05 SR-Token-UC PIC X(32). 05 SR-Token PIC X(32). 05 SR-Section PIC X(15). 05 SR-Line-No-Def PIC 9(6). 05 SR-Reference. 10 SR-Line-No-Ref PIC 9(6). 10 SR-Ref-Flag PIC X(1). FD Source-Code. 01 Source-Code-Rec. GC0410 05 SCR-1-128. GC0410 10 FILLER PIC X(6). GC0410 10 SCR-7 PIC X(1). GC0410 10 FILLER PIC X(121). 05 SCR-129-256 PIC X(128). WORKING-STORAGE SECTION. 78 Line-Nos-Per-Rec VALUE 8. 01 Cmd PIC X(256). 01 Delim PIC X(2). 01 Detail-Line-S. 05 DLS-Line-No PIC ZZZZZ9. 05 FILLER PIC X(1). 05 DLS-Statement PIC X(128). 01 Detail-Line-X. 05 DLX-Prog-ID PIC X(15). 05 FILLER PIC X(1). 05 DLX-Token PIC X(32). 05 FILLER PIC X(1). 05 DLX-Line-No-Def PIC ZZZZZ9. 05 FILLER PIC X(1). 05 DLX-Section PIC X(15). 05 FILLER PIC X(1). 05 DLX-Reference OCCURS Line-Nos-Per-Rec TIMES. 10 DLX-Line-No-Ref PIC ZZZZZ9. 10 DLX-Ref-Flag PIC X(1). 10 FILLER PIC X(1). 01 Dummy PIC X(1). 01 Env-TEMP PIC X(256). 01 Expanded-Src-Filename PIC X(256). 01 Filename PIC X(256). 01 Flags. GC0710 05 F-Duplicate PIC X(1). 05 F-First-Record PIC X(1). 05 F-In-Which-Pgm PIC X(1). 88 In-Main-Module VALUE 'M'. 88 In-Copybook VALUE 'C'. 05 F-Last-Token-Ended-Sent PIC X(1). 05 F-Processing-PICTURE PIC X(1). 05 F-Token-Ended-Sentence PIC X(1). GC0710 05 F-Verb-Has-Been-Found PIC X(1). 01 Group-Indicators. 05 GI-Prog-ID PIC X(15). 05 GI-Token PIC X(32). 01 Heading-1S. 05 FILLER PIC X(125) VALUE "OpenCOBOL 1.1 06FEB2009 Source Listing - " & "OCic Copyright (C) 2009-2010, Gary L. Cutler, GPL". 05 H1S-Date PIC 9999/99/99. 01 Heading-1X. 05 FILLER PIC X(125) VALUE "OpenCOBOL 1.1 06FEB2009 Cross-Reference Listing - " & "OCic Copyright (C) 2009-2010, Gary L. Cutler, GPL". 05 H1X-Date PIC 9999/99/99. 01 Heading-2 PIC X(135). 01 Heading-4S PIC X(16) VALUE "Line Statement". 01 Heading-4X PIC X(96) VALUE "PROGRAM-ID Identifier/Register/Function Defn Wher - "e Defined References (* = Updated)". 01 Heading-5S PIC X(135) VALUE "====== ===================================================== - "============================================================ - "===============". 01 Heading-5X PIC X(135) VALUE "=============== ================================ ====== ==== - "=========== ================================================ - "===============". 01 Held-Reference PIC X(100). 01 I USAGE BINARY-LONG. 01 J USAGE BINARY-LONG. 01 Lines-Left USAGE BINARY-LONG. 01 Lines-Per-Page USAGE BINARY-LONG. 01 Lines-Per-Page-ENV PIC X(256). 01 Num-UserNames USAGE BINARY-LONG. 01 PIC-X10 PIC X(10). 01 PIC-X32 PIC X(32). 01 PIC-X256 PIC X(256). 01 Program-Path PIC X(256). 01 Report-Filename PIC X(256). 01 Reserved-Words. 05 FILLER PIC X(33) VALUE "IABS". 05 FILLER PIC X(33) VALUE "VACCEPT". 05 FILLER PIC X(33) VALUE " ACCESS". 05 FILLER PIC X(33) VALUE "IACOS". 05 FILLER PIC X(33) VALUE " ACTIVE-CLASS". 05 FILLER PIC X(33) VALUE "VADD". 05 FILLER PIC X(33) VALUE " ADDRESS". 05 FILLER PIC X(33) VALUE " ADVANCING". 05 FILLER PIC X(33) VALUE "KAFTER". 05 FILLER PIC X(33) VALUE " ALIGNED". 05 FILLER PIC X(33) VALUE " ALL". 05 FILLER PIC X(33) VALUE "VALLOCATE". 05 FILLER PIC X(33) VALUE " ALPHABET". 05 FILLER PIC X(33) VALUE " ALPHABETIC". 05 FILLER PIC X(33) VALUE " ALPHABETIC-LOWER". 05 FILLER PIC X(33) VALUE " ALPHABETIC-UPPER". 05 FILLER PIC X(33) VALUE " ALPHANUMERIC". 05 FILLER PIC X(33) VALUE " ALPHANUMERIC-EDITED". 05 FILLER PIC X(33) VALUE " ALSO". 05 FILLER PIC X(33) VALUE "VALTER". 05 FILLER PIC X(33) VALUE " ALTERNATE". 05 FILLER PIC X(33) VALUE " AND". 05 FILLER PIC X(33) VALUE "IANNUITY". 05 FILLER PIC X(33) VALUE " ANY". 05 FILLER PIC X(33) VALUE " ANYCASE". 05 FILLER PIC X(33) VALUE " ARE". 05 FILLER PIC X(33) VALUE " AREA". 05 FILLER PIC X(33) VALUE " AREAS". 05 FILLER PIC X(33) VALUE " ARGUMENT-NUMBER". 05 FILLER PIC X(33) VALUE " ARGUMENT-VALUE". 05 FILLER PIC X(33) VALUE " AS". 05 FILLER PIC X(33) VALUE " ASCENDING". 05 FILLER PIC X(33) VALUE "IASIN". 05 FILLER PIC X(33) VALUE " ASSIGN". 05 FILLER PIC X(33) VALUE " AT". 05 FILLER PIC X(33) VALUE "IATAN". 05 FILLER PIC X(33) VALUE " AUTHOR". 05 FILLER PIC X(33) VALUE " AUTO". 05 FILLER PIC X(33) VALUE " AUTO-SKIP". 05 FILLER PIC X(33) VALUE " AUTOMATIC". 05 FILLER PIC X(33) VALUE " AUTOTERMINATE". 05 FILLER PIC X(33) VALUE " BACKGROUND-COLOR". 05 FILLER PIC X(33) VALUE " BASED". 05 FILLER PIC X(33) VALUE " BEEP". 05 FILLER PIC X(33) VALUE " BEFORE". 05 FILLER PIC X(33) VALUE " BELL". 05 FILLER PIC X(33) VALUE " BINARY". 05 FILLER PIC X(33) VALUE " BINARY-C-LONG". 05 FILLER PIC X(33) VALUE " BINARY-CHAR". 05 FILLER PIC X(33) VALUE " BINARY-DOUBLE". 05 FILLER PIC X(33) VALUE " BINARY-LONG". 05 FILLER PIC X(33) VALUE " BINARY-SHORT". 05 FILLER PIC X(33) VALUE " BIT". 05 FILLER PIC X(33) VALUE " BLANK". 05 FILLER PIC X(33) VALUE " BLINK". 05 FILLER PIC X(33) VALUE " BLOCK". 05 FILLER PIC X(33) VALUE " BOOLEAN". 05 FILLER PIC X(33) VALUE " BOTTOM". 05 FILLER PIC X(33) VALUE "YBY". 05 FILLER PIC X(33) VALUE "IBYTE-LENGTH". 05 FILLER PIC X(33) VALUE "MC01". 05 FILLER PIC X(33) VALUE "MC02". 05 FILLER PIC X(33) VALUE "MC03". 05 FILLER PIC X(33) VALUE "MC04". 05 FILLER PIC X(33) VALUE "MC05". 05 FILLER PIC X(33) VALUE "MC06". 05 FILLER PIC X(33) VALUE "MC07". 05 FILLER PIC X(33) VALUE "MC08". 05 FILLER PIC X(33) VALUE "MC09". 05 FILLER PIC X(33) VALUE "MC10". 05 FILLER PIC X(33) VALUE "MC11". 05 FILLER PIC X(33) VALUE "MC12". 05 FILLER PIC X(33) VALUE "VCALL". 05 FILLER PIC X(33) VALUE "VCANCEL". 05 FILLER PIC X(33) VALUE " CF". 05 FILLER PIC X(33) VALUE " CH". 05 FILLER PIC X(33) VALUE " CHAINING". 05 FILLER PIC X(33) VALUE "ICHAR". 05 FILLER PIC X(33) VALUE " CHARACTER". 05 FILLER PIC X(33) VALUE " CHARACTERS". 05 FILLER PIC X(33) VALUE " CLASS". 05 FILLER PIC X(33) VALUE " CLASS-ID". 05 FILLER PIC X(33) VALUE "VCLOSE". 05 FILLER PIC X(33) VALUE "ICOB-CRT-STATUS". 05 FILLER PIC X(33) VALUE " CODE". 05 FILLER PIC X(33) VALUE " CODE-SET". 05 FILLER PIC X(33) VALUE " COL". 05 FILLER PIC X(33) VALUE " COLLATING". 05 FILLER PIC X(33) VALUE " COLS". 05 FILLER PIC X(33) VALUE " COLUMN". 05 FILLER PIC X(33) VALUE " COLUMNS". 05 FILLER PIC X(33) VALUE "ICOMBINED-DATETIME". 05 FILLER PIC X(33) VALUE " COMMA". 05 FILLER PIC X(33) VALUE " COMMAND-LINE". 05 FILLER PIC X(33) VALUE "VCOMMIT". 05 FILLER PIC X(33) VALUE " COMMON". 05 FILLER PIC X(33) VALUE " COMP". 05 FILLER PIC X(33) VALUE " COMP-1". 05 FILLER PIC X(33) VALUE " COMP-2". 05 FILLER PIC X(33) VALUE " COMP-3". 05 FILLER PIC X(33) VALUE " COMP-4". 05 FILLER PIC X(33) VALUE " COMP-5". 05 FILLER PIC X(33) VALUE " COMP-X". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-1". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-2". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-3". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-4". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-5". 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-X". 05 FILLER PIC X(33) VALUE "VCOMPUTE". 05 FILLER PIC X(33) VALUE "ICONCATENATE". 05 FILLER PIC X(33) VALUE " CONDITION". 05 FILLER PIC X(33) VALUE "KCONFIGURATION". 05 FILLER PIC X(33) VALUE "MCONSOLE". 05 FILLER PIC X(33) VALUE " CONSTANT". 05 FILLER PIC X(33) VALUE " CONTAINS". 05 FILLER PIC X(33) VALUE " CONTENT". 05 FILLER PIC X(33) VALUE "VCONTINUE". 05 FILLER PIC X(33) VALUE " CONTROL". 05 FILLER PIC X(33) VALUE " CONTROLS". 05 FILLER PIC X(33) VALUE "KCONVERTING". 05 FILLER PIC X(33) VALUE " COPY". 05 FILLER PIC X(33) VALUE " CORR". 05 FILLER PIC X(33) VALUE " CORRESPONDING". 05 FILLER PIC X(33) VALUE "ICOS". 05 FILLER PIC X(33) VALUE "KCOUNT". 05 FILLER PIC X(33) VALUE " CRT". 05 FILLER PIC X(33) VALUE " CURRENCY". 05 FILLER PIC X(33) VALUE "ICURRENT-DATE". 05 FILLER PIC X(33) VALUE " CURSOR". 05 FILLER PIC X(33) VALUE " CYCLE". 05 FILLER PIC X(33) VALUE "KDATA". 05 FILLER PIC X(33) VALUE " DATA-POINTER". 05 FILLER PIC X(33) VALUE " DATE". 05 FILLER PIC X(33) VALUE " DATE-COMPILED". 05 FILLER PIC X(33) VALUE " DATE-MODIFIED". 05 FILLER PIC X(33) VALUE "IDATE-OF-INTEGER". 05 FILLER PIC X(33) VALUE "IDATE-TO-YYYYMMDD". 05 FILLER PIC X(33) VALUE " DATE-WRITTEN". 05 FILLER PIC X(33) VALUE " DAY". 05 FILLER PIC X(33) VALUE "IDAY-OF-INTEGER". 05 FILLER PIC X(33) VALUE " DAY-OF-WEEK". 05 FILLER PIC X(33) VALUE "IDAY-TO-YYYYDDD". 05 FILLER PIC X(33) VALUE " DE". 05 FILLER PIC X(33) VALUE " DEBUGGING". 05 FILLER PIC X(33) VALUE " DECIMAL-POINT". 05 FILLER PIC X(33) VALUE " DECLARATIVES". 05 FILLER PIC X(33) VALUE " DEFAULT". 05 FILLER PIC X(33) VALUE "VDELETE". 05 FILLER PIC X(33) VALUE " DELIMITED". 05 FILLER PIC X(33) VALUE "KDELIMITER". 05 FILLER PIC X(33) VALUE " DEPENDING". 05 FILLER PIC X(33) VALUE " DESCENDING". 05 FILLER PIC X(33) VALUE " DESTINATION". 05 FILLER PIC X(33) VALUE " DETAIL". 05 FILLER PIC X(33) VALUE " DISABLE". 05 FILLER PIC X(33) VALUE " DISK". 05 FILLER PIC X(33) VALUE "VDISPLAY". 05 FILLER PIC X(33) VALUE "VDIVIDE". 05 FILLER PIC X(33) VALUE "KDIVISION". 05 FILLER PIC X(33) VALUE "KDOWN". 05 FILLER PIC X(33) VALUE " DUPLICATES". 05 FILLER PIC X(33) VALUE " DYNAMIC". 05 FILLER PIC X(33) VALUE "IE". 05 FILLER PIC X(33) VALUE " EBCDIC". 05 FILLER PIC X(33) VALUE " EC". 05 FILLER PIC X(33) VALUE "VELSE". GC0710 05 FILLER PIC X(33) VALUE "KEND". 05 FILLER PIC X(33) VALUE " END-ACCEPT". 05 FILLER PIC X(33) VALUE " END-ADD". 05 FILLER PIC X(33) VALUE " END-CALL". 05 FILLER PIC X(33) VALUE " END-COMPUTE". 05 FILLER PIC X(33) VALUE " END-DELETE". 05 FILLER PIC X(33) VALUE " END-DISPLAY". 05 FILLER PIC X(33) VALUE " END-DIVIDE". 05 FILLER PIC X(33) VALUE " END-EVALUATE". 05 FILLER PIC X(33) VALUE " END-IF". 05 FILLER PIC X(33) VALUE " END-MULTIPLY". 05 FILLER PIC X(33) VALUE " END-OF-PAGE". 05 FILLER PIC X(33) VALUE " END-PERFORM". 05 FILLER PIC X(33) VALUE " END-READ". 05 FILLER PIC X(33) VALUE " END-RETURN". 05 FILLER PIC X(33) VALUE " END-REWRITE". 05 FILLER PIC X(33) VALUE " END-SEARCH". 05 FILLER PIC X(33) VALUE " END-START". 05 FILLER PIC X(33) VALUE " END-STRING". 05 FILLER PIC X(33) VALUE " END-SUBTRACT". 05 FILLER PIC X(33) VALUE " END-UNSTRING". 05 FILLER PIC X(33) VALUE " END-WRITE". 05 FILLER PIC X(33) VALUE "VENTRY". 05 FILLER PIC X(33) VALUE "KENVIRONMENT". 05 FILLER PIC X(33) VALUE " ENVIRONMENT-NAME". 05 FILLER PIC X(33) VALUE " ENVIRONMENT-VALUE". 05 FILLER PIC X(33) VALUE " EO". 05 FILLER PIC X(33) VALUE " EOL". 05 FILLER PIC X(33) VALUE " EOP". 05 FILLER PIC X(33) VALUE " EOS". 05 FILLER PIC X(33) VALUE " EQUAL". 05 FILLER PIC X(33) VALUE "KEQUALS". 05 FILLER PIC X(33) VALUE " ERASE". 05 FILLER PIC X(33) VALUE " ERROR". 05 FILLER PIC X(33) VALUE " ESCAPE". 05 FILLER PIC X(33) VALUE "VEVALUATE". 05 FILLER PIC X(33) VALUE " EXCEPTION". 05 FILLER PIC X(33) VALUE "IEXCEPTION-FILE". 05 FILLER PIC X(33) VALUE "IEXCEPTION-LOCATION". 05 FILLER PIC X(33) VALUE " EXCEPTION-OBJECT". 05 FILLER PIC X(33) VALUE "IEXCEPTION-STATEMENT". 05 FILLER PIC X(33) VALUE "IEXCEPTION-STATUS". 05 FILLER PIC X(33) VALUE " EXCLUSIVE". 05 FILLER PIC X(33) VALUE "VEXIT". 05 FILLER PIC X(33) VALUE "IEXP". 05 FILLER PIC X(33) VALUE "IEXP10". 05 FILLER PIC X(33) VALUE " EXTEND". 05 FILLER PIC X(33) VALUE " EXTERNAL". 05 FILLER PIC X(33) VALUE "IFACTORIAL". 05 FILLER PIC X(33) VALUE " FACTORY". 05 FILLER PIC X(33) VALUE " FALSE". 05 FILLER PIC X(33) VALUE "KFD". 05 FILLER PIC X(33) VALUE "KFILE". 05 FILLER PIC X(33) VALUE " FILE-CONTROL". 05 FILLER PIC X(33) VALUE " FILE-ID". 05 FILLER PIC X(33) VALUE " FILLER". 05 FILLER PIC X(33) VALUE " FINAL". 05 FILLER PIC X(33) VALUE " FIRST". 05 FILLER PIC X(33) VALUE " FLOAT-BINARY-16". 05 FILLER PIC X(33) VALUE " FLOAT-BINARY-34". 05 FILLER PIC X(33) VALUE " FLOAT-BINARY-7". 05 FILLER PIC X(33) VALUE " FLOAT-DECIMAL-16". 05 FILLER PIC X(33) VALUE " FLOAT-DECIMAL-34". 05 FILLER PIC X(33) VALUE " FLOAT-EXTENDED". 05 FILLER PIC X(33) VALUE " FLOAT-LONG". 05 FILLER PIC X(33) VALUE " FLOAT-SHORT". 05 FILLER PIC X(33) VALUE " FOOTING". 05 FILLER PIC X(33) VALUE " FOR". 05 FILLER PIC X(33) VALUE " FOREGROUND-COLOR". 05 FILLER PIC X(33) VALUE " FOREVER". 05 FILLER PIC X(33) VALUE " FORMAT". 05 FILLER PIC X(33) VALUE "MFORMFEED". 05 FILLER PIC X(33) VALUE "IFRACTION-PART". 05 FILLER PIC X(33) VALUE "VFREE". 05 FILLER PIC X(33) VALUE " FROM". 05 FILLER PIC X(33) VALUE " FULL". 05 FILLER PIC X(33) VALUE " FUNCTION". 05 FILLER PIC X(33) VALUE " FUNCTION-ID". 05 FILLER PIC X(33) VALUE " FUNCTION-POINTER". 05 FILLER PIC X(33) VALUE "VGENERATE". 05 FILLER PIC X(33) VALUE " GET". 05 FILLER PIC X(33) VALUE "KGIVING". 05 FILLER PIC X(33) VALUE " GLOBAL". 05 FILLER PIC X(33) VALUE "VGO". 05 FILLER PIC X(33) VALUE "VGOBACK". 05 FILLER PIC X(33) VALUE " GREATER". 05 FILLER PIC X(33) VALUE " GROUP". 05 FILLER PIC X(33) VALUE " GROUP-USAGE". 05 FILLER PIC X(33) VALUE " HEADING". 05 FILLER PIC X(33) VALUE " HIGH-VALUE". 05 FILLER PIC X(33) VALUE " HIGH-VALUES". 05 FILLER PIC X(33) VALUE " HIGHLIGHT". 05 FILLER PIC X(33) VALUE " I-O". 05 FILLER PIC X(33) VALUE " I-O-CONTROL". 05 FILLER PIC X(33) VALUE "KID". 05 FILLER PIC X(33) VALUE "KIDENTIFICATION". 05 FILLER PIC X(33) VALUE "VIF". 05 FILLER PIC X(33) VALUE " IGNORE". 05 FILLER PIC X(33) VALUE " IGNORING". 05 FILLER PIC X(33) VALUE " IN". 05 FILLER PIC X(33) VALUE " INDEX". 05 FILLER PIC X(33) VALUE "KINDEXED". 05 FILLER PIC X(33) VALUE " INDICATE". 05 FILLER PIC X(33) VALUE " INFINITY". 05 FILLER PIC X(33) VALUE " INHERITS". 05 FILLER PIC X(33) VALUE " INITIAL". 05 FILLER PIC X(33) VALUE " INITIALISED". 05 FILLER PIC X(33) VALUE "VINITIALIZE". 05 FILLER PIC X(33) VALUE " INITIALIZED". 05 FILLER PIC X(33) VALUE "VINITIATE". 05 FILLER PIC X(33) VALUE " INPUT". 05 FILLER PIC X(33) VALUE "KINPUT-OUTPUT". 05 FILLER PIC X(33) VALUE "VINSPECT". 05 FILLER PIC X(33) VALUE " INSTALLATION". 05 FILLER PIC X(33) VALUE "IINTEGER". 05 FILLER PIC X(33) VALUE "IINTEGER-OF-DATE". 05 FILLER PIC X(33) VALUE "IINTEGER-OF-DAY". 05 FILLER PIC X(33) VALUE "IINTEGER-PART". 05 FILLER PIC X(33) VALUE " INTERFACE". 05 FILLER PIC X(33) VALUE " INTERFACE-ID". 05 FILLER PIC X(33) VALUE "KINTO". 05 FILLER PIC X(33) VALUE " INTRINSIC". 05 FILLER PIC X(33) VALUE " INVALID". 05 FILLER PIC X(33) VALUE " INVOKE". 05 FILLER PIC X(33) VALUE " IS". 05 FILLER PIC X(33) VALUE " JUST". 05 FILLER PIC X(33) VALUE " JUSTIFIED". 05 FILLER PIC X(33) VALUE " KEY". 05 FILLER PIC X(33) VALUE " LABEL". 05 FILLER PIC X(33) VALUE " LAST". 05 FILLER PIC X(33) VALUE " LEADING". 05 FILLER PIC X(33) VALUE " LEFT". 05 FILLER PIC X(33) VALUE " LEFT-JUSTIFY". 05 FILLER PIC X(33) VALUE "ILENGTH". 05 FILLER PIC X(33) VALUE " LESS". 05 FILLER PIC X(33) VALUE " LIMIT". 05 FILLER PIC X(33) VALUE " LIMITS". 05 FILLER PIC X(33) VALUE " LINAGE". 05 FILLER PIC X(33) VALUE "ILINAGE-COUNTER". 05 FILLER PIC X(33) VALUE " LINE". 05 FILLER PIC X(33) VALUE " LINE-COUNTER". 05 FILLER PIC X(33) VALUE " LINES". 05 FILLER PIC X(33) VALUE "KLINKAGE". 05 FILLER PIC X(33) VALUE "KLOCAL-STORAGE". 05 FILLER PIC X(33) VALUE " LOCALE". 05 FILLER PIC X(33) VALUE "ILOCALE-DATE". 05 FILLER PIC X(33) VALUE "ILOCALE-TIME". 05 FILLER PIC X(33) VALUE "ILOCALE-TIME-FROM-SECONDS". 05 FILLER PIC X(33) VALUE " LOCK". 05 FILLER PIC X(33) VALUE "ILOG". 05 FILLER PIC X(33) VALUE "ILOG10". 05 FILLER PIC X(33) VALUE " LOW-VALUE". 05 FILLER PIC X(33) VALUE " LOW-VALUES". 05 FILLER PIC X(33) VALUE " LOWER". 05 FILLER PIC X(33) VALUE "ILOWER-CASE". 05 FILLER PIC X(33) VALUE " LOWLIGHT". 05 FILLER PIC X(33) VALUE " MANUAL". 05 FILLER PIC X(33) VALUE "IMAX". 05 FILLER PIC X(33) VALUE "IMEAN". 05 FILLER PIC X(33) VALUE "IMEDIAN". 05 FILLER PIC X(33) VALUE " MEMORY". 05 FILLER PIC X(33) VALUE "VMERGE". 05 FILLER PIC X(33) VALUE " METHOD". 05 FILLER PIC X(33) VALUE " METHOD-ID". 05 FILLER PIC X(33) VALUE "IMIDRANGE". 05 FILLER PIC X(33) VALUE "IMIN". 05 FILLER PIC X(33) VALUE " MINUS". 05 FILLER PIC X(33) VALUE "IMOD". 05 FILLER PIC X(33) VALUE " MODE". 05 FILLER PIC X(33) VALUE "VMOVE". 05 FILLER PIC X(33) VALUE " MULTIPLE". 05 FILLER PIC X(33) VALUE "VMULTIPLY". 05 FILLER PIC X(33) VALUE " NATIONAL". 05 FILLER PIC X(33) VALUE " NATIONAL-EDITED". 05 FILLER PIC X(33) VALUE " NATIVE". 05 FILLER PIC X(33) VALUE " NEGATIVE". 05 FILLER PIC X(33) VALUE " NESTED". 05 FILLER PIC X(33) VALUE "VNEXT". 05 FILLER PIC X(33) VALUE " NO". 05 FILLER PIC X(33) VALUE " NOT". 05 FILLER PIC X(33) VALUE " NULL". 05 FILLER PIC X(33) VALUE " NULLS". 05 FILLER PIC X(33) VALUE " NUMBER". 05 FILLER PIC X(33) VALUE "INUMBER-OF-CALL-PARAMETERS". 05 FILLER PIC X(33) VALUE " NUMBERS". 05 FILLER PIC X(33) VALUE " NUMERIC". 05 FILLER PIC X(33) VALUE " NUMERIC-EDITED". 05 FILLER PIC X(33) VALUE "INUMVAL". 05 FILLER PIC X(33) VALUE "INUMVAL-C". 05 FILLER PIC X(33) VALUE " OBJECT". 05 FILLER PIC X(33) VALUE " OBJECT-COMPUTER". 05 FILLER PIC X(33) VALUE " OBJECT-REFERENCE". 05 FILLER PIC X(33) VALUE " OCCURS". 05 FILLER PIC X(33) VALUE " OF". 05 FILLER PIC X(33) VALUE " OFF". 05 FILLER PIC X(33) VALUE " OMITTED". 05 FILLER PIC X(33) VALUE " ON". 05 FILLER PIC X(33) VALUE " ONLY". 05 FILLER PIC X(33) VALUE "VOPEN". 05 FILLER PIC X(33) VALUE " OPTIONAL". 05 FILLER PIC X(33) VALUE " OPTIONS". 05 FILLER PIC X(33) VALUE " OR". 05 FILLER PIC X(33) VALUE "IORD". 05 FILLER PIC X(33) VALUE "IORD-MAX". 05 FILLER PIC X(33) VALUE "IORD-MIN". 05 FILLER PIC X(33) VALUE " ORDER". 05 FILLER PIC X(33) VALUE " ORGANIZATION". 05 FILLER PIC X(33) VALUE " OTHER". 05 FILLER PIC X(33) VALUE " OUTPUT". 05 FILLER PIC X(33) VALUE " OVERFLOW". 05 FILLER PIC X(33) VALUE " OVERLINE". 05 FILLER PIC X(33) VALUE " OVERRIDE". 05 FILLER PIC X(33) VALUE " PACKED-DECIMAL". 05 FILLER PIC X(33) VALUE " PADDING". 05 FILLER PIC X(33) VALUE " PAGE". 05 FILLER PIC X(33) VALUE " PAGE-COUNTER". 05 FILLER PIC X(33) VALUE " PARAGRAPH". 05 FILLER PIC X(33) VALUE "VPERFORM". 05 FILLER PIC X(33) VALUE " PF". 05 FILLER PIC X(33) VALUE " PH". 05 FILLER PIC X(33) VALUE "IPI". 05 FILLER PIC X(33) VALUE "KPIC". 05 FILLER PIC X(33) VALUE "KPICTURE". 05 FILLER PIC X(33) VALUE " PLUS". 05 FILLER PIC X(33) VALUE "KPOINTER". 05 FILLER PIC X(33) VALUE " POSITION". 05 FILLER PIC X(33) VALUE " POSITIVE". 05 FILLER PIC X(33) VALUE " PRESENT". 05 FILLER PIC X(33) VALUE "IPRESENT-VALUE". 05 FILLER PIC X(33) VALUE " PREVIOUS". 05 FILLER PIC X(33) VALUE "MPRINTER". 05 FILLER PIC X(33) VALUE " PRINTING". 05 FILLER PIC X(33) VALUE "KPROCEDURE". 05 FILLER PIC X(33) VALUE " PROCEDURE-POINTER". 05 FILLER PIC X(33) VALUE " PROCEDURES". 05 FILLER PIC X(33) VALUE " PROCEED". 05 FILLER PIC X(33) VALUE " PROGRAM". 05 FILLER PIC X(33) VALUE "KPROGRAM-ID". 05 FILLER PIC X(33) VALUE " PROGRAM-POINTER". 05 FILLER PIC X(33) VALUE " PROMPT". 05 FILLER PIC X(33) VALUE " PROPERTY". 05 FILLER PIC X(33) VALUE " PROTOTYPE". 05 FILLER PIC X(33) VALUE " QUOTE". 05 FILLER PIC X(33) VALUE " QUOTES". 05 FILLER PIC X(33) VALUE " RAISE". 05 FILLER PIC X(33) VALUE " RAISING". 05 FILLER PIC X(33) VALUE "IRANDOM". 05 FILLER PIC X(33) VALUE "IRANGE". 05 FILLER PIC X(33) VALUE " RD". 05 FILLER PIC X(33) VALUE "VREAD". 05 FILLER PIC X(33) VALUE "VREADY". 05 FILLER PIC X(33) VALUE " RECORD". 05 FILLER PIC X(33) VALUE " RECORDING". 05 FILLER PIC X(33) VALUE " RECORDS". 05 FILLER PIC X(33) VALUE " RECURSIVE". 05 FILLER PIC X(33) VALUE "KREDEFINES". 05 FILLER PIC X(33) VALUE " REEL". 05 FILLER PIC X(33) VALUE " REFERENCE". 05 FILLER PIC X(33) VALUE " RELATIVE". 05 FILLER PIC X(33) VALUE "VRELEASE". 05 FILLER PIC X(33) VALUE "IREM". 05 FILLER PIC X(33) VALUE " REMAINDER". 05 FILLER PIC X(33) VALUE " REMARKS". 05 FILLER PIC X(33) VALUE " REMOVAL". 05 FILLER PIC X(33) VALUE "KRENAMES". 05 FILLER PIC X(33) VALUE "KREPLACING". 05 FILLER PIC X(33) VALUE "KREPORT". 05 FILLER PIC X(33) VALUE " REPORTING". 05 FILLER PIC X(33) VALUE " REPORTS". 05 FILLER PIC X(33) VALUE " REPOSITORY". 05 FILLER PIC X(33) VALUE " REPRESENTS-NOT-A-NUMBER". 05 FILLER PIC X(33) VALUE " REQUIRED". 05 FILLER PIC X(33) VALUE " RESERVE". 05 FILLER PIC X(33) VALUE " RESUME". 05 FILLER PIC X(33) VALUE " RETRY". 05 FILLER PIC X(33) VALUE "VRETURN". 05 FILLER PIC X(33) VALUE "IRETURN-CODE". 05 FILLER PIC X(33) VALUE "KRETURNING". 05 FILLER PIC X(33) VALUE "IREVERSE". 05 FILLER PIC X(33) VALUE " REVERSE-VIDEO". 05 FILLER PIC X(33) VALUE " REWIND". 05 FILLER PIC X(33) VALUE "VREWRITE". 05 FILLER PIC X(33) VALUE " RF". 05 FILLER PIC X(33) VALUE " RH". 05 FILLER PIC X(33) VALUE " RIGHT". 05 FILLER PIC X(33) VALUE " RIGHT-JUSTIFY". 05 FILLER PIC X(33) VALUE "VROLLBACK". 05 FILLER PIC X(33) VALUE " ROUNDED". 05 FILLER PIC X(33) VALUE " RUN". 05 FILLER PIC X(33) VALUE " SAME". 05 FILLER PIC X(33) VALUE "KSCREEN". 05 FILLER PIC X(33) VALUE " SCROLL". 05 FILLER PIC X(33) VALUE "KSD". 05 FILLER PIC X(33) VALUE "VSEARCH". 05 FILLER PIC X(33) VALUE "ISECONDS-FROM-FORMATTED-TIME". 05 FILLER PIC X(33) VALUE "ISECONDS-PAST-MIDNIGHT". 05 FILLER PIC X(33) VALUE "KSECTION". 05 FILLER PIC X(33) VALUE " SECURE". 05 FILLER PIC X(33) VALUE " SECURITY". 05 FILLER PIC X(33) VALUE " SEGMENT-LIMIT". 05 FILLER PIC X(33) VALUE " SELECT". 05 FILLER PIC X(33) VALUE " SELF". 05 FILLER PIC X(33) VALUE " SENTENCE". 05 FILLER PIC X(33) VALUE " SEPARATE". 05 FILLER PIC X(33) VALUE " SEQUENCE". 05 FILLER PIC X(33) VALUE " SEQUENTIAL". 05 FILLER PIC X(33) VALUE "VSET". 05 FILLER PIC X(33) VALUE " SHARING". 05 FILLER PIC X(33) VALUE "ISIGN". 05 FILLER PIC X(33) VALUE " SIGNED". 05 FILLER PIC X(33) VALUE " SIGNED-INT". 05 FILLER PIC X(33) VALUE " SIGNED-LONG". 05 FILLER PIC X(33) VALUE " SIGNED-SHORT". 05 FILLER PIC X(33) VALUE "ISIN". 05 FILLER PIC X(33) VALUE " SIZE". 05 FILLER PIC X(33) VALUE "VSORT". 05 FILLER PIC X(33) VALUE " SORT-MERGE". 05 FILLER PIC X(33) VALUE "ISORT-RETURN". 05 FILLER PIC X(33) VALUE " SOURCE". 05 FILLER PIC X(33) VALUE " SOURCE-COMPUTER". 05 FILLER PIC X(33) VALUE " SOURCES". 05 FILLER PIC X(33) VALUE " SPACE". 05 FILLER PIC X(33) VALUE " SPACE-FILL". 05 FILLER PIC X(33) VALUE " SPACES". 05 FILLER PIC X(33) VALUE " SPECIAL-NAMES". 05 FILLER PIC X(33) VALUE "ISQRT". 05 FILLER PIC X(33) VALUE " STANDARD". 05 FILLER PIC X(33) VALUE " STANDARD-1". 05 FILLER PIC X(33) VALUE " STANDARD-2". 05 FILLER PIC X(33) VALUE "ISTANDARD-DEVIATION". 05 FILLER PIC X(33) VALUE "VSTART". 05 FILLER PIC X(33) VALUE " STATUS". 05 FILLER PIC X(33) VALUE "VSTOP". 05 FILLER PIC X(33) VALUE "ISTORED-CHAR-LENGTH". 05 FILLER PIC X(33) VALUE "VSTRING". 05 FILLER PIC X(33) VALUE "ISUBSTITUTE". 05 FILLER PIC X(33) VALUE "ISUBSTITUTE-CASE". 05 FILLER PIC X(33) VALUE "VSUBTRACT". 05 FILLER PIC X(33) VALUE "ISUM". 05 FILLER PIC X(33) VALUE " SUPER". 05 FILLER PIC X(33) VALUE "VSUPPRESS". 05 FILLER PIC X(33) VALUE "MSWITCH-1". 05 FILLER PIC X(33) VALUE "MSWITCH-2". 05 FILLER PIC X(33) VALUE "MSWITCH-3". 05 FILLER PIC X(33) VALUE "MSWITCH-4". 05 FILLER PIC X(33) VALUE "MSWITCH-5". 05 FILLER PIC X(33) VALUE "MSWITCH-6". 05 FILLER PIC X(33) VALUE "MSWITCH-7". 05 FILLER PIC X(33) VALUE "MSWITCH-8". 05 FILLER PIC X(33) VALUE " SYMBOLIC". 05 FILLER PIC X(33) VALUE " SYNC". 05 FILLER PIC X(33) VALUE " SYNCHRONIZED". 05 FILLER PIC X(33) VALUE "MSYSERR". 05 FILLER PIC X(33) VALUE "MSYSIN". 05 FILLER PIC X(33) VALUE "MSYSIPT". 05 FILLER PIC X(33) VALUE "MSYSLIST". 05 FILLER PIC X(33) VALUE "MSYSLST". 05 FILLER PIC X(33) VALUE "MSYSOUT". 05 FILLER PIC X(33) VALUE " SYSTEM-DEFAULT". 05 FILLER PIC X(33) VALUE " TABLE". 05 FILLER PIC X(33) VALUE "KTALLYING". 05 FILLER PIC X(33) VALUE "ITAN". 05 FILLER PIC X(33) VALUE " TAPE". 05 FILLER PIC X(33) VALUE "VTERMINATE". 05 FILLER PIC X(33) VALUE " TEST". 05 FILLER PIC X(33) VALUE "ITEST-DATE-YYYYMMDD". 05 FILLER PIC X(33) VALUE "ITEST-DAY-YYYYDDD". 05 FILLER PIC X(33) VALUE " THAN". 05 FILLER PIC X(33) VALUE " THEN". 05 FILLER PIC X(33) VALUE " THROUGH". 05 FILLER PIC X(33) VALUE " THRU". 05 FILLER PIC X(33) VALUE " TIME". 05 FILLER PIC X(33) VALUE " TIMES". 05 FILLER PIC X(33) VALUE "KTO". 05 FILLER PIC X(33) VALUE " TOP". 05 FILLER PIC X(33) VALUE " TRAILING". 05 FILLER PIC X(33) VALUE " TRAILING-SIGN". 05 FILLER PIC X(33) VALUE "VTRANSFORM". 05 FILLER PIC X(33) VALUE "ITRIM". 05 FILLER PIC X(33) VALUE " TRUE". 05 FILLER PIC X(33) VALUE " TYPE". 05 FILLER PIC X(33) VALUE " TYPEDEF". 05 FILLER PIC X(33) VALUE " UNDERLINE". 05 FILLER PIC X(33) VALUE " UNIT". 05 FILLER PIC X(33) VALUE " UNIVERSAL". 05 FILLER PIC X(33) VALUE "VUNLOCK". 05 FILLER PIC X(33) VALUE " UNSIGNED". 05 FILLER PIC X(33) VALUE " UNSIGNED-INT". 05 FILLER PIC X(33) VALUE " UNSIGNED-LONG". 05 FILLER PIC X(33) VALUE " UNSIGNED-SHORT". 05 FILLER PIC X(33) VALUE "VUNSTRING". 05 FILLER PIC X(33) VALUE " UNTIL". 05 FILLER PIC X(33) VALUE "KUP". 05 FILLER PIC X(33) VALUE " UPDATE". 05 FILLER PIC X(33) VALUE " UPON". 05 FILLER PIC X(33) VALUE " UPPER". 05 FILLER PIC X(33) VALUE "IUPPER-CASE". 05 FILLER PIC X(33) VALUE " USAGE". 05 FILLER PIC X(33) VALUE "VUSE". 05 FILLER PIC X(33) VALUE " USER-DEFAULT". 05 FILLER PIC X(33) VALUE "KUSING". 05 FILLER PIC X(33) VALUE " VAL-STATUS". 05 FILLER PIC X(33) VALUE " VALID". 05 FILLER PIC X(33) VALUE " VALIDATE". 05 FILLER PIC X(33) VALUE " VALIDATE-STATUS". 05 FILLER PIC X(33) VALUE " VALUE". 05 FILLER PIC X(33) VALUE " VALUES". 05 FILLER PIC X(33) VALUE "IVARIANCE". 05 FILLER PIC X(33) VALUE "KVARYING". 05 FILLER PIC X(33) VALUE " WAIT". 05 FILLER PIC X(33) VALUE "VWHEN". 05 FILLER PIC X(33) VALUE "IWHEN-COMPILED". 05 FILLER PIC X(33) VALUE " WITH". 05 FILLER PIC X(33) VALUE " WORDS". 05 FILLER PIC X(33) VALUE "KWORKING-STORAGE". 05 FILLER PIC X(33) VALUE "VWRITE". 05 FILLER PIC X(33) VALUE "IYEAR-TO-YYYY". 05 FILLER PIC X(33) VALUE " YYYYDDD". 05 FILLER PIC X(33) VALUE " YYYYMMDD". 05 FILLER PIC X(33) VALUE " ZERO". 05 FILLER PIC X(33) VALUE " ZERO-FILL". 05 FILLER PIC X(33) VALUE " ZEROES". 05 FILLER PIC X(33) VALUE " ZEROS". 01 Reserved-Word-Table REDEFINES Reserved-Words. 05 Reserved-Word OCCURS 591 TIMES ASCENDING KEY RW-Word INDEXED RW-Idx. 10 RW-Type PIC X(1). 10 RW-Word PIC X(32). 01 Saved-Section PIC X(15). 01 Search-Token PIC X(32). 01 Source-Line-No PIC 9(6). 01 Src-Ptr USAGE BINARY-LONG. 01 Syntax-Parsing-Items. 05 SPI-Current-Char PIC X(1). 88 Current-Char-Is-Punct VALUE "=", "(", ")", "*", "/", "&", ";", ",", "<", ">", ":". 88 Current-Char-Is-Quote VALUE '"', "'". 88 Current-Char-Is-X VALUE "x", "X". 88 Current-Char-Is-Z VALUE "z", "Z". 05 SPI-Current-Division PIC X(1). 88 In-IDENTIFICATION-DIVISION VALUE "I", "?". 88 In-ENVIRONMENT-DIVISION VALUE "E". 88 In-DATA-DIVISION VALUE "D". 88 In-PROCEDURE-DIVISION VALUE "P". 05 SPI-Current-Line-No PIC 9(6). 05 SPI-Current-Program-ID. 10 FILLER PIC X(12). 10 SPI-CP-13-15 PIC X(3). 05 SPI-Current-Section. 10 SPI-CS-1 PIC X(1). 10 SPI-CS-2-14. 15 FILLER PIC X(10). 15 SPI-CS-11-14 PIC X(3). 10 SPI-CS-15 PIC X(1). 05 SPI-Current-Token PIC X(32). 05 SPI-Current-Token-UC PIC X(32). 05 SPI-Current-Verb PIC X(12). 05 SPI-Next-Char PIC X(1). 88 Next-Char-Is-Quote VALUE '"', "'". 05 SPI-Prior-Token PIC X(32). 05 SPI-Token-Type PIC X(1). 88 Token-Is-EOF VALUE HIGH-VALUES. 88 Token-Is-Identifier VALUE "I". 88 Token-Is-Key-Word VALUE "K", "V". 88 Token-Is-Literal-Alpha VALUE "L". 88 Token-Is-Literal-Number VALUE "N". 88 Token-Is-Verb VALUE "V". GC0710 88 Token-Is-Reserved-Word VALUE " ". 01 Tally USAGE BINARY-LONG. 01 Todays-Date PIC 9(8). LINKAGE SECTION. 01 Produce-Source-Listing PIC X(1). 01 Produce-Xref-Listing PIC X(1). 01 Src-Filename PIC X(256). / PROCEDURE DIVISION USING Produce-Source-Listing Produce-Xref-Listing Src-Filename. 000-Main SECTION. 001-Init. PERFORM 100-Initialization PERFORM 200-Execute-cobc OPEN OUTPUT Report-File IF Produce-Source-Listing NOT = SPACE PERFORM 500-Produce-Source-Listing END-IF IF Produce-Xref-Listing NOT = SPACE SORT Sort-File ASCENDING KEY SR-Prog-ID SR-Token-UC SR-Line-No-Ref INPUT PROCEDURE 300-Tokenize-Source OUTPUT PROCEDURE 400-Produce-Xref-Listing END-IF CLOSE Report-File GOBACK . / 100-Initialization SECTION. ***************************************************************** ** Perform all program-wide initialization operations ** ***************************************************************** 101-Establish-Working-Env. MOVE TRIM(Src-Filename,Leading) TO Src-Filename ACCEPT Env-TEMP FROM ENVIRONMENT "TEMP" END-ACCEPT ACCEPT Lines-Per-Page-ENV FROM ENVIRONMENT "OCXREF_LINES" END-ACCEPT INSPECT Src-Filename REPLACING ALL "\" BY "/" INSPECT Env-TEMP REPLACING ALL "\" BY "/" MOVE Src-Filename TO Program-Path MOVE Program-Path TO Heading-2 CALL "C$JUSTIFY" USING Heading-2, "Right" END-CALL MOVE LENGTH(TRIM(Src-Filename,Trailing)) TO I MOVE 0 TO J PERFORM UNTIL Src-Filename(I:1) = '/' OR I = 0 SUBTRACT 1 FROM I ADD 1 TO J END-PERFORM UNSTRING Src-Filename((I + 1):J) DELIMITED BY "." INTO Filename, Dummy END-UNSTRING STRING TRIM(Env-TEMP,Trailing) "/" TRIM(Filename,Trailing) ".i" DELIMITED SIZE INTO Expanded-Src-Filename END-STRING STRING Program-Path(1:I) TRIM(Filename,Trailing) ".lst" DELIMITED SIZE INTO Report-Filename END-STRING IF Lines-Per-Page-ENV NOT = SPACES MOVE NUMVAL(Lines-Per-Page-ENV) TO Lines-Per-Page ELSE MOVE 60 TO Lines-Per-Page END-IF ACCEPT Todays-Date FROM DATE YYYYMMDD END-ACCEPT MOVE Todays-Date TO H1X-Date H1S-Date MOVE "????????????..." TO SPI-Current-Program-ID MOVE SPACES TO SPI-Current-Verb Held-Reference MOVE "Y" TO F-First-Record . / 200-Execute-cobc SECTION. 201-Build-Cmd. STRING "cobc -E " TRIM(Program-Path, Trailing) " > " TRIM(Expanded-Src-Filename,Trailing) DELIMITED SIZE INTO Cmd END-STRING CALL "SYSTEM" USING Cmd END-CALL IF RETURN-CODE NOT = 0 DISPLAY "Cross-reference terminated by previous errors" UPON SYSERR END-DISPLAY GOBACK END-IF . 209-Exit. EXIT . / 300-Tokenize-Source SECTION. 301-Driver. OPEN INPUT Expand-Code MOVE SPACES TO Expand-Code-Rec MOVE 256 TO Src-Ptr MOVE 0 TO Num-UserNames SPI-Current-Line-No MOVE "?" TO SPI-Current-Division GC0710 MOVE "N" TO F-Verb-Has-Been-Found. PERFORM FOREVER PERFORM 310-Get-Token IF Token-Is-EOF EXIT PERFORM END-IF MOVE UPPER-CASE(SPI-Current-Token) TO SPI-Current-Token-UC IF Token-Is-Verb MOVE SPI-Current-Token-UC TO SPI-Current-Verb SPI-Prior-Token IF Held-Reference NOT = SPACES MOVE Held-Reference TO Sort-Rec MOVE SPACES TO Held-Reference RELEASE Sort-Rec END-IF END-IF EVALUATE TRUE WHEN In-IDENTIFICATION-DIVISION PERFORM 320-IDENTIFICATION-DIVISION WHEN In-ENVIRONMENT-DIVISION PERFORM 330-ENVIRONMENT-DIVISION WHEN In-DATA-DIVISION PERFORM 340-DATA-DIVISION WHEN In-PROCEDURE-DIVISION PERFORM 350-PROCEDURE-DIVISION END-EVALUATE IF Token-Is-Key-Word MOVE SPI-Current-Token-UC TO SPI-Prior-Token END-IF IF F-Token-Ended-Sentence = "Y" AND SPI-Current-Division NOT = "I" MOVE SPACES TO SPI-Prior-Token SPI-Current-Verb END-IF END-PERFORM CLOSE Expand-Code EXIT SECTION . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 310-Get-Token. *>-- Position to 1st non-blank character MOVE F-Token-Ended-Sentence TO F-Last-Token-Ended-Sent MOVE "N" TO F-Token-Ended-Sentence PERFORM UNTIL Expand-Code-Rec(Src-Ptr : 1) NOT = SPACE IF Src-Ptr > 255 READ Expand-Code AT END IF Held-Reference NOT = SPACES MOVE Held-Reference TO Sort-Rec MOVE SPACES TO Held-Reference RELEASE Sort-Rec END-IF SET Token-Is-EOF TO TRUE MOVE 0 TO SPI-Current-Line-No EXIT PARAGRAPH END-READ IF ECR-1 = "#" PERFORM 311-Control-Record ELSE PERFORM 312-Expand-Code-Record END-IF ELSE ADD 1 TO Src-Ptr END-IF END-PERFORM *>-- Extract token string MOVE Expand-Code-Rec(Src-Ptr : 1) TO SPI-Current-Char MOVE Expand-Code-Rec(Src-Ptr + 1: 1) TO SPI-Next-Char IF SPI-Current-Char = "." ADD 1 TO Src-Ptr MOVE SPI-Current-Char TO SPI-Current-Token MOVE SPACE TO SPI-Token-Type MOVE "Y" TO F-Token-Ended-Sentence EXIT PARAGRAPH END-IF IF Current-Char-Is-Punct AND SPI-Current-Char = "=" AND SPI-Current-Division = "P" ADD 1 TO Src-Ptr MOVE "EQUALS" TO SPI-Current-Token MOVE "K" TO SPI-Token-Type EXIT PARAGRAPH END-IF IF Current-Char-Is-Punct *> So subscripts don't get flagged w/ "*" AND SPI-Current-Char = "(" AND SPI-Current-Division = "P" MOVE SPACES TO SPI-Prior-Token END-IF IF Current-Char-Is-Punct ADD 1 TO Src-Ptr MOVE SPI-Current-Char TO SPI-Current-Token MOVE SPACE TO SPI-Token-Type EXIT PARAGRAPH END-IF IF Current-Char-Is-Quote ADD 1 TO Src-Ptr UNSTRING Expand-Code-Rec DELIMITED BY SPI-Current-Char INTO SPI-Current-Token WITH POINTER Src-Ptr END-UNSTRING IF Expand-Code-Rec(Src-Ptr : 1) = "." MOVE "Y" TO F-Token-Ended-Sentence ADD 1 TO Src-Ptr END-IF SET Token-Is-Literal-Alpha TO TRUE EXIT PARAGRAPH END-IF IF Current-Char-Is-X AND Next-Char-Is-Quote ADD 2 TO Src-Ptr UNSTRING Expand-Code-Rec DELIMITED BY SPI-Next-Char INTO SPI-Current-Token WITH POINTER Src-Ptr END-UNSTRING IF Expand-Code-Rec(Src-Ptr : 1) = "." MOVE "Y" TO F-Token-Ended-Sentence ADD 1 TO Src-Ptr END-IF SET Token-Is-Literal-Number TO TRUE EXIT PARAGRAPH END-IF IF Current-Char-Is-Z AND Next-Char-Is-Quote ADD 2 TO Src-Ptr UNSTRING Expand-Code-Rec DELIMITED BY SPI-Next-Char INTO SPI-Current-Token WITH POINTER Src-Ptr END-UNSTRING IF Expand-Code-Rec(Src-Ptr : 1) = "." MOVE "Y" TO F-Token-Ended-Sentence ADD 1 TO Src-Ptr END-IF SET Token-Is-Literal-Alpha TO TRUE EXIT PARAGRAPH END-IF IF F-Processing-PICTURE = "Y" UNSTRING Expand-Code-Rec DELIMITED BY ". " OR " " INTO SPI-Current-Token DELIMITER IN Delim WITH POINTER Src-Ptr END-UNSTRING IF Delim = ". " MOVE "Y" TO F-Token-Ended-Sentence ADD 1 TO Src-Ptr END-IF IF UPPER-CASE(SPI-Current-Token) = "IS" MOVE SPACE TO SPI-Token-Type EXIT PARAGRAPH ELSE MOVE "N" TO F-Processing-PICTURE MOVE SPACE TO SPI-Token-Type EXIT PARAGRAPH END-IF END-IF UNSTRING Expand-Code-Rec DELIMITED BY ". " OR " " OR "=" OR "(" OR ")" OR "*" OR "/" OR "&" OR ";" OR "," OR "<" OR ">" OR ":" INTO SPI-Current-Token DELIMITER IN Delim WITH POINTER Src-Ptr END-UNSTRING IF Delim = ". " MOVE "Y" TO F-Token-Ended-Sentence END-IF IF Delim NOT = ". " AND " " SUBTRACT 1 FROM Src-Ptr END-IF *>-- Classify Token MOVE UPPER-CASE(SPI-Current-Token) TO Search-Token IF Search-Token = "EQUAL" OR "EQUALS" MOVE "EQUALS" TO SPI-Current-Token MOVE "K" TO SPI-Token-Type EXIT PARAGRAPH END-IF SEARCH ALL Reserved-Word WHEN RW-Word (RW-Idx) = Search-Token MOVE RW-Type (RW-Idx) TO SPI-Token-Type GC0710 IF Token-Is-Verb GC0710 MOVE "Y" TO F-Verb-Has-Been-Found GC0710 END-IF EXIT PARAGRAPH END-SEARCH *>-- Not a reserved word, must be a user name SET Token-Is-Identifier TO TRUE *> NEEDS EXPANSION!!!! PERFORM 313-Check-For-Numeric-Token IF Token-Is-Literal-Number IF (F-Last-Token-Ended-Sent = "Y") AND (SPI-Current-Division = "D") MOVE "LEVEL #" TO SPI-Current-Token MOVE "K" TO SPI-Token-Type EXIT PARAGRAPH ELSE EXIT PARAGRAPH END-IF END-IF EXIT PARAGRAPH . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 311-Control-Record. UNSTRING ECR-2-256 DELIMITED BY '"' INTO PIC-X10, PIC-X256, Dummy END-UNSTRING INSPECT PIC-X10 REPLACING ALL '"' BY SPACE COMPUTE I = NUMVAL(PIC-X10) - 1 IF TRIM(PIC-X256,Trailing) = TRIM(Program-Path,Trailing) MOVE I TO SPI-Current-Line-No SET In-Main-Module TO TRUE IF Saved-Section NOT = SPACES MOVE Saved-Section TO SPI-Current-Section END-IF ELSE SET In-Copybook TO TRUE IF Saved-Section = SPACES MOVE SPI-Current-Section TO Saved-Section END-IF MOVE LENGTH(TRIM(PIC-X256,Trailing)) TO I MOVE 0 TO J PERFORM UNTIL PIC-X256(I:1) = '/' OR I = 0 SUBTRACT 1 FROM I ADD 1 TO J END-PERFORM UNSTRING PIC-X256((I + 1):J) DELIMITED BY "." INTO Filename, Dummy END-UNSTRING MOVE "[" TO SPI-CS-1 MOVE Filename TO SPI-CS-2-14 IF SPI-CS-11-14 NOT = SPACES MOVE "..." TO SPI-CS-11-14 END-IF MOVE "]" TO SPI-CS-15 END-IF MOVE SPACES TO Expand-Code-Rec *> Force another READ MOVE 256 TO Src-Ptr . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 312-Expand-Code-Record. MOVE 1 TO Src-Ptr IF In-Main-Module ADD 1 To SPI-Current-Line-No END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 313-Check-For-Numeric-Token. MOVE SPI-Current-Token TO PIC-X32 INSPECT PIC-X32 REPLACING TRAILING SPACES BY "0" IF PIC-X32 IS NUMERIC *> Simple Unsigned Integer SET Token-Is-Literal-Number TO TRUE EXIT PARAGRAPH END-IF IF PIC-X32(1:1) = "+" OR "-" MOVE "0" TO PIC-X32(1:1) END-IF MOVE 0 TO Tally INSPECT PIC-X32 TALLYING Tally FOR ALL "." IF Tally = 1 INSPECT PIC-X32 REPLACING ALL "." BY "0" END-IF IF PIC-X32 IS NUMERIC SET Token-Is-Literal-Number TO TRUE EXIT PARAGRAPH END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 320-IDENTIFICATION-DIVISION. GC0710 MOVE "N" TO F-Verb-Has-Been-Found IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION" MOVE SPI-Prior-Token TO SPI-Current-Division EXIT PARAGRAPH END-IF IF SPI-Prior-Token = "PROGRAM-ID" MOVE SPACES TO SPI-Prior-Token MOVE SPI-Current-Token TO SPI-Current-Program-ID IF SPI-CP-13-15 NOT = SPACES MOVE "..." TO SPI-CP-13-15 END-IF EXIT PARAGRAPH END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 330-ENVIRONMENT-DIVISION. IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION" MOVE SPI-Prior-Token TO SPI-Current-Division EXIT PARAGRAPH END-IF IF Token-Is-Key-Word AND SPI-Current-Token = "SECTION" MOVE SPI-Prior-Token TO SPI-Current-Section EXIT PARAGRAPH END-IF IF Token-Is-Identifier PERFORM 361-Release-Ref END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 340-DATA-DIVISION. IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION" MOVE SPI-Prior-Token TO SPI-Current-Division EXIT PARAGRAPH END-IF IF Token-Is-Key-Word AND SPI-Current-Token = "SECTION" MOVE SPI-Prior-Token TO SPI-Current-Section EXIT PARAGRAPH END-IF IF (SPI-Current-Token = "PIC" OR "PICTURE") AND (Token-Is-Key-Word) MOVE "Y" TO F-Processing-PICTURE EXIT PARAGRAPH END-IF GC0710 IF Token-Is-Reserved-Word GC0710 AND SPI-Prior-Token = "LEVEL #" GC0710 MOVE SPACES TO SPI-Prior-Token GC0710 EXIT PARAGRAPH GC0710 END-IF IF Token-Is-Identifier EVALUATE SPI-Prior-Token WHEN "FD" PERFORM 360-Release-Def MOVE SPACES TO SPI-Prior-Token WHEN "SD" PERFORM 360-Release-Def MOVE SPACES TO SPI-Prior-Token WHEN "LEVEL #" PERFORM 360-Release-Def MOVE SPACES TO SPI-Prior-Token WHEN "INDEXED" PERFORM 360-Release-Def MOVE SPACES TO SPI-Prior-Token WHEN "USING" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN "INTO" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE EXIT PARAGRAPH END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 350-PROCEDURE-DIVISION. IF SPI-Current-Section NOT = "PROCEDURE" MOVE "PROCEDURE" TO SPI-Current-Section END-IF GC0710 IF SPI-Current-Token-UC = "PROGRAM" GC0710 AND SPI-Prior-Token = "END" GC0710 MOVE "?" TO SPI-Current-Division GC0710 EXIT PARAGRAPH GC0710 END-IF IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION" MOVE SPI-Prior-Token TO SPI-Current-Division EXIT PARAGRAPH END-IF IF SPI-Current-Verb = SPACES GC0710 AND F-Verb-Has-Been-Found = "Y" IF Token-Is-Identifier PERFORM 360-Release-Def MOVE SPACES TO SPI-Prior-Token END-IF EXIT PARAGRAPH END-IF IF NOT Token-Is-Identifier EXIT PARAGRAPH END-IF EVALUATE SPI-Current-Verb WHEN "ACCEPT" PERFORM 351-ACCEPT WHEN "ADD" PERFORM 351-ADD WHEN "ALLOCATE" PERFORM 351-ALLOCATE WHEN "CALL" PERFORM 351-CALL WHEN "COMPUTE" PERFORM 351-COMPUTE WHEN "DIVIDE" PERFORM 351-DIVIDE WHEN "FREE" PERFORM 351-FREE WHEN "INITIALIZE" PERFORM 351-INITIALIZE WHEN "INSPECT" PERFORM 351-INSPECT WHEN "MOVE" PERFORM 351-MOVE WHEN "MULTIPLY" PERFORM 351-MULTIPLY WHEN "PERFORM" PERFORM 351-PERFORM WHEN "SET" PERFORM 351-SET WHEN "STRING" PERFORM 351-STRING WHEN "SUBTRACT" PERFORM 351-SUBTRACT WHEN "TRANSFORM" PERFORM 351-TRANSFORM WHEN "UNSTRING" PERFORM 351-UNSTRING WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-ACCEPT. EVALUATE SPI-Prior-Token WHEN "ACCEPT" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-ADD. EVALUATE SPI-Prior-Token WHEN "GIVING" PERFORM 362-Release-Upd WHEN "TO" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-ALLOCATE. EVALUATE SPI-Prior-Token WHEN "ALLOCATE" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN "RETURNING" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-CALL. EVALUATE SPI-Prior-Token WHEN "RETURNING" PERFORM 362-Release-Upd WHEN "GIVING" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-COMPUTE. EVALUATE SPI-Prior-Token WHEN "COMPUTE" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-DIVIDE. EVALUATE SPI-Prior-Token WHEN "INTO" PERFORM 363-Set-Upd MOVE Sort-Rec TO Held-Reference WHEN "GIVING" IF Held-Reference NOT = SPACES MOVE Held-Reference To Sort-Rec MOVE SPACES To Held-Reference SR-Ref-Flag RELEASE Sort-Rec END-IF PERFORM 362-Release-Upd WHEN "REMAINDER" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-FREE. PERFORM 362-Release-Upd . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-INITIALIZE. EVALUATE SPI-Prior-Token WHEN "INITIALIZE" PERFORM 362-Release-Upd WHEN "REPLACING" PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-INSPECT. EVALUATE SPI-Prior-Token WHEN "INSPECT" PERFORM 364-Set-Ref MOVE SPACES TO Held-Reference MOVE SPACES TO SPI-Prior-Token WHEN "TALLYING" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN "REPLACING" IF Held-Reference NOT = SPACES MOVE Held-Reference TO Sort-Rec MOVE SPACES TO Held-Reference MOVE "*" TO SR-Ref-Flag RELEASE Sort-Rec END-IF MOVE SPACES TO SPI-Prior-Token WHEN "CONVERTING" IF Held-Reference NOT = SPACES MOVE Held-Reference TO Sort-Rec MOVE SPACES TO Held-Reference MOVE "*" TO SR-Ref-Flag RELEASE Sort-Rec END-IF MOVE SPACES TO SPI-Prior-Token WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-MOVE. EVALUATE SPI-Prior-Token WHEN "TO" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-MULTIPLY. EVALUATE SPI-Prior-Token WHEN "BY" PERFORM 363-Set-Upd MOVE Sort-Rec TO Held-Reference WHEN "GIVING" MOVE Held-Reference TO Sort-Rec MOVE SPACES TO Held-Reference SR-Ref-Flag RELEASE Sort-Rec PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-PERFORM. EVALUATE SPI-Prior-Token WHEN "VARYING" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN "AFTER" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-SET. EVALUATE SPI-Prior-Token WHEN "SET" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-STRING. EVALUATE SPI-Prior-Token WHEN "INTO" PERFORM 362-Release-Upd WHEN "POINTER" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-SUBTRACT. EVALUATE SPI-Prior-Token WHEN "GIVING" PERFORM 362-Release-Upd WHEN "FROM" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-TRANSFORM. EVALUATE SPI-Prior-Token WHEN "TRANSFORM" PERFORM 362-Release-Upd MOVE SPACES TO SPI-Prior-Token WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 351-UNSTRING. EVALUATE SPI-Prior-Token WHEN "INTO" PERFORM 362-Release-Upd WHEN "DELIMITER" PERFORM 362-Release-Upd WHEN "COUNT" PERFORM 362-Release-Upd WHEN "POINTER" PERFORM 362-Release-Upd WHEN "TALLYING" PERFORM 362-Release-Upd WHEN OTHER PERFORM 361-Release-Ref END-EVALUATE . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 360-Release-Def. MOVE SPACES TO Sort-Rec MOVE SPI-Current-Program-ID TO SR-Prog-ID MOVE SPI-Current-Token-UC TO SR-Token-UC MOVE SPI-Current-Token TO SR-Token MOVE SPI-Current-Section TO SR-Section MOVE SPI-Current-Line-No TO SR-Line-No-Def MOVE 0 TO SR-Line-No-Ref RELEASE Sort-Rec . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 361-Release-Ref. PERFORM 364-Set-Ref RELEASE Sort-Rec . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 362-Release-Upd. PERFORM 363-Set-Upd RELEASE Sort-Rec . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 363-Set-Upd. MOVE SPACES TO Sort-Rec MOVE SPI-Current-Program-ID TO SR-Prog-ID MOVE SPI-Current-Token-UC TO SR-Token-UC MOVE SPI-Current-Token TO SR-Token MOVE SPI-Current-Section TO SR-Section MOVE SPI-Current-Line-No TO SR-Line-No-Ref MOVE "*" TO SR-Ref-Flag . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 364-Set-Ref. MOVE SPACES TO Sort-Rec MOVE SPI-Current-Program-ID TO SR-Prog-ID MOVE SPI-Current-Token-UC TO SR-Token-UC MOVE SPI-Current-Token TO SR-Token MOVE SPI-Current-Section TO SR-Section MOVE SPI-Current-Line-No TO SR-Line-No-Ref . / 400-Produce-Xref-Listing SECTION. 401-Init. MOVE SPACES TO Detail-Line-X Group-Indicators MOVE 0 TO I Lines-Left GC0710 MOVE 'N' TO F-Duplicate . 402-Process-Sorted-Recs. PERFORM FOREVER RETURN Sort-File AT END EXIT PERFORM END-RETURN IF SR-Prog-ID NOT = GI-Prog-ID OR SR-Token-UC NOT = GI-Token GC0710 MOVE 'N' TO F-Duplicate IF Detail-Line-X NOT = SPACES PERFORM 410-Generate-Report-Line END-IF IF SR-Prog-ID NOT = GI-Prog-ID MOVE 0 TO Lines-Left END-IF MOVE SR-Prog-ID TO GI-Prog-ID MOVE SR-Token-UC TO GI-Token END-IF GC0710 IF SR-Token-UC = GI-Token GC0710 AND SR-Line-No-Def NOT = SPACES GC0710 AND Detail-Line-X NOT = SPACES GC0710 MOVE 'Y' TO F-Duplicate GC0710 PERFORM 410-Generate-Report-Line GC0710 MOVE 0 TO I GC0710 MOVE SR-Prog-ID TO DLX-Prog-ID GC0710 MOVE ' (Duplicate Definition)' TO DLX-Token GC0710 MOVE SR-Section TO DLX-Section GC0710 MOVE SR-Line-No-Def TO DLX-Line-No-Def GC0710 EXIT PERFORM CYCLE GC0710 END-IF GC0710 IF SR-Token-UC = GI-Token GC0710 AND SR-Line-No-Def = SPACES GC0710 AND F-Duplicate = 'Y' GC0710 MOVE 'N' TO F-Duplicate GC0710 PERFORM 410-Generate-Report-Line GC0710 MOVE 0 TO I GC0710 MOVE SR-Prog-ID TO DLX-Prog-ID GC0710 MOVE ' (Duplicate References)' TO DLX-Token GC0710 END-IF IF Detail-Line-X = SPACES MOVE SR-Prog-ID TO DLX-Prog-ID MOVE SR-Token TO DLX-Token MOVE SR-Section TO DLX-Section IF SR-Line-No-Def NOT = SPACES MOVE SR-Line-No-Def TO DLX-Line-No-Def END-IF END-IF IF SR-Reference > '000000' ADD 1 TO I IF I > Line-Nos-Per-Rec PERFORM 410-Generate-Report-Line MOVE 1 TO I END-IF MOVE SR-Line-No-Ref TO DLX-Line-No-Ref (I) MOVE SR-Ref-Flag TO DLX-Ref-Flag (I) END-IF END-PERFORM IF Detail-Line-X NOT = SPACES PERFORM 410-Generate-Report-Line END-IF EXIT SECTION . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 410-Generate-Report-Line. IF Lines-Left < 1 IF F-First-Record = "Y" MOVE "N" TO F-First-Record WRITE Report-Rec FROM Heading-1X BEFORE 1 ELSE MOVE SPACES TO Report-Rec WRITE Report-Rec BEFORE PAGE MOVE SPACES TO Report-Rec WRITE Report-Rec BEFORE 1 WRITE Report-Rec FROM Heading-1X BEFORE 1 END-IF WRITE Report-Rec FROM Heading-2 BEFORE 1 WRITE Report-Rec FROM Heading-4X BEFORE 1 WRITE Report-Rec FROM Heading-5X BEFORE 1 COMPUTE Lines-Left = Lines-Per-Page - 4 END-COMPUTE END-IF WRITE Report-Rec FROM Detail-Line-X BEFORE 1 MOVE SPACES TO Detail-Line-X MOVE 0 TO I SUBTRACT 1 FROM Lines-Left . / 500-Produce-Source-Listing SECTION. 501-Generate-Source-Listing. OPEN INPUT Source-Code Expand-Code MOVE 0 TO Source-Line-No PERFORM FOREVER READ Expand-Code AT END EXIT PERFORM END-READ IF ECR-1 = "#" PERFORM 510-Control-Record ELSE PERFORM 520-Expand-Code-Record END-IF END-PERFORM CLOSE Source-Code Expand-Code EXIT SECTION . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 510-Control-Record. UNSTRING ECR-2-256 DELIMITED BY '"' INTO PIC-X10, PIC-X256, Dummy END-UNSTRING IF TRIM(PIC-X256,Trailing) = TRIM(Program-Path,Trailing) *> Main Pgm SET In-Main-Module TO TRUE IF Source-Line-No > 0 READ Expand-Code END-READ END-IF ELSE *> COPY SET In-Copybook TO TRUE END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 520-Expand-Code-Record. IF In-Main-Module ADD 1 To SPI-Current-Line-No READ Source-Code AT END NEXT SENTENCE END-READ ADD 1 TO Source-Line-No MOVE SPACES TO Detail-Line-S MOVE Source-Line-No TO DLS-Line-No MOVE SCR-1-128 TO DLS-Statement GC0410 IF SCR-7 = "/" GC0410 MOVE 0 TO Lines-Left GC0410 END-IF PERFORM 530-Generate-Source-Line IF SCR-129-256 NOT = SPACES MOVE SPACES TO Detail-Line-S MOVE SCR-129-256 TO DLS-Statement PERFORM 530-Generate-Source-Line END-IF ELSE IF Expand-Code-Rec NOT = SPACES MOVE SPACES TO Detail-Line-S MOVE ECR-1-128 TO DLS-Statement PERFORM 530-Generate-Source-Line IF ECR-129-256 NOT = SPACES MOVE SPACES TO Detail-Line-S MOVE ECR-129-256 TO DLS-Statement PERFORM 530-Generate-Source-Line END-IF END-IF END-IF . *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 530-Generate-Source-Line. IF Lines-Left < 1 IF F-First-Record = "Y" MOVE "N" TO F-First-Record WRITE Report-Rec FROM Heading-1S BEFORE 1 ELSE MOVE SPACES TO Report-Rec WRITE Report-Rec BEFORE PAGE MOVE SPACES TO Report-Rec WRITE Report-Rec BEFORE 1 WRITE Report-Rec FROM Heading-1S BEFORE 1 END-IF WRITE Report-Rec FROM Heading-2 BEFORE 1 WRITE Report-Rec FROM Heading-4S BEFORE 1 WRITE Report-Rec FROM Heading-5S BEFORE 1 COMPUTE Lines-Left = Lines-Per-Page - 4 END-COMPUTE END-IF WRITE Report-Rec FROM Detail-Line-S BEFORE 1 MOVE SPACES TO Detail-Line-S SUBTRACT 1 FROM Lines-Left . END PROGRAM LISTING. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.coffee000066400000000000000000000003731250413007300264770ustar00rootroot00000000000000# function arrows methodA:-> 'A' methodB:=> 'B' methodC:()=> 'C' methodD:()-> 'D' methodE:(a,b)-> 'E' methodF:(c,d)-> 'F' -> 'G' => 'H' (-> 'I') (=> 'J') # strings "#{wow}" "w#{wow}w" "#wow" "wow#" "w#ow" '#{wow}' 'w#{wow}w' '#wow' 'wow#' 'w#ow' pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.cpp000066400000000000000000002330141250413007300260320ustar00rootroot00000000000000/*************************************************************************** ansigenerator.cpp - description ------------------- begin : Jul 5 2004 copyright : (C) 2004 by André Simon email : andre.simon1@gmx.de ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "ansigenerator.h" using namespace std; namespace highlight { string AnsiGenerator::getOpenTag(const string&font, const string&fgCol, const string&bgCol) { ostringstream s; s << "\033["< #include #include #include #include "codegenerator.h" #include "charcodes.h" #include "version.h" namespace highlight { /** \brief This class generates ANSI escape sequences. It contains information about the resulting document structure (document header and footer), the colour system, white space handling and text formatting attributes. * @author Andre Simon */ class AnsiGenerator : public highlight::CodeGenerator { public: /** Constructor \param colourTheme Name of Colour theme to use */ AnsiGenerator( const string &colourTheme); AnsiGenerator(); ~AnsiGenerator(); /** prints document header \param title Title of the document */ string getHeader(const string & title); /** Prints document footer*/ string getFooter(); /** Prints document body*/ void printBody(); private: /** \return escaped character*/ virtual string maskCharacter(unsigned char ); /** gibt ANSI-"Tags" zurueck (Farbindex+bold+kursiv)*/ string getOpenTag(const string&font, const string&fgCol, const string&bgCol=""); string getMatchingOpenTag(unsigned int styleID); string getMatchingCloseTag(unsigned int styleID); }; } #endif /* * Copyright (c) 1998,1999,2000,2001,2002 Tal Davidson. All rights reserved. * * ASBeautifier.cpp * by Tal Davidson (davidsont@bigfoot.com) * This file is a part of "Artistic Style" - an indentater and reformatter * of C, C, C# and Java source files. * * The "Artistic Style" project, including all files needed to compile it, * is free software; you can redistribute it and/or use it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public * License along with this program. * * Patches: * 18 March 1999 - Brian Rampel - * Fixed inverse insertion of spaces vs. tabs when in -t mode. * 08 may 2004 * applied ASBeautifier.cpp.BITFIELD.patch.bz2 */ #include "compiler_defines.h" #include "ASBeautifier.h" #include #include #include #include #include #define INIT_CONTAINER(container, value) {if ( (container) != NULL ) delete (container); (container) = (value); } #define DELETE_CONTAINER(container) {if ( (container) != NULL ) delete (container) ; } #ifdef USES_NAMESPACE using namespace std; #endif #ifdef USES_NAMESPACE namespace astyle { #endif bool ASBeautifier::calledInitStatic = false; vector ASBeautifier::headers; vector ASBeautifier::nonParenHeaders; vector ASBeautifier::preBlockStatements; vector ASBeautifier::assignmentOperators; vector ASBeautifier::nonAssignmentOperators; /* * initialize the static vars */ void ASBeautifier::initStatic() { if (calledInitStatic) return; calledInitStatic = true; headers.push_back(&AS_IF); headers.push_back(&AS_ELSE); headers.push_back(&AS_FOR); headers.push_back(&AS_WHILE); headers.push_back(&AS_DO); headers.push_back(&AS_TRY); headers.push_back(&AS_CATCH); headers.push_back(&AS_FINALLY); headers.push_back(&AS_SYNCHRONIZED); headers.push_back(&AS_SWITCH); headers.push_back(&AS_CASE); headers.push_back(&AS_DEFAULT); headers.push_back(&AS_FOREACH); headers.push_back(&AS_LOCK); headers.push_back(&AS_UNSAFE); headers.push_back(&AS_FIXED); headers.push_back(&AS_GET); headers.push_back(&AS_SET); headers.push_back(&AS_ADD); headers.push_back(&AS_REMOVE); //headers.push_back(&AS_PUBLIC); //headers.push_back(&AS_PRIVATE); //headers.push_back(&AS_PROTECTED); //headers.push_back(&AS_OPERATOR); headers.push_back(&AS_TEMPLATE); headers.push_back(&AS_CONST); /**/ headers.push_back(&AS_STATIC); headers.push_back(&AS_EXTERN); nonParenHeaders.push_back(&AS_ELSE); nonParenHeaders.push_back(&AS_DO); nonParenHeaders.push_back(&AS_TRY); nonParenHeaders.push_back(&AS_FINALLY); nonParenHeaders.push_back(&AS_STATIC); nonParenHeaders.push_back(&AS_CONST); nonParenHeaders.push_back(&AS_EXTERN); nonParenHeaders.push_back(&AS_CASE); nonParenHeaders.push_back(&AS_DEFAULT); nonParenHeaders.push_back(&AS_UNSAFE); nonParenHeaders.push_back(&AS_GET); nonParenHeaders.push_back(&AS_SET); nonParenHeaders.push_back(&AS_ADD); nonParenHeaders.push_back(&AS_REMOVE); nonParenHeaders.push_back(&AS_PUBLIC); nonParenHeaders.push_back(&AS_PRIVATE); nonParenHeaders.push_back(&AS_PROTECTED); nonParenHeaders.push_back(&AS_TEMPLATE); nonParenHeaders.push_back(&AS_CONST); /// nonParenHeaders.push_back(&AS_ASM); preBlockStatements.push_back(&AS_CLASS); preBlockStatements.push_back(&AS_STRUCT); preBlockStatements.push_back(&AS_UNION); preBlockStatements.push_back(&AS_INTERFACE); preBlockStatements.push_back(&AS_NAMESPACE); preBlockStatements.push_back(&AS_THROWS); preBlockStatements.push_back(&AS_EXTERN); assignmentOperators.push_back(&AS_ASSIGN); assignmentOperators.push_back(&AS_PLUS_ASSIGN); assignmentOperators.push_back(&AS_MINUS_ASSIGN); assignmentOperators.push_back(&AS_MULT_ASSIGN); assignmentOperators.push_back(&AS_DIV_ASSIGN); assignmentOperators.push_back(&AS_MOD_ASSIGN); assignmentOperators.push_back(&AS_OR_ASSIGN); assignmentOperators.push_back(&AS_AND_ASSIGN); assignmentOperators.push_back(&AS_XOR_ASSIGN); assignmentOperators.push_back(&AS_GR_GR_GR_ASSIGN); assignmentOperators.push_back(&AS_GR_GR_ASSIGN); assignmentOperators.push_back(&AS_LS_LS_LS_ASSIGN); assignmentOperators.push_back(&AS_LS_LS_ASSIGN); assignmentOperators.push_back(&AS_RETURN); nonAssignmentOperators.push_back(&AS_EQUAL); nonAssignmentOperators.push_back(&AS_PLUS_PLUS); nonAssignmentOperators.push_back(&AS_MINUS_MINUS); nonAssignmentOperators.push_back(&AS_NOT_EQUAL); nonAssignmentOperators.push_back(&AS_GR_EQUAL); nonAssignmentOperators.push_back(&AS_GR_GR_GR); nonAssignmentOperators.push_back(&AS_GR_GR); nonAssignmentOperators.push_back(&AS_LS_EQUAL); nonAssignmentOperators.push_back(&AS_LS_LS_LS); nonAssignmentOperators.push_back(&AS_LS_LS); nonAssignmentOperators.push_back(&AS_ARROW); nonAssignmentOperators.push_back(&AS_AND); nonAssignmentOperators.push_back(&AS_OR); } /** * ASBeautifier's constructor */ ASBeautifier::ASBeautifier() { initStatic(); waitingBeautifierStack = NULL; activeBeautifierStack = NULL; waitingBeautifierStackLengthStack = NULL; activeBeautifierStackLengthStack = NULL; headerStack = NULL; tempStacks = NULL; blockParenDepthStack = NULL; blockStatementStack = NULL; parenStatementStack = NULL; bracketBlockStateStack = NULL; inStatementIndentStack = NULL; inStatementIndentStackSizeStack = NULL; parenIndentStack = NULL; sourceIterator = NULL; isMinimalConditinalIndentSet = false; shouldForceTabIndentation = false; setSpaceIndentation(4); setMaxInStatementIndentLength(40); setClassIndent(false); setSwitchIndent(false); setCaseIndent(false); setBlockIndent(false); setBracketIndent(false); setNamespaceIndent(false); setLabelIndent(false); setEmptyLineFill(false); setCStyle(); setPreprocessorIndent(false); } ASBeautifier::ASBeautifier(const ASBeautifier &other) { waitingBeautifierStack = NULL; activeBeautifierStack = NULL; waitingBeautifierStackLengthStack = NULL; activeBeautifierStackLengthStack = NULL; headerStack = new vector; *headerStack = *other.headerStack; tempStacks = new vector< vector* >; vector< vector* >::iterator iter; for (iter = other.tempStacks->begin(); iter != other.tempStacks->end(); ++iter) { vector *newVec = new vector; *newVec = **iter; tempStacks->push_back(newVec); } blockParenDepthStack = new vector; *blockParenDepthStack = *other.blockParenDepthStack; blockStatementStack = new vector; *blockStatementStack = *other.blockStatementStack; parenStatementStack = new vector; *parenStatementStack = *other.parenStatementStack; bracketBlockStateStack = new vector; *bracketBlockStateStack = *other.bracketBlockStateStack; inStatementIndentStack = new vector; *inStatementIndentStack = *other.inStatementIndentStack; inStatementIndentStackSizeStack = new vector; *inStatementIndentStackSizeStack = *other.inStatementIndentStackSizeStack; parenIndentStack = new vector; *parenIndentStack = *other.parenIndentStack; sourceIterator = other.sourceIterator; indentString = other.indentString; currentHeader = other.currentHeader; previousLastLineHeader = other.previousLastLineHeader; immediatelyPreviousAssignmentOp = other.immediatelyPreviousAssignmentOp; isInQuote = other.isInQuote; isInComment = other.isInComment; isInCase = other.isInCase; isInQuestion = other.isInQuestion; isInStatement =other. isInStatement; isInHeader = other.isInHeader; isCStyle = other.isCStyle; isInOperator = other.isInOperator; isInTemplate = other.isInTemplate; isInConst = other.isInConst; classIndent = other.classIndent; isInClassHeader = other.isInClassHeader; isInClassHeaderTab = other.isInClassHeaderTab; switchIndent = other.switchIndent; caseIndent = other.caseIndent; namespaceIndent = other.namespaceIndent; bracketIndent = other.bracketIndent; blockIndent = other.blockIndent; labelIndent = other.labelIndent; preprocessorIndent = other.preprocessorIndent; parenDepth = other.parenDepth; indentLength = other.indentLength; blockTabCount = other.blockTabCount; leadingWhiteSpaces = other.leadingWhiteSpaces; maxInStatementIndent = other.maxInStatementIndent; templateDepth = other.templateDepth; quoteChar = other.quoteChar; prevNonSpaceCh = other.prevNonSpaceCh; currentNonSpaceCh = other.currentNonSpaceCh; currentNonLegalCh = other.currentNonLegalCh; prevNonLegalCh = other.prevNonLegalCh; isInConditional = other.isInConditional; minConditionalIndent = other.minConditionalIndent; prevFinalLineSpaceTabCount = other.prevFinalLineSpaceTabCount; prevFinalLineTabCount = other.prevFinalLineTabCount; emptyLineFill = other.emptyLineFill; probationHeader = other.probationHeader; isInDefine = other.isInDefine; isInDefineDefinition = other.isInDefineDefinition; backslashEndsPrevLine = other.backslashEndsPrevLine; defineTabCount = other.defineTabCount; } /** * ASBeautifier's destructor */ ASBeautifier::~ASBeautifier() { DELETE_CONTAINER( headerStack ); DELETE_CONTAINER( tempStacks ); DELETE_CONTAINER( blockParenDepthStack ); DELETE_CONTAINER( blockStatementStack ); DELETE_CONTAINER( parenStatementStack ); DELETE_CONTAINER( bracketBlockStateStack ); DELETE_CONTAINER( inStatementIndentStack ); DELETE_CONTAINER( inStatementIndentStackSizeStack ); DELETE_CONTAINER( parenIndentStack ); // DELETE_CONTAINER( sourceIterator ); } /** * initialize the ASBeautifier. * * init() should be called every time a ABeautifier object is to start * beautifying a NEW source file. * init() recieves a pointer to a DYNAMICALLY CREATED ASSourceIterator object * that will be used to iterate through the source code. This object will be * deleted during the ASBeautifier's destruction, and thus should not be * deleted elsewhere. * * @param iter a pointer to the DYNAMICALLY CREATED ASSourceIterator object. */ void ASBeautifier::init(ASSourceIterator *iter) { sourceIterator = iter; init(); } /** * initialize the ASBeautifier. */ void ASBeautifier::init() { INIT_CONTAINER( waitingBeautifierStack, new vector ); INIT_CONTAINER( activeBeautifierStack, new vector ); INIT_CONTAINER( waitingBeautifierStackLengthStack, new vector ); INIT_CONTAINER( activeBeautifierStackLengthStack, new vector ); INIT_CONTAINER( headerStack, new vector ); INIT_CONTAINER( tempStacks, new vector< vector* > ); tempStacks->push_back(new vector); INIT_CONTAINER( blockParenDepthStack, new vector ); INIT_CONTAINER( blockStatementStack, new vector ); INIT_CONTAINER( parenStatementStack, new vector ); INIT_CONTAINER( bracketBlockStateStack, new vector ); bracketBlockStateStack->push_back(true); INIT_CONTAINER( inStatementIndentStack, new vector ); INIT_CONTAINER( inStatementIndentStackSizeStack, new vector ); inStatementIndentStackSizeStack->push_back(0); INIT_CONTAINER( parenIndentStack, new vector ); immediatelyPreviousAssignmentOp = NULL; previousLastLineHeader = NULL; isInQuote = false; isInComment = false; isInStatement = false; isInCase = false; isInQuestion = false; isInClassHeader = false; isInClassHeaderTab = false; isInHeader = false; isInOperator = false; isInTemplate = false; isInConst = false; isInConditional = false; templateDepth = 0; parenDepth=0; blockTabCount = 0; leadingWhiteSpaces = 0; prevNonSpaceCh = '{'; currentNonSpaceCh = '{'; prevNonLegalCh = '{'; currentNonLegalCh = '{'; prevFinalLineSpaceTabCount = 0; prevFinalLineTabCount = 0; probationHeader = NULL; backslashEndsPrevLine = false; isInDefine = false; isInDefineDefinition = false; defineTabCount = 0; } /** * set indentation style to ANSI C/C++. */ void ASBeautifier::setCStyle() { isCStyle = true; } /** * set indentation style to Java / K&R. */ void ASBeautifier::setJavaStyle() { isCStyle = false; } /** * indent using one tab per indentation */ void ASBeautifier::setTabIndentation(int length, bool forceTabs) { indentString = "\t"; indentLength = length; shouldForceTabIndentation = forceTabs; if (!isMinimalConditinalIndentSet) minConditionalIndent = indentLength * 2; } /** * indent using a number of spaces per indentation. * * @param length number of spaces per indent. */ void ASBeautifier::setSpaceIndentation(int length) { indentString=string(length, ' '); indentLength = length; if (!isMinimalConditinalIndentSet) minConditionalIndent = indentLength * 2; } /** * set the maximum indentation between two lines in a multi-line statement. * * @param max maximum indentation length. */ void ASBeautifier::setMaxInStatementIndentLength(int max) { maxInStatementIndent = max; } /** * set the minimum indentation between two lines in a multi-line condition. * * @param min minimal indentation length. */ void ASBeautifier::setMinConditionalIndentLength(int min) { minConditionalIndent = min; isMinimalConditinalIndentSet = true; } /** * set the state of the bracket indentation option. If true, brackets will * be indented one additional indent. * * @param state state of option. */ void ASBeautifier::setBracketIndent(bool state) { bracketIndent = state; } /** * set the state of the block indentation option. If true, entire blocks * will be indented one additional indent, similar to the GNU indent style. * * @param state state of option. */ void ASBeautifier::setBlockIndent(bool state) { if (state) setBracketIndent(false); // so that we don't have both bracket and block indent blockIndent = state; } /** * set the state of the class indentation option. If true, C++ class * definitions will be indented one additional indent. * * @param state state of option. */ void ASBeautifier::setClassIndent(bool state) { classIndent = state; } /** * set the state of the switch indentation option. If true, blocks of 'switch' * statements will be indented one additional indent. * * @param state state of option. */ void ASBeautifier::setSwitchIndent(bool state) { switchIndent = state; } /** * set the state of the case indentation option. If true, lines of 'case' * statements will be indented one additional indent. * * @param state state of option. */ void ASBeautifier::setCaseIndent(bool state) { caseIndent = state; } /** * set the state of the namespace indentation option. * If true, blocks of 'namespace' statements will be indented one * additional indent. Otherwise, NO indentation will be added. * * @param state state of option. */ void ASBeautifier::setNamespaceIndent(bool state) { namespaceIndent = state; } /** * set the state of the label indentation option. * If true, labels will be indented one indent LESS than the * current indentation level. * If false, labels will be flushed to the left with NO * indent at all. * * @param state state of option. */ void ASBeautifier::setLabelIndent(bool state) { labelIndent = state; } /** * set the state of the preprocessor indentation option. * If true, multiline #define statements will be indented. * * @param state state of option. */ void ASBeautifier::setPreprocessorIndent(bool state) { preprocessorIndent = state; } /** * set the state of the empty line fill option. * If true, empty lines will be filled with the whitespace. * of their previous lines. * If false, these lines will remain empty. * * @param state state of option. */ void ASBeautifier::setEmptyLineFill(bool state) { emptyLineFill = state; } /** * check if there are any indented lines ready to be read by nextLine() * * @return are there any indented lines ready? */ bool ASBeautifier::hasMoreLines() const { return sourceIterator->hasMoreLines(); } /** * get the next indented line. * * @return indented line. */ string ASBeautifier::nextLine() { return beautify(sourceIterator->nextLine()); } /** * beautify a line of source code. * every line of source code in a source code file should be sent * one after the other to the beautify method. * * @return the indented line. * @param originalLine the original unindented line. */ string ASBeautifier::beautify(const string &originalLine) { string line; bool isInLineComment = false; bool lineStartsInComment = false; bool isInClass = false; bool isInSwitch = false; bool isImmediatelyAfterConst = false; bool isSpecialChar = false; char ch = ' '; char prevCh; string outBuffer; // the newly idented line is bufferd here int tabCount = 0; const string *lastLineHeader = NULL; bool closingBracketReached = false; int spaceTabCount = 0; char tempCh; unsigned int headerStackSize = headerStack->size(); //bool isLineInStatement = isInStatement; bool shouldIndentBrackettedLine = true; int lineOpeningBlocksNum = 0; int lineClosingBlocksNum = 0; bool previousLineProbation = (probationHeader != NULL); unsigned int i; currentHeader = NULL; lineStartsInComment = isInComment; // handle and remove white spaces around the line: // If not in comment, first find out size of white space before line, // so that possible comments starting in the line continue in // relation to the preliminary white-space. if (!isInComment) { leadingWhiteSpaces = 0; while (leadingWhiteSpacesinit(); //defineBeautifier->isInDefineDefinition = true; //defineBeautifier->beautify(""); activeBeautifierStack->push_back(defineBeautifier); } else { // the is the cloned beautifier that is in charge of indenting the #define. isInDefine = true; } } else if (preproc.COMPARE(0, 2, string("if")) == 0) { // push a new beautifier into the stack waitingBeautifierStackLengthStack->push_back(waitingBeautifierStack->size()); activeBeautifierStackLengthStack->push_back(activeBeautifierStack->size()); waitingBeautifierStack->push_back(new ASBeautifier(*this)); } else if (preproc.COMPARE(0, 4/*2*/, string("else")) == 0) { if (!waitingBeautifierStack->empty()) { // MOVE current waiting beautifier to active stack. activeBeautifierStack->push_back(waitingBeautifierStack->back()); waitingBeautifierStack->pop_back(); } } else if (preproc.COMPARE(0, 4, string("elif")) == 0) { if (!waitingBeautifierStack->empty()) { // append a COPY current waiting beautifier to active stack, WITHOUT deleting the original. activeBeautifierStack->push_back( new ASBeautifier( *(waitingBeautifierStack->back()) ) ); } } else if (preproc.COMPARE(0, 5, string("endif")) == 0) { unsigned int stackLength; ASBeautifier *beautifier; if (!waitingBeautifierStackLengthStack->empty()) { stackLength = waitingBeautifierStackLengthStack->back(); waitingBeautifierStackLengthStack->pop_back(); while (waitingBeautifierStack->size() > stackLength) { beautifier = waitingBeautifierStack->back(); waitingBeautifierStack->pop_back(); delete beautifier; } } if (!activeBeautifierStackLengthStack->empty()) { stackLength = activeBeautifierStackLengthStack->back(); activeBeautifierStackLengthStack->pop_back(); while (activeBeautifierStack->size() > stackLength) { beautifier = activeBeautifierStack->back(); activeBeautifierStack->pop_back(); delete beautifier; } } } } // check if the last char is a backslash if(line.length() > 0) backslashEndsPrevLine = (line[line.length() - 1] == '\\'); else backslashEndsPrevLine = false; // check if this line ends a multi-line #define // if so, use the #define's cloned beautifier for the line's indentation // and then remove it from the active beautifier stack and delete it. if (!backslashEndsPrevLine && isInDefineDefinition && !isInDefine) { string beautifiedLine; ASBeautifier *defineBeautifier; isInDefineDefinition = false; defineBeautifier = activeBeautifierStack->back(); activeBeautifierStack->pop_back(); beautifiedLine = defineBeautifier->beautify(line); delete defineBeautifier; return beautifiedLine; } // unless this is a multi-line #define, return this precompiler line as is. if (!isInDefine && !isInDefineDefinition) return originalLine; } // if there exists any worker beautifier in the activeBeautifierStack, // then use it instead of me to indent the current line. if (!isInDefine && activeBeautifierStack != NULL && !activeBeautifierStack->empty()) { return activeBeautifierStack->back()->beautify(line); } // calculate preliminary indentation based on data from past lines if (!inStatementIndentStack->empty()) spaceTabCount = inStatementIndentStack->back(); for (i=0; i0 && (*headerStack)[i-1] != &AS_OPEN_BRACKET && (*headerStack)[i] == &AS_OPEN_BRACKET))) ++tabCount; if (isCStyle && !namespaceIndent && i >= 1 && (*headerStack)[i-1] == &AS_NAMESPACE && (*headerStack)[i] == &AS_OPEN_BRACKET) --tabCount; if (isCStyle && i >= 1 && (*headerStack)[i-1] == &AS_CLASS && (*headerStack)[i] == &AS_OPEN_BRACKET ) { if (classIndent) ++tabCount; isInClass = true; } // is the switchIndent option is on, indent switch statements an additional indent. else if (switchIndent && i > 1 && (*headerStack)[i-1] == &AS_SWITCH && (*headerStack)[i] == &AS_OPEN_BRACKET ) { ++tabCount; isInSwitch = true; } } if (!lineStartsInComment && isCStyle && isInClass && classIndent && headerStackSize >= 2 &&(*headerStack)[headerStackSize-2] == &AS_CLASS && (*headerStack)[headerStackSize-1] == &AS_OPEN_BRACKET && line[0] == '}') --tabCount; else if (!lineStartsInComment && isInSwitch && switchIndent && headerStackSize >= 2 && (*headerStack)[headerStackSize-2] == &AS_SWITCH && (*headerStack)[headerStackSize-1] == &AS_OPEN_BRACKET && line[0] == '}') --tabCount; if (isInClassHeader) { isInClassHeaderTab = true; tabCount += 2; } if (isInConditional) { --tabCount; } // parse characters in the current line. for (i=0; ipush_back(probationHeader); // handle the specific probation header isInConditional = (probationHeader == &AS_SYNCHRONIZED); if (probationHeader == &AS_CONST) isImmediatelyAfterConst = true; // isInConst = true; /* TODO: * There is actually no more need for the global isInConst variable. * The only reason for checking const is to see if there is a const * immediately before an open-bracket. * Since CONST is now put into probation and is checked during itspost-char, * isImmediatelyAfterConst can be set by its own... */ isInStatement = false; // if the probation comes from the previous line, then indent by 1 tab count. if (previousLineProbation && ch == '{') tabCount++; previousLineProbation = false; } // dismiss the probation header probationHeader = NULL; } prevNonSpaceCh = currentNonSpaceCh; currentNonSpaceCh = ch; if (!isLegalNameChar(ch) && ch != ',' && ch != ';' ) { prevNonLegalCh = currentNonLegalCh; currentNonLegalCh = ch; } //if (isInConst) //{ // isInConst = false; // isImmediatelyAfterConst = true; //} if (isInHeader) { isInHeader = false; currentHeader = headerStack->back(); } else currentHeader = NULL; if (isCStyle && isInTemplate && (ch == '<' || ch == '>') && findHeader(line, i, nonAssignmentOperators) == NULL) //; { if (ch == '<') { ++templateDepth; } else if (ch == '>') { if (--templateDepth <= 0) { if (isInTemplate) ch = ';'; else ch = 't'; isInTemplate = false; templateDepth = 0; } } } // handle parenthesies if (ch == '(' || ch == '[' || ch == ')' || ch == ']') { if (ch == '(' || ch == '[') { if (parenDepth == 0) { parenStatementStack->push_back(isInStatement); isInStatement = true; } parenDepth++; inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); if (currentHeader != NULL) registerInStatementIndent(line, i, spaceTabCount, minConditionalIndent/*indentLength*2*/, true); else registerInStatementIndent(line, i, spaceTabCount, 0, true); } else if (ch == ')' || ch == ']') { parenDepth--; if (parenDepth == 0) { isInStatement = parenStatementStack->back(); parenStatementStack->pop_back(); ch = ' '; isInConditional = false; } if (!inStatementIndentStackSizeStack->empty()) { unsigned int previousIndentStackSize = inStatementIndentStackSizeStack->back(); inStatementIndentStackSizeStack->pop_back(); while (previousIndentStackSize < inStatementIndentStack->size()) inStatementIndentStack->pop_back(); if (!parenIndentStack->empty()) { int poppedIndent = parenIndentStack->back(); parenIndentStack->pop_back(); if (i == 0) spaceTabCount = poppedIndent; } } } continue; } if (ch == '{') { bool isBlockOpener = false; // first, check if '{' is a block-opener or an static-array opener isBlockOpener = ( (prevNonSpaceCh == '{' && bracketBlockStateStack->back()) || prevNonSpaceCh == '}' || prevNonSpaceCh == ')' || prevNonSpaceCh == ';' || isInClassHeader || isBlockOpener || isImmediatelyAfterConst || (isInDefine && (prevNonSpaceCh == '(' || prevNonSpaceCh == '_' || isalnum(prevNonSpaceCh))) ); isInClassHeader = false; if (!isBlockOpener && currentHeader != NULL) { for (unsigned int n=0; n < nonParenHeaders.size(); n++) if (currentHeader == nonParenHeaders[n]) { isBlockOpener = true; break; } } bracketBlockStateStack->push_back(isBlockOpener); if (!isBlockOpener) { inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); registerInStatementIndent(line, i, spaceTabCount, 0, true); parenDepth++; if (i == 0) shouldIndentBrackettedLine = false; continue; } // this bracket is a block opener... ++lineOpeningBlocksNum; if (isInClassHeader) isInClassHeader = false; if (isInClassHeaderTab) { isInClassHeaderTab = false; tabCount -= 2; } blockParenDepthStack->push_back(parenDepth); blockStatementStack->push_back(isInStatement); inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); blockTabCount += isInStatement? 1 : 0; parenDepth = 0; isInStatement = false; tempStacks->push_back(new vector); headerStack->push_back(&AS_OPEN_BRACKET); lastLineHeader = &AS_OPEN_BRACKET; // <------ continue; } //check if a header has been reached if (prevCh == ' ') { bool isIndentableHeader = true; const string *newHeader = findHeader(line, i, headers); if (newHeader != NULL) { // if we reached here, then this is a header... isInHeader = true; vector *lastTempStack; if (tempStacks->empty()) lastTempStack = NULL; else lastTempStack = tempStacks->back(); // if a new block is opened, push a new stack into tempStacks to hold the // future list of headers in the new block. // take care of the special case: 'else if (...)' if (newHeader == &AS_IF && lastLineHeader == &AS_ELSE) { //spaceTabCount += indentLength; // to counter the opposite addition that occurs when the 'if' is registered below... headerStack->pop_back(); } // take care of 'else' else if (newHeader == &AS_ELSE) { if (lastTempStack != NULL) { int indexOfIf = indexOf(*lastTempStack, &AS_IF); // <--- if (indexOfIf != -1) { // recreate the header list in headerStack up to the previous 'if' // from the temporary snapshot stored in lastTempStack. int restackSize = lastTempStack->size() - indexOfIf - 1; for (int r=0; rpush_back(lastTempStack->back()); lastTempStack->pop_back(); } if (!closingBracketReached) tabCount += restackSize; } /* * If the above if is not true, i.e. no 'if' before the 'else', * then nothing beautiful will come out of this... * I should think about inserting an Exception here to notify the caller of this... */ } } // check if 'while' closes a previous 'do' else if (newHeader == &AS_WHILE) { if (lastTempStack != NULL) { int indexOfDo = indexOf(*lastTempStack, &AS_DO); // <--- if (indexOfDo != -1) { // recreate the header list in headerStack up to the previous 'do' // from the temporary snapshot stored in lastTempStack. int restackSize = lastTempStack->size() - indexOfDo - 1; for (int r=0; rpush_back(lastTempStack->back()); lastTempStack->pop_back(); } if (!closingBracketReached) tabCount += restackSize; } } } // check if 'catch' closes a previous 'try' or 'catch' else if (newHeader == &AS_CATCH || newHeader == &AS_FINALLY) { if (lastTempStack != NULL) { int indexOfTry = indexOf(*lastTempStack, &AS_TRY); if (indexOfTry == -1) indexOfTry = indexOf(*lastTempStack, &AS_CATCH); if (indexOfTry != -1) { // recreate the header list in headerStack up to the previous 'try' // from the temporary snapshot stored in lastTempStack. int restackSize = lastTempStack->size() - indexOfTry - 1; for (int r=0; rpush_back(lastTempStack->back()); lastTempStack->pop_back(); } if (!closingBracketReached) tabCount += restackSize; } } } else if (newHeader == &AS_CASE) { isInCase = true; if (!caseIndent) --tabCount; } else if(newHeader == &AS_DEFAULT) { isInCase = true; if (!caseIndent) --tabCount; } else if (newHeader == &AS_PUBLIC || newHeader == &AS_PROTECTED || newHeader == &AS_PRIVATE) { if (isCStyle && !isInClassHeader) --tabCount; isIndentableHeader = false; } //else if ((newHeader == &STATIC || newHeader == &SYNCHRONIZED) && // !headerStack->empty() && // (headerStack->back() == &STATIC || headerStack->back() == &SYNCHRONIZED)) //{ // isIndentableHeader = false; //} else if (newHeader == &AS_STATIC || newHeader == &AS_SYNCHRONIZED || (newHeader == &AS_CONST && isCStyle)) { if (!headerStack->empty() && (headerStack->back() == &AS_STATIC || headerStack->back() == &AS_SYNCHRONIZED || headerStack->back() == &AS_CONST)) { isIndentableHeader = false; } else { isIndentableHeader = false; probationHeader = newHeader; } } else if (newHeader == &AS_CONST) { // this will be entered only if NOT in C style // since otherwise the CONST would be found to be a probstion header... //if (isCStyle) // isInConst = true; isIndentableHeader = false; } /* else if (newHeader == &OPERATOR) { if (isCStyle) isInOperator = true; isIndentableHeader = false; } */ else if (newHeader == &AS_TEMPLATE) { if (isCStyle) isInTemplate = true; isIndentableHeader = false; } if (isIndentableHeader) { // 3.2.99 //spaceTabCount-=indentLength; headerStack->push_back(newHeader); isInStatement = false; if (indexOf(nonParenHeaders, newHeader) == -1) { isInConditional = true; } lastLineHeader = newHeader; } else isInHeader = false; //lastLineHeader = newHeader; outBuffer.append(newHeader->substr(1)); i += newHeader->length() - 1; continue; } } if (isCStyle && !isalpha(prevCh) && line.COMPARE(i, 8, AS_OPERATOR) == 0 && !isalnum(line[i+8])) { isInOperator = true; outBuffer.append(AS_OPERATOR.substr(1)); i += 7; continue; } if (ch == '?') isInQuestion = true; // special handling of 'case' statements if (ch == ':') { if (line.length() > i+1 && line[i+1] == ':') // look for :: { ++i; outBuffer.append(1, ':'); ch = ' '; continue; } else if (isCStyle && isInClass && prevNonSpaceCh != ')') { // BEGIN Content of ASBeautifier.cpp.BITFIELD.patch: unsigned int chIndex; char nextCh = 0; for (chIndex = i+1; chIndex < line.length(); chIndex++) if (!isWhiteSpace(line[chIndex])) break; if (chIndex< line.length()) nextCh = line[chIndex]; int nWord =0; for (chIndex = 0; chIndex < i; chIndex++) { if (!isWhiteSpace(line[chIndex])) { nWord ++; while (!isWhiteSpace(line[++chIndex])); } } if ((nextCh >= '0' && nextCh <= '9') || (nWord >1)) continue; // END Content of ASBeautifier.cpp.BITFIELD.patch: --tabCount; // found a 'private:' or 'public:' inside a class definition // so do nothing special } else if (isCStyle && isInClassHeader) { // found a 'class A : public B' definition // so do nothing special } else if (isInQuestion) { isInQuestion = false; } else if (isCStyle && prevNonSpaceCh == ')') { isInClassHeader = true; if (i==0) tabCount += 2; } else { currentNonSpaceCh = ';'; // so that brackets after the ':' will appear as block-openers if (isInCase) { isInCase = false; ch = ';'; // from here on, treat char as ';' } // BEGIN content of ASBeautifier.cpp.BITFIELD.patch.bz2 else // bitfield or labels { unsigned int chIndex; char nextCh = 0; for (chIndex = i+1; (isCStyle && chIndex < line.length()); chIndex++) if (!isWhiteSpace(line[chIndex])) break; if (chIndex< line.length()) nextCh = line[chIndex]; int nWord =0; for (chIndex = 0; chIndex < i; chIndex++) { if (!isWhiteSpace(line[chIndex])) { nWord ++; while (!isWhiteSpace(line[++chIndex])); } } if (isCStyle && (nextCh >= '0' && nextCh <= '9') || (nWord >1)) { continue; } // END content of ASASBeautifier.cpp.BITFIELD.patch.bz2 else // is in a label (e.g. 'label1:') { if (labelIndent) --tabCount; // unindent label by one indent else tabCount = 0; // completely flush indent to left } // BEGIN content of ASASBeautifier.cpp.BITFIELD.patch.bz2 } // END content of ASASBeautifier.cpp.BITFIELD.patch.bz2 } } if ((ch == ';' || (parenDepth>0 && ch == ',')) && !inStatementIndentStackSizeStack->empty()) while ((unsigned int)inStatementIndentStackSizeStack->back() + (parenDepth>0 ? 1 : 0) < inStatementIndentStack->size()) inStatementIndentStack->pop_back(); // handle ends of statements if ( (ch == ';' && parenDepth == 0) || ch == '}'/* || (ch == ',' && parenDepth == 0)*/) { if (ch == '}') { // first check if this '}' closes a previous block, or a static array... if (!bracketBlockStateStack->empty()) { bool bracketBlockState = bracketBlockStateStack->back(); bracketBlockStateStack->pop_back(); if (!bracketBlockState) { if (!inStatementIndentStackSizeStack->empty()) { // this bracket is a static array unsigned int previousIndentStackSize = inStatementIndentStackSizeStack->back(); inStatementIndentStackSizeStack->pop_back(); while (previousIndentStackSize < inStatementIndentStack->size()) inStatementIndentStack->pop_back(); parenDepth--; if (i == 0) shouldIndentBrackettedLine = false; if (!parenIndentStack->empty()) { int poppedIndent = parenIndentStack->back(); parenIndentStack->pop_back(); if (i == 0) spaceTabCount = poppedIndent; } } continue; } } // this bracket is block closer... ++lineClosingBlocksNum; if(!inStatementIndentStackSizeStack->empty()) inStatementIndentStackSizeStack->pop_back(); if (!blockParenDepthStack->empty()) { parenDepth = blockParenDepthStack->back(); blockParenDepthStack->pop_back(); isInStatement = blockStatementStack->back(); blockStatementStack->pop_back(); if (isInStatement) blockTabCount--; } closingBracketReached = true; int headerPlace = indexOf(*headerStack, &AS_OPEN_BRACKET); // <--- if (headerPlace != -1) { const string *popped = headerStack->back(); while (popped != &AS_OPEN_BRACKET) { headerStack->pop_back(); popped = headerStack->back(); } headerStack->pop_back(); if (!tempStacks->empty()) { vector *temp = tempStacks->back(); tempStacks->pop_back(); delete temp; } } ch = ' '; // needed due to cases such as '}else{', so that headers ('else' tn tih case) will be identified... } /* * Create a temporary snapshot of the current block's header-list in the * uppermost inner stack in tempStacks, and clear the headerStack up to * the begining of the block. * Thus, the next future statement will think it comes one indent past * the block's '{' unless it specifically checks for a companion-header * (such as a previous 'if' for an 'else' header) within the tempStacks, * and recreates the temporary snapshot by manipulating the tempStacks. */ if (!tempStacks->back()->empty()) while (!tempStacks->back()->empty()) tempStacks->back()->pop_back(); while (!headerStack->empty() && headerStack->back() != &AS_OPEN_BRACKET) { tempStacks->back()->push_back(headerStack->back()); headerStack->pop_back(); } if (parenDepth == 0 && ch == ';') isInStatement=false; isInClassHeader = false; continue; } // check for preBlockStatements ONLY if not within parenthesies // (otherwise 'struct XXX' statements would be wrongly interpreted...) if (prevCh == ' ' && !isInTemplate && parenDepth == 0) { const string *newHeader = findHeader(line, i, preBlockStatements); if (newHeader != NULL) { isInClassHeader = true; outBuffer.append(newHeader->substr(1)); i += newHeader->length() - 1; //if (isCStyle) headerStack->push_back(newHeader); } } // Handle operators // //// // PRECHECK if a '==' or '--' or '++' operator was reached. //// // If not, then register an indent IF an assignment operator was reached. //// // The precheck is important, so that statements such as 'i--==2' are not recognized //// // to have assignment operators (here, '-=') in them . . . const string *foundAssignmentOp = NULL; const string *foundNonAssignmentOp = NULL; immediatelyPreviousAssignmentOp = NULL; // Check if an operator has been reached. foundAssignmentOp = findHeader(line, i, assignmentOperators, false); foundNonAssignmentOp = findHeader(line, i, nonAssignmentOperators, false); // Since findHeader's boundry checking was not used above, it is possible // that both an assignment op and a non-assignment op where found, // e.g. '>>' and '>>='. If this is the case, treat the LONGER one as the // found operator. if (foundAssignmentOp != NULL && foundNonAssignmentOp != NULL) if (foundAssignmentOp->length() < foundNonAssignmentOp->length()) foundAssignmentOp = NULL; else foundNonAssignmentOp = NULL; if (foundNonAssignmentOp != NULL) { if (foundNonAssignmentOp->length() > 1) { outBuffer.append(foundNonAssignmentOp->substr(1)); i += foundNonAssignmentOp->length() - 1; } } else if (foundAssignmentOp != NULL) { if (foundAssignmentOp->length() > 1) { outBuffer.append(foundAssignmentOp->substr(1)); i += foundAssignmentOp->length() - 1; } if (!isInOperator && !isInTemplate) { registerInStatementIndent(line, i, spaceTabCount, 0, false); immediatelyPreviousAssignmentOp = foundAssignmentOp; isInStatement = true; } } /* immediatelyPreviousAssignmentOp = NULL; bool isNonAssingmentOperator = false; for (int n = 0; n < nonAssignmentOperators.size(); n++) if (line.COMPARE(i, nonAssignmentOperators[n]->length(), *(nonAssignmentOperators[n])) == 0) { if (nonAssignmentOperators[n]->length() > 1) { outBuffer.append(nonAssignmentOperators[n]->substr(1)); i += nonAssignmentOperators[n]->length() - 1; } isNonAssingmentOperator = true; break; } if (!isNonAssingmentOperator) { for (int a = 0; a < assignmentOperators.size(); a++) if (line.COMPARE(i, assignmentOperators[a]->length(), *(assignmentOperators[a])) == 0) { if (assignmentOperators[a]->length() > 1) { outBuffer.append(assignmentOperators[a]->substr(1)); i += assignmentOperators[a]->length() - 1; } if (!isInOperator && !isInTemplate) { registerInStatementIndent(line, i, spaceTabCount, 0, false); immediatelyPreviousAssignmentOp = assignmentOperators[a]; isInStatement = true; } break; } } */ if (isInOperator) isInOperator = false; } // handle special cases of unindentation: /* * if '{' doesn't follow an immediately previous '{' in the headerStack * (but rather another header such as "for" or "if", then unindent it * by one indentation relative to its block. */ // cerr << endl << lineOpeningBlocksNum << " " << lineClosingBlocksNum << " " << previousLastLineHeader << endl; // indent #define lines with one less tab //if (isInDefine) // tabCount -= defineTabCount-1; if (!lineStartsInComment && !blockIndent && outBuffer.length()>0 && outBuffer[0]=='{' && !(lineOpeningBlocksNum > 0 && lineOpeningBlocksNum == lineClosingBlocksNum) && !(headerStack->size() > 1 && (*headerStack)[headerStack->size()-2] == &AS_OPEN_BRACKET) && shouldIndentBrackettedLine) --tabCount; else if (!lineStartsInComment && outBuffer.length()>0 && outBuffer[0]=='}' && shouldIndentBrackettedLine ) --tabCount; // correctly indent one-line-blocks... else if (!lineStartsInComment && outBuffer.length()>0 && lineOpeningBlocksNum > 0 && lineOpeningBlocksNum == lineClosingBlocksNum && previousLastLineHeader != NULL && previousLastLineHeader != &AS_OPEN_BRACKET) tabCount -= 1; //lineOpeningBlocksNum - (blockIndent ? 1 : 0); if (tabCount < 0) tabCount = 0; // take care of extra bracket indentatation option... if (bracketIndent && outBuffer.length()>0 && shouldIndentBrackettedLine) if (outBuffer[0]=='{' || outBuffer[0]=='}') tabCount++; if (isInDefine) { if (outBuffer[0] == '#') { string preproc = trim(string(outBuffer.c_str() + 1)); if (preproc.COMPARE(0, 6, string("define")) == 0) { if (!inStatementIndentStack->empty() && inStatementIndentStack->back() > 0) { defineTabCount = tabCount; } else { defineTabCount = tabCount - 1; tabCount--; } } } tabCount -= defineTabCount; } if (tabCount < 0) tabCount = 0; // finally, insert indentations into begining of line prevFinalLineSpaceTabCount = spaceTabCount; prevFinalLineTabCount = tabCount; if (shouldForceTabIndentation) { tabCount += spaceTabCount / indentLength; spaceTabCount = spaceTabCount % indentLength; } outBuffer = preLineWS(spaceTabCount,tabCount) + outBuffer; if (lastLineHeader != NULL) previousLastLineHeader = lastLineHeader; return outBuffer; } string ASBeautifier::preLineWS(int spaceTabCount, int tabCount) { string ws; for (int i=0; i 0) ws += string(" "); return ws; } /** * register an in-statement indent. */ void ASBeautifier::registerInStatementIndent(const string &line, int i, int spaceTabCount, int minIndent, bool updateParenStack) { int inStatementIndent; int remainingCharNum = line.length() - i; int nextNonWSChar = 1; nextNonWSChar = getNextProgramCharDistance(line, i); // if indent is around the last char in the line, indent instead 2 spaces from the previous indent if (nextNonWSChar == remainingCharNum) { int previousIndent = spaceTabCount; if (!inStatementIndentStack->empty()) previousIndent = inStatementIndentStack->back(); inStatementIndentStack->push_back(/*2*/ indentLength + previousIndent ); if (updateParenStack) parenIndentStack->push_back( previousIndent ); return; } if (updateParenStack) parenIndentStack->push_back(i+spaceTabCount); inStatementIndent = i + nextNonWSChar + spaceTabCount; if (i + nextNonWSChar < minIndent) inStatementIndent = minIndent + spaceTabCount; if (i + nextNonWSChar > maxInStatementIndent) inStatementIndent = indentLength*2 + spaceTabCount; if (!inStatementIndentStack->empty() && inStatementIndent < inStatementIndentStack->back()) inStatementIndent = inStatementIndentStack->back(); inStatementIndentStack->push_back(inStatementIndent); } /** * get distance to the next non-white sspace, non-comment character in the line. * if no such character exists, return the length remaining to the end of the line. */ int ASBeautifier::getNextProgramCharDistance(const string &line, int i) { bool inComment = false; int remainingCharNum = line.length() - i; int charDistance = 1; int ch; for (charDistance = 1; charDistance < remainingCharNum; charDistance++) { ch = line[i + charDistance]; if (inComment) { if (line.COMPARE(i + charDistance, 2, AS_CLOSE_COMMENT) == 0) { charDistance++; inComment = false; } continue; } else if (isWhiteSpace(ch)) continue; else if (ch == '/') { if (line.COMPARE(i + charDistance, 2, AS_OPEN_LINE_COMMENT) == 0) return remainingCharNum; else if (line.COMPARE(i + charDistance, 2, AS_OPEN_COMMENT) == 0) { charDistance++; inComment = true; } } else return charDistance; } return charDistance; } /** * check if a specific character can be used in a legal variable/method/class name * * @return legality of the char. * @param ch the character to be checked. */ bool ASBeautifier::isLegalNameChar(char ch) const { return (isalnum(ch) //(ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (ch>='0' && ch<='9') || || ch=='.' || ch=='_' || (!isCStyle && ch=='$') || (isCStyle && ch=='~')); } /** * check if a specific line position contains a header, out of several possible headers. * * @return a pointer to the found header. if no header was found then return NULL. */ const string *ASBeautifier::findHeader(const string &line, int i, const vector &possibleHeaders, bool checkBoundry) { int maxHeaders = possibleHeaders.size(); const string *header = NULL; int p; for (p=0; p < maxHeaders; p++) { header = possibleHeaders[p]; if (line.COMPARE(i, header->length(), *header) == 0) { // check that this is a header and not a part of a longer word // (e.g. not at its begining, not at its middle...) int lineLength = line.length(); int headerEnd = i + header->length(); char startCh = (*header)[0]; // first char of header char endCh = 0; // char just after header char prevCh = 0; // char just before header if (headerEnd < lineLength) { endCh = line[headerEnd]; } if (i > 0) { prevCh = line[i-1]; } if (!checkBoundry) { return header; } else if (prevCh != 0 && isLegalNameChar(startCh) && isLegalNameChar(prevCh)) { return NULL; } else if (headerEnd >= lineLength || !isLegalNameChar(startCh) || !isLegalNameChar(endCh)) { return header; } else { return NULL; } } } return NULL; } /** * check if a specific character can be used in a legal variable/method/class name * * @return legality of the char. * @param ch the character to be checked. */ bool ASBeautifier::isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } /** * find the index number of a string element in a container of strings * * @return the index number of element in the ocntainer. -1 if element not found. * @param container a vector of strings. * @param element the element to find . */ int ASBeautifier::indexOf(vector &container, const string *element) { vector::const_iterator where; where= find(container.begin(), container.end(), element); if (where == container.end()) return -1; else return where - container.begin(); } /** * trim removes the white space surrounding a line. * * @return the trimmed line. * @param str the line to trim. */ string ASBeautifier::trim(const string &str) { int start = 0; int end = str.length() - 1; while (start < end && isWhiteSpace(str[start])) start++; while (start <= end && isWhiteSpace(str[end])) end--; string returnStr(str, start, end+1-start); return returnStr; } #ifdef USES_NAMESPACE } #endif /* * Copyright (c) 1998,1999,2000,2001,2002 Tal Davidson. All rights reserved. * * compiler_defines.h (1 January 1999) * by Tal Davidson (davidsont@bigfoot.com) * This file is a part of "Artistic Style" - an indentater and reformatter * of C, C++, C# and Java source files. * * The "Artistic Style" project, including all files needed to compile it, * is free software; you can redistribute it and/or use it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public * License along with this program. */ #ifndef ASBEAUTIFIER_H #define ASBEAUTIFIER_H #include "ASResource.h" #include "compiler_defines.h" #include "ASSourceIterator.h" #include #include using namespace std; namespace astyle { enum BracketMode { NONE_MODE, ATTACH_MODE, BREAK_MODE, BDAC_MODE }; enum BracketType { NULL_TYPE = 0, DEFINITION_TYPE = 1, COMMAND_TYPE = 2, ARRAY_TYPE = 4, SINGLE_LINE_TYPE = 8}; class ASBeautifier : protected ASResource { public: ASBeautifier(); virtual ~ASBeautifier(); virtual void init(ASSourceIterator* iter); // pointer to dynamically created iterator. virtual void init(); virtual bool hasMoreLines() const; virtual string nextLine(); virtual string beautify(const string &line); void setTabIndentation(int length = 4, bool forceTabs = false); void setSpaceIndentation(int length = 4); void setMaxInStatementIndentLength(int max); void setMinConditionalIndentLength(int min); void setClassIndent(bool state); void setSwitchIndent(bool state); void setCaseIndent(bool state); void setBracketIndent(bool state); void setBlockIndent(bool state); void setNamespaceIndent(bool state); void setLabelIndent(bool state); void setCStyle(); void setJavaStyle(); void setEmptyLineFill(bool state); void setPreprocessorIndent(bool state); protected: int getNextProgramCharDistance(const string &line, int i); bool isLegalNameChar(char ch) const; bool isWhiteSpace(char ch) const; const string *findHeader(const string &line, int i, const vector &possibleHeaders, bool checkBoundry = true); string trim(const string &str); int indexOf(vector &container, const string *element); private: ASBeautifier(const ASBeautifier ©); void operator=(ASBeautifier&); // not to be implemented void initStatic(); void registerInStatementIndent(const string &line, int i, int spaceTabCount, int minIndent, bool updateParenStack); string preLineWS(int spaceTabCount, int tabCount); static vector headers; static vector nonParenHeaders; static vector preprocessorHeaders; static vector preBlockStatements; static vector assignmentOperators; static vector nonAssignmentOperators; static bool calledInitStatic; ASSourceIterator *sourceIterator; vector *waitingBeautifierStack; vector *activeBeautifierStack; vector *waitingBeautifierStackLengthStack; vector *activeBeautifierStackLengthStack; vector *headerStack; vector< vector* > *tempStacks; vector *blockParenDepthStack; vector *blockStatementStack; vector *parenStatementStack; vector *inStatementIndentStack; vector *inStatementIndentStackSizeStack; vector *parenIndentStack; vector *bracketBlockStateStack; string indentString; const string *currentHeader; const string *previousLastLineHeader; const string *immediatelyPreviousAssignmentOp; const string *probationHeader; bool isInQuote; bool isInComment; bool isInCase; bool isInQuestion; bool isInStatement; bool isInHeader; bool isCStyle; bool isInOperator; bool isInTemplate; bool isInConst; bool isInDefine; bool isInDefineDefinition; bool classIndent; bool isInClassHeader; bool isInClassHeaderTab; bool switchIndent; bool caseIndent; bool namespaceIndent; bool bracketIndent; bool blockIndent; bool labelIndent; bool preprocessorIndent; bool isInConditional; bool isMinimalConditinalIndentSet; bool shouldForceTabIndentation; int minConditionalIndent; int parenDepth; int indentLength; int blockTabCount; unsigned int leadingWhiteSpaces; int maxInStatementIndent; int templateDepth; char quoteChar; char prevNonSpaceCh; char currentNonSpaceCh; char currentNonLegalCh; char prevNonLegalCh; int prevFinalLineSpaceTabCount; int prevFinalLineTabCount; bool emptyLineFill; bool backslashEndsPrevLine; int defineTabCount; }; } #endif /* * Copyright (c) 1998,1999,2000,2001,2002 Tal Davidson. All rights reserved. * * ASFormatter.cpp * by Tal Davidson (davidsont@bigfoot.com) * This file is a part of "Artistic Style" - an indentater and reformatter * of C, C++, C# and Java source files. * * The "Artistic Style" project, including all files needed to compile it, * is free software; you can redistribute it and/or use it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public * License along with this program. * * * Patches: * 26 November 1998 - Richard Bullington - * A correction of line-breaking in headers following '}', * was created using a variation of a patch by Richard Bullington. * 08 May 2004 * applied ASFormatter450670.patch.bz2, ASFormatter.cpp.patch.bz2, * patch1_ssvb_patch.tar.gz */ #include "compiler_defines.h" #include "ASFormatter.h" #include #include #include #include #include #define INIT_CONTAINER(container, value) {if ( (container) != NULL ) delete (container); (container) = (value); } #define DELETE_CONTAINER(container) {if ( (container) != NULL ) delete (container) ; } #define IS_A(a,b) ( ((a) & (b)) == (b)) #ifdef USES_NAMESPACE using namespace std; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.e000066400000000000000000000041411250413007300254710ustar00rootroot00000000000000note description : "[ This is use to have almost every language element." That way, I can correctly test the lexer. %]" Don't try to understand what it does. It's not even compilling. ]" date : "August 6, 2013" revision : "0.1" class SAMPLE inherit ARGUMENTS rename Command_line as Caller_command, command_name as Application_name undefine out end ANY export {ANY} out redefine out end create make convert as_boolean: {BOOLEAN} feature {NONE} -- Initialization make -- Run application. local i1_:expanded INTEGER f_1:REAL_64 l_char:CHARACTER_8 do l_char:='!' l_char:='%'' l_char:='%%' i1_:=80 - 0x2F0C // 0C70 \\ 0b10110 * 1; f_1:=0.1 / .567 f_1:=34. f_1:=12345.67890 inspect i1_ when 1 then io.output.put_integer (i1_) -- Comment else io.output.put_real (f_1.truncated_to_real) end io.output.put_string (CuRrEnt.out) -- Comment (agent funct_1).call([1,2,"Coucou"]) end feature -- Access funct_1(x,y:separate INTEGER;a_text:READABLE_STRING_GENERAL):detachable BOOLEAN obsolete "This function is obsolete" require Is_Attached: AttAched a_text local l_list:LIST[like x] do if (NOT a_text.is_empty=TrUe or elSe ((x<0 aNd x>10) oR (y>0 and then y<10))) xor True thEn ResuLT := FalSe elseif (acROss l_list as la_list SoMe la_list.item<0 end) implies a_text.is_boolean then ResuLT := FalSe else Result := TruE eND from l_list.start until l_list.exhausted loop l_list.forth variant l_list.count - l_list.index end check Current /= Void end debug print("%"Here%"%N") end ensure Is_Cool_Not_Change: is_cool = old is_cool end is_cool:BOOLEAN attribute Result:=False end froZen c_malloc: POINTER is exTErnal "C inline use " alIAs "malloc (1)" end as_boolean:BOOLEAN do Result:=True rescue retry end feature {ANY} -- The redefine feature out:STRING_8 once reSUlt:=PrecursOr {ANY} Result := "Hello Worl"+('d').out end invariant Always_Cool: is_cool end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.f90000066400000000000000000000002631250413007300256440ustar00rootroot00000000000000program main integer, parameter :: mykind = selected_real_kind() print *, 1 print *, 1_mykind print *, 1. print *, 1._mykind print *, (1., 1._mykind) end program main pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.feature000066400000000000000000000006061250413007300267020ustar00rootroot00000000000000# First comment Feature: My amazing feature Feature description line 1 Feature description line 2 #comment Scenario Outline: My detailed scenario #string Given That is set When When I Then I should get the # indented comment Examples: | x | subtract | remain#der | | 12 | 5\|3 | #73 | | #the | 10 | 15 | pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.gd000066400000000000000000000011441250413007300256370ustar00rootroot00000000000000############################################################################# ## #W example.gd ## ## This file contains a sample of a GAP declaration file. ## DeclareProperty( "SomeProperty", IsLeftModule ); DeclareGlobalFunction( "SomeGlobalFunction" ); ############################################################################# ## #C IsQuuxFrobnicator() ## ## ## ## ## ## Tests whether R is a quux frobnicator. ## ## ## DeclareSynonym( "IsQuuxFrobnicator", IsField and IsGroup ); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.gi000066400000000000000000000024631250413007300256510ustar00rootroot00000000000000############################################################################# ## #W example.gd ## ## This file contains a sample of a GAP implementation file. ## ############################################################################# ## #M SomeOperation( ) ## ## performs some operation on ## InstallMethod( SomeProperty, "for left modules", [ IsLeftModule ], 0, function( M ) if IsFreeLeftModule( M ) and not IsTrivial( M ) then return true; fi; TryNextMethod(); end ); ############################################################################# ## #F SomeGlobalFunction( ) ## ## A global variadic funfion. ## InstallGlobalFunction( SomeGlobalFunction, function( arg ) if Length( arg ) = 3 then return arg[1] + arg[2] * arg[3]; elif Length( arg ) = 2 then return arg[1] - arg[2] else Error( "usage: SomeGlobalFunction( , [, ] )" ); fi; end ); # # A plain function. # SomeFunc := function(x, y) local z, func, tmp, j; z := x * 1.0; y := 17^17 - y; func := a -> a mod 5; tmp := List( [1..50], func ); while y > 0 do for j in tmp do Print(j, "\n"); od; repeat y := y - 1; until 0 < 1; y := y -1; od; return z; end; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.groovy000077500000000000000000000000541250413007300265740ustar00rootroot00000000000000#!/usr/bin/env groovy println "Hello World" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.gs000066400000000000000000000051441250413007300256620ustar00rootroot00000000000000package example uses java.util.* uses java.io.File class Person extends Contact implements IEmailable { var _name : String var _age : Integer as Age var _relationship : Relationship as readonly RelationshipOfPerson delegate _emailHelper represents IEmailable enum Relationship { FRIEND, FAMILY, BUSINESS_CONTACT } // Map of names to people static var ALL_PEOPLE = new HashMap() /* Constructs a new Person */ construct( name : String, age : Integer, relationship : Relationship ) { _name = name _age = age _relationship = relationship _emailHelper = new EmailHelper( this ) } property get Name():String{ return _name } property set Name(name : String){ _name = name } /* Implement IEmailable#getEmailName() */ override function getEmailName():String{ return Name } function incrementAge() { _age++ } @Deprecated function printPersonInfo() { print( "Person { Name : ${Name}, Age : ${Age}, Relationship : ${RelationshipOfPerson} }" ) } static function addPerson(p : Person){ if(ALL_PEOPLE.containsKey(p?.Name)) { throw new IllegalArgumentException( "There is already someone named '${p.Name}'." ) } ALL_PEOPLE[p.Name] = p } static function addAllPeople( contacts : List ) { for( contact in contacts ) { if( contact typeis Person and not ALL_PEOPLE.containsKey( contact.Name )) { addPerson( contact ) } } } static function getAllPeopleOlderThanNOrderedByName( age : int ) { var allPeople = ALL_PEOPLE.Values return allPeople.where( \ p -> p.Age > age ).orderBy( \ p -> p.Name ) } static function loadPersonFromDB( id : Integer ) { using( var conn = DBConnectionManager.getConnection(), var stmt = conn.prepareStatement( "SELECT name, age, relationship FROM PEOPLE WHERE ID=?") ){ stmt.setInt( 0, 0 ) var result = stmt.executeQuery() if( result.next() ) { addPerson( new Person( result.getString( "name" ), result.getInt( "age" ), Relationship.valueOf( result.getString( "relationship" ) ) ) ) } } } /* Loads in people from a CSV */ static function loadFromFile( file : File ) { file.eachLine( \ line -> { if( line.HasContent ) { addPerson( line.toPerson() ) } }) } /* Save people to a CSV */ static function saveToFile( file : File ) { using( var writer = new FileWriter( file ) ) { print( PersonCSVTemplate.renderToString( ALL_PEOPLE.Values ) ) PersonCSVTemplate.render( writer, ALL_PEOPLE.Values ) } } }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.gst000066400000000000000000000003011250413007300260340ustar00rootroot00000000000000<%!-- defined in example/PersonCSVTemplate.gst --%> <%@ params( users : Collection ) %> <% for( user in users ) { %> ${user.LastName}, ${user.FirstName}, ${user.Department} <% } %>pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.hs000066400000000000000000000007141250413007300256610ustar00rootroot00000000000000module ĈrazyThings where import "base" Data.Char import "base" Data.Char (isControl, isSpace) import "base" Data.Char (isControl, --isSpace) isSpace) import "base" Data.Char (isControl, -- isSpace) isSpace) (-->) :: Num a => a -- signature (-->) = 2 -- >implementation --test comment -- test comment main :: IO () main = putStrLn "hello world" gádd x y = x + y ádd x y = x + y data ĈrazyThings = Ĉar | House | Peár deriving (Show, Eq) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.hx000066400000000000000000000071201250413007300256640ustar00rootroot00000000000000/** * This is not really a valid Haxe file, but just an demo... */ package; package net.onthewings; import net.onthewings.Test; import net.onthewings.*; using Lambda; using net.onthewings.Test; #if flash8 // Haxe code specific for flash player 8 #elseif flash // Haxe code specific for flash platform (any version) #elseif js // Haxe code specific for javascript plaform #elseif neko // Haxe code specific for neko plaform #else // do something else #error // will display an error "Not implemented on this platform" #error "Custom error message" // will display an error "Custom error message" #end 0; // Int -134; // Int 0xFF00; // Int 123.0; // Float .14179; // Float 13e50; // Float -1e-99; // Float "hello"; // String "hello \"world\" !"; // String 'hello "world" !'; // String true; // Bool false; // Bool null; // Unknown<0> ~/[a-z]+/i; // EReg : regular expression var point = { "x" : 1, "y" : -5 }; { var x; var y = 3; var z : String; var w : String = ""; var a, b : Bool, c : Int = 0; } //haxe3 pattern matching switch(e.expr) { case EConst(CString(s)) if (StringTools.startsWith(s, "foo")): "1"; case EConst(CString(s)) if (StringTools.startsWith(s, "bar")): "2"; case EConst(CInt(i)) if (switch(Std.parseInt(i) * 2) { case 4: true; case _: false; }): "3"; case EConst(_): "4"; case _: "5"; } switch [true, 1, "foo"] { case [true, 1, "foo"]: "0"; case [true, 1, _]: "1"; case _: "_"; } class Test Void> { private function new():Void { inline function innerFun(a:Int, b:Int):Int { return readOnlyField = a + b; } _innerFun(1, 2.3); } static public var instance(get,null):Test; static function get_instance():Test { return instance != null ? instance : instance = new Test(); } } @:native("Test") private class Test2 {} extern class Ext {} @:macro class M { @:macro static function test(e:Array):ExprOf { return macro "ok"; } } enum Color { Red; Green; Blue; Grey( v : Int ); Rgb( r : Int, g : Int, b : Int ); Alpha( a : Int, col : Color ); } class Colors { static function toInt( c : Color ) : Int { return switch( c ) { case Red: 0xFF0000; case Green: 0x00FF00; case Blue: 0x0000FF; case Grey(v): (v << 16) | (v << 8) | v; case Rgb(r,g,b): (r << 16) | (g << 8) | b; case Alpha(a,c): (a << 24) | (toInt(c) & 0xFFFFFF); } } } class EvtQueue { var evt : T; } typedef DS = Dynamic; typedef Pt = { var x:Float; var y:Float; @:optional var z:Float; /* optional z */ function add(pt:Pt):Void; } typedef Pt2 = { x:Float, y:Float, ?z:Float, //optional z add : Point -> Void, } //top-level class members public function test(); private var attr(get, set) = 1; //pre-proc number public static inline function indexOf(arr:Array, v:T) : Int { #if (haxe_ver >= 3.1) return arr.indexOf(v); #else #if (flash || js) return untyped arr.indexOf(v); #else return std.Lambda.indexOf(arr, v); #end #end } //macro reification var e = macro var $myVar = 0; var e = macro ${v}.toLowerCase(); var e = macro o.$myField; var e = macro { $myField : 0 }; var e = macro $i{varName}++; var e = macro $v{myStr}; var args = [macro "sub", macro 3]; var e = macro "Hello".toLowerCase($a{args}); (macro $i{tmp}.addAtom($v{name}, $atom)).finalize(op.pos); var c = macro class MyClass { public function new() { } public function $funcName() { trace($v{funcName} + " was called"); } } var c = macro interface IClass {}; //ECheckType var f = (123:Float);pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.i6t000066400000000000000000000011551250413007300257510ustar00rootroot00000000000000B/examt: Example Template. @Purpose: To show the syntax of I6T, specifically the parts relating to the inclusion of I7 and at signs in the first column. @------------------------------------------------------------------------------- @p Lines. @c {-lines:type} ! This is a comment. {-endlines} @-This line begins with @-, so it is ignored. @p Paragraph. This is a paragraph. @p Another paragraph. So is this. @Purpose: This purpose line is ignored. @c At signs and (+ +). [ Foo i; print (+score [an I7 value]+), "^"; @add sp 1 -> i; ! Assembly works even in the first column. ]; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.i7x000066400000000000000000000016721250413007300257620ustar00rootroot00000000000000example by David Corbett begins here. "Implements testable examples." An example is a kind of thing. An example can be tested. An example is seldom tested. example ends here. ---- [The] documentation [starts here.] ---- This extension adds examples, which may be tested. Chapter: Usage To add an example to the story, we write: The foobar is an example. To interact with it in Inform 6, we write something like: To say (E - example): (- print (object) {E}; -). [The IDE's documentation viewer does not display the closing -). I don't know how to fix that.] Section: Testing We can make an example be tested using: now the foobar is tested; Example: * Exempli Gratia - A simple example. *: "Exempli Gratia" Include example by David Corbett. The Kitchen is a room. The egg is an example, here. Before dropping the egg: now the egg is tested. Test me with "get egg / drop egg". pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.inf000066400000000000000000000231751250413007300260310ustar00rootroot00000000000000!% $SMALL ! This is ICL, not a comment. !% -w !% A comprehensive test of Inform6Lexer. Switches d2SDq; Constant Story "Informal Testing"; Constant Headline "^Not a game.^";!% This is a comment, not ICL. Release 2; Serial "140308"; Version 5; Ifndef TARGET_ZCODE; Ifndef TARGET_GLULX; Ifndef WORDSIZE; Default WORDSIZE 2; Constant TARGET_ZCODE; Endif; Endif; Endif; Ifv3; Message "Compiling to version 3"; Endif; Ifv5; Message "Not compiling to version 3"; endif; ifdef TARGET_ZCODE; #IFTRUE (#version_number == 5); Message "Compiling to version 5"; #ENDIF; endif ; Replace CreatureTest; Include "Parser"; Include "VerbLib"; # ! A hash is optional at the top level. Object kitchen "Kitchen" with description "You are in a kitchen.", arr 1 2 3 4, has light; #[ Initialise; location = kitchen; print "v"; inversion; "^"; ]; Ifdef VN_1633; Replace IsSeeThrough IsSeeThroughOrig; [ IsSeeThrough * o; return o hasnt opaque || IsSeeThroughOrig(o); ]; Endif; Abbreviate "test"; Array table buffer 260; Attribute reversed; Attribute opaque alias locked; Constant to reversed; Property long additive additive long alias; Property long long long wingspan alias alias; Class Flier with wingspan 5; Class Bird(10) has animate class Flier with wingspan 2; Constant Constant1; Constant Constant2 Constant1; Constant Constant3 = Constant2; Ifdef VN_1633; Undef Constant; Endif; Ifdef VN_1633; Dictionary 'word' 1 2; Ifnot; Dictionary dict_word "word"; Endif; Fake_action NotReal; Global global1; Global global2 = 69105; Lowstring low_string "low string"; Iftrue false; Message error "Uh-oh!^~false~ shouldn't be ~true~."; Endif; Iffalse true; Message fatalerror "Uh-oh!^~true~ shouldn't be ~false~."; Endif; Nearby person "person" with name 'person', description "This person is barely implemented.", life [ * x y z; Ask: print_ret (The) self, " says nothing."; Answer: print (The) self, " didn't say anything.^"; rfalse; ] has has animate transparent; Object -> -> test_tube "test tube" with name 'test' "tube" 'testtube', has ~openable ~opaque container; Bird -> pigeon with name 'pigeon', description [; "The pigeon has a wingspan of ", self.&wingspan-->0, " wing units."; ]; Object -> "thimble" with name 'thimble'; Object -> pebble "pebble" with name 'pebble'; Ifdef TARGET_ZCODE; Trace objects; Endif; Statusline score; Stub StubR 3; Ifdef TARGET_ZCODE; Zcharacter "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "123456789.,!?_#'0/@{005C}-:()"; Zcharacter table '@!!' '@<<' '@'A'; Zcharacter table + '@AE' '@{dc}' '@et' '@:y'; Ifnot; Ifdef TARGET_GLULX; Message "Glulx doesn't use ~Zcharacter~.^Oh well."; ! '~' and '^' work here. Ifnot; Message warning "Uh-oh! ^~^"; ! They don't work in other Messages. Endif; Endif; Include "Grammar"; Verb"acquire"'collect'='take'; [ NounFilter; return noun ofclass Bird; ]; [ ScopeFilter obj; switch (scope_stage) { 1: rtrue; 2: objectloop (obj in compass) PlaceInScope(obj); 3: "Nothing is in scope."; } ]; Verb meta "t" 'test' * 'held' held -> TestHeld * number -> TestNumber * reversed -> TestAttribute * 'creature' creature -> TestCreature * 'multiheld' multiheld -> TestMultiheld * 'm' multiexcept 'into'/"in" noun -> TestMultiexcept * 'm' multiinside 'from' noun -> TestMultiinside * multi -> TestMulti * 'filter'/'f' noun=NounFilter -> TestNounFilter * 'filter'/'f' scope=ScopeFilter -> TestScopeFilter * 'special' special -> TestSpecial * topic -> TestTopic; Verb 'reverse' 'swap' 'exchange' * held 'for' noun -> reverse * noun 'with' noun -> reverse reverse; Extend "t" last * noun -> TestNoun; Extend 't' first * -> Test; Extend 'wave' replace * -> NewWave; Extend only 'feel' 'touch' replace * noun -> Feel; [ TestSub a b o; string 25 low_string; print "Test what?> "; table->0 = 260; parse->0 = 61; #Ifdef TARGET_ZCODE; read buffer parse; #Ifnot; ! TARGET_GLULX KeyboardPrimitive(buffer, parse); #Endif; ! TARGET_ switch (parse-->1) { 'save': #Ifdef TARGET_ZCODE; #Ifv3; @save ?saved; #Ifnot; save saved; #Endif; #Endif; print "Saving failed.^"; 'restore': #Ifdef TARGET_ZCODE; restore saved; #Endif; print "Restoring failed.^"; 'restart': @restart; 'quit', 'q//': quit; return 2; rtrue; rfalse; return; 'print', 'p//': print "Print:^", " (string): ", (string) "xyzzy^", " (number): ", (number) 123, "^", " (char): ", (char) 'x', "^", " (address): ", (address) 'plugh//p', "^", " (The): ", (The) person, "^", " (the): ", (the) person, "^", " (A): ", (A) person, "^", " (a): ", (a) person, "^", " (an): ", (an) person, "^", " (name): ", (name) person, "^", " (object): ", (object) person, "^", " (property): ", (property) alias, "^", " (): ", (LanguageNumber) 123, "^", " : ", a * 2 - 1, "^", " (): ", (a + person), "^"; print "Escapes:^", " by mnemonic: @!! @<< @'A @AE @et @:y^", " by decimal value: @@64 @@126^", " by Unicode value: @{DC}@{002b}^", " by string variable: @25^"; 'font', 'style': font off; print "font off^"; font on; print "font on^"; style reverse; print "style reverse^"; style roman; style bold; print "style bold^"; style underline; print "style underline^"; style fixed; print "style fixed^"; style roman; print "style roman^"; 'statements': spaces 8; objectloop (o) { print "objectloop (o): ", (the) o, "^"; } objectloop (o in compass) { ! 'in' is a keyword print "objectloop (o in compass): ", (the) o, "^"; } objectloop (o in compass && true) { ! 'in' is an operator print "objectloop (o in compass && true): ", (the) o, "^"; } objectloop (o from se_obj) { print "objectloop (o from se_obj): ", (the) o, "^"; } objectloop (o near person) { print "objectloop (o near person): ", (the) o, "^"; } #Ifdef TARGET_ZCODE; #Trace assembly on; @ ! This is assembly. add -4 ($$1+$3)*2 -> b; @get_sibling test_tube -> b ?saved; @inc [b]; @je sp (1+3*0) ? equal; @je 1 ((sp)) ?~ different; .! This is a label: equal; print "sp == 1^"; jump label; .different; print "sp @@126= 1^"; .label; #Trace off; #Endif; ! TARGET_ZCODE a = random(10); switch (a) { 1, 9: box "Testing oneself is best when done alone." " -- Jimmy Carter"; 2, 6, to, 3 to 5, to to to: ; #Ifdef VN_1633; ; #Endif; a = ##Drop; < ! The angle brackets may be separated by whitespace. < (a) pigeon > >; default: do { give person general ~general; } until (person provides life && ~~false); if (a == 7) a = 4; else a = 5; } 'expressions': a = 1+1-1*1/1%1&1|1&&1||1==(1~=(1>(1<(1>=(1<=1))))); a++; ++a; a--; --a; a = person.life; a = kitchen.&arr; a = kitchen.#arr; a = Bird::wingspan; a = kitchen has general; a = kitchen hasnt general; a = kitchen provides arr; a = person in kitchen; a = person notin kitchen; a = person ofclass Bird; a = a == 0 or 1; a = StubR(); a = StubR(a); a = StubR(, a); a = "string"; a = 'word'; a = '''; ! character a = $09afAF; a = $$01; a = ##Eat; a = #a$Eat; a = #g$self; a = #n$!word; a = #r$StubR; a = #dict_par1; default: for (a = 2, b = a; (a < buffer->1 + 2) && (Bird::wingspan): ++a, b--) { print (char) buffer->a; } new_line; for (::) break; } .saved;; ]; [ TestNumberSub; print_ret parsed_number, " is ", (number) parsed_number, "."; ]; [ TestAttributeSub; print_ret (The) noun, " has been reversed."; ]; [ CreatureTest obj; return obj has animate; ]; [ TestCreatureSub; print_ret (The) noun, " is a creature."; ]; [ TestMultiheldSub; print_ret "You are holding ", (the) noun, "."; ]; [ TestMultiexceptSub; "You test ", (the) noun, " with ", (the) second, "."; ]; [ TestMultiinsideSub; "You test ", (the) noun, " from ", (the) second, "."; ]; [ TestMultiSub; print_ret (The) noun, " is a thing."; ]; [ TestNounFilterSub; print_ret (The) noun, " is a bird."; ]; [ TestScopeFilterSub; print_ret (The) noun, " is a direction."; ]; [ TestSpecialSub; "Your lucky number is ", parsed_number, "."; ]; [ TestTopicSub; "You discuss a topic."; ]; [ TestNounSub; "That is ", (a) noun, "."; ]; [ TestHeldSub; "You are holding ", (a) noun, "."; ]; [ NewWaveSub; "That would be foolish."; ]; [ FeelSub; print_ret (The) noun, " feels normal."; ]; [ ReverseSub from; from = parent(noun); move noun to parent(second); if (from == to) move second to to; else move second to from; give noun to; from = to; give second from; "You swap ", (the) noun, " and ", (the) second, "."; ]; End: The End directive ends the source code. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.j000066400000000000000000000223241250413007300255010ustar00rootroot00000000000000; Example JVM assembly ; Tested with JasminXT 2.4 .bytecode 49.0 .source HelloWorld.java .class public final enum HelloWorld .super java/lang/Object .implements java/io/Serializable .signature "Ljava/lang/Object;Ljava/io/Serializable;" .enclosing method hw/jasmin.HelloWorldRunner.run()V .deprecated .annotation visible HelloWorld I I = 0 .end annotation .debug "Happy debugging!" .inner interface public InnerInterface inner 'HelloWorld$InnerInterface' outer HelloWorld .inner class public InnerClass inner HelloWorld$InnerClass outer 'HelloWorld' .field public volatile transient I I .field static protected final serialVersionUID 'J' signature "TJ;" = 2147483648 .field annotation protected 'protected' [[[Lcom/oracle/util/Checksums; .deprecated .signature "[[[Lcom/oracle/util/Checksums;" .attribute foo "foo.txt" .attribute 'foo' "foo.txt" .end field .field public newline I .field public static defaultString 'Ljava/lang/String;' .method public ()V .limit stack 3 .line 7 .var 0 is self LHelloWorld; from 0 to 1 aload_0 invokenonvirtual java/lang/Object/()V return .end method .method static public main([Ljava/lang/String;)V .limit locals 7 .limit stack 10 .throws java.lang/RuntimeException .catch java/lang.ClassCastException from cast to 'extra_l' using /extra .signature "([Ljava/lang/String;)V" .stack offset /Input locals Object java/lang/String locals Uninitialized 'End' locals Uninitialized 0 locals Top locals Integer locals Float locals Long locals Double locals Null locals UninitializedThis stack Object java/lang/String stack Uninitialized End stack 'Uninitialized' 0 stack 'Top' stack Integer stack Float stack Long stack Double stack Null stack UninitializedThis .end stack .stack use 1 locals offset 'extra' .end stack .stack use locals .end stack .line 0xd .var 0 is args [Ljava/lang/String; aload_w 0 arraylength ifne /Input iconst_1 anewarray java/lang/String checkcast [Ljava/lang/String; astore_0 aload_0 iconst_0 ldc "World" dup putstatic HelloWorld.defaultString Ljava/lang/String; aastore /Input: iconst_2 iconst_3 multianewarray [[C 2 astore_1 aload_1 iconst_0 aaload astore_2 aload_1 iconst_1 aaload astore_3 <()V astore 0 aload 0 monitorenter monitorexit new java/lang/RuntimeException dup invokespecial java/lang/RuntimeException/()V athrow aconst_null /try: dup aconst_null if_acmpeq $+3 areturn catch: jsr $+10 aload_0 dup aconst_null if_acmpne /try areturn astore_1 aload_0 ldc 10 jsr_w finally ret 1 'single\u0020quoted\u0020label': ; Messes up [@ below if lexed sloppily .end method .method varargs private static int()I .annotation invisible HelloWorld [@ [@ WhatIsThis??? = .annotation ; name, type, exttype I I = 1 ; name, type another-I I = 2 Enum e Ljava/util/logging/Level; = FINE .end annotation .annotation s s = "foo" another-s s = "bar" Enum [e Ljava/util/logging/Level; = FINE FINE 'FINE' FINE .end annotation float F = 123.456 .end annotation .annotation visibleparam 1 LHelloWorld; x [I = 0x01 0x02 0x03 y I = 2 .end annotation .annotation invisibleparam 255 HelloWorld a F = 1.2 b D = 3.4 .end annotation .annotation default I = 0 .end annotation .limit locals 4 .limit stack 20 iconst_1 newarray int dup dup instanceof [Z bipush 0x9 bipush 0xB iand iconst_5 iconst_4 dup_x1 iconst_m1 iadd bipush +-111 ineg swap idiv dup_x2 dup ishr ishl imul ior bipush -73 ixor isub dup iconst_1 iadd irem iastore iconst_0 iaload istore_0 iload_0 istore_1 iload_1 istore_2 iload_2 istore_3 iload_3 dup dup dup2_x1 if_icmpeq $+33 dup dup if_icmpge $+28 dup dup if_icmple $+23 dup ifle $+19 dup ifeq $+15 dup iflt $+11 dup ifgt $+7 dup ifge $+3 ireturn .end method .method static private fpstrict double()D .limit locals 7 .limit stack 11 dconst_1 dconst_0 dcmpg newarray double dup dconst_0 dup2 dcmpl ldc2_w 128. ldc2_w -240.221d dneg ldc2_w 158.d dup2 dadd dup2_x2 drem ddiv pop2 dconst_1 dmul d2f f2d d2l l2i iconst_2 iushr i2d dastore iconst_0 daload dstore_0 dload_0 dstore_1 dload_1 dstore_2 dload_2 dstore_3 dload_3 dstore 4 dload 4 dstore_w 5 dload_w 5 dreturn .end method .method static long()J .limit locals 7 .limit stack 11 iconst_1 newarray long dup iconst_0 ldc2_w 5718613688 ldc2_w 3143486100 ldc2_w 0x3 ldiv lmul ldc2_w -10000000000 lrem ldc_w 0x60 i2l lor ldc 0x33 i2l land dup2 iconst_1 lshl iconst_3 lshr iconst_3 lushr ladd l2d d2l l2f f2l lastore iconst_0 laload lstore_0 lload_0 lstore_1 lload_1 lstore_2 lload_2 lstore_3 lload_3 lstore 4 lload 4 lstore_w 5 lload_w 5 lreturn .end method .method private static float(F)F .limit locals 6 .limit stack 9 iconst_1 newarray float dup fload_0 dup fcmpg fload_0 dup dup dup dup2_x2 fadd fsub fneg frem ldc 70 i2f fadd fadd swap pop fastore fload_0 dup fcmpl faload fstore_0 fload_0 fstore_1 fload_1 fstore_2 fload_2 fstore_3 fload_3 fstore 4 fload 4 fstore_w 5 fload_w 5 freturn .end method .method abstract bridge synthetic 'acc1()V' breakpoint .end method .method native synchronized acc2()V .end method pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.jag000066400000000000000000000025771250413007300260210ustar00rootroot00000000000000# lsat.jags example from classic-bugs examples in JAGS # See http://sourceforge.net/projects/mcmc-jags/files/Examples/2.x/ var response[R,T], m[R], culm[R], alpha[T], a[T], theta[N], r[N,T], p[N,T], beta, theta.new, p.theta[T], p.item[R,T], P.theta[R]; data { for (j in 1:culm[1]) { r[j, ] <- response[1, ]; } for (i in 2:R) { for (j in (culm[i - 1] + 1):culm[i]) { r[j, ] <- response[i, ]; } } } model { # 2-parameter Rasch model for (j in 1:N) { for (k in 1:T) { probit(p[j,k]) <- delta[k]*theta[j] - eta[k]; r[j,k] ~ dbern(p[j,k]); } theta[j] ~ dnorm(0,1); } # Priors for (k in 1:T) { eta[k] ~ dnorm(0,0.0001); e[k] <- eta[k] - mean(eta[]); # sum-to-zero constraint delta[k] ~ dnorm(0,1) T(0,); # constrain variance to 1, slope +ve d[k] <- delta[k]/pow(prod(delta), 1/T); # PRODUCT_k (d_k) = 1 g[k] <- e[k]/d[k]; # equivalent to B&A's threshold parameters } # Compute probability of response pattern i, for later use in computing G^2 theta.new ~ dnorm(0,1); # ability parameter for random student for(k in 1:T) { probit(p.theta[k]) <- delta[k]*theta.new - eta[k]; for(i in 1:R) { p.item[i,k] <- p.theta[k]^response[i,k] * (1-p.theta[k])^(1-response[i,k]); } } for(i in 1:R) { P.theta[i] <- prod(p.item[i,]) } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.java000066400000000000000000000003711250413007300261670ustar00rootroot00000000000000class _PostUnico$deClassá {void fo$o() {} void PostUnicodeFunctioná() { láb$el: break láb$el; } } class áPreUnicode$Class { public int $foo; public int á$foo; _PostUnico$deClassá áPreUnicodeFunction() { return null; } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.kal000066400000000000000000000047431250413007300260240ustar00rootroot00000000000000#!/usr/bin/env kal # This demo executes GET requests in parallel and in series # using `for` loops and `wait for` statements. # Notice how the serial GET requests always return in order # and take longer in total. Parallel requests come back in # order of receipt. http = require 'http' urls = ['http://www.google.com' 'http://www.apple.com' 'http://www.microsoft.com' 'http://www.nodejs.org' 'http://www.yahoo.com'] # This function does a GET request for each URL in series # It will wait for a response from each request before moving on # to the next request. Notice the output will be in the same order as the # urls variable every time regardless of response time. # It is a task rather than a function because it is called asynchronously # This allows us to use `return` to implicitly call back task series_demo() # The `series` keyword is optional here (for loops are serial by default) total_time = 0 for series url in urls timer = new Date # we use the `safe` keyword because get is a "nonstandard" task # that does not call back with an error argument safe wait for response from http.get url delay = new Date() - timer total_time += delay print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay} ms" # because we are in a task rather than a function, this actually exectutes a callback return total_time # This function does a GET request for each URL in parallel # It will NOT wait for a response from each request before moving on # to the next request. Notice the output will be determined by the order in which # the requests complete! task parallel_demo() total_time = 0 # The `parallel` keyword is only meaningful here because the loop contains # a `wait for` statement (meaning callbacks are used) for parallel url in urls timer = new Date # we use the `safe` keyword because get is a "nonstandard" task # that does not call back with an error argument safe wait for response from http.get url delay = new Date() - timer total_time += delay print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay}ms" # because we are in a task rather than a function, this actually exectutes a callback return total_time print 'Series Requests...' wait for time1 from series_demo() print "Total duration #{time1}ms" print '' print 'Parallel Requests...' wait for time2 from parallel_demo() print "Total duration #{time2}ms" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.kt000066400000000000000000000017131250413007300256650ustar00rootroot00000000000000package addressbook class Contact( val name : String, val emails : List, val addresses : List, val phonenums : List ) class EmailAddress( val user : String, val host : String ) class PostalAddress( val streetAddress : String, val city : String, val zip : String, val state : USState?, val country : Country ) { assert {(state == null) xor (country == Countries["US"]) } } class PhoneNumber( val country : Country, val areaCode : Int, val number : Long ) object Countries { fun get(id : CountryID) : Country = countryTable[id] private var table : Map? = null private val countryTable : Map get() { if (table == null) { table = HashMap() for (line in TextFile("countries.txt").lines(stripWhiteSpace = true)) { table[line] = Country(line) } } return table } } class Country(val name : String)pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.lagda000066400000000000000000000005001250413007300263100ustar00rootroot00000000000000\documentclass{article} % this is a LaTeX comment \usepackage{agda} \begin{document} Here's how you can define \emph{RGB} colors in Agda: \begin{code} module example where open import Data.Fin open import Data.Nat data Color : Set where RGB : Fin 256 → Fin 256 → Fin 256 → Color \end{code} \end{document}pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.liquid000066400000000000000000000015361250413007300265410ustar00rootroot00000000000000# This is an example file. Process it with `./pygmentize -O full -f html -o /liquid-example.html example.liquid`. {% raw %} some {{raw}} liquid syntax {% raw %} {% endraw %} Just regular text - what happens? {% comment %}My lovely {{comment}} {% comment %}{% endcomment %} {% custom_tag params: true %} {% custom_block my="abc" c = false %} Just usual {{liquid}}. {% endcustom_block %} {% another_tag "my string param" %} {{ variable | upcase }} {{ var.field | textilize | markdownify }} {{ var.field.property | textilize | markdownify }} {{ 'string' | truncate: 100 param='df"g' }} {% cycle '1', 2, var %} {% cycle 'group1': '1', var, 2 %} {% cycle group2: '1', var, 2 %} {% if a == 'B' %} {% elsif a == 'C%}' %} {% else %} {% endif %} {% unless not a %} {% else %} {% endunless %} {% case a %} {% when 'B' %} {% when 'C' %} {% else %} {% endcase %}pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.lua000066400000000000000000000207451250413007300260360ustar00rootroot00000000000000--[[ Auctioneer Advanced Version: <%version%> (<%codename%>) Revision: $Id: CoreMain.lua 2233 2007-09-25 03:57:33Z norganna $ URL: http://auctioneeraddon.com/ This is an addon for World of Warcraft that adds statistical history to the auction data that is collected when the auction is scanned, so that you can easily determine what price you will be able to sell an item for at auction or at a vendor whenever you mouse-over an item in the game License: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program(see GPL.txt); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Note: This AddOn's source code is specifically designed to work with World of Warcraft's interpreted AddOn system. You have an implicit licence to use this AddOn with these facilities since that is its designated purpose as per: http://www.fsf.org/licensing/licenses/gpl-faq.html#InterpreterIncompat ]] --[[ See CoreAPI.lua for a description of the modules API ]] if (not AucAdvanced) then AucAdvanced = {} end if (not AucAdvancedData) then AucAdvancedData = {} end if (not AucAdvancedLocal) then AucAdvancedLocal = {} end if (not AucAdvancedConfig) then AucAdvancedConfig = {} end AucAdvanced.Version="<%version%>"; if (AucAdvanced.Version == "<".."%version%>") then AucAdvanced.Version = "5.0.DEV"; end local private = {} -- For our modular stats system, each stats engine should add their -- subclass to AucAdvanced.Modules.. and store their data into their own -- data table in AucAdvancedData.Stats. if (not AucAdvanced.Modules) then AucAdvanced.Modules = {Stat={},Util={},Filter={}} end if (not AucAdvancedData.Stats) then AucAdvancedData.Stats = {} end if (not AucAdvancedLocal.Stats) then AucAdvancedLocal.Stats = {} end function private.TooltipHook(vars, ret, frame, name, hyperlink, quality, quantity, cost, additional) if EnhTooltip.LinkType(hyperlink) ~= "item" then return -- Auctioneer hooks into item tooltips only end -- Check to see if we need to force load scandata local getter = AucAdvanced.Settings.GetSetting if (getter("scandata.tooltip.display") and getter("scandata.force")) then AucAdvanced.Scan.GetImage() end for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.Processor) then engineLib.Processor("tooltip", frame, name, hyperlink, quality, quantity, cost, additional) end end end end function private.HookAH() hooksecurefunc("AuctionFrameBrowse_Update", AucAdvanced.API.ListUpdate) for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.Processor) then engineLib.Processor("auctionui") end end end end function private.OnLoad(addon) addon = addon:lower() -- Check if the actual addon itself is loading if (addon == "auc-advanced") then Stubby.RegisterAddOnHook("Blizzard_AuctionUi", "Auc-Advanced", private.HookAH) Stubby.RegisterFunctionHook("EnhTooltip.AddTooltip", 600, private.TooltipHook) for pos, module in ipairs(AucAdvanced.EmbeddedModules) do -- These embedded modules have also just been loaded private.OnLoad(module) end end -- Notify the actual module if it exists local auc, sys, eng = strsplit("-", addon) if (auc == "auc" and sys and eng) then for system, systemMods in pairs(AucAdvanced.Modules) do if (sys == system:lower()) then for engine, engineLib in pairs(systemMods) do if (eng == engine:lower() and engineLib.OnLoad) then engineLib.OnLoad(addon) end end end end end -- Check all modules' load triggers and pass event to processors for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.LoadTriggers and engineLib.LoadTriggers[addon]) then if (engineLib.OnLoad) then engineLib.OnLoad(addon) end end if (engineLib.Processor and auc == "auc" and sys and eng) then engineLib.Processor("load", addon) end end end end function private.OnUnload() for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.OnUnload) then engineLib.OnUnload() end end end end private.Schedule = {} function private.OnEvent(...) local event, arg = select(2, ...) if (event == "ADDON_LOADED") then local addon = string.lower(arg) if (addon:sub(1,4) == "auc-") then private.OnLoad(addon) end elseif (event == "AUCTION_HOUSE_SHOW") then -- Do Nothing for now elseif (event == "AUCTION_HOUSE_CLOSED") then AucAdvanced.Scan.Interrupt() elseif (event == "PLAYER_LOGOUT") then AucAdvanced.Scan.Commit(true) private.OnUnload() elseif event == "UNIT_INVENTORY_CHANGED" or event == "ITEM_LOCK_CHANGED" or event == "CURSOR_UPDATE" or event == "BAG_UPDATE" then private.Schedule["inventory"] = GetTime() + 0.15 end end function private.OnUpdate(...) if event == "inventory" then AucAdvanced.Post.AlertBagsChanged() end local now = GetTime() for event, time in pairs(private.Schedule) do if time > now then for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if engineLib.Processor then engineLib.Processor(event, time) end end end end private.Schedule[event] = nil end end private.Frame = CreateFrame("Frame") private.Frame:RegisterEvent("ADDON_LOADED") private.Frame:RegisterEvent("AUCTION_HOUSE_SHOW") private.Frame:RegisterEvent("AUCTION_HOUSE_CLOSED") private.Frame:RegisterEvent("UNIT_INVENTORY_CHANGED") private.Frame:RegisterEvent("ITEM_LOCK_CHANGED") private.Frame:RegisterEvent("CURSOR_UPDATE") private.Frame:RegisterEvent("BAG_UPDATE") private.Frame:RegisterEvent("PLAYER_LOGOUT") private.Frame:SetScript("OnEvent", private.OnEvent) private.Frame:SetScript("OnUpdate", private.OnUpdate) -- Auctioneer's debug functions AucAdvanced.Debug = {} local addonName = "Auctioneer" -- the addon's name as it will be displayed in -- the debug messages ------------------------------------------------------------------------------- -- Prints the specified message to nLog. -- -- syntax: -- errorCode, message = debugPrint([message][, category][, title][, errorCode][, level]) -- -- parameters: -- message - (string) the error message -- nil, no error message specified -- category - (string) the category of the debug message -- nil, no category specified -- title - (string) the title for the debug message -- nil, no title specified -- errorCode - (number) the error code -- nil, no error code specified -- level - (string) nLog message level -- Any nLog.levels string is valid. -- nil, no level specified -- -- returns: -- errorCode - (number) errorCode, if one is specified -- nil, otherwise -- message - (string) message, if one is specified -- nil, otherwise ------------------------------------------------------------------------------- function AucAdvanced.Debug.DebugPrint(message, category, title, errorCode, level) return DebugLib.DebugPrint(addonName, message, category, title, errorCode, level) end ------------------------------------------------------------------------------- -- Used to make sure that conditions are met within functions. -- If test is false, the error message will be written to nLog and the user's -- default chat channel. -- -- syntax: -- assertion = assert(test, message) -- -- parameters: -- test - (any) false/nil, if the assertion failed -- anything else, otherwise -- message - (string) the message which will be output to the user -- -- returns: -- assertion - (boolean) true, if the test passed -- false, otherwise ------------------------------------------------------------------------------- function AucAdvanced.Debug.Assert(test, message) return DebugLib.Assert(addonName, test, message) end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.ma000066400000000000000000000002771250413007300256500ustar00rootroot000000000000001 + 1 (* This is a comment *) Global` SomeNamespace`Foo f[x_, y__, 3, z___] := tsneirsnteintie "fosrt" neisnrteiasrn E + 3 Plus[1,Times[2,3]] Map[#1 + #2&, SomePairList] Plus[1.,-1,-1.,-1.0,]pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.monkey000066400000000000000000000050331250413007300265500ustar00rootroot00000000000000Strict ' single line comment #rem multi line comment #end #rem nested #rem multi line #end comment #end Import mojo Const ONECONST:Int = 1 Const TWOCONST := 2 Const THREECONST := 3, FOURCONST:Int = 4 Global someVariable:Int = 4 ' sample class from the documentation Class Game Extends App Function New() End Function DrawSpiral(clock) Local w=DeviceWidth/2 For Local i#=0 Until w*1.5 Step .2 Local x#,y# x=w+i*Sin(i*3+clock) y=w+i*Cos(i*2+clock) DrawRect x,y,1,1 Next hitbox.Collide(event.pos) End Field updateCount Method OnCreate() Print "spiral" SetUpdateRate 60 End Method OnUpdate() updateCount+=1 End Method OnRender() Cls DrawSpiral updateCount DrawSpiral updateCount*1.1 End End Class Enemy Method Die () Abstract End ' extending Class Hoodlum Extends Enemy ' field Field testField:Bool = True ' naming class with modulepath Local currentNode:list.Node Method Die () Print "B'oss, he-- he killed me, b'oss!" End End ' extending with generics Class VectorNode Extends Node End ' interfaces Interface Computer Method Boot () Method Process () Method Display () End Class PC Implements Computer End ' array syntax Global listOfStuff:String[42] Global lessStuff:String[5] = listOfStuff[4..8] Global oneStuff:String = listOfStuff[23] 'a comma separated sequence Global scores:Int[]=[10,20,30] 'a comma separated sequence Global text:String[]=["Hello","There","World"] Global worstCase:worst.List ' string type Global string1:String = "Hello world" Global string2$ = "Hello world" ' escape characers in strings Global string3 := "Hello~zWorld" Global string4 := "~qHello World~q" Global string5 := "~tIndented~n" Global string6 := "tilda is wavey... ~~" ' string pseudofunctions Print " Hello World ~n".Trim() ' prints "Hello World" Print "Hello World".ToUpper() ' prints "HELLO WORLD" ' Boolean shorttype Global boolVariable1:Bool = True Global boolVariable2? = False ' number formats Global hexNum1:Int = $3d0dead Global hexNum2% = $CAFEBABE Global floatNum1:Float = 3.141516 Global floatNum2# = 3.141516 Global floatNum3 := .141516 ' preprocessor keywords #If TARGET = "android" DoStuff() #ElseIf TARGET = "ios" DoOtherStuff() #End ' preprocessor variable #SOMETHING = True #Print SOMETHING #If SOMETHING #End ' operators Global a = 32 Global b = 32 ~ 0 b ~= 16 b |= 16 b &= 16 Global c = a | b pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.moo000066400000000000000000000017471250413007300260500ustar00rootroot00000000000000if (this.running) player:tell("[Train] Error: already a jump in progress"); return; endif this.running = 1; this.aborted = 0; this:announce_all("[Train] departure in 20 seconds"); dest = this.targets[random(length(this.targets))]; this:announce_all("[Train] Next stop is '", dest:title(), "'"); this:announce_all("You hear the engines starting up"); this.location:announce("The MOOTrain starts up his engines"); suspend(20); if (this.aborted) this.running = 0; this.aborted = 0; return; endif this:announce_all("[Train] Departure!"); this.location:announce_all("The MOOTrain leaves into the 42th dimension!"); this:announce_all("Outside you see the lights of the 42th dimension"); this:moveto(dest); suspend(4); this:announce_all("The glowing gets less, until you can see the clear shape of the room, the MOOTrain has landed in"); this.location:announce_all("The MOOTrain arrives out of the 42th dimension!"); this:announce_all("[Train] arrived in '", dest:title(), "'"); this.running = 0;pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.moon000066400000000000000000000350161250413007300262220ustar00rootroot00000000000000-- transform.moon -- Leaf Corcoran (leafot@gmail.com) 2011 -- -- This is part of the MoonScript compiler. See -- MoonScript is licensed under the MIT License -- module "moonscript.transform", package.seeall types = require "moonscript.types" util = require "moonscript.util" data = require "moonscript.data" import reversed from util import ntype, build, smart_node, is_slice from types import insert from table export Statement, Value, NameProxy, LocalName, Run -- always declares as local class LocalName new: (@name) => self[1] = "temp_name" get_name: => @name class NameProxy new: (@prefix) => self[1] = "temp_name" get_name: (scope) => if not @name @name = scope\free_name @prefix, true @name chain: (...) => items = {...} -- todo: fix ... propagation items = for i in *items if type(i) == "string" {"dot", i} else i build.chain { base: self unpack items } index: (key) => build.chain { base: self, {"index", key} } __tostring: => if @name ("name<%s>")\format @name else ("name")\format @prefix class Run new: (@fn) => self[1] = "run" call: (state) => self.fn state -- transform the last stm is a list of stms -- will puke on group apply_to_last = (stms, fn) -> -- find last (real) exp last_exp_id = 0 for i = #stms, 1, -1 stm = stms[i] if stm and util.moon.type(stm) != Run last_exp_id = i break return for i, stm in ipairs stms if i == last_exp_id fn stm else stm -- is a body a sindle expression/statement is_singular = (body) -> return false if #body != 1 if "group" == ntype body is_singular body[2] else true constructor_name = "new" class Transformer new: (@transformers, @scope) => @seen_nodes = {} transform: (scope, node, ...) => -- print scope, node, ... return node if @seen_nodes[node] @seen_nodes[node] = true while true transformer = @transformers[ntype node] res = if transformer transformer(scope, node, ...) or node else node return node if res == node node = res __call: (node, ...) => @transform @scope, node, ... instance: (scope) => Transformer @transformers, scope can_transform: (node) => @transformers[ntype node] != nil construct_comprehension = (inner, clauses) -> current_stms = inner for _, clause in reversed clauses t = clause[1] current_stms = if t == "for" _, names, iter = unpack clause {"foreach", names, iter, current_stms} elseif t == "when" _, cond = unpack clause {"if", cond, current_stms} else error "Unknown comprehension clause: "..t current_stms = {current_stms} current_stms[1] Statement = Transformer { assign: (node) => _, names, values = unpack node -- bubble cascading assigns if #values == 1 and types.cascading[ntype values[1]] values[1] = @transform.statement values[1], (stm) -> t = ntype stm if types.is_value stm {"assign", names, {stm}} else stm build.group { {"declare", names} values[1] } else node export: (node) => -- assign values if they are included if #node > 2 if node[2] == "class" cls = smart_node node[3] build.group { {"export", {cls.name}} cls } else build.group { node build.assign { names: node[2] values: node[3] } } else nil update: (node) => _, name, op, exp = unpack node op_final = op\match "^(.+)=$" error "Unknown op: "..op if not op_final build.assign_one name, {"exp", name, op_final, exp} import: (node) => _, names, source = unpack node stubs = for name in *names if type(name) == "table" name else {"dot", name} real_names = for name in *names type(name) == "table" and name[2] or name if type(source) == "string" build.assign { names: real_names values: [build.chain { base: source, stub} for stub in *stubs] } else source_name = NameProxy "table" build.group { {"declare", real_names} build["do"] { build.assign_one source_name, source build.assign { names: real_names values: [build.chain { base: source_name, stub} for stub in *stubs] } } } comprehension: (node, action) => _, exp, clauses = unpack node action = action or (exp) -> {exp} construct_comprehension action(exp), clauses -- handle cascading return decorator if: (node, ret) => if ret smart_node node -- mutate all the bodies node['then'] = apply_to_last node['then'], ret for i = 4, #node case = node[i] body_idx = #node[i] case[body_idx] = apply_to_last case[body_idx], ret node with: (node, ret) => _, exp, block = unpack node scope_name = NameProxy "with" build["do"] { build.assign_one scope_name, exp Run => @set "scope_var", scope_name build.group block if ret ret scope_name } foreach: (node) => smart_node node if ntype(node.iter) == "unpack" list = node.iter[2] index_name = NameProxy "index" list_name = NameProxy "list" slice_var = nil bounds = if is_slice list slice = list[#list] table.remove list table.remove slice, 1 slice[2] = if slice[2] and slice[2] != "" max_tmp_name = NameProxy "max" slice_var = build.assign_one max_tmp_name, slice[2] {"exp", max_tmp_name, "<", 0 "and", {"length", list_name}, "+", max_tmp_name "or", max_tmp_name } else {"length", list_name} slice else {1, {"length", list_name}} build.group { build.assign_one list_name, list slice_var build["for"] { name: index_name bounds: bounds body: { {"assign", node.names, {list_name\index index_name}} build.group node.body } } } switch: (node, ret) => _, exp, conds = unpack node exp_name = NameProxy "exp" -- convert switch conds into if statment conds convert_cond = (cond) -> t, case_exp, body = unpack cond out = {} insert out, t == "case" and "elseif" or "else" if t != "else" insert out, {"exp", case_exp, "==", exp_name} if t != "else" else body = case_exp if ret body = apply_to_last body, ret insert out, body out first = true if_stm = {"if"} for cond in *conds if_cond = convert_cond cond if first first = false insert if_stm, if_cond[2] insert if_stm, if_cond[3] else insert if_stm, if_cond build.group { build.assign_one exp_name, exp if_stm } class: (node) => _, name, parent_val, body = unpack node -- split apart properties and statements statements = {} properties = {} for item in *body switch item[1] when "stm" insert statements, item[2] when "props" for tuple in *item[2,] insert properties, tuple -- find constructor constructor = nil properties = for tuple in *properties if tuple[1] == constructor_name constructor = tuple[2] nil else tuple parent_cls_name = NameProxy "parent" base_name = NameProxy "base" self_name = NameProxy "self" cls_name = NameProxy "class" if not constructor constructor = build.fndef { args: {{"..."}} arrow: "fat" body: { build["if"] { cond: parent_cls_name then: { build.chain { base: "super", {"call", {"..."}} } } } } } else smart_node constructor constructor.arrow = "fat" cls = build.table { {"__init", constructor} {"__base", base_name} {"__name", {"string", '"', name}} -- "quote the string" {"__parent", parent_cls_name} } -- look up a name in the class object class_lookup = build["if"] { cond: {"exp", "val", "==", "nil", "and", parent_cls_name} then: { parent_cls_name\index"name" } } insert class_lookup, {"else", {"val"}} cls_mt = build.table { {"__index", build.fndef { args: {{"cls"}, {"name"}} body: { build.assign_one LocalName"val", build.chain { base: "rawget", {"call", {base_name, "name"}} } class_lookup } }} {"__call", build.fndef { args: {{"cls"}, {"..."}} body: { build.assign_one self_name, build.chain { base: "setmetatable" {"call", {"{}", base_name}} } build.chain { base: "cls.__init" {"call", {self_name, "..."}} } self_name } }} } cls = build.chain { base: "setmetatable" {"call", {cls, cls_mt}} } value = nil with build value = .block_exp { Run => @set "super", (block, chain) -> if chain slice = [item for item in *chain[3,]] new_chain = {"chain", parent_cls_name} head = slice[1] if head == nil return parent_cls_name switch head[1] -- calling super, inject calling name and self into chain when "call" calling_name = block\get"current_block" slice[1] = {"call", {"self", unpack head[2]}} act = if ntype(calling_name) != "value" then "index" else "dot" insert new_chain, {act, calling_name} -- colon call on super, replace class with self as first arg when "colon" call = head[3] insert new_chain, {"dot", head[2]} slice[1] = { "call", { "self", unpack call[2] } } insert new_chain, item for item in *slice new_chain else parent_cls_name .assign_one parent_cls_name, parent_val == "" and "nil" or parent_val .assign_one base_name, {"table", properties} .assign_one base_name\chain"__index", base_name build["if"] { cond: parent_cls_name then: { .chain { base: "setmetatable" {"call", { base_name, .chain { base: parent_cls_name, {"dot", "__base"}} }} } } } .assign_one cls_name, cls .assign_one base_name\chain"__class", cls_name .group if #statements > 0 { .assign_one LocalName"self", cls_name .group statements } else {} cls_name } value = .group { .declare names: {name} .assign { names: {name} values: {value} } } value } class Accumulator body_idx: { for: 4, while: 3, foreach: 4 } new: => @accum_name = NameProxy "accum" @value_name = NameProxy "value" @len_name = NameProxy "len" -- wraps node and mutates body convert: (node) => index = @body_idx[ntype node] node[index] = @mutate_body node[index] @wrap node -- wrap the node into a block_exp wrap: (node) => build.block_exp { build.assign_one @accum_name, build.table! build.assign_one @len_name, 0 node @accum_name } -- mutates the body of a loop construct to save last value into accumulator -- can optionally skip nil results mutate_body: (body, skip_nil=true) => val = if not skip_nil and is_singular body with body[1] body = {} else body = apply_to_last body, (n) -> build.assign_one @value_name, n @value_name update = { {"update", @len_name, "+=", 1} build.assign_one @accum_name\index(@len_name), val } if skip_nil table.insert body, build["if"] { cond: {"exp", @value_name, "!=", "nil"} then: update } else table.insert body, build.group update body default_accumulator = (node) => Accumulator!\convert node implicitly_return = (scope) -> fn = (stm) -> t = ntype stm if types.manual_return[t] or not types.is_value stm stm elseif types.cascading[t] scope.transform.statement stm, fn else if t == "comprehension" and not types.comprehension_has_value stm stm else {"return", stm} fn Value = Transformer { for: default_accumulator while: default_accumulator foreach: default_accumulator comprehension: (node) => a = Accumulator! node = @transform.statement node, (exp) -> a\mutate_body {exp}, false a\wrap node tblcomprehension: (node) => _, key_exp, value_exp, clauses = unpack node accum = NameProxy "tbl" dest = build.chain { base: accum, {"index", key_exp} } inner = build.assign_one dest, value_exp build.block_exp { build.assign_one accum, build.table! construct_comprehension {inner}, clauses accum } fndef: (node) => smart_node node node.body = apply_to_last node.body, implicitly_return self node if: (node) => build.block_exp { node } with: (node) => build.block_exp { node } switch: (node) => build.block_exp { node } -- pull out colon chain chain: (node) => stub = node[#node] if type(stub) == "table" and stub[1] == "colon_stub" table.remove node, #node base_name = NameProxy "base" fn_name = NameProxy "fn" is_super = node[2] == "super" @transform.value build.block_exp { build.assign { names: {base_name} values: {node} } build.assign { names: {fn_name} values: { build.chain { base: base_name, {"dot", stub[2]} } } } build.fndef { args: {{"..."}} body: { build.chain { base: fn_name, {"call", {is_super and "self" or base_name, "..."}} } } } } block_exp: (node) => _, body = unpack node fn = nil arg_list = {} insert body, Run => if @has_varargs insert arg_list, "..." insert fn.args, {"..."} fn = smart_node build.fndef body: body build.chain { base: {"parens", fn}, {"call", arg_list} } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.mq4000066400000000000000000000141261250413007300257520ustar00rootroot00000000000000//+------------------------------------------------------------------+ //| PeriodConverter.mq4 | //| Copyright 2006-2014, MetaQuotes Software Corp. | //| http://www.metaquotes.net | //+------------------------------------------------------------------+ #property copyright "2006-2014, MetaQuotes Software Corp." #property link "http://www.mql4.com" #property description "Period Converter to updated format of history base" #property strict #property show_inputs #include input int InpPeriodMultiplier=3; // Period multiplier factor int ExtHandle=-1; //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ void OnStart() { datetime time0; ulong last_fpos=0; long last_volume=0; int i,start_pos,periodseconds; int hwnd=0,cnt=0; //---- History header int file_version=401; string c_copyright; string c_symbol=Symbol(); int i_period=Period()*InpPeriodMultiplier; int i_digits=Digits; int i_unused[13]; MqlRates rate; //--- ExtHandle=FileOpenHistory(c_symbol+(string)i_period+".hst",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_ANSI); if(ExtHandle<0) return; c_copyright="(C)opyright 2003, MetaQuotes Software Corp."; ArrayInitialize(i_unused,0); //--- write history file header FileWriteInteger(ExtHandle,file_version,LONG_VALUE); FileWriteString(ExtHandle,c_copyright,64); FileWriteString(ExtHandle,c_symbol,12); FileWriteInteger(ExtHandle,i_period,LONG_VALUE); FileWriteInteger(ExtHandle,i_digits,LONG_VALUE); FileWriteInteger(ExtHandle,0,LONG_VALUE); FileWriteInteger(ExtHandle,0,LONG_VALUE); FileWriteArray(ExtHandle,i_unused,0,13); //--- write history file periodseconds=i_period*60; start_pos=Bars-1; rate.open=Open[start_pos]; rate.low=Low[start_pos]; rate.high=High[start_pos]; rate.tick_volume=(long)Volume[start_pos]; rate.spread=0; rate.real_volume=0; //--- normalize open time rate.time=Time[start_pos]/periodseconds; rate.time*=periodseconds; for(i=start_pos-1; i>=0; i--) { if(IsStopped()) break; time0=Time[i]; //--- history may be updated if(i==0) { //--- modify index if history was updated if(RefreshRates()) i=iBarShift(NULL,0,time0); } //--- if(time0>=rate.time+periodseconds || i==0) { if(i==0 && time0Low[0]) rate.low=Low[0]; if(rate.high=rate.time+periodseconds) { rate.time=time0/periodseconds; rate.time*=periodseconds; rate.open=Open[i]; rate.low=Low[i]; rate.high=High[i]; rate.close=Close[i]; rate.tick_volume=last_volume; } } else { rate.tick_volume+=(long)Volume[i]; if(rate.low>Low[i]) rate.low=Low[i]; if(rate.highLow[0]) rate.low=Low[0]; if(rate.highLow[1]) rate.low=Low[1]; if(rate.high=2) { PostMessageA(hwnd,WM_COMMAND,33324,0); last_time=cur_time; } } Sleep(50); } //--- } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- if(ExtHandle>=0) { FileClose(ExtHandle); ExtHandle=-1; } //--- } //+------------------------------------------------------------------+pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.mqh000066400000000000000000000114021250413007300260300ustar00rootroot00000000000000//+------------------------------------------------------------------+ //| Array.mqh | //| Copyright 2009-2013, MetaQuotes Software Corp. | //| http://www.mql4.com | //+------------------------------------------------------------------+ #include //+------------------------------------------------------------------+ //| Class CArray | //| Purpose: Base class of dynamic arrays. | //| Derives from class CObject. | //+------------------------------------------------------------------+ class CArray : public CObject { protected: int m_step_resize; // increment size of the array int m_data_total; // number of elements int m_data_max; // maximmum size of the array without memory reallocation int m_sort_mode; // mode of array sorting public: CArray(void); ~CArray(void); //--- methods of access to protected data int Step(void) const { return(m_step_resize); } bool Step(const int step); int Total(void) const { return(m_data_total); } int Available(void) const { return(m_data_max-m_data_total); } int Max(void) const { return(m_data_max); } bool IsSorted(const int mode=0) const { return(m_sort_mode==mode); } int SortMode(void) const { return(m_sort_mode); } //--- cleaning method void Clear(void) { m_data_total=0; } //--- methods for working with files virtual bool Save(const int file_handle); virtual bool Load(const int file_handle); //--- sorting method void Sort(const int mode=0); protected: virtual void QuickSort(int beg,int end,const int mode=0) { } }; //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CArray::CArray(void) : m_step_resize(16), m_data_total(0), m_data_max(0), m_sort_mode(-1) { } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CArray::~CArray(void) { } //+------------------------------------------------------------------+ //| Method Set for variable m_step_resize | //+------------------------------------------------------------------+ bool CArray::Step(const int step) { //--- check if(step>0) { m_step_resize=step; return(true); } //--- failure return(false); } //+------------------------------------------------------------------+ //| Sorting an array in ascending order | //+------------------------------------------------------------------+ void CArray::Sort(const int mode) { //--- check if(IsSorted(mode)) return; m_sort_mode=mode; if(m_data_total<=1) return; //--- sort QuickSort(0,m_data_total-1,mode); } //+------------------------------------------------------------------+ //| Writing header of array to file | //+------------------------------------------------------------------+ bool CArray::Save(const int file_handle) { //--- check handle if(file_handle!=INVALID_HANDLE) { //--- write start marker - 0xFFFFFFFFFFFFFFFF if(FileWriteLong(file_handle,-1)==sizeof(long)) { //--- write array type if(FileWriteInteger(file_handle,Type(),INT_VALUE)==INT_VALUE) return(true); } } //--- failure return(false); } //+------------------------------------------------------------------+ //| Reading header of array from file | //+------------------------------------------------------------------+ bool CArray::Load(const int file_handle) { //--- check handle if(file_handle!=INVALID_HANDLE) { //--- read and check start marker - 0xFFFFFFFFFFFFFFFF if(FileReadLong(file_handle)==-1) { //--- read and check array type if(FileReadInteger(file_handle,INT_VALUE)==Type()) return(true); } } //--- failure return(false); } //+------------------------------------------------------------------+ pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.msc000066400000000000000000000020771250413007300260350ustar00rootroot00000000000000msc { hscale=5; //test comment a,b,c,d; /* another comment goes here */ /* too */ // now ... [label="test1", id="1"]; --- [label="test2", id="2"]; ||| [label="test3", id="2"]; a ABOX b; a--b [label="test4", id="2"]; a == b [label="test5", id="2"]; a .. b [label="test6", id="2"]; a::b [label="test7", id="2"]; a<<=>> b [label="test8", id="2"], b <->c [label="test9", id="2"], b RBOX c; a BOX d; a<=> b [label="test10", id="2"]; a <<>> b [label="test11", id="2"]; a<:>b [label="test12", id="2"]; a->b [label="test13", id="2"]; a =>> b [label="test14", id="2"], b >> c [label="test15", id="2"], a=> b [label="test16", id="2"]; a :>b [label="test17", id="2"]; a-x b [label="test18", id="2"]; a -Xb [label="test19", id="2"]; a<- b [label="test20", id="2"]; a <<=b [label="test21", id="2"]; a<< b [label="test22", id="2"]; a <= b [label="test23", id="2"]; a<: b [label="test24", id="2"]; a -xb [label="test25", id="2"]; a-X b [ label="test26",id="2" ]; a->* [label="test27" , id="2"]; *<-b [label="test28",id="28"]; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.ni000066400000000000000000000021041250413007300256500ustar00rootroot00000000000000 | | | "Informal by Nature" [ * * * ] by [ * * * ] David Corbett [This is a [nested] comment.] Section 1 - Use option translation Use maximum tests of at least 100 translates as (- @c Constant MAX_TESTS = {N}; —). | Section 2 A room has a number called size. The Kitchen is a room. "A nondescript kitchen.“ The Kitchen has size 2. When play begins: say "Testing:[line break]"; test 0. To test (N — number): (— if (Test({N}) == (+size of the Kitchen [this should succeed]+)) {-open—brace} print â€Success.^â€; {-close-brace} else { print “Failure.^"; } ]; ! You shouldn't end a routine within a phrase definition, but it works. [ Unused; #Include "\ @p \ "; ! At signs hold no power here. ! Of course, the file "@p .h" must exist. -). Include (-!% This is not ICL. [ Test x; if (x) {x++;} {–! Single line comment.} @inc x; @p At signs. ... @Purpose: ... ... @-... @c ... @inc x; @c @c return x; ]; @Purpose: ... @------------------------------------------------------------------------------- -). pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.nim000066400000000000000000001045011250413007300260310ustar00rootroot00000000000000import glib2, gtk2, gdk2, gtksourceview, dialogs, os, pango, osproc, strutils import pegs, streams import settings, types, cfg, search {.push callConv:cdecl.} const NimrodProjectExt = ".nimprj" var win: types.MainWin win.Tabs = @[] search.win = addr(win) var lastSession: seq[string] = @[] var confParseFail = False # This gets set to true # When there is an error parsing the config # Load the settings try: win.settings = cfg.load(lastSession) except ECFGParse: # TODO: Make the dialog show the exception confParseFail = True win.settings = cfg.defaultSettings() except EIO: win.settings = cfg.defaultSettings() proc getProjectTab(): int = for i in 0..high(win.tabs): if win.tabs[i].filename.endswith(NimrodProjectExt): return i proc saveTab(tabNr: int, startpath: string) = if tabNr < 0: return if win.Tabs[tabNr].saved: return var path = "" if win.Tabs[tabNr].filename == "": path = ChooseFileToSave(win.w, startpath) # dialogs.nim STOCK_OPEN instead of STOCK_SAVE else: path = win.Tabs[tabNr].filename if path != "": var buffer = PTextBuffer(win.Tabs[tabNr].buffer) # Get the text from the TextView var startIter: TTextIter buffer.getStartIter(addr(startIter)) var endIter: TTextIter buffer.getEndIter(addr(endIter)) var text = buffer.getText(addr(startIter), addr(endIter), False) # Save it to a file var f: TFile if open(f, path, fmWrite): f.write(text) f.close() win.tempStuff.lastSaveDir = splitFile(path).dir # Change the tab name and .Tabs.filename etc. win.Tabs[tabNr].filename = path win.Tabs[tabNr].saved = True var name = extractFilename(path) var cTab = win.Tabs[tabNr] cTab.label.setText(name) else: error(win.w, "Unable to write to file") proc saveAllTabs() = for i in 0..high(win.tabs): saveTab(i, os.splitFile(win.tabs[i].filename).dir) # GTK Events # -- w(PWindow) proc destroy(widget: PWidget, data: pgpointer) {.cdecl.} = # gather some settings win.settings.VPanedPos = PPaned(win.sourceViewTabs.getParent()).getPosition() win.settings.winWidth = win.w.allocation.width win.settings.winHeight = win.w.allocation.height # save the settings win.save() # then quit main_quit() proc delete_event(widget: PWidget, event: PEvent, user_data: pgpointer): bool = var quit = True for i in low(win.Tabs)..len(win.Tabs)-1: if not win.Tabs[i].saved: var askSave = dialogNewWithButtons("", win.w, 0, STOCK_SAVE, RESPONSE_ACCEPT, STOCK_CANCEL, RESPONSE_CANCEL, "Close without saving", RESPONSE_REJECT, nil) askSave.setTransientFor(win.w) # TODO: Make this dialog look better var label = labelNew(win.Tabs[i].filename & " is unsaved, would you like to save it ?") PBox(askSave.vbox).pack_start(label, False, False, 0) label.show() var resp = askSave.run() gtk2.destroy(PWidget(askSave)) case resp of RESPONSE_ACCEPT: saveTab(i, os.splitFile(win.tabs[i].filename).dir) quit = True of RESPONSE_CANCEL: quit = False break of RESPONSE_REJECT: quit = True else: quit = False break # If False is returned the window will close return not quit proc windowState_Changed(widget: PWidget, event: PEventWindowState, user_data: pgpointer) = win.settings.winMaximized = (event.newWindowState and WINDOW_STATE_MAXIMIZED) != 0 # -- SourceView(PSourceView) & SourceBuffer proc updateStatusBar(buffer: PTextBuffer){.cdecl.} = # Incase this event gets fired before # bottomBar is initialized if win.bottomBar != nil and not win.tempStuff.stopSBUpdates: var iter: TTextIter win.bottomBar.pop(0) buffer.getIterAtMark(addr(iter), buffer.getInsert()) var row = getLine(addr(iter)) + 1 var col = getLineOffset(addr(iter)) discard win.bottomBar.push(0, "Line: " & $row & " Column: " & $col) proc cursorMoved(buffer: PTextBuffer, location: PTextIter, mark: PTextMark, user_data: pgpointer){.cdecl.} = updateStatusBar(buffer) proc onCloseTab(btn: PButton, user_data: PWidget) = if win.sourceViewTabs.getNPages() > 1: var tab = win.sourceViewTabs.pageNum(user_data) win.sourceViewTabs.removePage(tab) win.Tabs.delete(tab) proc onSwitchTab(notebook: PNotebook, page: PNotebookPage, pageNum: guint, user_data: pgpointer) = if win.Tabs.len()-1 >= pageNum: win.w.setTitle("Aporia IDE - " & win.Tabs[pageNum].filename) proc createTabLabel(name: string, t_child: PWidget): tuple[box: PWidget, label: PLabel] = var box = hboxNew(False, 0) var label = labelNew(name) var closebtn = buttonNew() closeBtn.setLabel(nil) var iconSize = iconSizeFromName("tabIconSize") if iconSize == 0: iconSize = iconSizeRegister("tabIconSize", 10, 10) var image = imageNewFromStock(STOCK_CLOSE, iconSize) discard gSignalConnect(closebtn, "clicked", G_Callback(onCloseTab), t_child) closebtn.setImage(image) gtk2.setRelief(closebtn, RELIEF_NONE) box.packStart(label, True, True, 0) box.packEnd(closebtn, False, False, 0) box.showAll() return (box, label) proc changed(buffer: PTextBuffer, user_data: pgpointer) = # Update the 'Line & Column' #updateStatusBar(buffer) # Change the tabs state to 'unsaved' # and add '*' to the Tab Name var current = win.SourceViewTabs.getCurrentPage() var name = "" if win.Tabs[current].filename == "": win.Tabs[current].saved = False name = "Untitled *" else: win.Tabs[current].saved = False name = extractFilename(win.Tabs[current].filename) & " *" var cTab = win.Tabs[current] cTab.label.setText(name) # Other(Helper) functions proc initSourceView(SourceView: var PWidget, scrollWindow: var PScrolledWindow, buffer: var PSourceBuffer) = # This gets called by addTab # Each tabs creates a new SourceView # SourceScrolledWindow(ScrolledWindow) scrollWindow = scrolledWindowNew(nil, nil) scrollWindow.setPolicy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) scrollWindow.show() # SourceView(gtkSourceView) SourceView = sourceViewNew(buffer) PSourceView(SourceView).setInsertSpacesInsteadOfTabs(True) PSourceView(SourceView).setIndentWidth(win.settings.indentWidth) PSourceView(SourceView).setShowLineNumbers(win.settings.showLineNumbers) PSourceView(SourceView).setHighlightCurrentLine( win.settings.highlightCurrentLine) PSourceView(SourceView).setShowRightMargin(win.settings.rightMargin) PSourceView(SourceView).setAutoIndent(win.settings.autoIndent) var font = font_description_from_string(win.settings.font) SourceView.modifyFont(font) scrollWindow.add(SourceView) SourceView.show() buffer.setHighlightMatchingBrackets( win.settings.highlightMatchingBrackets) # UGLY workaround for yet another compiler bug: discard gsignalConnect(buffer, "mark-set", GCallback(aporia.cursorMoved), nil) discard gsignalConnect(buffer, "changed", GCallback(aporia.changed), nil) # -- Set the syntax highlighter scheme buffer.setScheme(win.scheme) proc addTab(name, filename: string) = ## Adds a tab, if filename is not "" reads the file. And sets ## the tabs SourceViews text to that files contents. assert(win.nimLang != nil) var buffer: PSourceBuffer = sourceBufferNew(win.nimLang) if filename != nil and filename != "": var lang = win.langMan.guessLanguage(filename, nil) if lang != nil: buffer.setLanguage(lang) else: buffer.setHighlightSyntax(False) var nam = name if nam == "": nam = "Untitled" if filename == "": nam.add(" *") elif filename != "" and name == "": # Disable the undo/redo manager. buffer.begin_not_undoable_action() # Load the file. var file: string = readFile(filename) if file != nil: buffer.set_text(file, len(file)) # Enable the undo/redo manager. buffer.end_not_undoable_action() # Get the name.ext of the filename, for the tabs title nam = extractFilename(filename) # Init the sourceview var sourceView: PWidget var scrollWindow: PScrolledWindow initSourceView(sourceView, scrollWindow, buffer) var (TabLabel, labelText) = createTabLabel(nam, scrollWindow) # Add a tab discard win.SourceViewTabs.appendPage(scrollWindow, TabLabel) var nTab: Tab nTab.buffer = buffer nTab.sourceView = sourceView nTab.label = labelText nTab.saved = (filename != "") nTab.filename = filename win.Tabs.add(nTab) PTextView(SourceView).setBuffer(nTab.buffer) # GTK Events Contd. # -- TopMenu & TopBar proc newFile(menuItem: PMenuItem, user_data: pgpointer) = addTab("", "") win.sourceViewTabs.setCurrentPage(win.Tabs.len()-1) proc openFile(menuItem: PMenuItem, user_data: pgpointer) = var startpath = "" var currPage = win.SourceViewTabs.getCurrentPage() if currPage <% win.tabs.len: startpath = os.splitFile(win.tabs[currPage].filename).dir if startpath.len == 0: # Use lastSavePath as the startpath startpath = win.tempStuff.lastSaveDir if startpath.len == 0: startpath = os.getHomeDir() var files = ChooseFilesToOpen(win.w, startpath) if files.len() > 0: for f in items(files): try: addTab("", f) except EIO: error(win.w, "Unable to read from file") # Switch to the newly created tab win.sourceViewTabs.setCurrentPage(win.Tabs.len()-1) proc saveFile_Activate(menuItem: PMenuItem, user_data: pgpointer) = var current = win.SourceViewTabs.getCurrentPage() saveTab(current, os.splitFile(win.tabs[current].filename).dir) proc saveFileAs_Activate(menuItem: PMenuItem, user_data: pgpointer) = var current = win.SourceViewTabs.getCurrentPage() var (filename, saved) = (win.Tabs[current].filename, win.Tabs[current].saved) win.Tabs[current].saved = False win.Tabs[current].filename = "" saveTab(current, os.splitFile(filename).dir) # If the user cancels the save file dialog. Restore the previous filename # and saved state if win.Tabs[current].filename == "": win.Tabs[current].filename = filename win.Tabs[current].saved = saved proc undo(menuItem: PMenuItem, user_data: pgpointer) = var current = win.SourceViewTabs.getCurrentPage() if win.Tabs[current].buffer.canUndo(): win.Tabs[current].buffer.undo() proc redo(menuItem: PMenuItem, user_data: pgpointer) = var current = win.SourceViewTabs.getCurrentPage() if win.Tabs[current].buffer.canRedo(): win.Tabs[current].buffer.redo() proc find_Activate(menuItem: PMenuItem, user_data: pgpointer) = # Get the selected text, and set the findEntry to it. var currentTab = win.SourceViewTabs.getCurrentPage() var insertIter: TTextIter win.Tabs[currentTab].buffer.getIterAtMark(addr(insertIter), win.Tabs[currentTab].buffer.getInsert()) var insertOffset = addr(insertIter).getOffset() var selectIter: TTextIter win.Tabs[currentTab].buffer.getIterAtMark(addr(selectIter), win.Tabs[currentTab].buffer.getSelectionBound()) var selectOffset = addr(selectIter).getOffset() if insertOffset != selectOffset: var text = win.Tabs[currentTab].buffer.getText(addr(insertIter), addr(selectIter), false) win.findEntry.setText(text) win.findBar.show() win.findEntry.grabFocus() win.replaceEntry.hide() win.replaceLabel.hide() win.replaceBtn.hide() win.replaceAllBtn.hide() proc replace_Activate(menuitem: PMenuItem, user_data: pgpointer) = win.findBar.show() win.findEntry.grabFocus() win.replaceEntry.show() win.replaceLabel.show() win.replaceBtn.show() win.replaceAllBtn.show() proc settings_Activate(menuitem: PMenuItem, user_data: pgpointer) = settings.showSettings(win) proc viewBottomPanel_Toggled(menuitem: PCheckMenuItem, user_data: pgpointer) = win.settings.bottomPanelVisible = menuitem.itemGetActive() if win.settings.bottomPanelVisible: win.bottomPanelTabs.show() else: win.bottomPanelTabs.hide() var pegLineError = peg"{[^(]*} '(' {\d+} ', ' \d+ ') Error:' \s* {.*}" pegLineWarning = peg"{[^(]*} '(' {\d+} ', ' \d+ ') ' ('Warning:'/'Hint:') \s* {.*}" pegOtherError = peg"'Error:' \s* {.*}" pegSuccess = peg"'Hint: operation successful'.*" proc addText(textView: PTextView, text: string, colorTag: PTextTag = nil) = if text != nil: var iter: TTextIter textView.getBuffer().getEndIter(addr(iter)) if colorTag == nil: textView.getBuffer().insert(addr(iter), text, len(text)) else: textView.getBuffer().insertWithTags(addr(iter), text, len(text), colorTag, nil) proc createColor(textView: PTextView, name, color: string): PTextTag = var tagTable = textView.getBuffer().getTagTable() result = tagTable.tableLookup(name) if result == nil: result = textView.getBuffer().createTag(name, "foreground", color, nil) when not defined(os.findExe): proc findExe(exe: string): string = ## returns "" if the exe cannot be found result = addFileExt(exe, os.exeExt) if ExistsFile(result): return var path = os.getEnv("PATH") for candidate in split(path, pathSep): var x = candidate / result if ExistsFile(x): return x result = "" proc GetCmd(cmd, filename: string): string = var f = quoteIfContainsWhite(filename) if cmd =~ peg"\s* '$' y'findExe' '(' {[^)]+} ')' {.*}": var exe = quoteIfContainsWhite(findExe(matches[0])) if exe.len == 0: exe = matches[0] result = exe & " " & matches[1] % f else: result = cmd % f proc showBottomPanel() = if not win.settings.bottomPanelVisible: win.bottomPanelTabs.show() win.settings.bottomPanelVisible = true PCheckMenuItem(win.viewBottomPanelMenuItem).itemSetActive(true) # Scroll to the end of the TextView # This is stupid, it works sometimes... it's random var endIter: TTextIter win.outputTextView.getBuffer().getEndIter(addr(endIter)) discard win.outputTextView.scrollToIter( addr(endIter), 0.25, False, 0.0, 0.0) proc compileRun(currentTab: int, shouldRun: bool) = if win.Tabs[currentTab].filename.len == 0: return # Clear the outputTextView win.outputTextView.getBuffer().setText("", 0) var outp = osProc.execProcess(GetCmd(win.settings.nimrodCmd, win.Tabs[currentTab].filename)) # Colors var normalTag = createColor(win.outputTextView, "normalTag", "#3d3d3d") var errorTag = createColor(win.outputTextView, "errorTag", "red") var warningTag = createColor(win.outputTextView, "warningTag", "darkorange") var successTag = createColor(win.outputTextView, "successTag", "darkgreen") for x in outp.splitLines(): if x =~ pegLineError / pegOtherError: win.outputTextView.addText("\n" & x, errorTag) elif x=~ pegSuccess: win.outputTextView.addText("\n" & x, successTag) # Launch the process if shouldRun: var filename = changeFileExt(win.Tabs[currentTab].filename, os.ExeExt) var output = "\n" & osProc.execProcess(filename) win.outputTextView.addText(output) elif x =~ pegLineWarning: win.outputTextView.addText("\n" & x, warningTag) else: win.outputTextView.addText("\n" & x, normalTag) showBottomPanel() proc CompileCurrent_Activate(menuitem: PMenuItem, user_data: pgpointer) = saveFile_Activate(nil, nil) compileRun(win.SourceViewTabs.getCurrentPage(), false) proc CompileRunCurrent_Activate(menuitem: PMenuItem, user_data: pgpointer) = saveFile_Activate(nil, nil) compileRun(win.SourceViewTabs.getCurrentPage(), true) proc CompileProject_Activate(menuitem: PMenuItem, user_data: pgpointer) = saveAllTabs() compileRun(getProjectTab(), false) proc CompileRunProject_Activate(menuitem: PMenuItem, user_data: pgpointer) = saveAllTabs() compileRun(getProjectTab(), true) proc RunCustomCommand(cmd: string) = saveFile_Activate(nil, nil) var currentTab = win.SourceViewTabs.getCurrentPage() if win.Tabs[currentTab].filename.len == 0 or cmd.len == 0: return # Clear the outputTextView win.outputTextView.getBuffer().setText("", 0) var outp = osProc.execProcess(GetCmd(cmd, win.Tabs[currentTab].filename)) var normalTag = createColor(win.outputTextView, "normalTag", "#3d3d3d") for x in outp.splitLines(): win.outputTextView.addText("\n" & x, normalTag) showBottomPanel() proc RunCustomCommand1(menuitem: PMenuItem, user_data: pgpointer) = RunCustomCommand(win.settings.customCmd1) proc RunCustomCommand2(menuitem: PMenuItem, user_data: pgpointer) = RunCustomCommand(win.settings.customCmd2) proc RunCustomCommand3(menuitem: PMenuItem, user_data: pgpointer) = RunCustomCommand(win.settings.customCmd3) # -- FindBar proc nextBtn_Clicked(button: PButton, user_data: pgpointer) = findText(True) proc prevBtn_Clicked(button: PButton, user_data: pgpointer) = findText(False) proc replaceBtn_Clicked(button: PButton, user_data: pgpointer) = var currentTab = win.SourceViewTabs.getCurrentPage() var start, theEnd: TTextIter if not win.Tabs[currentTab].buffer.getSelectionBounds( addr(start), addr(theEnd)): # If no text is selected, try finding a match. findText(True) if not win.Tabs[currentTab].buffer.getSelectionBounds( addr(start), addr(theEnd)): # No match return # Remove the text win.Tabs[currentTab].buffer.delete(addr(start), addr(theEnd)) # Insert the replacement var text = getText(win.replaceEntry) win.Tabs[currentTab].buffer.insert(addr(start), text, len(text)) proc replaceAllBtn_Clicked(button: PButton, user_data: pgpointer) = var find = getText(win.findEntry) var replace = getText(win.replaceEntry) discard replaceAll(find, replace) proc closeBtn_Clicked(button: PButton, user_data: pgpointer) = win.findBar.hide() proc caseSens_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = win.settings.search = "casesens" proc caseInSens_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = win.settings.search = "caseinsens" proc style_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = win.settings.search = "style" proc regex_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = win.settings.search = "regex" proc peg_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = win.settings.search = "peg" proc extraBtn_Clicked(button: PButton, user_data: pgpointer) = var extraMenu = menuNew() var group: PGSList var caseSensMenuItem = radio_menu_item_new(group, "Case sensitive") extraMenu.append(caseSensMenuItem) discard signal_connect(caseSensMenuItem, "toggled", SIGNAL_FUNC(caseSens_Changed), nil) caseSensMenuItem.show() group = caseSensMenuItem.ItemGetGroup() var caseInSensMenuItem = radio_menu_item_new(group, "Case insensitive") extraMenu.append(caseInSensMenuItem) discard signal_connect(caseInSensMenuItem, "toggled", SIGNAL_FUNC(caseInSens_Changed), nil) caseInSensMenuItem.show() group = caseInSensMenuItem.ItemGetGroup() var styleMenuItem = radio_menu_item_new(group, "Style insensitive") extraMenu.append(styleMenuItem) discard signal_connect(styleMenuItem, "toggled", SIGNAL_FUNC(style_Changed), nil) styleMenuItem.show() group = styleMenuItem.ItemGetGroup() var regexMenuItem = radio_menu_item_new(group, "Regex") extraMenu.append(regexMenuItem) discard signal_connect(regexMenuItem, "toggled", SIGNAL_FUNC(regex_Changed), nil) regexMenuItem.show() group = regexMenuItem.ItemGetGroup() var pegMenuItem = radio_menu_item_new(group, "Pegs") extraMenu.append(pegMenuItem) discard signal_connect(pegMenuItem, "toggled", SIGNAL_FUNC(peg_Changed), nil) pegMenuItem.show() # Make the correct radio button active case win.settings.search of "casesens": PCheckMenuItem(caseSensMenuItem).ItemSetActive(True) of "caseinsens": PCheckMenuItem(caseInSensMenuItem).ItemSetActive(True) of "style": PCheckMenuItem(styleMenuItem).ItemSetActive(True) of "regex": PCheckMenuItem(regexMenuItem).ItemSetActive(True) of "peg": PCheckMenuItem(pegMenuItem).ItemSetActive(True) extraMenu.popup(nil, nil, nil, nil, 0, get_current_event_time()) # GUI Initialization proc createAccelMenuItem(toolsMenu: PMenu, accGroup: PAccelGroup, label: string, acc: gint, action: proc (i: PMenuItem, p: pgpointer)) = var result = menu_item_new(label) result.addAccelerator("activate", accGroup, acc, 0, ACCEL_VISIBLE) ToolsMenu.append(result) show(result) discard signal_connect(result, "activate", SIGNAL_FUNC(action), nil) proc createSeparator(menu: PMenu) = var sep = separator_menu_item_new() menu.append(sep) sep.show() proc initTopMenu(MainBox: PBox) = # Create a accelerator group, used for shortcuts # like CTRL + S in SaveMenuItem var accGroup = accel_group_new() add_accel_group(win.w, accGroup) # TopMenu(MenuBar) var TopMenu = menuBarNew() # FileMenu var FileMenu = menuNew() var NewMenuItem = menu_item_new("New") # New FileMenu.append(NewMenuItem) show(NewMenuItem) discard signal_connect(NewMenuItem, "activate", SIGNAL_FUNC(newFile), nil) createSeparator(FileMenu) var OpenMenuItem = menu_item_new("Open...") # Open... # CTRL + O OpenMenuItem.add_accelerator("activate", accGroup, KEY_o, CONTROL_MASK, ACCEL_VISIBLE) FileMenu.append(OpenMenuItem) show(OpenMenuItem) discard signal_connect(OpenMenuItem, "activate", SIGNAL_FUNC(aporia.openFile), nil) var SaveMenuItem = menu_item_new("Save") # Save # CTRL + S SaveMenuItem.add_accelerator("activate", accGroup, KEY_s, CONTROL_MASK, ACCEL_VISIBLE) FileMenu.append(SaveMenuItem) show(SaveMenuItem) discard signal_connect(SaveMenuItem, "activate", SIGNAL_FUNC(saveFile_activate), nil) var SaveAsMenuItem = menu_item_new("Save As...") # Save as... SaveAsMenuItem.add_accelerator("activate", accGroup, KEY_s, CONTROL_MASK or gdk2.SHIFT_MASK, ACCEL_VISIBLE) FileMenu.append(SaveAsMenuItem) show(SaveAsMenuItem) discard signal_connect(SaveAsMenuItem, "activate", SIGNAL_FUNC(saveFileAs_Activate), nil) var FileMenuItem = menuItemNewWithMnemonic("_File") FileMenuItem.setSubMenu(FileMenu) FileMenuItem.show() TopMenu.append(FileMenuItem) # Edit menu var EditMenu = menuNew() var UndoMenuItem = menu_item_new("Undo") # Undo EditMenu.append(UndoMenuItem) show(UndoMenuItem) discard signal_connect(UndoMenuItem, "activate", SIGNAL_FUNC(aporia.undo), nil) var RedoMenuItem = menu_item_new("Redo") # Undo EditMenu.append(RedoMenuItem) show(RedoMenuItem) discard signal_connect(RedoMenuItem, "activate", SIGNAL_FUNC(aporia.redo), nil) createSeparator(EditMenu) var FindMenuItem = menu_item_new("Find") # Find FindMenuItem.add_accelerator("activate", accGroup, KEY_f, CONTROL_MASK, ACCEL_VISIBLE) EditMenu.append(FindMenuItem) show(FindMenuItem) discard signal_connect(FindMenuItem, "activate", SIGNAL_FUNC(aporia.find_Activate), nil) var ReplaceMenuItem = menu_item_new("Replace") # Replace ReplaceMenuItem.add_accelerator("activate", accGroup, KEY_h, CONTROL_MASK, ACCEL_VISIBLE) EditMenu.append(ReplaceMenuItem) show(ReplaceMenuItem) discard signal_connect(ReplaceMenuItem, "activate", SIGNAL_FUNC(aporia.replace_Activate), nil) createSeparator(EditMenu) var SettingsMenuItem = menu_item_new("Settings...") # Settings EditMenu.append(SettingsMenuItem) show(SettingsMenuItem) discard signal_connect(SettingsMenuItem, "activate", SIGNAL_FUNC(aporia.Settings_Activate), nil) var EditMenuItem = menuItemNewWithMnemonic("_Edit") EditMenuItem.setSubMenu(EditMenu) EditMenuItem.show() TopMenu.append(EditMenuItem) # View menu var ViewMenu = menuNew() win.viewBottomPanelMenuItem = check_menu_item_new("Bottom Panel") PCheckMenuItem(win.viewBottomPanelMenuItem).itemSetActive( win.settings.bottomPanelVisible) win.viewBottomPanelMenuItem.add_accelerator("activate", accGroup, KEY_f9, CONTROL_MASK, ACCEL_VISIBLE) ViewMenu.append(win.viewBottomPanelMenuItem) show(win.viewBottomPanelMenuItem) discard signal_connect(win.viewBottomPanelMenuItem, "toggled", SIGNAL_FUNC(aporia.viewBottomPanel_Toggled), nil) var ViewMenuItem = menuItemNewWithMnemonic("_View") ViewMenuItem.setSubMenu(ViewMenu) ViewMenuItem.show() TopMenu.append(ViewMenuItem) # Tools menu var ToolsMenu = menuNew() createAccelMenuItem(ToolsMenu, accGroup, "Compile current file", KEY_F4, aporia.CompileCurrent_Activate) createAccelMenuItem(ToolsMenu, accGroup, "Compile & run current file", KEY_F5, aporia.CompileRunCurrent_Activate) createSeparator(ToolsMenu) createAccelMenuItem(ToolsMenu, accGroup, "Compile project", KEY_F8, aporia.CompileProject_Activate) createAccelMenuItem(ToolsMenu, accGroup, "Compile & run project", KEY_F9, aporia.CompileRunProject_Activate) createSeparator(ToolsMenu) createAccelMenuItem(ToolsMenu, accGroup, "Run custom command 1", KEY_F1, aporia.RunCustomCommand1) createAccelMenuItem(ToolsMenu, accGroup, "Run custom command 2", KEY_F2, aporia.RunCustomCommand2) createAccelMenuItem(ToolsMenu, accGroup, "Run custom command 3", KEY_F3, aporia.RunCustomCommand3) var ToolsMenuItem = menuItemNewWithMnemonic("_Tools") ToolsMenuItem.setSubMenu(ToolsMenu) ToolsMenuItem.show() TopMenu.append(ToolsMenuItem) # Help menu MainBox.packStart(TopMenu, False, False, 0) TopMenu.show() proc initToolBar(MainBox: PBox) = # TopBar(ToolBar) var TopBar = toolbarNew() TopBar.setStyle(TOOLBAR_ICONS) var NewFileItem = TopBar.insertStock(STOCK_NEW, "New File", "New File", SIGNAL_FUNC(aporia.newFile), nil, 0) TopBar.appendSpace() var OpenItem = TopBar.insertStock(STOCK_OPEN, "Open", "Open", SIGNAL_FUNC(aporia.openFile), nil, -1) var SaveItem = TopBar.insertStock(STOCK_SAVE, "Save", "Save", SIGNAL_FUNC(saveFile_Activate), nil, -1) TopBar.appendSpace() var UndoItem = TopBar.insertStock(STOCK_UNDO, "Undo", "Undo", SIGNAL_FUNC(aporia.undo), nil, -1) var RedoItem = TopBar.insertStock(STOCK_REDO, "Redo", "Redo", SIGNAL_FUNC(aporia.redo), nil, -1) MainBox.packStart(TopBar, False, False, 0) TopBar.show() proc initSourceViewTabs() = win.SourceViewTabs = notebookNew() #win.sourceViewTabs.dragDestSet(DEST_DEFAULT_DROP, nil, 0, ACTION_MOVE) discard win.SourceViewTabs.signalConnect( "switch-page", SIGNAL_FUNC(onSwitchTab), nil) #discard win.SourceViewTabs.signalConnect( # "drag-drop", SIGNAL_FUNC(svTabs_DragDrop), nil) #discard win.SourceViewTabs.signalConnect( # "drag-data-received", SIGNAL_FUNC(svTabs_DragDataRecv), nil) #discard win.SourceViewTabs.signalConnect( # "drag-motion", SIGNAL_FUNC(svTabs_DragMotion), nil) win.SourceViewTabs.set_scrollable(True) win.SourceViewTabs.show() if lastSession.len != 0: for i in 0 .. len(lastSession)-1: var splitUp = lastSession[i].split('|') var (filename, offset) = (splitUp[0], splitUp[1]) addTab("", filename) var iter: TTextIter win.Tabs[i].buffer.getIterAtOffset(addr(iter), offset.parseInt()) win.Tabs[i].buffer.moveMarkByName("insert", addr(iter)) win.Tabs[i].buffer.moveMarkByName("selection_bound", addr(iter)) # TODO: Fix this..... :( discard PTextView(win.Tabs[i].sourceView). scrollToIter(addr(iter), 0.25, true, 0.0, 0.0) else: addTab("", "") # This doesn't work :\ win.Tabs[0].sourceView.grabFocus() proc initBottomTabs() = win.bottomPanelTabs = notebookNew() if win.settings.bottomPanelVisible: win.bottomPanelTabs.show() # output tab var tabLabel = labelNew("Output") var outputTab = vboxNew(False, 0) discard win.bottomPanelTabs.appendPage(outputTab, tabLabel) # Compiler tabs, gtktextview var outputScrolledWindow = scrolledwindowNew(nil, nil) outputScrolledWindow.setPolicy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) outputTab.packStart(outputScrolledWindow, true, true, 0) outputScrolledWindow.show() win.outputTextView = textviewNew() outputScrolledWindow.add(win.outputTextView) win.outputTextView.show() outputTab.show() proc initTAndBP(MainBox: PBox) = # This init's the HPaned, which splits the sourceViewTabs # and the BottomPanelTabs initSourceViewTabs() initBottomTabs() var TAndBPVPaned = vpanedNew() tandbpVPaned.pack1(win.sourceViewTabs, resize=True, shrink=False) tandbpVPaned.pack2(win.bottomPanelTabs, resize=False, shrink=False) MainBox.packStart(TAndBPVPaned, True, True, 0) tandbpVPaned.setPosition(win.settings.VPanedPos) TAndBPVPaned.show() proc initFindBar(MainBox: PBox) = # Create a fixed container win.findBar = HBoxNew(False, 0) win.findBar.setSpacing(4) # Add a Label 'Find' var findLabel = labelNew("Find:") win.findBar.packStart(findLabel, False, False, 0) findLabel.show() # Add a (find) text entry win.findEntry = entryNew() win.findBar.packStart(win.findEntry, False, False, 0) discard win.findEntry.signalConnect("activate", SIGNAL_FUNC( aporia.nextBtn_Clicked), nil) win.findEntry.show() var rq: TRequisition win.findEntry.sizeRequest(addr(rq)) # Make the (find) text entry longer win.findEntry.set_size_request(190, rq.height) # Add a Label 'Replace' # - This Is only shown, when the 'Search & Replace'(CTRL + H) is shown win.replaceLabel = labelNew("Replace:") win.findBar.packStart(win.replaceLabel, False, False, 0) #replaceLabel.show() # Add a (replace) text entry # - This Is only shown, when the 'Search & Replace'(CTRL + H) is shown win.replaceEntry = entryNew() win.findBar.packStart(win.replaceEntry, False, False, 0) #win.replaceEntry.show() var rq1: TRequisition win.replaceEntry.sizeRequest(addr(rq1)) # Make the (replace) text entry longer win.replaceEntry.set_size_request(100, rq1.height) # Find next button var nextBtn = buttonNew("Next") win.findBar.packStart(nextBtn, false, false, 0) discard nextBtn.signalConnect("clicked", SIGNAL_FUNC(aporia.nextBtn_Clicked), nil) nextBtn.show() var nxtBtnRq: TRequisition nextBtn.sizeRequest(addr(nxtBtnRq)) # Find previous button var prevBtn = buttonNew("Previous") win.findBar.packStart(prevBtn, false, false, 0) discard prevBtn.signalConnect("clicked", SIGNAL_FUNC(aporia.prevBtn_Clicked), nil) prevBtn.show() # Replace button # - This Is only shown, when the 'Search & Replace'(CTRL + H) is shown win.replaceBtn = buttonNew("Replace") win.findBar.packStart(win.replaceBtn, false, false, 0) discard win.replaceBtn.signalConnect("clicked", SIGNAL_FUNC(aporia.replaceBtn_Clicked), nil) #replaceBtn.show() # Replace all button # - this Is only shown, when the 'Search & Replace'(CTRL + H) is shown win.replaceAllBtn = buttonNew("Replace All") win.findBar.packStart(win.replaceAllBtn, false, false, 0) discard win.replaceAllBtn.signalConnect("clicked", SIGNAL_FUNC(aporia.replaceAllBtn_Clicked), nil) #replaceAllBtn.show() # Right side ... # Close button - With a close stock image var closeBtn = buttonNew() var closeImage = imageNewFromStock(STOCK_CLOSE, ICON_SIZE_SMALL_TOOLBAR) var closeBox = hboxNew(False, 0) closeBtn.add(closeBox) closeBox.show() closeBox.add(closeImage) closeImage.show() discard closeBtn.signalConnect("clicked", SIGNAL_FUNC(aporia.closeBtn_Clicked), nil) win.findBar.packEnd(closeBtn, False, False, 2) closeBtn.show() # Extra button - When clicked shows a menu with options like 'Use regex' var extraBtn = buttonNew() var extraImage = imageNewFromStock(STOCK_PROPERTIES, ICON_SIZE_SMALL_TOOLBAR) var extraBox = hboxNew(False, 0) extraBtn.add(extraBox) extraBox.show() extraBox.add(extraImage) extraImage.show() discard extraBtn.signalConnect("clicked", SIGNAL_FUNC(aporia.extraBtn_Clicked), nil) win.findBar.packEnd(extraBtn, False, False, 0) extraBtn.show() MainBox.packStart(win.findBar, False, False, 0) win.findBar.show() proc initStatusBar(MainBox: PBox) = win.bottomBar = statusbarNew() MainBox.packStart(win.bottomBar, False, False, 0) win.bottomBar.show() discard win.bottomBar.push(0, "Line: 0 Column: 0") proc initControls() = # Load up the language style win.langMan = languageManagerGetDefault() var langpaths: array[0..1, cstring] = [cstring(os.getApplicationDir() / langSpecs), nil] win.langMan.setSearchPath(addr(langpaths)) var nimLang = win.langMan.getLanguage("nimrod") win.nimLang = nimLang # Load the scheme var schemeMan = schemeManagerGetDefault() var schemepaths: array[0..1, cstring] = [cstring(os.getApplicationDir() / styles), nil] schemeMan.setSearchPath(addr(schemepaths)) win.scheme = schemeMan.getScheme(win.settings.colorSchemeID) # Window win.w = windowNew(gtk2.WINDOW_TOPLEVEL) win.w.setDefaultSize(win.settings.winWidth, win.settings.winHeight) win.w.setTitle("Aporia IDE") if win.settings.winMaximized: win.w.maximize() win.w.show() # The window has to be shown before # setting the position of the VPaned so that # it gets set correctly, when the window is maximized. discard win.w.signalConnect("destroy", SIGNAL_FUNC(aporia.destroy), nil) discard win.w.signalConnect("delete_event", SIGNAL_FUNC(aporia.delete_event), nil) discard win.w.signalConnect("window-state-event", SIGNAL_FUNC(aporia.windowState_Changed), nil) # MainBox (vbox) var MainBox = vboxNew(False, 0) win.w.add(MainBox) initTopMenu(MainBox) initToolBar(MainBox) initTAndBP(MainBox) initFindBar(MainBox) initStatusBar(MainBox) MainBox.show() if confParseFail: dialogs.warning(win.w, "Error parsing config file, using default settings.") nimrod_init() initControls() main() pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.nix000066400000000000000000000046201250413007300260450ustar00rootroot00000000000000{ stdenv, fetchurl, fetchgit, openssl, zlib, pcre, libxml2, libxslt, expat , rtmp ? false , fullWebDAV ? false , syslog ? false , moreheaders ? false, ...}: let version = "1.4.4"; mainSrc = fetchurl { url = "http://nginx.org/download/nginx-${version}.tar.gz"; sha256 = "1f82845mpgmhvm151fhn2cnqjggw9w7cvsqbva9rb320wmc9m63w"; }; rtmp-ext = fetchgit { url = git://github.com/arut/nginx-rtmp-module.git; rev = "1cfb7aeb582789f3b15a03da5b662d1811e2a3f1"; sha256 = "03ikfd2l8mzsjwx896l07rdrw5jn7jjfdiyl572yb9jfrnk48fwi"; }; dav-ext = fetchgit { url = git://github.com/arut/nginx-dav-ext-module.git; rev = "54cebc1f21fc13391aae692c6cce672fa7986f9d"; sha256 = "1dvpq1fg5rslnl05z8jc39sgnvh3akam9qxfl033akpczq1bh8nq"; }; syslog-ext = fetchgit { url = https://github.com/yaoweibin/nginx_syslog_patch.git; rev = "165affd9741f0e30c4c8225da5e487d33832aca3"; sha256 = "14dkkafjnbapp6jnvrjg9ip46j00cr8pqc2g7374z9aj7hrvdvhs"; }; moreheaders-ext = fetchgit { url = https://github.com/agentzh/headers-more-nginx-module.git; rev = "refs/tags/v0.23"; sha256 = "12pbjgsxnvcf2ff2i2qdn39q4cm5czlgrng96j8ml4cgxvnbdh39"; }; in stdenv.mkDerivation rec { name = "nginx-${version}"; src = mainSrc; buildInputs = [ openssl zlib pcre libxml2 libxslt ] ++ stdenv.lib.optional fullWebDAV expat; patches = if syslog then [ "${syslog-ext}/syslog_1.4.0.patch" ] else []; configureFlags = [ "--with-http_ssl_module" "--with-http_spdy_module" "--with-http_xslt_module" "--with-http_sub_module" "--with-http_dav_module" "--with-http_gzip_static_module" "--with-http_secure_link_module" "--with-ipv6" # Install destination problems # "--with-http_perl_module" ] ++ stdenv.lib.optional rtmp "--add-module=${rtmp-ext}" ++ stdenv.lib.optional fullWebDAV "--add-module=${dav-ext}" ++ stdenv.lib.optional syslog "--add-module=${syslog-ext}" ++ stdenv.lib.optional moreheaders "--add-module=${moreheaders-ext}"; preConfigure = '' export NIX_CFLAGS_COMPILE="$NIX_CFLAGS_COMPILE -I${libxml2 }/include/libxml2" ''; # escape example postInstall = '' mv $out/sbin $out/bin ''' ''${ ${ if true then ${ "" } else false } ''; meta = { description = "A reverse proxy and lightweight webserver"; maintainers = [ stdenv.lib.maintainers.raskin]; platforms = stdenv.lib.platforms.all; inherit version; }; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.ns2000066400000000000000000000021611250413007300257470ustar00rootroot00000000000000Newsqueak2 'Langexplr ' class ShapesExperiment usingLib: platform = ( "A small experiment for using Hopscotch shape classes ." | CanvasDependent = platform CanvasDependent. Presenter = platform HPresenter. Subject = platform Subject. EllipseShape = platform EllipseShape. Color = platform Color. | ) ( class ShapesExperimentSubject = Subject( "Subject for shapes experiment" | | ) ('as yet unclassified' createPresenter = ( ^ShapesExperimentPresenter new subject: self. ) ) class ShapesExperimentPresenter = Presenter ( "A presenter for a small experiment of using shape classes" | | ) ('as yet unclassified' controlPoint = ( ^ControlPoint new. ) definition = ( ^ column: { canvas: { at: 10 @ 10 display: controlPoint. at: 15 @ 10 display: controlPoint. } } ) ) class ControlPoint = CanvasDependent( "A class that represents a small point in the screen" | | ) ('as yet unclassified' addVisualsTo: container = ( container add: visual. updateLayout. ) createVisual = ( | s | s:: EllipseShape new size: 5@5 . s color: Color red. ^ s ) )) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.pas000066400000000000000000001724731250413007300260460ustar00rootroot00000000000000// vim:ft=pascal unit YTools; {=============================================================================== cYcnus.YTools 1.0.3 Beta for Delphi 4+ by licenser and Murphy ©2000-2003 by cYcnus visit www.cYcnus.de licenser@cYcnus.de (Heinz N. Gies) murphy@cYcnus.de (Kornelius Kalnbach) this unit is published under the terms of the GPL ===============================================================================} interface uses Windows, SysUtils, Classes, YTypes; const BackSpace = #8; Tab = #9; LF = #10; //Line Feed CR = #13; //Carriage Return Space = #32; EOLChars = [CR, LF]; {$IFNDEF VER140} sLineBreak = #13#10; SwitchChars = ['/', '-']; {$ENDIF} EOL = sLineBreak; MaxCard = High(Cardinal); AllChars = [#0..#255]; Alphabetical = ['A'..'Z', 'a'..'z']; DecimalChars = ['0'..'9']; AlphaNumerical = Alphabetical + DecimalChars; StrangeChars = [#0..#31, #127, #129, #141..#144, #157, #158]; HexadecimalChars = DecimalChars + ['A'..'F', 'a'..'f']; OctalChars = ['0'..'7']; BinaryChars = ['0', '1']; QuoteChars = ['''', '"']; WildCards = ['*', '?']; FileNameEnemies = WildCards + ['\', '/', ':', '<', '>', '|']; HexChar: array[THex] of Char = ( '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); LowerHexChar: array[THex] of Char = ( '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); BaseNChar: array[TBaseN] of Char = ( '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H', 'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'); cYcnusOverlayColor = $050001; faFindEveryFile = faReadOnly + faHidden + faSysFile + faArchive; platWin9x = [VER_PLATFORM_WIN32s, VER_PLATFORM_WIN32_WINDOWS]; { Debugging } procedure ClearReport(const ReportName: string); procedure Report(const ReportName, Text: string); procedure ReportFmt(const ReportName, Fmt: string; const Args: array of const); { Params } procedure GetParams(Strings: TStrings); overload; function GetParams(const Separator: string = ' '): string; overload; function ParamNum(const S: string): Integer; function ParamPrefixNum(const Prefix: string): Integer; function Param(const S: string): Boolean; function ParamPrefix(const Prefix: string): Boolean; function Switch(const Switch: string; const PrefixChars: TCharSet = SwitchChars; IgnoreCase: Boolean = True): Boolean; function GetParam(const Prefix: string = ''; const Default: string = ''): string; { Dirs & UserName} function GetMyDir(FullPath: Boolean = False): string; function WinDir: string; function SysDir: string; function UserName: string; { Strings & Chars} function FirstChar(const S: string): Char; function LastChar(const S: string): Char; function CharPos(C: Char; const S: string; Offset: Integer = 1): Integer; overload; function CharPos(C: TCharSet; const S: string; Offset: Integer = 1): Integer; overload; function CharPosR(C: Char; const S: string; Offset: Integer = -1): Integer; function PosEx(const SubStr, S: string; Offset: Integer = 1): Integer; function PosExText(const SubStr, S: string; Offset: Integer = 1): Integer; function PosExAnsiText(const SubStr, S: string; Offset: Integer = 1): Integer; function UntilChar(const S: string; Brake: Char): string; overload; function UntilChar(const S: string; Brake: TCharSet): string; overload; function UntilLastChar(const S: string; Brake: Char; IgnoreNoBrake: Boolean = True): string; function FromChar(const S: string; Brake: Char): string; overload; function FromChar(const S: string; Brake: TCharSet): string; overload; function FromLastChar(const S: string; Brake: Char; IgnoreNoBrake: Boolean = False): string; function BetweenChars(const S: string; Start, Finish: Char; Inclusive: Boolean = False): string; function UntilStr(const S: string; Brake: string): string; function FromStr(const S: string; Brake: string): string; function StringWrap(const S: string; Width: Integer; const LineEnd: string = EOL): string; { Splitting & Combining } function Split(const S, Separator: string; IgnoreMultiSep: Boolean = True; MinCount: Integer = 0): TStrA; overload; procedure Split(const S, Separator: string; Strings: TStrings; IgnoreMultiSep: Boolean = True); overload; function Split(const S: string; Separators: TCharSet; IgnoreMultiSep: Boolean = True; MinCount: Integer = 0): TStrA; overload; procedure TileStr(const S: string; BrakeStart: Integer; BrakeEnd: Integer; out Left, Right: string); function Join(Strings: TStrings; Separator: string = ' '): string; overload; function Join(StrA: TStrA; Separator: string = ' '): string; overload; function MulStr(const S: string; Count: Integer): string; { Strings ausrichten } function AlignR(const S: string; Width: Integer; Filler: Char = ' '): string; function MaxStr(const S: string; MaxLen: Integer): string; { Stringing } function TrimAll(const S: string): string; function ControlChar(C: Char): Boolean; function FriendlyChar(C: Char): Char; function FriendlyStr(const S: string): string; overload; function FriendlyStr(a: TByteA): string; overload; function Quote(const S: string; Quoter: Char = '"'): string; function UnQuote(const S: string): string; function DeQuote(const S: string): string; function StrNumerus(const Value: Integer; const Singular, Plural: string; const Zero: string = '0'): string; function MakeStr(const Items: array of const; Separator: string = ''): string; procedure ShowText(const Items: array of const; Separator: string = ''); { Delete } function DeleteChars(const S: string; C: Char): string; overload; function DeleteChars(const S: string; C: TCharSet): string; overload; function ExtractChars(const S: string; C: TCharSet): string; { Find } function CharCount(const S: string; C: Char): Integer; function CharIn(const S: string; C: Char): Boolean; overload; function CharIn(const S: string; C: TCharSet): Boolean; overload; function StrAtPos(const S: string; Pos: Integer; const Str: string): Boolean; function StrAtBegin(const S, Str: string): Boolean; function StrIn(const S, SubStr: string): Boolean; overload; function StrIn(A: TStrA; const S: string): Boolean; overload; function StrIn(SL: TStrings; const S: string): Boolean; overload; function StrIndex(A: TStrA; const S: string): Integer; overload; function StrIndex(SL: TStrings; const S: string): Integer; overload; function TextAtPos(const S: string; Pos: Integer; const Text: string): Boolean; function TextAtBegin(const S, Text: string): Boolean; function TextIn(const S, Text: string): Boolean; overload; function TextIn(A: TStrA; const Text: string): Boolean; overload; function TextIn(SL: TStrings; const Text: string): Boolean; overload; function TextIndex(A: TStrA; const Text: string): Integer; overload; function TextIndex(SL: TStrings; const Text: string): Integer; overload; { Replace } function ReplaceChars(const S: string; Old, New: Char): string; overload; function ReplaceChars(const S: string; Old: TCharSet; New: Char): string; overload; function Replace(const S, Old, New: string): string; { TStrings } function SLOfFile(const FileName: string): TStringList; function ContainsEmptyLines(SL: TStrings): Boolean; procedure DeleteEmptyLines(SL: TStrings); procedure DeleteCommentLines(SL: TStrings; const CommentSign: string = '//'); procedure WriteSL(Strings: TStrings; const Prefix: string = ''; const Suffix: string = ''); function FindLine(SL: TStrings; const S: string): Integer; procedure QuickSortSL(SL: TStringList); { TStrA } function IncStrA(StrA: TStrA): Integer; { TByteA } function StrOfByteA(a: TByteA): string; function ByteAOfStr(const S: string): TByteA; function ByteAOfInt(i: Integer): TByteA; function IntOfByteA(A: TByteA): Integer; function ByteAOfHex(const Hex: string): TByteA; function SameByteA(const A, B: TByteA): Boolean; function Reverse(a: TByteA): TByteA; function SaveByteA(Data: TByteA; const FileName: string; Overwrite: Boolean = True): Boolean; function LoadByteA(const FileName: string): TByteA; function Endian(i: Integer): Integer; { Files } function SizeOfFile(const FileName: string): Integer; function FileEx(const FileName: string; AllowFolders: Boolean = False): Boolean; function LWPSolve(const Dir: string): string; function LWPSlash(const Dir: string): string; function ExtractDrive(const FileName: string): string; function ExtractPath(const FileName: string): string; function ExtractPrefix(const FileName: string): string; function ExtractSuffix(const FileName: string): string; function IsValidFileName(const FileName: string): Boolean; function MakeValidFileName(FileName: string; const Default: string = 'File'): string; { Converting } function IsValidInteger(const S: string): Boolean; function IsValidCardinal(const S: string): Boolean; function StrOfBool(flag: Boolean; const TrueStr: string = 'True'; const FalseStr: string = 'False'): string; function StrOfInt(i: Integer): string; function CardOfStr(const S: string): Cardinal; function HexOrd(Hex: Char): THex; function ByteOfHex(Hex: THexByteStr): Byte; function DecOfHex(const Hex: string): string; function HexOfByte(b: Byte): THexByteStr; function HexOfCard(i: Cardinal): string; overload; function HexOfCard(i: Cardinal; Digits: Integer): string; overload; function PascalHexArray(a: TByteA; Name: string): string; function HexOfByteA(a: TByteA; Blocks: Integer = 1; const Splitter: string = ' '): string; function BinOfByteA(a: TByteA; Blocks: Integer = 4; const Splitter: string = ' '): string; function CardOfHex(Hex: string): Cardinal; function IntOfBin(Bin: string): Cardinal; function BinOfIntFill(n: cardinal; MinCount: Integer = 8): string; function BinOfInt(n: cardinal): string; function BaseNOfInt(I: Cardinal; B: TBaseN): string; function IntOfBaseN(V: string; B: TBaseN): Cardinal; { Ranges } function KeepIn(i, Bottom, Top: Variant): Variant; function InRange(Value, Bottom, Top: Variant): Boolean; function InStrictRange(Value, Bottom, Top: Variant): Boolean; function Min(const A, B: Integer): Integer; overload; function Min(const A: TIntA): Integer; overload; function Max(const A, B: Integer): Integer; overload; function Max(const A: TIntA): Integer; overload; const RangesSeparator = ','; RangeInnerSeparator = '-'; RangeInfinite = '*'; RangeSpecialChars = [RangesSeparator, RangeInnerSeparator, RangeInfinite]; function RangesOfStr(const S: string): TRanges; function InRanges(Ranges: TRanges; TestValue: Cardinal): Boolean; function Success(Res: Integer; ResultOnSuccess: Integer = ERROR_SUCCESS): Boolean; function Failure(Res: Integer; ResultOnSuccess: Integer = ERROR_SUCCESS): Boolean; function ExpandString(const S: string): string; { Files } procedure DeleteFiles(const Mask: string; ScanSubDirs: Boolean = True; Attributes: Integer = faFindEveryFile); procedure FileNew(const FileName: string); function DateTimeOfFileTime(const FileTime: TFileTime): TDateTime; { FileNames } function GetFileNew(FileName: string; NoFloppyDrives: Boolean = True): string; { Finding Files } function FindAll(Strings: TStrings; const Mask: string; ScanSubDirs: Boolean = True; Attributes: Integer = faFindEveryFile; FileReturn: TFileNameFunc = nil): Boolean; function FindAllFirst(const Mask: string; ScanSubDirs: Boolean = True; Attributes: Integer = faFindEveryFile): string; function FullOSInfo: string; function Win32PlatformStr: string; function Win9x: Boolean; function WinNT: Boolean; function Win2000: Boolean; function WinXP: Boolean; var MyDir: string = ''; LastSuccessRes: Integer = 0; { Backward compatibility } {$IFNDEF VER130} function SameText(const S1, S2: string): Boolean; {$ENDIF} implementation {$IFNDEF VER140} uses FileCtrl; {$ENDIF} {$IFNDEF VER130} function SameText(const S1, S2: string): Boolean; begin Result := CompareText(S1, S2) = 0; end; {$ENDIF} procedure Report(const ReportName, Text: string); var F: TextFile; FileName: string; begin FileName := MyDir + ReportName + '.rep'; Assign(F, FileName); try if not FileExists(FileName) then Rewrite(F) else Append(F); WriteLn(F, Text); finally Close(F); end; end; procedure ClearReport(const ReportName: string); var FileName: string; begin FileName := MyDir + ReportName + '.rep'; DeleteFile(FileName); end; procedure ReportFmt(const ReportName, Fmt: string; const Args: array of const); begin Report(ReportName, Format(Fmt, Args)); end; procedure GetParams(Strings: TStrings); var P: PChar; Param: string; function GetParamStr(var P: PChar; var Param: string): Boolean; var Quoted: Boolean; begin Param := ''; repeat while (P[0] <> #0) and (P[0] <= ' ') do Inc(P); Quoted := False; while P[0] <> #0 do begin if P[0] = '"' then begin Quoted := not Quoted; Inc(P); Continue; end; if (P[0] <= ' ') and not Quoted then Break; Param := Param + P[0]; Inc(P); end; until (Param <> '') or (P[0] = #0); Result := Param <> ''; end; begin Strings.Clear; P := GetCommandLine; GetParamStr(P, Param); while GetParamStr(P, Param) do Strings.Add(Param); end; function GetParams(const Separator: string = ' '): string; var SL: TStringList; begin SL := TStringList.Create; GetParams(SL); Result := Join(SL, Separator); SL.Free; end; function Switch(const Switch: string; const PrefixChars: TCharSet = SwitchChars; IgnoreCase: Boolean = True): Boolean; //= SysUtils.FindCmdLineSwitch var i: Integer; s: string; begin Result := True; for i := 1 to ParamCount do begin s := ParamStr(i); if (s <> '') and (s[1] in PrefixChars) then begin //i know that always s <> '', but this is saver s := Copy(s, 2, MaxInt); if (s = Switch) or (IgnoreCase and (0=AnsiCompareText(s, Switch))) then Exit; end; end; Result := False; end; function ParamNum(const S: string): Integer; begin for Result := 1 to ParamCount do if 0=AnsiCompareText(ParamStr(Result), S) then Exit; Result := 0; end; function ParamPrefixNum(const Prefix: string): Integer; var Len: Integer; begin Len := Length(Prefix); for Result := 1 to ParamCount do if 0=AnsiCompareText(Copy(ParamStr(Result), 1, Len), Prefix) then Exit; Result := 0; end; function Param(const S: string): Boolean; begin Result := ParamNum(S) > 0; end; function ParamPrefix(const Prefix: string): Boolean; begin Result := ParamPrefixNum(Prefix) > 0; end; function GetParam(const Prefix: string = ''; const Default: string = ''): string; var i: Integer; begin Result := Default; if Prefix = '' then begin Result := ParamStr(1); Exit; end; i := ParamPrefixNum(Prefix); if i > 0 then Result := Copy(ParamStr(i), Length(Prefix) + 1, MaxInt); end; function GetMyDir(FullPath: Boolean = False): string; var Buffer: array[0..260] of Char; begin Result := ''; SetString(Result, Buffer, GetModuleFileName(0, Buffer, SizeOf(Buffer))); if FullPath then Result := GetFileNew(Result); Result := ExtractPath(Result); end; function WinDir: string; var Res: PChar; begin Result := '\'; GetMem(Res, MAX_PATH); GetWindowsDirectory(Res, MAX_PATH); Result := Res + '\'; FreeMem(Res, MAX_PATH); end; function SysDir: string; var Res: PChar; begin Result := '\'; GetMem(Res, MAX_PATH); GetSystemDirectory(Res, MAX_PATH); Result := Res + '\'; FreeMem(Res, MAX_PATH); end; function UserName: string; var Len: Cardinal; Res: PChar; begin Result := ''; GetMem(Res, MAX_PATH); Len := MAX_PATH; GetUserName(Res, Len); Result := Res; FreeMem(Res, MAX_PATH); end; function FirstChar(const S: string): Char; begin if s = '' then Result := #0 else Result := s[1]; end; function LastChar(const S: string): Char; begin if s = '' then Result := #0 else Result := s[Length(s)]; end; function CharPos(C: Char; const S: string; Offset: Integer = 1): Integer; var MaxPosToSearch: Integer; begin Result := Offset; MaxPosToSearch := Length(S); while Result <= MaxPosToSearch do begin if S[Result] = C then Exit; Inc(Result); end; Result := 0; end; function CharPos(C: TCharSet; const S: string; Offset: Integer = 1): Integer; var MaxPosToSearch: Integer; begin Result := Offset; MaxPosToSearch := Length(S); while Result <= MaxPosToSearch do begin if S[Result] in C then Exit; Inc(Result); end; Result := 0; end; function CharPosR(C: Char; const S: string; Offset: Integer = -1): Integer; begin if Offset < 0 then Result := Length(S) + 1 - Offset else Result := Offset; if Result > Length(S) then Result := Length(S); while Result > 0 do begin if S[Result] = C then Exit; Dec(Result); end; end; function PosEx(const SubStr, S: string; Offset: Integer = 1): Integer; var MaxPosToSearch, LenSubStr, i: Integer; begin if SubStr = '' then begin Result := 0; Exit; end; if Offset < 1 then Result := 1 else Result := Offset; LenSubStr := Length(SubStr); MaxPosToSearch := Length(S) - LenSubStr + 1; while Result <= MaxPosToSearch do begin if S[Result] = SubStr[1] then begin i := 1; while (i < LenSubStr) and (S[Result + i] = SubStr[i + 1]) do Inc(i); if i = LenSubStr then Exit; end; Inc(Result); end; Result := 0; end; function PosExText(const SubStr, S: string; Offset: Integer = 1): Integer; var MaxPosToSearch, LenSubStr, i: Integer; function SameChar(a, b: Char): Boolean; begin Result := UpCase(a) = UpCase(b) end; begin if SubStr = '' then begin Result := 0; Exit; end; if Offset < 1 then Result := 1 else Result := Offset; LenSubStr := Length(SubStr); MaxPosToSearch := Length(S) - LenSubStr + 1; while Result <= MaxPosToSearch do begin if SameChar(S[Result], SubStr[1]) then begin i := 1; while (i < LenSubStr) and (SameChar(S[Result + i], SubStr[i + 1])) do Inc(i); if i = LenSubStr then Exit; end; Inc(Result); end; Result := 0; end; function PosExAnsiText(const SubStr, S: string; Offset: Integer = 1): Integer; var MaxPosToSearch, LenSubStr, i: Integer; function SameChar(a, b: Char): Boolean; begin Result := CharLower(PChar(a)) = CharLower(PChar(b)); end; begin if SubStr = '' then begin Result := 0; Exit; end; if Offset < 1 then Result := 1 else Result := Offset; LenSubStr := Length(SubStr); MaxPosToSearch := Length(S) - LenSubStr + 1; while Result <= MaxPosToSearch do begin if SameChar(S[Result], SubStr[1]) then begin i := 1; while (i < LenSubStr) and (SameChar(S[Result + i], SubStr[i + 1])) do Inc(i); if i = LenSubStr then Exit; end; Inc(Result); end; Result := 0; end; function UntilChar(const S: string; Brake: Char): string; var p: Integer; begin p := CharPos(Brake, S); if p > 0 then Result := Copy(S, 1, p - 1) else Result := S; end; function UntilChar(const S: string; Brake: TCharSet): string; var p: Integer; begin Result := ''; p := CharPos(Brake, S); if p > 0 then Result := Copy(S, 1, p - 1) else Result := S; end; function UntilLastChar(const S: string; Brake: Char; IgnoreNoBrake: Boolean = True): string; var p: Integer; begin Result := ''; p := CharPosR(Brake, S); if p > 0 then Result := Copy(S, 1, p - 1) else if IgnoreNoBrake then Result := S; end; function FromChar(const S: string; Brake: Char): string; var p: Integer; begin Result := ''; p := CharPos(Brake, S); if p > 0 then Result := Copy(S, p + 1, Length(S) - p); end; function FromChar(const S: string; Brake: TCharSet): string; var p: Integer; begin Result := ''; p := CharPos(Brake, S); if p > 0 then Result := Copy(S, p + 1, Length(S) - p); end; function FromLastChar(const S: string; Brake: Char; IgnoreNoBrake: Boolean = False): string; var p: Integer; begin Result := ''; p := CharPosR(Brake, S); if p > 0 then Result := Copy(S, p + 1, Length(S) - p) else if IgnoreNoBrake then Result := S; end; function BetweenChars(const S: string; Start, Finish: Char; Inclusive: Boolean = False): string; var p, fin: Integer; begin Result := ''; p := CharPos(Start, S); if p = 0 then Exit; fin := CharPos(Finish, S, p + 1); if fin = 0 then Exit; if not Inclusive then begin Inc(p); Dec(fin); end; Result := Copy(S, p, fin - p + 1); end; function UntilStr(const S: string; Brake: string): string; var p: Integer; begin if Length(Brake) = 1 then begin Result := UntilChar(S, Brake[1]); Exit; end; p := PosEx(Brake, S); if p > 0 then Result := Copy(S, 1, p - 1) else Result := S; end; function FromStr(const S: string; Brake: string): string; var p: Integer; begin if Length(Brake) = 1 then begin Result := FromChar(S, Brake[1]); Exit; end; Result := ''; p := PosEx(Brake, s); if p > 0 then begin Inc(p, Length(Brake)); Result := Copy(S, p, Length(S) - p + 1); end; end; function StringWrap(const S: string; Width: Integer; const LineEnd: string = EOL): string; var i: Integer; begin Result := ''; if (S = '') or (Width < 1) then Exit; i := 1; while True do begin Result := Result + Copy(S, i, Width); Inc(i, Width); if i <= Length(S) then Result := Result + LineEnd else Exit; end; end; function Split(const S, Separator: string; IgnoreMultiSep: Boolean = True; MinCount: Integer = 0): TStrA; var p, fin, SepLen: Integer; procedure Add(const S: string); begin if IgnoreMultiSep and (S = '') then Exit; SetLength(Result, Length(Result) + 1); Result[High(Result)] := S; end; begin if S = '' then begin if Length(Result) < MinCount then SetLength(Result, MinCount); Exit; end; Result := nil; SepLen := Length(Separator); p := 1; fin := PosEx(Separator, S); while fin > 0 do begin Add(Copy(S, p, fin - p)); p := fin + SepLen; fin := PosEx(Separator, S, p); end; Add(Copy(S, p, Length(S) - p + 1)); if Length(Result) < MinCount then SetLength(Result, MinCount); end; procedure Split(const S, Separator: string; Strings: TStrings; IgnoreMultiSep: Boolean = True); var p, fin, SepLen: Integer; procedure Add(const S: string); begin if IgnoreMultiSep and (S = '') then Exit; Strings.Add(S); end; begin if S = '' then Exit; Strings.BeginUpdate; SepLen := Length(Separator); p := 1; fin := PosEx(Separator, S); while fin > 0 do begin Add(Copy(S, p, fin - p)); p := fin + SepLen; fin := PosEx(Separator, S, p); end; Add(Copy(S, p, Length(S) - p + 1)); Strings.EndUpdate; end; function Split(const S: string; Separators: TCharSet; IgnoreMultiSep: Boolean = True; MinCount: Integer = 0): TStrA; var p, fin: Integer; procedure Add(const S: string); begin if IgnoreMultiSep and (S = '') then Exit; SetLength(Result, Length(Result) + 1); Result[High(Result)] := S; end; begin if S = '' then begin if Length(Result) < MinCount then SetLength(Result, MinCount); Exit; end; Result := nil; p := 1; fin := CharPos(Separators, S); while fin > 0 do begin Add(Copy(S, p, fin - p)); p := fin + 1; fin := CharPos(Separators, S, p); end; Add(Copy(S, p, Length(S) - p + 1)); if Length(Result) < MinCount then SetLength(Result, MinCount); end; procedure TileStr(const S: string; BrakeStart: Integer; BrakeEnd: Integer; out Left, Right: string); begin Left := Copy(S, 1, BrakeStart-1); Right := Copy(S, BrakeEnd + 1, MaxInt); end; function Join(Strings: TStrings; Separator: string = ' '): string; var i, imax: Integer; begin Result := ''; imax := Strings.Count-1; for i := 0 to imax do begin Result := Result + Strings[i]; if i < imax then Result := Result + Separator; end; end; function Join(StrA: TStrA; Separator: string = ' '): string; overload; var i: Integer; begin Result := ''; for i := 0 to High(StrA) do begin Result := Result + StrA[i]; if i < High(StrA) then Result := Result + Separator; end; end; function MulStr(const S: string; Count: Integer): string; var P: PChar; Len, i: Integer; begin Result := ''; if Count = 0 then Exit; Len := Length(S); SetLength(Result, Len * Count); P := Pointer(Result); for i := 1 to Count do begin Move(Pointer(S)^, P^, Len); Inc(P, Len); end; end; function AlignR(const S: string; Width: Integer; Filler: Char = ' '): string; begin Result := MulStr(Filler, Width - Length(S)) + S; end; function MaxStr(const S: string; MaxLen: Integer): string; var Len: Integer; begin Len := Length(S); if Len <= MaxLen then begin Result := S; Exit end; Result := Copy(S, 1, MaxLen - 3) + '...'; end; function TrimAll(const S: string): string; var i: Integer; begin for i := 1 to Length(S) do if S[i] > #32 then Result := Result + S[i]; end; function ControlChar(C: Char): Boolean; begin Result := C in StrangeChars; end; function FriendlyChar(C: Char): Char; begin case C of #0: Result := '.'; #1..#31: Result := '?'; #255: Result := '#'; else Result := C; end; end; function FriendlyStr(const S: string): string; var i: Integer; begin SetLength(Result, Length(S)); for i := 1 to Length(S) do Result[i] := FriendlyChar(S[i]); end; function FriendlyStr(a: TByteA): string; var i: Integer; begin SetLength(Result, Length(a)); for i := 0 to High(a) do Result[i + 1] := FriendlyChar(Char(a[i])); end; function Quote(const S: string; Quoter: Char = '"'): string; begin Result := S; if FirstChar(S) <> Quoter then Result := Quoter + Result; if LastChar(S) <> Quoter then Result := Result + Quoter; end; function DeQuote(const S: string): string; begin Result := ''; if Length(S) > 2 then Result := Copy(S, 2, Length(S) - 2); end; function UnQuote(const S: string): string; var Start, Len: Integer; begin Start := 1; Len := Length(S); if (S <> '') and (S[1] in ([#0..#32] + QuoteChars)) then begin if (LastChar(S) = S[1]) then Dec(Len); Inc(Start); end; Result := Copy(S, Start, Len - Start + 1); end; function StrNumerus(const Value: Integer; const Singular, Plural: string; const Zero: string = '0'): string; begin if Abs(Value) = 1 then Result := IntToStr(Value) + ' ' + Singular else if Value = 0 then Result := Zero + ' ' + Plural else Result := IntToStr(Value) + ' ' + Plural; end; function MakeStr(const Items: array of const; Separator: string = ''): string; const BoolStrings: array[Boolean] of string = ('False', 'True'); var i: Integer; function StrOfP(P: Pointer): string; begin if P = nil then Result := '[nil]' else Result := '[' + IntToStr(Cardinal(P)) + ']'; end; procedure Add(const S: string); begin Result := Result + s + Separator; end; begin Result := ''; for i := 0 to High(Items) do with Items[i] do case VType of vtString: Add(VString^); vtInteger: Add(IntToStr(VInteger)); vtBoolean: Add(BoolStrings[VBoolean]); vtChar: Add(VChar); vtPChar: Add(VPChar); vtExtended: Add(FloatToStr(VExtended^)); vtObject: if VObject is TComponent then Add(TComponent(VObject).Name) else Add(VObject.ClassName); vtClass: Add(VClass.ClassName); vtAnsiString: Add(string(VAnsiString)); vtCurrency: Add(CurrToStr(VCurrency^)); vtInt64: Add(IntToStr(VInt64^)); vtVariant: Add(string(VVariant^)); vtWideChar: Add(VWideChar); vtPWideChar: Add(VPWideChar); vtInterface: Add(StrOfP(VInterface)); vtPointer: Add(StrOfP(VPointer)); vtWideString: Add(WideString(VWideString)); end; if Result <> '' then SetLength(result, Length(Result) - Length(Separator)); end; procedure ShowText(const Items: array of const; Separator: string = ''); var Text: string; begin Text := MakeStr(Items, Separator); MessageBox(0, PChar(Text), 'Info', MB_OK and MB_APPLMODAL); end; function DeleteChars(const S: string; C: Char): string; var i: Integer; begin Result := ''; for i := 1 to Length(S) do if S[i] <> C then Result := Result + S[i]; end; function DeleteChars(const S: string; C: TCharSet): string; var i: Integer; begin Result := ''; for i := 1 to Length(S) do if not (S[i] in C) then Result := Result + S[i]; end; function ExtractChars(const S: string; C: TCharSet): string; var i: Integer; begin Result := ''; for i := 1 to Length(S) do if S[i] in C then Result := Result + S[i]; end; function CharCount(const S: string; C: Char): Integer; var i: Integer; begin Result := 0; for i := 1 to Length(S) do if S[i] = C then Inc(Result); end; function StrAtPos(const S: string; Pos: Integer; const Str: string): Boolean; begin Result := (Str <> '') and (Str = Copy(S, Pos, Length(Str))); end; function TextAtPos(const S: string; Pos: Integer; const Text: string): Boolean; begin Result := (Text <> '') and SameText(Text, Copy(S, Pos, Length(Text))); end; function StrAtBegin(const S, Str: string): Boolean; begin Result := StrAtPos(S, 1, Str); end; function TextAtBegin(const S, Text: string): Boolean; begin Result := TextAtPos(S, 1, Text); end; function CharIn(const S: string; C: Char): Boolean; var i: Integer; begin Result := True; for i := 1 to Length(S) do if S[i] = C then Exit; Result := False; end; function CharIn(const S: string; C: TCharSet): Boolean; var i: Integer; begin Result := False; for i := 1 to Length(S) do begin Result := S[i] in C; if Result then Exit; end; end; function StrIn(const S, SubStr: string): Boolean; begin Result := PosEx(SubStr, S) > 0; end; function StrIn(SL: TStrings; const S: string): Boolean; var i: Integer; begin Result := False; for i := 0 to SL.Count-1 do begin Result := (S = SL[i]); if Result then Exit; end; end; function StrIn(A: TStrA; const S: string): Boolean; var i: Integer; begin Result := False; for i := Low(A) to High(A) do begin Result := (S = A[i]); if Result then Exit; end; end; function TextIn(const S, Text: string): Boolean; begin Result := PosExText(Text, S) > 0; end; function TextIn(SL: TStrings; const Text: string): Boolean; var i: Integer; begin Result := False; for i := 0 to SL.Count-1 do begin Result := SameText(Text, SL[i]); if Result then Exit; end; end; function TextIn(A: TStrA; const Text: string): Boolean; var i: Integer; begin Result := False; for i := Low(A) to High(A) do begin Result := SameText(Text, A[i]); if Result then Exit; end; end; function StrIndex(SL: TStrings; const S: string): Integer; begin for Result := 0 to SL.Count-1 do if S = SL[Result] then Exit; Result := -1; end; function StrIndex(A: TStrA; const S: string): Integer; begin for Result := Low(A) to High(A) do if S = A[Result] then Exit; Result := -1; end; function TextIndex(SL: TStrings; const Text: string): Integer; begin for Result := 0 to SL.Count-1 do if SameText(Text, SL[Result]) then Exit; Result := -1; end; function TextIndex(A: TStrA; const Text: string): Integer; begin for Result := Low(A) to High(A) do if SameText(Text, A[Result]) then Exit; Result := -1; end; function ReplaceChars(const S: string; Old, New: Char): string; var i: Integer; begin Result := S; for i := 1 to Length(Result) do if Result[i] = Old then Result[i] := New; end; function ReplaceChars(const S: string; Old: TCharSet; New: Char): string; var i: Integer; begin Result := S; for i := 1 to Length(Result) do if Result[i] in Old then Result[i] := New; end; function Replace(const S, Old, New: string): string; var oldp, ps: Integer; begin ps := 1; Result := ''; while True do begin oldp := ps; ps := PosEx(Old, S, oldp); if ps = 0 then begin Result := Result + Copy(S, oldp, Length(S) - oldp + 1); Exit; end; Result := Result + Copy(S, oldp, ps - oldp) + New; Inc(ps, Length(Old)); end; end; function SLOfFile(const FileName: string): TStringList; begin Result := TStringList.Create; if FileExists(FileName) then Result.LoadFromFile(FileName); end; function ContainsEmptyLines(SL: TStrings): Boolean; begin Result := StrIn(SL, ''); end; procedure DeleteEmptyLines(SL: TStrings); var i: Integer; begin i := 0; while i < SL.Count do begin if SL[i] = '' then SL.Delete(i) else Inc(i); end; end; procedure DeleteCommentLines(SL: TStrings; const CommentSign: string = '//'); var i: Integer; begin i := 0; while i < SL.Count do begin if (SL[i] = '') or (StrAtBegin(TrimLeft(SL[i]), CommentSign)) then SL.Delete(i) else Inc(i); end; end; function FindLine(SL: TStrings; const S: string): Integer; begin for Result := 0 to SL.Count-1 do if TextAtBegin(SL[Result], S) then Exit; Result := -1; end; procedure QuickSortSL(SL: TStringList); procedure Sort(l, r: Integer); var i,j: Integer; z,x: string; begin i := l; j := r; x := SL[(j + i) div 2]; repeat while SL[i] < x do Inc(i); while SL[j] > x do Dec(j); if i <= j then begin z := SL[i]; SL[i] := SL[j]; SL[j] := z; Inc(i); Dec(j); end; until i > j; if j > l then Sort(l, j); if i < r then Sort(i, r); end; begin if SL.Count > 0 then Sort(0, SL.Count-1); end; function IncStrA(StrA: TStrA): Integer; begin SetLength(StrA, Length(StrA) + 1); Result := High(StrA); end; function StrOfByteA(a: TByteA): string; begin Result := string(Copy(a, 0, Length(a))); end; function ByteAOfStr(const S: string): TByteA; begin Result := TByteA(Copy(S, 1, Length(s))); end; function ByteAOfInt(i: Integer): TByteA; begin SetLength(Result, SizeOf(Integer)); Move(i, Pointer(Result)^, SizeOf(Integer)); end; function IntOfByteA(A: TByteA): Integer; begin Result := 0; Move(Pointer(A)^, Result, Min(Length(A), SizeOf(Integer))); end; function ByteAOfHex(const Hex: string): TByteA; var i: Integer; h: string; begin h := ExtractChars(Hex, HexadecimalChars); SetLength(Result, Length(h) div 2); for i := 0 to High(Result) do Result[i] := ByteOfHex(Copy(h, (i shl 1) + 1, 2)); end; function SizeOfFile(const FileName: string): Integer; var F: file; begin AssignFile(F, FileName); {$I-}Reset(F, 1);{$I+} if IOResult = 0 then begin Result := FileSize(F); CloseFile(F); end else Result := 0; end; function FileEx(const FileName: string; AllowFolders: Boolean = False): Boolean; var FindData: TWin32FindData; begin if FileName = '' then begin Result := False; Exit; end; Result := (AllowFolders and DirectoryExists(FileName)) or (FindFirstFile(PChar(FileName), FindData) <> INVALID_HANDLE_VALUE); Result := Result and not CharIn(FileName, WildCards); Result := Result and (AllowFolders or ((FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0)); end; function LWPSolve(const Dir: string): string; begin if (Dir <> '') and (Dir[Length(Dir)] = '\') then begin Result := Copy(Dir, 1, Length(Dir) - 1); end else Result := Dir; end; function LWPSlash(const Dir: string): string; begin if (Dir <> '') and (Dir[Length(Dir)] = '\') then begin Result := Copy(Dir, 1, Length(Dir)); end else Result := Dir + '\'; end; function ExtractDrive(const FileName: string): string; begin Result := ''; if (Length(FileName) >= 2) and (FileName[2] = ':') then Result := UpperCase(FileName[1] + ':\'); end; function ExtractPath(const FileName: string): string; var p: Integer; begin p := CharPosR('\', FileName); if P > 0 then Result := Copy(FileName, 1, p) else Result := FileName; end; function ExtractPrefix(const FileName: string): string; begin Result := UntilLastChar(ExtractFileName(FileName), '.'); end; function ExtractSuffix(const FileName: string): string; begin Result := FromLastChar(ExtractFileName(FileName), '.'); end; function SameByteA(const A, B: TByteA): Boolean; begin Result := (A = B) or ((Length(A) = Length(B)) and CompareMem(A, B, Length(A))); end; function Reverse(A: TByteA): TByteA; var i: Integer; begin SetLength(Result, Length(A)); for i := 0 to High(A) do Result[High(Result) - i] := A[i]; end; function Endian(i: Integer): Integer; type EndianArray = packed array[0..3] of Byte; var a, b: EndianArray; begin a := EndianArray(i); b[0] := a[3]; b[1] := a[2]; b[2] := a[1]; b[3] := a[0]; Result := Integer(b); end; function SaveByteA(Data: TByteA; const FileName: string; Overwrite: Boolean = True): Boolean; var F: file; begin if FileExists(FileName) and not Overwrite then begin Result := False; Exit end; AssignFile(F, FileName); {$I-}Rewrite(F, 1);{$I+} if IOResult = 0 then begin if Length(Data) > 0 then BlockWrite(F, Data[0], Length(Data)); CloseFile(F); Result := True; end else Result := False; end; function LoadByteA(const FileName: string): TByteA; var F: file; begin AssignFile(F, FileName); {$I-}Reset(F, 1);{$I+} if IOResult = 0 then begin SetLength(Result, FileSize(F)); if Length(Result) > 0 then BlockRead(F, Result[0], FileSize(F)); CloseFile(F); end else SetLength(Result, 0); end; function IsValidFileName(const FileName: string): Boolean; begin Result := (FileName <> '') and not CharIn(FileName, FileNameEnemies) and CharIn(Trim(FileName), AllChars - ['.']); end; function MakeValidFileName(FileName: string; const Default: string = 'File'): string; begin if FileName = '' then FileName := Default; if CharIn(FileName, FileNameEnemies) then Result := ReplaceChars(FileName, FileNameEnemies, '_') else if not CharIn(Trim(FileName), AllChars - ['.']) then Result := Default else Result := FileName; end; function IsValidInteger(const S: string): Boolean; {const LowInt = '2147483648'; HighInt = '2147483647'; var len, RealLen, i, o: Integer; c: Char; begin Result := False; if S = '' then Exit; len := Length(S); o := 1; if S[1] = '-' then begin if len = 1 then Exit; Inc(o); while (o <= len) and (S[o] = '0') do Inc(o); if o > len then Exit; if o < len then begin RealLen := len - o + 1; if RealLen > Length(LowInt) then Exit else if RealLen = Length(LowInt) then begin for i := 1 to Length(LowInt) do begin c := S[i + o - 1]; if (c < '0') or (c > LowInt[i]) then Exit; if c in ['0'..Char((Byte(LowInt[i])-1))] then Break; end; Inc(o, i); end; end; end else begin while (o <= len) and (S[o] = '0') do Inc(o); if o <= len then begin RealLen := len - o + 1; if RealLen > Length(HighInt) then Exit else if RealLen = Length(HighInt) then begin for i := 1 to Length(HighInt) do begin c := S[i + o - 1]; if (c < '0') or (c > HighInt[i]) then Exit; if c in ['0'..Char((Byte(HighInt[i])-1))] then Break; end; Inc(o, i); end; end; end; for i := o to len do if not (S[i] in ['0'..'9']) then Exit; Result := True; } var i: Int64; begin i := StrToInt64Def(S, High(Int64)); Result := (i >= Low(Integer)) and (i <= High(Integer)); end; function IsValidCardinal(const S: string): Boolean; {const HighCard = '4294967295'; var len, RealLen, i, o: Integer; begin Result := False; if S = '' then Exit; len := Length(S); o := 1; while (o <= len) and (S[o] = '0') do Inc(o); if o <= len then begin RealLen := len - o + 1; if RealLen > Length(HighCard) then Exit else if RealLen = Length(HighCard) then begin for i := 1 to Length(HighCard) do begin if S[i + o - 1] > HighCard[i] then Exit; if S[i + o - 1] in ['0'..Char((Byte(HighCard[i])-1))] then Break; end; Inc(o, i); end; end; for i := o to len do if not (S[i] in ['0'..'9']) then Exit; Result := True; } var i: Int64; begin i := StrToInt64Def(S, -1); Result := (i >= 0) and (i <= High(Cardinal)); end; function StrOfBool(flag: Boolean; const TrueStr: string = 'True'; const FalseStr: string = 'False'): string; begin if Flag then Result := TrueStr else Result := FalseStr; end; function StrOfInt(i: Integer): string; begin { if i = 0 then begin Result := '0'; Exit end; while i > 0 do begin Result := Char(Byte('0') + (i mod 10)) + Result; i := i div 10; end;} Result := IntToStr(i); end; function CardOfStr(const S: string): Cardinal; var Res: Int64; begin Res := StrToInt64Def(S, -1); if Res > High(Cardinal) then Res := High(Cardinal) else if Res < 0 then Res := 0; Result := Cardinal(Res); end; function HexOrd(Hex: Char): THex; begin case Hex of '0'..'9': Result := Byte(Hex) - 48; 'A'..'F': Result := Byte(Hex) - 55; 'a'..'f': Result := Byte(Hex) - 87; else Result := 0; end; end; function ByteOfHex(Hex: THexByteStr): Byte; begin Result := (HexOrd(Hex[1]) shl 4) + HexOrd(Hex[2]); end; function DecOfHex(const Hex: string): string; begin Result := IntToStr(CardOfHex(Hex)); end; function HexOfByte(b: Byte): THexByteStr; begin Result := HexChar[(b and $F0) shr 4] + HexChar[ b and $0F ]; end; {function HexOfCard2(c: Cardinal): string; var Data: array[0..(1 shl 4) - 1] of Char; i: Integer; begin for i := 0 to (1 shl 4) - 1 do if i < 10 then Data[i] := Char(Ord('0') + i) else Data[i] := Char(Ord('A') + i - 10); Result := Data[(c and (((1 shl (1 shl 2)) - 1) shl (7 shl 2))) shr (7 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (6 shl 2))) shr (6 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (5 shl 2))) shr (5 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (4 shl 2))) shr (4 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (3 shl 2))) shr (3 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (2 shl 2))) shr (2 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (1 shl 2))) shr (1 shl 2)] + Data[(c and (((1 shl (1 shl 2)) - 1) shl (0 shl 2))) shr (0 shl 2)]; end; } function HexOfCard(i: Cardinal): string; var a: Cardinal; begin Result := ''; while i > 0 do begin a := i and $F; Result := HexChar[a] + Result; i := i shr 4; end; end; function HexOfCard(i: Cardinal; Digits: Integer): string; var a: Cardinal; begin Result := ''; while i > 0 do begin a := i and $F; Result := HexChar[a] + Result; i := i shr 4; end; Result := MulStr('0', Digits - Length(Result)) + Result; end; function PascalHexArray(a: TByteA; Name: string): string; var i, len: Integer; begin Result := 'const' + EOL + ' ' + Name + ': array[0..' + IntToStr(High(a)) + '] of Byte = ('; len := Length(a); for i := 0 to len-1 do begin if (i mod 19) = 0 then Result := Result + EOL + ' ' + ' '; Result := Result + '$' + HexOfByte(a[i]); if i < len-1 then Result := Result + ','; end; Result := Result + EOL + ' );'; end; function HexOfByteA(a: TByteA; Blocks: Integer = 1; const Splitter: string = ' '): string; var i: Integer; begin Result := ''; if Blocks > 0 then for i := 0 to High(a) do begin Result := Result + HexOfByte(a[i]); if i < High(a) then if ((i+1) mod Blocks) = 0 then Result := Result + Splitter; end else for i := 0 to High(a) do Result := Result + HexOfByte(a[i]); end; function BinOfByteA(a: TByteA; Blocks: Integer = 4; const Splitter: string = ' '): string; var i, max: Integer; Bit: Boolean; begin Result := ''; if Blocks > 0 then begin max := 8 * (High(a)) + 7; for i := 0 to max do begin Bit := 7-(i mod 8) in TBitSet(a[i div 8]); Result := Result + Char(Byte('0') + Byte(Bit)); if i < max then if ((i+1) mod Blocks) = 0 then Result := Result + Splitter; end; end else for i := 0 to High(a) do Result := Result + Char(Byte('0') + a[i] shr (i and 8)); end; function CardOfHex(Hex: string): Cardinal; var i: Integer; begin Result := 0; Hex := Copy(ExtractChars(Hex, HexadecimalChars), 1, 8); for i := 1 to Length(Hex) do if Hex[i] <> '0' then Inc(Result, HexOrd(Hex[i]) shl ((Length(Hex) - i) shl 2)); end; function IntOfBin(Bin: string): Cardinal; var i: Integer; begin Result := 0; Bin := Copy(ExtractChars(Bin, BinaryChars), 1, 32); for i := Length(Bin) downto 1 do if Bin[i] = '1' then Inc(Result, 1 shl (Length(Bin) - i)); end; function BinOfInt(n: Cardinal): string; var a: Integer; begin if n = 0 then begin Result := '0'; exit; end; Result := ''; while n > 0 do begin a := n and 1; Result := Char(a + Byte('0')) + Result; n := n shr 1; end; end; function BinOfIntFill(n: Cardinal; MinCount: Integer = 8): string; var a: Integer; begin if n = 0 then begin Result := MulStr('0', MinCount); Exit; end; Result := ''; while n > 0 do begin a := n and 1; Result := Char(a + Byte('0')) + Result; n := n shr 1; end; Result := MulStr('0', MinCount - Length(Result)) + Result; end; function BaseNOfInt(I: Cardinal; B: TBaseN): string; var a: Integer; begin if (B < 2) or (i = 0) then begin Result := '0'; Exit; end; Result := ''; while i > 0 do begin a := i mod B; Result := BaseNChar[a] + Result; i := i div B; end; end; function IntOfBaseN(V: string; B: TBaseN): Cardinal; var i: Integer; F: Cardinal; c: Byte; begin Result := 0; V := TrimAll(V); F := 1; for i := Length(V) downto 1 do begin c := Byte(UpCase(V[i])); case Char(c) of '0'..'9': c := c - 48; 'A'..'Z': c := c - 55; end; if c < B then Result := Result + Byte(c) * F; F := F * B; end; end; function KeepIn(i, Bottom, Top: Variant): Variant; begin Result := i; if Result > Top then Result := Top else if Result < Bottom then Result := Bottom; end; function InRange(Value, Bottom, Top: Variant): Boolean; begin Result := (Value >= Bottom) and (Value <= Top); end; function InStrictRange(Value, Bottom, Top: Variant): Boolean; begin Result := (Value > Bottom) and (Value < Top); end; function Min(const A, B: Integer): Integer; begin if A < B then Result := A else Result := B; end; function Min(const A: TIntA): Integer; var i: Integer; begin Result := 0; if Length(A) = 0 then Exit; Result := A[0]; for i := 1 to High(A) do if A[i] < Result then Result := A[i]; end; function Max(const A, B: Integer): Integer; begin if A > B then Result := A else Result := B; end; function Max(const A: TIntA): Integer; var i: Integer; begin Result := 0; if Length(A) = 0 then Exit; Result := A[0]; for i := 1 to High(A) do if A[i] > Result then Result := A[i]; end; function RangesOfStr(const S: string): TRanges; var SL: TStringList; r, b, t: string; i, p: Integer; function TryStrToCard(const S: string; out Value: Cardinal): Boolean; var E: Integer; begin Val(S, Value, E); Result := E = 0; end; begin Result := nil; SL := TStringList.Create; try Split(S, RangesSeparator, SL); SetLength(Result, SL.Count); for i := 0 to SL.Count-1 do begin r := SL[i]; with Result[i] do begin p := CharPos(RangeInnerSeparator, r); Simple := p = 0; // no '-' found if Simple then begin if r = RangeInfinite then begin // * --> *-* Simple := False; Bottom := Low(Bottom); Top := High(Top); end else if not TryStrToCard(r, Value) then Break; end else begin TileStr(r, p, p, b, t); if b = RangeInfinite then Bottom := Low(Bottom) else if not TryStrToCard(b, Bottom) then Break; if t = RangeInfinite then Top := High(Top) else if not TryStrToCard(t, Top) then Break; if Bottom > Top then begin p := Bottom; Bottom := Top; Top := p; end; end; end; end; if i <> SL.Count then Result := nil; finally SL.Free; end; end; function InRanges(Ranges: TRanges; TestValue: Cardinal): Boolean; var i: Integer; begin Result := True; for i := 0 to High(Ranges) do with Ranges[i] do if Simple then begin if TestValue = Value then Exit; end else begin if InRange(TestValue, Bottom, Top) then Exit; end; Result := False; end; procedure WriteSL(Strings: TStrings; const Prefix: string = ''; const Suffix: string = ''); var i: Integer; begin for i := 0 to Strings.Count-1 do WriteLn(Prefix + Strings[i] + Suffix); end; function Success(Res: Integer; ResultOnSuccess: Integer = ERROR_SUCCESS): Boolean; begin Result := (Res = ResultOnSuccess); LastSuccessRes := Res; end; function Failure(Res: Integer; ResultOnSuccess: Integer = ERROR_SUCCESS): Boolean; begin Result := not Success(Res, ResultOnSuccess); end; function ExpandString(const S: string): string; var Len: Integer; P, Res: PChar; begin Result := ''; P := PChar(S); Len := ExpandEnvironmentStrings(P, nil, 0); if Len = 0 then Exit; GetMem(Res, Len); ExpandEnvironmentStrings(P, Res, Len); Result := Res; FreeMem(Res, Len); end; function FindAll(Strings: TStrings; const Mask: string; ScanSubDirs: Boolean = True; Attributes: Integer = faFindEveryFile; FileReturn: TFileNameFunc = nil): Boolean; var Path, FileName: string; procedure ScanDir(const Path, FileName: string); var PSR: TSearchRec; Res: Integer; procedure Add(const S: string); begin if S <> '' then Strings.Add(S); end; begin Res := FindFirst(Path + FileName, Attributes, PSR); while Success(Res, 0) do begin if Assigned(FileReturn) then Add(FileReturn(Path + PSR.Name)) else Add(Path + PSR.Name); Res := FindNext(PSR); end; FindClose(PSR); if not ScanSubDirs then Exit; Res := FindFirst(Path + '*', faDirectory, PSR); while Success(Res, 0) do begin if (PSR.Attr and faDirectory > 0) and (PSR.Name <> '.') and (PSR.Name <> '..') then ScanDir(Path + PSR.Name + '\', FileName); Res := FindNext(PSR); end; FindClose(PSR); end; begin Strings.Clear; Path := ExtractPath(Mask); FileName := ExtractFileName(Mask); ScanDir(Path, FileName); Result := Strings.Count > 0; end; function FindAllFirst(const Mask: string; ScanSubDirs: Boolean = True; Attributes: Integer = faFindEveryFile): string; var Path, FileName: string; function ScanDir(const Path, FileName: string): Boolean; var PSR: TSearchRec; Res: Integer; begin Result := False; if Success(FindFirst(Path + FileName, Attributes, PSR), 0) then begin FindAllFirst := Path + PSR.Name; Result := True; FindClose(PSR); Exit; end; if not ScanSubDirs then Exit; Res := FindFirst(Path + '*', faDirectory, PSR); while not Result and Success(Res, 0) do begin if (PSR.Attr and faDirectory > 0) and (PSR.Name <> '.') and (PSR.Name <> '..') then Result := ScanDir(Path + PSR.Name + '\', FileName); Res := FindNext(PSR); end; FindClose(PSR); end; begin Result := ''; Path := ExtractPath(Mask); FileName := ExtractFileName(Mask); ScanDir(Path, FileName); end; procedure DeleteFiles(const Mask: string; ScanSubDirs: Boolean = True; Attributes: Integer = faFindEveryFile); var Path, FileName: string; procedure ScanDir(const Path, FileName: string); var PSR: TSearchRec; Res: Integer; procedure TryDeleteFile(const FileName: string); begin try DeleteFile(Path + PSR.Name); except end; end; begin Res := FindFirst(Path + FileName, Attributes, PSR); while Success(Res, 0) do begin TryDeleteFile(Path + PSR.Name); Res := FindNext(PSR); end; FindClose(PSR); if not ScanSubDirs then Exit; Res := FindFirst(Path + '*', faDirectory, PSR); while Success(Res, 0) do begin if (PSR.Attr and faDirectory > 0) and (PSR.Name <> '.') and (PSR.Name <> '..') then begin ScanDir(Path + PSR.Name + '\', FileName); TryDeleteFile(Path + PSR.Name); end; Res := FindNext(PSR); end; FindClose(PSR); end; begin Path := ExtractPath(Mask); FileName := ExtractFileName(Mask); ScanDir(Path, FileName); end; function GetFileNew(FileName: string; NoFloppyDrives: Boolean = True): string; var Drive: string; pf, pd, Len: Integer; PSR: TSearchRec; begin Result := ''; FileName := Trim(FileName); if Length(FileName) < 2 then Exit; Drive := ExtractDrive(FileName); if not DirectoryExists(Drive) then Exit; if NoFloppyDrives and (Drive[1] in ['A', 'B']) then Exit; Len := Length(FileName); Result := Drive; pf := Length(Drive) + 1; while pf <= Len do begin if FileName[pf] = '\' then begin Result := Result + '\'; Inc(pf); Continue; end; pd := CharPos('\', FileName, pf); if pd = 0 then begin if 0=FindFirst(Result + Copy(FileName, pf, MaxInt), faFindEveryFile, PSR) then begin Result := Result + PSR.Name; Break; end else begin FindClose(PSR); if 0=FindFirst(Result + Copy(FileName, pf, MaxInt), faDirectory, PSR) then Result := Result + PSR.Name + '\' else Result := ''; FindClose(PSR); if Result = '' then Break; end; end; if 0=FindFirst(Result + Copy(FileName, pf, pd - pf), faDirectory, PSR) then Result := Result + PSR.Name + '\' else Result := ''; FindClose(PSR); if Result = '' then Break; pf := pd + 1; end; if (Result <> '') and not FileEx(Result, True) then Result := ''; end; function DateTimeOfFileTime(const FileTime: TFileTime): TDateTime; var LocalFileTime: TFileTime; Res: Integer; begin Result := 0; FileTimeToLocalFileTime(FileTime, LocalFileTime); if not FileTimeToDosDateTime(LocalFileTime, LongRec(Res).Hi, LongRec(Res).Lo) then Res := -1; if (Res = -1) or (Res = 0) then Exit; try Result := FileDateToDateTime(Res); except end; end; procedure FileNew(const FileName: string); var Handle: Integer; begin Handle := FileCreate(FileName); FileClose(Handle); end; function Win32PlatformStr: string; const PlatformStrings: array[VER_PLATFORM_WIN32s..VER_PLATFORM_WIN32_NT] of string = ('VER_PLATFORM_WIN32s', 'VER_PLATFORM_WIN32_WINDOWS', 'VER_PLATFORM_WIN32_NT'); begin Result := PlatformStrings[Win32Platform]; end; function FullOSInfo: string; begin Result := Format( 'Platform: %s' + EOL + 'Version: %d.%d Build %d' + EOL + 'CSD: %s', [ Win32PlatformStr, Win32MajorVersion, Win32MinorVersion, Win32BuildNumber, Win32CSDVersion ] ); end; function Win9x: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_WINDOWS; end; function WinNT: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_NT; end; function Win2000: Boolean; begin Result := (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion = 4); end; function WinXP: Boolean; begin Result := Win32MajorVersion >= 5; end; initialization MyDir := GetMyDir; end. unit FifoStream; interface uses Classes, windows, Dialogs; const DefaultChunksize = 32768; // 32kb per chunk as default. type PMemChunk = ^TMemChunk; TMemChunk = record Filled: Longword; Read: Longword; Data: pointer; end; TFifo = class private FBuffers: TList; FChunksize: Longword; FCritSect: TRTLCriticalSection; FIsWinNT: boolean; FBytesInFifo: LongWord; protected function GetBytesInFifo: LongWord; public constructor Create; destructor Destroy; override; procedure Write(Data: pointer; Size: LongWord); procedure Read(Buff: pointer; var ReqSize: LongWord); procedure PeekData(Buff: pointer; var ReqSize: LongWord); published property BytesInFifo: LongWord read FBytesInFifo; end; implementation constructor TFifo.Create; begin inherited; FBuffers := TList.Create; // set default chunksize... FChunksize := DefaultChunksize; InitializeCriticalSection(FCritSect); end; destructor TFifo.Destroy; var I: Integer; begin EnterCriticalSection(FCritSect); for I := 0 to FBuffers.count - 1 do begin FreeMem(PMemChunk(Fbuffers[I]).Data); Dispose(PMemChunk(Fbuffers[I])); end; FBuffers.Clear; FBuffers.Free; LeaveCriticalSection(FCritSect); DeleteCriticalSection(FCritSect); inherited; end; function TFifo.GetBytesInFifo: LongWord; begin Result := 0; if FBuffers.Count = 0 then begin exit; end else begin if FBuffers.Count > 1 then Inc(Result, (FBuffers.Count - 1) * FChunkSize); Inc(Result, PMemChunk(FBuffers[Fbuffers.Count - 1]).Filled); Dec(Result, PMemChunk(FBuffers[0]).Read); end; end; procedure TFifo.Write(Data: pointer; Size: LongWord); var Privpointer: pointer; PrivSize: LongWord; Chunk: PMemChunk; PosInChunk: pointer; begin if LongWord(Data) = 0 then begin // null pointer? somebody is trying to fool us, get out... Exit; end; EnterCriticalSection(FCritSect); PrivPointer := Data; PrivSize := 0; // are already buffers there? if FBuffers.count > 0 then begin // is the last one of them not completely filled? if PMemChunk(FBuffers[FBuffers.count - 1]).filled < FChunksize then // not completely filled, so fill up the buffer. begin Chunk := PMemChunk(FBuffers[FBuffers.count - 1]); // fetch chunkdata. PosInChunk := Chunk.Data; // move to current fill pos... Inc(LongWord(PosInChunk), Chunk.Filled); // can we fill the chunk completely? if Size > FChunksize - Chunk.Filled then begin // yes we can. Move(PrivPointer^, PosInChunk^, FChunksize - Chunk.Filled); Inc(PrivSize, FChunksize - Chunk.Filled); Inc(LongWord(PrivPointer), FChunksize - Chunk.Filled); Chunk.Filled := FChunkSize; end else // we have to less data for filling the chunk completely, // just put everything in. begin Move(PrivPointer^, PosInChunk^, Size); Inc(PrivSize, Size); Inc(Chunk.Filled, Size); end; end; end; // as long as we have remaining stuff put it into new chunks. while (PrivSize < Size) do begin new(Chunk); GetMem(Chunk.Data, FChunksize); Chunk.Read := 0; // can we fill an entire chunk with the remaining data? if Privsize + FChunksize < Size then begin // yes we can, so put the stuff in. Move(Privpointer^, Chunk.Data^, FChunksize); Inc(LongWord(PrivPointer), FChunksize); Inc(PrivSize, FChunksize); Chunk.Filled := FChunksize; end else // we have to less data to fill the entire chunk, just put the remaining stuff in. begin Move(Privpointer^, Chunk.Data^, Size - Privsize); Chunk.Filled := Size - Privsize; Inc(PrivSize, Size - Privsize); end; Fbuffers.Add(Chunk); end; if Size <> Privsize then Showmessage('miscalculation in TFifo.write'); FBytesInFifo := GetBytesInFifo; LeaveCriticalSection(FCritSect); end; procedure TFifo.Read(Buff: pointer; var ReqSize: LongWord); var PrivSize: Integer; Privpos: pointer; Chunk: PMemChunk; ChunkPos: pointer; begin if LongWord(Buff) = 0 then begin // null pointer? somebody is trying to fool us, get out... Exit; end; EnterCriticalSection(FCritSect); PrivSize := 0; Privpos := Buff; while FBuffers.Count > 0 do begin Chunk := PMemChunk(FBuffers[0]); ChunkPos := Chunk.data; Inc(LongWord(ChunkPos), Chunk.Read); // does the remaining part of the chunk fit into the buffer? if PrivSize + (Chunk.Filled - Chunk.read) < ReqSize then begin // yep, it fits Move(ChunkPos^, Privpos^, Chunk.Filled - Chunk.read); Inc(PrivSize, Chunk.Filled - Chunk.read); FreeMem(Chunk.Data); Dispose(Chunk); FBuffers.Delete(0); end else // remaining part didn't fit, get as much as we can and increment the // read attribute. begin Move(ChunkPos^, Privpos^, ReqSize - PrivSize); Inc(Chunk.read, ReqSize - PrivSize); Inc(PrivSize, ReqSize - PrivSize); // as we filled the buffer, we'll have to break here. break; end; end; FBytesInFifo := GetBytesInFifo; LeaveCriticalSection(FCritSect); ReqSize := PrivSize; end; // read Data from Stream without removing it from the Stream... procedure TFifo.PeekData(Buff: pointer; var ReqSize: LongWord); var PrivSize: Integer; Privpos: pointer; Chunk: PMemChunk; ChunkPos: pointer; ChunkNr: Integer; begin if LongWord(Buff) = 0 then begin // null pointer? somebody is trying to fool us, get out... Exit; end; EnterCriticalSection(FCritSect); PrivSize := 0; Privpos := Buff; ChunkNr := 0; while FBuffers.Count > ChunkNr do begin Chunk := PMemChunk(FBuffers[ChunkNr]); ChunkPos := Chunk.data; Inc(LongWord(ChunkPos), Chunk.Read); // does the remaining part of the chunk fit into the buffer? if PrivSize + (Chunk.Filled - Chunk.read) < ReqSize then begin // yep, it fits Move(ChunkPos^, Privpos^, Chunk.Filled - Chunk.read); Inc(PrivSize, Chunk.Filled - Chunk.read); Inc(ChunkNr); end else // remaining part didn't fit, get as much as we can and increment the // read attribute. begin Move(ChunkPos^, Privpos^, ReqSize - PrivSize); Inc(PrivSize, ReqSize - PrivSize); // as we filled the buffer, we'll have to break here. break; end; end; LeaveCriticalSection(FCritSect); ReqSize := PrivSize; end; end. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.pp000066400000000000000000000002021250413007300256560ustar00rootroot00000000000000exec { 'grep': command => 'grep "\'" -rI *', path => '/bin:/usr/bin', } node default { notify {"Hello World":;} } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.prg000066400000000000000000000064251250413007300260440ustar00rootroot00000000000000&& This is a concatenation of all VFP examples on Wikipedia. && Copyright 2013 Wikimedia, under the GFDL. FOR i = 1 to 10 x = x + 6.5 ENDFOR IF i = 25 i = i + 1 ELSE i = i + 3 ENDIF x = 1 DO WHILE x < 50 x = x + 1 ENDDO x = 1 DO WHILE .T. x = x + 1 IF x < 50 LOOP ELSE EXIT ENDIF ENDDO nMonth = MONTH(DATE()) DO CASE CASE nMonth <= 3 MESSAGEBOX("Q1") CASE nMonth <= 6 MESSAGEBOX("Q2") CASE nMonth <= 9 MESSAGEBOX("Q3") OTHERWISE MESSAGEBOX("Q4") ENDCASE FOR EACH oControl IN THISFORM.Controls MESSAGEBOX(oControl.Name) ENDFOR f = Factorial(10) FUNCTION Factorial(n) LOCAL i,r r = 1 FOR i = n TO 1 STEP -1 r = r * n ENDFOR RETURN r ENDFUNC loForm = CREATEOBJECT("HiForm") loForm.Show(1) DEFINE CLASS HiForm AS Form AutoCenter = .T. Caption = "Hello, World" ADD OBJECT lblHi as Label WITH ; Caption = "Hello, World!" ENDDEFINE loMine = CREATEOBJECT("MyClass") ? loMine.cProp1 && This will work. (Double-ampersand marks an end-of-line comment) ? loMine.cProp2 && Program Error: Property CPROP2 is not found. ? loMine.MyMethod1() && This will work. ? loMine.MyMethod2() && Program Error: Property MYMETHOD2 is not found. DEFINE CLASS MyClass AS Custom cProp1 = "My Property" && This is a public property HIDDEN cProp2 && This is a private (hidden) property dProp3 = {} && Another public property PROCEDURE Init() && Class constructor This.cProp2 = "This is a hidden property." ENDPROC PROCEDURE dProp3_Access && Property Getter RETURN DATE() ENDPROC PROCEDURE dProp3_Assign(vNewVal) && Property Setter IF VARTYPE(vNewVal) = "D" THIS.dProp3 = vNewVal ENDIF ENDPROC PROCEDURE MyMethod1() * This is a public method, calling a hidden method that returns * the value of a hidden property. RETURN This.MyMethod2() ENDPROC HIDDEN PROCEDURE MyMethod2() && This is a private (hidden) method RETURN This.cProp2 ENDPROC ENDDEFINE && Create a table CREATE TABLE randData (iData I) && Populate with random data using xBase and SQL DML commands FOR i = 1 TO 50 APPEND BLANK REPLACE iData WITH (RAND() * 100) INSERT INTO randData (iData) VALUES (RAND() * 100) ENDFOR && Place a structural index on the data INDEX ON iData TAG iData CLOSE ALL && Display ordered data using xBase-style commands USE randData SET ORDER TO iData GO TOP LIST NEXT 10 && First 10 GO BOTTOM SKIP -10 LIST REST && Last 10 CLOSE ALL && Browse ordered data using SQL DML commands SELECT * ; FROM randData ; ORDER BY iData DESCENDING && Connect to an ODBC data source LOCAL nHnd nHnd = SQLCONNECT ("ODBCDSN", "user", "pwd") && Execute a SQL command LOCAL nResult nResult = SQLEXEC (nHnd, "USE master") IF nResult < 0 MESSAGEBOX ("MASTER database does not exist!") RETURN ENDIF && Retrieve data from the remote server and stores it in && a local data cursor nResult = SQLEXEC (nHnd, "SELECT * FROM authors", "QAUTHORS") && Update a record in a remote table using parameters PRIVATE cAuthorID, cAuthorName cAuthorID = "1001" cAuthorName = "New name" nResult = SQLEXEC (nHnd, "UPDATE authors SET auth_name = ?cAuthorName WHERE auth_id = ?cAuthorID") && Close the connection SQLDISCONNECT(nHnd) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.rb000066400000000000000000001453471250413007300256660ustar00rootroot00000000000000module CodeRay module Scanners class Ruby < Scanner RESERVED_WORDS = [ 'and', 'def', 'end', 'in', 'or', 'unless', 'begin', 'defined?', 'ensure', 'module', 'redo', 'super', 'until', 'BEGIN', 'break', 'do', 'next', 'rescue', 'then', 'when', 'END', 'case', 'else', 'for', 'retry', 'while', 'alias', 'class', 'elsif', 'if', 'not', 'return', 'undef', 'yield', ] DEF_KEYWORDS = ['def'] MODULE_KEYWORDS = ['class', 'module'] DEF_NEW_STATE = WordList.new(:initial). add(DEF_KEYWORDS, :def_expected). add(MODULE_KEYWORDS, :module_expected) WORDS_ALLOWING_REGEXP = [ 'and', 'or', 'not', 'while', 'until', 'unless', 'if', 'elsif', 'when' ] REGEXP_ALLOWED = WordList.new(false). add(WORDS_ALLOWING_REGEXP, :set) PREDEFINED_CONSTANTS = [ 'nil', 'true', 'false', 'self', 'DATA', 'ARGV', 'ARGF', '__FILE__', '__LINE__', ] IDENT_KIND = WordList.new(:ident). add(RESERVED_WORDS, :reserved). add(PREDEFINED_CONSTANTS, :pre_constant) METHOD_NAME = / #{IDENT} [?!]? /xo METHOD_NAME_EX = / #{METHOD_NAME} # common methods: split, foo=, empty?, gsub! | \*\*? # multiplication and power | [-+~]@? # plus, minus | [\/%&|^`] # division, modulo or format strings, &and, |or, ^xor, `system` | \[\]=? # array getter and setter | <=?>? | >=? # comparison, rocket operator | << | >> # append or shift left, shift right | ===? # simple equality and case equality /ox GLOBAL_VARIABLE = / \$ (?: #{IDENT} | \d+ | [~&+`'=\/,;_.<>!@0$?*":F\\] | -[a-zA-Z_0-9] ) /ox DOUBLEQ = / " [^"\#\\]* (?: (?: \#\{.*?\} | \#(?:$")? | \\. ) [^"\#\\]* )* "? /ox SINGLEQ = / ' [^'\\]* (?: \\. [^'\\]* )* '? /ox STRING = / #{SINGLEQ} | #{DOUBLEQ} /ox SHELL = / ` [^`\#\\]* (?: (?: \#\{.*?\} | \#(?:$`)? | \\. ) [^`\#\\]* )* `? /ox REGEXP = / \/ [^\/\#\\]* (?: (?: \#\{.*?\} | \#(?:$\/)? | \\. ) [^\/\#\\]* )* \/? /ox DECIMAL = /\d+(?:_\d+)*/ # doesn't recognize 09 as octal error OCTAL = /0_?[0-7]+(?:_[0-7]+)*/ HEXADECIMAL = /0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*/ BINARY = /0b[01]+(?:_[01]+)*/ EXPONENT = / [eE] [+-]? #{DECIMAL} /ox FLOAT = / #{DECIMAL} (?: #{EXPONENT} | \. #{DECIMAL} #{EXPONENT}? ) / INTEGER = /#{OCTAL}|#{HEXADECIMAL}|#{BINARY}|#{DECIMAL}/ def reset super @regexp_allowed = false end def next_token return if @scanner.eos? kind = :error if @scanner.scan(/\s+/) # in every state kind = :space @regexp_allowed = :set if @regexp_allowed or @scanner.matched.index(?\n) # delayed flag setting elsif @state == :def_expected if @scanner.scan(/ (?: (?:#{IDENT}(?:\.|::))* | (?:@@?|$)? #{IDENT}(?:\.|::) ) #{METHOD_NAME_EX} /ox) kind = :method @state = :initial else @scanner.getch end @state = :initial elsif @state == :module_expected if @scanner.scan(/<#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^>#\\\\]*)*>?|([^a-zA-Z\\\\])(?:(?!\1)[^#\\\\])*(?:(?:#\{.*?\}|#|\\\\.)(?:(?!\1)[^#\\\\])*)*\1?)|\([^)#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^)#\\\\]*)*\)?|\[[^\]#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^\]#\\\\]*)*\]?|\{[^}#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^}#\\\\]*)*\}?|<[^>#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^>#\\\\]*)*>?|([^a-zA-Z\s\\\\])(?:(?!\2)[^#\\\\])*(?:(?:#\{.*?\}|#|\\\\.)(?:(?!\2)[^#\\\\])*)*\2?|\\\\[^#\\\\]*(?:(?:#\{.*?\}|#)[^#\\\\]*)*\\\\?)/ elsif @scanner.scan(/:(?:#{GLOBAL_VARIABLE}|#{METHOD_NAME_EX}|#{STRING})/ox) kind = :symbol elsif @scanner.scan(/ \? (?: [^\s\\] | \\ (?:M-\\C-|C-\\M-|M-\\c|c\\M-|c|C-|M-))? (?: \\ (?: . | [0-7]{3} | x[0-9A-Fa-f][0-9A-Fa-f] ) ) /mox) kind = :integer elsif @scanner.scan(/ [-+*\/%=<>;,|&!()\[\]{}~?] | \.\.?\.? | ::? /x) kind = :operator @regexp_allowed = :set if @scanner.matched[-1,1] =~ /[~=!<>|&^,\(\[+\-\/\*%]\z/ elsif @scanner.scan(FLOAT) kind = :float elsif @scanner.scan(INTEGER) kind = :integer else @scanner.getch end end token = Token.new @scanner.matched, kind if kind == :regexp token.text << @scanner.scan(/[eimnosux]*/) end @regexp_allowed = (@regexp_allowed == :set) # delayed flag setting token end end register Ruby, 'ruby', 'rb' end end class Set include Enumerable # Creates a new set containing the given objects. def self.[](*ary) new(ary) end # Creates a new set containing the elements of the given enumerable # object. # # If a block is given, the elements of enum are preprocessed by the # given block. def initialize(enum = nil, &block) # :yields: o @hash ||= Hash.new enum.nil? and return if block enum.each { |o| add(block[o]) } else merge(enum) end end # Copy internal hash. def initialize_copy(orig) @hash = orig.instance_eval{@hash}.dup end # Returns the number of elements. def size @hash.size end alias length size # Returns true if the set contains no elements. def empty? @hash.empty? end # Removes all elements and returns self. def clear @hash.clear self end # Replaces the contents of the set with the contents of the given # enumerable object and returns self. def replace(enum) if enum.class == self.class @hash.replace(enum.instance_eval { @hash }) else enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" clear enum.each { |o| add(o) } end self end # Converts the set to an array. The order of elements is uncertain. def to_a @hash.keys end def flatten_merge(set, seen = Set.new) set.each { |e| if e.is_a?(Set) if seen.include?(e_id = e.object_id) raise ArgumentError, "tried to flatten recursive Set" end seen.add(e_id) flatten_merge(e, seen) seen.delete(e_id) else add(e) end } self end protected :flatten_merge # Returns a new set that is a copy of the set, flattening each # containing set recursively. def flatten self.class.new.flatten_merge(self) end # Equivalent to Set#flatten, but replaces the receiver with the # result in place. Returns nil if no modifications were made. def flatten! if detect { |e| e.is_a?(Set) } replace(flatten()) else nil end end # Returns true if the set contains the given object. def include?(o) @hash.include?(o) end alias member? include? # Returns true if the set is a superset of the given set. def superset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if size < set.size set.all? { |o| include?(o) } end # Returns true if the set is a proper superset of the given set. def proper_superset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if size <= set.size set.all? { |o| include?(o) } end # Returns true if the set is a subset of the given set. def subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size < size all? { |o| set.include?(o) } end # Returns true if the set is a proper subset of the given set. def proper_subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size <= size all? { |o| set.include?(o) } end # Calls the given block once for each element in the set, passing # the element as parameter. def each @hash.each_key { |o| yield(o) } self end # Adds the given object to the set and returns self. Use +merge+ to # add several elements at once. def add(o) @hash[o] = true self end alias << add # Adds the given object to the set and returns self. If the # object is already in the set, returns nil. def add?(o) if include?(o) nil else add(o) end end # Deletes the given object from the set and returns self. Use +subtract+ to # delete several items at once. def delete(o) @hash.delete(o) self end # Deletes the given object from the set and returns self. If the # object is not in the set, returns nil. def delete?(o) if include?(o) delete(o) else nil end end # Deletes every element of the set for which block evaluates to # true, and returns self. def delete_if @hash.delete_if { |o,| yield(o) } self end # Do collect() destructively. def collect! set = self.class.new each { |o| set << yield(o) } replace(set) end alias map! collect! # Equivalent to Set#delete_if, but returns nil if no changes were # made. def reject! n = size delete_if { |o| yield(o) } size == n ? nil : self end # Merges the elements of the given enumerable object to the set and # returns self. def merge(enum) if enum.is_a?(Set) @hash.update(enum.instance_eval { @hash }) else enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" enum.each { |o| add(o) } end self end # Deletes every element that appears in the given enumerable object # and returns self. def subtract(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" enum.each { |o| delete(o) } self end # Returns a new set built by merging the set and the elements of the # given enumerable object. def |(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" dup.merge(enum) end alias + | ## alias union | ## # Returns a new set built by duplicating the set, removing every # element that appears in the given enumerable object. def -(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" dup.subtract(enum) end alias difference - ## # Returns a new array containing elements common to the set and the # given enumerable object. def &(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" n = self.class.new enum.each { |o| n.add(o) if include?(o) } n end alias intersection & ## # Returns a new array containing elements exclusive between the set # and the given enumerable object. (set ^ enum) is equivalent to # ((set | enum) - (set & enum)). def ^(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" n = dup enum.each { |o| if n.include?(o) then n.delete(o) else n.add(o) end } n end # Returns true if two sets are equal. The equality of each couple # of elements is defined according to Object#eql?. def ==(set) equal?(set) and return true set.is_a?(Set) && size == set.size or return false hash = @hash.dup set.all? { |o| hash.include?(o) } end def hash # :nodoc: @hash.hash end def eql?(o) # :nodoc: return false unless o.is_a?(Set) @hash.eql?(o.instance_eval{@hash}) end # Classifies the set by the return value of the given block and # returns a hash of {value => set of elements} pairs. The block is # called once for each element of the set, passing the element as # parameter. # # e.g.: # # require 'set' # files = Set.new(Dir.glob("*.rb")) # hash = files.classify { |f| File.mtime(f).year } # p hash # => {2000=>#, # # 2001=>#, # # 2002=>#} def classify # :yields: o h = {} each { |i| x = yield(i) (h[x] ||= self.class.new).add(i) } h end # Divides the set into a set of subsets according to the commonality # defined by the given block. # # If the arity of the block is 2, elements o1 and o2 are in common # if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are # in common if block.call(o1) == block.call(o2). # # e.g.: # # require 'set' # numbers = Set[1, 3, 4, 6, 9, 10, 11] # set = numbers.divide { |i,j| (i - j).abs == 1 } # p set # => #, # # #, # # #, # # #}> def divide(&func) if func.arity == 2 require 'tsort' class << dig = {} # :nodoc: include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end each { |u| dig[u] = a = [] each{ |v| func.call(u, v) and a << v } } set = Set.new() dig.each_strongly_connected_component { |css| set.add(self.class.new(css)) } set else Set.new(classify(&func).values) end end InspectKey = :__inspect_key__ # :nodoc: # Returns a string containing a human-readable representation of the # set. ("#") def inspect ids = (Thread.current[InspectKey] ||= []) if ids.include?(object_id) return sprintf('#<%s: {...}>', self.class.name) end begin ids << object_id return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2]) ensure ids.pop end end def pretty_print(pp) # :nodoc: pp.text sprintf('#<%s: {', self.class.name) pp.nest(1) { pp.seplist(self) { |o| pp.pp o } } pp.text "}>" end def pretty_print_cycle(pp) # :nodoc: pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...') end end # SortedSet implements a set which elements are sorted in order. See Set. class SortedSet < Set @@setup = false class << self def [](*ary) # :nodoc: new(ary) end def setup # :nodoc: @@setup and return begin require 'rbtree' module_eval %{ def initialize(*args, &block) @hash = RBTree.new super end } rescue LoadError module_eval %{ def initialize(*args, &block) @keys = nil super end def clear @keys = nil super end def replace(enum) @keys = nil super end def add(o) @keys = nil @hash[o] = true self end alias << add def delete(o) @keys = nil @hash.delete(o) self end def delete_if n = @hash.size @hash.delete_if { |o,| yield(o) } @keys = nil if @hash.size != n self end def merge(enum) @keys = nil super end def each to_a.each { |o| yield(o) } end def to_a (@keys = @hash.keys).sort! unless @keys @keys end } end @@setup = true end end def initialize(*args, &block) # :nodoc: SortedSet.setup initialize(*args, &block) end end module Enumerable # Makes a set from the enumerable object with given arguments. def to_set(klass = Set, *args, &block) klass.new(self, *args, &block) end end # =begin # == RestricedSet class # RestricedSet implements a set with restrictions defined by a given # block. # # === Super class # Set # # === Class Methods # --- RestricedSet::new(enum = nil) { |o| ... } # --- RestricedSet::new(enum = nil) { |rset, o| ... } # Creates a new restricted set containing the elements of the given # enumerable object. Restrictions are defined by the given block. # # If the block's arity is 2, it is called with the RestrictedSet # itself and an object to see if the object is allowed to be put in # the set. # # Otherwise, the block is called with an object to see if the object # is allowed to be put in the set. # # === Instance Methods # --- restriction_proc # Returns the restriction procedure of the set. # # =end # # class RestricedSet < Set # def initialize(*args, &block) # @proc = block or raise ArgumentError, "missing a block" # # if @proc.arity == 2 # instance_eval %{ # def add(o) # @hash[o] = true if @proc.call(self, o) # self # end # alias << add # # def add?(o) # if include?(o) || !@proc.call(self, o) # nil # else # @hash[o] = true # self # end # end # # def replace(enum) # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" # clear # enum.each { |o| add(o) } # # self # end # # def merge(enum) # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" # enum.each { |o| add(o) } # # self # end # } # else # instance_eval %{ # def add(o) # if @proc.call(o) # @hash[o] = true # end # self # end # alias << add # # def add?(o) # if include?(o) || !@proc.call(o) # nil # else # @hash[o] = true # self # end # end # } # end # # super(*args) # end # # def restriction_proc # @proc # end # end if $0 == __FILE__ eval DATA.read, nil, $0, __LINE__+4 end # = rweb - CGI Support Library # # Author:: Johannes Barre (mailto:rweb@igels.net) # Copyright:: Copyright (c) 2003, 04 by Johannes Barre # License:: GNU Lesser General Public License (COPYING, http://www.gnu.org/copyleft/lesser.html) # Version:: 0.1.0 # CVS-ID:: $Id: example.rb 39 2005-11-05 03:33:55Z murphy $ # # == What is Rweb? # Rweb is a replacement for the cgi class included in the ruby distribution. # # == How to use # # === Basics # # This class is made to be as easy as possible to use. An example: # # require "rweb" # # web = Rweb.new # web.out do # web.puts "Hello world!" # end # # The visitor will get a simple "Hello World!" in his browser. Please notice, # that won't set html-tags for you, so you should better do something like this: # # require "rweb" # # web = Rweb.new # web.out do # web.puts "Hello world!" # end # # === Set headers # Of course, it's also possible to tell the browser, that the content of this # page is plain text instead of html code: # # require "rweb" # # web = Rweb.new # web.out do # web.header("content-type: text/plain") # web.puts "Hello plain world!" # end # # Please remember, headers can't be set after the page content has been send. # You have to set all nessessary headers before the first puts oder print. It's # possible to cache the content until everything is complete. Doing it this # way, you can set headers everywhere. # # If you set a header twice, the second header will replace the first one. The # header name is not casesensitive, it will allways converted in to the # capitalised form suggested by the w3c (http://w3.org) # # === Set cookies # Setting cookies is quite easy: # include 'rweb' # # web = Rweb.new # Cookie.new("Visits", web.cookies['visits'].to_i +1) # web.out do # web.puts "Welcome back! You visited this page #{web.cookies['visits'].to_i +1} times" # end # # See the class Cookie for more details. # # === Get form and cookie values # There are four ways to submit data from the browser to the server and your # ruby script: via GET, POST, cookies and file upload. Rweb doesn't support # file upload by now. # # include 'rweb' # # web = Rweb.new # web.out do # web.print "action: #{web.get['action']} " # web.puts "The value of the cookie 'visits' is #{web.cookies['visits']}" # web.puts "The post parameter 'test['x']' is #{web.post['test']['x']}" # end RWEB_VERSION = "0.1.0" RWEB = "rweb/#{RWEB_VERSION}" #require 'rwebcookie' -> edit by bunny :-) class Rweb # All parameter submitted via the GET method are available in attribute # get. This is Hash, where every parameter is available as a key-value # pair. # # If your input tag has a name like this one, it's value will be available # as web.get["fieldname"] # # You can submit values as a Hash # # # will be available as # web.get["text"]["index"] # web.get["text"]["index2"] # Integers are also possible # # # # will be available as # web.get["int"][0] # First Field # web.get["int"][1] # Second one # Please notice, this doesn'd work like you might expect: # # It will not be available as web.get["text"]["index"] but # web.get["text[index]"] attr_reader :get # All parameters submitted via POST are available in the attribute post. It # works like the get attribute. # # will be available as # web.post["text"][0] attr_reader :post # All cookies submitted by the browser are available in cookies. This is a # Hash, where every cookie is a key-value pair. attr_reader :cookies # The name of the browser identification is submitted as USER_AGENT and # available in this attribute. attr_reader :user_agent # The IP address of the client. attr_reader :remote_addr # Creates a new Rweb object. This should only done once. You can set various # options via the settings hash. # # "cache" => true: Everything you script send to the client will be cached # until the end of the out block or until flush is called. This way, you # can modify headers and cookies even after printing something to the client. # # "safe" => level: Changes the $SAFE attribute. By default, $SAFE will be set # to 1. If $SAFE is already higher than this value, it won't be changed. # # "silend" => true: Normaly, Rweb adds automaticly a header like this # "X-Powered-By: Rweb/x.x.x (Ruby/y.y.y)". With the silend option you can # suppress this. def initialize (settings = {}) # {{{ @header = {} @cookies = {} @get = {} @post = {} # Internal attributes @status = nil @reasonPhrase = nil @setcookies = [] @output_started = false; @output_allowed = false; @mod_ruby = false @env = ENV.to_hash if defined?(MOD_RUBY) @output_method = "mod_ruby" @mod_ruby = true elsif @env['SERVER_SOFTWARE'] =~ /^Microsoft-IIS/i @output_method = "nph" else @output_method = "ph" end unless settings.is_a?(Hash) raise TypeError, "settings must be a Hash" end @settings = settings unless @settings.has_key?("safe") @settings["safe"] = 1 end if $SAFE < @settings["safe"] $SAFE = @settings["safe"] end unless @settings.has_key?("cache") @settings["cache"] = false end # mod_ruby sets no QUERY_STRING variable, if no GET-Parameters are given unless @env.has_key?("QUERY_STRING") @env["QUERY_STRING"] = "" end # Now we split the QUERY_STRING by the seperators & and ; or, if # specified, settings['get seperator'] unless @settings.has_key?("get seperator") get_args = @env['QUERY_STRING'].split(/[&;]/) else get_args = @env['QUERY_STRING'].split(@settings['get seperator']) end get_args.each do | arg | arg_key, arg_val = arg.split(/=/, 2) arg_key = Rweb::unescape(arg_key) arg_val = Rweb::unescape(arg_val) # Parse names like name[0], name['text'] or name[] pattern = /^(.+)\[("[^\]]*"|'[^\]]*'|[0-9]*)\]$/ keys = [] while match = pattern.match(arg_key) arg_key = match[1] keys = [match[2]] + keys end keys = [arg_key] + keys akt = @get last = nil lastkey = nil keys.each do |key| if key == "" # No key specified (like in "test[]"), so we use the # lowerst unused Integer as key key = 0 while akt.has_key?(key) key += 1 end elsif /^[0-9]*$/ =~ key # If the index is numerical convert it to an Integer key = key.to_i elsif key[0].chr == "'" || key[0].chr == '"' key = key[1, key.length() -2] end if !akt.has_key?(key) || !akt[key].class == Hash # create an empty Hash if there isn't already one akt[key] = {} end last = akt lastkey = key akt = akt[key] end last[lastkey] = arg_val end if @env['REQUEST_METHOD'] == "POST" if @env.has_key?("CONTENT_TYPE") && @env['CONTENT_TYPE'] == "application/x-www-form-urlencoded" && @env.has_key?('CONTENT_LENGTH') unless @settings.has_key?("post seperator") post_args = $stdin.read(@env['CONTENT_LENGTH'].to_i).split(/[&;]/) else post_args = $stdin.read(@env['CONTENT_LENGTH'].to_i).split(@settings['post seperator']) end post_args.each do | arg | arg_key, arg_val = arg.split(/=/, 2) arg_key = Rweb::unescape(arg_key) arg_val = Rweb::unescape(arg_val) # Parse names like name[0], name['text'] or name[] pattern = /^(.+)\[("[^\]]*"|'[^\]]*'|[0-9]*)\]$/ keys = [] while match = pattern.match(arg_key) arg_key = match[1] keys = [match[2]] + keys end keys = [arg_key] + keys akt = @post last = nil lastkey = nil keys.each do |key| if key == "" # No key specified (like in "test[]"), so we use # the lowerst unused Integer as key key = 0 while akt.has_key?(key) key += 1 end elsif /^[0-9]*$/ =~ key # If the index is numerical convert it to an Integer key = key.to_i elsif key[0].chr == "'" || key[0].chr == '"' key = key[1, key.length() -2] end if !akt.has_key?(key) || !akt[key].class == Hash # create an empty Hash if there isn't already one akt[key] = {} end last = akt lastkey = key akt = akt[key] end last[lastkey] = arg_val end else # Maybe we should print a warning here? $stderr.print("Unidentified form data recived and discarded.") end end if @env.has_key?("HTTP_COOKIE") cookie = @env['HTTP_COOKIE'].split(/; ?/) cookie.each do | c | cookie_key, cookie_val = c.split(/=/, 2) @cookies [Rweb::unescape(cookie_key)] = Rweb::unescape(cookie_val) end end if defined?(@env['HTTP_USER_AGENT']) @user_agent = @env['HTTP_USER_AGENT'] else @user_agent = nil; end if defined?(@env['REMOTE_ADDR']) @remote_addr = @env['REMOTE_ADDR'] else @remote_addr = nil end # }}} end # Prints a String to the client. If caching is enabled, the String will # buffered until the end of the out block ends. def print(str = "") # {{{ unless @output_allowed raise "You just can write to output inside of a Rweb::out-block" end if @settings["cache"] @buffer += [str.to_s] else unless @output_started sendHeaders end $stdout.print(str) end nil # }}} end # Prints a String to the client and adds a line break at the end. Please # remember, that a line break is not visible in HTML, use the
HTML-Tag # for this. If caching is enabled, the String will buffered until the end # of the out block ends. def puts(str = "") # {{{ self.print(str + "\n") # }}} end # Alias to print. def write(str = "") # {{{ self.print(str) # }}} end # If caching is enabled, all cached data are send to the cliend and the # cache emptied. def flush # {{{ unless @output_allowed raise "You can't use flush outside of a Rweb::out-block" end buffer = @buffer.join unless @output_started sendHeaders end $stdout.print(buffer) @buffer = [] # }}} end # Sends one or more header to the client. All headers are cached just # before body data are send to the client. If the same header are set # twice, only the last value is send. # # Example: # web.header("Last-Modified: Mon, 16 Feb 2004 20:15:41 GMT") # web.header("Location: http://www.ruby-lang.org") # # You can specify more than one header at the time by doing something like # this: # web.header("Content-Type: text/plain\nContent-Length: 383") # or # web.header(["Content-Type: text/plain", "Content-Length: 383"]) def header(str) # {{{ if @output_started raise "HTTP-Headers are already send. You can't change them after output has started!" end unless @output_allowed raise "You just can set headers inside of a Rweb::out-block" end if str.is_a?Array str.each do | value | self.header(value) end elsif str.split(/\n/).length > 1 str.split(/\n/).each do | value | self.header(value) end elsif str.is_a? String str.gsub!(/\r/, "") if (str =~ /^HTTP\/1\.[01] [0-9]{3} ?.*$/) == 0 pattern = /^HTTP\/1.[01] ([0-9]{3}) ?(.*)$/ result = pattern.match(str) self.setstatus(result[0], result[1]) elsif (str =~ /^status: [0-9]{3} ?.*$/i) == 0 pattern = /^status: ([0-9]{3}) ?(.*)$/i result = pattern.match(str) self.setstatus(result[0], result[1]) else a = str.split(/: ?/, 2) @header[a[0].downcase] = a[1] end end # }}} end # Changes the status of this page. There are several codes like "200 OK", # "302 Found", "404 Not Found" or "500 Internal Server Error". A list of # all codes is available at # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10 # # You can just send the code number, the reason phrase will be added # automaticly with the recommendations from the w3c if not specified. If # you set the status twice or more, only the last status will be send. # Examples: # web.status("401 Unauthorized") # web.status("410 Sad but true, this lonely page is gone :(") # web.status(206) # web.status("400") # # The default status is "200 OK". If a "Location" header is set, the # default status is "302 Found". def status(str) # {{{ if @output_started raise "HTTP-Headers are already send. You can't change them after output has started!" end unless @output_allowed raise "You just can set headers inside of a Rweb::out-block" end if str.is_a?Integer @status = str elsif str.is_a?String p1 = /^([0-9]{3}) ?(.*)$/ p2 = /^HTTP\/1\.[01] ([0-9]{3}) ?(.*)$/ p3 = /^status: ([0-9]{3}) ?(.*)$/i if (a = p1.match(str)) == nil if (a = p2.match(str)) == nil if (a = p3.match(str)) == nil raise ArgumentError, "Invalid argument", caller end end end @status = a[1].to_i if a[2] != "" @reasonPhrase = a[2] else @reasonPhrase = getReasonPhrase(@status) end else raise ArgumentError, "Argument of setstatus must be integer or string", caller end # }}} end # Handles the output of your content and rescues all exceptions. Send all # data in the block to this method. For example: # web.out do # web.header("Content-Type: text/plain") # web.puts("Hello, plain world!") # end def out # {{{ @output_allowed = true @buffer = []; # We use an array as buffer, because it's more performant :) begin yield rescue Exception => exception $stderr.puts "Ruby exception rescued (#{exception.class}): #{exception.message}" $stderr.puts exception.backtrace.join("\n") unless @output_started self.setstatus(500) @header = {} end unless (@settings.has_key?("hide errors") and @settings["hide errors"] == true) unless @output_started self.header("Content-Type: text/html") self.puts "" self.puts "" self.puts "" self.puts "500 Internal Server Error" self.puts "" self.puts "" end if @header.has_key?("content-type") and (@header["content-type"] =~ /^text\/html/i) == 0 self.puts "

Internal Server Error

" self.puts "

The server encountered an exception and was unable to complete your request.

" self.puts "

The exception has provided the following information:

" self.puts "
#{exception.class}: #{exception.message} on"
                    self.puts
                    self.puts "#{exception.backtrace.join("\n")}
" self.puts "" self.puts "" else self.puts "The server encountered an exception and was unable to complete your request" self.puts "The exception has provided the following information:" self.puts "#{exception.class}: #{exception.message}" self.puts self.puts exception.backtrace.join("\n") end end end if @settings["cache"] buffer = @buffer.join unless @output_started unless @header.has_key?("content-length") self.header("content-length: #{buffer.length}") end sendHeaders end $stdout.print(buffer) elsif !@output_started sendHeaders end @output_allowed = false; # }}} end # Decodes URL encoded data, %20 for example stands for a space. def Rweb.unescape(str) # {{{ if defined? str and str.is_a? String str.gsub!(/\+/, " ") str.gsub(/%.{2}/) do | s | s[1,2].hex.chr end end # }}} end protected def sendHeaders # {{{ Cookie.disallow # no more cookies can be set or modified if !(@settings.has_key?("silent") and @settings["silent"] == true) and !@header.has_key?("x-powered-by") if @mod_ruby header("x-powered-by: #{RWEB} (Ruby/#{RUBY_VERSION}, #{MOD_RUBY})"); else header("x-powered-by: #{RWEB} (Ruby/#{RUBY_VERSION})"); end end if @output_method == "ph" if ((@status == nil or @status == 200) and !@header.has_key?("content-type") and !@header.has_key?("location")) header("content-type: text/html") end if @status != nil $stdout.print "Status: #{@status} #{@reasonPhrase}\r\n" end @header.each do |key, value| key = key *1 # "unfreeze" key :) key[0] = key[0,1].upcase![0] key = key.gsub(/-[a-z]/) do |char| "-" + char[1,1].upcase end $stdout.print "#{key}: #{value}\r\n" end cookies = Cookie.getHttpHeader # Get all cookies as an HTTP Header if cookies $stdout.print cookies end $stdout.print "\r\n" elsif @output_method == "nph" elsif @output_method == "mod_ruby" r = Apache.request if ((@status == nil or @status == 200) and !@header.has_key?("content-type") and !@header.has_key?("location")) header("text/html") end if @status != nil r.status_line = "#{@status} #{@reasonPhrase}" end r.send_http_header @header.each do |key, value| key = key *1 # "unfreeze" key :) key[0] = key[0,1].upcase![0] key = key.gsub(/-[a-z]/) do |char| "-" + char[1,1].upcase end puts "#{key}: #{value.class}" #r.headers_out[key] = value end end @output_started = true # }}} end def getReasonPhrase (status) # {{{ if status == 100 "Continue" elsif status == 101 "Switching Protocols" elsif status == 200 "OK" elsif status == 201 "Created" elsif status == 202 "Accepted" elsif status == 203 "Non-Authoritative Information" elsif status == 204 "No Content" elsif status == 205 "Reset Content" elsif status == 206 "Partial Content" elsif status == 300 "Multiple Choices" elsif status == 301 "Moved Permanently" elsif status == 302 "Found" elsif status == 303 "See Other" elsif status == 304 "Not Modified" elsif status == 305 "Use Proxy" elsif status == 307 "Temporary Redirect" elsif status == 400 "Bad Request" elsif status == 401 "Unauthorized" elsif status == 402 "Payment Required" elsif status == 403 "Forbidden" elsif status == 404 "Not Found" elsif status == 405 "Method Not Allowed" elsif status == 406 "Not Acceptable" elsif status == 407 "Proxy Authentication Required" elsif status == 408 "Request Time-out" elsif status == 409 "Conflict" elsif status == 410 "Gone" elsif status == 411 "Length Required" elsif status == 412 "Precondition Failed" elsif status == 413 "Request Entity Too Large" elsif status == 414 "Request-URI Too Large" elsif status == 415 "Unsupported Media Type" elsif status == 416 "Requested range not satisfiable" elsif status == 417 "Expectation Failed" elsif status == 500 "Internal Server Error" elsif status == 501 "Not Implemented" elsif status == 502 "Bad Gateway" elsif status == 503 "Service Unavailable" elsif status == 504 "Gateway Time-out" elsif status == 505 "HTTP Version not supported" else raise "Unknown Statuscode. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1 for more information." end # }}} end end class Cookie attr_reader :name, :value, :maxage, :path, :domain, :secure, :comment # Sets a cookie. Please see below for details of the attributes. def initialize (name, value = nil, maxage = nil, path = nil, domain = nil, secure = false) # {{{ # HTTP headers (Cookies are a HTTP header) can only set, while no content # is send. So an exception will be raised, when @@allowed is set to false # and a new cookie has set. unless defined?(@@allowed) @@allowed = true end unless @@allowed raise "You can't set cookies after the HTTP headers are send." end unless defined?(@@list) @@list = [] end @@list += [self] unless defined?(@@type) @@type = "netscape" end unless name.class == String raise TypeError, "The name of a cookie must be a string", caller end if value.class.superclass == Integer || value.class == Float value = value.to_s elsif value.class != String && value != nil raise TypeError, "The value of a cookie must be a string, integer, float or nil", caller end if maxage.class == Time maxage = maxage - Time.now elsif !maxage.class.superclass == Integer || !maxage == nil raise TypeError, "The maxage date of a cookie must be an Integer or Time object or nil.", caller end unless path.class == String || path == nil raise TypeError, "The path of a cookie must be nil or a string", caller end unless domain.class == String || domain == nil raise TypeError, "The value of a cookie must be nil or a string", caller end unless secure == true || secure == false raise TypeError, "The secure field of a cookie must be true or false", caller end @name, @value, @maxage, @path, @domain, @secure = name, value, maxage, path, domain, secure @comment = nil # }}} end # Modifies the value of this cookie. The information you want to store. If the # value is nil, the cookie will be deleted by the client. # # This attribute can be a String, Integer or Float object or nil. def value=(value) # {{{ if value.class.superclass == Integer || value.class == Float value = value.to_s elsif value.class != String && value != nil raise TypeError, "The value of a cookie must be a string, integer, float or nil", caller end @value = value # }}} end # Modifies the maxage of this cookie. This attribute defines the lifetime of # the cookie, in seconds. A value of 0 means the cookie should be discarded # imediatly. If it set to nil, the cookie will be deleted when the browser # will be closed. # # Attention: This is different from other implementations like PHP, where you # gives the seconds since 1/1/1970 0:00:00 GMT. # # This attribute must be an Integer or Time object or nil. def maxage=(maxage) # {{{ if maxage.class == Time maxage = maxage - Time.now elsif maxage.class.superclass == Integer || !maxage == nil raise TypeError, "The maxage of a cookie must be an Interger or Time object or nil.", caller end @maxage = maxage # }}} end # Modifies the path value of this cookie. The client will send this cookie # only, if the requested document is this directory or a subdirectory of it. # # The value of the attribute must be a String object or nil. def path=(path) # {{{ unless path.class == String || path == nil raise TypeError, "The path of a cookie must be nil or a string", caller end @path = path # }}} end # Modifies the domain value of this cookie. The client will send this cookie # only if it's connected with this domain (or a subdomain, if the first # character is a dot like in ".ruby-lang.org") # # The value of this attribute must be a String or nil. def domain=(domain) # {{{ unless domain.class == String || domain == nil raise TypeError, "The domain of a cookie must be a String or nil.", caller end @domain = domain # }}} end # Modifies the secure flag of this cookie. If it's true, the client will only # send this cookie if it is secured connected with us. # # The value od this attribute has to be true or false. def secure=(secure) # {{{ unless secure == true || secure == false raise TypeError, "The secure field of a cookie must be true or false", caller end @secure = secure # }}} end # Modifies the comment value of this cookie. The comment won't be send, if # type is "netscape". def comment=(comment) # {{{ unless comment.class == String || comment == nil raise TypeError, "The comment of a cookie must be a string or nil", caller end @comment = comment # }}} end # Changes the type of all cookies. # Allowed values are RFC2109 and netscape (default). def Cookie.type=(type) # {{{ unless @@allowed raise "The cookies are allready send, so you can't change the type anymore." end unless type.downcase == "rfc2109" && type.downcase == "netscape" raise "The type of the cookies must be \"RFC2109\" or \"netscape\"." end @@type = type; # }}} end # After sending this message, no cookies can be set or modified. Use it, when # HTTP-Headers are send. Rweb does this for you. def Cookie.disallow # {{{ @@allowed = false true # }}} end # Returns a HTTP header (type String) with all cookies. Rweb does this for # you. def Cookie.getHttpHeader # {{{ if defined?(@@list) if @@type == "netscape" str = "" @@list.each do |cookie| if cookie.value == nil cookie.maxage = 0 cookie.value = "" end # TODO: Name and value should be escaped! str += "Set-Cookie: #{cookie.name}=#{cookie.value}" unless cookie.maxage == nil expire = Time.now + cookie.maxage expire.gmtime str += "; Expire=#{expire.strftime("%a, %d-%b-%Y %H:%M:%S %Z")}" end unless cookie.domain == nil str += "; Domain=#{cookie.domain}" end unless cookie.path == nil str += "; Path=#{cookie.path}" end if cookie.secure str += "; Secure" end str += "\r\n" end return str else # type == "RFC2109" str = "Set-Cookie: " comma = false; @@list.each do |cookie| if cookie.value == nil cookie.maxage = 0 cookie.value = "" end if comma str += "," end comma = true str += "#{cookie.name}=\"#{cookie.value}\"" unless cookie.maxage == nil str += "; Max-Age=\"#{cookie.maxage}\"" end unless cookie.domain == nil str += "; Domain=\"#{cookie.domain}\"" end unless cookie.path == nil str += "; Path=\"#{cookie.path}\"" end if cookie.secure str += "; Secure" end unless cookie.comment == nil str += "; Comment=\"#{cookie.comment}\"" end str += "; Version=\"1\"" end str end else false end # }}} end end require 'strscan' module BBCode DEBUG = true use 'encoder', 'tags', 'tagstack', 'smileys' =begin The Parser class takes care of the encoding. It scans the given BBCode (as plain text), finds tags and smilies and also makes links of urls in text. Normal text is send directly to the encoder. If a tag was found, an instance of a Tag subclass is created to handle the case. The @tagstack manages tag nesting and ensures valid HTML. =end class Parser class Attribute # flatten and use only one empty_arg def self.create attr attr = flatten attr return @@empty_attr if attr.empty? new attr end private_class_method :new # remove leading and trailing whitespace; concat lines def self.flatten attr attr.strip.gsub(/\n/, ' ') # -> ^ and $ can only match at begin and end now end ATTRIBUTE_SCAN = / (?!$) # don't match at end \s* ( # $1 = key [^=\s\]"\\]* (?: (?: \\. | "[^"\\]*(?:\\.[^"\\]*)*"? ) [^=\s\]"\\]* )* ) (?: = ( # $2 = value [^\s\]"\\]* (?: (?: \\. | "[^"\\]*(?:\\.[^"\\]*)*"? ) [^\s\]"\\]* )* )? )? \s* /x def self.parse source source = source.dup # empty_tag: the tag looks like [... /] # slice!: this deletes the \s*/] at the end # \s+ because [url=http://rubybb.org/forum/] is NOT an empty tag. # In RubyBBCode, you can use [url=http://rubybb.org/forum/ /], and this has to be # interpreted correctly. empty_tag = source.sub!(/^:/, '=') or source.slice!(/\/$/) debug 'PARSE: ' + source.inspect + ' => ' + empty_tag.inspect #-> we have now an attr that's EITHER empty OR begins and ends with non-whitespace. attr = Hash.new attr[:flags] = [] source.scan(ATTRIBUTE_SCAN) { |key, value| if not value attr[:flags] << unescape(key) else next if value.empty? and key.empty? attr[unescape(key)] = unescape(value) end } debug attr.inspect return empty_tag, attr end def self.unescape_char esc esc[1] end def self.unquote qt qt[1..-1].chomp('"').gsub(/\\./) { |esc| unescape_char esc } end def self.unescape str str.gsub(/ (\\.) | (" [^"\\]* (?:\\.[^"\\]*)* "?) /x) { if $1 unescape_char $1 else unquote $2 end } end include Enumerable def each &block @args.each(&block) end attr_reader :source, :args, :value def initialize source @source = source debug 'Attribute#new(%p)' % source @empty_tag, @attr = Attribute.parse source @value = @attr[''].to_s end def empty? self == @@empty_attr end def empty_tag? @empty_tag end def [] *keys res = @attr[*keys] end def flags attr[:flags] end def to_s @attr end def inspect 'ATTR[' + @attr.inspect + (@empty_tag ? ' | empty tag' : '') + ']' end end class Attribute @@empty_attr = new '' end end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.red000066400000000000000000000156631250413007300260320ustar00rootroot00000000000000Red [ Title: "Red console" Author: ["Nenad Rakocevic" "Kaj de Vos"] File: %console.red Tabs: 4 Rights: "Copyright (C) 2012-2013 Nenad Rakocevic. All rights reserved." License: { Distributed under the Boost Software License, Version 1.0. See https://github.com/dockimbel/Red/blob/master/BSL-License.txt } Purpose: "Just some code for testing Pygments colorizer" Language: http://www.red-lang.org/ ] #system-global [ #either OS = 'Windows [ #import [ "kernel32.dll" stdcall [ AttachConsole: "AttachConsole" [ processID [integer!] return: [integer!] ] SetConsoleTitle: "SetConsoleTitleA" [ title [c-string!] return: [integer!] ] ReadConsole: "ReadConsoleA" [ consoleInput [integer!] buffer [byte-ptr!] charsToRead [integer!] numberOfChars [int-ptr!] inputControl [int-ptr!] return: [integer!] ] ] ] line-buffer-size: 16 * 1024 line-buffer: allocate line-buffer-size ][ #switch OS [ MacOSX [ #define ReadLine-library "libreadline.dylib" ] #default [ #define ReadLine-library "libreadline.so.6" #define History-library "libhistory.so.6" ] ] #import [ ReadLine-library cdecl [ read-line: "readline" [ ; Read a line from the console. prompt [c-string!] return: [c-string!] ] rl-bind-key: "rl_bind_key" [ key [integer!] command [integer!] return: [integer!] ] rl-insert: "rl_insert" [ count [integer!] key [integer!] return: [integer!] ] ] #if OS <> 'MacOSX [ History-library cdecl [ add-history: "add_history" [ ; Add line to the history. line [c-string!] ] ] ] ] rl-insert-wrapper: func [ [cdecl] count [integer!] key [integer!] return: [integer!] ][ rl-insert count key ] ] ] Windows?: system/platform = 'Windows read-argument: routine [ /local args [str-array!] str [red-string!] ][ if system/args-count <> 2 [ SET_RETURN(none-value) exit ] args: system/args-list + 1 ;-- skip binary filename str: simple-io/read-txt args/item SET_RETURN(str) ] init-console: routine [ str [string!] /local ret ][ #either OS = 'Windows [ ;ret: AttachConsole -1 ;if zero? ret [print-line "ReadConsole failed!" halt] ret: SetConsoleTitle as c-string! string/rs-head str if zero? ret [print-line "SetConsoleTitle failed!" halt] ][ rl-bind-key as-integer tab as-integer :rl-insert-wrapper ] ] input: routine [ prompt [string!] /local len ret str buffer line ][ #either OS = 'Windows [ len: 0 print as c-string! string/rs-head prompt ret: ReadConsole stdin line-buffer line-buffer-size :len null if zero? ret [print-line "ReadConsole failed!" halt] len: len + 1 line-buffer/len: null-byte str: string/load as c-string! line-buffer len ][ line: read-line as c-string! string/rs-head prompt if line = null [halt] ; EOF #if OS <> 'MacOSX [add-history line] str: string/load line 1 + length? line ; free as byte-ptr! line ] SET_RETURN(str) ] count-delimiters: function [ buffer [string!] return: [block!] ][ list: copy [0 0] c: none foreach c buffer [ case [ escaped? [ escaped?: no ] in-comment? [ switch c [ #"^/" [in-comment?: no] ] ] 'else [ switch c [ #"^^" [escaped?: yes] #";" [if zero? list/2 [in-comment?: yes]] #"[" [list/1: list/1 + 1] #"]" [list/1: list/1 - 1] #"{" [list/2: list/2 + 1] #"}" [list/2: list/2 - 1] ] ] ] ] list ] do-console: function [][ buffer: make string! 10000 prompt: red-prompt: "red>> " mode: 'mono switch-mode: [ mode: case [ cnt/1 > 0 ['block] cnt/2 > 0 ['string] 'else [ prompt: red-prompt do eval 'mono ] ] prompt: switch mode [ block ["[^-"] string ["{^-"] mono [red-prompt] ] ] eval: [ code: load/all buffer unless tail? code [ set/any 'result do code unless unset? :result [ if 67 = length? result: mold/part :result 67 [ ;-- optimized for width = 72 clear back tail result append result "..." ] print ["==" result] ] ] clear buffer ] while [true][ unless tail? line: input prompt [ append buffer line cnt: count-delimiters buffer either Windows? [ remove skip tail buffer -2 ;-- clear extra CR (Windows) ][ append buffer lf ;-- Unix ] switch mode [ block [if cnt/1 <= 0 [do switch-mode]] string [if cnt/2 <= 0 [do switch-mode]] mono [do either any [cnt/1 > 0 cnt/2 > 0][switch-mode][eval]] ] ] ] ] q: :quit if script: read-argument [ script: load script either any [ script/1 <> 'Red not block? script/2 ][ print "*** Error: not a Red program!" ][ do skip script 2 ] quit ] init-console "Red Console" print { -=== Red Console alpha version ===- (only ASCII input supported) } do-consolepygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.reds000066400000000000000000000071651250413007300262130ustar00rootroot00000000000000Red/System [ Title: "Red/System example file" Purpose: "Just some code for testing Pygments colorizer" Language: http://www.red-lang.org/ ] #include %../common/FPU-configuration.reds ; C types #define time! long! #define clock! long! date!: alias struct! [ second [integer!] ; 0-61 (60?) minute [integer!] ; 0-59 hour [integer!] ; 0-23 day [integer!] ; 1-31 month [integer!] ; 0-11 year [integer!] ; Since 1900 weekday [integer!] ; 0-6 since Sunday yearday [integer!] ; 0-365 daylight-saving-time? [integer!] ; Negative: unknown ] #either OS = 'Windows [ #define clocks-per-second 1000 ][ ; CLOCKS_PER_SEC value for Syllable, Linux (XSI-conformant systems) ; TODO: check for other systems #define clocks-per-second 1000'000 ] #import [LIBC-file cdecl [ ; Error handling form-error: "strerror" [ ; Return error description. code [integer!] return: [c-string!] ] print-error: "perror" [ ; Print error to standard error output. string [c-string!] ] ; Memory management make: "calloc" [ ; Allocate zero-filled memory. chunks [size!] size [size!] return: [binary!] ] resize: "realloc" [ ; Resize memory allocation. memory [binary!] size [size!] return: [binary!] ] ] JVM!: alias struct! [ reserved0 [int-ptr!] reserved1 [int-ptr!] reserved2 [int-ptr!] DestroyJavaVM [function! [[JNICALL] vm [JVM-ptr!] return: [jint!]]] AttachCurrentThread [function! [[JNICALL] vm [JVM-ptr!] penv [struct! [p [int-ptr!]]] args [byte-ptr!] return: [jint!]]] DetachCurrentThread [function! [[JNICALL] vm [JVM-ptr!] return: [jint!]]] GetEnv [function! [[JNICALL] vm [JVM-ptr!] penv [struct! [p [int-ptr!]]] version [integer!] return: [jint!]]] AttachCurrentThreadAsDaemon [function! [[JNICALL] vm [JVM-ptr!] penv [struct! [p [int-ptr!]]] args [byte-ptr!] return: [jint!]]] ] ;just some datatypes for testing: #some-hash 10-1-2013 quit ;binary: #{00FF0000} #{00FF0000 FF000000} #{00FF0000 FF000000} ;with tab instead of space 2#{00001111} 64#{/wAAAA==} 64#{/wAAA A==} ;with space inside 64#{/wAAA A==} ;with tab inside ;string with char {bla ^(ff) foo} {bla ^(( foo} ;some numbers: 12 1'000 1.2 FF00FF00h ;some tests of hexa number notation with not common ending [ff00h ff00h] ff00h{} FFh"foo" 00h(1 + 2) (AEh) ;normal words: foo char ;get-word :foo ;lit-word: 'foo 'foo ;multiple comment tests... 1 + 1 comment "aa" 2 + 2 comment {aa} 3 + 3 comment {a^{} 4 + 4 comment {{}} 5 + 5 comment { foo: 6 } 6 + 6 comment [foo: 6] 7 + 7 comment [foo: "[" ] 8 + 8 comment [foo: {^{} ] 9 + 9 comment [foo: {boo} ] 10 + 10 comment 5-May-2014/11:17:34+2:00 11 + 11 to-integer foo foo/(a + 1)/b call/output reform ['which interpreter] path: copy "" version-1.1: 00010001h #if type = 'exe [ push system/stack/frame ;-- save previous frame pointer system/stack/frame: system/stack/top ;-- @@ reposition frame pointer just after the catch flag ] push CATCH_ALL ;-- exceptions root barrier push 0 ;-- keep stack aligned on 64-bitpygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.reg000066400000000000000000000005701250413007300260240ustar00rootroot00000000000000Windows Registry Editor Version 5.00 ; comment [HKEY_CURRENT_USER\SOFTWARE\Pygments] @="Hello" "Key With Spaces"="Something" "Key With ="="With Quotes" "Key With = 2"=dword:123 "Key" = "Value" "Hex"=hex(0):1,2,3,a,b,f "Hex 2"=hex(5):80,00,00,ff [-HKEY_CURRENT_USER\SOFTWARE\Pygments\Subkey] [HKEY_CURRENT_USER\SOFTWARE\Pygments\Subkey2] ; comment @=- "Foo"=- "Foo"="Value" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.rexx000066400000000000000000000015361250413007300262400ustar00rootroot00000000000000/* REXX example. */ /* Some basic constructs. */ almost_pi = 0.1415 + 3 if almost_pi < 3 then say 'huh?' else do say 'almost_pi=' almost_pi || " - ok" end x = '"' || "'" || '''' || """" /* quotes */ /* A comment * spawning multiple lines. /* / */ /* Built-in functions. */ line = 'line containing some short text' say WordPos(line, 'some') say Word(line, 4) /* Labels and procedures. */ some_label : divide: procedure parse arg some other return some / other call divide(5, 2) /* Loops */ do i = 1 to 5 do j = -3 to -9 by -3 say i '+' j '=' i + j end j end i do forever leave end /* Print a text file on MVS. */ ADDRESS TSO "ALLOC F(TEXTFILE) DSN('some.text.dsn') SHR REU" "EXECIO * DISKR TEXTFILE ( FINIS STEM LINES." "FREE F(TEXTFILE)" I = 1 DO WHILE I <= LINES.0 SAY ' LINE ' I ' : ' LINES.I I = I + 1 END pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.rhtml000066400000000000000000000425761250413007300264110ustar00rootroot00000000000000<% @title = 'Moderatoren-Interface' %>
<%= link_to 'Proben', :controller => '/admin/proben' %>
Die angesetzten Proben des Orchesters
<%= link_to 'Auftritte', :controller => '/admin/proben' %>
Die Auftritte des Orchesters
<%- if @valid_user and @valid_user.admin? -%>
<%= link_to 'Benutzer', :controller => '/admin/user' %>
Benutzer organisieren (nur für den Admin)
<%- end -%>
<% @title = 'Anmeldung' %> <%= render :partial => 'user_form', :object => @user %> <% @title = 'Administrator erstellen' %> <%= render :partial => 'user_form', :object => @user %> <%= form_tag %>
Name: <%= text_field 'user', 'name' %>
Passwort: <%= password_field 'user', 'password' %>
<%= submit_tag 'Anmelden' %>
<%= end_form_tag %> <% @title = 'Neuer Benutzer' -%> <%= error_messages_for :user %> <%= render :partial => 'form', :object => @user %> <%= form_tag %>
Name: <%= text_field 'user', 'name' %>
Passwort: <%= password_field 'user', 'password' %>
<%= submit_tag 'Anlegen' %>
<%= end_form_tag %> <% @title = 'Auftritte' %> <%= render :partial => 'head' %> <%= render :partial => 'day', :collection => @days %>
<% day, auftritte = *day -%> <% for auftritt in auftritte -%> <%= colorize day.to_s(:dots) if day %> <% if day and day.wday == 6 %>
Samstag<% end %> <%= colorize auftritt.time %> <%= colorize auftritt.program %> <%= link_to 'E', :controller => 'admin/auftritte', :action => :edit, :id => auftritt %> <%= colorize(auftritt.place, 'Ort: ') + '
' unless auftritt.place.blank? %> <% day = nil end -%> Datum Zeit Programm Ort <% @title = "Besetzung - #{@instrument.name}" %>

<%= pluralize(@members.size, 'Schüler spielt', 'Schüler spielen') %> <%= h @instrument.name %>:

<%= render :partial => 'member', :collection => @members %>
<% @title = 'Besetzung: %d Mitglieder' % Member.count -%> <%= render :partial => 'member', :collection => @members %>
<% @title = "Besetzung - Instrument wählen" %>
    <% for instr in @instruments -%>
  • <%= link_to h(instr.name), :action => :instrument, :id => instr.name %> (<%= h instr.members.size %>)
  • <% end -%>
<% @title = "Besetzung: #{@member.name}" -%>
Instrument / Aufgabe:
<%= link_to_instruments_of @member %>
Geburtstag:
<%= h @member.birthday.to_s(:dots) %>
Adresse:
<%= h @member.street %>
<%= h @member.plz %>
Telefon:
<%= h @member.phone %>
Email:
<%= mail_to @member.email, @member.email, :encode => 'javascript' %>
<%= link_to member.name, :action => :show, :id => member %>: <%= link_to_instruments_of member %> <% @title = 'Arbeitsgruppen' -%>

Die Arbeitsgruppen sind verantwortlich für die Organisation und Durchführung verschiedenster Aufgaben:

  • Plakate und Konzertkarten
    • Frau Schraps
    • Paul-Robert Achcenich
    • Josefine Dahms
  • Noten
    • Frau Puppe
    • Theresa Rebin
  • Programme
    • ?
  • Instrumentenstransporte
    • Frau Feldmann
    • Knut Müller
    • Patrick Wolter
    • Alexaner Wolf
  • Internetseite
    • Frau Sternbeck
    • Uwe Ritzschke
    • Paul-Robert Achcenich
    • Knut Müller
    • Alexander Wolf
<% @title = 'Chronik' -%>

Das Jugendsinfonieorchester Marzahn-Hellersdorf wurde im Januar 2005 an der Musikschule Marzahn-Hellersdorf gegründet und gab im Mai 2005 sein erstes umjubeltes Konzert im FEZ Wuhlheide. Das Orchester umfasst zur Zeit ca. 65 jugendliche Musiker und soll auf die Größe eines ausgewachsenen Sinfonieorchesters erweitert werden (80-100 Musiker).

Als musikalischer Leiter konnte der Dirigent und Echo-Preisträger Jobst Liebrecht gewonnen werden, der die Musikschule schon aus einer früheren Zusammenarbeit anlässlich der Kinderoper 'Pollicino' von Hans Werner Henze kennt. Das Orchester probt wöchentlich. Neben den Tuttiproben finden außerdem ebenfalls wöchentlich Stimmsatzproben statt, die von Lehrkräften betreut werden. Das gemeinsame Ziel ist der Aufbau eines leistungsstarken, lebendigen Klangkörpers, der die Jugendlichen und die Zuhörer ganz neu und direkt für die Orchestermusik begeistert und diese Musik in den sozialen Brennpunkt Marzahn- Hellersdorf trägt.

Im Jahr sind etwa 2-3 Konzertprogramme geplant, mit denen wir in Konzertsälen auftreten. Das erste Konzert des Jugendsinfonieorchesters Marzahn-Hellersdorf wurde von DeutschlandRadio Kultur aufgezeichnet und in einer Sendung mit dem Titel „EINSTAND: Nicht nur auf der Strasse herumhängen” porträtiert. Wir wollen außerdem vor Ort in Marzahn und Hellersdorf in die Öffentlichkeit gehen und spielen, um so für die Kultur zu werben und auch weitere Kinder und Jugendliche für die Musik und fürs Mitmachen zu gewinnen. Durch die Einrichtung eines zusätzlichen Vororchesters wird längerfristig versucht, die Arbeit auf ein breites Fundament zu stellen, eine Werkstatt, ein musikalisches Bauhaus zu gründen. Wenn die Orchesterarbeit erfolgreich angelaufen ist, sollen auch übergreifende Projekte (Theater, Tanz, Chor) stattfinden.

Das Orchester will Musik von heute spielen in jedem Sinn, ob es sich um Stücke aus der sinfonischen Tradition handelt oder um zeitgenössische Musik. Wir kennen keine Berührungsängste und sind neugierig auf Musik aller Art und möchten diese Neugierde mit unserem Publikum teilen.

<% @title = 'Dirigent - Jobst Liebrecht' -%>

<%= image_tag 'jobstliebrecht.jpg', :alt => 'Jobst Liebrecht', :title => 'Jobst Liebrecht', :class => 'pic_right' %> Jobst Liebrecht studierte Dirigieren an der Musikhochschule in München und bei Peter Eötvös. Sein spezielles Interesse für neue Musik führte schnell zur Zusammenarbeit mit renommierten Ensembles auf dem Gebiet wie dem Ensemble Modern, Frankfurt, dem Klangforum-Ensemble, Wien, dem Ensemble Köln sowie dem Ensemble United Berlin. Aufnahmen entstanden beim WDR, beim DeutschlandRadio Berlin, beim BR und beim SFB. Er dirigierte u.a. das Rundfunk Sinfonieorchester Berlin, die Duisburger Philharmoniker und das Münchner Kammerorchester sowie in den Opernhäusern in Halle und Giessen. Tourneen im Ausland führten ihn nach Argentinien, Georgien, Südkorea und in die USA.

Zu den Ur- und Erstaufführungen, die er betreut hat, gehören die Opern 'Lunu' von Moritz Eggert, 'Gloria von Jaxtberg' von HK Gruber sowie in Zusammenarbeit mit dem Regisseur Einar Schleef das Musiktheaterspiel 'Der Golem in Bayreuth' von Ulla Berkewicz/Lesch Schmidt am Wiener Burgtheater.

Jobst Liebrecht war mehrere Jahre lang Assistent von Hans Werner Henze und auch immer wieder pädagogisch tätig. Seine Aufnahme von Henzes Märchenoper 'Pollicino', die als CD bei Wergo erschienen ist, wurde mit dem ECHO-Preis 2004 in der Sparte 'Klassik für Kinder' ausgezeichnet.

Als Komponist ist Jobst Liebrecht mit Liedern, Kammermusik sowie Bühnenmusiken an die Öffentlichkeit getreten.

<% message, backtrace = session[:boom] -%> <% @title = 'Fehler in Zeile %d' % [backtrace[/line\s+#(\d+)/,1]] -%>
<%= h message %>
<%= debug backtrace %> <% cache :action_suffix => (action = params[:action]) do -%>

Der Inhalt für die Aktion <%= h action.inspect %> fehlt noch.

<% end -%> <% @title = 'Schulferien Berlin' -%>

Unser Orchester besteht zu einem sehr großen Teil aus Schülern und auch die Musikschule, der die meisten von uns entstammen, hat in den Schulferien geschlossen.
Deshalb finden innerhalb der Berliner Ferienzeiten keine Proben statt.

Zeitraum 2006 2007 2008
Winter 30.01. - 03.02. 05.02. - 10.02. 04.02. - 09.02.
Ostern/Frühjahr 10.04. - 21.04. 02.04. - 13.04. 17.03. - 28.03.
Himmelf./Pfingsten 30.04. / 18.05. 30.04. / 18.05. 02.05.
Sommer 06.07. - 19.08. 12.07. - 25.08. 17.07. - 30.08.
Herbst 02.10. - 14.10. 15.10. - 27.10.
Weihnachten 27.12. - 05.01.07 24.12. - 04.01.08
<% @title = 'Termine' -%>
  • <%= link_to 'Auftritte', :controller => '/auftritte' %>
  • <%= link_to 'Schulferien', :controller => '/content', :action => :schulferien %>
<%= tag 'meta', :'http-equiv' => 'content-language', :content => 'de' %> <%= tag 'meta', :'http-equiv' => 'content-type', :content => 'text/html; charset=UTF-8' %> JSO<%-if @title-%> - <%= h @title %><%- end -%> <%= stylesheet_link_tag '/rcss/main' %> <%#= stylesheet_link_tag 'main' %> <%= javascript_include_tag 'nospam' %> <%#= javascript_include_tag :defaults %>
<%= image_tag 'JSO-Logo.gif', :alt => 'JSO-Logo' %>
jugendsinfonieorchester
<% if valid_user -%>
<% end -%> <% cache :controller => 'menu', :action => 'main_menu' do -%> <%= render_component :controller => 'menu', :action => 'index' %> <% end -%>
<% unless @flash.keys.empty? -%>
<%- for kind, msg in @flash -%>
<%= h msg %>
<%- end -%>
<% end -%> <%= content_tag 'h3', h(@title) if @title %> <%= @content_for_layout %>
powered by Ruby on Rails <%= Rails::Info.properties.value_for 'Rails version' %> [<%= h RAILS_ENV[/^./] %>] <%= image_tag 'css.png', :alt => 'valid CSS', :title => 'valid Cascading Style Sheet', :style => 'display: inline; vertical-align: middle' %> <%= image_tag 'xhtml11.png', :alt => 'valid XHTML 1.1', :title => 'valid eXtensible Hypertext Markup Language 1.1', :style => 'display: inline; vertical-align: middle' %>
<% @title = 'Übersicht' -%>

nächste Probe

<%= render :partial => 'proben/head' %> <%= render :partial => 'proben/day', :object => @next_probe %>

<%= link_to 'weitere Proben...', :controller => 'proben' %>

nächster Auftritt

<%= render :partial => 'auftritte/head' %> <%= render :partial => 'auftritte/day', :object => @next_auftritt %>

<%= link_to 'mehr Auftritte...', :controller => 'auftritte' %>

    <%= category 'Übersicht', home_url %> <%= subcat 'Wer sind wir?', :wer %> <%= subcat 'Dirigent' %> <%= subcat 'Besetzung', url_for(:controller => '/besetzung') %> <%= subcat 'Repertoire' %> <%= category 'Termine' %> <%= subcat 'Auftritte', url_for(:controller => '/auftritte', :action => :plan) %> <%= subcat 'Schulferien' %> <%= category 'Probenplan', url_for(:controller => '/proben', :action => :plan) %> <%= category 'Organisation' %> <%= subcat 'Orchesterrat' %> <%= subcat 'Arbeitsgruppen' %> <%= category 'Chronik' %> <%= subcat 'Konzerte' %> <%= subcat 'Audio' %> <%= subcat 'Presse' %> <%= category 'Links', '#' %> <%= subcat 'Bilderseite', 'http://musikschule.iden04.de' %> <%= subcat 'Musikschule', 'http://www.musikschule-marzahn-hellersdorf.de' %>

  • <%= category 'Kontakt' %>
<% @title = 'Probenplan' %> <%= render :partial => 'head' %> <%= render :partial => 'day', :collection => @days %>

Ort (wenn nicht anders angegeben): Schule am Pappelhof

<%= render_partial 'raum' %> <% day, proben = *day -%> <% for probe in proben -%> <%= colorize day.to_s(:dots) if day %> <% if day and day.wday == 6 %>
Samstag<% end %> <%= colorize probe.time %> <%= colorize(probe.place, 'Ort: ') + '
' unless probe.place.blank? %> <%= colorize probe.program %> <%= link_to 'E', :controller => 'admin/proben', :action => :edit, :id => probe %> <%= h probe.instrumentation %> <% day = nil end -%> Datum Zeit Stücke Besetzung

Probenräume

Wer Raum Adresse
Streicher Schule am Pappelhof
(Raum Nr.)
(Anschrifft Pappelhofschule)
Blechbläser Musikschule Marzahn
(Raum Nr.)
(Anschrifft Musikscule Marzahn)
Holzbläser Schule am Pappelhof
(Raum Nr.)
(Anschrifft Pappelhofschule)
... (Ort)
(Raum Nr.)
(Anschrifft)
pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.rkt000066400000000000000000000261151250413007300260520ustar00rootroot00000000000000#lang racket (require (only-in srfi/13 string-contains)) ; Single-line comment style. ;; Single-line comment style. #| Multi-line comment style ... on one line |# #| Multi-line comment style ... #|### #| nested |#||| |# ... on multiple lines |# #;(s-expression comment (one line)) #; (s-expression comment (multiple lines)) #! shebang comment #!/shebang comment #! shebang \ comment #!/shebang \ comment ;; Uncommented numbers after single-line comments ;; NEL…133 ;; LS
8232 ;; PS
8233 #reader racket (define(a-function x #:keyword [y 0]) (define foo0 'symbol) ; () [define foo1 'symbol] ; [] {define foo2 'symbol} ; {} (define 100-Continue 'symbol) (and (append (car'(1 2 3)))) (regexp-match? #rx"foobar" "foobar") (regexp-match? #px"\"foo\\(bar\\)?\"" "foobar") (regexp-match? #rx#"foobar" "foobar") (regexp-match? #px#"foobar" "foobar") (define #csa 1) #Ci (let ([#%A|||b #true C \|d "foo"]) (displayln #cS #%\ab\ #true\ C\ \\d||)) (for/list ([x (in-list (list 1 2 (list 3 4)))]) (cond [(pair? x) (car x)] [else x]))) ;; Literals (values ;; #b #b1 #b+1 #b-1 #b.1 #b1. #b0.1 #b+0.1 #b-0.1 #b1/10 #b+1/10 #b-1/10 #b1e11 #b+1e11 #b-1e11 #b.1e11 #b1.e11 #b0.1e11 #b+0.1e11 #b-0.1e11 #b1/10e11 #b+1/10e11 #b-1/10e11 #b+i #b1+i #b+1+i #b-1+i #b.1+i #b1.+i #b0.1+i #b+0.1+i #b-0.1+i #b1/10+i #b+1/10+i #b-1/10+i #b1e11+i #b+1e11+i #b-1e11+i #b1.e11+i #b.1e11+i #b0.1e11+i #b+0.1e11+i #b-0.1e11+i #b1/10e11+i #b+1/10e11+i #b-1/10e11+i #b+1i #b1+1i #b+1+1i #b-1+1i #b1.+1i #b.1+1i #b0.1+1i #b+0.1+1i #b-0.1+1i #b1/10+1i #b+1/10+1i #b-1/10+1i #b1e11+1i #b+1e11+1i #b-1e11+1i #b.1e11+1i #b0.1e11+1i #b+0.1e11+1i #b-0.1e11+1i #b1/10e11+1i #b+1/10e11+1i #b-1/10e11+1i #b+1/10e11i #b1+1/10e11i #b+1+1/10e11i #b-1+1/10e11i #b.1+1/10e11i #b0.1+1/10e11i #b+0.1+1/10e11i #b-0.1+1/10e11i #b1/10+1/10e11i #b+1/10+1/10e11i #b-1/10+1/10e11i #b1e11+1/10e11i #b+1e11+1/10e11i #b-1e11+1/10e11i #b.1e11+1/10e11i #b0.1e11+1/10e11i #b+0.1e11+1/10e11i #b-0.1e11+1/10e11i #b1/10e11+1/10e11i #b+1/10e11+1/10e11i #b-1/10e11+1/10e11i ;; #d #d1 #d+1 #d-1 #d.1 #d1. #d1.2 #d+1.2 #d-1.2 #d1/2 #d+1/2 #d-1/2 #d1e3 #d+1e3 #d-1e3 #d.1e3 #d1.e3 #d1.2e3 #d+1.2e3 #d-1.2e3 #d1/2e3 #d+1/2e3 #d-1/2e3 #d+i #d1+i #d+1+i #d-1+i #d.1+i #d1.+i #d1.2+i #d+1.2+i #d-1.2+i #d1/2+i #d+1/2+i #d-1/2+i #d1e3+i #d+1e3+i #d-1e3+i #d1.e3+i #d.1e3+i #d1.2e3+i #d+1.2e3+i #d-1.2e3+i #d1/2e3+i #d+1/2e3+i #d-1/2e3+i #d+1i #d1+1i #d+1+1i #d-1+1i #d1.+1i #d.1+1i #d1.2+1i #d+1.2+1i #d-1.2+1i #d1/2+1i #d+1/2+1i #d-1/2+1i #d1e3+1i #d+1e3+1i #d-1e3+1i #d.1e3+1i #d1.2e3+1i #d+1.2e3+1i #d-1.2e3+1i #d1/2e3+1i #d+1/2e3+1i #d-1/2e3+1i #d+1/2e3i #d1+1/2e3i #d+1+1/2e3i #d-1+1/2e3i #d.1+1/2e3i #d1.2+1/2e3i #d+1.2+1/2e3i #d-1.2+1/2e3i #d1/2+1/2e3i #d+1/2+1/2e3i #d-1/2+1/2e3i #d1e3+1/2e3i #d+1e3+1/2e3i #d-1e3+1/2e3i #d.1e3+1/2e3i #d1.2e3+1/2e3i #d+1.2e3+1/2e3i #d-1.2e3+1/2e3i #d1/2e3+1/2e3i #d+1/2e3+1/2e3i #d-1/2e3+1/2e3i ;; Extflonums +nan.t 1t3 +1t3 -1t3 .1t3 1.t3 1.2t3 +1.2t3 -1.2t3 1/2t3 +1/2t3 -1/2t3 1#t0 1.#t0 .2#t0 1.2#t0 1#/2t0 1/2#t0 1#/2#t0 1#t3 1.#t3 .2#t3 1.2#t3 1#/2t3 1/2#t3 1#/2#t3 ;; No # reader prefix -- same as #d -1.23 1.123 1e3 1e-22 1/2 -1/2 1 -1 ;; #e #e-1.23 #e1.123 #e1e3 #e1e-22 #e1 #e-1 #e1/2 #e-1/2 ;; #d#e #d#e-1.23 #d#e1.123 #d#e1e3 #d#e1e-22 #d#e1 #d#e-1 #d#e1/2 #d#e-1/2 ;; #e#d #e#d-1.23 #e#d1.123 #e#d1e3 #e#d1e-22 #e#d1 #e#d-1 #e#d1/2 #e#d-1/2 ;; #i always float #i-1.23 #i1.123 #i1e3 #i1e-22 #i1/2 #i-1/2 #i1 #i-1 ;; Implicitly inexact numbers +nan.0 1# 1.# .2# 1.2# 1#/2 1/2# 1#/2# 1#e3 1.#e3 .2#e3 1.2#e3 1#/2e3 1/2#e3 1#/2#e3 +nan.0+i 1#+i 1.#+i .2#+i 1.2#+i 1#/2+i 1/2#+i 1#/2#+i 1#e3+i 1.#e3+i .2#e3+i 1.2#e3+i 1#/2e3+i 1/2#e3+i 1#/2#e3+i +nan.0i +1#i +1.#i +.2#i +1.2#i +1#/2i +1/2#i +1#/2#i +1#e3i +1.#e3i +.2#e3i +1.2#e3i +1#/2e3i +1/2#e3i +1#/2#e3i 0+nan.0i 0+1#i 0+1.#i 0+.2#i 0+1.2#i 0+1#/2i 0+1/2#i 0+1#/2#i 0+1#e3i 0+1.#e3i 0+.2#e3i 0+1.2#e3i 0+1#/2e3i 0+1/2#e3i 0+1#/2#e3i 1#/2#e3+nan.0i 1#/2#e3+1#i 1#/2#e3+1.#i 1#/2#e3+.2#i 1#/2#e3+1.2#i 1#/2#e3+1#/2i 1#/2#e3+1/2#i 1#/2#e3+1#/2#i 1#/2#e3+1#e3i 1#/2#e3+1.#e3i 1#/2#e3+.2#e3i 1#/2#e3+1.2#e3i 1#/2#e3+1#/2e3i 1#/2#e3+1/2#e3i 1#/2#e3+1#/2#e3i +nan.0@1 1#@1 1.#@1 .2#@1 1.2#@1 1#/2@1 1/2#@1 1#/2#@1 1#e3@1 1.#e3@1 .2#e3@1 1.2#e3@1 1#/2e3@1 1/2#e3@1 1#/2#e3@1 1@+nan.0 1@1# 1@1.# 1@.2# 1@1.2# 1@1#/2 1@1/2# 1@1#/2# 1@1#e3 1@1.#e3 1@.2#e3 1@1.2#e3 1@1#/2e3 1@1/2#e3 1@1#/2#e3 1#/2#e3@1# 1#/2#e3@1.# 1#/2#e3@.2# 1#/2#e3@1.2# 1#/2#e3@1#/2 1#/2#e3@1/2# 1#/2#e3@1#/2# 1#/2#e3@1#e3 1#/2#e3@1.#e3 1#/2#e3@.2#e3 1#/2#e3@1.2#e3 1#/2#e3@1#/2e3 1#/2#e3@1/2#e3 1#/2#e3@1#/2#e3 ;; #o #o777.777 #o-777.777 #o777e777 #o777e-777 #o3/7 #o-3/7 #o777 #o-777 #e#o777.777 #e#o-777.777 #e#o777e777 #e#o777e-777 #e#o3/7 #e#o-3/7 #e#o777 #e#o-777 #i#o777.777 #i#o-777.777 #i#o777e777 #i#o777e-777 #i#o3/7 #i#o-3/7 #i#o777 #i#o-777 ;; #x #x-f.f #xf.f #xfsf #xfs-f #x7/f #x-7/f #x-f #xf #e#x-f.f #e#xf.f #e#xfsf #e#xfs-f #e#x7/f #e#x-7/f #e#x-f #e#xf #i#x-f.f #i#xf.f #i#xfsf #i#xfs-f #i#x7/f #i#x-7/f #i#x-f #i#xf ;; Not numbers '-1.23x '1.123x '1e3x '1e-22x '1/2x '-1/2x '1x '-1x '/ '1/ '/2 '1//2 '1e3. '1e 'e3 '.i '1.2.3 '1..2 '.1. '@ '1@ '@2 '1@@2 '1@2@3 '1@2i '1+-2i '1i+2 '1i+2i '1+2i+3i '- '--1 '+ '++1 '1/2.3 '1#2 '1#.2 '1.#2 '.#2 '+nan.t+nan.ti '+nan.t@nan.t ;; Booleans #t #T #true #f #F #false ;; Characters, strings, and byte strings #\ #\Null9 #\n9 #\99 #\0009 #\u3BB #\u03BB9 #\U3BB #\U000003BB9 #\λ9 "string\ \a.\b.\t.\n.\v.\f.\r.\e.\".\'.\\.\1.\123.\1234.\x9.\x30.\x303" "\u9.\u1234.\u12345.\U9.\U00100000.\U001000000" #"byte-string\7\xff\t" #< (listof string?) string?) ;; Appends all the strings together, quoting them as appropriate for Python, ;; with commas and spaces between them, wrapping at 80 characters, with an ;; indentation of 8 spaces. (define (wrap-lines lst) (define INDENTATION '" ") (define WIDTH '80) (define (wrap-lines* lst done-lines current-line) (if (null? lst) (string-append (foldr string-append "" done-lines) current-line) (let* ([str (first lst)] [wrapped-str (if (regexp-match-exact? '#px"[[:ascii:]]+" str) (string-append "'" str "',") (string-append "u'" str "',"))] [new-line (string-append current-line " " wrapped-str)]) (if ((string-length new-line) . >= . WIDTH) (wrap-lines* (rest lst) (append done-lines `(,(string-append current-line "\n"))) (string-append INDENTATION wrapped-str)) (wrap-lines* (rest lst) done-lines new-line))))) (wrap-lines* lst '() INDENTATION)) ;; (-> string? boolean?) ;; Returns #t if str represents a syntax identifier in the current namespace, ;; otherwise #f. (define (syntax-identifier? str) (with-handlers ([exn? exn?]) (not (eval (call-with-input-string str read))))) (define RACKET-NAMESPACE (parameterize ([current-namespace (make-base-namespace)]) (namespace-require 'racket) (current-namespace))) (define BOUND-IDENTIFIERS (parameterize ([current-namespace RACKET-NAMESPACE]) (sort (map symbol->string (namespace-mapped-symbols)) string<=?))) (define-values (KEYWORDS BUILTINS) (parameterize ([current-namespace RACKET-NAMESPACE]) (partition syntax-identifier? BOUND-IDENTIFIERS))) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.rpf000066400000000000000000000000671250413007300260370ustar00rootroot00000000000000declare xyz true declare s "some string" i = 2 f = 0.2 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.sh000066400000000000000000000003531250413007300256600ustar00rootroot00000000000000#!/bin/bash printf "%d %s\n" 10 "foo" printf "%d %s\n" $((10#1)) "bar" let "m = 10#${1:1:2}" echo $m m=$((10#${1:4:3} + 10#${1:1:3})) echo $m m=$((10#${1:4:3})) echo $m m=$((10#$1)) echo $m m=$((10#1)) echo $m m=$((10)) echo $m pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.sh-session000066400000000000000000000005001250413007300273330ustar00rootroot00000000000000user@host:~/path$ ls -a . .. a b c user@host:~/path$ diff -u a b --- a 2008-07-26 17:10:07.000000000 -0700 +++ b 2008-07-26 17:10:10.000000000 -0700 @@ -1,3 +1,3 @@ a -b +x c user@host:~/path$ echo \ > a a user@host:~/path$ su root@host:~# sh-3.1$ # on hardy sh$ # on etch (virtualenv-name)user@host:~$ ls -a pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.shell-session000066400000000000000000000036031250413007300300370ustar00rootroot00000000000000[user@linuxbox imx-bootlets-src-10.05.02]$ make CROSS_COMPILE=arm-none-eabi- clean rm -rf *.sb rm -f sd_mmc_bootstream.raw rm -f linux_prep/board/*.o ... Files: rm -f power_prep.o eabi.o Build output: make[1]: Leaving directory `/home/...' [user@linuxbox imx-bootlets-src-10.05.02]$ make CROSS_COMPILE=arm-none-eabi- make[1]: Entering directory `/home/...' ... #@echo "generating U-Boot boot stream image" #elftosb2 -z -c ./uboot_prebuilt.db -o imx23_uboot.sb echo "generating kernel bootstream file sd_mmc_bootstream.raw" generating kernel bootstream file sd_mmc_bootstream.raw #Please use cfimager to burn xxx_linux.sb. The below way will no #work at imx28 platform. > test $ test rm -f sd_mmc_bootstream.raw [user@linuxbox imx-bootlets-src-10.05.02]$ pi@raspberrypi ~ $ sudo sh -c "echo 17 > /sys/class/gpio/export" pi@raspberrypi ~ $ sudo sh -c "echo out > /sys/class/gpio/gpio17/direction" pi@raspberrypi ~ $ sudo sh -c "echo 1 > /sys/class/gpio/gpio17/value" pi@raspberrypi ~ $ sudo sh -c "echo 0 > /sys/class/gpio/gpio17/value" pi@raspberrypi ~ $ [user@linuxbox ~]$ # copy other stuff to the SD card root@imx233-olinuxino-micro:~# lsmod Not tainted [user@linuxbox ~]$ tail -n 2 /mnt/rpi/etc/inittab #Spawn a getty on Raspberry Pi serial line T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100 pi@raspberrypi:~/Adafruit-WebIDE$ mkdir tmp pi@raspberrypi:~/Adafruit-WebIDE$ npm config set tmp tmp pi@raspberrypi:~/Adafruit-WebIDE$ npm install pi@raspberrypi ~/Adafruit-WebIDE $ ifconfig eth0 eth0 Link encap:Ethernet HWaddr b5:33:ff:33:ee:aq inet addr:10.42.0.60 Bcast:10.42.0.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:21867 errors:0 dropped:0 overruns:0 frame:0 TX packets:8684 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:27338495 (26.0 MiB) TX bytes:1268356 (1.2 MiB) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.slim000066400000000000000000000012471250413007300262150ustar00rootroot00000000000000doctype html html head title Slim Examples meta name="keywords" content="template language" meta name="author" content=author javascript: alert('Slim supports embedded javascript!') body h1 Markup examples #content p This example shows you how a basic Slim file looks like. == yield - unless items.empty? table - for item in items do tr td.name = item.name td.price = item.price - else p | No items found. Please add some inventory. Thank you! div id="footer" = render 'footer' | Copyright (C) #{year} #{author} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.sls000066400000000000000000000020201250413007300260400ustar00rootroot00000000000000include: - moosefs {% for mnt in salt['cmd.run']('ls /dev/data/moose*').split() %} /mnt/moose{{ mnt[-1] }}: mount.mounted: - device: {{ mnt }} - fstype: xfs - mkmnt: True file.directory: - user: mfs - group: mfs - require: - user: mfs - group: mfs {% endfor %} /etc/mfshdd.cfg: file.managed: - source: salt://moosefs/mfshdd.cfg - user: root - group: root - mode: 644 - template: jinja - require: - pkg: mfs-chunkserver /etc/mfschunkserver.cfg: file.managed: - source: salt://moosefs/mfschunkserver.cfg - user: root - group: root - mode: 644 - template: jinja - require: - pkg: mfs-chunkserver mfs-chunkserver: pkg: - installed mfschunkserver: service: - running - require: {% for mnt in salt['cmd.run']('ls /dev/data/moose*') %} - mount: /mnt/moose{{ mnt[-1] }} - file: /mnt/moose{{ mnt[-1] }} {% endfor %} - file: /etc/mfschunkserver.cfg - file: /etc/mfshdd.cfg - file: /var/lib/mfs pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.sml000066400000000000000000000056761250413007300260560ustar00rootroot00000000000000structure C = struct val a = 12 fun f x = x + 5 end (*(*(*(*(* This file is all pretty strange Standard ML *)*)*)*) (**)*) (* Robert J. Simmons *) (* Comments (* can be nested *) *) structure S = struct val x = (1, 2, "three") end structure Sv = struct (* These look good *) val x = (1, 2, "three") val z = #2 x (* Although these look bad (not all the numbers are constants), * * they never occur in practice, as they are equivalent to the above. *) val x = {1 = 1, 3 = "three", 2 = 2} val z = # 2 x val || = 12 end signature S = sig end structure S = struct val x = (1, 2, "three") datatype 'a t = T of 'a and u = U of v * v withtype v = {left: int t, right: int t} exception E1 of int and E2 fun 'a id (x: 'a) : 'a = x val 'a id = fn (x : 'a) => x end signature R = sig type t val x : t val f : t * int -> int end structure R : R = struct datatype t = T of int val x : t = T 0 fun f (T x, i : int) : int = x + i fun 'a id (x: 'a) : 'a = x end signature BA_Z = sig val s: int include S R end structure b______ = struct (* What (* A * strange * name *) for ) a ( struct *) val !%&$#+-/:<=>?@\~`^|* = 3 type struct' = int list and 'a sig' = 'a list and ('a, 'b) end' = 'b option * 'a list structure baz = struct structure Bar = struct val foo = !%&$#+-/:<=>?@\~`^|* end end infixr +!+ fun (a +!+ b) = (op +) (a, b) open baz S R val$$$ = fn x => fn y => fn z => fn w => w val (foo, ++, bar, ||) = (4, baz.Bar.foo, !%&$#+-/:<=>?@\~`^|*, Bar.foo) val _ = $$$foo++bar|| val val'ue : ' list = [] val struct3 : (' -> ') = fn x => x val end_struct_' : ('a -> 'a) = fn x => x val x : (''a -> ''a) = fn x => x val x : ('''' -> '''') = fn x => x val x : unit = print "Weird, huh?\n" val w = {x=1,y=2,##= =3,4=3} val {##=, x, 4=a,...} = w val z = #4 w val z = # ##= w fun f x y 0 = 4 | f x y z = 4 + Sv.|| exception Foo of int datatype ('0, 'b, '_, ') f'o'o = Bar | baZ12' | dsfa_fad | #@$ | Bug and (', ''', '''', ''''') bar = Bee of unit | Ben of (', ''', '''', ''''') f'o'o * int | X of ''' list fun q x = raise Foo x and h x = raise Foo (~x) val x = 4 and y = 5 fun q 0 = 4 | q 1 = (case 1 of 1 => 2 | 3 => 4 | x => y) | q y = case y of 1 => 2 | 3 => 4 | x => y val x = ref true fun q 0 = 4 | q 1 = if false then case 1 of 1 => 2 | 3 => 4 | x => y else 19 | q 2 = (while !x handle Match => !x | Fail _ => !x do () ; 2) | q x = (raise Match) handle Domain => 9 | Match => 3 fun p 0 = 12 | p 1 = 8 | p 2 = r false | p x = r true and r true = 19 | r false = 12 val _ = 123 val _ = 0001 val _ = ~123 val _ = ~0001 val _ = 0w12412 val _ = 0w12412 val _ = 0xfA0 val _ = ~0xfA0 val _ = 0wxfA0 val _ = 1.4 val _ = ~1.4 val _ = 1e~2 val _ = 1E~2 val _ = 1e2 val _ = 1E2 val _ = 1.4e~2 val _ = 1.4E~2 val _ = 1.4e2 val _ = 1.4E2 val c = #"\000" val st = "foo \ \ bar" ^ "baz \ \ and \ \ such\n" val () = print st val _ = foo::bar::4::[++] end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.snobol000066400000000000000000000005621250413007300265440ustar00rootroot00000000000000-SOME RANDOM DIRECTIVE WOULD GO HERE * * SNOBOL4 example file for lexer * SOME.THING_OR_OTHER32 = 1 + 1.0 - 1E3 * 1E-3 ** 2.718284590E0 + :F(END)S(IN_LOOP) PATTERN = LEN(3) ("GAR" | "BAR") IN_LOOP THING = INPUT :F(END) THING LEN(3) ("GAR" | "BAR") :S(OK) OUTPUT = THING " : Failure!" :(IN_LOOP) OK OUTPUT = THING ' : "Success"!' :(IN_LOOP) END FOOBAR FOOGAR THiNIg pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.stan000066400000000000000000000041251250413007300262140ustar00rootroot00000000000000/* A file for testing Stan syntax highlighting. It is not a real model and will not compile */ # also a comment // also a comment data { // valid name int abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_abc; // all types should be highlighed int a3; real foo[2]; vector[3] bar; row_vector[3] baz; matrix[3,3] qux; simplex[3] quux; ordered[3] corge; positive_ordered[3] wibble; corr_matrix[3] grault; cov_matrix[3] garply; cholesky_factor_cov[3] waldo; real foo1; real foo2; real foo3; } transformed data { real xyzzy; int thud; row_vector grault2; matrix qux2; // all floating point literals should be recognized // all operators should be recognized // paren should be recognized; xyzzy <- 1234.5687 + .123 - (2.7e3 / 2E-5 * 135e-5); // integer literal thud <- -12309865; // ./ and .* should be recognized as operators grault2 <- grault .* garply ./ garply; // ' and \ should be regognized as operators qux2 <- qux' \ bar; } parameters { real fred; real plugh; } transformed parameters { } model { // ~, <- are operators, // T may be be recognized // normal is a function fred ~ normal(0, 1) T(-0.5, 0.5); real tmp; // C++ reserved real public; // control structures for (i in 1:10) { tmp <- tmp + 0.1; } tmp <- 0.0; while (tmp < 5.0) { tmp <- tmp + 1; } if (tmp > 0.0) { print(tmp); } else { print(tmp); } // operators tmp || tmp; tmp && tmp; tmp == tmp; tmp != tmp; tmp < tmp; tmp <= tmp; tmp > tmp; tmp >= tmp; tmp + tmp; tmp - tmp; tmp * tmp; tmp / tmp; tmp .* tmp; tmp ./ tmp; ! tmp; - tmp; + tmp; tmp '; // lp__ should be highlighted // normal_log as a function lp__ <- lp__ + normal_log(plugh, 0, 1); increment_log_prob(normal_log(plugh, 0, 1)); // print statement and string literal print("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_~@#$%^&*`'-+={}[].,;: "); print("Hello, world!"); print(""); } generated quantities { real bar1; bar1 <- foo + 1; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.tea000066400000000000000000000006071250413007300260210ustar00rootroot00000000000000<% template example() {...} a = 123 b = "test"; c = 4.5 d = call other() f = other2() define g as String h = true i = false j = null %> Example<title> <body> <a href="http://example.com">Test link</a> <% // Second block if(a == 123 and b == "test") { 'yes' } else { 'no' } foreach(i in 1..10) { i & "," } foreach(i in #(1,2,3) reverse { i & ";" } %>�������������������������������������������������������������������������������������������������������������������������pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.todotxt���������������������������0000664�0000000�0000000�00000000562�12504130073�0026755�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������(A) Call Mom @Phone +Family (A) 2014-01-08 Schedule annual checkup +Health (B) Outline chapter 5 +Novel @Computer (C) Add cover sheets @Office +TPSReports Plan backyard herb garden @Home Pick up milk @GroceryStore Research self-publishing services +Novel @Computer x 2014-01-10 Download Todo.txt mobile app @Phone x 2014-01-10 2014-01-07 Download Todo.txt CLI @Computer ����������������������������������������������������������������������������������������������������������������������������������������������pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.ts��������������������������������0000664�0000000�0000000�00000001027�12504130073�0025673�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������class Animal { constructor(public name) { } move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name) { super(name); } move() { alert("Slithering..."); super.move(5); } } class Horse extends Animal { constructor(name) { super(name); } move() { alert("Galloping..."); super.move(45); } } var sam = new Snake("Sammy the Python") var tom: Animal = new Horse("Tommy the Palomino") sam.move() tom.move(34) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.u���������������������������������0000664�0000000�0000000�00000020717�12504130073�0025520�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ // This is a one line comment. /* an inner comment */ /* nested /* comments */ */ /* /* Multi-line. */ */ // Binary blob escape. //"some text \B(3)("\") ouhyeah" == "\"\\\""; "some text \B(3)("\") ouhyeah" == "\"\\\""; 'some text \B(3)('\') ouhyeah' == '\'\\\''; //"\B(4)()"'()"; "\B(4)()"'()"; '\B(4)()'"()'; //blob size limits "hey ! \B(0)() oh !" //blob format is wrong "hey ! \B(2)(aaa) oh !" "hey ! \B(100)(aaa) oh !" //multiple blob in a string "hey ! \B(3)(aaa) hey ! \B(3)(aaa) oh !" // multiple digits blob size "hey ! \B(10)(aaaaaaaaaa) !" "hey ! \B(10)(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) !" "hey ! \B(100)(a) !" // multiple digits blob size "hey ! \B(007)(aaaaaaa) !" "hey ! \B(007)(aa) !" "hey ! \B(007)(aaaaaaaaaaaaaaaaaa) !" // deprecated and restricted keyworks emit Event.new; static int main(); loopn (2) {echo("a");}; foreach (var i : [1,2,3,4]) { echo(i); }; function() {}; var 'if'; var this.'else'; var '%x'; var '1 2 3'; var this.'[]'; // angles pi == 180deg; pi == 200grad; // Dictionary [ => ]; // The empty dictionary // duration 1d == 24h; 0.5d == 12h; 1h == 60min; 1min == 60s; 1s == 1000ms; 1s == 1; 1s 2s 3s == 6; 1s 1ms == 1.001; 1ms 1s == 1.001; 1 == 1; 1 == 1.0; 1.2 == 1.2000; 1.234e6 == 1234000; 1e+11 == 1E+11; 1e10 == 10000000000; 1e30 == 1e10 * 1e10 * 1e10; 0.000001; 0.0000001; 0.00000000001; 1e+3; 1E-5; 1.; // [00004701:error] !!! syntax error: unexpected ; 0x2a == 42; 0x2A == 42; 0xabcdef == 11259375; 0xABCDEF == 11259375; 0xFFFFFFFF == 4294967295; //123foo; //[00005658:error] !!! syntax error: invalid token: '123foo' //12.3foo; //[00018827:error] !!! syntax error: invalid token: '12.3foo' 0xabcdef; //[00060432] 11259375 //0xabcdefg; //[00061848:error] !!! syntax error: invalid token: '0xabcdefg' []; // The empty list [1, 2, 3]; // Special characters. "\"" == "\""; "\\" == "\\"; // ASCII characters. "\a" == "\007"; "\a" == "\x07"; "\b" == "\010"; "\b" == "\x08"; "\f" == "\014"; "\f" == "\x0c"; "\n" == "\012"; "\n" == "\x0a"; "\r" == "\015"; "\r" == "\x0d"; "\t" == "\011"; "\t" == "\x09"; "\v" == "\013"; "\v" == "\x0b"; // Octal escapes. "\0" == "\00"; "\0" == "\000"; "\0000" == "\0""0"; "\062\063" == "23"; // Hexadecimal escapes. "\x00" == "\0"; "\x32\x33" == "23"; "foo" "bar" "baz" == "foobarbaz"; // Tuples (); [00000000] () (1,); [00000000] (1,) (1, 2); [00000000] (1, 2) (1, 2, 3, 4,); [00000000] (1, 2, 3, 4) function Global.verboseId(var x) { echo(x) | x }|; class verboseId(Global).math : verboseId(Math) { }; { for (3) { sleep(1s); echo("ping"); }, sleep(0.5s); for (3) { sleep(1s); echo("pong"); }, }; 1 + 1 == 2; 1 - 2 == -1; 2 * 3 == 6; 10 / 2 == 5; 2 ** 10 == 1024; -(1 + 2) == -3; 1 + 2 * 3 == 7; (1 + 2) * 3 == 9; -2 ** 2 == -4; - - - - 1 == 1; a = b a += b a -= b a *= b a /= b a %= b a ^= b var value = 0|; var valueAlias = value|; value += 10; valueAlias; var myList = []|; var myList.specialFeature = 42|; myList += [1, 2, 3]; myList.specialFeature; var myOtherList = myList + [4, 5]; myOtherList.specialFeature; var something = []|; var somethingElse = something|; something += [1, 2]; somethingElse += [3, 4]; something; class Counter { var count = 0; function init (n) { var this.count = n }; // Display the value, and the identity. function asString() { "%s @ %s" % [count, uid ] }; function '+'(var n) { new(count + n) }; function '-'(var n) { new(count - n) }; }|; class ImmutableCounter : Counter { function '+='(var n) { this + n }; function '-='(var n) { this - n }; }|; var ic1 = ImmutableCounter.new(0); var ic2 = ic1; ic1 += 1; ic1; ic2; a << b a >> b a ^ b 4 << 2 == 16; 4 >> 2 == 1; !a a && b a || b true && true; true || false; !true == false; true || (1 / 0); (false && (1 / 0)) == false; a == b a != b a === b a !== b a ~= b a =~= b a < b a <= b a > b a >= b assert{ ! (0 < 0); 0 <= 0; 0 == 0; 0 !== 0; }; a in b a not in b a[args] a[args] = v 1 in [0, 1, 2]; 3 not in [0, 1, 2]; "one" in ["zero" => 0, "one" => 1, "two" => 2]; "three" not in ["zero" => 0, "one" => 1, "two" => 2]; a.b a.b(args) a->b a->b = v a.&b var obj = Object.new|; function obj.f() { 24 }|; var f = function(a, b) { echo(b + a); }| f(1, 0); function g3() { return; // Stop execution at this point and return void echo(0); // This is not executed }| Object.setProperty, to define/set a property. Object.getProperty, to get a property. Object.removeProperty, to delete a property. Object.hasProperty, to test for the existence of a property. Object.properties, to get all the properties of a slot. enum Suit { hearts, diamonds, clubs, spades, // Last comma is optional }; for (var suit in Suit) echo("%s the ace of %s." % [find_ace(suit), suit]); switch ( ("foo", [1, 2]) ) { // The pattern does not match the values of the list. case ("foo", [2, 1]): echo("fail"); // The pattern does not match the tuple. case ["foo", [1, 2]]: echo("fail"); // The pattern matches and binds the variable "l" // but the condition is not verified. case ("foo", var l) if l.size == 0: echo("fail"); // The pattern matches. case ("foo", [var a, var b]): echo("foo(%s, %s)" % [a, b]); }; //[00000000] *** foo(1, 2) { ["b" => var b, "a" => var a] = ["a" => 1, "b" => 2, "c" => 3]; echo("a = %d, b = %d" % [a, b]); }; //[00000000] *** a = 1, b = 2 switch (["speed" => 2, "time" => 6s]) { case ["speed" => var s] if s > 3: echo("Too fast"); case ["speed" => var s, "time" => var t] if s * t > 10: echo("Too far"); }; //[00000000] *** Too far try { throw ("message", 0) } catch (var e if e.isA(Exception)) { echo(e.message) } catch ((var msg, var value) if value.isA(Float)) { echo("%s: %d" % [msg, value]) }; //[00000000] *** message: 0 { var e = Event.new; at (e?(var msg, var value) if value % 2 == 0) echo("%s: %d" % [msg, value]); // Does not trigger the "at" because the guard is not verified. e!("message", 1); // Trigger the "at". e!("message", 2); }; //[00000000] *** message: 2 for (var i = 0; i < 8; i++) { if (i % 2 != 0) continue; echo(i); }; do (1024) { assert(this == 1024); assert(sqrt == 32); setSlot("y", 23); }.y; { var n = 10|; var res = []|; loop;{ n--; res << n; if (n == 0) break }; res } { var n = 10|; var res = []|; loop|{ n--; res << n; if (n == 0) break }; res } var j = 3| while (0 < j) { echo(j); j--; }; { var i = 4| while| (true) { i -= 1; echo ("in: " + i); if (i == 1) break else if (i == 2) continue; echo ("out: " + i); }; }; function test(e) { try { throw e; } catch (0) { echo("zero") } catch ([var x, var y]) { echo(x + y) } } | {}; try { echo("try") } catch { echo("catch")} else { echo("else")}; try { echo("inside"); } finally { echo("finally"); }; //[00000001] *** inside //[00000002] *** finally at (e?(var start) ~ 1s) echo("in : %s" % (time - start).round) onleave echo("out: %s" % (time - start).round); // This emission is too short to trigger the at. e!(time); // This one is long enough. // The body triggers 1s after the emission started. e!(time) ~ 2s; //[00001000] *** in : 1 //[00002000] *** out: 2 timeout (2.1s) every (1s) echo("Are you still there?"); //[00000000] *** Are you still there? //[00001000] *** Are you still there? //[00002000] *** Are you still there? every| (1s) { echo("aba"); }; for, (var i = 3; 0 < i; i -= 1) { echo (i); }; for& (var i: [0, 1, 2]) { echo (i * i); }; loop,{ }; waituntil (e?(1, var b)); whenever (e?("arg", var arg) if arg % 2) echo("e (%s) on" % arg) else echo("e off"); while, (i) { var j = i -= 1; }| var y = 0; { sleep(0.5s); y = 100 smooth:3s, }, �������������������������������������������������pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.weechatlog������������������������0000664�0000000�0000000�00000001364�12504130073�0027373�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������**** Beginning of log 2007 Sep 01 00:23:55 **** 2007 Sep 01 00:23:55 --> weechat_user (weechat@localhost.) ist in den Channel &bitlbee gekommen 2007 Sep 01 00:23:55 -=- Modus &bitlbee [+t] durch localhost. 2007 Sep 01 00:23:55 -@- Nicks &bitlbee: [@root @weechat_user] 2007 Sep 01 00:23:55 -=- Channel &bitlbee: 2 Nicks (2 Operatoren, 0 Halb-Operator, 0 Gevoiceter, 0 normal) 2007 Sep 01 00:23:55 -=- Das Topic von &bitlbee lautet: "Welcome to the control channel. Type help for help information." 2007 Sep 01 00:23:55 <root> Welcome to the BitlBee gateway! 2007 Sep 01 00:23:55 <root> 2007 Sep 01 00:23:55 <root> If you've never used BitlBee before, please do read the help information using the help command. Lots of FAQ's are answered there.����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.xhtml�����������������������������0000664�0000000�0000000�00000027216�12504130073�0026411�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<html> <head> <script lang="javascript" type="text/javascript"> // <!-- function toggleVisible(element) { if (element.style.display == 'block') { element.style.display = 'none'; } else { element.style.display = 'block'; } return false; } // --> </script> <title>Error

Error

Path: #{path}
#{CGI.escapeHTML(error.to_s)}
Reload this page. Go to the referer or the home page.
In file '#{error.hot_file}' #{error.hot_file =~ /\.xhtml$/ ? '(line numbering is aproximate due to template transformation)' : nil}:

#{line}
#{line}

Stack Trace

Request

Response

Session



Powered by Nitro version #{Nitro::Version}

Home > System > #{"%plural%".humanize} > Edit #{"%name%".humanize}

Show editable #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list", :all => true} Show all #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list"}
#{form_for(@%name%)}

#{"%plural%".humanize}

New #{"%name%".humanize}

Search #{"%plural%".humanize}:  
#{obj.to_s} #{obj.update_time.stamp(:db)} edit del

Home > System > #{"%plural%".humanize}

New #{"%name%".humanize}

Search #{"%plural%".humanize}:  

#(obj.to_s) #{obj.update_time.stamp(:db)} edit del
#{@pager.navigation}

Home > System > #{"%plural%".humanize} > New #{"%name%".humanize}

Show editable #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list", :all => true, :enctype => "multipart/form-data"} Show all #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list", :enctype => "multipart/form-data"}

Home > System > #{"%plural%".humanize} > Search for '#@query'

Search #{"%plural%".humanize}:  

Search method is not implemented for this object

#(obj.to_s) #{obj.update_time.stamp(:db)} edit del
#{@pager.navigation}

View %name%

List of %plural%

#{@obj.to_yaml}
Access denied

Home > System

Og managed classes

Class Count Cleanup Properties
#{c.name} #{c.count} delete destroy #{c.properties.values.join(', ')}

System configuration

Name Value Type Description
#{s.owner}.#{s.name} #{s.value.inspect} #{s.type} #{s.options[:doc]}
Test hello Hello #{username} how do you feel? Here is your Token: #{token}

Questions with Tags: #{@tags.join(" ")}

0 ?> Too many results for that Tag, please reduce the number by using one of the following Tags: #{cloud_of(@qtags)}

#{q.question}

#{excerpt}

#{q.answers.size.to_i} answers

#{@qpager.navigation}

no question with this/these tag(s) found

Ask a question here.

0 ?>

Tips with Tags: #{@tags.join(" ")}

Too many results for that Tag, please reduce the number by using one of the following Tags: #{cloud_of(@ttags)}

#{t.title}

#{excerpt}

#{@tpager.navigation}
0 ?>

Tutorials with Tags: #{@tags.join(" ")}

Too many results for that Tag, please reduce the number by using one of the following Tags: #{cloud_of(@tuttags)}

#{t.title}

#{excerpt}

#{@tpager.navigation}
pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.xtend000066400000000000000000000013271250413007300263720ustar00rootroot00000000000000package beer import static extension beer.BottleSupport.* import org.junit.Test class BottleSong { @Test def void singIt() { println(singTheSong(99)) } def singTheSong(int all) ''' «FOR i : all .. 1» «i.Bottles» of beer on the wall, «i.bottles» of beer. Take one down and pass it around, «(i - 1).bottles» of beer on the wall. «ENDFOR» No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, «all.bottles» of beer on the wall. ''' def private java.lang.String bottles(int i) { switch i { case 0 : 'no more bottles' case 1 : 'one bottle' default : '''«i» bottles''' }.toString } def String Bottles(int i) { bottles(i).toFirstUpper } }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.yaml000066400000000000000000000116741250413007300262200ustar00rootroot00000000000000 # # Examples from the Preview section of the YAML specification # (http://yaml.org/spec/1.2/#Preview) # # Sequence of scalars --- - Mark McGwire - Sammy Sosa - Ken Griffey # Mapping scalars to scalars --- hr: 65 # Home runs avg: 0.278 # Batting average rbi: 147 # Runs Batted In # Mapping scalars to sequences --- american: - Boston Red Sox - Detroit Tigers - New York Yankees national: - New York Mets - Chicago Cubs - Atlanta Braves # Sequence of mappings --- - name: Mark McGwire hr: 65 avg: 0.278 - name: Sammy Sosa hr: 63 avg: 0.288 # Sequence of sequences --- - [name , hr, avg ] - [Mark McGwire, 65, 0.278] - [Sammy Sosa , 63, 0.288] # Mapping of mappings --- Mark McGwire: {hr: 65, avg: 0.278} Sammy Sosa: { hr: 63, avg: 0.288 } # Two documents in a stream --- # Ranking of 1998 home runs - Mark McGwire - Sammy Sosa - Ken Griffey --- # Team ranking - Chicago Cubs - St Louis Cardinals # Documents with the end indicator --- time: 20:03:20 player: Sammy Sosa action: strike (miss) ... --- time: 20:03:47 player: Sammy Sosa action: grand slam ... # Comments --- hr: # 1998 hr ranking - Mark McGwire - Sammy Sosa rbi: # 1998 rbi ranking - Sammy Sosa - Ken Griffey # Anchors and aliases --- hr: - Mark McGwire # Following node labeled SS - &SS Sammy Sosa rbi: - *SS # Subsequent occurrence - Ken Griffey # Mapping between sequences --- ? - Detroit Tigers - Chicago cubs : - 2001-07-23 ? [ New York Yankees, Atlanta Braves ] : [ 2001-07-02, 2001-08-12, 2001-08-14 ] # Inline nested mapping --- # products purchased - item : Super Hoop quantity: 1 - item : Basketball quantity: 4 - item : Big Shoes quantity: 1 # Literal scalars --- | # ASCII art \//||\/|| // || ||__ # Folded scalars --- > Mark McGwire's year was crippled by a knee injury. # Preserved indented block in a folded scalar --- > Sammy Sosa completed another fine season with great stats. 63 Home Runs 0.288 Batting Average What a year! # Indentation determines scope --- name: Mark McGwire accomplishment: > Mark set a major league home run record in 1998. stats: | 65 Home Runs 0.278 Batting Average # Quoted scalars --- unicode: "Sosa did fine.\u263A" control: "\b1998\t1999\t2000\n" hex esc: "\x0d\x0a is \r\n" single: '"Howdy!" he cried.' quoted: ' # not a ''comment''.' tie-fighter: '|\-*-/|' # Multi-line flow scalars --- plain: This unquoted scalar spans many lines. quoted: "So does this quoted scalar.\n" # Integers --- canonical: 12345 decimal: +12_345 sexagesimal: 3:25:45 octal: 014 hexadecimal: 0xC # Floating point --- canonical: 1.23015e+3 exponential: 12.3015e+02 sexagesimal: 20:30.15 fixed: 1_230.15 negative infinity: -.inf not a number: .NaN # Miscellaneous --- null: ~ true: boolean false: boolean string: '12345' # Timestamps --- canonical: 2001-12-15T02:59:43.1Z iso8601: 2001-12-14t21:59:43.10-05:00 spaced: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 # Various explicit tags --- not-date: !!str 2002-04-28 picture: !!binary | R0lGODlhDAAMAIQAAP//9/X 17unp5WZmZgAAAOfn515eXv Pz7Y6OjuDg4J+fn5OTk6enp 56enmleECcgggoBADs= application specific tag: !something | The semantics of the tag above may be different for different documents. # Global tags %TAG ! tag:clarkevans.com,2002: --- !shape # Use the ! handle for presenting # tag:clarkevans.com,2002:circle - !circle center: &ORIGIN {x: 73, y: 129} radius: 7 - !line start: *ORIGIN finish: { x: 89, y: 102 } - !label start: *ORIGIN color: 0xFFEEBB text: Pretty vector drawing. # Unordered sets --- !!set # sets are represented as a # mapping where each key is # associated with the empty string ? Mark McGwire ? Sammy Sosa ? Ken Griff # Ordered mappings --- !!omap # ordered maps are represented as # a sequence of mappings, with # each mapping having one key - Mark McGwire: 65 - Sammy Sosa: 63 - Ken Griffy: 58 # Full length example --- ! invoice: 34843 date : 2001-01-23 bill-to: &id001 given : Chris family : Dumars address: lines: | 458 Walkman Dr. Suite #292 city : Royal Oak state : MI postal : 48046 ship-to: *id001 product: - sku : BL394D quantity : 4 description : Basketball price : 450.00 - sku : BL4438H quantity : 1 description : Super Hoop price : 2392.00 tax : 251.42 total: 4443.52 comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. # Another full-length example --- Time: 2001-11-23 15:01:42 -5 User: ed Warning: This is an error message for the log file --- Time: 2001-11-23 15:02:31 -5 User: ed Warning: A slightly different error message. --- Date: 2001-11-23 15:03:17 -5 User: ed Fatal: Unknown variable "bar" Stack: - file: TopClass.py line: 23 code: | x = MoreObject("345\n") - file: MoreClass.py line: 58 code: |- foo = bar pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example2.aspx000066400000000000000000000011741250413007300263050ustar00rootroot00000000000000<%@ Register TagPrefix="Acme" TagName="Message" Src="userctrl2_vb.ascx" %>

A Simple User Control w/ Properties

pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example2.msc000066400000000000000000000031721250413007300261140ustar00rootroot00000000000000#!/usr/bin/mscgen -Tpng # # testinput2.msc : Sample msc input file with URLs # # This file is PUBLIC DOMAIN and may be freely reproduced, distributed, # transmitted, used, modified, built upon, or otherwise exploited by # anyone for any purpose, commercial or non-commercial, and in any way, # including by methods that have not yet been invented or conceived. # # This file is provided "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER # EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # # Note: This is from mscgen-0.20 msc { A,B; --- [label="Start", ID="1"]; A->B [label="signal"]; A<-B [label="signal"]; A=>B [label="method"]; A<=B [label="method"]; A>>B [label="return"]; A<>B [label="call-back"]; A<<=B [label="call-back", URL="www.google.com"]; A x- B [label="loss"]; A -x B [label="loss"]; --- [label="Left arcs", ID="2", IDURL="www.google.co.uk"]; A->A [label="signal"]; A<-A [label="signal"]; A=>A [label="method"]; A<=A [label="method"]; A>>A [label="return"]; A<>A [label="call-back"]; A<<=A [label="call-back", URL="www.google.com", ID="3"]; A x- A [label="loss"]; A -x A [label="loss"]; --- [label="Right arcs"]; B->B [label="signal"]; B<-B [label="signal"]; B=>B [label="method"]; B<=B [label="method"]; B>>B [label="return"]; B<>B [label="call-back", ID="4"]; B<<=B [label="call-back", URL="www.google.com"]; B x- B [label="loss"]; B -x B [label="loss"]; --- [label="End of arcs", URL="www.google.com"]; ... [label="Some time passes", URL="www.google.com"]; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/exampleScript.cfc000066400000000000000000000172541250413007300271760ustar00rootroot00000000000000 /** ******************************************************************************** ContentBox - A Modular Content Platform Copyright 2012 by Luis Majano and Ortus Solutions, Corp www.gocontentbox.org | www.luismajano.com | www.ortussolutions.com ******************************************************************************** Apache License, Version 2.0 Copyright Since [2012] [Luis Majano and Ortus Solutions,Corp] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************** * A generic content service for content objects */ component extends="coldbox.system.orm.hibernate.VirtualEntityService" singleton{ // DI property name="settingService" inject="id:settingService@cb"; property name="cacheBox" inject="cachebox"; property name="log" inject="logbox:logger:{this}"; property name="customFieldService" inject="customFieldService@cb"; property name="categoryService" inject="categoryService@cb"; property name="commentService" inject="commentService@cb"; property name="contentVersionService" inject="contentVersionService@cb"; property name="authorService" inject="authorService@cb"; property name="populator" inject="wirebox:populator"; property name="systemUtil" inject="SystemUtil@cb"; /* * Constructor * @entityName.hint The content entity name to bind this service to. */ ContentService function init(entityName="cbContent"){ // init it super.init(entityName=arguments.entityName, useQueryCaching=true); // Test scope coloring in pygments this.colorTestVar = "Just for testing pygments!"; cookie.colorTestVar = ""; client.colorTestVar = "" session.colorTestVar = ""; application.colorTestVar = ""; return this; } /** * Clear all content caches * @async.hint Run it asynchronously or not, defaults to false */ function clearAllCaches(boolean async=false){ var settings = settingService.getAllSettings(asStruct=true); // Get appropriate cache provider var cache = cacheBox.getCache( settings.cb_content_cacheName ); cache.clearByKeySnippet(keySnippet="cb-content",async=arguments.async); return this; } /** * Clear all page wrapper caches * @async.hint Run it asynchronously or not, defaults to false */ function clearAllPageWrapperCaches(boolean async=false){ var settings = settingService.getAllSettings(asStruct=true); // Get appropriate cache provider var cache = cacheBox.getCache( settings.cb_content_cacheName ); cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper",async=arguments.async); return this; } /** * Clear all page wrapper caches * @slug.hint The slug partial to clean on * @async.hint Run it asynchronously or not, defaults to false */ function clearPageWrapperCaches(required any slug, boolean async=false){ var settings = settingService.getAllSettings(asStruct=true); // Get appropriate cache provider var cache = cacheBox.getCache( settings.cb_content_cacheName ); cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper-#arguments.slug#",async=arguments.async); return this; } /** * Clear a page wrapper cache * @slug.hint The slug to clean * @async.hint Run it asynchronously or not, defaults to false */ function clearPageWrapper(required any slug, boolean async=false){ var settings = settingService.getAllSettings(asStruct=true); // Get appropriate cache provider var cache = cacheBox.getCache( settings.cb_content_cacheName ); cache.clear("cb-content-pagewrapper-#arguments.slug#/"); return this; } /** * Searches published content with cool paramters, remember published content only * @searchTerm.hint The search term to search * @max.hint The maximum number of records to paginate * @offset.hint The offset in the pagination * @asQuery.hint Return as query or array of objects, defaults to array of objects * @sortOrder.hint The sorting of the search results, defaults to publishedDate DESC * @isPublished.hint Search for published, non-published or both content objects [true, false, 'all'] * @searchActiveContent.hint Search only content titles or both title and active content. Defaults to both. */ function searchContent( any searchTerm="", numeric max=0, numeric offset=0, boolean asQuery=false, any sortOrder="publishedDate DESC", any isPublished=true, boolean searchActiveContent=true){ var results = {}; var c = newCriteria(); // only published content if( isBoolean( arguments.isPublished ) ){ // Published bit c.isEq( "isPublished", javaCast( "Boolean", arguments.isPublished ) ); // Published eq true evaluate other params if( arguments.isPublished ){ c.isLt("publishedDate", now() ) .$or( c.restrictions.isNull("expireDate"), c.restrictions.isGT("expireDate", now() ) ) .isEq("passwordProtection",""); } } // Search Criteria if( len( arguments.searchTerm ) ){ // like disjunctions c.createAlias("activeContent","ac"); // Do we search title and active content or just title? if( arguments.searchActiveContent ){ c.$or( c.restrictions.like("title","%#arguments.searchTerm#%"), c.restrictions.like("ac.content", "%#arguments.searchTerm#%") ); } else{ c.like( "title", "%#arguments.searchTerm#%" ); } } // run criteria query and projections count results.count = c.count( "contentID" ); results.content = c.resultTransformer( c.DISTINCT_ROOT_ENTITY ) .list(offset=arguments.offset, max=arguments.max, sortOrder=arguments.sortOrder, asQuery=arguments.asQuery); return results; } /********************************************* PRIVATE *********************************************/ /** * Update the content hits * @contentID.hint The content id to update */ private function syncUpdateHits(required contentID){ var q = new Query(sql="UPDATE cb_content SET hits = hits + 1 WHERE contentID = #arguments.contentID#").execute(); return this; } private function closureTest(){ methodCall( param1, function( arg1, required arg2 ){ var settings = settingService.getAllSettings(asStruct=true); // Get appropriate cache provider var cache = cacheBox.getCache( settings.cb_content_cacheName ); cache.clear("cb-content-pagewrapper-#arguments.slug#/"); return this; }, param1 ); } private function StructliteralTest(){ return { foo = bar, brad = 'Wood', func = function( arg1, required arg2 ){ var settings = settingService.getAllSettings(asStruct=true); // Get appropriate cache provider var cache = cacheBox.getCache( settings.cb_content_cacheName ); cache.clear("cb-content-pagewrapper-#arguments.slug#/"); return this; }, array = [ 1, 2, 3, 4, 5, 'test', 'testing', 'testerton', { foo = true, brad = false, wood = null } ], last = "final" }; } private function arrayliteralTest(){ return [ 1, 2, 3, 4, 5, 'test', 'testing', 'testerton', { foo = true, brad = false, wood = null }, 'testy-von-testavich' ]; } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/exampleTag.cfc000066400000000000000000000007321250413007300264360ustar00rootroot00000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example_elixir.ex000066400000000000000000000070351250413007300272420ustar00rootroot00000000000000# Numbers 0b0101011 1234 ; 0x1A ; 0xbeef ; 0763 3.14 ; 5.0e21 ; 0.5e-12 100_000_000 # Characters ?a ; ?1 ; ?\n ; ?\s ; ?\c ; ? ; ?, ?\x{12} ; ?\x{abcd} ?\x34 ; ?\xf ?\123 ; ?\12 ; ?\7 # Atoms :this ; :that :'complex atom' :"with' \"\" 'quotes" :" multi line ' \s \123 \xff atom" :... ; :<<>> ; :%{} ; :% ; :{} :++; :--; :*; :~~~ # Strings "Hello world" "Interspersed \x{ff} codes \7 \8 \65 \016 and \t\s\z\+ \\ escapes" "Quotes ' inside \" \123 the \"\" \xF string \\\" end" "Multiline string" # Char lists 'this is a list' 'escapes \' \t \\\'' 'Multiline char list ' # Binaries <<1, 2, 3>> <<"hello"::binary, c :: utf8, x::[4, unit(2)]>> = "hello™1" # Sigils ~r/this + i\s "a" regex/ ~R'this + i\s "a" regex too' ~w(hello #{ ["has" <> "123", '\c\d', "\123 interpol" | []] } world)s ~W(hello #{no "123" \c\d \123 interpol} world)s ~S"No escapes \s\t\n and no #{interpolation}" :"atoms work #{"to" <> "o"}" # Operators x = 1 + 2.0 * 3 y = true and false; z = false xor true ... = 144 ... == !x && y || z "hello" |> String.upcase |> String.downcase() {^z, a} = {true, x} # Lists, tuples, maps, keywords [1, :a, 'hello'] ++ [2, 3] [:head | [?t, ?a, ?i, ?l]] {:one, 2.0, "three"} [...: "this", <<>>: "is", %{}: "a keyword", %: "list", {}: "too"] ["this is an atom too": 1, "so is this": 2] [option: "value", key: :word] [++: "operator", ~~~: :&&&] map = %{shortcut: "syntax"} %{map | "update" => "me"} %{ 12 => 13, :weird => ['thing'] } # Comprehensions for x <- 1..10, x < 5, do: {x, x} pixels = "12345678" for << <> <- pixels >> do [r, {g, %{"b" => a}}] end # String interpolation "String #{inspect "interpolation"} is quite #{1+4+7} difficult" # Modules defmodule Long.Module.Name do @moduledoc "Simple module docstring" @doc """ Multiline docstring "with quotes" and #{ %{"interpolation" => "in" <> "action"} } """ defstruct [:a, :name, :height] @doc ~S''' No #{interpolation} of any kind. \000 \x{ff} \n #{\x{ff}} ''' def func(a, b \\ []), do: :ok @doc false def __before_compile__(_) do :ok end end # Structs defmodule Second.Module do s = %Long.Module.Name{name: "Silly"} %{s | height: {192, :cm}} end # Types, pseudo-vars, attributes defmodule M do @custom_attr :some_constant @before_compile Long.Module.Name @typedoc "This is a type" @type typ :: integer @typedoc """ Another type """ @opaque typtyp :: 1..10 @spec func(typ, typtyp) :: :ok | :fail def func(a, b) do a || b || :ok || :fail Path.expand("..", __DIR__) IO.inspect __ENV__ __NOTAPSEUDOVAR__ = 11 __MODULE__.func(b, a) end defmacro m() do __CALLER__ end end # Functions anon = fn x, y, z -> fn(a, b, c) -> &(x + y - z * a / &1 + b + div(&2, c)) end end &Set.put(&1, &2) ; & Set.put(&1, &2) ; &( Set.put(&1, &1) ) # Function calls anon.(1, 2, 3); self; hd([1,2,3]) Kernel.spawn(fn -> :ok end) IO.ANSI.black # Control flow if :this do :that else :otherwise end pid = self receive do {:EXIT, _} -> :done {^pid, :_} -> nil after 100 -> :no_luck end case __ENV__.line do x when is_integer(x) -> x x when x in 1..12 -> -x end cond do false -> "too bad" 4 > 5 -> "oops" true -> nil end # Lexical scope modifiers import Kernel, except: [spawn: 1, +: 2, /: 2, Unless: 2] alias Long.Module.Name, as: Namen use Bitwise 4 &&& 5 2 <<< 3 # Protocols defprotocol Useless do def func1(this) def func2(that) end defimpl Useless, for: Atom do end # Exceptions defmodule NotAnError do defexception [:message] end raise NotAnError, message: "This is not an error" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example_file.fy000066400000000000000000000050251250413007300266640ustar00rootroot00000000000000class Person { def initialize: @name age: @age { """ This is a docstring for the Person constructor method. Docstrings usually are multi-line, like this one. """ } def to_s { # return is optional in this case, but we use it nontheless return "Person with name: #{@name inspect} and age: #{@age}" } } class PersonWithCity : Person { def initialize: @name age: @age city: @city { } def to_s { super to_s ++ " living in: #{@city inspect}" } } p1 = Person new: "Johnny Jackson" age: 42 p1 println # prints: Person with name: "Johnny Jackson" and age: 42 p2 = PersonWithCity new: "John Appleseed" age: 55 city: "New York" p2 println # prints: Person with name: "John Appleseed" age: 55 living in: "New York" array = [1,2,3, "foo", 'bar] hash = <['foo => "bar", 'bar => 42]> tuple = (1,2,"hello","world") block = |x, y| { x + y println } block call: [4,2] 0b010101 & 0b00101 to_s: 2 . println 0xFF & 0xAB to_s: 16 . println 0o77 > 0o76 println 123.123 + 0.222 println x = 0 try { 10 / x println } catch ZeroDivisionError => e { x = 3 retry } finally { "Finally, done!" println } def a_method: arg1 with_default_arg: arg2 (42) { arg1 * arg2 println } a_method: 42 a_method: 42 with_default_arg: 85 class ClassWithClassMethod { def self class_method1 { 'works } def ClassWithClassMethod class_method2 { 'this_as_well } } ClassWithClassMethod class_method1 println ClassWithClassMethod class_method2 println def another_method: block { 1 upto: 10 . map: block } # local returns another_method: |x| { return_local x * 2 } . inspect println # pattern matching: class PatternMatching { def match_it: obj { match obj { case String -> "It's a String!" println case Fixnum -> "It's a Number!" println case _ -> "Aything else!" println } } def match_with_extract: str { match str { # m holds the MatchData object, m1 & m2 the first and second matches case /^(.*) : (.*)$/ -> |m, m1, m2| "First match: #{m1}" println "Second match: #{m2}" println } } } pm = PatternMatching new pm match_it: "foo" pm match_it: 42 pm match_it: 'foo pm match_with_extract: "Hello : World!" # calling ruby methods: [3, 2, 1] reverse() each() |a| { puts(a) } "Hello" sub("ll", "y") println [3, 2, 1] map() |a| { a * 2 } inject(0) |s i| { s + i } println # test symbol highlighting ['foo] ['foo?!] {'foo} {'foo!?} {'foo:bar?!=&/:} ('foo) # future sends 42 @ to_s class println 42 @ to_s: 16 . value println # async sends 42 @@ println 42 @@ upto: 100 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/firefox.mak000066400000000000000000000277351250413007300260420ustar00rootroot00000000000000# # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** DEPTH = . topsrcdir = @top_srcdir@ srcdir = @srcdir@ VPATH = @srcdir@ include $(DEPTH)/config/autoconf.mk include $(topsrcdir)/build/unix/modules.mk ifeq ($(BUILD_MODULES),all) # # And now for something completely different... # Divide the default build into tiers. # Tiers must be defined on module boundaries # SUPPRESS_DEFAULT_RULES = 1 default alldep all:: $(SUBMAKEFILES) $(RM) -rf $(DIST)/sdk $(RM) -rf $(DIST)/include $(MAKE) -C config export $(MAKE) nspr $(MAKE) ldap $(MAKE) tier_0 $(MAKE) tier_1 $(MAKE) tier_2 $(MAKE) tier_9 $(MAKE) tier_50 $(MAKE) tier_99 # Make sure that the existing rulesets work DIRS = \ $(tier_0_dirs) \ $(tier_1_dirs) \ $(tier_2_dirs) \ $(tier_9_dirs) \ $(tier_50_dirs) \ $(NULL) ifdef GC_LEAK_DETECTOR DIRS += gc/boehm endif DIRS += $(tier_99_dirs) # # tier 0 - base build config dirs # tier_0_dirs = \ config \ build \ $(NULL) # # tier 1 - 3rd party individual libraries # tier_1_dirs += dbm ifndef MOZ_NATIVE_JPEG tier_1_dirs += jpeg endif ifndef MOZ_NATIVE_ZLIB tier_1_dirs += modules/zlib endif # Installer needs standalone libjar, hence standalone zlib ifdef MOZ_INSTALLER tier_1_dirs += modules/zlib/standalone endif ifdef MOZ_UPDATER tier_1_dirs += modules/libbz2 tier_1_dirs += modules/libmar endif ifdef MOZ_SVG_RENDERER_LIBART tier_1_dirs += other-licenses/libart_lgpl endif # # tier 2 - base libraries # tier_2_dirs = \ js \ xpcom \ $(NULL) ifndef MOZ_NO_XPCOM_OBSOLETE tier_2_dirs += modules/libreg xpcom/obsolete endif ifdef NS_TRACE_MALLOC tier_2_dirs += tools/trace-malloc/lib endif # # tier 9 - core components (necko,gecko) # tier_9_dirs += \ js/src/xpconnect \ intl \ db \ $(NULL) ifdef MOZ_STORAGE tier_9_dirs += storage endif ifdef MOZ_ENABLE_XLIB tier_9_dirs += gfx/src/xlibrgb widget/src/xlibxtbin endif ifdef MOZ_ENABLE_GTK tier_9_dirs += widget/src/gtksuperwin widget/src/gtkxtbin endif ifdef MOZ_ENABLE_GTK2 tier_9_dirs += widget/src/gtkxtbin endif ifdef MOZ_IPCD tier_9_dirs += ipc/ipcd endif ifdef MOZ_JSDEBUGGER tier_9_dirs += js/jsd endif tier_9_dirs += \ modules/libutil \ netwerk \ modules/libjar \ uriloader \ modules/libpref \ modules/libimg \ caps \ rdf \ parser/expat \ parser/xml \ parser/htmlparser \ gfx \ modules/libpr0n \ sun-java \ modules/plugin \ dom \ view \ widget \ content \ layout \ xpfe/components/shistory \ docshell \ webshell \ embedding \ editor \ xpfe/appshell \ $(NULL) ifdef MOZ_OJI tier_9_dirs += \ js/src/liveconnect \ modules/oji \ $(NULL) endif ifdef ACCESSIBILITY tier_9_dirs += accessible endif # # tier 50 - xpfe & toolkit # ifdef MOZ_XUL ifdef MOZ_XUL_APP tier_50_dirs += chrome else tier_50_dirs += rdf/chrome endif else tier_50_dirs += embedding/minimo/chromelite endif tier_50_dirs += profile # This must preceed xpfe ifdef MOZ_JPROF tier_50_dirs += tools/jprof endif ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT))) tier_50_dirs += xpfe/bootstrap/appleevents endif tier_50_dirs += \ xpfe \ toolkit/components \ $(NULL) ifndef MOZ_XUL_APP tier_50_dirs += themes endif ifdef MOZ_ENABLE_XREMOTE tier_50_dirs += widget/src/xremoteclient endif ifdef MOZ_XUL_APP tier_50_dirs += toolkit endif ifdef MOZ_PHOENIX #XXXBlake this shell path is a temp hack; toolkit shouldn't depend on browser tier_50_dirs += browser/components/shell/public endif ifdef MOZ_XPINSTALL tier_50_dirs += xpinstall endif # JavaXPCOM JNI code is compiled into libXUL ifdef MOZ_JAVAXPCOM tier_50_dirs += extensions/java/xpcom/src endif ifdef MOZ_ENABLE_LIBXUL tier_50_dirs += \ toolkit/library \ xpcom/stub \ $(NULL) endif ifdef NS_TRACE_MALLOC tier_50_dirs += tools/trace-malloc endif ifdef MOZ_PSM tier_50_dirs += security/manager else tier_50_dirs += security/manager/boot/public security/manager/ssl/public endif ifdef MOZ_LDAP_XPCOM tier_50_dirs += directory/xpcom endif ifndef MINIMO ifdef MOZ_XUL_APP ifdef MOZ_ENABLE_GTK2 tier_50_dirs += toolkit/components/gnome endif endif endif ifdef MOZ_LEAKY tier_50_dirs += tools/leaky endif ifdef MOZ_MAPINFO tier_50_dirs += tools/codesighs endif # # tier 99 - application features # ifdef MOZ_MAIL_NEWS tier_99_dirs += mailnews endif ifdef MOZ_CALENDAR tier_99_dirs += calendar endif ifdef MOZ_EXTENSIONS tier_99_dirs += extensions endif ifdef MOZ_JAVAXPCOM tier_99_dirs += extensions/java endif # axcontrol ifeq ($(OS_ARCH),WINNT) ifndef MOZ_NO_ACTIVEX_SUPPORT tier_99_dirs += \ embedding/browser/activex/src/control \ embedding/browser/activex/src/control_kicker \ $(NULL) endif endif # Java Embedding Plugin ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT))) tier_99_dirs += plugin/oji/JEP endif ifneq (,$(filter browser suite,$(MOZ_BUILD_APP))) tier_99_dirs += xpfe/components/search endif ifdef MOZ_BRANDING_DIRECTORY tier_99_dirs += $(MOZ_BRANDING_DIRECTORY) endif ifdef MOZ_PHOENIX tier_99_dirs += browser xpfe/bootstrap/init.d endif ifdef MOZ_XULRUNNER tier_99_dirs += xulrunner endif ifdef MOZ_COMPOSER tier_99_dirs += editor/ui endif ifdef MOZ_THUNDERBIRD tier_99_dirs += mail xpfe/bootstrap/init.d endif ifdef MOZ_STANDALONE_COMPOSER tier_99_dirs += composer endif ifdef MOZ_SUNBIRD tier_99_dirs += calendar/sunbird endif ifdef MOZ_SUITE tier_99_dirs += suite endif ifdef MINIMO tier_99_dirs += minimo endif ifdef MOZ_XUL_APP ifdef MOZ_INSTALLER tier_99_dirs += toolkit/mozapps/installer endif else ifneq (,$(MOZ_XPFE_COMPONENTS)$(MOZ_XUL)) ifndef MINIMO tier_99_dirs += xpfe/bootstrap endif endif endif ifneq (,$(MOZ_ENABLE_GTK)$(MOZ_ENABLE_GTK2)) tier_99_dirs += embedding/browser/gtk endif # viewer ifneq (,$(ENABLE_TESTS)) ifndef MOZ_ENABLE_LIBXUL tier_99_dirs += webshell/tests endif endif # winembed, mfcembed ifeq ($(OS_ARCH),WINNT) ifneq (,$(ENABLE_TESTS)$(MOZILLA_OFFICIAL)) tier_99_dirs += embedding/tests endif endif # os2embed ifeq ($(OS_ARCH),OS2) ifneq (,$(ENABLE_TESTS)$(MOZILLA_OFFICIAL)) tier_99_dirs += embedding/tests endif endif ifeq ($(MOZ_BUILD_APP),macbrowser) tier_99_dirs += \ embedding/config \ camino \ $(NULL) endif # test harnesses ifdef ENABLE_TESTS tier_99_dirs += tools/test-harness endif else # Standalone build DIRS = $(BUILD_MODULE_DIRS) # Hack to generate xpidl Makefile ifneq ($(BUILD_MODULES),all) ifneq (,$(findstring xpcom, $(BUILD_MODULE_DIRS))) DIRS := xpcom/typelib $(DIRS) SUBMAKEFILES := xpcom/typelib/Makefile endif endif default:: $(SUBMAKEFILES) $(MAKE) export $(MAKE) libs endif # BUILD_MODULES == all STATIC_MAKEFILES := nsprpub directory/c-sdk security/nss GARBAGE_DIRS += dist DIST_GARBAGE = config.cache config.log config.status config-defs.h \ dependencies.beos config/autoconf.mk config/myrules.mk config/myconfig.mk \ unallmakefiles mozilla-config.h \ $(topsrcdir)/.mozconfig.mk $(topsrcdir)/.mozconfig.out # Build pseudo-external modules first when export is explicitly called export:: $(RM) -rf $(DIST)/sdk $(MAKE) -C config export $(MAKE) nspr $(MAKE) ldap ifneq ($(BUILD_MODULES),all) ifneq (,$(findstring xpcom, $(BUILD_MODULE_DIRS))) $(MAKE) -C xpcom/typelib $(MAKE) export-idl endif endif install:: ifndef MOZ_NATIVE_NSPR $(MAKE) -C nsprpub real_install DESTDIR=$(DESTDIR) libdir=$(mozappdir) includedir=$(includedir)/nspr $(RM) -f $(addprefix $(DESTDIR)$(mozappdir)/$(LIB_PREFIX), $(addsuffix .$(LIB_SUFFIX), nspr4 plds4 plc4)) $(RM) -f $(addprefix $(DESTDIR)$(bindir)/,nspr-config compile-et.pl prerr.properties) endif ifdef MOZ_LDAP_XPCOM $(MAKE) -C directory/c-sdk real_install DESTDIR=$(DESTDIR) libdir=$(mozappdir) includedir=$(includedir)/ldap endif include $(topsrcdir)/config/rules.mk # Clean up after pseudo-external modules clean clobber realclean clobber_all distclean:: ifndef MOZ_NATIVE_NSPR $(MAKE) -C nsprpub $@ endif ifdef MOZ_LDAP_XPCOM $(MAKE) -C directory/c-sdk $@ endif # Map mozilla targets to standard automake target ifdef MOZ_ENABLE_LIBXUL tier_50: $(addsuffix /Makefile, $(filter-out $(STATIC_MAKEFILES), $($@_dirs))) @echo "tier_50: $(tier_50_dirs)" @$(EXIT_ON_ERROR) \ for d in $(tier_50_dirs); do \ $(UPDATE_TITLE) \ if test ! -f $$d/Makefile; then \ $(PERL) $(AUTOCONF_TOOLS)/make-makefile -t $(topsrcdir) -d $(DEPTH) $(CYGWIN_TOPSRCDIR) $$d/Makefile; \ fi; \ $(MAKE) -C $$d export; \ done ; \ for d in $(tier_50_dirs); do \ $(UPDATE_TITLE) \ $(MAKE) -C $$d libs; \ done @echo "Building tools from tier 2/9/50" @$(EXIT_ON_ERROR) \ for d in $(tier_2_dirs) $(tier_9_dirs) $(tier_50_dirs); do \ $(UPDATE_TITLE) \ $(MAKE) -C $$d tools; \ done; endif tier_%: @echo "$@: $($@_dirs)" @$(EXIT_ON_ERROR) \ for d in $($@_dirs); do \ $(UPDATE_TITLE) \ if test ! -f $$d/Makefile; then \ $(PERL) $(AUTOCONF_TOOLS)/make-makefile -t $(topsrcdir) -d $(DEPTH) $(CYGWIN_TOPSRCDIR) $$d/Makefile; \ fi; \ $(MAKE) -C $$d export; \ done ; \ for d in $($@_dirs); do $(UPDATE_TITLE) \ $(MAKE) -C $$d libs; \ done # # Individual modules # boehm: ifdef GC_LEAK_DETECTOR $(MAKE) -C gc/boehm endif nspr: boehm ifndef MOZ_NATIVE_NSPR $(MAKE) -C nsprpub endif ldap: ifdef MOZ_LDAP_XPCOM $(MAKE) -C directory/c-sdk endif distclean:: cat unallmakefiles | $(XARGS) rm -f rm -f unallmakefiles $(DIST_GARBAGE) ifeq ($(OS_ARCH),WINNT) rebase: ifdef MOZILLA_OFFICIAL echo rebasing $(DIST) /bin/find $(DIST) -name "*.dll" > rebase.lst rebase -b 60000000 -R . -G rebase.lst rm rebase.lst endif splitsymbols: ifdef MOZILLA_OFFICIAL ifdef MOZ_DEBUG_SYMBOLS echo finding pdb files mkdir -p $(DIST)/$(BUILDID) -cp `/bin/find . -path "./dist" -prune -o -name "*.dll" | sed "s/\.dll$$/\.pdb/" | xargs` $(DIST)/$(BUILDID) -cp `/bin/find . -path "./dist" -prune -o -name "*.exe" | sed "s/\.exe$$/\.pdb/" | xargs` $(DIST)/$(BUILDID) -cp `/bin/find . -path "./dist" -prune -o -name "*.EXE" | sed "s/\.EXE$$/\.pdb/" | xargs` $(DIST)/$(BUILDID) endif # MOZ_DEBUG_SYMBOLS ifdef MOZ_PROFILE echo splitting symbols out of binaries /bin/find $(DIST) -name "*.dll" -exec splitsym {} \; /bin/find $(DIST) -name "*.exe" -exec splitsym {} \; /bin/find $(DIST) -name "*.EXE" -exec splitsym {} \; mkdir -p $(DIST)/$(BUILDID) /bin/find $(DIST) -name "*.dbg" -exec mv {} $(DIST)/$(BUILDID) \; endif # MOZ_PROFILE endif # MOZILLA_OFFICIAL signnss: ifdef MOZILLA_OFFICIAL echo signing NSS libs cd $(DIST)/bin; ./shlibsign.exe -v -i softokn3.dll cd $(DIST)/bin; ./shlibsign.exe -v -i freebl3.dll endif # MOZILLA_OFFICIAL BUILDID = $(shell cat $(DEPTH)/config/build_number) deliver: splitsymbols rebase signnss endif # WINNT pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/flipflop.sv000066400000000000000000000004111250413007300260510ustar00rootroot00000000000000module toplevel(clock,reset); input clock; input reset; reg flop1; reg flop2; always @ (posedge reset or posedge clock) if (reset) begin flop1 <= 0; flop2 <= 1; end else begin flop1 <= flop2; flop2 <= flop1; end endmodule pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/foo.sce000066400000000000000000000000641250413007300251470ustar00rootroot00000000000000// Scilab // disp(%pi); assert_checkequal(2+2,4); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/format.ml000066400000000000000000001226601250413007300255210ustar00rootroot00000000000000(***********************************************************************) (* *) (* Objective Caml *) (* *) (* Pierre Weis, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. All rights reserved. This file is distributed *) (* under the terms of the GNU Library General Public License, with *) (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) (* $Id: format.ml,v 1.65 2005/09/26 10:13:08 weis Exp $ *) (************************************************************** Data structures definitions. **************************************************************) type size;; external size_of_int : int -> size = "%identity";; external int_of_size : size -> int = "%identity";; (* Tokens are one of the following : *) type pp_token = | Pp_text of string (* normal text *) | Pp_break of int * int (* complete break *) | Pp_tbreak of int * int (* go to next tabulation *) | Pp_stab (* set a tabulation *) | Pp_begin of int * block_type (* beginning of a block *) | Pp_end (* end of a block *) | Pp_tbegin of tblock (* beginning of a tabulation block *) | Pp_tend (* end of a tabulation block *) | Pp_newline (* to force a newline inside a block *) | Pp_if_newline (* to do something only if this very line has been broken *) | Pp_open_tag of string (* opening a tag name *) | Pp_close_tag (* closing the most recently opened tag *) and tag = string and block_type = | Pp_hbox (* Horizontal block no line breaking *) | Pp_vbox (* Vertical block each break leads to a new line *) | Pp_hvbox (* Horizontal-vertical block: same as vbox, except if this block is small enough to fit on a single line *) | Pp_hovbox (* Horizontal or Vertical block: breaks lead to new line only when necessary to print the content of the block *) | Pp_box (* Horizontal or Indent block: breaks lead to new line only when necessary to print the content of the block, or when it leads to a new indentation of the current line *) | Pp_fits (* Internal usage: when a block fits on a single line *) and tblock = Pp_tbox of int list ref (* Tabulation box *) ;; (* The Queue: contains all formatting elements. elements are tuples (size, token, length), where size is set when the size of the block is known len is the declared length of the token. *) type pp_queue_elem = { mutable elem_size : size; token : pp_token; length : int };; (* Scan stack: each element is (left_total, queue element) where left_total is the value of pp_left_total when the element has been enqueued. *) type pp_scan_elem = Scan_elem of int * pp_queue_elem;; (* Formatting stack: used to break the lines while printing tokens. The formatting stack contains the description of the currently active blocks. *) type pp_format_elem = Format_elem of block_type * int;; (* General purpose queues, used in the formatter. *) type 'a queue_elem = | Nil | Cons of 'a queue_cell and 'a queue_cell = {mutable head : 'a; mutable tail : 'a queue_elem};; type 'a queue = { mutable insert : 'a queue_elem; mutable body : 'a queue_elem };; (* The formatter specific tag handling functions. *) type formatter_tag_functions = { mark_open_tag : tag -> string; mark_close_tag : tag -> string; print_open_tag : tag -> unit; print_close_tag : tag -> unit; };; (* A formatter with all its machinery. *) type formatter = { mutable pp_scan_stack : pp_scan_elem list; mutable pp_format_stack : pp_format_elem list; mutable pp_tbox_stack : tblock list; mutable pp_tag_stack : tag list; mutable pp_mark_stack : tag list; (* Global variables: default initialization is set_margin 78 set_min_space_left 0. *) (* Value of right margin. *) mutable pp_margin : int; (* Minimal space left before margin, when opening a block. *) mutable pp_min_space_left : int; (* Maximum value of indentation: no blocks can be opened further. *) mutable pp_max_indent : int; (* Space remaining on the current line. *) mutable pp_space_left : int; (* Current value of indentation. *) mutable pp_current_indent : int; (* True when the line has been broken by the pretty-printer. *) mutable pp_is_new_line : bool; (* Total width of tokens already printed. *) mutable pp_left_total : int; (* Total width of tokens ever put in queue. *) mutable pp_right_total : int; (* Current number of opened blocks. *) mutable pp_curr_depth : int; (* Maximum number of blocks which can be simultaneously opened. *) mutable pp_max_boxes : int; (* Ellipsis string. *) mutable pp_ellipsis : string; (* Output function. *) mutable pp_output_function : string -> int -> int -> unit; (* Flushing function. *) mutable pp_flush_function : unit -> unit; (* Output of new lines. *) mutable pp_output_newline : unit -> unit; (* Output of indentation spaces. *) mutable pp_output_spaces : int -> unit; (* Are tags printed ? *) mutable pp_print_tags : bool; (* Are tags marked ? *) mutable pp_mark_tags : bool; (* Find opening and closing markers of tags. *) mutable pp_mark_open_tag : tag -> string; mutable pp_mark_close_tag : tag -> string; mutable pp_print_open_tag : tag -> unit; mutable pp_print_close_tag : tag -> unit; (* The pretty-printer queue. *) mutable pp_queue : pp_queue_elem queue };; (************************************************************** Auxilliaries and basic functions. **************************************************************) (* Queues auxilliaries. *) let make_queue () = {insert = Nil; body = Nil};; let clear_queue q = q.insert <- Nil; q.body <- Nil;; let add_queue x q = let c = Cons {head = x; tail = Nil} in match q with | {insert = Cons cell} -> q.insert <- c; cell.tail <- c (* Invariant: when insert is Nil body should be Nil. *) | _ -> q.insert <- c; q.body <- c;; exception Empty_queue;; let peek_queue = function | {body = Cons {head = x}} -> x | _ -> raise Empty_queue;; let take_queue = function | {body = Cons {head = x; tail = tl}} as q -> q.body <- tl; if tl = Nil then q.insert <- Nil; (* Maintain the invariant. *) x | _ -> raise Empty_queue;; (* Enter a token in the pretty-printer queue. *) let pp_enqueue state ({length = len} as token) = state.pp_right_total <- state.pp_right_total + len; add_queue token state.pp_queue;; let pp_clear_queue state = state.pp_left_total <- 1; state.pp_right_total <- 1; clear_queue state.pp_queue;; (* Pp_infinity: large value for default tokens size. Pp_infinity is documented as being greater than 1e10; to avoid confusion about the word ``greater'', we choose pp_infinity greater than 1e10 + 1; for correct handling of tests in the algorithm, pp_infinity must be even one more than 1e10 + 1; let's stand on the safe side by choosing 1.e10+10. Pp_infinity could probably be 1073741823 that is 2^30 - 1, that is the minimal upper bound for integers; now that max_int is defined, this limit could also be defined as max_int - 1. However, before setting pp_infinity to something around max_int, we must carefully double-check all the integer arithmetic operations that involve pp_infinity, since any overflow would wreck havoc the pretty-printing algorithm's invariants. Given that this arithmetic correctness check is difficult and error prone and given that 1e10 + 1 is in practice large enough, there is no need to attempt to set pp_infinity to the theoretically maximum limit. Is it not worth the burden ! *) let pp_infinity = 1000000010;; (* Output functions for the formatter. *) let pp_output_string state s = state.pp_output_function s 0 (String.length s) and pp_output_newline state = state.pp_output_newline ();; let pp_display_blanks state n = state.pp_output_spaces n;; (* To format a break, indenting a new line. *) let break_new_line state offset width = pp_output_newline state; state.pp_is_new_line <- true; let indent = state.pp_margin - width + offset in (* Don't indent more than pp_max_indent. *) let real_indent = min state.pp_max_indent indent in state.pp_current_indent <- real_indent; state.pp_space_left <- state.pp_margin - state.pp_current_indent; pp_display_blanks state state.pp_current_indent;; (* To force a line break inside a block: no offset is added. *) let break_line state width = break_new_line state 0 width;; (* To format a break that fits on the current line. *) let break_same_line state width = state.pp_space_left <- state.pp_space_left - width; pp_display_blanks state width;; (* To indent no more than pp_max_indent, if one tries to open a block beyond pp_max_indent, then the block is rejected on the left by simulating a break. *) let pp_force_break_line state = match state.pp_format_stack with | Format_elem (bl_ty, width) :: _ -> if width > state.pp_space_left then (match bl_ty with | Pp_fits -> () | Pp_hbox -> () | _ -> break_line state width) | _ -> pp_output_newline state;; (* To skip a token, if the previous line has been broken. *) let pp_skip_token state = (* When calling pp_skip_token the queue cannot be empty. *) match take_queue state.pp_queue with {elem_size = size; length = len} -> state.pp_left_total <- state.pp_left_total - len; state.pp_space_left <- state.pp_space_left + int_of_size size;; (************************************************************** The main pretting printing functions. **************************************************************) (* To format a token. *) let format_pp_token state size = function | Pp_text s -> state.pp_space_left <- state.pp_space_left - size; pp_output_string state s; state.pp_is_new_line <- false | Pp_begin (off, ty) -> let insertion_point = state.pp_margin - state.pp_space_left in if insertion_point > state.pp_max_indent then (* can't open a block right there. *) begin pp_force_break_line state end; let offset = state.pp_space_left - off in let bl_type = begin match ty with | Pp_vbox -> Pp_vbox | _ -> if size > state.pp_space_left then ty else Pp_fits end in state.pp_format_stack <- Format_elem (bl_type, offset) :: state.pp_format_stack | Pp_end -> begin match state.pp_format_stack with | x :: (y :: l as ls) -> state.pp_format_stack <- ls | _ -> () (* No more block to close. *) end | Pp_tbegin (Pp_tbox _ as tbox) -> state.pp_tbox_stack <- tbox :: state.pp_tbox_stack | Pp_tend -> begin match state.pp_tbox_stack with | x :: ls -> state.pp_tbox_stack <- ls | _ -> () (* No more tabulation block to close. *) end | Pp_stab -> begin match state.pp_tbox_stack with | Pp_tbox tabs :: _ -> let rec add_tab n = function | [] -> [n] | x :: l as ls -> if n < x then n :: ls else x :: add_tab n l in tabs := add_tab (state.pp_margin - state.pp_space_left) !tabs | _ -> () (* No opened tabulation block. *) end | Pp_tbreak (n, off) -> let insertion_point = state.pp_margin - state.pp_space_left in begin match state.pp_tbox_stack with | Pp_tbox tabs :: _ -> let rec find n = function | x :: l -> if x >= n then x else find n l | [] -> raise Not_found in let tab = match !tabs with | x :: l -> begin try find insertion_point !tabs with Not_found -> x end | _ -> insertion_point in let offset = tab - insertion_point in if offset >= 0 then break_same_line state (offset + n) else break_new_line state (tab + off) state.pp_margin | _ -> () (* No opened tabulation block. *) end | Pp_newline -> begin match state.pp_format_stack with | Format_elem (_, width) :: _ -> break_line state width | _ -> pp_output_newline state end | Pp_if_newline -> if state.pp_current_indent != state.pp_margin - state.pp_space_left then pp_skip_token state | Pp_break (n, off) -> begin match state.pp_format_stack with | Format_elem (ty, width) :: _ -> begin match ty with | Pp_hovbox -> if size > state.pp_space_left then break_new_line state off width else break_same_line state n | Pp_box -> (* Have the line just been broken here ? *) if state.pp_is_new_line then break_same_line state n else if size > state.pp_space_left then break_new_line state off width else (* break the line here leads to new indentation ? *) if state.pp_current_indent > state.pp_margin - width + off then break_new_line state off width else break_same_line state n | Pp_hvbox -> break_new_line state off width | Pp_fits -> break_same_line state n | Pp_vbox -> break_new_line state off width | Pp_hbox -> break_same_line state n end | _ -> () (* No opened block. *) end | Pp_open_tag tag_name -> let marker = state.pp_mark_open_tag tag_name in pp_output_string state marker; state.pp_mark_stack <- tag_name :: state.pp_mark_stack | Pp_close_tag -> begin match state.pp_mark_stack with | tag_name :: tags -> let marker = state.pp_mark_close_tag tag_name in pp_output_string state marker; state.pp_mark_stack <- tags | _ -> () (* No more tag to close. *) end;; (* Print if token size is known or printing is delayed. Size is known when not negative. Printing is delayed when the text waiting in the queue requires more room to format than exists on the current line. *) let rec advance_left state = try match peek_queue state.pp_queue with {elem_size = size; token = tok; length = len} -> let size = int_of_size size in if not (size < 0 && (state.pp_right_total - state.pp_left_total < state.pp_space_left)) then begin ignore(take_queue state.pp_queue); format_pp_token state (if size < 0 then pp_infinity else size) tok; state.pp_left_total <- len + state.pp_left_total; advance_left state end with Empty_queue -> ();; let enqueue_advance state tok = pp_enqueue state tok; advance_left state;; (* To enqueue a string : try to advance. *) let make_queue_elem size tok len = {elem_size = size; token = tok; length = len};; let enqueue_string_as state size s = let len = int_of_size size in enqueue_advance state (make_queue_elem size (Pp_text s) len);; let enqueue_string state s = let len = String.length s in enqueue_string_as state (size_of_int len) s;; (* Routines for scan stack determine sizes of blocks. *) (* The scan_stack is never empty. *) let scan_stack_bottom = let q_elem = make_queue_elem (size_of_int (-1)) (Pp_text "") 0 in [Scan_elem (-1, q_elem)];; (* Set size of blocks on scan stack: if ty = true then size of break is set else size of block is set; in each case pp_scan_stack is popped. *) let clear_scan_stack state = state.pp_scan_stack <- scan_stack_bottom;; (* Pattern matching on scan stack is exhaustive, since scan_stack is never empty. Pattern matching on token in scan stack is also exhaustive, since scan_push is used on breaks and opening of boxes. *) let set_size state ty = match state.pp_scan_stack with | Scan_elem (left_tot, ({elem_size = size; token = tok} as queue_elem)) :: t -> let size = int_of_size size in (* test if scan stack contains any data that is not obsolete. *) if left_tot < state.pp_left_total then clear_scan_stack state else begin match tok with | Pp_break (_, _) | Pp_tbreak (_, _) -> if ty then begin queue_elem.elem_size <- size_of_int (state.pp_right_total + size); state.pp_scan_stack <- t end | Pp_begin (_, _) -> if not ty then begin queue_elem.elem_size <- size_of_int (state.pp_right_total + size); state.pp_scan_stack <- t end | _ -> () (* scan_push is only used for breaks and boxes. *) end | _ -> () (* scan_stack is never empty. *);; (* Push a token on scan stack. If b is true set_size is called. *) let scan_push state b tok = pp_enqueue state tok; if b then set_size state true; state.pp_scan_stack <- Scan_elem (state.pp_right_total, tok) :: state.pp_scan_stack;; (* To open a new block : the user may set the depth bound pp_max_boxes any text nested deeper is printed as the ellipsis string. *) let pp_open_box_gen state indent br_ty = state.pp_curr_depth <- state.pp_curr_depth + 1; if state.pp_curr_depth < state.pp_max_boxes then let elem = make_queue_elem (size_of_int (- state.pp_right_total)) (Pp_begin (indent, br_ty)) 0 in scan_push state false elem else if state.pp_curr_depth = state.pp_max_boxes then enqueue_string state state.pp_ellipsis;; (* The box which is always opened. *) let pp_open_sys_box state = pp_open_box_gen state 0 Pp_hovbox;; (* Close a block, setting sizes of its subblocks. *) let pp_close_box state () = if state.pp_curr_depth > 1 then begin if state.pp_curr_depth < state.pp_max_boxes then begin pp_enqueue state {elem_size = size_of_int 0; token = Pp_end; length = 0}; set_size state true; set_size state false end; state.pp_curr_depth <- state.pp_curr_depth - 1; end;; (* Open a tag, pushing it on the tag stack. *) let pp_open_tag state tag_name = if state.pp_print_tags then begin state.pp_tag_stack <- tag_name :: state.pp_tag_stack; state.pp_print_open_tag tag_name end; if state.pp_mark_tags then pp_enqueue state {elem_size = size_of_int 0; token = Pp_open_tag tag_name; length = 0};; (* Close a tag, popping it from the tag stack. *) let pp_close_tag state () = if state.pp_mark_tags then pp_enqueue state {elem_size = size_of_int 0; token = Pp_close_tag; length = 0}; if state.pp_print_tags then begin match state.pp_tag_stack with | tag_name :: tags -> state.pp_print_close_tag tag_name; state.pp_tag_stack <- tags | _ -> () (* No more tag to close. *) end;; let pp_set_print_tags state b = state.pp_print_tags <- b;; let pp_set_mark_tags state b = state.pp_mark_tags <- b;; let pp_get_print_tags state () = state.pp_print_tags;; let pp_get_mark_tags state () = state.pp_mark_tags;; let pp_set_tags state b = pp_set_print_tags state b; pp_set_mark_tags state b;; let pp_get_formatter_tag_functions state () = { mark_open_tag = state.pp_mark_open_tag; mark_close_tag = state.pp_mark_close_tag; print_open_tag = state.pp_print_open_tag; print_close_tag = state.pp_print_close_tag; };; let pp_set_formatter_tag_functions state { mark_open_tag = mot; mark_close_tag = mct; print_open_tag = pot; print_close_tag = pct; } = state.pp_mark_open_tag <- mot; state.pp_mark_close_tag <- mct; state.pp_print_open_tag <- pot; state.pp_print_close_tag <- pct;; (* Initialize pretty-printer. *) let pp_rinit state = pp_clear_queue state; clear_scan_stack state; state.pp_format_stack <- []; state.pp_tbox_stack <- []; state.pp_tag_stack <- []; state.pp_mark_stack <- []; state.pp_current_indent <- 0; state.pp_curr_depth <- 0; state.pp_space_left <- state.pp_margin; pp_open_sys_box state;; (* Flushing pretty-printer queue. *) let pp_flush_queue state b = while state.pp_curr_depth > 1 do pp_close_box state () done; state.pp_right_total <- pp_infinity; advance_left state; if b then pp_output_newline state; pp_rinit state;; (************************************************************** Procedures to format objects, and use boxes **************************************************************) (* To format a string. *) let pp_print_as_size state size s = if state.pp_curr_depth < state.pp_max_boxes then enqueue_string_as state size s;; let pp_print_as state isize s = pp_print_as_size state (size_of_int isize) s;; let pp_print_string state s = pp_print_as state (String.length s) s;; (* To format an integer. *) let pp_print_int state i = pp_print_string state (string_of_int i);; (* To format a float. *) let pp_print_float state f = pp_print_string state (string_of_float f);; (* To format a boolean. *) let pp_print_bool state b = pp_print_string state (string_of_bool b);; (* To format a char. *) let pp_print_char state c = let s = String.create 1 in s.[0] <- c; pp_print_as state 1 s;; (* Opening boxes. *) let pp_open_hbox state () = pp_open_box_gen state 0 Pp_hbox and pp_open_vbox state indent = pp_open_box_gen state indent Pp_vbox and pp_open_hvbox state indent = pp_open_box_gen state indent Pp_hvbox and pp_open_hovbox state indent = pp_open_box_gen state indent Pp_hovbox and pp_open_box state indent = pp_open_box_gen state indent Pp_box;; (* Print a new line after printing all queued text (same for print_flush but without a newline). *) let pp_print_newline state () = pp_flush_queue state true; state.pp_flush_function () and pp_print_flush state () = pp_flush_queue state false; state.pp_flush_function ();; (* To get a newline when one does not want to close the current block. *) let pp_force_newline state () = if state.pp_curr_depth < state.pp_max_boxes then enqueue_advance state (make_queue_elem (size_of_int 0) Pp_newline 0);; (* To format something if the line has just been broken. *) let pp_print_if_newline state () = if state.pp_curr_depth < state.pp_max_boxes then enqueue_advance state (make_queue_elem (size_of_int 0) Pp_if_newline 0);; (* Breaks: indicate where a block may be broken. If line is broken then offset is added to the indentation of the current block else (the value of) width blanks are printed. To do (?) : add a maximum width and offset value. *) let pp_print_break state width offset = if state.pp_curr_depth < state.pp_max_boxes then let elem = make_queue_elem (size_of_int (- state.pp_right_total)) (Pp_break (width, offset)) width in scan_push state true elem;; let pp_print_space state () = pp_print_break state 1 0 and pp_print_cut state () = pp_print_break state 0 0;; (* Tabulation boxes. *) let pp_open_tbox state () = state.pp_curr_depth <- state.pp_curr_depth + 1; if state.pp_curr_depth < state.pp_max_boxes then let elem = make_queue_elem (size_of_int 0) (Pp_tbegin (Pp_tbox (ref []))) 0 in enqueue_advance state elem;; (* Close a tabulation block. *) let pp_close_tbox state () = if state.pp_curr_depth > 1 then begin if state.pp_curr_depth < state.pp_max_boxes then let elem = make_queue_elem (size_of_int 0) Pp_tend 0 in enqueue_advance state elem; state.pp_curr_depth <- state.pp_curr_depth - 1 end;; (* Print a tabulation break. *) let pp_print_tbreak state width offset = if state.pp_curr_depth < state.pp_max_boxes then let elem = make_queue_elem (size_of_int (- state.pp_right_total)) (Pp_tbreak (width, offset)) width in scan_push state true elem;; let pp_print_tab state () = pp_print_tbreak state 0 0;; let pp_set_tab state () = if state.pp_curr_depth < state.pp_max_boxes then let elem = make_queue_elem (size_of_int 0) Pp_stab 0 in enqueue_advance state elem;; (************************************************************** Procedures to control the pretty-printers **************************************************************) (* Fit max_boxes. *) let pp_set_max_boxes state n = if n > 1 then state.pp_max_boxes <- n;; (* To know the current maximum number of boxes allowed. *) let pp_get_max_boxes state () = state.pp_max_boxes;; let pp_over_max_boxes state () = state.pp_curr_depth = state.pp_max_boxes;; (* Ellipsis. *) let pp_set_ellipsis_text state s = state.pp_ellipsis <- s and pp_get_ellipsis_text state () = state.pp_ellipsis;; (* To set the margin of pretty-printer. *) let pp_limit n = if n < pp_infinity then n else pred pp_infinity;; let pp_set_min_space_left state n = if n >= 1 then let n = pp_limit n in state.pp_min_space_left <- n; state.pp_max_indent <- state.pp_margin - state.pp_min_space_left; pp_rinit state;; (* Initially, we have : pp_max_indent = pp_margin - pp_min_space_left, and pp_space_left = pp_margin. *) let pp_set_max_indent state n = pp_set_min_space_left state (state.pp_margin - n);; let pp_get_max_indent state () = state.pp_max_indent;; let pp_set_margin state n = if n >= 1 then let n = pp_limit n in state.pp_margin <- n; let new_max_indent = (* Try to maintain max_indent to its actual value. *) if state.pp_max_indent <= state.pp_margin then state.pp_max_indent else (* If possible maintain pp_min_space_left to its actual value, if this leads to a too small max_indent, take half of the new margin, if it is greater than 1. *) max (max (state.pp_margin - state.pp_min_space_left) (state.pp_margin / 2)) 1 in (* Rebuild invariants. *) pp_set_max_indent state new_max_indent;; let pp_get_margin state () = state.pp_margin;; let pp_set_formatter_output_functions state f g = state.pp_output_function <- f; state.pp_flush_function <- g;; let pp_get_formatter_output_functions state () = (state.pp_output_function, state.pp_flush_function);; let pp_set_all_formatter_output_functions state ~out:f ~flush:g ~newline:h ~spaces:i = pp_set_formatter_output_functions state f g; state.pp_output_newline <- (function () -> h ()); state.pp_output_spaces <- (function n -> i n);; let pp_get_all_formatter_output_functions state () = (state.pp_output_function, state.pp_flush_function, state.pp_output_newline, state.pp_output_spaces);; let pp_set_formatter_out_channel state os = state.pp_output_function <- output os; state.pp_flush_function <- (fun () -> flush os);; (************************************************************** Creation of specific formatters **************************************************************) let default_pp_mark_open_tag s = "<" ^ s ^ ">";; let default_pp_mark_close_tag s = "";; let default_pp_print_open_tag s = ();; let default_pp_print_close_tag = default_pp_print_open_tag;; let pp_make_formatter f g h i = (* The initial state of the formatter contains a dummy box. *) let pp_q = make_queue () in let sys_tok = make_queue_elem (size_of_int (-1)) (Pp_begin (0, Pp_hovbox)) 0 in add_queue sys_tok pp_q; let sys_scan_stack = (Scan_elem (1, sys_tok)) :: scan_stack_bottom in {pp_scan_stack = sys_scan_stack; pp_format_stack = []; pp_tbox_stack = []; pp_tag_stack = []; pp_mark_stack = []; pp_margin = 78; pp_min_space_left = 10; pp_max_indent = 78 - 10; pp_space_left = 78; pp_current_indent = 0; pp_is_new_line = true; pp_left_total = 1; pp_right_total = 1; pp_curr_depth = 1; pp_max_boxes = max_int; pp_ellipsis = "."; pp_output_function = f; pp_flush_function = g; pp_output_newline = h; pp_output_spaces = i; pp_print_tags = false; pp_mark_tags = false; pp_mark_open_tag = default_pp_mark_open_tag; pp_mark_close_tag = default_pp_mark_close_tag; pp_print_open_tag = default_pp_print_open_tag; pp_print_close_tag = default_pp_print_close_tag; pp_queue = pp_q };; (* Default function to output spaces. *) let blank_line = String.make 80 ' ';; let rec display_blanks state n = if n > 0 then if n <= 80 then state.pp_output_function blank_line 0 n else begin state.pp_output_function blank_line 0 80; display_blanks state (n - 80) end;; (* Default function to output new lines. *) let display_newline state () = state.pp_output_function "\n" 0 1;; let make_formatter f g = let ff = pp_make_formatter f g ignore ignore in ff.pp_output_newline <- display_newline ff; ff.pp_output_spaces <- display_blanks ff; ff;; let formatter_of_out_channel oc = make_formatter (output oc) (fun () -> flush oc);; let formatter_of_buffer b = make_formatter (Buffer.add_substring b) ignore;; let stdbuf = Buffer.create 512;; let str_formatter = formatter_of_buffer stdbuf;; let std_formatter = formatter_of_out_channel stdout;; let err_formatter = formatter_of_out_channel stderr;; let flush_str_formatter () = pp_flush_queue str_formatter false; let s = Buffer.contents stdbuf in Buffer.reset stdbuf; s;; (************************************************************** Basic functions on the standard formatter **************************************************************) let open_hbox = pp_open_hbox std_formatter and open_vbox = pp_open_vbox std_formatter and open_hvbox = pp_open_hvbox std_formatter and open_hovbox = pp_open_hovbox std_formatter and open_box = pp_open_box std_formatter and close_box = pp_close_box std_formatter and open_tag = pp_open_tag std_formatter and close_tag = pp_close_tag std_formatter and print_as = pp_print_as std_formatter and print_string = pp_print_string std_formatter and print_int = pp_print_int std_formatter and print_float = pp_print_float std_formatter and print_char = pp_print_char std_formatter and print_bool = pp_print_bool std_formatter and print_break = pp_print_break std_formatter and print_cut = pp_print_cut std_formatter and print_space = pp_print_space std_formatter and force_newline = pp_force_newline std_formatter and print_flush = pp_print_flush std_formatter and print_newline = pp_print_newline std_formatter and print_if_newline = pp_print_if_newline std_formatter and open_tbox = pp_open_tbox std_formatter and close_tbox = pp_close_tbox std_formatter and print_tbreak = pp_print_tbreak std_formatter and set_tab = pp_set_tab std_formatter and print_tab = pp_print_tab std_formatter and set_margin = pp_set_margin std_formatter and get_margin = pp_get_margin std_formatter and set_max_indent = pp_set_max_indent std_formatter and get_max_indent = pp_get_max_indent std_formatter and set_max_boxes = pp_set_max_boxes std_formatter and get_max_boxes = pp_get_max_boxes std_formatter and over_max_boxes = pp_over_max_boxes std_formatter and set_ellipsis_text = pp_set_ellipsis_text std_formatter and get_ellipsis_text = pp_get_ellipsis_text std_formatter and set_formatter_out_channel = pp_set_formatter_out_channel std_formatter and set_formatter_output_functions = pp_set_formatter_output_functions std_formatter and get_formatter_output_functions = pp_get_formatter_output_functions std_formatter and set_all_formatter_output_functions = pp_set_all_formatter_output_functions std_formatter and get_all_formatter_output_functions = pp_get_all_formatter_output_functions std_formatter and set_formatter_tag_functions = pp_set_formatter_tag_functions std_formatter and get_formatter_tag_functions = pp_get_formatter_tag_functions std_formatter and set_print_tags = pp_set_print_tags std_formatter and get_print_tags = pp_get_print_tags std_formatter and set_mark_tags = pp_set_mark_tags std_formatter and get_mark_tags = pp_get_mark_tags std_formatter and set_tags = pp_set_tags std_formatter ;; (************************************************************** Printf implementation. **************************************************************) (* Error messages when processing formats. *) (* Trailer: giving up at character number ... *) let giving_up mess fmt i = "fprintf: " ^ mess ^ " ``" ^ fmt ^ "'', \ giving up at character number " ^ string_of_int i ^ (if i < String.length fmt then " (" ^ String.make 1 fmt.[i] ^ ")." else String.make 1 '.');; (* When an invalid format deserves a special error explanation. *) let format_invalid_arg mess fmt i = invalid_arg (giving_up mess fmt i);; (* Standard invalid format. *) let invalid_format fmt i = format_invalid_arg "bad format" fmt i;; (* Cannot find a valid integer into that format. *) let invalid_integer fmt i = invalid_arg (giving_up "bad integer specification" fmt i);; (* Finding an integer out of a sub-string of the format. *) let format_int_of_string fmt i s = let sz = try int_of_string s with | Failure s -> invalid_integer fmt i in size_of_int sz;; (* Getting strings out of buffers. *) let get_buffer_out b = let s = Buffer.contents b in Buffer.reset b; s;; (* [ppf] is supposed to be a pretty-printer that outputs in buffer [b]: to extract contents of [ppf] as a string we flush [ppf] and get the string out of [b]. *) let string_out b ppf = pp_flush_queue ppf false; get_buffer_out b;; (* Applies [printer] to a formatter that outputs on a fresh buffer, then returns the resulting material. *) let exstring printer arg = let b = Buffer.create 512 in let ppf = formatter_of_buffer b in printer ppf arg; string_out b ppf;; (* To turn out a character accumulator into the proper string result. *) let implode_rev s0 = function | [] -> s0 | l -> String.concat "" (List.rev (s0 :: l));; external format_to_string : ('a, 'b, 'c, 'd) format4 -> string = "%identity";; (* [fprintf_out] is the printf-like function generator: given the - [str] flag that tells if we are printing into a string, - the [out] function that has to be called at the end of formatting, it generates a [fprintf] function that takes as arguments a [ppf] formatter and a printing format to print the rest of arguments according to the format. Regular [fprintf]-like functions of this module are obtained via partial applications of [fprintf_out]. *) let mkprintf str get_out = let rec kprintf k fmt = let fmt = format_to_string fmt in let len = String.length fmt in let kpr fmt v = let ppf = get_out fmt in let print_as = ref None in let pp_print_as_char c = match !print_as with | None -> pp_print_char ppf c | Some size -> pp_print_as_size ppf size (String.make 1 c); print_as := None and pp_print_as_string s = match !print_as with | None -> pp_print_string ppf s | Some size -> pp_print_as_size ppf size s; print_as := None in let rec doprn n i = if i >= len then Obj.magic (k ppf) else match fmt.[i] with | '%' -> Printf.scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m | '@' -> let i = succ i in if i >= len then invalid_format fmt i else begin match fmt.[i] with | '[' -> do_pp_open_box ppf n (succ i) | ']' -> pp_close_box ppf (); doprn n (succ i) | '{' -> do_pp_open_tag ppf n (succ i) | '}' -> pp_close_tag ppf (); doprn n (succ i) | ' ' -> pp_print_space ppf (); doprn n (succ i) | ',' -> pp_print_cut ppf (); doprn n (succ i) | '?' -> pp_print_flush ppf (); doprn n (succ i) | '.' -> pp_print_newline ppf (); doprn n (succ i) | '\n' -> pp_force_newline ppf (); doprn n (succ i) | ';' -> do_pp_break ppf n (succ i) | '<' -> let got_size size n i = print_as := Some size; doprn n (skip_gt i) in get_int n (succ i) got_size | '@' as c -> pp_print_as_char c; doprn n (succ i) | c -> invalid_format fmt i end | c -> pp_print_as_char c; doprn n (succ i) and cont_s n s i = pp_print_as_string s; doprn n i and cont_a n printer arg i = if str then pp_print_as_string ((Obj.magic printer : unit -> _ -> string) () arg) else printer ppf arg; doprn n i and cont_t n printer i = if str then pp_print_as_string ((Obj.magic printer : unit -> string) ()) else printer ppf; doprn n i and cont_f n i = pp_print_flush ppf (); doprn n i and cont_m n sfmt i = kprintf (Obj.magic (fun _ -> doprn n i)) sfmt and get_int n i c = if i >= len then invalid_integer fmt i else match fmt.[i] with | ' ' -> get_int n (succ i) c | '%' -> let cont_s n s i = c (format_int_of_string fmt i s) n i and cont_a n printer arg i = invalid_integer fmt i and cont_t n printer i = invalid_integer fmt i and cont_f n i = invalid_integer fmt i and cont_m n sfmt i = invalid_integer fmt i in Printf.scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m | _ -> let rec get j = if j >= len then invalid_integer fmt j else match fmt.[j] with | '0' .. '9' | '-' -> get (succ j) | _ -> let size = if j = i then size_of_int 0 else format_int_of_string fmt j (String.sub fmt i (j - i)) in c size n j in get i and skip_gt i = if i >= len then invalid_format fmt i else match fmt.[i] with | ' ' -> skip_gt (succ i) | '>' -> succ i | _ -> invalid_format fmt i and get_box_kind i = if i >= len then Pp_box, i else match fmt.[i] with | 'h' -> let i = succ i in if i >= len then Pp_hbox, i else begin match fmt.[i] with | 'o' -> let i = succ i in if i >= len then format_invalid_arg "bad box format" fmt i else begin match fmt.[i] with | 'v' -> Pp_hovbox, succ i | c -> format_invalid_arg ("bad box name ho" ^ String.make 1 c) fmt i end | 'v' -> Pp_hvbox, succ i | c -> Pp_hbox, i end | 'b' -> Pp_box, succ i | 'v' -> Pp_vbox, succ i | _ -> Pp_box, i and get_tag_name n i c = let rec get accu n i j = if j >= len then c (implode_rev (String.sub fmt i (j - i)) accu) n j else match fmt.[j] with | '>' -> c (implode_rev (String.sub fmt i (j - i)) accu) n j | '%' -> let s0 = String.sub fmt i (j - i) in let cont_s n s i = get (s :: s0 :: accu) n i i and cont_a n printer arg i = let s = if str then (Obj.magic printer : unit -> _ -> string) () arg else exstring printer arg in get (s :: s0 :: accu) n i i and cont_t n printer i = let s = if str then (Obj.magic printer : unit -> string) () else exstring (fun ppf () -> printer ppf) () in get (s :: s0 :: accu) n i i and cont_f n i = format_invalid_arg "bad tag name specification" fmt i and cont_m n sfmt i = format_invalid_arg "bad tag name specification" fmt i in Printf.scan_format fmt v n j cont_s cont_a cont_t cont_f cont_m | c -> get accu n i (succ j) in get [] n i i and do_pp_break ppf n i = if i >= len then begin pp_print_space ppf (); doprn n i end else match fmt.[i] with | '<' -> let rec got_nspaces nspaces n i = get_int n i (got_offset nspaces) and got_offset nspaces offset n i = pp_print_break ppf (int_of_size nspaces) (int_of_size offset); doprn n (skip_gt i) in get_int n (succ i) got_nspaces | c -> pp_print_space ppf (); doprn n i and do_pp_open_box ppf n i = if i >= len then begin pp_open_box_gen ppf 0 Pp_box; doprn n i end else match fmt.[i] with | '<' -> let kind, i = get_box_kind (succ i) in let got_size size n i = pp_open_box_gen ppf (int_of_size size) kind; doprn n (skip_gt i) in get_int n i got_size | c -> pp_open_box_gen ppf 0 Pp_box; doprn n i and do_pp_open_tag ppf n i = if i >= len then begin pp_open_tag ppf ""; doprn n i end else match fmt.[i] with | '<' -> let got_name tag_name n i = pp_open_tag ppf tag_name; doprn n (skip_gt i) in get_tag_name n (succ i) got_name | c -> pp_open_tag ppf ""; doprn n i in doprn (Printf.index_of_int 0) 0 in Printf.kapr kpr fmt in kprintf;; (************************************************************** Defining [fprintf] and various flavors of [fprintf]. **************************************************************) let kfprintf k ppf = mkprintf false (fun _ -> ppf) k;; let fprintf ppf = kfprintf ignore ppf;; let printf fmt = fprintf std_formatter fmt;; let eprintf fmt = fprintf err_formatter fmt;; let kbprintf k b = mkprintf false (fun _ -> formatter_of_buffer b) k;; let bprintf b = kbprintf ignore b;; let ksprintf k = let b = Buffer.create 512 in let k ppf = k (string_out b ppf) in mkprintf true (fun _ -> formatter_of_buffer b) k;; let kprintf = ksprintf;; let sprintf fmt = ksprintf (fun s -> s) fmt;; at_exit print_flush;; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/fucked_up.rb000066400000000000000000000103331250413007300261620ustar00rootroot00000000000000# vim:ft=ruby events = Hash.new { |h, k| h[k] = [] } DATA.read.split(/\n\n\n\s*/).each do |event| name = event[/^.*/].sub(/http:.*/, '') event[/\n.*/m].scan(/^([A-Z]{2}\S*)\s*(\S*)\s*(\S*)(\s*\S*)/) do |kind, day, daytime, comment| events[ [day, daytime] ] << [kind, name + comment] end end conflicts = 0 events.to_a.sort_by do |(day, daytime),| [%w(Mo Di Mi Do Fr).index(day) || 0, daytime] end.each do |(day, daytime), names| if names.size > 1 conflicts += 1 print '!!! ' end print "#{day} #{daytime}: " names.each { |kind, name| puts " #{kind} #{name}" } puts end puts '%d conflicts' % conflicts puts '%d SWS' % (events.inject(0) { |sum, ((day, daytime),)| sum + (daytime[/\d+$/].to_i - daytime[/^\d+/].to_i) }) string = % foo # strange. huh? print "Escape here: \n" print 'Dont escape here: \n' __END__ Informatik und Informationsgesellschaft I: Digitale Medien (32 214) Computer lassen ihre eigentliche Bestimmung durch Multimedia und Vernetzung erkennen: Es sind digitale Medien, die alle bisherigen Massen- und Kommunikationsmedien simulieren, kopieren oder ersetzen können. Die kurze Geschichte elektronischer Medien vom Telegramm bis zum Fernsehen wird so zur Vorgeschichte des Computers als Medium. Der Prozess der Mediatisierung der Rechnernetze soll in Technik, Theorie und Praxis untersucht werden. Das PR soll die Techniken der ortsverteilten und zeitversetzten Lehre an Hand praktischer Übungen vorführen und untersuchen. VL Di 15-17 wöch. RUD 25, 3.101 J. Koubek VL Do 15-17 wöch. RUD 25, 3.101 UE/PR Do 17-19 wöch. RUD 25, 3.101 J.-M. Loebel Methoden und Modelle des Systementwurfs (32 223) Gute Methoden zum Entwurf und zur Verifikation von Systemen sind ein Schlüssel für gute Software. Dieses Seminar betrachtet moderne Entwurfsmethoden. VL Di 09-11 wöch. RUD 26, 0’313 W. Reisig VL Do 09-11 wöch. RUD 26, 0’313 UE Di 11-13 wöch. RUD 26, 0’313 PR Di 13-15 wöch. RUD 26, 0’313 D. Weinberg Komplexitätstheorie (32 229) In dieser Vorlesung untersuchen wir eine Reihe von wichtigen algorithmischen Problemstellungen aus verschiedenen Bereichen der Informatik. Unser besonderes Interesse gilt dabei der Abschätzung der Rechenressourcen, die zu ihrer Lösung aufzubringen sind. Die Vorlesung bildet eine wichtige Grundlage für weiterführende Veranstaltungen in den Bereichen Algorithmen, Kryptologie, Algorithmisches Lernen und Algorithmisches Beweisen. VL Di 09-11 wöch. RUD 26, 1’303 J. Köbler VL Do 09-11 wöch. RUD 26, 1’305 UE Do 11-13 wöch. RUD 26, 1’305 Zuverlässige Systeme (32 234) Mit zunehmender Verbreitung der Computertechnologie in immer mehr Bereichen des menschlichen Lebens wird die Zuverlässigkeit solcher Systeme zu einer immer zentraleren Frage. Der Halbkurs "Zuverlässige Systeme" konzentriert sich auf folgende Schwerpunkte: Zuverlässigkeit, Fehlertoleranz, Responsivität, Messungen, Anwendungen, Systemmodelle und Techniken, Ausfallverhalten, Fehlermodelle, Schedulingtechniken, Software/Hardware - responsives Systemdesign, Analyse und Synthese, Bewertung, Fallstudien in Forschung und Industrie. Der Halbkurs kann mit dem Halbkurs "Eigenschaften mobiler und eingebetteter Systeme" zu einem Projektkurs kombiniert werden. Ein gemeinsames Projekt begleitet beide Halbkurse. VL Di 09-11 wöch. RUD 26, 1’308 M. Malek VL Do 09-11 wöch. RUD 26, 1’308 PR n.V. Stochastik für InformatikerInnen (32 239) Grundlagen der Wahrscheinlichkeitsrechnung, Diskrete und stetige Wahrscheinlichkeitsmodelle in der Informatik, Grenzwertsätze, Simulationsverfahren, Zufallszahlen, Statistische Schätz- und Testverfahren, Markoffsche Ketten, Simulated Annealing, Probabilistische Analyse von Algorithmen. VL Mo 09-11 wöch. RUD 25, 3.101 W. Kössler VL Mi 09-11 wöch. RUD 25, 3.101 UE Mo 11-13 wöch. RUD 25, 3.101 UE Mi 11-13 wöch. RUD 25. 3.101 Geschichte der Informatik – Ausgewählte Kapitel (32 243) VL Mi 13-15 wöch. RUD 25, 3.113 W. Coy Aktuelle Themen der Theoretischen Informatik (32 260) In diesem Seminar sollen wichtige aktuelle Veröffentlichungen aus der theoretischen Informatik gemeinsam erarbeitet werden. Genaueres wird erst kurz vor dem Seminar entschieden. Bei Interesse wenden Sie sich bitte möglichst frühzeitig an den Veranstalter. SE Fr 09-11 wöch. RUD 26, 1’307 M. Grohe  pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/function.mu000066400000000000000000000000101250413007300260470ustar00rootroot00000000000000a::b () pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/functional.rst000066400000000000000000001454271250413007300266010ustar00rootroot00000000000000Functional Programming HOWTO ================================ **Version 0.30** (This is a first draft. Please send comments/error reports/suggestions to amk@amk.ca. This URL is probably not going to be the final location of the document, so be careful about linking to it -- you may want to add a disclaimer.) In this document, we'll take a tour of Python's features suitable for implementing programs in a functional style. After an introduction to the concepts of functional programming, we'll look at language features such as iterators and generators and relevant library modules such as ``itertools`` and ``functools``. .. contents:: Introduction ---------------------- This section explains the basic concept of functional programming; if you're just interested in learning about Python language features, skip to the next section. Programming languages support decomposing problems in several different ways: * Most programming languages are **procedural**: programs are lists of instructions that tell the computer what to do with the program's input. C, Pascal, and even Unix shells are procedural languages. * In **declarative** languages, you write a specification that describes the problem to be solved, and the language implementation figures out how to perform the computation efficiently. SQL is the declarative language you're most likely to be familiar with; a SQL query describes the data set you want to retrieve, and the SQL engine decides whether to scan tables or use indexes, which subclauses should be performed first, etc. * **Object-oriented** programs manipulate collections of objects. Objects have internal state and support methods that query or modify this internal state in some way. Smalltalk and Java are object-oriented languages. C++ and Python are languages that support object-oriented programming, but don't force the use of object-oriented features. * **Functional** programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don't have any internal state that affects the output produced for a given input. Well-known functional languages include the ML family (Standard ML, OCaml, and other variants) and Haskell. The designers of some computer languages have chosen one approach to programming that's emphasized. This often makes it difficult to write programs that use a different approach. Other languages are multi-paradigm languages that support several different approaches. Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. In a large program, different sections might be written using different approaches; the GUI might be object-oriented while the processing logic is procedural or functional, for example. In a functional program, input flows through a set of functions. Each function operates on its input and produces some output. Functional style frowns upon functions with side effects that modify internal state or make other changes that aren't visible in the function's return value. Functions that have no side effects at all are called **purely functional**. Avoiding side effects means not using data structures that get updated as a program runs; every function's output must only depend on its input. Some languages are very strict about purity and don't even have assignment statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all side effects. Printing to the screen or writing to a disk file are side effects, for example. For example, in Python a ``print`` statement or a ``time.sleep(1)`` both return no useful value; they're only called for their side effects of sending some text to the screen or pausing execution for a second. Python programs written in functional style usually won't go to the extreme of avoiding all I/O or all assignments; instead, they'll provide a functional-appearing interface but will use non-functional features internally. For example, the implementation of a function will still use assignments to local variables, but won't modify global variables or have other side effects. Functional programming can be considered the opposite of object-oriented programming. Objects are little capsules containing some internal state along with a collection of method calls that let you modify this state, and programs consist of making the right set of state changes. Functional programming wants to avoid state changes as much as possible and works with data flowing between functions. In Python you might combine the two approaches by writing functions that take and return instances representing objects in your application (e-mail messages, transactions, etc.). Functional design may seem like an odd constraint to work under. Why should you avoid objects and side effects? There are theoretical and practical advantages to the functional style: * Formal provability. * Modularity. * Composability. * Ease of debugging and testing. Formal provability '''''''''''''''''''''' A theoretical benefit is that it's easier to construct a mathematical proof that a functional program is correct. For a long time researchers have been interested in finding ways to mathematically prove programs correct. This is different from testing a program on numerous inputs and concluding that its output is usually correct, or reading a program's source code and concluding that the code looks right; the goal is instead a rigorous proof that a program produces the right result for all possible inputs. The technique used to prove programs correct is to write down **invariants**, properties of the input data and of the program's variables that are always true. For each line of code, you then show that if invariants X and Y are true **before** the line is executed, the slightly different invariants X' and Y' are true **after** the line is executed. This continues until you reach the end of the program, at which point the invariants should match the desired conditions on the program's output. Functional programming's avoidance of assignments arose because assignments are difficult to handle with this technique; assignments can break invariants that were true before the assignment without producing any new invariants that can be propagated onward. Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe there's an error in it, and you wrongly believe you've proved the program correct. Modularity '''''''''''''''''''''' A more practical benefit of functional programming is that it forces you to break apart your problem into small pieces. Programs are more modular as a result. It's easier to specify and write a small function that does one thing than a large function that performs a complicated transformation. Small functions are also easier to read and to check for errors. Ease of debugging and testing '''''''''''''''''''''''''''''''''' Testing and debugging a functional-style program is easier. Debugging is simplified because functions are generally small and clearly specified. When a program doesn't work, each function is an interface point where you can check that the data are correct. You can look at the intermediate inputs and outputs to quickly isolate the function that's responsible for a bug. Testing is easier because each function is a potential subject for a unit test. Functions don't depend on system state that needs to be replicated before running a test; instead you only have to synthesize the right input and then check that the output matches expectations. Composability '''''''''''''''''''''' As you work on a functional-style program, you'll write a number of functions with varying inputs and outputs. Some of these functions will be unavoidably specialized to a particular application, but others will be useful in a wide variety of programs. For example, a function that takes a directory path and returns all the XML files in the directory, or a function that takes a filename and returns its contents, can be applied to many different situations. Over time you'll form a personal library of utilities. Often you'll assemble new programs by arranging existing functions in a new configuration and writing a few functions specialized for the current task. Iterators ----------------------- I'll start by looking at a Python language feature that's an important foundation for writing functional-style programs: iterators. An iterator is an object representing a stream of data; this object returns the data one element at a time. A Python iterator must support a method called ``next()`` that takes no arguments and always returns the next element of the stream. If there are no more elements in the stream, ``next()`` must raise the ``StopIteration`` exception. Iterators don't have to be finite, though; it's perfectly reasonable to write an iterator that produces an infinite stream of data. The built-in ``iter()`` function takes an arbitrary object and tries to return an iterator that will return the object's contents or elements, raising ``TypeError`` if the object doesn't support iteration. Several of Python's built-in data types support iteration, the most common being lists and dictionaries. An object is called an **iterable** object if you can get an iterator for it. You can experiment with the iteration interface manually:: >>> L = [1,2,3] >>> it = iter(L) >>> print it >>> it.next() 1 >>> it.next() 2 >>> it.next() 3 >>> it.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> Python expects iterable objects in several different contexts, the most important being the ``for`` statement. In the statement ``for X in Y``, Y must be an iterator or some object for which ``iter()`` can create an iterator. These two statements are equivalent:: for i in iter(obj): print i for i in obj: print i Iterators can be materialized as lists or tuples by using the ``list()`` or ``tuple()`` constructor functions:: >>> L = [1,2,3] >>> iterator = iter(L) >>> t = tuple(iterator) >>> t (1, 2, 3) Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple:: >>> L = [1,2,3] >>> iterator = iter(L) >>> a,b,c = iterator >>> a,b,c (1, 2, 3) Built-in functions such as ``max()`` and ``min()`` can take a single iterator argument and will return the largest or smallest element. The ``"in"`` and ``"not in"`` operators also support iterators: ``X in iterator`` is true if X is found in the stream returned by the iterator. You'll run into obvious problems if the iterator is infinite; ``max()``, ``min()``, and ``"not in"`` will never return, and if the element X never appears in the stream, the ``"in"`` operator won't return either. Note that you can only go forward in an iterator; there's no way to get the previous element, reset the iterator, or make a copy of it. Iterator objects can optionally provide these additional capabilities, but the iterator protocol only specifies the ``next()`` method. Functions may therefore consume all of the iterator's output, and if you need to do something different with the same stream, you'll have to create a new iterator. Data Types That Support Iterators ''''''''''''''''''''''''''''''''''' We've already seen how lists and tuples support iterators. In fact, any Python sequence type, such as strings, will automatically support creation of an iterator. Calling ``iter()`` on a dictionary returns an iterator that will loop over the dictionary's keys:: >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} >>> for key in m: ... print key, m[key] Mar 3 Feb 2 Aug 8 Sep 9 May 5 Jun 6 Jul 7 Jan 1 Apr 4 Nov 11 Dec 12 Oct 10 Note that the order is essentially random, because it's based on the hash ordering of the objects in the dictionary. Applying ``iter()`` to a dictionary always loops over the keys, but dictionaries have methods that return other iterators. If you want to iterate over keys, values, or key/value pairs, you can explicitly call the ``iterkeys()``, ``itervalues()``, or ``iteritems()`` methods to get an appropriate iterator. The ``dict()`` constructor can accept an iterator that returns a finite stream of ``(key, value)`` tuples:: >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] >>> dict(iter(L)) {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'} Files also support iteration by calling the ``readline()`` method until there are no more lines in the file. This means you can read each line of a file like this:: for line in file: # do something for each line ... Sets can take their contents from an iterable and let you iterate over the set's elements:: S = set((2, 3, 5, 7, 11, 13)) for i in S: print i Generator expressions and list comprehensions ---------------------------------------------------- Two common operations on an iterator's output are 1) performing some operation for every element, 2) selecting a subset of elements that meet some condition. For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring. List comprehensions and generator expressions (short form: "listcomps" and "genexps") are a concise notation for such operations, borrowed from the functional programming language Haskell (http://www.haskell.org). You can strip all the whitespace from a stream of strings with the following code:: line_list = [' line 1\n', 'line 2 \n', ...] # Generator expression -- returns iterator stripped_iter = (line.strip() for line in line_list) # List comprehension -- returns list stripped_list = [line.strip() for line in line_list] You can select only certain elements by adding an ``"if"`` condition:: stripped_list = [line.strip() for line in line_list if line != ""] With a list comprehension, you get back a Python list; ``stripped_list`` is a list containing the resulting lines, not an iterator. Generator expressions return an iterator that computes the values as necessary, not needing to materialize all the values at once. This means that list comprehensions aren't useful if you're working with iterators that return an infinite stream or a very large amount of data. Generator expressions are preferable in these situations. Generator expressions are surrounded by parentheses ("()") and list comprehensions are surrounded by square brackets ("[]"). Generator expressions have the form:: ( expression for expr in sequence1 if condition1 for expr2 in sequence2 if condition2 for expr3 in sequence3 ... if condition3 for exprN in sequenceN if conditionN ) Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses). The elements of the generated output will be the successive values of ``expression``. The ``if`` clauses are all optional; if present, ``expression`` is only evaluated and added to the result when ``condition`` is true. Generator expressions always have to be written inside parentheses, but the parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write:: obj_total = sum(obj.count for obj in list_all_objects()) The ``for...in`` clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are iterated over from left to right, **not** in parallel. For each element in ``sequence1``, ``sequence2`` is looped over from the beginning. ``sequence3`` is then looped over for each resulting pair of elements from ``sequence1`` and ``sequence2``. To put it another way, a list comprehension or generator expression is equivalent to the following Python code:: for expr1 in sequence1: if not (condition1): continue # Skip this element for expr2 in sequence2: if not (condition2): continue # Skip this element ... for exprN in sequenceN: if not (conditionN): continue # Skip this element # Output the value of # the expression. This means that when there are multiple ``for...in`` clauses but no ``if`` clauses, the length of the resulting output will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long:: seq1 = 'abc' seq2 = (1,2,3) >>> [ (x,y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] To avoid introducing an ambiguity into Python's grammar, if ``expression`` is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct:: # Syntax error [ x,y for x in seq1 for y in seq2] # Correct [ (x,y) for x in seq1 for y in seq2] Generators ----------------------- Generators are a special class of functions that simplify the task of writing iterators. Regular functions compute a value and return it, but generators return an iterator that returns a stream of values. You're doubtless familiar with how regular function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a ``return`` statement, the local variables are destroyed and the value is returned to the caller. A later call to the same function creates a new private namespace and a fresh set of local variables. But, what if the local variables weren't thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions. Here's the simplest example of a generator function:: def generate_ints(N): for i in range(N): yield i Any function containing a ``yield`` keyword is a generator function; this is detected by Python's bytecode compiler which compiles the function specially as a result. When you call a generator function, it doesn't return a single value; instead it returns a generator object that supports the iterator protocol. On executing the ``yield`` expression, the generator outputs the value of ``i``, similar to a ``return`` statement. The big difference between ``yield`` and a ``return`` statement is that on reaching a ``yield`` the generator's state of execution is suspended and local variables are preserved. On the next call to the generator's ``.next()`` method, the function will resume executing. Here's a sample usage of the ``generate_ints()`` generator:: >>> gen = generate_ints(3) >>> gen >>> gen.next() 0 >>> gen.next() 1 >>> gen.next() 2 >>> gen.next() Traceback (most recent call last): File "stdin", line 1, in ? File "stdin", line 2, in generate_ints StopIteration You could equally write ``for i in generate_ints(5)``, or ``a,b,c = generate_ints(3)``. Inside a generator function, the ``return`` statement can only be used without a value, and signals the end of the procession of values; after executing a ``return`` the generator cannot return any further values. ``return`` with a value, such as ``return 5``, is a syntax error inside a generator function. The end of the generator's results can also be indicated by raising ``StopIteration`` manually, or by just letting the flow of execution fall off the bottom of the function. You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting ``self.count`` to 0, and having the ``next()`` method increment ``self.count`` and return it. However, for a moderately complicated generator, writing a corresponding class can be much messier. The test suite included with Python's library, ``test_generators.py``, contains a number of more interesting examples. Here's one generator that implements an in-order traversal of a tree using generators recursively. :: # A recursive generator that generates Tree leaves in in-order. def inorder(t): if t: for x in inorder(t.left): yield x yield t.label for x in inorder(t.right): yield x Two other examples in ``test_generators.py`` produce solutions for the N-Queens problem (placing N queens on an NxN chess board so that no queen threatens another) and the Knight's Tour (finding a route that takes a knight to every square of an NxN chessboard without visiting any square twice). Passing values into a generator '''''''''''''''''''''''''''''''''''''''''''''' In Python 2.4 and earlier, generators only produced output. Once a generator's code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. You could hack together this ability by making the generator look at a global variable or by passing in some mutable object that callers then modify, but these approaches are messy. In Python 2.5 there's a simple way to pass values into a generator. ``yield`` became an expression, returning a value that can be assigned to a variable or otherwise operated on:: val = (yield i) I recommend that you **always** put parentheses around a ``yield`` expression when you're doing something with the returned value, as in the above example. The parentheses aren't always necessary, but it's easier to always add them instead of having to remember when they're needed. (PEP 342 explains the exact rules, which are that a ``yield``-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write ``val = yield i`` but have to use parentheses when there's an operation, as in ``val = (yield i) + 12``.) Values are sent into a generator by calling its ``send(value)`` method. This method resumes the generator's code and the ``yield`` expression returns the specified value. If the regular ``next()`` method is called, the ``yield`` returns ``None``. Here's a simple counter that increments by 1 and allows changing the value of the internal counter. :: def counter (maximum): i = 0 while i < maximum: val = (yield i) # If value provided, change counter if val is not None: i = val else: i += 1 And here's an example of changing the counter: >>> it = counter(10) >>> print it.next() 0 >>> print it.next() 1 >>> print it.send(8) 8 >>> print it.next() 9 >>> print it.next() Traceback (most recent call last): File ``t.py'', line 15, in ? print it.next() StopIteration Because ``yield`` will often be returning ``None``, you should always check for this case. Don't just use its value in expressions unless you're sure that the ``send()`` method will be the only method used resume your generator function. In addition to ``send()``, there are two other new methods on generators: * ``throw(type, value=None, traceback=None)`` is used to raise an exception inside the generator; the exception is raised by the ``yield`` expression where the generator's execution is paused. * ``close()`` raises a ``GeneratorExit`` exception inside the generator to terminate the iteration. On receiving this exception, the generator's code must either raise ``GeneratorExit`` or ``StopIteration``; catching the exception and doing anything else is illegal and will trigger a ``RuntimeError``. ``close()`` will also be called by Python's garbage collector when the generator is garbage-collected. If you need to run cleanup code when a ``GeneratorExit`` occurs, I suggest using a ``try: ... finally:`` suite instead of catching ``GeneratorExit``. The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers. Generators also become **coroutines**, a more generalized form of subroutines. Subroutines are entered at one point and exited at another point (the top of the function, and a ``return`` statement), but coroutines can be entered, exited, and resumed at many different points (the ``yield`` statements). Built-in functions ---------------------------------------------- Let's look in more detail at built-in functions often used with iterators. Two Python's built-in functions, ``map()`` and ``filter()``, are somewhat obsolete; they duplicate the features of list comprehensions but return actual lists instead of iterators. ``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. :: def upper(s): return s.upper() map(upper, ['sentence', 'fragment']) => ['SENTENCE', 'FRAGMENT'] [upper(s) for s in ['sentence', 'fragment']] => ['SENTENCE', 'FRAGMENT'] As shown above, you can achieve the same effect with a list comprehension. The ``itertools.imap()`` function does the same thing but can handle infinite iterators; it'll be discussed later, in the section on the ``itertools`` module. ``filter(predicate, iter)`` returns a list that contains all the sequence elements that meet a certain condition, and is similarly duplicated by list comprehensions. A **predicate** is a function that returns the truth value of some condition; for use with ``filter()``, the predicate must take a single value. :: def is_even(x): return (x % 2) == 0 filter(is_even, range(10)) => [0, 2, 4, 6, 8] This can also be written as a list comprehension:: >>> [x for x in range(10) if is_even(x)] [0, 2, 4, 6, 8] ``filter()`` also has a counterpart in the ``itertools`` module, ``itertools.ifilter()``, that returns an iterator and can therefore handle infinite sequences just as ``itertools.imap()`` can. ``reduce(func, iter, [initial_value])`` doesn't have a counterpart in the ``itertools`` module because it cumulatively performs an operation on all the iterable's elements and therefore can't be applied to infinite iterables. ``func`` must be a function that takes two elements and returns a single value. ``reduce()`` takes the first two elements A and B returned by the iterator and calculates ``func(A, B)``. It then requests the third element, C, calculates ``func(func(A, B), C)``, combines this result with the fourth element returned, and continues until the iterable is exhausted. If the iterable returns no values at all, a ``TypeError`` exception is raised. If the initial value is supplied, it's used as a starting point and ``func(initial_value, A)`` is the first calculation. :: import operator reduce(operator.concat, ['A', 'BB', 'C']) => 'ABBC' reduce(operator.concat, []) => TypeError: reduce() of empty sequence with no initial value reduce(operator.mul, [1,2,3], 1) => 6 reduce(operator.mul, [], 1) => 1 If you use ``operator.add`` with ``reduce()``, you'll add up all the elements of the iterable. This case is so common that there's a special built-in called ``sum()`` to compute it:: reduce(operator.add, [1,2,3,4], 0) => 10 sum([1,2,3,4]) => 10 sum([]) => 0 For many uses of ``reduce()``, though, it can be clearer to just write the obvious ``for`` loop:: # Instead of: product = reduce(operator.mul, [1,2,3], 1) # You can write: product = 1 for i in [1,2,3]: product *= i ``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples containing the count and each element. :: enumerate(['subject', 'verb', 'object']) => (0, 'subject'), (1, 'verb'), (2, 'object') ``enumerate()`` is often used when looping through a list and recording the indexes at which certain conditions are met:: f = open('data.txt', 'r') for i, line in enumerate(f): if line.strip() == '': print 'Blank line at line #%i' % i ``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the elements of the iterable into a list, sorts the list, and returns the sorted result. The ``cmp``, ``key``, and ``reverse`` arguments are passed through to the constructed list's ``.sort()`` method. :: import random # Generate 8 random numbers between [0, 10000) rand_list = random.sample(range(10000), 8) rand_list => [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] sorted(rand_list) => [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] sorted(rand_list, reverse=True) => [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] (For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the Python wiki at http://wiki.python.org/moin/HowTo/Sorting.) The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an iterable's contents. ``any()`` returns True if any element in the iterable is a true value, and ``all()`` returns True if all of the elements are true values:: any([0,1,0]) => True any([0,0,0]) => False any([1,1,1]) => True all([0,1,0]) => False all([0,0,0]) => False all([1,1,1]) => True Small functions and the lambda statement ---------------------------------------------- When writing functional-style programs, you'll often need little functions that act as predicates or that combine elements in some way. If there's a Python built-in or a module function that's suitable, you don't need to define a new function at all:: stripped_lines = [line.strip() for line in lines] existing_files = filter(os.path.exists, file_list) If the function you need doesn't exist, you need to write it. One way to write small functions is to use the ``lambda`` statement. ``lambda`` takes a number of parameters and an expression combining these parameters, and creates a small function that returns the value of the expression:: lowercase = lambda x: x.lower() print_assign = lambda name, value: name + '=' + str(value) adder = lambda x, y: x+y An alternative is to just use the ``def`` statement and define a function in the usual way:: def lowercase(x): return x.lower() def print_assign(name, value): return name + '=' + str(value) def adder(x,y): return x + y Which alternative is preferable? That's a style question; my usual course is to avoid using ``lambda``. One reason for my preference is that ``lambda`` is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can't have multiway ``if... elif... else`` comparisons or ``try... except`` statements. If you try to do too much in a ``lambda`` statement, you'll end up with an overly complicated expression that's hard to read. Quick, what's the following code doing? :: total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1] You can figure it out, but it takes time to disentangle the expression to figure out what's going on. Using a short nested ``def`` statements makes things a little bit better:: def combine (a, b): return 0, a[1] + b[1] total = reduce(combine, items)[1] But it would be best of all if I had simply used a ``for`` loop:: total = 0 for a, b in items: total += b Or the ``sum()`` built-in and a generator expression:: total = sum(b for a,b in items) Many uses of ``reduce()`` are clearer when written as ``for`` loops. Fredrik Lundh once suggested the following set of rules for refactoring uses of ``lambda``: 1) Write a lambda function. 2) Write a comment explaining what the heck that lambda does. 3) Study the comment for a while, and think of a name that captures the essence of the comment. 4) Convert the lambda to a def statement, using that name. 5) Remove the comment. I really like these rules, but you're free to disagree that this lambda-free style is better. The itertools module ----------------------- The ``itertools`` module contains a number of commonly-used iterators as well as functions for combining several iterators. This section will introduce the module's contents by showing small examples. The module's functions fall into a few broad classes: * Functions that create a new iterator based on an existing iterator. * Functions for treating an iterator's elements as function arguments. * Functions for selecting portions of an iterator's output. * A function for grouping an iterator's output. Creating new iterators '''''''''''''''''''''' ``itertools.count(n)`` returns an infinite stream of integers, increasing by 1 each time. You can optionally supply the starting number, which defaults to 0:: itertools.count() => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... itertools.count(10) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... ``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable and returns a new iterator that returns its elements from first to last. The new iterator will repeat these elements infinitely. :: itertools.cycle([1,2,3,4,5]) => 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... ``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or returns the element endlessly if ``n`` is not provided. :: itertools.repeat('abc') => abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... itertools.repeat('abc', 5) => abc, abc, abc, abc, abc ``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as input, and returns all the elements of the first iterator, then all the elements of the second, and so on, until all of the iterables have been exhausted. :: itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => a, b, c, 1, 2, 3 ``itertools.izip(iterA, iterB, ...)`` takes one element from each iterable and returns them in a tuple:: itertools.izip(['a', 'b', 'c'], (1, 2, 3)) => ('a', 1), ('b', 2), ('c', 3) It's similiar to the built-in ``zip()`` function, but doesn't construct an in-memory list and exhaust all the input iterators before returning; instead tuples are constructed and returned only if they're requested. (The technical term for this behaviour is `lazy evaluation `__.) This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be the same length as the shortest iterable. :: itertools.izip(['a', 'b'], (1, 2, 3)) => ('a', 1), ('b', 2) You should avoid doing this, though, because an element may be taken from the longer iterators and discarded. This means you can't go on to use the iterators further because you risk skipping a discarded element. ``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a slice of the iterator. With a single ``stop`` argument, it will return the first ``stop`` elements. If you supply a starting index, you'll get ``stop-start`` elements, and if you supply a value for ``step``, elements will be skipped accordingly. Unlike Python's string and list slicing, you can't use negative values for ``start``, ``stop``, or ``step``. :: itertools.islice(range(10), 8) => 0, 1, 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8) => 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8, 2) => 2, 4, 6 ``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n`` independent iterators that will all return the contents of the source iterator. If you don't supply a value for ``n``, the default is 2. Replicating iterators requires saving some of the contents of the source iterator, so this can consume significant memory if the iterator is large and one of the new iterators is consumed more than the others. :: itertools.tee( itertools.count() ) => iterA, iterB where iterA -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... and iterB -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... Calling functions on elements ''''''''''''''''''''''''''''' Two functions are used for calling other functions on the contents of an iterable. ``itertools.imap(f, iterA, iterB, ...)`` returns a stream containing ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``:: itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) => 6, 8, 8 The ``operator`` module contains a set of functions corresponding to Python's operators. Some examples are ``operator.add(a, b)`` (adds two values), ``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')`` (returns a callable that fetches the ``"id"`` attribute). ``itertools.starmap(func, iter)`` assumes that the iterable will return a stream of tuples, and calls ``f()`` using these tuples as the arguments:: itertools.starmap(os.path.join, [('/usr', 'bin', 'java'), ('/bin', 'python'), ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')]) => /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby Selecting elements '''''''''''''''''' Another group of functions chooses a subset of an iterator's elements based on a predicate. ``itertools.ifilter(predicate, iter)`` returns all the elements for which the predicate returns true:: def is_even(x): return (x % 2) == 0 itertools.ifilter(is_even, itertools.count()) => 0, 2, 4, 6, 8, 10, 12, 14, ... ``itertools.ifilterfalse(predicate, iter)`` is the opposite, returning all elements for which the predicate returns false:: itertools.ifilterfalse(is_even, itertools.count()) => 1, 3, 5, 7, 9, 11, 13, 15, ... ``itertools.takewhile(predicate, iter)`` returns elements for as long as the predicate returns true. Once the predicate returns false, the iterator will signal the end of its results. :: def less_than_10(x): return (x < 10) itertools.takewhile(less_than_10, itertools.count()) => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 itertools.takewhile(is_even, itertools.count()) => 0 ``itertools.dropwhile(predicate, iter)`` discards elements while the predicate returns true, and then returns the rest of the iterable's results. :: itertools.dropwhile(less_than_10, itertools.count()) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... itertools.dropwhile(is_even, itertools.count()) => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... Grouping elements ''''''''''''''''' The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is the most complicated. ``key_func(elem)`` is a function that can compute a key value for each element returned by the iterable. If you don't supply a key function, the key is simply each element itself. ``groupby()`` collects all the consecutive elements from the underlying iterable that have the same key value, and returns a stream of 2-tuples containing a key value and an iterator for the elements with that key. :: city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), ('Anchorage', 'AK'), ('Nome', 'AK'), ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), ... ] def get_state ((city, state)): return state itertools.groupby(city_list, get_state) => ('AL', iterator-1), ('AK', iterator-2), ('AZ', iterator-3), ... where iterator-1 => ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') iterator-2 => ('Anchorage', 'AK'), ('Nome', 'AK') iterator-3 => ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ') ``groupby()`` assumes that the underlying iterable's contents will already be sorted based on the key. Note that the returned iterators also use the underlying iterable, so you have to consume the results of iterator-1 before requesting iterator-2 and its corresponding key. The functools module ---------------------------------------------- The ``functools`` module in Python 2.5 contains some higher-order functions. A **higher-order function** takes one or more functions as input and returns a new function. The most useful tool in this module is the ``partial()`` function. For programs written in a functional style, you'll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function ``f(a, b, c)``; you may wish to create a new function ``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for one of ``f()``'s parameters. This is called "partial function application". The constructor for ``partial`` takes the arguments ``(function, arg1, arg2, ... kwarg1=value1, kwarg2=value2)``. The resulting object is callable, so you can just call it to invoke ``function`` with the filled-in arguments. Here's a small but realistic example:: import functools def log (message, subsystem): "Write the contents of 'message' to the specified subsystem." print '%s: %s' % (subsystem, message) ... server_log = functools.partial(log, subsystem='server') server_log('Unable to open socket') The operator module ------------------- The ``operator`` module was mentioned earlier. It contains a set of functions corresponding to Python's operators. These functions are often useful in functional-style code because they save you from writing trivial functions that perform a single operation. Some of the functions in this module are: * Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``, ``abs()``, ... * Logical operations: ``not_()``, ``truth()``. * Bitwise operations: ``and_()``, ``or_()``, ``invert()``. * Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``. * Object identity: ``is_()``, ``is_not()``. Consult `the operator module's documentation `__ for a complete list. The functional module --------------------- Collin Winter's `functional module `__ provides a number of more advanced tools for functional programming. It also reimplements several Python built-ins, trying to make them more intuitive to those used to functional programming in other languages. This section contains an introduction to some of the most important functions in ``functional``; full documentation can be found at `the project's website `__. ``compose(outer, inner, unpack=False)`` The ``compose()`` function implements function composition. In other words, it returns a wrapper around the ``outer`` and ``inner`` callables, such that the return value from ``inner`` is fed directly to ``outer``. That is, :: >>> def add(a, b): ... return a + b ... >>> def double(a): ... return 2 * a ... >>> compose(double, add)(5, 6) 22 is equivalent to :: >>> double(add(5, 6)) 22 The ``unpack`` keyword is provided to work around the fact that Python functions are not always `fully curried `__. By default, it is expected that the ``inner`` function will return a single object and that the ``outer`` function will take a single argument. Setting the ``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which will be expanded before being passed to ``outer``. Put simply, :: compose(f, g)(5, 6) is equivalent to:: f(g(5, 6)) while :: compose(f, g, unpack=True)(5, 6) is equivalent to:: f(*g(5, 6)) Even though ``compose()`` only accepts two functions, it's trivial to build up a version that will compose any number of functions. We'll use ``reduce()``, ``compose()`` and ``partial()`` (the last of which is provided by both ``functional`` and ``functools``). :: from functional import compose, partial multi_compose = partial(reduce, compose) We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of ``"".join(...)`` that converts its arguments to string:: from functional import compose, partial join = compose("".join, partial(map, str)) ``flip(func)`` ``flip()`` wraps the callable in ``func`` and causes it to receive its non-keyword arguments in reverse order. :: >>> def triple(a, b, c): ... return (a, b, c) ... >>> triple(5, 6, 7) (5, 6, 7) >>> >>> flipped_triple = flip(triple) >>> flipped_triple(5, 6, 7) (7, 6, 5) ``foldl(func, start, iterable)`` ``foldl()`` takes a binary function, a starting value (usually some kind of 'zero'), and an iterable. The function is applied to the starting value and the first element of the list, then the result of that and the second element of the list, then the result of that and the third element of the list, and so on. This means that a call such as:: foldl(f, 0, [1, 2, 3]) is equivalent to:: f(f(f(0, 1), 2), 3) ``foldl()`` is roughly equivalent to the following recursive function:: def foldl(func, start, seq): if len(seq) == 0: return start return foldl(func, func(start, seq[0]), seq[1:]) Speaking of equivalence, the above ``foldl`` call can be expressed in terms of the built-in ``reduce`` like so:: reduce(f, [1, 2, 3], 0) We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a cleaner, more aesthetically-pleasing version of Python's ``"".join(...)`` idiom:: from functional import foldl, partial from operator import concat join = partial(foldl, concat, "") Revision History and Acknowledgements ------------------------------------------------ The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton. Version 0.1: posted June 30 2006. Version 0.11: posted July 1 2006. Typo fixes. Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes. Version 0.21: Added more references suggested on the tutor mailing list. Version 0.30: Adds a section on the ``functional`` module written by Collin Winter; adds short section on the operator module; a few other edits. References -------------------- General ''''''''''''''' **Structure and Interpretation of Computer Programs**, by Harold Abelson and Gerald Jay Sussman with Julie Sussman. Full text at http://mitpress.mit.edu/sicp/. In this classic textbook of computer science, chapters 2 and 3 discuss the use of sequences and streams to organize the data flow inside a program. The book uses Scheme for its examples, but many of the design approaches described in these chapters are applicable to functional-style Python code. http://www.defmacro.org/ramblings/fp.html: A general introduction to functional programming that uses Java examples and has a lengthy historical introduction. http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry describing functional programming. http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines. http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying. Python-specific ''''''''''''''''''''''''''' http://gnosis.cx/TPiP/: The first chapter of David Mertz's book :title-reference:`Text Processing in Python` discusses functional programming for text processing, in the section titled "Utilizing Higher-Order Functions in Text Processing". Mertz also wrote a 3-part series of articles on functional programming for IBM's DeveloperWorks site; see `part 1 `__, `part 2 `__, and `part 3 `__, Python documentation ''''''''''''''''''''''''''' http://docs.python.org/lib/module-itertools.html: Documentation for the ``itertools`` module. http://docs.python.org/lib/module-operator.html: Documentation for the ``operator`` module. http://www.python.org/dev/peps/pep-0289/: PEP 289: "Generator Expressions" http://www.python.org/dev/peps/pep-0342/ PEP 342: "Coroutines via Enhanced Generators" describes the new generator features in Python 2.5. .. comment Topics to place ----------------------------- XXX os.walk() XXX Need a large example. But will an example add much? I'll post a first draft and see what the comments say. .. comment Original outline: Introduction Idea of FP Programs built out of functions Functions are strictly input-output, no internal state Opposed to OO programming, where objects have state Why FP? Formal provability Assignment is difficult to reason about Not very relevant to Python Modularity Small functions that do one thing Debuggability: Easy to test due to lack of state Easy to verify output from intermediate steps Composability You assemble a toolbox of functions that can be mixed Tackling a problem Need a significant example Iterators Generators The itertools module List comprehensions Small functions and the lambda statement Built-in functions map filter reduce .. comment Handy little function for printing part of an iterator -- used while writing this document. import itertools def print_iter(it): slice = itertools.islice(it, 10) for elem in slice[:-1]: sys.stdout.write(str(elem)) sys.stdout.write(', ') print elem[-1] pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/garcia-wachs.kk000066400000000000000000000077141250413007300265610ustar00rootroot00000000000000// Koka language test module // This module implements the GarsiaWachs algorithm. // It is an adaptation of the algorithm in ML as described by JeanChristophe Filli�tre: // in ''A functional implementation of the GarsiaWachs algorithm. (functional pearl). ML workshop 2008, pages 91--96''. // See: http://www.lri.fr/~filliatr/publis/gwWml08.pdf // // The algorithm is interesting since it uses mutable references shared between a list and tree but the // side effects are not observable from outside. Koka automatically infers that the final algorithm is pure. // Note: due to a current limitation in the divergence analysis, koka cannot yet infer that mutually recursive // definitions in "insert" and "extract" are terminating and the final algorithm still has a divergence effect. // However, koka does infer that no other effect (i.e. an exception due to a partial match) can occur. module garcsiaWachs import test = qualified std/flags # pre processor test public function main() { wlist = Cons1(('a',3), [('b',2),('c',1),('d',4),('e',5)]) tree = wlist.garsiaWachs() tree.show.println() } //---------------------------------------------------- // Trees //---------------------------------------------------- public type tree { con Leaf(value :a) con Node(left :tree, right :tree) } function show( t : tree ) : string { match(t) { Leaf(c) -> core/show(c) Node(l,r) -> "Node(" + show(l) + "," + show(r) + ")" } } //---------------------------------------------------- // Non empty lists //---------------------------------------------------- public type list1 { Cons1( head : a, tail : list ) } function map( xs, f ) { val Cons1(y,ys) = xs return Cons1(f(y), core/map(ys,f)) } function zip( xs :list1, ys :list1 ) : list1<(a,b)> { Cons1( (xs.head, ys.head), zip(xs.tail, ys.tail)) } //---------------------------------------------------- // Phase 1 //---------------------------------------------------- function insert( after : list<(tree,int)>, t : (tree,int), before : list<(tree,int)> ) : div tree { match(before) { Nil -> extract( [], Cons1(t,after) ) Cons(x,xs) -> { if (x.snd < t.snd) then return insert( Cons(x,after), t, xs ) match(xs) { Nil -> extract( [], Cons1(x,Cons(t,after)) ) Cons(y,ys) -> extract( ys, Cons1(y,Cons(x,Cons(t,after))) ) } } } } function extract( before : list<(tree,int)>, after : list1<(tree,int)> ) : div tree { val Cons1((t1,w1) as x, xs ) = after match(xs) { Nil -> t1 Cons((t2,w2) as y, ys) -> match(ys) { Nil -> insert( [], (Node(t1,t2), w1+w2), before ) Cons((_,w3),_zs) -> if (w1 <= w3) then insert(ys, (Node(t1,t2), w1+w2), before) else extract(Cons(x,before), Cons1(y,ys)) } } } function balance( xs : list1<(tree,int)> ) : div tree { extract( [], xs ) } //---------------------------------------------------- // Phase 2 //---------------------------------------------------- function mark( depth :int, t :tree<(a,ref)> ) : > () { match(t) { Leaf((_,d)) -> d := depth Node(l,r) -> { mark(depth+1,l); mark(depth+1,r) } } } function build( depth :int, xs :list1<(a,ref)> ) : ,div> (tree,list<(a,ref)>) { if (!(xs.head.snd) == depth) return (Leaf(xs.head.fst), xs.tail) l = build(depth+1, xs) match(l.snd) { Nil -> (l.fst, Nil) Cons(y,ys) -> { r = build(depth+1, Cons1(y,ys)) (Node(l.fst,r.fst), r.snd) } } } //---------------------------------------------------- // Main //---------------------------------------------------- public function garsiaWachs( xs : list1<(a,int)> ) : div tree { refs = xs.map(fst).map( fun(x) { (x, ref(0)) } ) wleafs = zip( refs.map(Leaf), xs.map(snd) ) tree = balance(wleafs) mark(0,tree) build(0,refs).fst } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/genclass.clj000066400000000000000000000527141250413007300261720ustar00rootroot00000000000000; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Common Public License 1.0 (http://opensource.org/licenses/cpl.php) ; which can be found in the file CPL.TXT at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (in-ns 'clojure) (import '(java.lang.reflect Modifier Constructor) '(clojure.asm ClassWriter ClassVisitor Opcodes Type) '(clojure.asm.commons Method GeneratorAdapter) '(clojure.lang IPersistentMap)) ;(defn method-sig [#^java.lang.reflect.Method meth] ; [(. meth (getName)) (seq (. meth (getParameterTypes)))]) (defn- non-private-methods [#^Class c] (loop [mm {} considered #{} c c] (if c (let [[mm considered] (loop [mm mm considered considered meths (concat (seq (. c (getDeclaredMethods))) (seq (. c (getMethods))))] (if meths (let [#^Method meth (first meths) mods (. meth (getModifiers)) mk (method-sig meth)] (if (or (considered mk) (. Modifier (isPrivate mods)) (. Modifier (isStatic mods)) (. Modifier (isFinal mods))) (recur mm (conj considered mk) (rest meths)) (recur (assoc mm mk meth) (conj considered mk) (rest meths)))) [mm considered]))] (recur mm considered (. c (getSuperclass)))) mm))) (defn- ctor-sigs [super] (for [#^Constructor ctor (. super (getDeclaredConstructors)) :when (not (. Modifier (isPrivate (. ctor (getModifiers)))))] (apply vector (. ctor (getParameterTypes))))) (defn- escape-class-name [c] (.. (.getSimpleName c) (replace "[]" "<>"))) (defn- overload-name [mname pclasses] (if (seq pclasses) (apply str mname (interleave (repeat \-) (map escape-class-name pclasses))) (str mname "-void"))) ;(distinct (map first(keys (mapcat non-private-methods [Object IPersistentMap])))) (defn gen-class "Generates compiled bytecode for a class with the given package-qualified cname (which, as all names in these parameters, can be a string or symbol). The gen-class construct contains no implementation, as the implementation will be dynamically sought by the generated class in functions in a corresponding Clojure namespace. Given a generated class org.mydomain.MyClass, methods will be implemented that look for same-named functions in a Clojure namespace called org.domain.MyClass. The init and main functions (see below) will be found similarly. The static initializer for the generated class will attempt to load the Clojure support code for the class as a resource from the claspath, e.g. in the example case, org/mydomain/MyClass.clj Returns a map containing :name and :bytecode. Most uses will be satisfied by the higher-level gen-and-load-class and gen-and-store-class functions, which generate and immediately load, or generate and store to disk, respectively. Options should be a set of key/value pairs, all of which are optional: :extends aclass Specifies the superclass, the non-private methods of which will be overridden by the class. If not provided, defaults to Object. :implements [interface ...] One or more interfaces, the methods of which will be implemented by the class. :init name If supplied, names a function that will be called with the arguments to the constructor. Must return [[superclass-constructor-args] state] If not supplied, the constructor args are passed directly to the superclass constructor and the state will be nil :constructors {[param-types] [super-param-types], ...} By default, constructors are created for the generated class which match the signature(s) of the constructors for the superclass. This parameter may be used to explicitly specify constructors, each entry providing a mapping from a constructor signature to a superclass constructor signature. When you supply this, you must supply an :init specifier. :methods [[name [param-types] return-type], ...] The generated class automatically defines all of the non-private methods of its superclasses/interfaces. This parameter can be used to specify the signatures of additional methods of the generated class. Do not repeat superclass/interface signatures here. :main boolean If supplied and true, a static public main function will be generated. It will pass each string of the String[] argument as a separate argument to a function called 'main. :factory name If supplied, a (set of) public static factory function(s) will be created with the given name, and the same signature(s) as the constructor(s). :state name If supplied, a public final instance field with the given name will be created. You must supply an :init function in order to provide a value for the state. Note that, though final, the state can be a ref or agent, supporting the creation of Java objects with transactional or asynchronous mutation semantics. :exposes {protected-field-name {:get name :set name}, ...} Since the implementations of the methods of the generated class occur in Clojure functions, they have no access to the inherited protected fields of the superclass. This parameter can be used to generate public getter/setter methods exposing the protected field(s) for use in the implementation." [cname & options] (let [name (str cname) {:keys [extends implements constructors methods main factory state init exposes]} (apply hash-map options) super (or extends Object) interfaces implements supers (cons super (seq interfaces)) ctor-sig-map (or constructors (zipmap (ctor-sigs super) (ctor-sigs super))) cv (new ClassWriter (. ClassWriter COMPUTE_MAXS)) cname (. name (replace "." "/")) ctype (. Type (getObjectType cname)) iname (fn [c] (.. Type (getType c) (getInternalName))) totype (fn [c] (. Type (getType c))) to-types (fn [cs] (if (pos? (count cs)) (into-array (map totype cs)) (make-array Type 0))) obj-type (totype Object) arg-types (fn [n] (if (pos? n) (into-array (replicate n obj-type)) (make-array Type 0))) super-type (totype super) init-name (str init) factory-name (str factory) state-name (str state) main-name "main" var-name (fn [s] (str s "__var")) rt-type (totype clojure.lang.RT) var-type (totype clojure.lang.Var) ifn-type (totype clojure.lang.IFn) iseq-type (totype clojure.lang.ISeq) ex-type (totype java.lang.UnsupportedOperationException) all-sigs (distinct (concat (map #(let[[m p] (key %)] {m [p]}) (mapcat non-private-methods supers)) (map (fn [[m p]] {(str m) [p]}) methods))) sigs-by-name (apply merge-with concat {} all-sigs) overloads (into {} (filter (fn [[m s]] (rest s)) sigs-by-name)) var-fields (concat (and init [init-name]) (and main [main-name]) (distinct (concat (keys sigs-by-name) (mapcat (fn [[m s]] (map #(overload-name m %) s)) overloads) (mapcat (comp (partial map str) vals val) exposes)))) emit-get-var (fn [gen v] (let [false-label (. gen newLabel) end-label (. gen newLabel)] (. gen getStatic ctype (var-name v) var-type) (. gen dup) (. gen invokeVirtual var-type (. Method (getMethod "boolean isBound()"))) (. gen ifZCmp (. GeneratorAdapter EQ) false-label) (. gen invokeVirtual var-type (. Method (getMethod "Object get()"))) (. gen goTo end-label) (. gen mark false-label) (. gen pop) (. gen visitInsn (. Opcodes ACONST_NULL)) (. gen mark end-label))) emit-forwarding-method (fn [mname pclasses rclass else-gen] (let [ptypes (to-types pclasses) rtype (totype rclass) m (new Method mname rtype ptypes) is-overload (overloads mname) gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv) found-label (. gen (newLabel)) else-label (. gen (newLabel)) end-label (. gen (newLabel))] (. gen (visitCode)) (when is-overload (emit-get-var gen (overload-name mname pclasses)) (. gen (dup)) (. gen (ifNonNull found-label)) (. gen (pop))) (emit-get-var gen mname) (. gen (dup)) (. gen (ifNull else-label)) (when is-overload (. gen (mark found-label))) ;if found (. gen (loadThis)) ;box args (dotimes i (count ptypes) (. gen (loadArg i)) (. clojure.lang.Compiler$HostExpr (emitBoxReturn nil gen (nth pclasses i)))) ;call fn (. gen (invokeInterface ifn-type (new Method "invoke" obj-type (into-array (cons obj-type (replicate (count ptypes) obj-type)))))) ;unbox return (. gen (unbox rtype)) (when (= (. rtype (getSort)) (. Type VOID)) (. gen (pop))) (. gen (goTo end-label)) ;else call supplied alternative generator (. gen (mark else-label)) (. gen (pop)) (else-gen gen m) (. gen (mark end-label)) (. gen (returnValue)) (. gen (endMethod)))) ] ;start class definition (. cv (visit (. Opcodes V1_5) (. Opcodes ACC_PUBLIC) cname nil (iname super) (when interfaces (into-array (map iname interfaces))))) ;static fields for vars (doseq v var-fields (. cv (visitField (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_FINAL) (. Opcodes ACC_STATIC)) (var-name v) (. var-type getDescriptor) nil nil))) ;instance field for state (when state (. cv (visitField (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_FINAL)) state-name (. obj-type getDescriptor) nil nil))) ;static init to set up var fields and load clj (let [gen (new GeneratorAdapter (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_STATIC)) (. Method getMethod "void ()") nil nil cv)] (. gen (visitCode)) (doseq v var-fields (. gen push name) (. gen push v) (. gen (invokeStatic rt-type (. Method (getMethod "clojure.lang.Var var(String,String)")))) (. gen putStatic ctype (var-name v) var-type)) (. gen push ctype) (. gen push (str (. name replace \. (. java.io.File separatorChar)) ".clj")) (. gen (invokeStatic rt-type (. Method (getMethod "void loadResourceScript(Class,String)")))) (. gen (returnValue)) (. gen (endMethod))) ;ctors (doseq [pclasses super-pclasses] ctor-sig-map (let [ptypes (to-types pclasses) super-ptypes (to-types super-pclasses) m (new Method "" (. Type VOID_TYPE) ptypes) super-m (new Method "" (. Type VOID_TYPE) super-ptypes) gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv) no-init-label (. gen newLabel) end-label (. gen newLabel) nth-method (. Method (getMethod "Object nth(Object,int)")) local (. gen newLocal obj-type)] (. gen (visitCode)) (if init (do (emit-get-var gen init-name) (. gen dup) (. gen ifNull no-init-label) ;box init args (dotimes i (count pclasses) (. gen (loadArg i)) (. clojure.lang.Compiler$HostExpr (emitBoxReturn nil gen (nth pclasses i)))) ;call init fn (. gen (invokeInterface ifn-type (new Method "invoke" obj-type (arg-types (count ptypes))))) ;expecting [[super-ctor-args] state] returned (. gen dup) (. gen push 0) (. gen (invokeStatic rt-type nth-method)) (. gen storeLocal local) (. gen (loadThis)) (. gen dupX1) (dotimes i (count super-pclasses) (. gen loadLocal local) (. gen push i) (. gen (invokeStatic rt-type nth-method)) (. clojure.lang.Compiler$HostExpr (emitUnboxArg nil gen (nth super-pclasses i)))) (. gen (invokeConstructor super-type super-m)) (if state (do (. gen push 1) (. gen (invokeStatic rt-type nth-method)) (. gen (putField ctype state-name obj-type))) (. gen pop)) (. gen goTo end-label) ;no init found (. gen mark no-init-label) (. gen (throwException ex-type (str init-name " not defined"))) (. gen mark end-label)) (if (= pclasses super-pclasses) (do (. gen (loadThis)) (. gen (loadArgs)) (. gen (invokeConstructor super-type super-m))) (throw (new Exception ":init not specified, but ctor and super ctor args differ")))) (. gen (returnValue)) (. gen (endMethod)) ;factory (when factory (let [fm (new Method factory-name ctype ptypes) gen (new GeneratorAdapter (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_STATIC)) fm nil nil cv)] (. gen (visitCode)) (. gen newInstance ctype) (. gen dup) (. gen (loadArgs)) (. gen (invokeConstructor ctype m)) (. gen (returnValue)) (. gen (endMethod)))))) ;add methods matching supers', if no fn -> call super (let [mm (non-private-methods super)] (doseq #^java.lang.reflect.Method meth (vals mm) (emit-forwarding-method (.getName meth) (.getParameterTypes meth) (.getReturnType meth) (fn [gen m] (. gen (loadThis)) ;push args (. gen (loadArgs)) ;call super (. gen (visitMethodInsn (. Opcodes INVOKESPECIAL) (. super-type (getInternalName)) (. m (getName)) (. m (getDescriptor))))))) ;add methods matching interfaces', if no fn -> throw (doseq #^Class iface interfaces (doseq #^java.lang.reflect.Method meth (. iface (getMethods)) (when-not (contains? mm (method-sig meth)) (emit-forwarding-method (.getName meth) (.getParameterTypes meth) (.getReturnType meth) (fn [gen m] (. gen (throwException ex-type (. m (getName))))))))) ;extra methods (doseq [mname pclasses rclass :as msig] methods (emit-forwarding-method (str mname) pclasses rclass (fn [gen m] (. gen (throwException ex-type (. m (getName)))))))) ;main (when main (let [m (. Method getMethod "void main (String[])") gen (new GeneratorAdapter (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_STATIC)) m nil nil cv) no-main-label (. gen newLabel) end-label (. gen newLabel)] (. gen (visitCode)) (emit-get-var gen main-name) (. gen dup) (. gen ifNull no-main-label) (. gen loadArgs) (. gen (invokeStatic rt-type (. Method (getMethod "clojure.lang.ISeq seq(Object)")))) (. gen (invokeInterface ifn-type (new Method "applyTo" obj-type (into-array [iseq-type])))) (. gen pop) (. gen goTo end-label) ;no main found (. gen mark no-main-label) (. gen (throwException ex-type (str main-name " not defined"))) (. gen mark end-label) (. gen (returnValue)) (. gen (endMethod)))) ;field exposers (doseq [f {getter :get setter :set}] exposes (let [fld (.getField super (str f)) ftype (totype (.getType fld))] (when getter (let [m (new Method (str getter) ftype (to-types [])) gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv)] (. gen (visitCode)) (. gen loadThis) (. gen getField ctype (str f) ftype) (. gen (returnValue)) (. gen (endMethod)))) (when setter (let [m (new Method (str setter) (. Type VOID_TYPE) (into-array [ftype])) gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv)] (. gen (visitCode)) (. gen loadThis) (. gen loadArgs) (. gen putField ctype (str f) ftype) (. gen (returnValue)) (. gen (endMethod)))))) ;finish class def (. cv (visitEnd)) {:name name :bytecode (. cv (toByteArray))})) (defn gen-and-load-class "Generates and immediately loads the bytecode for the specified class. Note that a class generated this way can be loaded only once - the JVM supports only one class with a given name per classloader. Subsequent to generation you can import it into any desired namespaces just like any other class. See gen-class for a description of the options." [name & options] (let [{:keys [name bytecode]} (apply gen-class (str name) options)] (.. clojure.lang.RT ROOT_CLASSLOADER (defineClass (str name) bytecode)))) (defn gen-and-save-class "Generates the bytecode for the named class and stores in a .class file in a subpath of the supplied path, the directories for which must already exist. See gen-class for a description of the options" [path name & options] (let [{:keys [name bytecode]} (apply gen-class (str name) options) file (java.io.File. path (str (. name replace \. (. java.io.File separatorChar)) ".class"))] (.createNewFile file) (with-open f (java.io.FileOutputStream. file) (.write f bytecode)))) (comment ;usage (gen-class package-qualified-name ;all below are optional :extends aclass :implements [interface ...] :constructors {[param-types] [super-param-types], } :methods [[name [param-types] return-type], ] :main boolean :factory name :state name :init name :exposes {protected-field {:get name :set name}, }) ;(gen-and-load-class (clojure/gen-and-save-class "/Users/rich/Downloads" 'fred.lucy.Ethel :extends clojure.lang.Box ;APersistentMap :implements [clojure.lang.IPersistentMap] :state 'state ;:constructors {[Object] [Object]} ;:init 'init :main true :factory 'create :methods [['foo [Object] Object] ['foo [] Object]] :exposes {'val {:get 'getVal :set 'setVal}}) (in-ns 'fred.lucy.Ethel__2276) (clojure/refer 'clojure :exclude '(assoc seq count cons)) (defn init [n] [[] n]) (defn foo ([this] :foo) ([this x] x)) (defn main [x y] (println x y)) (in-ns 'user) (def ethel (new fred.lucy.Ethel__2276 42)) (def ethel (fred.lucy.Ethel__2276.create 21)) (fred.lucy.Ethel__2276.main (into-array ["lucy" "ricky"])) (.state ethel) (.foo ethel 7) (.foo ethel) (.getVal ethel) (.setVal ethel 12) (gen-class org.clojure.MyComparator :implements [Comparator]) (in-ns 'org.clojure.MyComparator) (defn compare [this x y] ...) (load-file "/Users/rich/dev/clojure/src/genclass.clj") (clojure/gen-and-save-class "/Users/rich/dev/clojure/gen/" 'org.clojure.ClojureServlet :extends javax.servlet.http.HttpServlet) ) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/genshi_example.xml+genshi000066400000000000000000000203231250413007300306530ustar00rootroot00000000000000 $title

(${v or 'No'} match${v != 1 and 'es' or ''})

$title ${num_matches(len(tickets))}

Filters
 


Note: See TracQuery for help on using queries.
pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/genshitext_example.genshitext000066400000000000000000000005141250413007300316710ustar00rootroot00000000000000 ## a comment \## not a comment #if foo ${bar} #endif The answer is: #choose #when 0 == 1 0 #end #when 1 == 1 1 #end #otherwise 2 #end #end -- comment about choose #for item in items * ${item} #end #def greeting(name) Hello, ${name}! #end ${greeting('world')} #with y=7; z=x+10 $x $y $z #end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/glsl.frag000066400000000000000000000002371250413007300254740ustar00rootroot00000000000000/* Fragment shader */ void main() { gl_FragColor[0] = gl_FragCoord[0] / 400.0; gl_FragColor[1] = gl_FragCoord[1] / 400.0; gl_FragColor[2] = 1.0; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/glsl.vert000066400000000000000000000004431250413007300255340ustar00rootroot00000000000000/* Vertex shader */ uniform float waveTime; uniform float waveWidth; uniform float waveHeight; void main(void) { vec4 v = vec4(gl_Vertex); v.z = sin(waveWidth * v.x + waveTime) * cos(waveWidth * v.y + waveTime) * waveHeight; gl_Position = gl_ModelViewProjectionMatrix * v; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/grammar-test.p6000066400000000000000000000005261250413007300265450ustar00rootroot00000000000000token pod_formatting_code { $=<[A..Z]> '<' { $*POD_IN_FORMATTINGCODE := 1 } $=[ '> ]+ '>' { $*POD_IN_FORMATTINGCODE := 0 } } token pod_string { + } token something:sym«<» { } token name { } token comment:sym<#> { '#' {} \N* } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/hash_syntax.rb000066400000000000000000000003301250413007300265420ustar00rootroot00000000000000{ :old_syntax => 'ok' } { 'stings as key' => 'should be ok' } { new_syntax: 'broken until now' } { withoutunderscore: 'should be ok' } { _underscoreinfront: 'might be ok, if I understand the pygments code correct' } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/hello.at000066400000000000000000000002071250413007300253200ustar00rootroot00000000000000def me := object: { def name := "Kevin"; def sayHello(peerName) { system.println(peerName + " says hello!"); }; }; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/hello.golo000066400000000000000000000001111250413007300256460ustar00rootroot00000000000000module hello.World function main = |args| { println("Hello world!") } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/hello.lsl000066400000000000000000000002401250413007300255030ustar00rootroot00000000000000default { state_entry() { llSay(0, "Hello, Avatar!"); } touch_start(integer total_number) { llSay(0, "Touched."); } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/hello.smali000066400000000000000000000015001250413007300260160ustar00rootroot00000000000000# To Recreate: # # echo -e 'class hello {\n public static void main(String[] args) {\n # System.out.println("hi");\n }\n}\n' > hello.java # javac -target 1.4 -source 1.4 hello.java # dx --dex --output=hello.dex hello.class # baksmali hello.dex # cat out/hello.smali .class Lhello; .super Ljava/lang/Object; .source "hello.java" # direct methods .method constructor ()V .registers 1 .prologue .line 1 invoke-direct {p0}, Ljava/lang/Object;->()V return-void .end method .method public static main([Ljava/lang/String;)V .registers 3 .parameter .prologue .line 3 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const-string v1, "hi" invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V .line 4 return-void .end method pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/hello.sp000066400000000000000000000002021250413007300253310ustar00rootroot00000000000000#include // Single line comment /* Multi line comment */ public OnPluginStart() { PrintToServer("Hello."); } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/html+php_faulty.php000066400000000000000000000000061250413007300275100ustar00rootroot00000000000000 * * Hybris is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Hybris is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Hybris. If not, see . */ import std.io.file; class File { protected file, fileName, mode; public method File( fileName, mode ){ me.fileName = fileName; me.mode = mode; me.file = fopen ( me.fileName, me.mode); } private method isBinary(){ return me.mode.find("b") != false; } public method File ( file ){ me.file = file; } private method __expire() { me.close(); } public method close(){ fclose( me.file ); } public method readLine(){ return line = fgets( me.file ); } public method getFileName(){ return me.fileName; } public method getSize(){ return fsize( me.fileName ); } public method getPosition(){ return ftell( me.file ); } public method readAll(){ text = ""; line = ""; while ( ( line = fgets(me.file) ) != 0 ){ text += line; } return text; } public method read(){ byte = ' '; if ( fread( me.file, byte) > 0 ) { return byte; } else { return -1; } } public method read( bytes ) { word = ""; byte = ' '; if ( fread( me.file, byte, bytes) > 0 ) { word += byte; } else { return -1; } return word; } public method read ( seek, seekType ){ if ( me.seek( seek, seekType) == 0 ) { return -1; } return me.read(); } public method read ( bytes, seek, seekType ){ if ( me.seek( seek, seekType) == 0 ) { return -1; } return me.read( bytes ); } public method readType ( type ){ if ( me.isBinary() == false ) { return -1; } if ( fread (me.file, type ) > 0 ) { return type; } else { return -1; } } operator >> ( object ){ return me.readType(object); } public method readType ( type, bytes ){ if ( me.isBinary() == false ) { return -1; } if ( fread (me.file, type, bytes ) > 0){ return type; } else { return -1; } } public method readType ( type, seek, seekType ){ if ( ( me.isBinary() == false ) | ( me.seek( seek, seekType) == 0 ) ) { return -1; } return me.readType( type ); } public method readType( type, bytes, seek, seekType){ if ( ( me.isBinary() == false ) | ( me.seek( seek, seekType) == 0 ) ) { return -1; } return me.readType( type, bytes ); } public method write( data ){ return fwrite( me.file, data ); } operator << ( object ){ return me.write(object); } public method write ( data, bytes ){ return fwrite( me.file, data, bytes); } public method seek( pos, mode ){ return fseek( me.file, pos, mode ); } public method merge ( fileName ){ text = file ( fileName ); return me.write ( me.file, text ); } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/idl_sample.pro000066400000000000000000000040621250413007300265250ustar00rootroot00000000000000; docformat = 'rst' ; Example IDL (Interactive Data Language) source code. ;+ ; Get `nIndices` random indices for an array of size `nValues` (without ; repeating an index). ; ; :Examples: ; Try:: ; ; IDL> r = randomu(seed, 10) ; IDL> print, r, format='(4F)' ; 0.6297589 0.7815896 0.2508559 0.7546844 ; 0.1353382 0.1245834 0.8733745 0.0753110 ; 0.8054136 0.9513228 ; IDL> ind = mg_sample(10, 3, seed=seed) ; IDL> print, ind ; 2 4 7 ; IDL> print, r[ind] ; 0.250856 0.135338 0.0753110 ; ; :Returns: ; lonarr(`nIndices`) ; ; :Params: ; nValues : in, required, type=long ; size of array to choose indices from ; nIndices : in, required, type=long ; number of indices needed ; ; :Keywords: ; seed : in, out, optional, type=integer or lonarr(36) ; seed to use for random number generation, leave undefined to use a ; seed generated from the system clock; new seed will be output ;- function mg_sample, nValues, nIndices, seed=seed compile_opt strictarr ; get random nIndices by finding the indices of the smallest nIndices in a ; array of random values values = randomu(seed, nValues) ; our random values are uniformly distributed, so ideally the nIndices ; smallest values are in the first bin of the below histogram nBins = nValues / nIndices h = histogram(values, nbins=nBins, reverse_indices=ri) ; the candidates for being in the first nIndices will live in bins 0..bin nCandidates = 0L for bin = 0L, nBins - 1L do begin nCandidates += h[bin] if (nCandidates ge nIndices) then break endfor ; get the candidates and sort them candidates = ri[ri[0] : ri[bin + 1L] - 1L] sortedCandidates = sort(values[candidates]) ; return the first nIndices of them return, (candidates[sortedCandidates])[0:nIndices-1L] end ; main-level example program r = randomu(seed, 10) print, r ind = mg_sample(10, 3, seed=seed) print, ind print, r[ind] endpygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/iex_example000066400000000000000000000005511250413007300261140ustar00rootroot00000000000000iex> :" multi ...> line ' \s \123 \x20 ...> atom" :" multi\n line ' S \natom" iex(1)> <<"hello"::binary, c :: utf8, x::[4, unit(2)]>> = "hello™1" "hello™1" iex(2)> c 8482 iex> 1 + :atom ** (ArithmeticError) bad argument in arithmetic expression :erlang.+(1, :atom) iex(3)> 1 + ...(3)> 2 + ...(3)> 3 6 iex> IO.puts "Hello world" Hello world :ok pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/inet_pton6.dg000066400000000000000000000052071250413007300262750ustar00rootroot00000000000000import '/re' import '/sys' # IPv6address = hexpart [ ":" IPv4address ] # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT # hexpart = [ hexseq ] [ "::" [ hexseq ] ] # hexseq = hex4 *( ":" hex4) # hex4 = 1*4HEXDIG hexpart = r'({0}|)(?:::({0}|)|)'.format r'(?:[\da-f]{1,4})(?::[\da-f]{1,4})*' addrv4 = r'(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})' addrv6 = re.compile $ r'(?i)(?:{})(?::{})?$'.format hexpart addrv4 # Parse a base-N number given a list of its digits. # # :param q: the number of digits in that numeral system # # :param digits: an iterable of integers in range [0..q] # # :return: a decimal integer # base_n = q digits -> foldl (x y -> x * q + y) 0 digits # Parse a sequence of hexadecimal numbers # # :param q: a string of colon-separated base-16 integers # # :return: an iterable of Python ints # unhex = q -> q and map (p -> int p 16) (q.split ':') # Parse an IPv6 address as specified in RFC 4291. # # :param address: a string, obviously. # # :return: an integer which, written in binary form, points to the same node. # inet_pton6 = address -> not (match = addrv6.match address) => raise $ ValueError 'not a valid IPv6 address' start, end, *ipv4 = match.groups! is_ipv4 = not $ None in ipv4 shift = (7 - start.count ':' - 2 * is_ipv4) * 16 (end is None and shift) or shift < 0 => raise $ ValueError 'not a valid IPv6 address' hexaddr = (base_n 0x10000 (unhex start) << shift) + base_n 0x10000 (unhex $ end or '') if (is_ipv4 => (hexaddr << 32) + base_n 0x100 (map int ipv4)) (otherwise => hexaddr) inet6_type = q -> if q == 0 => 'unspecified' q == 1 => 'loopback' (q >> 32) == 0x000000000000ffff => 'IPv4-mapped' (q >> 64) == 0xfe80000000000000 => 'link-local' (q >> 120) != 0x00000000000000ff => 'general unicast' (q >> 112) % (1 << 4) == 0x0000000000000000 => 'multicast w/ reserved scope value' (q >> 112) % (1 << 4) == 0x000000000000000f => 'multicast w/ reserved scope value' (q >> 112) % (1 << 4) == 0x0000000000000001 => 'interface-local multicast' (q >> 112) % (1 << 4) == 0x0000000000000004 => 'admin-local multicast' (q >> 112) % (1 << 4) == 0x0000000000000005 => 'site-local multicast' (q >> 112) % (1 << 4) == 0x0000000000000008 => 'organization-local multicast' (q >> 112) % (1 << 4) == 0x000000000000000e => 'global multicast' (q >> 112) % (1 << 4) != 0x0000000000000002 => 'multicast w/ unknown scope value' (q >> 24) % (1 << 112) == 0x00000000000001ff => 'solicited-node multicast' otherwise => 'link-local multicast' print $ (x -> inet6_type x, hex x) $ inet_pton6 $ sys.stdin.read!.strip! pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/intro.ik000066400000000000000000000007251250413007300253540ustar00rootroot00000000000000#!/usr/bin/ioke Ioke = LanguageExperiment with( goal: :expressiveness, data: as(code), code: as(data), features: [ :dynamic, :object_oriented, :prototype_based, :homoiconic, :macros ], runtimes:(JVM, CLR), inspirations: set(Io, Smalltalk, Ruby, Lisp) ) hello = method("Every example needs a hello world!", name, "hello, #{name}!" println) Ioke inspirations select( features include?(:object_oriented) ) each(x, hello(x name)) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ints.php000066400000000000000000000001511250413007300253530ustar00rootroot00000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/intsyn.fun000066400000000000000000000535071250413007300257400ustar00rootroot00000000000000(* Internal Syntax *) (* Author: Frank Pfenning, Carsten Schuermann *) (* Modified: Roberto Virga *) functor IntSyn (structure Global : GLOBAL) :> INTSYN = struct type cid = int (* Constant identifier *) type name = string (* Variable name *) type mid = int (* Structure identifier *) type csid = int (* CS module identifier *) (* Contexts *) datatype 'a Ctx = (* Contexts *) Null (* G ::= . *) | Decl of 'a Ctx * 'a (* | G, D *) (* ctxPop (G) => G' Invariant: G = G',D *) fun ctxPop (Decl (G, D)) = G exception Error of string (* raised if out of space *) (* ctxLookup (G, k) = D, kth declaration in G from right to left Invariant: 1 <= k <= |G|, where |G| is length of G *) fun ctxLookup (Decl (G', D), 1) = D | ctxLookup (Decl (G', _), k') = ctxLookup (G', k'-1) (* | ctxLookup (Null, k') = (print ("Looking up k' = " ^ Int.toString k' ^ "\n"); raise Error "Out of Bounce\n")*) (* ctxLookup (Null, k') should not occur by invariant *) (* ctxLength G = |G|, the number of declarations in G *) fun ctxLength G = let fun ctxLength' (Null, n) = n | ctxLength' (Decl(G, _), n)= ctxLength' (G, n+1) in ctxLength' (G, 0) end type FgnExp = exn (* foreign expression representation *) exception UnexpectedFgnExp of FgnExp (* raised by a constraint solver if passed an incorrect arg *) type FgnCnstr = exn (* foreign unification constraint representation *) exception UnexpectedFgnCnstr of FgnCnstr (* raised by a constraint solver if passed an incorrect arg *) datatype Depend = (* Dependency information *) No (* P ::= No *) | Maybe (* | Maybe *) | Meta (* | Meta *) (* Expressions *) datatype Uni = (* Universes: *) Kind (* L ::= Kind *) | Type (* | Type *) datatype Exp = (* Expressions: *) Uni of Uni (* U ::= L *) | Pi of (Dec * Depend) * Exp (* | bPi (D, P). V *) | Root of Head * Spine (* | C @ S *) | Redex of Exp * Spine (* | U @ S *) | Lam of Dec * Exp (* | lam D. U *) | EVar of Exp option ref * Dec Ctx * Exp * (Cnstr ref) list ref (* | X : G|-V, Cnstr *) | EClo of Exp * Sub (* | U[s] *) | AVar of Exp option ref (* | A *) | NVar of int (* | n (linear, fully applied) *) (* grafting variable *) | FgnExp of csid * FgnExp (* | (foreign expression) *) and Head = (* Heads: *) BVar of int (* H ::= k *) | Const of cid (* | c *) | Proj of Block * int (* | #k(b) *) | Skonst of cid (* | c# *) | Def of cid (* | d *) | NSDef of cid (* | d (non strict) *) | FVar of name * Exp * Sub (* | F[s] *) | FgnConst of csid * ConDec (* | (foreign constant) *) and Spine = (* Spines: *) Nil (* S ::= Nil *) | App of Exp * Spine (* | U ; S *) | SClo of Spine * Sub (* | S[s] *) and Sub = (* Explicit substitutions: *) Shift of int (* s ::= ^n *) | Dot of Front * Sub (* | Ft.s *) and Front = (* Fronts: *) Idx of int (* Ft ::= k *) | Exp of Exp (* | U *) | Axp of Exp (* | U (assignable) *) | Block of Block (* | _x *) | Undef (* | _ *) and Dec = (* Declarations: *) Dec of name option * Exp (* D ::= x:V *) | BDec of name option * (cid * Sub) (* | v:l[s] *) | ADec of name option * int (* | v[^-d] *) | NDec of name option and Block = (* Blocks: *) Bidx of int (* b ::= v *) | LVar of Block option ref * Sub * (cid * Sub) (* | L(l[^k],t) *) | Inst of Exp list (* | u1, ..., Un *) (* Constraints *) and Cnstr = (* Constraint: *) Solved (* Cnstr ::= solved *) | Eqn of Dec Ctx * Exp * Exp (* | G|-(U1 == U2) *) | FgnCnstr of csid * FgnCnstr (* | (foreign) *) and Status = (* Status of a constant: *) Normal (* inert *) | Constraint of csid * (Dec Ctx * Spine * int -> Exp option) (* acts as constraint *) | Foreign of csid * (Spine -> Exp) (* is converted to foreign *) and FgnUnify = (* Result of foreign unify *) Succeed of FgnUnifyResidual list (* succeed with a list of residual operations *) | Fail and FgnUnifyResidual = (* Residual of foreign unify *) Assign of Dec Ctx * Exp * Exp * Sub (* perform the assignment G |- X = U [ss] *) | Delay of Exp * Cnstr ref (* delay cnstr, associating it with all the rigid EVars in U *) (* Global signature *) and ConDec = (* Constant declaration *) ConDec of string * mid option * int * Status (* a : K : kind or *) * Exp * Uni (* c : A : type *) | ConDef of string * mid option * int (* a = A : K : kind or *) * Exp * Exp * Uni (* d = M : A : type *) * Ancestor (* Ancestor info for d or a *) | AbbrevDef of string * mid option * int (* a = A : K : kind or *) * Exp * Exp * Uni (* d = M : A : type *) | BlockDec of string * mid option (* %block l : SOME G1 PI G2 *) * Dec Ctx * Dec list | BlockDef of string * mid option * cid list (* %block l = (l1 | ... | ln) *) | SkoDec of string * mid option * int (* sa: K : kind or *) * Exp * Uni (* sc: A : type *) and Ancestor = (* Ancestor of d or a *) Anc of cid option * int * cid option (* head(expand(d)), height, head(expand[height](d)) *) (* NONE means expands to {x:A}B *) datatype StrDec = (* Structure declaration *) StrDec of string * mid option (* Form of constant declaration *) datatype ConDecForm = FromCS (* from constraint domain *) | Ordinary (* ordinary declaration *) | Clause (* %clause declaration *) (* Type abbreviations *) type dctx = Dec Ctx (* G = . | G,D *) type eclo = Exp * Sub (* Us = U[s] *) type bclo = Block * Sub (* Bs = B[s] *) type cnstr = Cnstr ref (* exception Error of string (* raised if out of space *) *) structure FgnExpStd = struct structure ToInternal = FgnOpnTable (type arg = unit type result = Exp) structure Map = FgnOpnTable (type arg = Exp -> Exp type result = Exp) structure App = FgnOpnTable (type arg = Exp -> unit type result = unit) structure EqualTo = FgnOpnTable (type arg = Exp type result = bool) structure UnifyWith = FgnOpnTable (type arg = Dec Ctx * Exp type result = FgnUnify) fun fold csfe f b = let val r = ref b fun g U = r := f (U,!r) in App.apply csfe g ; !r end end structure FgnCnstrStd = struct structure ToInternal = FgnOpnTable (type arg = unit type result = (Dec Ctx * Exp) list) structure Awake = FgnOpnTable (type arg = unit type result = bool) structure Simplify = FgnOpnTable (type arg = unit type result = bool) end fun conDecName (ConDec (name, _, _, _, _, _)) = name | conDecName (ConDef (name, _, _, _, _, _, _)) = name | conDecName (AbbrevDef (name, _, _, _, _, _)) = name | conDecName (SkoDec (name, _, _, _, _)) = name | conDecName (BlockDec (name, _, _, _)) = name | conDecName (BlockDef (name, _, _)) = name fun conDecParent (ConDec (_, parent, _, _, _, _)) = parent | conDecParent (ConDef (_, parent, _, _, _, _, _)) = parent | conDecParent (AbbrevDef (_, parent, _, _, _, _)) = parent | conDecParent (SkoDec (_, parent, _, _, _)) = parent | conDecParent (BlockDec (_, parent, _, _)) = parent | conDecParent (BlockDef (_, parent, _)) = parent (* conDecImp (CD) = k Invariant: If CD is either a declaration, definition, abbreviation, or a Skolem constant then k stands for the number of implicit elements. *) fun conDecImp (ConDec (_, _, i, _, _, _)) = i | conDecImp (ConDef (_, _, i, _, _, _, _)) = i | conDecImp (AbbrevDef (_, _, i, _, _, _)) = i | conDecImp (SkoDec (_, _, i, _, _)) = i | conDecImp (BlockDec (_, _, _, _)) = 0 (* watch out -- carsten *) fun conDecStatus (ConDec (_, _, _, status, _, _)) = status | conDecStatus _ = Normal (* conDecType (CD) = V Invariant: If CD is either a declaration, definition, abbreviation, or a Skolem constant then V is the respective type *) fun conDecType (ConDec (_, _, _, _, V, _)) = V | conDecType (ConDef (_, _, _, _, V, _, _)) = V | conDecType (AbbrevDef (_, _, _, _, V, _)) = V | conDecType (SkoDec (_, _, _, V, _)) = V (* conDecBlock (CD) = (Gsome, Lpi) Invariant: If CD is block definition then Gsome is the context of some variables and Lpi is the list of pi variables *) fun conDecBlock (BlockDec (_, _, Gsome, Lpi)) = (Gsome, Lpi) (* conDecUni (CD) = L Invariant: If CD is either a declaration, definition, abbreviation, or a Skolem constant then L is the respective universe *) fun conDecUni (ConDec (_, _, _, _, _, L)) = L | conDecUni (ConDef (_, _, _, _, _, L, _)) = L | conDecUni (AbbrevDef (_, _, _, _, _, L)) = L | conDecUni (SkoDec (_, _, _, _, L)) = L fun strDecName (StrDec (name, _)) = name fun strDecParent (StrDec (_, parent)) = parent local val maxCid = Global.maxCid val dummyEntry = ConDec("", NONE, 0, Normal, Uni (Kind), Kind) val sgnArray = Array.array (maxCid+1, dummyEntry) : ConDec Array.array val nextCid = ref(0) val maxMid = Global.maxMid val sgnStructArray = Array.array (maxMid+1, StrDec("", NONE)) : StrDec Array.array val nextMid = ref (0) in (* Invariants *) (* Constant declarations are all well-typed *) (* Constant declarations are stored in beta-normal form *) (* All definitions are strict in all their arguments *) (* If Const(cid) is valid, then sgnArray(cid) = ConDec _ *) (* If Def(cid) is valid, then sgnArray(cid) = ConDef _ *) fun sgnClean (i) = if i >= !nextCid then () else (Array.update (sgnArray, i, dummyEntry); sgnClean (i+1)) fun sgnReset () = ((* Fri Dec 20 12:04:24 2002 -fp *) (* this circumvents a space leak *) sgnClean (0); nextCid := 0; nextMid := 0) fun sgnSize () = (!nextCid, !nextMid) fun sgnAdd (conDec) = let val cid = !nextCid in if cid > maxCid then raise Error ("Global signature size " ^ Int.toString (maxCid+1) ^ " exceeded") else (Array.update (sgnArray, cid, conDec) ; nextCid := cid + 1; cid) end (* 0 <= cid < !nextCid *) fun sgnLookup (cid) = Array.sub (sgnArray, cid) fun sgnApp (f) = let fun sgnApp' (cid) = if cid = !nextCid then () else (f cid; sgnApp' (cid+1)) in sgnApp' (0) end fun sgnStructAdd (strDec) = let val mid = !nextMid in if mid > maxMid then raise Error ("Global signature size " ^ Int.toString (maxMid+1) ^ " exceeded") else (Array.update (sgnStructArray, mid, strDec) ; nextMid := mid + 1; mid) end (* 0 <= mid < !nextMid *) fun sgnStructLookup (mid) = Array.sub (sgnStructArray, mid) (* A hack used in Flit - jcreed 6/05 *) fun rename (cid, new) = let val newConDec = case sgnLookup cid of ConDec (n,m,i,s,e,u) => ConDec(new,m,i,s,e,u) | ConDef (n,m,i,e,e',u,a) => ConDef(new,m,i,e,e',u,a) | AbbrevDef (n,m,i,e,e',u) => AbbrevDef (new,m,i,e,e',u) | BlockDec (n,m,d,d') => BlockDec (new,m,d,d') | SkoDec (n,m,i,e,u) => SkoDec (new,m,i,e,u) in Array.update (sgnArray, cid, newConDec) end end fun constDef (d) = (case sgnLookup (d) of ConDef(_, _, _, U,_, _, _) => U | AbbrevDef (_, _, _, U,_, _) => U) fun constType (c) = conDecType (sgnLookup c) fun constImp (c) = conDecImp (sgnLookup c) fun constUni (c) = conDecUni (sgnLookup c) fun constBlock (c) = conDecBlock (sgnLookup c) fun constStatus (c) = (case sgnLookup (c) of ConDec (_, _, _, status, _, _) => status | _ => Normal) (* Explicit Substitutions *) (* id = ^0 Invariant: G |- id : G id is patsub *) val id = Shift(0) (* shift = ^1 Invariant: G, V |- ^ : G ^ is patsub *) val shift = Shift(1) (* invShift = ^-1 = _.^0 Invariant: G |- ^-1 : G, V ^-1 is patsub *) val invShift = Dot(Undef, id) (* comp (s1, s2) = s' Invariant: If G' |- s1 : G and G'' |- s2 : G' then s' = s1 o s2 and G'' |- s1 o s2 : G If s1, s2 patsub then s' patsub *) fun comp (Shift (0), s) = s (* next line is an optimization *) (* roughly 15% on standard suite for Twelf 1.1 *) (* Sat Feb 14 10:15:16 1998 -fp *) | comp (s, Shift (0)) = s | comp (Shift (n), Dot (Ft, s)) = comp (Shift (n-1), s) | comp (Shift (n), Shift (m)) = Shift (n+m) | comp (Dot (Ft, s), s') = Dot (frontSub (Ft, s'), comp (s, s')) (* bvarSub (n, s) = Ft' Invariant: If G |- s : G' G' |- n : V then Ft' = Ftn if s = Ft1 .. Ftn .. ^k or Ft' = ^(n+k) if s = Ft1 .. Ftm ^k and m Bidx k' | Block B => B) | blockSub (LVar (ref (SOME B), sk, _), s) = blockSub (B, comp (sk, s)) (* -fp Sun Dec 1 21:18:30 2002 *) (* --cs Sun Dec 1 11:25:41 2002 *) (* Since always . |- t : Gsome, discard s *) (* where is this needed? *) (* Thu Dec 6 20:30:26 2001 -fp !!! *) | blockSub (LVar (r as ref NONE, sk, (l, t)), s) = LVar(r, comp(sk, s), (l, t)) (* was: LVar (r, comp(sk, s), (l, comp (t, s))) July 22, 2010 -fp -cs *) (* comp(^k, s) = ^k' for some k' by invariant *) | blockSub (L as Inst ULs, s') = Inst (map (fn U => EClo (U, s')) ULs) (* this should be right but somebody should verify *) (* frontSub (Ft, s) = Ft' Invariant: If G |- s : G' G' |- Ft : V then Ft' = Ft [s] and G |- Ft' : V [s] NOTE: EClo (U, s) might be undefined, so if this is ever computed eagerly, we must introduce an "Undefined" exception, raise it in whnf and handle it here so Exp (EClo (U, s)) => Undef *) and frontSub (Idx (n), s) = bvarSub (n, s) | frontSub (Exp (U), s) = Exp (EClo (U, s)) | frontSub (Undef, s) = Undef | frontSub (Block (B), s) = Block (blockSub (B, s)) (* decSub (x:V, s) = D' Invariant: If G |- s : G' G' |- V : L then D' = x:V[s] and G |- V[s] : L *) (* First line is an optimization suggested by cs *) (* D[id] = D *) (* Sat Feb 14 18:37:44 1998 -fp *) (* seems to have no statistically significant effect *) (* undo for now Sat Feb 14 20:22:29 1998 -fp *) (* fun decSub (D, Shift(0)) = D | decSub (Dec (x, V), s) = Dec (x, EClo (V, s)) *) fun decSub (Dec (x, V), s) = Dec (x, EClo (V, s)) | decSub (NDec x, s) = NDec x | decSub (BDec (n, (l, t)), s) = BDec (n, (l, comp (t, s))) (* dot1 (s) = s' Invariant: If G |- s : G' then s' = 1. (s o ^) and for all V s.t. G' |- V : L G, V[s] |- s' : G', V If s patsub then s' patsub *) (* first line is an optimization *) (* roughly 15% on standard suite for Twelf 1.1 *) (* Sat Feb 14 10:16:16 1998 -fp *) fun dot1 (s as Shift (0)) = s | dot1 s = Dot (Idx(1), comp(s, shift)) (* invDot1 (s) = s' invDot1 (1. s' o ^) = s' Invariant: s = 1 . s' o ^ If G' |- s' : G (so G',V[s] |- s : G,V) *) fun invDot1 (s) = comp (comp(shift, s), invShift) (* Declaration Contexts *) (* ctxDec (G, k) = x:V Invariant: If |G| >= k, where |G| is size of G, then G |- k : V and G |- V : L *) fun ctxDec (G, k) = let (* ctxDec' (G'', k') = x:V where G |- ^(k-k') : G'', 1 <= k' <= k *) fun ctxDec' (Decl (G', Dec (x, V')), 1) = Dec (x, EClo (V', Shift (k))) | ctxDec' (Decl (G', BDec (n, (l, s))), 1) = BDec (n, (l, comp (s, Shift (k)))) | ctxDec' (Decl (G', _), k') = ctxDec' (G', k'-1) (* ctxDec' (Null, k') should not occur by invariant *) in ctxDec' (G, k) end (* blockDec (G, v, i) = V Invariant: If G (v) = l[s] and Sigma (l) = SOME Gsome BLOCK Lblock and G |- s : Gsome then G |- pi (v, i) : V *) fun blockDec (G, v as (Bidx k), i) = let val BDec (_, (l, s)) = ctxDec (G, k) (* G |- s : Gsome *) val (Gsome, Lblock) = conDecBlock (sgnLookup l) fun blockDec' (t, D :: L, 1, j) = decSub (D, t) | blockDec' (t, _ :: L, n, j) = blockDec' (Dot (Exp (Root (Proj (v, j), Nil)), t), L, n-1, j+1) in blockDec' (s, Lblock, i, 1) end (* EVar related functions *) (* newEVar (G, V) = newEVarCnstr (G, V, nil) *) fun newEVar (G, V) = EVar(ref NONE, G, V, ref nil) (* newAVar G = new AVar (assignable variable) *) (* AVars carry no type, ctx, or cnstr *) fun newAVar () = AVar(ref NONE) (* newTypeVar (G) = X, X new where G |- X : type *) fun newTypeVar (G) = EVar(ref NONE, G, Uni(Type), ref nil) (* newLVar (l, s) = (l[s]) *) fun newLVar (sk, (cid, t)) = LVar (ref NONE, sk, (cid, t)) (* Definition related functions *) (* headOpt (U) = SOME(H) or NONE, U should be strict, normal *) fun headOpt (Root (H, _)) = SOME(H) | headOpt (Lam (_, U)) = headOpt U | headOpt _ = NONE fun ancestor' (NONE) = Anc(NONE, 0, NONE) | ancestor' (SOME(Const(c))) = Anc(SOME(c), 1, SOME(c)) | ancestor' (SOME(Def(d))) = (case sgnLookup(d) of ConDef(_, _, _, _, _, _, Anc(_, height, cOpt)) => Anc(SOME(d), height+1, cOpt)) | ancestor' (SOME _) = (* FgnConst possible, BVar impossible by strictness *) Anc(NONE, 0, NONE) (* ancestor(U) = ancestor info for d = U *) fun ancestor (U) = ancestor' (headOpt U) (* defAncestor(d) = ancestor of d, d must be defined *) fun defAncestor (d) = (case sgnLookup(d) of ConDef(_, _, _, _, _, _, anc) => anc) (* Type related functions *) (* targetHeadOpt (V) = SOME(H) or NONE where H is the head of the atomic target type of V, NONE if V is a kind or object or have variable type. Does not expand type definitions. *) (* should there possibly be a FgnConst case? also targetFamOpt -kw *) fun targetHeadOpt (Root (H, _)) = SOME(H) | targetHeadOpt (Pi(_, V)) = targetHeadOpt V | targetHeadOpt (Redex (V, S)) = targetHeadOpt V | targetHeadOpt (Lam (_, V)) = targetHeadOpt V | targetHeadOpt (EVar (ref (SOME(V)),_,_,_)) = targetHeadOpt V | targetHeadOpt (EClo (V, s)) = targetHeadOpt V | targetHeadOpt _ = NONE (* Root(Bvar _, _), Root(FVar _, _), Root(FgnConst _, _), EVar(ref NONE,..), Uni, FgnExp _ *) (* Root(Skonst _, _) can't occur *) (* targetHead (A) = a as in targetHeadOpt, except V must be a valid type *) fun targetHead (A) = valOf (targetHeadOpt A) (* targetFamOpt (V) = SOME(cid) or NONE where cid is the type family of the atomic target type of V, NONE if V is a kind or object or have variable type. Does expand type definitions. *) fun targetFamOpt (Root (Const(cid), _)) = SOME(cid) | targetFamOpt (Pi(_, V)) = targetFamOpt V | targetFamOpt (Root (Def(cid), _)) = targetFamOpt (constDef cid) | targetFamOpt (Redex (V, S)) = targetFamOpt V | targetFamOpt (Lam (_, V)) = targetFamOpt V | targetFamOpt (EVar (ref (SOME(V)),_,_,_)) = targetFamOpt V | targetFamOpt (EClo (V, s)) = targetFamOpt V | targetFamOpt _ = NONE (* Root(Bvar _, _), Root(FVar _, _), Root(FgnConst _, _), EVar(ref NONE,..), Uni, FgnExp _ *) (* Root(Skonst _, _) can't occur *) (* targetFam (A) = a as in targetFamOpt, except V must be a valid type *) fun targetFam (A) = valOf (targetFamOpt A) end; (* functor IntSyn *) structure IntSyn :> INTSYN = IntSyn (structure Global = Global); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/intsyn.sig000066400000000000000000000264001250413007300257220ustar00rootroot00000000000000(* Internal Syntax *) (* Author: Frank Pfenning, Carsten Schuermann *) (* Modified: Roberto Virga *) signature INTSYN = sig type cid = int (* Constant identifier *) type mid = int (* Structure identifier *) type csid = int (* CS module identifier *) type FgnExp = exn (* foreign expression representation *) exception UnexpectedFgnExp of FgnExp (* raised by a constraint solver if passed an incorrect arg *) type FgnCnstr = exn (* foreign constraint representation *) exception UnexpectedFgnCnstr of FgnCnstr (* raised by a constraint solver if passed an incorrect arg *) (* Contexts *) datatype 'a Ctx = (* Contexts *) Null (* G ::= . *) | Decl of 'a Ctx * 'a (* | G, D *) val ctxPop : 'a Ctx -> 'a Ctx val ctxLookup: 'a Ctx * int -> 'a val ctxLength: 'a Ctx -> int datatype Depend = (* Dependency information *) No (* P ::= No *) | Maybe (* | Maybe *) | Meta (* | Meta *) (* expressions *) datatype Uni = (* Universes: *) Kind (* L ::= Kind *) | Type (* | Type *) datatype Exp = (* Expressions: *) Uni of Uni (* U ::= L *) | Pi of (Dec * Depend) * Exp (* | Pi (D, P). V *) | Root of Head * Spine (* | H @ S *) | Redex of Exp * Spine (* | U @ S *) | Lam of Dec * Exp (* | lam D. U *) | EVar of Exp option ref * Dec Ctx * Exp * (Cnstr ref) list ref (* | X : G|-V, Cnstr *) | EClo of Exp * Sub (* | U[s] *) | AVar of Exp option ref (* | A *) | FgnExp of csid * FgnExp (* | (foreign expression) *) | NVar of int (* | n (linear, fully applied variable used in indexing *) and Head = (* Head: *) BVar of int (* H ::= k *) | Const of cid (* | c *) | Proj of Block * int (* | #k(b) *) | Skonst of cid (* | c# *) | Def of cid (* | d (strict) *) | NSDef of cid (* | d (non strict) *) | FVar of string * Exp * Sub (* | F[s] *) | FgnConst of csid * ConDec (* | (foreign constant) *) and Spine = (* Spines: *) Nil (* S ::= Nil *) | App of Exp * Spine (* | U ; S *) | SClo of Spine * Sub (* | S[s] *) and Sub = (* Explicit substitutions: *) Shift of int (* s ::= ^n *) | Dot of Front * Sub (* | Ft.s *) and Front = (* Fronts: *) Idx of int (* Ft ::= k *) | Exp of Exp (* | U *) | Axp of Exp (* | U *) | Block of Block (* | _x *) | Undef (* | _ *) and Dec = (* Declarations: *) Dec of string option * Exp (* D ::= x:V *) | BDec of string option * (cid * Sub) (* | v:l[s] *) | ADec of string option * int (* | v[^-d] *) | NDec of string option and Block = (* Blocks: *) Bidx of int (* b ::= v *) | LVar of Block option ref * Sub * (cid * Sub) (* | L(l[^k],t) *) | Inst of Exp list (* | U1, ..., Un *) (* It would be better to consider having projections count like substitutions, then we could have Inst of Sub here, which would simplify a lot of things. I suggest however to wait until the next big overhaul of the system -- cs *) (* | BClo of Block * Sub (* | b[s] *) *) (* constraints *) and Cnstr = (* Constraint: *) Solved (* Cnstr ::= solved *) | Eqn of Dec Ctx * Exp * Exp (* | G|-(U1 == U2) *) | FgnCnstr of csid * FgnCnstr (* | (foreign) *) and Status = (* Status of a constant: *) Normal (* inert *) | Constraint of csid * (Dec Ctx * Spine * int -> Exp option) (* acts as constraint *) | Foreign of csid * (Spine -> Exp) (* is converted to foreign *) and FgnUnify = (* Result of foreign unify *) Succeed of FgnUnifyResidual list (* succeed with a list of residual operations *) | Fail and FgnUnifyResidual = Assign of Dec Ctx * Exp * Exp * Sub (* perform the assignment G |- X = U [ss] *) | Delay of Exp * Cnstr ref (* delay cnstr, associating it with all the rigid EVars in U *) (* Global signature *) and ConDec = (* Constant declaration *) ConDec of string * mid option * int * Status (* a : K : kind or *) * Exp * Uni (* c : A : type *) | ConDef of string * mid option * int (* a = A : K : kind or *) * Exp * Exp * Uni (* d = M : A : type *) * Ancestor (* Ancestor info for d or a *) | AbbrevDef of string * mid option * int (* a = A : K : kind or *) * Exp * Exp * Uni (* d = M : A : type *) | BlockDec of string * mid option (* %block l : SOME G1 PI G2 *) * Dec Ctx * Dec list | BlockDef of string * mid option * cid list (* %block l = (l1 | ... | ln) *) | SkoDec of string * mid option * int (* sa: K : kind or *) * Exp * Uni (* sc: A : type *) and Ancestor = (* Ancestor of d or a *) Anc of cid option * int * cid option (* head(expand(d)), height, head(expand[height](d)) *) (* NONE means expands to {x:A}B *) datatype StrDec = (* Structure declaration *) StrDec of string * mid option (* Form of constant declaration *) datatype ConDecForm = FromCS (* from constraint domain *) | Ordinary (* ordinary declaration *) | Clause (* %clause declaration *) (* Type abbreviations *) type dctx = Dec Ctx (* G = . | G,D *) type eclo = Exp * Sub (* Us = U[s] *) type bclo = Block * Sub (* Bs = B[s] *) type cnstr = Cnstr ref exception Error of string (* raised if out of space *) (* standard operations on foreign expressions *) structure FgnExpStd : sig (* convert to internal syntax *) structure ToInternal : FGN_OPN where type arg = unit where type result = Exp (* apply function to subterms *) structure Map : FGN_OPN where type arg = Exp -> Exp where type result = Exp (* apply function to subterms, for effect *) structure App : FGN_OPN where type arg = Exp -> unit where type result = unit (* test for equality *) structure EqualTo : FGN_OPN where type arg = Exp where type result = bool (* unify with another term *) structure UnifyWith : FGN_OPN where type arg = Dec Ctx * Exp where type result = FgnUnify (* fold a function over the subterms *) val fold : (csid * FgnExp) -> (Exp * 'a -> 'a) -> 'a -> 'a end (* standard operations on foreign constraints *) structure FgnCnstrStd : sig (* convert to internal syntax *) structure ToInternal : FGN_OPN where type arg = unit where type result = (Dec Ctx * Exp) list (* awake *) structure Awake : FGN_OPN where type arg = unit where type result = bool (* simplify *) structure Simplify : FGN_OPN where type arg = unit where type result = bool end val conDecName : ConDec -> string val conDecParent : ConDec -> mid option val conDecImp : ConDec -> int val conDecStatus : ConDec -> Status val conDecType : ConDec -> Exp val conDecBlock : ConDec -> dctx * Dec list val conDecUni : ConDec -> Uni val strDecName : StrDec -> string val strDecParent : StrDec -> mid option val sgnReset : unit -> unit val sgnSize : unit -> cid * mid val sgnAdd : ConDec -> cid val sgnLookup: cid -> ConDec val sgnApp : (cid -> unit) -> unit val sgnStructAdd : StrDec -> mid val sgnStructLookup : mid -> StrDec val constType : cid -> Exp (* type of c or d *) val constDef : cid -> Exp (* definition of d *) val constImp : cid -> int val constStatus : cid -> Status val constUni : cid -> Uni val constBlock : cid -> dctx * Dec list (* Declaration Contexts *) val ctxDec : dctx * int -> Dec (* get variable declaration *) val blockDec : dctx * Block * int -> Dec (* Explicit substitutions *) val id : Sub (* id *) val shift : Sub (* ^ *) val invShift : Sub (* ^-1 *) val bvarSub : int * Sub -> Front (* k[s] *) val frontSub : Front * Sub -> Front (* H[s] *) val decSub : Dec * Sub -> Dec (* x:V[s] *) val blockSub : Block * Sub -> Block (* B[s] *) val comp : Sub * Sub -> Sub (* s o s' *) val dot1 : Sub -> Sub (* 1 . (s o ^) *) val invDot1 : Sub -> Sub (* (^ o s) o ^-1) *) (* EVar related functions *) val newEVar : dctx * Exp -> Exp (* creates X:G|-V, [] *) val newAVar : unit -> Exp (* creates A (bare) *) val newTypeVar : dctx -> Exp (* creates X:G|-type, [] *) val newLVar : Sub * (cid * Sub) -> Block (* creates B:(l[^k],t) *) (* Definition related functions *) val headOpt : Exp -> Head option val ancestor : Exp -> Ancestor val defAncestor : cid -> Ancestor (* Type related functions *) (* Not expanding type definitions *) val targetHeadOpt : Exp -> Head option (* target type family or NONE *) val targetHead : Exp -> Head (* target type family *) (* Expanding type definitions *) val targetFamOpt : Exp -> cid option (* target type family or NONE *) val targetFam : Exp -> cid (* target type family *) (* Used in Flit *) val rename : cid * string -> unit end; (* signature INTSYN *) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/irb_heredoc000066400000000000000000000001641250413007300260610ustar00rootroot00000000000000irb(main):001:0> puts < nil irb(main):005:0> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/irc.lsp000077500000000000000000000220331250413007300251700ustar00rootroot00000000000000#!/usr/bin/env newlisp ;; @module IRC ;; @description a basic irc library ;; @version early alpha! 0.1 2011-10-31 14:21:26 ;; @author cormullion ;; Usage: ;; (IRC:init "newlithper") ; a username/nick (not that one obviously :-) ;; (IRC:connect "irc.freenode.net" 6667) ; irc/server ;; (IRC:join-channel {#newlisp}) ; join a room ;; either (IRC:read-irc-loop) ; loop - monitor only, no input ;; or (IRC:session) ; a command-line session, end with /QUIT (context 'IRC) (define Inickname) (define Ichannels) (define Iserver) (define Iconnected) (define Icallbacks '()) (define Idle-time 400) ; seconds (define Itime-stamp) ; time since last message was processed (define (register-callback callback-name callback-function) (println {registering callback for } callback-name { : } (sym (term callback-function) (prefix callback-function))) (push (list callback-name (sym (term callback-function) (prefix callback-function))) Icallbacks)) (define (do-callback callback-name data) (when (set 'func (lookup callback-name Icallbacks)) ; find first callback (if-not (catch (apply func (list data)) 'error) (println {error in callback } callback-name {: } error)))) (define (do-callbacks callback-name data) (dolist (rf (ref-all callback-name Icallbacks)) (set 'callback-entry (Icallbacks (first rf))) (when (set 'func (last callback-entry)) (if-not (catch (apply func (list data)) 'error) (println {error in callback } callback-name {: } error))))) (define (init str) (set 'Inickname str) (set 'Iconnected nil) (set 'Ichannels '()) (set 'Itime-stamp (time-of-day))) (define (connect server port) (set 'Iserver (net-connect server port)) (net-send Iserver (format "USER %s %s %s :%s\r\n" Inickname Inickname Inickname Inickname)) (net-send Iserver (format "NICK %s \r\n" Inickname)) (set 'Iconnected true) (do-callbacks "connect" (list (list "server" server) (list "port" port)))) (define (identify password) (net-send Iserver (format "PRIVMSG nickserv :identify %s\r\n" password))) (define (join-channel channel) (when (net-send Iserver (format "JOIN %s \r\n" channel)) (push channel Ichannels) (do-callbacks "join-channel" (list (list "channel" channel) (list "nickname" Inickname))))) (define (part chan) (if-not (empty? chan) ; leave specified (begin (net-send Iserver (format "PART %s\r\n" chan)) (replace channel Ichannels) (do-callbacks "part" (list (list "channel" channel)))) ; leave all (begin (dolist (channel Ichannels) (net-send Iserver (format "PART %s\r\n" channel)) (replace channel Ichannels) (do-callbacks "part" (list (list "channel" channel))))))) (define (do-quit message) (do-callbacks "quit" '()) ; chance to do stuff before quit... (net-send Iserver (format "QUIT :%s\r\n" message)) (sleep 1000) (set 'Ichannels '()) (close Iserver) (set 'Iconnected nil)) (define (privmsg user message) (net-send Iserver (format "PRIVMSG %s :%s\r\n" user message))) (define (notice user message) (net-send Iserver (format "NOTICE %s :%s\r\n" user message))) (define (send-to-server message (channel nil)) (cond ((starts-with message {/}) ; default command character (set 'the-message (replace "^/" (copy message) {} 0)) ; keep original (net-send Iserver (format "%s \r\n" the-message)) ; send it ; do a quit (if (starts-with (lower-case the-message) "quit") (do-quit { enough}))) (true (if (nil? channel) ; say to all channels (dolist (c Ichannels) (net-send Iserver (format "PRIVMSG %s :%s\r\n" c message))) ; say to specified channel (if (find channel Ichannels) (net-send Iserver (format "PRIVMSG %s :%s\r\n" channel message)))))) (do-callbacks "send-to-server" (list (list "channel" channel) (list "message" message)))) (define (process-command sender command text) (cond ((= sender "PING") (net-send Iserver (format "PONG %s\r\n" command))) ((or (= command "NOTICE") (= command "PRIVMSG")) (process-message sender command text)) ((= command "JOIN") (set 'username (first (clean empty? (parse sender {!|:} 0)))) (set 'channel (last (clean empty? (parse sender {!|:} 0)))) (println {username } username { joined } channel) (do-callbacks "join" (list (list "channel" channel) (list "username" username)))) (true nil))) (define (process-message sender command text) (let ((username {} target {} message {})) (set 'username (first (clean empty? (parse sender {!|:} 0)))) (set 'target (trim (first (clean empty? (parse text {!|:} 0))))) (set 'message (slice text (+ (find {:} text) 1))) (cond ((starts-with message "\001") (process-ctcp username target message)) ((find target Ichannels) (cond ((= command {PRIVMSG}) (do-callbacks "channel-message" (list (list "channel" target) (list "username" username) (list "message" message)))) ((= command {NOTICE}) (do-callbacks "channel-notice" (list (list "channel" target) (list "username" username) (list "message" message)))))) ((= target Inickname) (cond ((= command {PRIVMSG}) (do-callbacks "private-message" (list (list "username" username) (list "message" message)))) ((= command {NOTICE}) (do-callbacks "private-notice" (list (list "username" username) (list "message" message)))))) (true nil)))) (define (process-ctcp username target message) (cond ((starts-with message "\001VERSION\001") (net-send Iserver (format "NOTICE %s :\001VERSION %s\001\r\n" username version))) ((starts-with message "\001PING") (set 'data (first (rest (clean empty? (parse message { } 0))))) (set 'data (trim data "\001" "\001")) (net-send Iserver (format "NOTICE %s :\001PING %s\001\r\n" username data))) ((starts-with message "\001ACTION") (set 'data (first (rest (clean empty? (parse message { } 0))))) (set 'data (join data { })) (set 'data (trim data "\001" "\001")) (if (find target Ichannels) (do-callbacks "channel-action" (list (list "username" username) (list "message" message)))) (if (= target Inickname) (do-callbacks "private-action" (list (list "username" username) (list "message" message))))) ((starts-with message "\001TIME\001") (net-send Iserver (format "NOTICE %s:\001TIME :%s\001\r\n" username (date)))))) (define (parse-buffer raw-buffer) (let ((messages (clean empty? (parse raw-buffer "\r\n" 0))) (sender {} command {} text {})) ; check for elapsed time since last activity (when (> (sub (time-of-day) Itime-stamp) (mul Idle-time 1000)) (do-callbacks "idle-event") (set 'Itime-stamp (time-of-day))) (dolist (message messages) (set 'message-parts (parse message { })) (unless (empty? message-parts) (set 'sender (first message-parts)) (catch (set 'command (first (rest message-parts))) 'error) (catch (set 'text (join (rest (rest message-parts)) { })) 'error)) (process-command sender command text)))) (define (read-irc) (let ((buffer {})) (when (!= (net-peek Iserver) 0) (net-receive Iserver buffer 8192 "\n") (unless (empty? buffer) (parse-buffer buffer))))) (define (read-irc-loop) ; monitoring (let ((buffer {})) (while Iconnected (read-irc) (sleep 1000)))) (define (print-raw-message data) ; example of using a callback (set 'raw-data (lookup "message" data)) (set 'channel (lookup "channel" data)) (set 'message-text raw-data) (println (date (date-value) 0 {%H:%M:%S }) username {> } message-text)) (define (print-outgoing-message data) (set 'raw-data (lookup "message" data)) (set 'channel (lookup "channel" data)) (set 'message-text raw-data) (println (date (date-value) 0 {%H:%M:%S }) Inickname {> } message-text)) (define (session); interactive terminal ; must add callbacks to display messages (register-callback "channel-message" 'print-raw-message) (register-callback "send-to-server" 'print-outgoing-message) (while Iconnected (while (zero? (peek 0)) (read-irc)) (send-to-server (string (read-line 0)))) (println {finished session } (date)) (exit)) ; end of IRC code pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/java.properties000066400000000000000000000001601250413007300267240ustar00rootroot00000000000000foo = bar foo: bar foo.oof: \ bar=baz; \ asdf // comment # comment ; comment x:a\ b x: a \ b x = \ pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/jbst_example1.jbst000066400000000000000000000015301250413007300273110ustar00rootroot00000000000000<%@ Control Name="MyApp.MyJbstControl" Language="JavaScript" %> <%! /* initialization code block, executed only once as control is loaded */ /* alternate syntax to script block above */ this.myInitTime = this.generateValue(); %> <% /* data binding code block, executed each time as control is data bound */ this.myBindTime = this.generateValue(); %> <%-- JBST Comment --%> <%= this.myBindTime /* data binding expression */ %> <%= this.myInitTime /* data binding expression */ %> <%$ Resources: localizationKey %><%-- JBST globalization--%>pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/jbst_example2.jbst000066400000000000000000000025231250413007300273150ustar00rootroot00000000000000<%@ Control Name="Foo.MyZebraList" Language="JavaScript" %>

<%= this.data.title %> as of <%= this.formatTime(this.data.timestamp) %>!

<%= this.data.description %>

  • <%= this.data.label %> (<%= this.index+1 %> of <%= this.count %>)
pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/jinjadesignerdoc.rst000066400000000000000000000556601250413007300277400ustar00rootroot00000000000000====================== Designer Documentation ====================== This part of the Jinja documentaton is meant for template designers. Basics ====== The Jinja template language is designed to strike a balance between content and application logic. Nevertheless you can use a python like statement language. You don't have to know how Python works to create Jinja templates, but if you know it you can use some additional statements you may know from Python. Here is a small example template: .. sourcecode:: html+jinja My Webpage

My Webpage

{{ variable }} This covers the default settings. The application developer might have changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar. This documentation just covers the default values. A variable looks like ``{{ foobar }}`` where foobar is the variable name. Inside of statements (``{% some content here %}``) variables are just normal names without the braces around it. In fact ``{{ foobar }}`` is just an alias for the statement ``{% print foobar %}``. Variables are coming from the context provided by the application. Normally there should be a documentation regarding the context contents but if you want to know the content of the current context, you can add this to your template: .. sourcecode:: html+jinja
{{ debug()|e }}
A context isn't flat which means that each variable can has subvariables, as long as it is representable as python data structure. You can access attributes of a variable using the dot and bracket operators. The following examples show this: .. sourcecode:: jinja {{ user.username }} is the same as {{ user['username'] }} you can also use a variable to access an attribute: {{ users[current_user].username }} If you have numerical indices you have to use the [] syntax: {{ users[0].username }} Filters ======= In the examples above you might have noticed the pipe symbols. Pipe symbols tell the engine that it has to apply a filter on the variable. Here is a small example: .. sourcecode:: jinja {{ variable|replace('foo', 'bar')|escape }} If you want, you can also put whitespace between the filters. This will look for a variable `variable`, pass it to the filter `replace` with the arguments ``'foo'`` and ``'bar'``, and pass the result to the filter `escape` that automatically XML-escapes the value. The `e` filter is an alias for `escape`. Here is the complete list of supported filters: [[list_of_filters]] .. admonition:: note Filters have a pretty low priority. If you want to add fitered values you have to put them into parentheses. The same applies if you want to access attributes: .. sourcecode:: jinja correct: {{ (foo|filter) + (bar|filter) }} wrong: {{ foo|filter + bar|filter }} correct: {{ (foo|filter).attribute }} wrong: {{ foo|filter.attribute }} Tests ===== You can use the `is` operator to perform tests on a value: .. sourcecode:: jinja {{ 42 is numeric }} -> true {{ "foobar" is numeric }} -> false {{ 'FOO' is upper }} -> true These tests are especially useful when used in `if` conditions. [[list_of_tests]] Global Functions ================ Test functions and filter functions live in their own namespace. Global functions not. They behave like normal objects in the context. Beside the functions added by the application or framewhere there are two functions available per default: `range` Works like the python `range function`_ just that it doesn't support ranges greater than ``1000000``. `debug` Function that outputs the contents of the context. Loops ===== To iterate over a sequence, you can use the `for` loop. It basically looks like a normal Python `for` loop and works pretty much the same: .. sourcecode:: html+jinja

Members

    {% for user in users %}
  • {{ loop.index }} / {{ loop.length }} - {{ user.username|escape }}
  • {% else %}
  • no users found
  • {% endfor %}
*Important* Contrary to Python is the optional ``else`` block only executed if there was no iteration because the sequence was empty. Inside of a `for` loop block you can access some special variables: +----------------------+----------------------------------------+ | Variable | Description | +======================+========================================+ | `loop.index` | The current iteration of the loop. | +----------------------+----------------------------------------+ | `loop.index0` | The current iteration of the loop, | | | starting counting by 0. | +----------------------+----------------------------------------+ | `loop.revindex` | The number of iterations from the end | | | of the loop. | +----------------------+----------------------------------------+ | `loop.revindex0` | The number of iterations from the end | | | of the loop, starting counting by 0. | +----------------------+----------------------------------------+ | `loop.first` | True if first iteration. | +----------------------+----------------------------------------+ | `loop.last` | True if last iteration. | +----------------------+----------------------------------------+ | `loop.even` | True if current iteration is even. | +----------------------+----------------------------------------+ | `loop.odd` | True if current iteration is odd. | +----------------------+----------------------------------------+ | `loop.length` | Total number of items in the sequence. | +----------------------+----------------------------------------+ | `loop.parent` | The context of the parent loop. | +----------------------+----------------------------------------+ Loops also support recursion. Let's assume you have a sitemap where each item might have a number of child items. A template for that could look like this: .. sourcecode:: html+jinja

Sitemap
    {% for item in sitemap recursive %}
  • {{ item.title|e }} {% if item.children %}
      {{ loop(item.children) }}
    {% endif %}
  • {% endfor %}
What happens here? Basically the first thing that is different to a normal loop is the additional ``recursive`` modifier in the `for`-loop declaration. It tells the template engine that we want recursion. If recursion is enabled the special `loop` variable is callable. If you call it with a sequence it will automatically render the loop at that position with the new sequence as argument. Cycling ======= Sometimes you might want to have different text snippets for each row in a list, for example to have alternating row colors. You can easily do this by using the ``{% cycle %}`` tag: .. sourcecode:: html+jinja
    {% for message in messages %}
  • {{ message|e }}
  • {% endfor %}
Each time Jinja encounters a `cycle` tag it will cycle through the list of given items and return the next one. If you pass it one item jinja assumes that this item is a sequence from the context and uses this: .. sourcecode:: html+jinja
  • ...
  • Conditions ========== Jinja supports Python-like `if` / `elif` / `else` constructs: .. sourcecode:: jinja {% if user.active %} user {{ user.name|e }} is active. {% elif user.deleted %} user {{ user.name|e }} was deleted some time ago. {% else %} i don't know what's wrong with {{ user.username|e }} {% endif %} If the user is active the first block is rendered. If not and the user was deleted the second one, in all other cases the third one. You can also use comparison operators: .. sourcecode:: html+jinja {% if amount < 0 %} {{ amount }} {% else %} {{ amount }} {% endif %} .. admonition:: Note Of course you can use `or` / `and` and parentheses to create more complex conditions, but usually the logic is already handled in the application and you don't have to create such complex constructs in the template code. However in some situations it might be a good thing to have the abilities to create them. Operators ========= Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can can use expressions. In expressions you can use any of the following operators: ======= =================================================================== ``+`` add the right operand to the left one. ``{{ 1 + 2 }}`` would return ``3``. ``-`` subtract the right operand from the left one. ``{{ 1 - 1 }}`` would return ``0``. ``/`` divide the left operand by the right one. ``{{ 1 / 2 }}`` would return ``0.5``. ``*`` multiply the left operand with the right one. ``{{ 2 * 2 }}`` would return ``4``. ``**`` raise the left operand to the power of the right operand. ``{{ 2**3 }}`` would return ``8``. ``in`` perform sequence membership test. ``{{ 1 in [1,2,3] }}`` would return true. ``is`` perform a test on the value. See the section about tests for more information. ``|`` apply a filter on the value. See the section about filters for more information. ``and`` return true if the left and the right operand is true. ``or`` return true if the left or the right operand is true. ``not`` negate a statement (see below) ``()`` call a callable: ``{{ user.get_username() }}``. Inside of the parentheses you can use variables: ``{{ user.get(username) }}``. ======= =================================================================== Note that there is no support for any bit operations or something similar. * special note regarding `not`: The `is` and `in` operators support negation using an infix notation too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar`` and ``not foo in bar``. All other expressions require a prefix notation: ``not (foo and bar)``. Boolean Values ============== In If-Conditions Jinja performs a boolean check. All empty values (eg: empty lists ``[]``, empty dicts ``{}`` etc) evaluate to `false`. Numbers that are equal to `0`/`0.00` are considered `false` too. The boolean value of other objects depends on the behavior the application developer gave it. Usually items are `true`. Here some examples that should explain it: .. sourcecode:: jinja {% if [] %} will always be false because it's an empty list {% if {} %} false too. {% if ['foo'] %} this is true. Because the list is not empty. {% if "foobar" %} this is also true because the string is not empty. Slicing ======= Some objects support slicing operations. For example lists: .. sourcecode:: jinja {% for item in items[:5] %} This will only iterate over the first 5 items of the list {% for item in items[5:10] %} This will only iterate from item 5 to 10. {% for item in items[:10:2] %} This will only yield items from start to ten and only returing even items. For more informations about slicing have a look at the `slicing chapter`_ in the "Dive into Python" e-book. Macros ====== If you want to use a partial template in more than one place, you might want to create a macro from it: .. sourcecode:: html+jinja {% macro show_user user %}

    {{ user.name|e }}

    {{ user.description }}
    {% endmacro %} Now you can use it from everywhere in the code by passing it an item: .. sourcecode:: jinja {% for user in users %} {{ show_user(user) }} {% endfor %} You can also specify more than one value: .. sourcecode:: html+jinja {% macro show_dialog title, text %}

    {{ title|e }}

    {{ text|e }}
    {% endmacro %} {{ show_dialog('Warning', 'something went wrong i guess') }} Inheritance =========== The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines **blocks** that child templates can override. Sounds complicated but is very basic. It's easiest to understand it by starting with an example. Base Template ------------- This template, which we'll call ``base.html``, defines a simple HTML skeleton document that you might use for a simple two-column page. It's the job of "child" templates to fill the empty blocks with content: .. sourcecode:: html+jinja {% block title %}{% endblock %} - My Webpage {% block html_head %}{% endblock %}
    {% block content %}{% endblock %}
    In this example, the ``{% block %}`` tags define four blocks that child templates can fill in. All the `block` tag does is to tell the template engine that a child template may override those portions of the template. Child Template -------------- A child template might look like this: .. sourcecode:: html+jinja {% extends "base.html" %} {% block title %}Index{% endblock %} {% block html_head %} {% endblock %} {% block content %}

    Index

    Welcome on my awsome homepage.

    {% endblock %} The ``{% extends %}`` tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, first it locates the parent. The filename of the template depends on the template loader. For example the ``FileSystemLoader`` allows you to access other templates by giving the filename. You can access templates in subdirectories with an slash: .. sourcecode:: jinja {% extends "layout/default.html" %} But this behavior can depend on the application using Jinja. Note that since the child template didn't define the ``footer`` block, the value from the parent template is used instead. .. admonition:: Note You can't define multiple ``{% block %}`` tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill - it also defines the content that fills the hole in the *parent*. If there were two similarly-named ``{% block %}`` tags in a template, that template's parent wouldn't know which one of the blocks' content to use. Template Inclusion ================== You can load another template at a given position using ``{% include %}``. Usually it's a better idea to use inheritance but if you for example want to load macros, `include` works better than `extends`: .. sourcecode:: jinja {% include "myhelpers.html" %} {{ my_helper("foo") }} If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now use it from the template as shown above. Filtering Blocks ================ Sometimes it could be a good idea to filter a complete block of text. For example, if you want to escape some html code: .. sourcecode:: jinja {% filter escape %} goes here {% endfilter %} Of course you can chain filters too: .. sourcecode:: jinja {% filter lower|escape %} SOME TEXT {% endfilter %} returns ``"<b>some text</b>"``. Defining Variables ================== You can also define variables in the namespace using the ``{% set %}`` tag: .. sourcecode:: jinja {% set foo = 'foobar' %} {{ foo }} This should ouput ``foobar``. Scopes ====== Jinja has multiple scopes. A scope is something like a new transparent foil on a stack of foils. You can only write to the outermost foil but read all of them since you can look through them. If you remove the top foil all data on that foil disappears. Some tags in Jinja add a new layer to the stack. Currently these are `block`, `for`, `macro` and `filter`. This means that variables and other elements defined inside a macro, loop or some of the other tags listed above will be only available in that block. Here an example: .. sourcecode:: jinja {% macro angryhello name %} {% set angryname = name|upper %} Hello {{ name }}. Hello {{ name }}! HELLO {{ angryname }}!!!!!!111 {% endmacro %} The variable ``angryname`` just exists inside the macro, not outside it. Defined macros appear on the context as variables. Because of this, they are affected by the scoping too. A macro defined inside of a macro is just available in those two macros (the macro itself and the macro it's defined in). For `set` and `macro` two additional rules exist: If a macro is defined in an extended template but outside of a visible block (thus outside of any block) will be available in all blocks below. This allows you to use `include` statements to load often used macros at once. Undefined Variables =================== If you have already worked with python you probably know about the fact that undefined variables raise an exception. This is different in Jinja. There is a special value called `undefined` that represents values that do not exist. This special variable works complete different from any variables you maybe know. If you print it using ``{{ variable }}`` it will not appear because it's literally empty. If you try to iterate over it, it will work. But no items are returned. Comparing this value to any other value results in `false`. Even if you compare it to itself: .. sourcecode:: jinja {{ undefined == undefined }} will return false. Not even undefined is undefined :) Use `is defined` / `is not defined`: {{ undefined is not defined }} will return true. There are also some additional rules regarding this special value. Any mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand as result: .. sourcecode:: jinja {{ undefined + "foo" }} returns "foo" {{ undefined - 42 }} returns 42. Note: not -42! In any expression `undefined` evaluates to `false`. It has no length, all attribute calls return undefined, calling too: .. sourcecode:: jinja {{ undefined.attribute().attribute_too[42] }} still returns `undefined`. Escaping ======== Sometimes you might want to add Jinja syntax elements into the template without executing them. In that case you have quite a few possibilities. For small parts this might be a good way: .. sourcecode:: jinja {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }} When you have multiple elements you can use the ``raw`` block: .. sourcecode:: jinja {% raw %} Filtering blocks works like this in Jinja: {% filter escape %} goes here {% endfilter %} {% endraw %} Reserved Keywords ================= Jinja has some keywords you cannot use a variable names. This limitation exists to make look coherent. Syntax highlighters won't mess things up and you will don't have unexpected output. The following keywords exist and cannot be used as identifiers: `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`, `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`, `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`, `raw`, `recursive`, `set`, `trans` If you want to use such a name you have to prefix or suffix it or use alternative names: .. sourcecode:: jinja {% for macro_ in macros %} {{ macro_('foo') }} {% endfor %} If future Jinja releases add new keywords those will be "light" keywords which means that they won't raise an error for several releases but yield warnings on the application side. But it's very unlikely that new keywords will be added. Internationalization ==================== If the application is configured for i18n, you can define translatable blocks for translators using the `trans` tag or the special underscore function: .. sourcecode:: jinja {% trans %} this is a translatable block {% endtrans %} {% trans "This is a translatable string" %} {{ _("This is a translatable string") }} The latter one is useful if you want translatable arguments for filters etc. If you want to have plural forms too, use the `pluralize` block: .. sourcecode:: jinja {% trans users=users %} One user found. {% pluralize %} {{ users }} users found. {% endtrans %} {% trans first=(users|first).username|escape, user=users|length %} one user {{ first }} found. {% pluralize users %} {{ users }} users found, the first one is called {{ first }}. {% endtrans %} If you have multiple arguments, the first one is assumed to be the indicator (the number that is used to determine the correct singular or plural form. If you don't have the indicator variable on position 1 you have to tell the `pluralize` tag the correct variable name. Inside translatable blocks you cannot use blocks or expressions (however you can still use the ``raw`` block which will work as expected). The variable print syntax (``{{ variablename }}``) is the only way to insert the variables defined in the ``trans`` header. Filters must be applied in the header. .. admonition:: note Please make sure that you always use pluralize blocks where required. Many languages have more complex plural forms than the English language. Never try to workaround that issue by using something like this: .. sourcecode:: jinja {% if count != 1 %} {{ count }} users found. {% else %} one user found. {% endif %} .. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice .. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/json.lasso000066400000000000000000000251061250413007300257100ustar00rootroot00000000000000 // // // If: (Lasso_TagExists: 'Encode_JSON') == False; Define_Tag: 'JSON', -Namespace='Encode_', -Required='value', -Optional='options'; Local: 'escapes' = Map('\\' = '\\', '"' = '"', '\r' = 'r', '\n' = 'n', '\t' = 't', '\f' = 'f', '\b' = 'b'); Local: 'output' = ''; Local: 'newoptions' = (Array: -Internal); If: !(Local_Defined: 'options') || (#options->(IsA: 'array') == False); Local: 'options' = (Array); /If; If: (#options >> -UseNative) || (Params >> -UseNative); #newoptions->(Insert: -UseNative); /If; If: (#options >> -NoNative) || (Params >> -NoNative); #newoptions->(Insert: -NoNative); /If; If: (#options !>> -UseNative) && ((#value->(IsA: 'set')) || (#value->(IsA: 'list')) || (#value->(IsA: 'queue')) || (#value->(IsA: 'priorityqueue')) || (#value->(IsA: 'stack'))); #output += (Encode_JSON: Array->(insertfrom: #value->iterator) &, -Options=#newoptions); Else: (#options !>> -UseNative) && (#value->(IsA: 'pair')); #output += (Encode_JSON: (Array: #value->First, #value->Second)); Else: (#options !>> -Internal) && (#value->(Isa: 'array') == False) && (#value->(IsA: 'map') == False); #output += '[' + (Encode_JSON: #value, -Options=#newoptions) + ']'; Else: (#value->(IsA: 'literal')); #output += #value; Else: (#value->(IsA: 'string')); #output += '"'; Loop: (#value->Length); Local('character' = #value->(Get: Loop_Count)); #output->(Append: (Match_RegExp('[\\x{0020}-\\x{21}\\x{23}-\\x{5b}\\x{5d}-\\x{10fff}]') == #character) ? #character | '\\' + (#escapes->(Contains: #character) ? #escapes->(Find: #character) | 'u' + String(Encode_Hex(#character))->PadLeading(4, '0')&) ); /Loop; #output += '"'; Else: (#value->(IsA: 'integer')) || (#value->(IsA: 'decimal')) || (#value->(IsA: 'boolean')); #output += (String: #value); Else: (#value->(IsA: 'null')); #output += 'null'; Else: (#value->(IsA: 'date')); If: #value->gmt; #output += '"' + #value->(format: '%QT%TZ') + '"'; Else; #output += '"' + #value->(format: '%QT%T') + '"'; /If; Else: (#value->(IsA: 'array')); #output += '['; Iterate: #value, (Local: 'temp'); #output += (Encode_JSON: #temp, -Options=#newoptions); If: #value->Size != Loop_Count; #output += ', '; /If; /Iterate; #output += ']'; Else: (#value->(IsA: 'object')); #output += '{'; Iterate: #value, (Local: 'temp'); #output += #temp->First + ': ' + (Encode_JSON: #temp->Second, -Options=#newoptions); If: (#value->Size != Loop_Count); #output += ', '; /If; /Iterate; #output += '}'; Else: (#value->(IsA: 'map')); #output += '{'; Iterate: #value, (Local: 'temp'); #output += (Encode_JSON: #temp->First, -Options=#newoptions) + ': ' + (Encode_JSON: #temp->Second, -Options=#newoptions); If: (#value->Size != Loop_Count); #output += ', '; /If; /Iterate; #output += '}'; Else: (#value->(IsA: 'client_ip')) || (#value->(IsA: 'client_address')); #output += (Encode_JSON: (String: #value), -Options=#newoptions); Else: (#options !>> -UseNative) && (#value->(IsA: 'set')) || (#value->(IsA: 'list')) || (#value->(IsA: 'queue')) || (#value->(IsA: 'priorityqueue')) || (#value->(IsA: 'stack')); #output += (Encode_JSON: Array->(insertfrom: #value->iterator) &, -Options=#newoptions); Else: (#options !>> -NoNative); #output += (Encode_JSON: (Map: '__jsonclass__'=(Array:'deserialize',(Array:'' + #value->Serialize + '')))); /If; Return: @#output; /Define_Tag; /If; If: (Lasso_TagExists: 'Decode_JSON') == False; Define_Tag: 'JSON', -Namespace='Decode_', -Required='value'; (#value == '') ? Return: Null; Define_Tag: 'consume_string', -Required='ibytes'; Local: 'unescapes' = (map: 34 = '"', 92 = '\\', 98 = '\b', 102 = '\f', 110 = '\n', 114 = '\r', 116 = '\t'); Local: 'temp' = 0, 'obytes' = Bytes; While: ((#temp := #ibytes->export8bits) != 34); // '"' If: (#temp === 92); // '\' #temp = #ibytes->export8bits; If: (#temp === 117); // 'u' #obytes->(ImportString: (Decode_Hex: (String: #ibytes->(GetRange: #ibytes->Position + 1, 4)))->(ExportString: 'UTF-16'), 'UTF-8'); #ibytes->(SetPosition: #ibytes->Position + 4); Else; If: (#unescapes->(Contains: #temp)); #obytes->(ImportString: #unescapes->(Find: #temp), 'UTF-8'); Else; #obytes->(Import8Bits: #temp); /If; /If; Else; #obytes->(Import8Bits: #temp); /If; /While; Local('output' = #obytes->(ExportString: 'UTF-8')); If: #output->(BeginsWith: '') && #output->(EndsWith: ''); Local: 'temp' = #output - '' - ''; Local: 'output' = null; Protect; #output->(Deserialize: #temp); /Protect; Else: (Valid_Date: #output, -Format='%QT%TZ'); Local: 'output' = (Date: #output, -Format='%QT%TZ'); Else: (Valid_Date: #output, -Format='%QT%T'); Local: 'output' = (Date: #output, -Format='%QT%T'); /If; Return: @#output; /Define_Tag; Define_Tag: 'consume_token', -Required='ibytes', -required='temp'; Local: 'obytes' = bytes->(import8bits: #temp) &; local: 'delimit' = (array: 9, 10, 13, 32, 44, 58, 93, 125); // \t\r\n ,:]} While: (#delimit !>> (#temp := #ibytes->export8bits)); #obytes->(import8bits: #temp); /While; Local: 'output' = (String: #obytes); If: (#output == 'true') || (#output == 'false'); Return: (Boolean: #output); Else: (#output == 'null'); Return: Null; Else: (String_IsNumeric: #output); Return: (#output >> '.') ? (Decimal: #output) | (Integer: #output); /If; Return: @#output; /Define_Tag; Define_Tag: 'consume_array', -Required='ibytes'; Local: 'output' = array; local: 'delimit' = (array: 9, 10, 13, 32, 44); // \t\r\n , local: 'temp' = 0; While: ((#temp := #ibytes->export8bits) != 93); // ] If: (#delimit >> #temp); // Discard whitespace Else: (#temp == 34); // " #output->(insert: (consume_string: @#ibytes)); Else: (#temp == 91); // [ #output->(insert: (consume_array: @#ibytes)); Else: (#temp == 123); // { #output->(insert: (consume_object: @#ibytes)); Else; #output->(insert: (consume_token: @#ibytes, @#temp)); (#temp == 93) ? Loop_Abort; /If; /While; Return: @#output; /Define_Tag; Define_Tag: 'consume_object', -Required='ibytes'; Local: 'output' = map; local: 'delimit' = (array: 9, 10, 13, 32, 44); // \t\r\n , local: 'temp' = 0; local: 'key' = null; local: 'val' = null; While: ((#temp := #ibytes->export8bits) != 125); // } If: (#delimit >> #temp); // Discard whitespace Else: (#key !== null) && (#temp == 34); // " #output->(insert: #key = (consume_string: @#ibytes)); #key = null; Else: (#key !== null) && (#temp == 91); // [ #output->(insert: #key = (consume_array: @#ibytes)); #key = null; Else: (#key !== null) && (#temp == 123); // { #output->(insert: #key = (consume_object: @#ibytes)); #key = null; Else: (#key !== null); #output->(insert: #key = (consume_token: @#ibytes, @#temp)); (#temp == 125) ? Loop_abort; #key = null; Else; #key = (consume_string: @#ibytes); while(#delimit >> (#temp := #ibytes->export8bits)); /while; #temp != 58 ? Loop_Abort; /If; /While; If: (#output >> '__jsonclass__') && (#output->(Find: '__jsonclass__')->(isa: 'array')) && (#output->(Find: '__jsonclass__')->size >= 2) && (#output->(Find: '__jsonclass__')->First == 'deserialize'); Return: #output->(find: '__jsonclass__')->Second->First; Else: (#output >> 'native') && (#output >> 'comment') && (#output->(find: 'comment') == 'http://www.lassosoft.com/json'); Return: #output->(find: 'native'); /If; Return: @#output; /Define_Tag; Local: 'ibytes' = (bytes: #value); Local: 'start' = 1; #ibytes->removeLeading(BOM_UTF8); Local: 'temp' = #ibytes->export8bits; If: (#temp == 91); // [ Local: 'output' = (consume_array: @#ibytes); Return: @#output; Else: (#temp == 123); // { Local: 'output' = (consume_object: @#ibytes); Return: @#output; /If; /Define_Tag; /If; If: (Lasso_TagExists: 'Literal') == False; Define_Type: 'Literal', 'String'; /Define_Type; /If; If: (Lasso_TagExists: 'Object') == False; Define_Type: 'Object', 'Map'; /Define_Type; /If; If: (Lasso_TagExists: 'JSON_RPCCall') == False; Define_Tag: 'RPCCall', -Namespace='JSON_', -Required='method', -Optional='params', -Optional='id', -Optional='host'; !(Local_Defined: 'host') ? Local: 'host' = 'http://localhost/lassoapps.8/rpc/rpc.lasso'; !(Local_Defined: 'id') ? Local: 'id' = Lasso_UniqueID; Local: 'request' = (Map: 'method' = #method, 'params' = #params, 'id' = #id); Local: 'request' = (Encode_JSON: #request); Local: 'result' = (Include_URL: #host, -PostParams=#request); Local: 'result' = (Decode_JSON: #result); Return: @#result; /Define_Tag; /If; If: (Lasso_TagExists: 'JSON_Records') == False; Define_Tag: 'JSON_Records', -Optional='KeyField', -Optional='ReturnField', -Optional='ExcludeField', -Optional='Fields'; Local: '_fields' = (Local_Defined: 'fields') && #fields->(IsA: 'array') ? #fields | Field_Names; Fail_If: #_fields->size == 0, -1, 'No fields found for [JSON_Records]'; Local: '_keyfield' = (Local: 'keyfield'); If: #_fields !>> #_keyfield; Local: '_keyfield' = (KeyField_Name); If: #_fields !>> #_keyfield; Local: '_keyfield' = 'ID'; If: #_fields !>> #_keyfield; Local: '_keyfield' = #_fields->First; /If; /If; /If; Local: '_index' = #_fields->(FindPosition: #_keyfield)->First; Local: '_return' = (Local_Defined: 'returnfield') ? (Params->(Find: -ReturnField)->(ForEach: {Params->First = Params->First->Second; Return: True}) &) | @#_fields; Local: '_exclude' = (Local_Defined: 'excludefield') ? (Params->(Find: -ExcludeField)->(ForEach: {Params->First = Params->First->Second; Return: True}) &) | Array; Local: '_records' = Array; Iterate: Records_Array, (Local: '_record'); Local: '_temp' = Map; Iterate: #_fields, (Local: '_field'); ((#_return >> #_field) && (#_exclude !>> #_field)) ? #_temp->Insert(#_field = #_record->(Get: Loop_Count)); /Iterate; #_records->Insert(#_temp); /Iterate; Local: '_output' = (Encode_JSON: (Object: 'error_msg'=Error_Msg, 'error_code'=Error_Code, 'found_count'=Found_Count, 'keyfield'=#_keyfield, 'rows'=#_records)); Return: @#_output; /Define_Tag; /If; ?> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/json.lasso9000066400000000000000000000172241250413007300260030ustar00rootroot00000000000000 /** trait_json_serialize Objects with this trait will be assumed to convert to json data when its ->asString method is called */ define trait_json_serialize => trait { require asString() } define json_serialize(e::bytes)::string => ('"' + (string(#e)->Replace(`\`, `\\`) & Replace('\"', '\\"') & Replace('\r', '\\r') & Replace('\n', '\\n') & Replace('\t', '\\t') & Replace('\f', '\\f') & Replace('\b', '\\b') &) + '"') define json_serialize(e::string)::string => ('"' + (string(#e)->Replace(`\`, `\\`) & Replace('\"', '\\"') & Replace('\r', '\\r') & Replace('\n', '\\n') & Replace('\t', '\\t') & Replace('\f', '\\f') & Replace('\b', '\\b') &) + '"') define json_serialize(e::json_literal)::string => (#e->asstring) define json_serialize(e::integer)::string => (#e->asstring) define json_serialize(e::decimal)::string => (#e->asstring) define json_serialize(e::boolean)::string => (#e->asstring) define json_serialize(e::null)::string => ('null') define json_serialize(e::date)::string => ('"' + #e->format(#e->gmt ? '%QT%TZ' | '%Q%T') + '"') /* define json_serialize(e::array)::string => { local(output) = ''; local(delimit) = ''; #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } return('[' + #output + ']'); } define json_serialize(e::staticarray)::string => { local(output) = ''; local(delimit) = ''; #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } return('[' + #output + ']'); } */ define json_serialize(e::trait_forEach)::string => { local(output) = ''; local(delimit) = ''; #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } return('[' + #output + ']'); } define json_serialize(e::map)::string => { local(output = with pr in #e->eachPair select json_serialize(#pr->first->asString) + ': ' + json_serialize(#pr->second)) return '{' + #output->join(',') + '}' } define json_serialize(e::json_object)::string => { local(output) = ''; local(delimit) = ''; #e->foreachpair => { #output += #delimit + #1->first + ': ' + json_serialize(#1->second); #delimit = ', '; } return('{' + #output + '}'); } define json_serialize(e::trait_json_serialize) => #e->asString define json_serialize(e::any)::string => json_serialize('' + #e->serialize + '') // Bil Corry fixes for decoding json define json_consume_string(ibytes::bytes) => { local(obytes) = bytes; local(temp) = 0; while((#temp := #ibytes->export8bits) != 34); #obytes->import8bits(#temp); (#temp == 92) ? #obytes->import8bits(#ibytes->export8bits); // Escape \ /while; local(output = string(#obytes)->unescape) //Replace('\\"', '\"') & Replace('\\r', '\r') & Replace('\\n', '\n') & Replace('\\t', '\t') & Replace('\\f', '\f') & Replace('\\b', '\b') &; if(#output->BeginsWith('') && #output->EndsWith('')); Protect; return serialization_reader(xml(#output - '' - ''))->read /Protect; else( (#output->size == 16 or #output->size == 15) and regexp(`\d{8}T\d{6}Z?`, '', #output)->matches) return date(#output, -Format=#output->size == 16?`yyyyMMdd'T'HHmmssZ`|`yyyyMMdd'T'HHmmss`) /if return #output } // Bil Corry fix + Ke fix define json_consume_token(ibytes::bytes, temp::integer) => { local(obytes = bytes->import8bits(#temp) &, delimit = array(9, 10, 13, 32, 44, 58, 93, 125)) // \t\r\n ,:]} while(#delimit !>> (#temp := #ibytes->export8bits)) #obytes->import8bits(#temp) /while #temp == 125? // } #ibytes->marker -= 1 //============================================================================ // Is also end of token if end of array[] #temp == 93? // ] #ibytes->marker -= 1 //............................................................................ local(output = string(#obytes)) #output == 'true'? return true #output == 'false'? return false #output == 'null'? return null string_IsNumeric(#output)? return (#output >> '.')? decimal(#output) | integer(#output) return #output } // Bil Corry fix define json_consume_array(ibytes::bytes)::array => { Local(output) = array; local(delimit) = array( 9, 10, 13, 32, 44); // \t\r\n , local(temp) = 0; While((#temp := #ibytes->export8bits) != 93); // ] If(#delimit >> #temp); // Discard whitespace Else(#temp == 34); // " #output->insert(json_consume_string(#ibytes)); Else(#temp == 91); // [ #output->insert(json_consume_array(#ibytes)); Else(#temp == 123); // { #output->insert(json_consume_object(#ibytes)); Else; #output->insert(json_consume_token(#ibytes, #temp)); (#temp == 93) ? Loop_Abort; /If; /While; Return(#output); } // Bil Corry fix define json_consume_object(ibytes::bytes)::map => { Local('output' = map, 'delimit' = array( 9, 10, 13, 32, 44), // \t\r\n , 'temp' = 0, 'key' = null, 'val' = null); While((#temp := #ibytes->export8bits) != 125); // } If(#delimit >> #temp); // Discard whitespace Else((#key !== null) && (#temp == 34)); // " #output->insert(#key = json_consume_string(#ibytes)); #key = null; Else((#key !== null) && (#temp == 91)); // [ #output->insert(#key = json_consume_array(#ibytes)); #key = null; Else((#key !== null) && (#temp == 123)); // { #output->insert(#key = json_consume_object(#ibytes)); #key = null; Else((#key !== null)); #output->insert(#key = json_consume_token(#ibytes, #temp)); #key = null; Else; #key = json_consume_string(#ibytes); while(#delimit >> (#temp := #ibytes->export8bits)); /while; #temp != 58 ? Loop_Abort; /If; /While; If((#output >> '__jsonclass__') && (#output->Find('__jsonclass__')->isa('array')) && (#output->Find('__jsonclass__')->size >= 2) && (#output->Find('__jsonclass__')->First == 'deserialize')); Return(#output->find('__jsonclass__')->Second->First); Else((#output >> 'native') && (#output >> 'comment') && (#output->find('comment') == 'http://www.lassosoft.com/json')); Return(#output->find('native')); /If; Return(#output); } // Bil Corry fix + Ke fix define json_deserialize(ibytes::bytes)::any => { #ibytes->removeLeading(bom_utf8); //============================================================================ // Reset marker on provided bytes #ibytes->marker = 0 //............................................................................ Local(temp) = #ibytes->export8bits; If(#temp == 91); // [ Return(json_consume_array(#ibytes)); Else(#temp == 123); // { Return(json_consume_object(#ibytes)); else(#temp == 34) // " return json_consume_string(#ibytes) /If; } define json_deserialize(s::string) => json_deserialize(bytes(#s)) /**! json_literal - This is a subclass of String used for JSON encoding. A json_literal works exactly like a string, but will be inserted directly rather than being encoded into JSON. This allows JavaScript elements like functions to be inserted into JSON objects. This is most useful when the JSON object will be used within a JavaScript on the local page. [Map: 'fn'=Literal('function(){ ...})] => {'fn': function(){ ...}} **/ define json_literal => type { parent string } /**! json_object - This is a subclass of Map used for JSON encoding. An object works exactly like a map, but when it is encoded into JSON all of the keys will be inserted literally. This makes it easy to create a JavaScript object without extraneous quote marks. Object('name'='value') => {name: "value"} **/ define json_object => type { parent map public onCreate(...) => ..onCreate(:#rest or (:)) } define json_rpccall(method::string, params=map, id='', host='') => { #id == '' ? #host = Lasso_UniqueID; #host == '' ? #host = 'http://localhost/lassoapps.8/rpc/rpc.lasso'; Return(Decode_JSON(Include_URL(#host, -PostParams=Encode_JSON(Map('method' = #method, 'params' = #params, 'id' = #id))))); } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/language.hy000066400000000000000000000075421250413007300260250ustar00rootroot00000000000000;;;; This contains some of the core Hy functions used ;;;; to make functional programming slightly easier. ;;;; (defn _numeric-check [x] (if (not (numeric? x)) (raise (TypeError (.format "{0!r} is not a number" x))))) (defn cycle [coll] "Yield an infinite repetition of the items in coll" (setv seen []) (for [x coll] (yield x) (.append seen x)) (while seen (for [x seen] (yield x)))) (defn dec [n] "Decrement n by 1" (_numeric-check n) (- n 1)) (defn distinct [coll] "Return a generator from the original collection with duplicates removed" (let [[seen []] [citer (iter coll)]] (for [val citer] (if (not_in val seen) (do (yield val) (.append seen val)))))) (defn drop [count coll] "Drop `count` elements from `coll` and yield back the rest" (let [[citer (iter coll)]] (try (for [i (range count)] (next citer)) (catch [StopIteration])) citer)) (defn even? [n] "Return true if n is an even number" (_numeric-check n) (= (% n 2) 0)) (defn filter [pred coll] "Return all elements from `coll` that pass `pred`" (let [[citer (iter coll)]] (for [val citer] (if (pred val) (yield val))))) (defn inc [n] "Increment n by 1" (_numeric-check n) (+ n 1)) (defn instance? [klass x] (isinstance x klass)) (defn iterable? [x] "Return true if x is iterable" (try (do (iter x) true) (catch [Exception] false))) (defn iterate [f x] (setv val x) (while true (yield val) (setv val (f val)))) (defn iterator? [x] "Return true if x is an iterator" (try (= x (iter x)) (catch [TypeError] false))) (defn neg? [n] "Return true if n is < 0" (_numeric-check n) (< n 0)) (defn none? [x] "Return true if x is None" (is x None)) (defn numeric? [x] (import numbers) (instance? numbers.Number x)) (defn nth [coll index] "Return nth item in collection or sequence, counting from 0" (if (not (neg? index)) (if (iterable? coll) (try (first (list (take 1 (drop index coll)))) (catch [IndexError] None)) (try (get coll index) (catch [IndexError] None))) None)) (defn odd? [n] "Return true if n is an odd number" (_numeric-check n) (= (% n 2) 1)) (defn pos? [n] "Return true if n is > 0" (_numeric_check n) (> n 0)) (defn remove [pred coll] "Return coll with elements removed that pass `pred`" (let [[citer (iter coll)]] (for [val citer] (if (not (pred val)) (yield val))))) (defn repeat [x &optional n] "Yield x forever or optionally n times" (if (none? n) (setv dispatch (fn [] (while true (yield x)))) (setv dispatch (fn [] (for [_ (range n)] (yield x))))) (dispatch)) (defn repeatedly [func] "Yield result of running func repeatedly" (while true (yield (func)))) (defn take [count coll] "Take `count` elements from `coll`, or the whole set if the total number of entries in `coll` is less than `count`." (let [[citer (iter coll)]] (for [_ (range count)] (yield (next citer))))) (defn take-nth [n coll] "Return every nth member of coll raises ValueError for (not (pos? n))" (if (pos? n) (let [[citer (iter coll)] [skip (dec n)]] (for [val citer] (yield val) (for [_ (range skip)] (next citer)))) (raise (ValueError "n must be positive")))) (defn take-while [pred coll] "Take all elements while `pred` is true" (let [[citer (iter coll)]] (for [val citer] (if (pred val) (yield val) (break))))) (defn zero? [n] "Return true if n is 0" (_numeric_check n) (= n 0)) (def *exports* ["cycle" "dec" "distinct" "drop" "even?" "filter" "inc" "instance?" "iterable?" "iterate" "iterator?" "neg?" "none?" "nth" "numeric?" "odd?" "pos?" "remove" "repeat" "repeatedly" "take" "take_nth" "take_while" "zero?"]) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/lighttpd_config.conf000066400000000000000000000010541250413007300277030ustar00rootroot00000000000000fastcgi.server = ( ".php" => (( "bin-path" => "/path/to/php-cgi", "socket" => "/tmp/php.socket", "max-procs" => 2, "bin-environment" => ( "PHP_FCGI_CHILDREN" => "16", "PHP_FCGI_MAX_REQUESTS" => "10000" ), "bin-copy-environment" => ( "PATH", "SHELL", "USER" ), "broken-scriptfilename" => "enable" ))) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/limbo.b000066400000000000000000000232431250413007300251410ustar00rootroot00000000000000implement Ninewin; include "sys.m"; sys: Sys; include "draw.m"; draw: Draw; Image, Display, Pointer: import draw; include "arg.m"; include "keyboard.m"; include "tk.m"; include "wmclient.m"; wmclient: Wmclient; Window: import wmclient; include "sh.m"; sh: Sh; # run a p9 graphics program (default rio) under inferno wm, # making available to it: # /dev/winname - naming the current inferno window (changing on resize) # /dev/mouse - pointer file + resize events; write to change position # /dev/cursor - change appearance of cursor. # /dev/draw - inferno draw device # /dev/cons - read keyboard events, write to 9win stdout. Ninewin: module { init: fn(ctxt: ref Draw->Context, argv: list of string); }; winname: string; init(ctxt: ref Draw->Context, argv: list of string) { size := Draw->Point(500, 500); sys = load Sys Sys->PATH; draw = load Draw Draw->PATH; wmclient = load Wmclient Wmclient->PATH; wmclient->init(); sh = load Sh Sh->PATH; buts := Wmclient->Resize; if(ctxt == nil){ ctxt = wmclient->makedrawcontext(); buts = Wmclient->Plain; } arg := load Arg Arg->PATH; arg->init(argv); arg->setusage("9win [-s] [-x width] [-y height]"); exportonly := 0; while(((opt := arg->opt())) != 0){ case opt { 's' => exportonly = 1; 'x' => size.x = int arg->earg(); 'y' => size.y = int arg->earg(); * => arg->usage(); } } if(size.x < 1 || size.y < 1) arg->usage(); argv = arg->argv(); if(argv != nil && hd argv == "-s"){ exportonly = 1; argv = tl argv; } if(argv == nil && !exportonly) argv = "rio" :: nil; if(argv != nil && exportonly){ sys->fprint(sys->fildes(2), "9win: no command allowed with -s flag\n"); raise "fail:usage"; } title := "9win"; if(!exportonly) title += " " + hd argv; w := wmclient->window(ctxt, title, buts); w.reshape(((0, 0), size)); w.onscreen(nil); if(w.image == nil){ sys->fprint(sys->fildes(2), "9win: cannot get image to draw on\n"); raise "fail:no window"; } sys->pctl(Sys->FORKNS|Sys->NEWPGRP, nil); ld := "/n/9win"; if(sys->bind("#s", ld, Sys->MREPL) == -1 && sys->bind("#s", ld = "/n/local", Sys->MREPL) == -1){ sys->fprint(sys->fildes(2), "9win: cannot bind files: %r\n"); raise "fail:error"; } w.startinput("kbd" :: "ptr" :: nil); spawn ptrproc(rq := chan of Sys->Rread, ptr := chan[10] of ref Pointer, reshape := chan[1] of int); fwinname := sys->file2chan(ld, "winname"); fconsctl := sys->file2chan(ld, "consctl"); fcons := sys->file2chan(ld, "cons"); fmouse := sys->file2chan(ld, "mouse"); fcursor := sys->file2chan(ld, "cursor"); if(!exportonly){ spawn run(sync := chan of string, w.ctl, ld, argv); if((e := <-sync) != nil){ sys->fprint(sys->fildes(2), "9win: %s", e); raise "fail:error"; } } spawn serveproc(w, rq, fwinname, fconsctl, fcons, fmouse, fcursor); if(!exportonly){ # handle events synchronously so that we don't get a "killed" message # from the shell. handleevents(w, ptr, reshape); }else{ spawn handleevents(w, ptr, reshape); sys->bind(ld, "/dev", Sys->MBEFORE); export(sys->fildes(0), w.ctl); } } handleevents(w: ref Window, ptr: chan of ref Pointer, reshape: chan of int) { for(;;)alt{ c := <-w.ctxt.ctl or c = <-w.ctl => e := w.wmctl(c); if(e != nil) sys->fprint(sys->fildes(2), "9win: ctl error: %s\n", e); if(e == nil && c != nil && c[0] == '!'){ alt{ reshape <-= 1 => ; * => ; } winname = nil; } p := <-w.ctxt.ptr => if(w.pointer(*p) == 0){ # XXX would block here if client isn't reading mouse... but we do want to # extert back-pressure, which conflicts. alt{ ptr <-= p => ; * => ; # sys->fprint(sys->fildes(2), "9win: discarding mouse event\n"); } } } } serveproc(w: ref Window, mouserq: chan of Sys->Rread, fwinname, fconsctl, fcons, fmouse, fcursor: ref Sys->FileIO) { winid := 0; krc: list of Sys->Rread; ks: string; for(;;)alt { c := <-w.ctxt.kbd => ks[len ks] = inf2p9key(c); if(krc != nil){ hd krc <-= (array of byte ks, nil); ks = nil; krc = tl krc; } (nil, d, nil, wc) := <-fcons.write => if(wc != nil){ sys->write(sys->fildes(1), d, len d); wc <-= (len d, nil); } (nil, nil, nil, rc) := <-fcons.read => if(rc != nil){ if(ks != nil){ rc <-= (array of byte ks, nil); ks = nil; }else krc = rc :: krc; } (offset, nil, nil, rc) := <-fwinname.read => if(rc != nil){ if(winname == nil){ winname = sys->sprint("noborder.9win.%d", winid++); if(w.image.name(winname, 1) == -1){ sys->fprint(sys->fildes(2), "9win: namewin %q failed: %r", winname); rc <-= (nil, "namewin failure"); break; } } d := array of byte winname; if(offset < len d) d = d[offset:]; else d = nil; rc <-= (d, nil); } (nil, nil, nil, wc) := <-fwinname.write => if(wc != nil) wc <-= (-1, "permission denied"); (nil, nil, nil, rc) := <-fconsctl.read => if(rc != nil) rc <-= (nil, "permission denied"); (nil, d, nil, wc) := <-fconsctl.write => if(wc != nil){ if(string d != "rawon") wc <-= (-1, "cannot change console mode"); else wc <-= (len d, nil); } (nil, nil, nil, rc) := <-fmouse.read => if(rc != nil) mouserq <-= rc; (nil, d, nil, wc) := <-fmouse.write => if(wc != nil){ e := cursorset(w, string d); if(e == nil) wc <-= (len d, nil); else wc <-= (-1, e); } (nil, nil, nil, rc) := <-fcursor.read => if(rc != nil) rc <-= (nil, "permission denied"); (nil, d, nil, wc) := <-fcursor.write => if(wc != nil){ e := cursorswitch(w, d); if(e == nil) wc <-= (len d, nil); else wc <-= (-1, e); } } } ptrproc(rq: chan of Sys->Rread, ptr: chan of ref Pointer, reshape: chan of int) { rl: list of Sys->Rread; c := ref Pointer(0, (0, 0), 0); for(;;){ ch: int; alt{ p := <-ptr => ch = 'm'; c = p; <-reshape => ch = 'r'; rc := <-rq => rl = rc :: rl; continue; } if(rl == nil) rl = <-rq :: rl; hd rl <-= (sys->aprint("%c%11d %11d %11d %11d ", ch, c.xy.x, c.xy.y, c.buttons, c.msec), nil); rl = tl rl; } } cursorset(w: ref Window, m: string): string { if(m == nil || m[0] != 'm') return "invalid mouse message"; x := int m[1:]; for(i := 1; i < len m; i++) if(m[i] == ' '){ while(m[i] == ' ') i++; break; } if(i == len m) return "invalid mouse message"; y := int m[i:]; return w.wmctl(sys->sprint("ptr %d %d", x, y)); } cursorswitch(w: ref Window, d: array of byte): string { Hex: con "0123456789abcdef"; if(len d != 2*4+64) return w.wmctl("cursor"); hot := Draw->Point(bglong(d, 0*4), bglong(d, 1*4)); s := sys->sprint("cursor %d %d 16 32 ", hot.x, hot.y); for(i := 2*4; i < len d; i++){ c := int d[i]; s[len s] = Hex[c >> 4]; s[len s] = Hex[c & 16rf]; } return w.wmctl(s); } run(sync, ctl: chan of string, ld: string, argv: list of string) { Rcmeta: con "|<>&^*[]?();"; sys->pctl(Sys->FORKNS, nil); if(sys->bind("#₪", "/srv", Sys->MCREATE) == -1){ sync <-= sys->sprint("cannot bind srv device: %r"); exit; } srvname := "/srv/9win."+string sys->pctl(0, nil); # XXX do better. fd := sys->create(srvname, Sys->ORDWR, 8r600); if(fd == nil){ sync <-= sys->sprint("cannot create %s: %r", srvname); exit; } sync <-= nil; spawn export(fd, ctl); sh->run(nil, "os" :: "rc" :: "-c" :: "mount "+srvname+" /mnt/term;"+ "rm "+srvname+";"+ "bind -b /mnt/term"+ld+" /dev;"+ "bind /mnt/term/dev/draw /dev/draw ||"+ "bind -a /mnt/term/dev /dev;"+ quotedc("cd"::"/mnt/term"+cwd()::nil, Rcmeta)+";"+ quotedc(argv, Rcmeta)+";":: nil ); } export(fd: ref Sys->FD, ctl: chan of string) { sys->export(fd, "/", Sys->EXPWAIT); ctl <-= "exit"; } inf2p9key(c: int): int { KF: import Keyboard; P9KF: con 16rF000; Spec: con 16rF800; Khome: con P9KF|16r0D; Kup: con P9KF|16r0E; Kpgup: con P9KF|16r0F; Kprint: con P9KF|16r10; Kleft: con P9KF|16r11; Kright: con P9KF|16r12; Kdown: con Spec|16r00; Kview: con Spec|16r00; Kpgdown: con P9KF|16r13; Kins: con P9KF|16r14; Kend: con P9KF|16r18; Kalt: con P9KF|16r15; Kshift: con P9KF|16r16; Kctl: con P9KF|16r17; case c { Keyboard->LShift => return Kshift; Keyboard->LCtrl => return Kctl; Keyboard->LAlt => return Kalt; Keyboard->Home => return Khome; Keyboard->End => return Kend; Keyboard->Up => return Kup; Keyboard->Down => return Kdown; Keyboard->Left => return Kleft; Keyboard->Right => return Kright; Keyboard->Pgup => return Kpgup; Keyboard->Pgdown => return Kpgdown; Keyboard->Ins => return Kins; # function keys KF|1 or KF|2 or KF|3 or KF|4 or KF|5 or KF|6 or KF|7 or KF|8 or KF|9 or KF|10 or KF|11 or KF|12 => return (c - KF) + P9KF; } return c; } cwd(): string { return sys->fd2path(sys->open(".", Sys->OREAD)); } # from string.b, waiting for declaration to be uncommented. quotedc(argv: list of string, cl: string): string { s := ""; while (argv != nil) { arg := hd argv; for (i := 0; i < len arg; i++) { c := arg[i]; if (c == ' ' || c == '\t' || c == '\n' || c == '\'' || in(c, cl)) break; } if (i < len arg || arg == nil) { s += "'" + arg[0:i]; for (; i < len arg; i++) { if (arg[i] == '\'') s[len s] = '\''; s[len s] = arg[i]; } s[len s] = '\''; } else s += arg; if (tl argv != nil) s[len s] = ' '; argv = tl argv; } return s; } in(c: int, s: string): int { n := len s; if(n == 0) return 0; ans := 0; negate := 0; if(s[0] == '^') { negate = 1; s = s[1:]; n--; } for(i := 0; i < n; i++) { if(s[i] == '-' && i > 0 && i < n-1) { if(c >= s[i-1] && c <= s[i+1]) { ans = 1; break; } i++; } else if(c == s[i]) { ans = 1; break; } } if(negate) ans = !ans; # just to showcase labels skip: return ans; } bglong(d: array of byte, i: int): int { return int d[i] | (int d[i+1]<<8) | (int d[i+2]<<16) | (int d[i+3]<<24); } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/linecontinuation.py000066400000000000000000000006051250413007300276250ustar00rootroot00000000000000apple.filter(x, y) apple.\ filter(x, y) 1 \ . \ __str__ from os import path from \ os \ import \ path import os.path as something import \ os.path \ as \ something class \ Spam: pass class Spam: pass class Spam(object): pass class \ Spam \ ( object ) \ : pass def \ spam \ ( \ ) \ : \ pass pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/livescript-demo.ls000066400000000000000000000017141250413007300273410ustar00rootroot00000000000000a = -> [1 to 50] const b = --> [2 til 5] var c = ~~> 10_000_000km * 500ms - 16~ff / 32~lol e = (a) -> (b) ~> (c) --> (d, e) ~~> <[list of words]> dashes-identifiers = -> a - a b -- c 1-1 1- -1 a- a a -a underscores_i$d = -> /regexp1/ //regexp2//g 'strings' and "strings" and \strings and \#$-"\'strings another-word-list = <[ more words ]> [2 til 10] |> map (* 2) |> filter (> 5) |> fold (+) obj = prop1: 1 prop2: 2 class Class extends Anc-est-or (args) -> <- # Comment <~ /* Comment */ void undefined yes no on off a.void b.undefined c.off d.if f.no g.not avoid bundefined coff dif fno gnot "inter #{2 + 2} #variable" '''HELLO 'world' ''' copy = (from, to, callback) --> error, data <- read file return callback error if error? error <~ write file, data return callback error if error? callback() take(n, [x, ...xs]:list) = | n <= 0 => [] | empty list => [] | otherwise => [x] +++ take n - 1, xs pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/logos_example.xm000066400000000000000000000004621250413007300270760ustar00rootroot00000000000000%hook ABC - (id)a:(B)b { %log; return %orig(nil); } %end %subclass DEF: NSObject - (id)init { [%c(RuntimeAccessibleClass) alloc]; return nil; } %end %group OptionalHooks %hook ABC - (void)release { [self retain]; %orig; } %end %end %ctor { %init; if(OptionalCondition) %init(OptionalHooks); } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ltmain.sh000066400000000000000000002301111250413007300255060ustar00rootroot00000000000000# ltmain.sh - Provide generalized library-building support services. # NOTE: Changing this file will not affect anything until you rerun configure. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005 # Free Software Foundation, Inc. # Originally by Gordon Matzigkeit , 1996 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. basename="s,^.*/,,g" # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" # define SED for historic ltconfig's generated by Libtool 1.3 test -z "$SED" && SED=sed # The name of this program: progname=`echo "$progpath" | $SED $basename` modename="$progname" # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 PROGRAM=ltmain.sh PACKAGE=libtool VERSION=1.5.22 TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)" # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi # Same for EGREP, and just to be sure, do LTCC as well if test "X$EGREP" = X ; then EGREP=egrep fi if test "X$LTCC" = X ; then LTCC=${CC-gcc} fi # Check that we have a working $echo. if test "X$1" = X--no-reexec; then # Discard the --no-reexec flag, and continue. shift elif test "X$1" = X--fallback-echo; then # Avoid inline document here, it may be left over : elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then # Yippee, $echo works! : else # Restart under the correct shell, and then maybe $echo will work. exec $SHELL "$progpath" --no-reexec ${1+"$@"} fi if test "X$1" = X--fallback-echo; then # used as fallback echo shift cat <&2 $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 exit $EXIT_FAILURE fi # Global variables. mode=$default_mode nonopt= prev= prevopt= run= show="$echo" show_help= execute_dlfiles= duplicate_deps=no preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" if test -z "$max_cmd_len"; then i=0 testring="ABCD" new_result= # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while (test "X"`$SHELL $0 --fallback-echo "X$testring" 2>/dev/null` \ = "XX$testring") >/dev/null 2>&1 && new_result=`expr "X$testring" : ".*" 2>&1` && max_cmd_len="$new_result" && test "$i" != 17 # 1/2 MB should be enough do i=`expr $i + 1` testring="$testring$testring" done testring= # Add a significant safety factor because C++ compilers can tack on massive # amounts of additional arguments before passing them to the linker. # It appears as though 1/2 is a usable value. max_cmd_len=`expr $max_cmd_len \/ 2` fi ##################################### # Shell function definitions: # This seems to be the best place for them # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $mkdir "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || { $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2 exit $EXIT_FAILURE } fi $echo "X$my_tmpdir" | $Xsed } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. func_win32_libid () { win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \ $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then win32_nmres=`eval $NM -f posix -A $1 | \ $SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $echo $win32_libid_type } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") arg="\"$arg\"" ;; esac CC_quoted="$CC_quoted $arg" done case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") arg="\"$arg\"" ;; esac CC_quoted="$CC_quoted $arg" done # user sometimes does CC=-gcc so we need to match that to 'gcc' trimedcc=`echo ${CC} | $SED -e "s/${host}-//g"` # and sometimes libtool has CC=-gcc but user does CC=gcc extendcc=${host}-${CC} # and sometimes libtool has CC=-gcc but user has CC=-gcc # (Gentoo-specific hack because we always export $CHOST) mungedcc=${CHOST-${host}}-${trimedcc} case "$@ " in "cc "* | " cc "* | "${host}-cc "* | " ${host}-cc "*|\ "gcc "* | " gcc "* | "${host}-gcc "* | " ${host}-gcc "*) tagname=CC break ;; "$trimedcc "* | " $trimedcc "* | "`$echo $trimedcc` "* | " `$echo $trimedcc` "*|\ "$extendcc "* | " $extendcc "* | "`$echo $extendcc` "* | " `$echo $extendcc` "*|\ "$mungedcc "* | " $mungedcc "* | "`$echo $mungedcc` "* | " `$echo $mungedcc` "*|\ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then $echo "$modename: unable to infer tagged configuration" $echo "$modename: specify a tag with \`--tag'" 1>&2 exit $EXIT_FAILURE # else # $echo "$modename: using $tagname tagged configuration" fi ;; esac fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)" $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $? if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2 exit $EXIT_FAILURE fi } # func_extract_archives gentop oldlib ... func_extract_archives () { my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" my_status="" $show "${rm}r $my_gentop" $run ${rm}r "$my_gentop" $show "$mkdir $my_gentop" $run $mkdir "$my_gentop" my_status=$? if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then exit $my_status fi for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'` my_xdir="$my_gentop/$my_xlib" $show "${rm}r $my_xdir" $run ${rm}r "$my_xdir" $show "$mkdir $my_xdir" $run $mkdir "$my_xdir" exit_status=$? if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then exit $exit_status fi case $host in *-darwin*) $show "Extracting $my_xabs" # Do not bother doing anything if just a dry run if test -z "$run"; then darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'` darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null` if test -n "$darwin_arches"; then darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= $show "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}" lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we have a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` lipo -create -output "$darwin_file" $darwin_files done # $darwin_filelist ${rm}r unfat-$$ cd "$darwin_orig_dir" else cd "$darwin_orig_dir" func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches fi # $run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # End of Shell function definitions ##################################### # Darwin sucks eval std_shrext=\"$shrext_cmds\" disable_libs=no # Parse our command line options once, thoroughly. while test "$#" -gt 0 do arg="$1" shift case $arg in -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;; *) optarg= ;; esac # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in execute_dlfiles) execute_dlfiles="$execute_dlfiles $arg" ;; tag) tagname="$arg" preserve_args="${preserve_args}=$arg" # Check whether tagname contains only valid characters case $tagname in *[!-_A-Za-z0-9,/]*) $echo "$progname: invalid tag name: $tagname" 1>&2 exit $EXIT_FAILURE ;; esac case $tagname in CC) # Don't test for the "default" C tag, as we know, it's there, but # not specially marked. ;; *) if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then taglist="$taglist $tagname" # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`" else $echo "$progname: ignoring unknown tag $tagname" 1>&2 fi ;; esac ;; *) eval "$prev=\$arg" ;; esac prev= prevopt= continue fi # Have we seen a non-optional argument yet? case $arg in --help) show_help=yes ;; --version) $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP" $echo $echo "Copyright (C) 2005 Free Software Foundation, Inc." $echo "This is free software; see the source for copying conditions. There is NO" $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." exit $? ;; --config) ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath # Now print the configurations for the tags. for tagname in $taglist; do ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath" done exit $? ;; --debug) $echo "$progname: enabling shell trace mode" set -x preserve_args="$preserve_args $arg" ;; --dry-run | -n) run=: ;; --features) $echo "host: $host" if test "$build_libtool_libs" = yes; then $echo "enable shared libraries" else $echo "disable shared libraries" fi if test "$build_old_libs" = yes; then $echo "enable static libraries" else $echo "disable static libraries" fi exit $? ;; --finish) mode="finish" ;; --mode) prevopt="--mode" prev=mode ;; --mode=*) mode="$optarg" ;; --preserve-dup-deps) duplicate_deps="yes" ;; --quiet | --silent) show=: preserve_args="$preserve_args $arg" ;; --tag) prevopt="--tag" prev=tag preserve_args="$preserve_args --tag" ;; --tag=*) set tag "$optarg" ${1+"$@"} shift prev=tag preserve_args="$preserve_args --tag" ;; -dlopen) prevopt="-dlopen" prev=execute_dlfiles ;; -*) $echo "$modename: unrecognized option \`$arg'" 1>&2 $echo "$help" 1>&2 exit $EXIT_FAILURE ;; *) nonopt="$arg" break ;; esac done if test -n "$prevopt"; then $echo "$modename: option \`$prevopt' requires an argument" 1>&2 $echo "$help" 1>&2 exit $EXIT_FAILURE fi case $disable_libs in no) ;; shared) build_libtool_libs=no build_old_libs=yes ;; static) build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` ;; esac # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= if test -z "$show_help"; then # Infer the operation mode. if test -z "$mode"; then $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2 $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2 case $nonopt in *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*) mode=link for arg do case $arg in -c) mode=compile break ;; esac done ;; *db | *dbx | *strace | *truss) mode=execute ;; *install*|cp|mv) mode=install ;; *rm) mode=uninstall ;; *) # If we have no mode, but dlfiles were specified, then do execute mode. test -n "$execute_dlfiles" && mode=execute # Just use the default operation mode. if test -z "$mode"; then if test -n "$nonopt"; then $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2 else $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2 fi fi ;; esac fi # Only execute mode is allowed to have -dlopen flags. if test -n "$execute_dlfiles" && test "$mode" != execute; then $echo "$modename: unrecognized option \`-dlopen'" 1>&2 $echo "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$modename --help --mode=$mode' for more information." # These modes are in order of execution frequency so that they run quickly. case $mode in # libtool compile mode compile) modename="$modename: compile" # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) if test -n "$libobj" ; then $echo "$modename: you cannot specify \`-o' more than once" 1>&2 exit $EXIT_FAILURE fi arg_mode=target continue ;; -static | -prefer-pic | -prefer-non-pic) later="$later $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"` lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" # Double-quote args containing other shell metacharacters. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") arg="\"$arg\"" ;; esac lastarg="$lastarg $arg" done IFS="$save_ifs" lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"` # Add the arguments to base_compile. base_compile="$base_compile $lastarg" continue ;; * ) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"` case $lastarg in # Double-quote args containing other shell metacharacters. # Many Bourne shells cannot handle close brackets correctly # in scan sets, and some SunOS ksh mistreat backslash-escaping # in scan sets (worked around with variable expansion), # and furthermore cannot handle '|' '&' '(' ')' in scan sets # at all, so we specify them separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") lastarg="\"$lastarg\"" ;; esac base_compile="$base_compile $lastarg" done # for arg case $arg_mode in arg) $echo "$modename: you must specify an argument for -Xcompile" exit $EXIT_FAILURE ;; target) $echo "$modename: you must specify a target with \`-o'" 1>&2 exit $EXIT_FAILURE ;; *) # Get the name of the library object. [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'` ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo xform='[cCFSifmso]' case $libobj in *.ada) xform=ada ;; *.adb) xform=adb ;; *.ads) xform=ads ;; *.asm) xform=asm ;; *.c++) xform=c++ ;; *.cc) xform=cc ;; *.ii) xform=ii ;; *.class) xform=class ;; *.cpp) xform=cpp ;; *.cxx) xform=cxx ;; *.f90) xform=f90 ;; *.for) xform=for ;; *.java) xform=java ;; esac libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` case $libobj in *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;; *) $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2 exit $EXIT_FAILURE ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -static) build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"` case $qlibobj in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") qlibobj="\"$qlibobj\"" ;; esac test "X$libobj" != "X$qlibobj" \ && $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \ && $echo "$modename: libobj name \`$libobj' may not contain shell special characters." objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'` xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'` if test "X$xdir" = "X$obj"; then xdir= else xdir=$xdir/ fi lobj=${xdir}$objdir/$objname if test -z "$base_compile"; then $echo "$modename: you must specify a compilation command" 1>&2 $echo "$help" 1>&2 exit $EXIT_FAILURE fi # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi $run $rm $removelist trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" removelist="$removelist $output_obj $lockfile" trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $run ln "$srcfile" "$lockfile" 2>/dev/null; do $show "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $echo "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $run $rm $removelist exit $EXIT_FAILURE fi $echo "$srcfile" > "$lockfile" fi if test -n "$fix_srcfile_path"; then eval srcfile=\"$fix_srcfile_path\" fi qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"` case $qsrcfile in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") qsrcfile="\"$qsrcfile\"" ;; esac $run $rm "$libobj" "${libobj}T" # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. test -z "$run" && cat > ${libobj}T </dev/null`" != "X$srcfile"; then $echo "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $run $rm $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then $show "$mv $output_obj $lobj" if $run $mv $output_obj $lobj; then : else error=$? $run $rm $removelist exit $error fi fi # Append the name of the PIC object to the libtool object file. test -z "$run" && cat >> ${libobj}T <> ${libobj}T </dev/null`" != "X$srcfile"; then $echo "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $run $rm $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then $show "$mv $output_obj $obj" if $run $mv $output_obj $obj; then : else error=$? $run $rm $removelist exit $error fi fi # Append the name of the non-PIC object the libtool object file. # Only append if the libtool object file exists. test -z "$run" && cat >> ${libobj}T <> ${libobj}T <&2 fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes else if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built fi build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test ;; *) qarg=$arg ;; esac libtool_args="$libtool_args $qarg" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) compile_command="$compile_command @OUTPUT@" finalize_command="$finalize_command @OUTPUT@" ;; esac case $prev in dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. compile_command="$compile_command @SYMFILE@" finalize_command="$finalize_command @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then dlfiles="$dlfiles $arg" else dlprefiles="$dlprefiles $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" if test ! -f "$arg"; then $echo "$modename: symbol file \`$arg' does not exist" exit $EXIT_FAILURE fi prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat $save_arg` do # moreargs="$moreargs $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then pic_object= non_pic_object= # Read the .lo file # If there is no directory component, then add one. case $arg in */* | *\\*) . $arg ;; *) . ./$arg ;; esac if test -z "$pic_object" || \ test -z "$non_pic_object" || test "$pic_object" = none && \ test "$non_pic_object" = none; then $echo "$modename: cannot find name of object for \`$arg'" 1>&2 exit $EXIT_FAILURE fi # Extract subdirectory from the argument. xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` if test "X$xdir" = "X$arg"; then xdir= else xdir="$xdir/" fi if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles="$dlfiles $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles="$dlprefiles $pic_object" prev= fi # A PIC object. libobjs="$libobjs $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object non_pic_objects="$non_pic_objects $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" non_pic_objects="$non_pic_objects $non_pic_object" fi else # Only an error if not doing a dry-run. if test -z "$run"; then $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 exit $EXIT_FAILURE else # Dry-run case. # Extract subdirectory from the argument. xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` if test "X$xdir" = "X$arg"; then xdir= else xdir="$xdir/" fi pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` libobjs="$libobjs $pic_object" non_pic_objects="$non_pic_objects $non_pic_object" fi fi done else $echo "$modename: link input file \`$save_arg' does not exist" exit $EXIT_FAILURE fi arg=$save_arg prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) $echo "$modename: only absolute run-paths are allowed" 1>&2 exit $EXIT_FAILURE ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) rpath="$rpath $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) xrpath="$xrpath $arg" ;; esac fi prev= continue ;; xcompiler) compiler_flags="$compiler_flags $qarg" prev= compile_command="$compile_command $qarg" finalize_command="$finalize_command $qarg" continue ;; xlinker) linker_flags="$linker_flags $qarg" compiler_flags="$compiler_flags $wl$qarg" prev= compile_command="$compile_command $wl$qarg" finalize_command="$finalize_command $wl$qarg" continue ;; xcclinker) linker_flags="$linker_flags $qarg" compiler_flags="$compiler_flags $qarg" prev= compile_command="$compile_command $qarg" finalize_command="$finalize_command $qarg" continue ;; shrext) shrext_cmds="$arg" prev= continue ;; darwin_framework|darwin_framework_skip) test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg" compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" prev= continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then compile_command="$compile_command $link_static_flag" finalize_command="$finalize_command $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2 continue ;; -avoid-version) avoid_version=yes continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then $echo "$modename: more than one -exported-symbols argument is not allowed" exit $EXIT_FAILURE fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework|-arch|-isysroot) case " $CC " in *" ${arg} ${1} "* | *" ${arg} ${1} "*) prev=darwin_framework_skip ;; *) compiler_flags="$compiler_flags $arg" prev=darwin_framework ;; esac compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" ;; esac continue ;; -L*) dir=`$echo "X$arg" | $Xsed -e 's/^-L//'` # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2 absdir="$dir" notinst_path="$notinst_path $dir" fi dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "*) ;; *) deplibs="$deplibs -L$dir" lib_search_path="$lib_search_path $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; *) dllsearchpath="$dllsearchpath:$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; *) dllsearchpath="$dllsearchpath:$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework deplibs="$deplibs -framework System" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi deplibs="$deplibs $arg" continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. -model) compile_command="$compile_command $arg" compiler_flags="$compiler_flags $arg" finalize_command="$finalize_command $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) compiler_flags="$compiler_flags $arg" compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" continue ;; -module) module=yes continue ;; # -64, -mips[0-9] enable 64-bit mode on the SGI compiler # -r[0-9][0-9]* specifies the processor on the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler # +DA*, +DD* enable 64-bit mode on the HP compiler # -q* pass through compiler args for the IBM compiler # -m* pass through architecture-specific compiler args for GCC # -m*, -t[45]*, -txscale* pass through architecture-specific # compiler args for GCC # -pg pass through profiling flag for GCC # @file GCC response files -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \ -t[45]*|-txscale*|@*) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") arg="\"$arg\"" ;; esac compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" compiler_flags="$compiler_flags $arg" continue ;; -shrext) prev=shrext continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) # The PATH hackery in wrapper scripts is required on Windows # in order for the loader to find any dlls it needs. $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2 $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2 fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) dir=`$echo "X$arg" | $Xsed -e 's/^-R//'` # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) $echo "$modename: only absolute run-paths are allowed" 1>&2 exit $EXIT_FAILURE ;; esac case "$xrpath " in *" $dir "*) ;; *) xrpath="$xrpath $dir" ;; esac continue ;; -static) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -Wc,*) args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'` arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" case $flag in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") flag="\"$flag\"" ;; esac arg="$arg $wl$flag" compiler_flags="$compiler_flags $flag" done IFS="$save_ifs" arg=`$echo "X$arg" | $Xsed -e "s/^ //"` ;; -Wl,*) args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'` arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" case $flag in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") flag="\"$flag\"" ;; esac arg="$arg $wl$flag" compiler_flags="$compiler_flags $wl$flag" linker_flags="$linker_flags $flag" done IFS="$save_ifs" arg=`$echo "X$arg" | $Xsed -e "s/^ //"` ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # Some other compiler flag. -* | +*) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") arg="\"$arg\"" ;; esac ;; *.$objext) # A standard object. objs="$objs $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then pic_object= non_pic_object= # Read the .lo file # If there is no directory component, then add one. case $arg in */* | *\\*) . $arg ;; *) . ./$arg ;; esac if test -z "$pic_object" || \ test -z "$non_pic_object" || test "$pic_object" = none && \ test "$non_pic_object" = none; then $echo "$modename: cannot find name of object for \`$arg'" 1>&2 exit $EXIT_FAILURE fi # Extract subdirectory from the argument. xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` if test "X$xdir" = "X$arg"; then xdir= else xdir="$xdir/" fi if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles="$dlfiles $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles="$dlprefiles $pic_object" prev= fi # A PIC object. libobjs="$libobjs $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object non_pic_objects="$non_pic_objects $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" non_pic_objects="$non_pic_objects $non_pic_object" fi else # Only an error if not doing a dry-run. if test -z "$run"; then $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 exit $EXIT_FAILURE else # Dry-run case. # Extract subdirectory from the argument. xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` if test "X$xdir" = "X$arg"; then xdir= else xdir="$xdir/" fi pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` libobjs="$libobjs $pic_object" non_pic_objects="$non_pic_objects $non_pic_object" fi fi ;; *.$libext) # An archive. deplibs="$deplibs $arg" old_deplibs="$old_deplibs $arg" continue ;; *.la) # A libtool-controlled library. if test "$prev" = dlfiles; then # This library was specified with -dlopen. dlfiles="$dlfiles $arg" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. dlprefiles="$dlprefiles $arg" prev= else deplibs="$deplibs $arg" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` case $arg in *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") arg="\"$arg\"" ;; esac ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" fi done # argument parsing loop if test -n "$prev"; then $echo "$modename: the \`$prevarg' option requires an argument" 1>&2 $echo "$help" 1>&2 exit $EXIT_FAILURE fi if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" compile_command="$compile_command $arg" finalize_command="$finalize_command $arg" fi oldlibs= # calculate the name of the file, without its directory outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'` libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'` if test "X$output_objdir" = "X$output"; then output_objdir="$objdir" else output_objdir="$output_objdir/$objdir" fi # Create the object directory. if test ! -d "$output_objdir"; then $show "$mkdir $output_objdir" $run $mkdir $output_objdir exit_status=$? if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then exit $exit_status fi fi # Determine the type of output case $output in "") $echo "$modename: you must specify an output file" 1>&2 $echo "$help" 1>&2 exit $EXIT_FAILURE ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac case $host in *cygwin* | *mingw* | *pw32*) # don't eliminate duplications in $postdeps and $predeps duplicate_compiler_generated_deps=yes ;; *) duplicate_compiler_generated_deps=$duplicate_deps ;; esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if test "X$duplicate_deps" = "Xyes" ; then case "$libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi libs="$libs $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; esac pre_post_deps="$pre_post_deps $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries case $linkmode in lib) passes="conv link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2 exit $EXIT_FAILURE ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else compiler_flags="$compiler_flags $deplib" fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2 continue fi name=`$echo "X$deplib" | $Xsed -e 's/^-l//'` for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then library_names= old_library= case $lib in */* | *\\*) . $lib ;; *) . ./$lib ;; esac for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` test "X$ladir" = "X$lib" && ladir="." lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` ;; *) $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2 ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'` # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) xrpath="$xrpath $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) lib="$deplib" ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"` if eval $echo \"$deplib\" 2>/dev/null \ | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then $echo $echo "*** Warning: Trying to link with static lib archive $deplib." $echo "*** I have the capability to make that library automatically link in when" $echo "*** you link to this library. But I can only do this if you have a" $echo "*** shared version of the library, which you do not appear to have" $echo "*** because the file extensions .$libext of this argument makes me believe" $echo "*** that it is just a static archive that I should not used here." else $echo $echo "*** Warning: Linking the shared library $output against the" $echo "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. newdlprefiles="$newdlprefiles $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else newdlfiles="$newdlfiles $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2 exit $EXIT_FAILURE fi # Check to see that this really is a libtool archive. if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : else $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 exit $EXIT_FAILURE fi ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` test "X$ladir" = "X$lib" && ladir="." dlname= dlopen= dlpreopen= libdir= library_names= old_library= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file case $lib in */* | *\\*) . $lib ;; *) . ./$lib ;; esac if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && dlfiles="$dlfiles $dlopen" test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 exit $EXIT_FAILURE fi # It is a libtool convenience library, so add in its objects. convenience="$convenience $ladir/$objdir/$old_library" old_convenience="$old_convenience $ladir/$objdir/$old_library" tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if test "X$duplicate_deps" = "Xyes" ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done elif test "$linkmode" != prog && test "$linkmode" != lib; then $echo "$modename: \`$lib' is not a convenience library" 1>&2 exit $EXIT_FAILURE fi continue fi # $pass = conv # Get the name of the library we link against. linklib= for l in $old_library $library_names; do linklib="$l" done if test -z "$linklib"; then $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 exit $EXIT_FAILURE fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2 exit $EXIT_FAILURE fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. dlprefiles="$dlprefiles $lib $dependency_libs" else newdlfiles="$newdlfiles $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2 $echo "$modename: passing it literally to the linker, although it might fail" 1>&2 abs_ladir="$ladir" fi ;; esac laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then $echo "$modename: warning: library \`$lib' was moved." 1>&2 dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$libdir" absdir="$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later notinst_path="$notinst_path $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later notinst_path="$notinst_path $abs_ladir" fi fi # $installed = yes name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir"; then $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2 exit $EXIT_FAILURE fi # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then newdlprefiles="$newdlprefiles $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then newdlprefiles="$newdlprefiles $dir/$dlname" else newdlprefiles="$newdlprefiles $dir/$linklib" fi fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then newlib_search_path="$newlib_search_path $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if test "X$duplicate_deps" = "Xyes" ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; esac fi tmp_libs="$tmp_libs $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { test "$prefer_static_libs" = no || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath " in *" $dir "*) ;; *" $absdir "*) ;; *) temp_rpath="$temp_rpath $absdir" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath="$compile_rpath $absdir" esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes ; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then if test "$installed" = no; then notinst_deplibs="$notinst_deplibs $lib" need_relink=yes fi # This is a shared library # Warn about portability, can't link against -module's on # some systems (darwin) if test "$shouldnotlink" = yes && test "$pass" = link ; then $echo if test "$linkmode" = prog; then $echo "*** Warning: Linking the executable $output against the loadable module" else $echo "*** Warning: Linking the shared library $output against the loadable module" fi $echo "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath="$compile_rpath $absdir" esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath="$finalize_rpath $libdir" esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names realname="$2" shift; shift libname=`eval \\$echo \"$libname_spec\"` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw*) major=`expr $current - $age` versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" soname=`$echo $soroot | ${SED} -e 's/^.*\///'` newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a" # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else $show "extracting exported symbol list from \`$soname'" save_ifs="$IFS"; IFS='~' cmds=$extract_expsyms_cmds for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $show "$cmd" $run eval "$cmd" || exit $? done IFS="$save_ifs" fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else $show "generating import library for \`$soname'" save_ifs="$IFS"; IFS='~' cmds=$old_archive_from_expsyms_cmds for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $show "$cmd" $run eval "$cmd" || exit $? done IFS="$save_ifs" fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a module then we can not link against # it, someone is ignoring the new warnings I added if /usr/bin/file -L $add 2> /dev/null | $EGREP ": [^:]* bundle" >/dev/null ; then $echo "** Warning, lib $linklib is a module, not a shared library" if test -z "$old_library" ; then $echo $echo "** And there doesn't seem to be a static archive available" $echo "** The link will probably fail, sorry" else add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$dir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir="$add_dir -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then $echo "$modename: configuration error: unsupported hardcode properties" exit $EXIT_FAILURE fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && \ test "$hardcode_minus_L" != yes && \ test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir="$add_dir -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/main.cmake000066400000000000000000000041171250413007300256210ustar00rootroot00000000000000CMAKE_MINIMUM_REQUIRED(VERSION 2.6 FATAL_ERROR) SET( SOURCES back.c io.c main.c ) MESSAGE( ${SOURCES} ) # three arguments, prints "back.cio.cmain.c" MESSAGE( "${SOURCES}" ) # one argument, prints "back.c;io.c;main.c" MESSAGE( "" ) # one argument, prints "" an empty line MESSAGE( "${EMPTY_STRING}" ) # one argument, prints "" an empty line MESSAGE( ${EMPTY_STRING} ) # zero arguments, causes CMake Error # "MESSAGE called with incorrect number of arguments" MESSAGE( \\\"\ \(\)\#\$\^ ) # this message contains literal characters MESSAGE( "This is practice." ) # prints "This is practice." MESSAGE( "This;is;practice." ) # prints "This;is;practice." MESSAGE( "Hi. ) MESSAGE( x )" ) # prints "Hi. ) MESSAGE( x )" MESSAGE( "Welc"ome ) # rule 1 MESSAGE( Welc"ome" ) # rule 3 MESSAGE( Welc"ome)" ) # rule 2 MESSAGE( ""Thanks ) # rule 1 MESSAGE( Thanks"" ) # rule 3 SET( x y A B C ) # stores "y;A;B;C" in x (without quote) SET( ${x} ) # => SET( y;A;B;C ) => SET( y A B C) MESSAGE( ${y} ) # prints "ABC" to stdout (without quotes) SET( y x ) # stores "x" in y (without quotes) SET( ${y} y = x ) # => SET( x y ) MESSAGE( "\${x} = '${x}'" ) # prints "${x} = 'y;=;x'" to stdout (without quotes) SET( y ${x} ) # => SET( y y = x ) => stores "y;=;x" in y (without quotes) MESSAGE( ${y} ) # prints "y=x" to stdout (without quotes) SET( x a b c ) # stores "a;b;c" in x (without quotes) SET( y "a b c" ) # stores "a b c" in y (without quotes) MESSAGE( a b c ) # prints "abc" to stdout (without quotes) MESSAGE( ${x} ) # prints "abc" to stdout (without quotes) MESSAGE("${x}") # prints "a;b;c" to stdout (without quotes) MESSAGE( ${y} ) # prints "a b c" to stdout (without quotes) MESSAGE("${y}") # prints "a b c" to stdout (without quotes) # This is a comment. COMMAND( arguments go here ) ANOTHER_COMMAND() # this command has no arguments YET_ANOTHER_COMMAND( these arguments are spread # another comment over several lines ) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/markdown.lsp000077500000000000000000000523301250413007300262400ustar00rootroot00000000000000#!/usr/bin/env newlisp ;; @module markdown ;; @author cormullion ;; @description a port of John Gruber's Markdown to newLISP ;; @location http://unbalanced-parentheses.nfshost.com/ ;; @version of date 2011-10-02 22:36:02 ;; version history: at the end ;; a port of John Gruber's Markdown.pl (http://daringfireball.net/markdown) script to newLISP... ;; see his original Perl script for explanations of the fearsome regexen and ;; byzantine logic, etc... ;; TODO: ;; the following Markdown tests fail: ;; Inline HTML (Advanced) ... FAILED ;; Links, reference style ... FAILED -- nested brackets ;; Links, shortcut references ... FAILED ;; Markdown Documentation - Syntax ... FAILED ;; Ordered and unordered lists ... FAILED -- a nested ordered list error ;; parens in url : ![this is a stupid URL](http://example.com/(parens).jpg) see (Images.text) ;; Add: email address scrambling (context 'Hash) (define HashTable:HashTable) (define (build-escape-table) (set '*escape-chars* [text]\`*_{}[]()>#+-.![/text]) (dolist (c (explode *escape-chars*)) (HashTable c (hash c)))) (define (init-hash txt) ; finds a hash identifier that doesn't occur anywhere in the text (set 'counter 0) (set 'hash-prefix "HASH") (set 'hash-id (string hash-prefix counter)) (do-while (find hash-id txt) (set 'hash-id (string hash-prefix (inc counter)))) (Hash:build-escape-table)) (define (hash s) (HashTable s (string hash-id (inc counter)))) (context 'markdown) (define (markdown:markdown txt) (initialize) (Hash:init-hash txt) (unescape-special-chars (block-transforms (strip-link-definitions (protect (cleanup txt)))))) (define (initialize) (set '*escape-pairs* '( ({\\\\} {\}) ({\\`} {`}) ({\\\*} {*}) ({\\_} {_}) ([text]\\\{[/text] [text]{[/text]) ([text]\\\}[/text] [text]}[/text]) ({\\\[} {[}) ({\\\]} {]}) ({\\\(} {(}) ({\\\)} {)}) ({\\>} {>}) ({\\\#} {#}) ({\\\+} {+}) ({\\\-} {-}) ({\\\.} {.}) ({\\!} {!}))) (set '*hashed-html-blocks* '()) (set '*list-level* 0)) (define (block-transforms txt) (form-paragraphs (protect (block-quotes (code-blocks (lists (horizontal-rules (headers txt)))))))) (define (span-transforms txt) (line-breaks (emphasis (amps-and-angles (auto-links (anchors (images (escape-special-chars (escape-special-chars (code-spans txt) 'inside-attributes))))))))) (define (tokenize-html xhtml) ; return list of tag/text portions of xhtml text (letn ( (tag-match [text]((?s:)| (?s:<\?.*?\?>)| (?:<[a-z/!$](?:[^<>]| (?:<[a-z/!$](?:[^<>]| (?:<[a-z/!$](?:[^<>]| (?:<[a-z/!$](?:[^<>]| (?:<[a-z/!$](?:[^<>]| (?:<[a-z/!$](?:[^<>])*>))*>))*>))*>))*>))*>))[/text]) ; yeah, well... (str xhtml) (len (length str)) (pos 0) (tokens '())) (while (set 'tag-start (find tag-match str 8)) (if (< pos tag-start) (push (list 'text (slice str pos (- tag-start pos))) tokens -1)) (push (list 'tag $0) tokens -1) (set 'str (slice str (+ tag-start (length $0)))) (set 'pos 0)) ; leftovers (if (< pos len) (push (list 'text (slice str pos (- len pos))) tokens -1)) tokens)) (define (escape-special-chars txt (within-tag-attributes nil)) (let ((temp (tokenize-html txt)) (new-text {})) (dolist (pair temp) (if (= (first pair) 'tag) ; 'tag (begin (set 'new-text (replace {\\} (last pair) (HashTable {\\}) 0)) (replace [text](?<=.)(?=.)[/text] new-text (HashTable {`}) 0) (replace {\*} new-text (HashTable {*}) 0) (replace {_} new-text (HashTable {_} ) 0)) ; 'text (if within-tag-attributes (set 'new-text (last pair)) (set 'new-text (encode-backslash-escapes (last pair))))) (setf (temp $idx) (list (first pair) new-text))) ; return as text (join (map last temp)))) (define (encode-backslash-escapes t) (dolist (pair *escape-pairs*) (replace (first pair) t (HashTable (last pair)) 14))) (define (encode-code s) ; encode/escape certain characters inside Markdown code runs (replace {&} s "&" 0) (replace {<} s "<" 0) (replace {>} s ">" 0) (replace {\*} s (HashTable {\\}) 0) (replace {_} s (HashTable {_}) 0) (replace "{" s (HashTable "{") 0) (replace {\[} s (HashTable {[}) 0) (replace {\]} s (HashTable {]}) 0) (replace {\\} s (HashTable "\\") 0)) (define (code-spans s) (replace {(?} (encode-code (trim $2)) {
    }) 2)) (define (encode-alt s) (replace {&} s "&" 0) (replace {"} s """ 0)) (define (images txt) (let ((alt-text {}) (url {}) (title {}) (ref-regex {(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])}) (inline-regex {(!\[(.*?)\]\([ \t]*?[ \t]*((['"])(.*?)\5[ \t]*)?\))}) (whole-match {}) (result {}) (id-ref {}) (url {})) ; reference links ![alt text][id] (replace ref-regex txt (begin (set 'whole-match $1 'alt-text $2 'id-ref $3) (if alt-text (replace {"} alt-text {"} 0)) (if (empty? id-ref) (set 'id-ref (lower-case alt-text))) (if (lookup id-ref *link-database*) (set 'url (first (lookup id-ref *link-database*))) (set 'url nil)) (if url (begin (replace {\*} url (HashTable {*}) 0) (replace {_} url (HashTable {_}) 0) )) (if (last (lookup id-ref *link-database*)) ; title (begin (set 'title (last (lookup id-ref *link-database*))) (replace {"} title {"} 0) (replace {\*} title (HashTable {*}) 0) (replace {_} title (HashTable {_}) 0)) ; no title (set 'title {}) ) (if url (set 'result (string {} 
          alt-text {})) (set 'result whole-match)) ) 0 ) ; inline image refs: ![alt text](url "optional title") (replace inline-regex txt (begin (set 'whole-match $1) (set 'alt-text $2) (set 'url $3) (set 'title $6) (if alt-text (replace {"} alt-text {"} 0) (set 'alt-text {})) (if title (begin (replace {"} title {"} 0) (replace {\*} title (HashTable {*}) 0) (replace {_} title (HashTable {_}) 0)) (set 'title {})) (replace {\*} url (HashTable {*}) 0) (replace {_} url (HashTable {_}) 0) (string {} 
           alt-text {}) ) 0 ) ; empty ones are possible (set '$1 {}) (replace {!\[(.*?)\]\([ \t]*\)} txt (string {} $1 {}) 0))) (define (make-anchor link-text id-ref ) ; Link defs are in the form: ^[id]: url "optional title" ; stored in link db list as (id (url title)) ; params are text to be linked and the id of the link in the db ; eg bar 1 for [bar][1] (let ((title {}) (id id-ref) (url nil)) (if link-text (begin (replace {"} link-text {"} 0) (replace {\n} link-text { } 0) (replace {[ ]?\n} link-text { } 0))) (if (null? id ) (set 'id (lower-case link-text))) (if (not (nil? (lookup id *link-database*))) (begin (set 'url (first (lookup id *link-database*))) (replace {\*} url (HashTable {*}) 0) (replace {_} url (HashTable {_}) 0) (if (set 'title (last (lookup id *link-database*))) (begin (replace {"} title {"} 0) (replace {\*} title (HashTable {*}) 0) (replace {_} title (HashTable {_}) 0)) (set 'title {}))) (set 'url nil)) (if url (string {} link-text {}) (string {[} link-text {][} id-ref {]})))) (define (anchors txt) (letn ((nested-brackets {(?>[^\[\]]+)*}) (ref-link-regex (string {(\[(} nested-brackets {)\][ ]?(?:\n[ ]*)?\[(.*?)\])})) (inline-regex {(\[(.*?)\]\([ ]*?[ ]*((['"])(.*?)\5[ \t]*)?\))}) (link-text {}) (url {}) (title {})) ; reference-style links: [link text] [id] (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {} '$6 {}) ; i still don't think I should have to do this... ; what about this regex instead? (set 'ref-link-regex {(\[(.*?)\][ ]?\[(.*?)\])}) (replace ref-link-regex txt (make-anchor $2 $3) 8) ; $2 is link text, $3 is id ; inline links: [link text](url "optional title") (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {} '$6 {}) (replace inline-regex txt (begin (set 'link-text $2) (set 'url $3) (set 'title $6) (if link-text (replace {"} link-text {"} 0)) (if title (begin (replace {"} title {"} 0) (replace {\*} title (HashTable {*}) 0) (replace {_} title (HashTable {_}) 0)) (set 'title {})) (replace {\*} url (HashTable {*}) 0) (replace {_} url (HashTable {_}) 0) (replace {^<(.*)>$} url $1 0) (string {} link-text {} )) 8 ) ; replace ) txt) (define (auto-links txt) (replace [text]<((https?|ftp):[^'">\s]+)>[/text] txt (string {} $1 {}) 0 ) ; to-do: email ... ) (define (amps-and-angles txt) ; Smart processing for ampersands and angle brackets (replace [text]&(?!\#?[xX]?(?:[0-9a-fA-F]+|\w+);)[/text] txt {&} 10 ) (replace [text]<(?![a-z/?\$!])[/text] txt {<} 10)) (define (emphasis txt) ; italics/bold: strong first (replace [text] (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 [/text] txt (string {} $2 {}) 8 ) (replace [text] (\*|_) (?=\S) (.+?) (?<=\S) \1 [/text] txt (string {} $2 {}) 8 )) (define (line-breaks txt) ; handles line break markers (replace " {2,}\n" txt "
    \n" 0)) (define (hex-str-to-unicode-char strng) ; given a five character string, assume it's "U" + 4 hex chars and convert ; return the character... (char (int (string "0x" (1 strng)) 0 16))) (define (ustring s) ; any four digit string preceded by U (replace "U[0-9a-f]{4,}" s (hex-str-to-unicode-char $0) 0)) (define (cleanup txt) ; cleanup the text by normalizing some possible variations (replace "\r\n|\r" txt "\n" 0) ; standardize line ends (push "\n\n" txt -1) ; end with two returns (set 'txt (detab txt)) ; convert tabs to spaces ; convert inline Unicode: (set 'txt (ustring txt)) (replace "\n[ \t]+\n" txt "\n\n" 0) ; lines with only spaces and tabs ) (define (protect txt) ; protect or "hash html blocks" (letn ((nested-block-regex [text](^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b(.*\n)*?[ \t]*(?=\n+|\Z))[/text]) (liberal-tag-regex [text](^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b(.*\n)*?.*[ \t]*(?=\n+|\Z))[/text]) (hr-regex [text](?:(?<=\n\n)|\A\n?)([ ]{0,3}<(hr)\b([^<>])*?/?>[ \t]*(?=\n{2,}|\Z))[/text]) (html-comment-regex [text](?:(?<=\n\n)|\A\n?)([ ]{0,3}(?s:)[ \t]*(?=\n{2,}|\Z))[/text]) (results '()) (chunk-count (length (set 'chunks (parse txt "\n\n")))) (chunk-size 500)) ; due to a limitation in PCRE, long sections have to be divided up otherwise we'll crash ; so divide up long texts into chunks, then do the regex on each chunk ; not an ideal solution, but it works ok :( (for (i 0 chunk-count chunk-size) ; do a chunk (set 'text-chunk (join (i (- (min chunk-count (- (+ i chunk-size) 1)) i) chunks) "\n\n")) (dolist (rgx (list nested-block-regex liberal-tag-regex hr-regex html-comment-regex)) (replace rgx text-chunk (begin (set 'key (Hash:hash $1)) (push (list key $1 ) *hashed-html-blocks* -1) (string "\n\n" key "\n\n")) 2)) ; save this partial result (push text-chunk results -1) ) ; for ; return string result (join results "\n\n"))) (define (unescape-special-chars t) ; Swap back in all the special characters we've hidden. (dolist (pair (HashTable)) (replace (last pair) t (first pair) 10)) t) (define (strip-link-definitions txt) ; strip link definitions from the text and store them ; Link defs are in the form: ^[id]: url "optional title" ; stored in link db list as (id (url title)) (let ((link-db '()) (url {}) (id {}) (title {})) (replace [text]^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(?<=\s)["(](.+?)[")][ \t]*)?(?:\n+|\Z)[/text] txt (begin (set 'id (lower-case $1) 'url (amps-and-angles $2) 'title $3) (if title (replace {"} title {"} 0)) (push (list id (list url title)) link-db) (set '$3 {}) ; necessary? (string {}) ; remove from text ) 10) (set '*link-database* link-db) txt)) (define (horizontal-rules txt) (replace [text]^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$[/text] txt "\n
    " 14) (replace [text]^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$[/text] txt "\n
    " 14) (replace [text]^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$[/text] txt "\n
    " 14)) (define (headers txt) ; setext headers (let ((level 1)) (replace [text]^(.+)[ \t]*\n=+[ \t]*\n+[/text] txt (string "

    " (span-transforms $1) "

    \n\n") 2) (replace [text]^(.+)[ \t]*\n-+[ \t]*\n+[/text] txt (string "

    " (span-transforms $1) "

    \n\n") 2) ; atx headers (replace [text]^(\#{1,6})\s*(.+?)[ ]*\#*(\n+)[/text] txt (begin (set 'level (length $1)) (string "" (span-transforms $2) "\n\n") ) 2))) (define (lists txt) (letn ((marker-ul {[*+-]}) (marker-ol {\d+[.]}) (marker-any (string {(?:} marker-ul {|} marker-ol {)})) (whole-list-regex (string [text](([ ]{0,3}([/text] marker-any [text])[ \t]+)(?s:.+?)(\z|\n{2,}(?=\S)(?![ \t]*[/text] marker-any [text][ \t]+)))[/text])) (my-list {}) (list-type {}) (my-result {})) (replace (if (> *list-level* 0) (string {^} whole-list-regex) (string {(?:(?<=\n\n)|\A\n?)} whole-list-regex)) txt (begin (set 'my-list $1) (if (find $3 marker-ul) (set 'list-type "ul" 'marker-type marker-ul) (set 'list-type "ol" 'marker-type marker-ol)) (replace [text]\n{2,}[/text] my-list "\n\n\n" 0) (set 'my-result (process-list-items my-list marker-any)) (replace {\s+$} my-result {} 0) (string {<} list-type {>} "\n" my-result "\n" {} "\n")) 10 ; must be multiline ))) (define (process-list-items list-text marker-any) (let ((list-regex (string [text](\n)?(^[ \t]*)([/text] marker-any [text])[ \t]+((?s:.+?)(\n{1,2}))(?=\n*(\z|\2([/text] marker-any [text])[ \t]+))[/text])) (item {}) (leading-line {}) (leading-space {}) (result {})) (inc *list-level*) (replace [text]\n{2,}\z[/text] list-text "\n" 0) (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {}) (replace list-regex list-text (begin (set 'item $4) (set 'leading-line $1) (set 'leading-space $2) (if (or (not (empty? leading-line)) (ends-with item "\n{2,}" 0)) (set 'item (block-transforms (outdent item))) ; recurse for sub lists (begin (set 'item (lists (outdent item))) (set 'item (span-transforms (trim item "\n"))) )) (string {
  • } item {
  • } "\n")) 10) (dec *list-level*) list-text)) (define (code-blocks txt) (let ((code-block {}) (token-list '())) (replace [text](?:\n\n|\A)((?:(?:[ ]{4}|\t).*\n+)+)((?=^[ ]{0,3}\S)|\Z)[/text] txt (begin (set 'code-block $1) ; format if Nestor module is loaded and it's not marked as plain (if (and (not (starts-with code-block " ;plain\n")) (context? Nestor)) ; format newlisp (begin ; remove flag if present (replace "[ ]{4};newlisp\n" code-block {} 0) (set 'code-block (protect (Nestor:nlx-to-html (Nestor:my-read (trim (detab (outdent code-block)) "\n"))))) code-block) ; don't format (begin ; trim leading and trailing newlines (replace "[ ]{4};plain\n" code-block {} 0) (set 'code-block (trim (detab (encode-code (outdent code-block))) "\n")) (set '$1 {}) (set 'code-block (string "\n\n
    " code-block "\n
    \n\n"))))) 10))) (define (block-quotes txt) (let ((block-quote {})) (replace [text]((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)[/text] txt (begin (set 'block-quote $1) (replace {^[ ]*>[ ]?} block-quote {} 2) (replace {^[ ]+$} block-quote {} 2) (set 'block-quote (block-transforms block-quote)) ; recurse ; remove leading spaces (replace {(\s*
    .+?
    )} block-quote (trim $1) 2) (string "
    \n" block-quote "\n
    \n\n")) 2))) (define (outdent s) (replace [text]^(\t|[ ]{1,4})[/text] s {} 2)) (define (detab s) (replace [text](.*?)\t[/text] s (string $1 (dup { } (- 4 (% (length $1) 4)))) 2)) (define (form-paragraphs txt) (let ((grafs '()) (original nil)) (set 'txt (trim txt "\n")) ; strip blank lines before and after (set 'grafs (parse txt "\n{2,}" 0)) ; split (dolist (p grafs) (if (set 'original (lookup p *hashed-html-blocks*)) ; html blocks (setf (grafs $idx) original) ; wrap

    tags round everything else (setf (grafs $idx) (string {

    } (replace {^[ ]*} (span-transforms p) {} (+ 4 8 16)) {

    })))) (join grafs "\n\n"))) [text] ; three command line arguments: let's hope last one is a file (when (= 3 (length (main-args))) (println (markdown (read-file (main-args 2)))) (exit)) ; hack for command-line and module loading (set 'level (sys-info 3)) ; if level is 2, then we're probably invoking markdown.lsp directly ; if level is > 3, then we're probably loading it into another script... (when (= level 2) ; running on command line, read STDIN and execute: (while (read-line) (push (current-line) *stdin* -1)) (println (markdown (join *stdin* "\n"))) (exit)) [/text] ;; version 2011-09-16 16:31:29 ;; Changed to different hash routine. Profiling shows that hashing takes 40% of the execution time. ;; Unfortunately this new version is only very slightly faster. ;; Command-line arguments hack in previous version doesn't work. ;; ;; version 2011-08-18 15:04:40 ;; various fixes, and added hack for running this from the command-line: ;; echo "hi there" | newlisp markdown.lsp ;; echo "hello world" | markdown.lsp ;; cat file.text | newlisp markdown.lsp ;; ;; version 2010-11-14 17:34:52 ;; some problems in ustring. Probably remove it one day, as it's non standard... ;; ;; version 2010-10-14 18:41:38 ;; added code to work round PCRE crash in (protect ... ;; ;; version date 2010-07-10 22:20:25 ;; modified call to 'read' since lutz has changed it ;; ;; version date 2009-11-16 22:10:10 ;; fixed bug in tokenize.html ;; ;; version date 2008-10-08 18:44:46 ;; changed nth-set to setf to be version-10 ready. ;; This means that now this script will NOT work with ;; earlier versions of newLISP!!!!!!!!!!! ;; requires Nestor if you want source code colouring... ;; ;; version date 2008-08-08 16:54:56 ;; changed (unless to (if (not ... :( ;; ;; version date 2008-07-20 14:!2:29 ;; added hex-str-to-unicode-char ustring ;; ;; version date 2008-03-07 15:36:09 ;; fixed load error ;; ;; version date 2007-11-17 16:20:57 ;; added syntax colouring module ;; ;; version date 2007-11-14 09:19:42 ;; removed reliance on dostring for compatibility with 9.1 ; eofpygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/matlab_noreturn000066400000000000000000000000451250413007300270060ustar00rootroot00000000000000 function myfunc(s) a = 1; end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/matlab_sample000066400000000000000000000010341250413007300264120ustar00rootroot00000000000000function zz=sample(aa) %%%%%%%%%%%%%%%%%% % some comments %%%%%%%%%%%%%%%%%% x = 'a string'; % some 'ticks' in a comment y = 'a string with ''interal'' quotes'; for i=1:20 disp(i); end a = rand(30); b = rand(30); c = a .* b ./ a \ ... comment at end of line and continuation (b .* a + b - a); c = a' * b'; % note: these ticks are for transpose, not quotes. disp('a comment symbol, %, in a string'); !echo abc % this isn't a comment - it's passed to system command function y=myfunc(x) y = exp(x); {% a block comment %} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/matlabsession_sample.txt000066400000000000000000000004621250413007300306400ustar00rootroot00000000000000>> >> >> a = 'okay' a = okay >> x = rand(3) % a matrix x = 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575 >> 1/0 ans = Inf >> foo ??? Undefined function or variable 'foo'. >> >> >> {cos(2*pi), 'testing'} ans = [1] 'testing' >> >> >> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/metagrammar.treetop000066400000000000000000000243251250413007300275770ustar00rootroot00000000000000module Treetop module Compiler grammar Metagrammar rule treetop_file requires:(space? require_statement)* prefix:space? module_or_grammar suffix:space? { def compile requires.text_value + prefix.text_value + module_or_grammar.compile + suffix.text_value end } end rule require_statement prefix:space? "require" [ \t]+ [^\n\r]+ [\n\r] end rule module_or_grammar module_declaration / grammar end rule module_declaration prefix:('module' space name:([A-Z] alphanumeric_char* ('::' [A-Z] alphanumeric_char*)*) space) module_contents:(module_declaration / grammar) suffix:(space 'end') { def compile prefix.text_value + module_contents.compile + suffix.text_value end def parser_name prefix.name.text_value+'::'+module_contents.parser_name end } end rule grammar 'grammar' space grammar_name space ('do' space)? declaration_sequence space? 'end' end rule grammar_name ([A-Z] alphanumeric_char*) end rule declaration_sequence head:declaration tail:(space declaration)* { def declarations [head] + tail end def tail super.elements.map { |elt| elt.declaration } end } / '' { def compile(builder) end } end rule declaration parsing_rule / include_declaration end rule include_declaration 'include' space [A-Z] (alphanumeric_char / '::')* { def compile(builder) builder << text_value end } end rule parsing_rule 'rule' space nonterminal space ('do' space)? parsing_expression space 'end' end rule parsing_expression choice / sequence / primary end rule choice head:alternative tail:(space? '/' space? alternative)+ { def alternatives [head] + tail end def tail super.elements.map {|elt| elt.alternative} end def inline_modules (alternatives.map {|alt| alt.inline_modules }).flatten end } end rule sequence head:labeled_sequence_primary tail:(space labeled_sequence_primary)+ node_class_declarations { def sequence_elements [head] + tail end def tail super.elements.map {|elt| elt.labeled_sequence_primary } end def inline_modules (sequence_elements.map {|elt| elt.inline_modules}).flatten + [sequence_element_accessor_module] + node_class_declarations.inline_modules end def inline_module_name node_class_declarations.inline_module_name end } end rule alternative sequence / primary end rule primary prefix atomic { def compile(address, builder, parent_expression=nil) prefix.compile(address, builder, self) end def prefixed_expression atomic end def inline_modules atomic.inline_modules end def inline_module_name nil end } / prefix space? predicate_block { def compile(address, builder, parent_expression=nil) prefix.compile(address, builder, self) end def prefixed_expression predicate_block end def inline_modules [] end } / atomic suffix node_class_declarations { def compile(address, builder, parent_expression=nil) suffix.compile(address, builder, self) end def optional_expression atomic end def node_class_name node_class_declarations.node_class_name end def inline_modules atomic.inline_modules + node_class_declarations.inline_modules end def inline_module_name node_class_declarations.inline_module_name end } / atomic node_class_declarations { def compile(address, builder, parent_expression=nil) atomic.compile(address, builder, self) end def node_class_name node_class_declarations.node_class_name end def inline_modules atomic.inline_modules + node_class_declarations.inline_modules end def inline_module_name node_class_declarations.inline_module_name end } end rule labeled_sequence_primary label sequence_primary { def compile(lexical_address, builder) sequence_primary.compile(lexical_address, builder) end def inline_modules sequence_primary.inline_modules end def label_name if label.name label.name elsif sequence_primary.instance_of?(Nonterminal) sequence_primary.text_value else nil end end } end rule label (alpha_char alphanumeric_char*) ':' { def name elements[0].text_value end } / '' { def name nil end } end rule sequence_primary prefix atomic { def compile(lexical_address, builder) prefix.compile(lexical_address, builder, self) end def prefixed_expression elements[1] end def inline_modules atomic.inline_modules end def inline_module_name nil end } / prefix space? predicate_block { def compile(address, builder, parent_expression=nil) prefix.compile(address, builder, self) end def prefixed_expression predicate_block end def inline_modules [] end } / atomic suffix { def compile(lexical_address, builder) suffix.compile(lexical_address, builder, self) end def node_class_name nil end def inline_modules atomic.inline_modules end def inline_module_name nil end } / atomic end rule suffix repetition_suffix / optional_suffix end rule optional_suffix '?' end rule node_class_declarations node_class_expression trailing_inline_module { def node_class_name node_class_expression.node_class_name end def inline_modules trailing_inline_module.inline_modules end def inline_module trailing_inline_module.inline_module end def inline_module_name inline_module.module_name if inline_module end } end rule repetition_suffix '+' / '*' / occurrence_range end rule occurrence_range space? min:([0-9])* '..' max:([0-9])* end rule prefix '&' / '!' / '~' end rule atomic terminal / nonterminal / parenthesized_expression end rule parenthesized_expression '(' space? parsing_expression space? ')' { def inline_modules parsing_expression.inline_modules end } end rule nonterminal !keyword_inside_grammar (alpha_char alphanumeric_char*) end rule terminal quoted_string / character_class / anything_symbol end rule quoted_string (single_quoted_string / double_quoted_string) { def string super.text_value end } end rule double_quoted_string '"' string:(!'"' ("\\\\" / '\"' / .))* '"' end rule single_quoted_string "'" string:(!"'" ("\\\\" / "\\'" / .))* "'" end rule character_class '[' characters:(!']' ('\\' . / bracket_expression / !'\\' .))+ ']' { def characters super.text_value end } end rule bracket_expression '[:' '^'? ( 'alnum' / 'alpha' / 'blank' / 'cntrl' / 'digit' / 'graph' / 'lower' / 'print' / 'punct' / 'space' / 'upper' / 'xdigit' / 'word' ) ':]' end rule anything_symbol '.' end rule node_class_expression space '<' (!'>' .)+ '>' { def node_class_name elements[2].text_value end } / '' { def node_class_name nil end } end rule trailing_inline_module space inline_module { def inline_modules [inline_module] end def inline_module_name inline_module.module_name end } / '' { def inline_modules [] end def inline_module nil end def inline_module_name nil end } end rule predicate_block '' inline_module end rule inline_module '{' (inline_module / ![{}] .)* '}' end rule keyword_inside_grammar ('rule' / 'end') !non_space_char end rule non_space_char !space . end rule alpha_char [A-Za-z_] end rule alphanumeric_char alpha_char / [0-9] end rule space (white / comment_to_eol)+ end rule comment_to_eol '#' (!"\n" .)* end rule white [ \t\n\r] end end end end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/minehunt.qml000066400000000000000000000075101250413007300262350ustar00rootroot00000000000000 /**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ import QtQuick 1.0 import "MinehuntCore" 1.0 Item { id: field property int clickx: 0 property int clicky: 0 width: 450; height: 450 Image { source: "MinehuntCore/pics/background.png"; anchors.fill: parent; fillMode: Image.Tile } Grid { anchors.horizontalCenter: parent.horizontalCenter columns: 9; spacing: 1 Repeater { id: repeater model: tiles delegate: Tile {} } } Row { id: gamedata x: 20; spacing: 20 anchors.bottom: field.bottom; anchors.bottomMargin: 15 Image { source: "MinehuntCore/pics/quit.png" scale: quitMouse.pressed ? 0.8 : 1.0 smooth: quitMouse.pressed y: 10 MouseArea { id: quitMouse anchors.fill: parent anchors.margins: -20 onClicked: Qt.quit() } } Column { spacing: 2 Image { source: "MinehuntCore/pics/bomb-color.png" } Text { anchors.horizontalCenter: parent.horizontalCenter; color: "white"; text: numMines } } Column { spacing: 2 Image { source: "MinehuntCore/pics/flag-color.png" } Text { anchors.horizontalCenter: parent.horizontalCenter; color: "white"; text: numFlags } } } Image { anchors.bottom: field.bottom; anchors.bottomMargin: 15 anchors.right: field.right; anchors.rightMargin: 20 source: isPlaying ? 'MinehuntCore/pics/face-smile.png' : hasWon ? 'MinehuntCore/pics/face-smile-big.png': 'MinehuntCore/pics/face-sad.png' MouseArea { anchors.fill: parent; onPressed: reset() } } Text { anchors.centerIn: parent; width: parent.width - 20 horizontalAlignment: Text.AlignHCenter wrapMode: Text.WordWrap text: "Minehunt demo has to be compiled to run.\n\nPlease see README." color: "white"; font.bold: true; font.pixelSize: 14 visible: tiles == undefined } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/minimal.ns2000066400000000000000000000001721250413007300257420ustar00rootroot00000000000000class A = ( | a = self m. | ) ( m = (^a isNil ifTrue: [0] ifFalse: [1]) ) class B = C ( | b0 = 0. b1 = b0 + 1. | ) () pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/moin_SyntaxReference.txt000066400000000000000000000165441250413007300305720ustar00rootroot00000000000000## Please edit system and help pages ONLY in the moinmaster wiki! For more ## information, please see MoinMaster:MoinPagesEditorGroup. ##master-page:Unknown-Page ##master-date:Unknown-Date #acl MoinPagesEditorGroup:read,write,delete,revert All:read #format wiki #language en This page aims to introduce the most important elements of MoinMoin``'s syntax at a glance, showing first the markup verbatim and then how it is rendered by the wiki engine. Additionally, you'll find links to the relative help pages. Please note that some of the features depend on your configuration. = Table of Contents = {{{ '''Contents''' (up to the 2nd level) [[TableOfContents(2)]] }}} '''Contents''' (up to the 2nd level) [[TableOfContents(2)]] = Headings = '''''see:''' HelpOnHeadlines'' {{{ = heading 1st level = == heading 2nd level == === heading 3rd level === ==== heading 4th level ==== ===== heading 5th level ===== }}} = heading 1st level = == heading 2nd level == === heading 3rd level === ==== heading 4th level ==== ===== heading 5th level ===== = Text Formatting = '''''see:''' HelpOnFormatting'' {{{ * ''emphasized (italics)'' * '''boldface''' * '''''bold italics''''' * `monospace` * {{{source code}}} * __underline__ * ,,sub,,script * ^super^script * ~-smaller-~ * ~+larger+~ * --(strike through)-- }}} * ''emphasized (italics)'' * '''boldface''' * '''''bold italics''''' * `monospace` * {{{source code}}} * __underline__ * ,,sub,,script * ^super^script * ~-smaller-~ * ~+larger+~ * --(strike through)-- = Hyperlinks = '''''see:''' HelpOnLinking'' == Internal Links == {{{ * FrontPage * ["FrontPage"] * HelpOnEditing/SubPages * /SubPage * ../SiblingPage * [:FrontPage:named link] * [#anchorname] * [#anchorname description] * [wiki:Self:PageName#anchorname] * [wiki:Self:PageName#anchorname description] * attachment:filename.txt }}} * FrontPage * ["FrontPage"] * HelpOnEditing/SubPages * /SubPage * ../SiblingPage * [:FrontPage:named link] * [#anchorname] * [#anchorname description] * [wiki:Self:PageName#anchorname] * [wiki:Self:PageName#anchorname description] * attachment:filename.txt == External Links == {{{ * http://moinmoin.wikiwikiweb.de/ * [http://moinmoin.wikiwikiweb.de/] * [http://moinmoin.wikiwikiweb.de/ MoinMoin Wiki] * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png] * http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png moinmoin.png] * MeatBall:InterWiki * wiki:MeatBall/InterWiki * [wiki:MeatBall/InterWiki] * [wiki:MeatBall/InterWiki InterWiki page on MeatBall] * [file://///servername/share/full/path/to/file/filename%20with%20spaces.txt link to file filename with spaces.txt] * user@example.com }}} * http://moinmoin.wikiwikiweb.de/ * [http://moinmoin.wikiwikiweb.de/] * [http://moinmoin.wikiwikiweb.de/ MoinMoin Wiki] * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png] * http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png moinmoin.png] * MeatBall:InterWiki * wiki:MeatBall/InterWiki * [wiki:MeatBall/InterWiki] * [wiki:MeatBall/InterWiki InterWiki page on MeatBall] * [file://///servername/share/full/path/to/file/filename%20with%20spaces.txt link to file filename with spaces.txt] * user@example.com == Avoid or Limit Automatical Linking == {{{ * Wiki''''''Name * Wiki``Name * !WikiName * WikiName''''''s * WikiName``s * `http://www.example.com` }}} * Wiki''''''Name * Wiki``Name * !WikiName * WikiName''''''s * WikiName``s * `http://www.example.com` = Blockquotes and Indentions = {{{ indented text text indented to the 2nd level }}} indented text text indented to the 2nd level = Lists = '''''see:''' HelpOnLists'' == Unordered Lists == {{{ * item 1 * item 2 (preceding white space) * item 2.1 * item 2.1.1 * item 3 . item 3.1 (bulletless) . item 4 (bulletless) * item 4.1 . item 4.1.1 (bulletless) }}} * item 1 * item 2 (preceding white space) * item 2.1 * item 2.1.1 * item 3 . item 3.1 (bulletless) . item 4 (bulletless) * item 4.1 . item 4.1.1 (bulletless) == Ordered Lists == === with Numbers === {{{ 1. item 1 1. item 1.1 1. item 1.2 1. item 2 }}} 1. item 1 1. item 1.1 1. item 1.2 1. item 2 === with Roman Numbers === {{{ I. item 1 i. item 1.1 i. item 1.2 I. item 2 }}} I. item 1 i. item 1.1 i. item 1.2 I. item 2 === with Letters === {{{ A. item A a. item A. a) a. item A. b) A. item B }}} A. item A a. item A. a) a. item A. b) A. item B == Definition Lists == {{{ term:: definition object:: description 1 :: description 2 Action Items:: :: First Item :: Second Item }}} term:: definition object:: description 1 :: description 2 Action Items:: :: First Item :: Second Item = Horizontal Rules = '''''see:''' HelpOnRules'' {{{ ---- ----- ------ ------- -------- --------- ---------- }}} ---- ----- ------ ------- -------- --------- ---------- = Tables = '''''see:''' HelpOnTables'' == Tables == {{{ ||'''A'''||'''B'''||'''C'''|| ||1 ||2 ||3 || }}} ||'''A'''||'''B'''||'''C'''|| ||1 ||2 ||3 || == Cell Width == {{{ ||minimal width ||<99%>maximal width || }}} ||minimal width ||<99%>maximal width || == Spanning Rows and Columns == {{{ ||<|2> cell spanning 2 rows ||cell in the 2nd column || ||cell in the 2nd column of the 2nd row || ||<-2> cell spanning 2 columns || ||||use empty cells as a shorthand || }}} ||<|2> cell spanning 2 rows ||cell in the 2nd column || ||cell in the 2nd column of the 2nd row || ||<-2> cell spanning 2 columns || ||||use empty cells as a shorthand || == Alignment of Cell Contents == {{{ ||<^|3> top (combined) ||<:99%> center (combined) || bottom (combined) || ||<)> right || ||<(> left || }}} ||<^|3> top (combined) ||<:99%> center (combined) || bottom (combined) || ||<)> right || ||<(> left || == Coulored Table Cells == {{{ ||<#0000FF> blue ||<#00FF00> green ||<#FF0000> red || ||<#00FFFF> cyan ||<#FF00FF> magenta ||<#FFFF00> yellow || }}} ||<#0000FF> blue ||<#00FF00> green ||<#FF0000> red || ||<#00FFFF> cyan ||<#FF00FF> magenta ||<#FFFF00> yellow || == HTML-like Options for Tables == {{{ ||A || like <|2> || || like <#00FF00> || || like <-2>|| }}} ||A || like <|2> || || like <#00FF00> || || like <-2>|| = Macros and Variables = == Macros == '''''see:''' HelpOnMacros'' * `[[Anchor(anchorname)]]` inserts a link anchor `anchorname` * `[[BR]]` inserts a hard line break * `[[FootNote(Note)]]` inserts a footnote saying `Note` * `[[Include(HelpOnMacros/Include)]]` inserts the contents of the page `HelpOnMacros/Include` inline * `[[MailTo(user AT example DOT com)]]` obfuscates the email address `user@example.com` to users not logged in == Variables == '''''see:''' HelpOnVariables'' * `@``SIG``@` inserts your login name and timestamp of modification * `@``TIME``@` inserts date and time of modification = Smileys and Icons = '''''see:''' HelpOnSmileys'' [[ShowSmileys]] = Source code = '''''see:''' HelpOnParsers'' == Verbatim Display == {{{ { { { def hello(): print "Hello World!" } } } }}} /!\ Remove spaces between "`{ { {`" and "`} } }`". {{{ def hello(): print "Hello World!" }}} == Syntax Highlighting == {{{ { { {#!python def hello(): print "Hello World!" } } } }}} /!\ Remove spaces between "`{ { {`" and "`} } }`". {{{#!python def hello(): print "Hello World!" }}} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/multiline_regexes.rb000066400000000000000000000007031250413007300277410ustar00rootroot00000000000000/ this is a multiline regex / this /is a multiline regex too/ foo = /is also one/ also /4 is one/ this(/ too /) # this not 2 /4 asfsadf/ # this is also not one 0x4d /25 foo/ 42 and /this is also a multiline regex/ # And here some special string cases foo = % blah # comment here to ensure whitespace foo(% blah ) foo << % blah # stupid but has to work foo = % blah + % blub # wicked foo = %q wicked # works too pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/nanomsg.intr000066400000000000000000000051521250413007300262330ustar00rootroot00000000000000module: nanomsg synopsis: generated bindings for the nanomsg library author: Bruce Mitchener, Jr. copyright: See LICENSE file in this distribution. define simple-C-mapped-subtype () export-map , export-function: identity; end; define interface #include { "sp/sp.h", "sp/fanin.h", "sp/inproc.h", "sp/pair.h", "sp/reqrep.h", "sp/survey.h", "sp/fanout.h", "sp/ipc.h", "sp/pubsub.h", "sp/tcp.h" }, exclude: { "SP_HAUSNUMERO", "SP_PAIR_ID", "SP_PUBSUB_ID", "SP_REQREP_ID", "SP_FANIN_ID", "SP_FANOUT_ID", "SP_SURVEY_ID" }, equate: {"char *" => }, rename: { "sp_recv" => %sp-recv, "sp_send" => %sp-send, "sp_setsockopt" => %sp-setsockopt }; function "sp_version", output-argument: 1, output-argument: 2, output-argument: 3; function "sp_send", map-argument: { 2 => }; function "sp_recv", map-argument: { 2 => }; end interface; // Function for adding the base address of the repeated slots of a // to an offset and returning the result as a . This is // necessary for passing contents across the FFI. define function buffer-offset (the-buffer :: , data-offset :: ) => (result-offset :: ) u%+(data-offset, primitive-wrap-machine-word (primitive-repeated-slot-as-raw (the-buffer, primitive-repeated-slot-offset(the-buffer)))) end function; define inline function sp-send (socket :: , data :: , flags :: ) => (res :: ) %sp-send(socket, buffer-offset(data, 0), data.size, flags) end; define inline function sp-recv (socket :: , data :: , flags :: ) => (res :: ) %sp-recv(socket, buffer-offset(data, 0), data.size, flags); end; define inline method sp-setsockopt (socket :: , level :: , option :: , value :: ) with-stack-structure (int :: ) pointer-value(int) := value; let setsockopt-result = %sp-setsockopt(socket, level, option, int, size-of()); if (setsockopt-result < 0) // Check error! end; setsockopt-result end; end; define inline method sp-setsockopt (socket :: , level :: , option :: , data :: ) let setsockopt-result = %sp-setsockopt(socket, level, option, as(, data), data.size); if (setsockopt-result < 0) // Check error! end; setsockopt-result end; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/nasm_aoutso.asm000066400000000000000000000052571250413007300267330ustar00rootroot00000000000000; test source file for assembling to NetBSD/FreeBSD a.out shared library ; build with: ; nasm -f aoutb aoutso.asm ; ld -Bshareable -o aoutso.so aoutso.o ; test with: ; cc -o aoutso aouttest.c aoutso.so ; ./aoutso ; This file should test the following: ; [1] Define and export a global text-section symbol ; [2] Define and export a global data-section symbol ; [3] Define and export a global BSS-section symbol ; [4] Define a non-global text-section symbol ; [5] Define a non-global data-section symbol ; [6] Define a non-global BSS-section symbol ; [7] Define a COMMON symbol ; [8] Define a NASM local label ; [9] Reference a NASM local label ; [10] Import an external symbol ; [11] Make a PC-relative call to an external symbol ; [12] Reference a text-section symbol in the text section ; [13] Reference a data-section symbol in the text section ; [14] Reference a BSS-section symbol in the text section ; [15] Reference a text-section symbol in the data section ; [16] Reference a data-section symbol in the data section ; [17] Reference a BSS-section symbol in the data section BITS 32 EXTERN __GLOBAL_OFFSET_TABLE_ GLOBAL _lrotate:function ; [1] GLOBAL _greet:function ; [1] GLOBAL _asmstr:data _asmstr.end-_asmstr ; [2] GLOBAL _textptr:data 4 ; [2] GLOBAL _selfptr:data 4 ; [2] GLOBAL _integer:data 4 ; [3] EXTERN _printf ; [10] COMMON _commvar 4 ; [7] SECTION .text ; prototype: long lrotate(long x, int num); _lrotate: ; [1] push ebp mov ebp,esp mov eax,[ebp+8] mov ecx,[ebp+12] .label rol eax,1 ; [4] [8] loop .label ; [9] [12] mov esp,ebp pop ebp ret ; prototype: void greet(void); _greet push ebx ; we'll use EBX for GOT, so save it call .getgot .getgot: pop ebx add ebx,__GLOBAL_OFFSET_TABLE_ + $$ - .getgot wrt ..gotpc mov eax,[ebx+_integer wrt ..got] ; [14] mov eax,[eax] inc eax mov [ebx+localint wrt ..gotoff],eax ; [14] mov eax,[ebx+_commvar wrt ..got] push dword [eax] mov eax,[ebx+localptr wrt ..gotoff] ; [13] push dword [eax] mov eax,[ebx+_integer wrt ..got] ; [1] [14] push dword [eax] lea eax,[ebx+_printfstr wrt ..gotoff] push eax ; [13] call _printf wrt ..plt ; [11] add esp,16 pop ebx ret SECTION .data ; a string _asmstr db 'hello, world', 0 ; [2] .end ; a string for Printf _printfstr db "integer==%d, localint==%d, commvar=%d" db 10, 0 ; some pointers localptr dd localint ; [5] [17] _textptr dd _greet wrt ..sym ; [15] _selfptr dd _selfptr wrt ..sym ; [16] SECTION .bss ; an integer _integer resd 1 ; [3] ; a local integer localint resd 1 ; [6] pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/nasm_objexe.asm000066400000000000000000000010571250413007300266670ustar00rootroot00000000000000; Demonstration of how to write an entire .EXE format program as a .OBJ ; file to be linked. Tested with the VAL free linker. ; To build: ; nasm -fobj objexe.asm ; val objexe.obj,objexe.exe; ; To test: ; objexe ; (should print `hello, world') segment code ..start: mov ax,data mov ds,ax mov ax,stack mov ss,ax mov sp,stacktop mov dx,hello mov ah,9 int 0x21 mov ax,0x4c00 int 0x21 segment data hello: db 'hello, world', 13, 10, '$' segment stack stack resb 64 stacktop: pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/nemerle_sample.n000066400000000000000000000027551250413007300270500ustar00rootroot00000000000000using System; namespace Demo.Ns { /// sample class public class ClassSample : Base { /* sample multiline comment */ #region region sample fieldSample : int; #endregion public virtual someMethod(str : string) : list[double] { def x = "simple string"; def x = $"simple $splice string $(spliceMethod() + 1)"; def x = <# recursive <# string #> sample #>; def x = $<# recursive $splice <# string #> sample ..$(lst; "; "; x => $"x * 2 = $(x * 2)") str #>; def x = @"somestring \"; def localFunc(arg) { arg + 1; } match (localFunc(2)) { | 3 => "ok"; | _ => "fail"; } using (x = SomeObject()) { foreach (item in someCollection) { def i = try { int.Parse(item) } catch { | _ is FormatException => 0; } when (i > 0xff) unless (i < 555L) WriteLine(i); } } protected override overrideSample() : void {} private privateSample() : void {} public abstract abstractSample() : void {} } } module ModuleSample { } variant RgbColor { | Red | Yellow | Green | Different { red : float; green : float; blue : float; } } macro sampleMacro(expr) syntax ("write", expr) { <[ WriteLine($(expr : dyn)) ]> } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/nginx_nginx.conf000066400000000000000000000051751250413007300270750ustar00rootroot00000000000000 #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] $request ' '"$status" $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # location ~ \.php$ { proxy_pass http://127.0.0.1; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } } # another virtual host using mix of IP-, name-, and port-based configuration # server { listen 8000; listen somename:8080; server_name somename alias another.alias; location / { root html; index index.html index.htm; } } # HTTPS server # server { listen 443; server_name localhost; ssl on; ssl_certificate cert.pem; ssl_certificate_key cert.key; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { root html; index index.html index.htm; } } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/numbers.c000066400000000000000000000003031250413007300255030ustar00rootroot00000000000000/* * Some Number Test */ int i = 24241424; float f1 = 342423423.24234; float f2 = 25235235.; float f3 = .234234; float f4 = 234243e+34343; float f5 = 24234e-234; int o = 0234; int h = 0x2342; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/objc_example.m000066400000000000000000000064711250413007300265060ustar00rootroot00000000000000// Test various types of includes #import # import #import "stdio.h" #\ import \ "stdlib.h" # /*line1*/ \ import /* line 2 */ \ "stdlib.h" // line 3 // Commented out code with preprocessor #if 0 #define MY_NUMBER 3 #endif #\ if 1 #define TEST_NUMBER 3 #endif // Empty preprocessor # // Class forward declaration @class MyClass; // Empty classes @interface EmptyClass @end @interface EmptyClass2 { } @end @interface EmptyClass3 : EmptyClass2 { } @end // Custom class inheriting from built-in @interface MyClass : NSObject { @public NSString *myString; __weak NSString *_weakString; @protected NSTextField *_textField; @private NSDate *privateDate; } // Various property aatributes @property(copy, readwrite, nonatomic) NSString *myString; @property(weak) NSString *weakString; @property(retain, strong, atomic) IBOutlet NSTextField *textField; // Class methods + (void)classMethod1:(NSString *)arg; + (void)classMethod2:(NSString *) arg; // Test space before arg @end typedef id B; #pragma mark MyMarker // MyClass.m // Class extension to declare private property @interface MyClass () @property(retain) NSDate *privateDate; - (void)hiddenMethod; @end // Special category @interface MyClass (Special) @property(retain) NSDate *specialDate; @end @implementation MyClass @synthesize myString; @synthesize privateDate; - (id)a:(B)b { /** * C-style comment */ // Selector keywords/types SEL someMethod = @selector(hiddenMethod); // Boolean types Boolean b1 = FALSE; BOOL b2 = NO; bool b3 = true; /** * Number literals */ // Int Literal NSNumber *n1 = @( 1 ); // Method call NSNumber *n2 = @( [b length] ); // Define variable NSNumber *n3 = @( TEST_NUMBER ); // Arthimetic expression NSNumber *n4 = @(1 + 2); // From variable int myInt = 5; NSNumber *n5 = @(myInt); // Nest expression NSNumber *n6 = @(1 + (2 + 6.0)); // Bool literal NSNumber *n7 = @NO; // Bool expression NSNumber *n8 = @(YES); // Character NSNumber *n9 = @'a'; // int NSNumber *n10 = @123; // unsigned NSNumber *n11 = @1234U; // long NSNumber *n12 = @1234567890L; // float NSNumber *n13 = @3.14F; // double NSNumber *n14 = @3.14F; // Array literals NSArray *arr = @[ @"1", @"2" ]; arr = @[ @[ @"1", @"2" ], [arr lastObject] ]; [arr lastObject]; [@[ @"1", @"2" ] lastObject]; // Dictionary literals NSDictionary *d = @{ @"key": @"value" }; [[d allKeys] lastObject]; [[@{ @"key": @"value" } allKeys] lastObject]; d = @{ @"key": @{ @"key": @"value" } }; [self hiddenMethod]; [b length]; [privateDate class]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"1", @"one", @"2", @"two", @"3", @"three", nil]; NSString *key; for (key in dictionary) { NSLog(@"Number: %@, Word: %@", key, [dictionary valueForKey:key]); } // Blocks int (^myBlock)(int arg1, int arg2); NSString *(^myName)(NSString *) = ^(NSString *value) { return value; }; return nil; } - (void)hiddenMethod { // Synchronized block @synchronized(self) { [myString retain]; [myString release]; } } + (void)classMethod1:(NSString *)arg {} + (void)classMethod2:(NSString *) arg { // Autorelease pool block @autoreleasepool { NSLog(@"Hello, World!"); } } @end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/openedge_example000066400000000000000000000010651250413007300271160ustar00rootroot00000000000000{include.i} {nested.i {include.i}} &SCOPED-DEFINE MY_NAME "Abe" DEF VAR i AS INT NO-UNDO. i = 0xABE + 1337 / (1 * 1.00) def var clowercasetest as char no-undo. DEF VAR vardashtest AS DATETIME-TZ NO-UNDO. DEFINE TEMP-TABLE ttNames NO-UNDO FIELD cName AS CHAR INDEX IXPK_ttNames IS PRIMARY UNIQUE cName. /* One-line comment */ /* Two-line Comment */ /* Nested /* Multiline /* Comment */ */ */ CREATE ttNames. ASSIGN ttNames.cName = {&MY_NAME}. FOR EACH ttNames: MESSAGE "Hello, " + ttNames.cName + '!' VIEW-AS ALERT-BOX. END. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/pawn_example000066400000000000000000000007621250413007300263000ustar00rootroot00000000000000{include.i} {nested.i {include.i}} &SCOPED-DEFINE MY_NAME "Abe" DEF VAR i AS INT NO-UNDO. i = 0xABE + 1337 / (1 * 1.00) def var clowercasetest as char no-undo. DEF VAR vardashtest AS DATETIME-TZ NO-UNDO. DEFINE TEMP-TABLE ttNames NO-UNDO FIELD cName AS CHAR INDEX IXPK_ttNames IS PRIMARY UNIQUE cName. /* One-line comment */ /* Two-line Comment */ CREATE ttNames. ASSIGN ttNames.cName = {&MY_NAME}. FOR EACH ttNames: MESSAGE "Hello, " + ttNames.cName + '!' VIEW-AS ALERT-BOX. END. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/perl_misc000066400000000000000000000022351250413007300255720ustar00rootroot00000000000000#!/usr/bin/perl # from http://gist.github.com/485595 use strict; use warnings; use Time::HiRes 'usleep'; for (1..5) { open my $in, '<', '/proc/sys/kernel/random/entropy_avail' or die; print <$in>; close $in; usleep 100_000; } # other miscellaneous tests of numbers separated by _ #usleep 100_000; 100_000_000; my $nichts = 0.005_006; print "$nichts\n"; my $nichts2 = 0.005_006_007; print 900_800_700.005_006_007, $/; # numbers from `man 1 perlnumber` my $n; $n = 1234; # decimal integer $n = 0b1110011; # binary integer $n = 01234; # octal integer $n = 0x1234; # hexadecimal integer $n = 12.34e-56; # exponential notation $n = "-12.34e56"; # number specified as a string $n = "1234"; # number specified as a string # other numbers for ( -9876, +8765, -9876.02, -9876.02e+10, +765_432e30, 2002., .2002, ) { print $_, "\n"; } # operators on numbers for ( $n + 300, $n - 300, $n / 300 + 10, $n * 250 / 2.0, $n == 100, $n != 100, $n > 100, $n >= 100, $n < 100, $n <= 100, $n % 2, abs $n, ) { print $_, "\n"; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/perl_perl5db000066400000000000000000000743721250413007300262070ustar00rootroot00000000000000 =head1 NAME perl5db.pl - the perl debugger =head1 SYNOPSIS perl -d your_Perl_script =head1 DESCRIPTION After this routine is over, we don't have user code executing in the debugger's context, so we can use C freely. =cut ############################################## Begin lexical danger zone # 'my' variables used here could leak into (that is, be visible in) # the context that the code being evaluated is executing in. This means that # the code could modify the debugger's variables. # # Fiddling with the debugger's context could be Bad. We insulate things as # much as we can. sub eval { # 'my' would make it visible from user code # but so does local! --tchrist # Remember: this localizes @DB::res, not @main::res. local @res; { # Try to keep the user code from messing with us. Save these so that # even if the eval'ed code changes them, we can put them back again. # Needed because the user could refer directly to the debugger's # package globals (and any 'my' variables in this containing scope) # inside the eval(), and we want to try to stay safe. local $otrace = $trace; local $osingle = $single; local $od = $^D; # Untaint the incoming eval() argument. { ($evalarg) = $evalarg =~ /(.*)/s; } # $usercontext built in DB::DB near the comment # "set up the context for DB::eval ..." # Evaluate and save any results. @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug # Restore those old values. $trace = $otrace; $single = $osingle; $^D = $od; } # Save the current value of $@, and preserve it in the debugger's copy # of the saved precious globals. my $at = $@; # Since we're only saving $@, we only have to localize the array element # that it will be stored in. local $saved[0]; # Preserve the old value of $@ eval { &DB::save }; # Now see whether we need to report an error back to the user. if ($at) { local $\ = ''; print $OUT $at; } # Display as required by the caller. $onetimeDump and $onetimedumpDepth # are package globals. elsif ($onetimeDump) { if ( $onetimeDump eq 'dump' ) { local $option{dumpDepth} = $onetimedumpDepth if defined $onetimedumpDepth; dumpit( $OUT, \@res ); } elsif ( $onetimeDump eq 'methods' ) { methods( $res[0] ); } } ## end elsif ($onetimeDump) @res; } ## end sub eval ############################################## End lexical danger zone # After this point it is safe to introduce lexicals. # The code being debugged will be executing in its own context, and # can't see the inside of the debugger. # # However, one should not overdo it: leave as much control from outside as # possible. If you make something a lexical, it's not going to be addressable # from outside the debugger even if you know its name. # This file is automatically included if you do perl -d. # It's probably not useful to include this yourself. # # Before venturing further into these twisty passages, it is # wise to read the perldebguts man page or risk the ire of dragons. # # (It should be noted that perldebguts will tell you a lot about # the underlying mechanics of how the debugger interfaces into the # Perl interpreter, but not a lot about the debugger itself. The new # comments in this code try to address this problem.) # Note that no subroutine call is possible until &DB::sub is defined # (for subroutines defined outside of the package DB). In fact the same is # true if $deep is not defined. # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich) # modified Perl debugger, to be run from Emacs in perldb-mode # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990 # Johan Vromans -- upgrade to 4.0 pl 10 # Ilya Zakharevich -- patches after 5.001 (and some before ;-) # (We have made efforts to clarify the comments in the change log # in other places; some of them may seem somewhat obscure as they # were originally written, and explaining them away from the code # in question seems conterproductive.. -JM) =head1 DEBUGGER INITIALIZATION The debugger starts up in phases. =head2 BASIC SETUP First, it initializes the environment it wants to run in: turning off warnings during its own compilation, defining variables which it will need to avoid warnings later, setting itself up to not exit when the program terminates, and defaulting to printing return values for the C command. =cut # Needed for the statement after exec(): # # This BEGIN block is simply used to switch off warnings during debugger # compiliation. Probably it would be better practice to fix the warnings, # but this is how it's done at the moment. BEGIN { $ini_warn = $^W; $^W = 0; } # Switch compilation warnings off until another BEGIN. # test if assertions are supported and actived: BEGIN { $ini_assertion = eval "sub asserting_test : assertion {1}; 1"; # $ini_assertion = undef => assertions unsupported, # " = 1 => assertions supported # print "\$ini_assertion=$ini_assertion\n"; } local ($^W) = 0; # Switch run-time warnings off during init. =head2 THREADS SUPPORT If we are running under a threaded Perl, we require threads and threads::shared if the environment variable C is set, to enable proper threaded debugger control. C<-dt> can also be used to set this. Each new thread will be announced and the debugger prompt will always inform you of each new thread created. It will also indicate the thread id in which we are currently running within the prompt like this: [tid] DB<$i> Where C<[tid]> is an integer thread id and C<$i> is the familiar debugger command prompt. The prompt will show: C<[0]> when running under threads, but not actually in a thread. C<[tid]> is consistent with C usage. While running under threads, when you set or delete a breakpoint (etc.), this will apply to all threads, not just the currently running one. When you are in a currently executing thread, you will stay there until it completes. With the current implementation it is not currently possible to hop from one thread to another. The C and C commands are currently fairly minimal - see C and C. Note that threading support was built into the debugger as of Perl version C<5.8.6> and debugger version C<1.2.8>. =cut BEGIN { # ensure we can share our non-threaded variables or no-op if ($ENV{PERL5DB_THREADED}) { require threads; require threads::shared; import threads::shared qw(share); $DBGR; share(\$DBGR); lock($DBGR); print "Threads support enabled\n"; } else { *lock = sub(*) {}; *share = sub(*) {}; } } # This would probably be better done with "use vars", but that wasn't around # when this code was originally written. (Neither was "use strict".) And on # the principle of not fiddling with something that was working, this was # left alone. warn( # Do not ;-) # These variables control the execution of 'dumpvar.pl'. $dumpvar::hashDepth, $dumpvar::arrayDepth, $dumpvar::dumpDBFiles, $dumpvar::dumpPackages, $dumpvar::quoteHighBit, $dumpvar::printUndef, $dumpvar::globPrint, $dumpvar::usageOnly, # used to save @ARGV and extract any debugger-related flags. @ARGS, # used to control die() reporting in diesignal() $Carp::CarpLevel, # used to prevent multiple entries to diesignal() # (if for instance diesignal() itself dies) $panic, # used to prevent the debugger from running nonstop # after a restart $second_time, ) if 0; foreach my $k (keys (%INC)) { &share(\$main::{'_<'.$filename}); }; # Command-line + PERLLIB: # Save the contents of @INC before they are modified elsewhere. @ini_INC = @INC; # This was an attempt to clear out the previous values of various # trapped errors. Apparently it didn't help. XXX More info needed! # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?! # We set these variables to safe values. We don't want to blindly turn # off warnings, because other packages may still want them. $trace = $signal = $single = 0; # Uninitialized warning suppression # (local $^W cannot help - other packages!). # Default to not exiting when program finishes; print the return # value when the 'r' command is used to return from a subroutine. $inhibit_exit = $option{PrintRet} = 1; =head1 OPTION PROCESSING The debugger's options are actually spread out over the debugger itself and C; some of these are variables to be set, while others are subs to be called with a value. To try to make this a little easier to manage, the debugger uses a few data structures to define what options are legal and how they are to be processed. First, the C<@options> array defines the I of all the options that are to be accepted. =cut @options = qw( CommandSet hashDepth arrayDepth dumpDepth DumpDBFiles DumpPackages DumpReused compactDump veryCompact quote HighBit undefPrint globPrint PrintRet UsageOnly frame AutoTrace TTY noTTY ReadLine NonStop LineInfo maxTraceLen recallCommand ShellBang pager tkRunning ornaments signalLevel warnLevel dieLevel inhibit_exit ImmediateStop bareStringify CreateTTY RemotePort windowSize DollarCaretP OnlyAssertions WarnAssertions ); @RememberOnROptions = qw(DollarCaretP OnlyAssertions); =pod Second, C lists the variables that each option uses to save its state. =cut %optionVars = ( hashDepth => \$dumpvar::hashDepth, arrayDepth => \$dumpvar::arrayDepth, CommandSet => \$CommandSet, DumpDBFiles => \$dumpvar::dumpDBFiles, DumpPackages => \$dumpvar::dumpPackages, DumpReused => \$dumpvar::dumpReused, HighBit => \$dumpvar::quoteHighBit, undefPrint => \$dumpvar::printUndef, globPrint => \$dumpvar::globPrint, UsageOnly => \$dumpvar::usageOnly, CreateTTY => \$CreateTTY, bareStringify => \$dumpvar::bareStringify, frame => \$frame, AutoTrace => \$trace, inhibit_exit => \$inhibit_exit, maxTraceLen => \$maxtrace, ImmediateStop => \$ImmediateStop, RemotePort => \$remoteport, windowSize => \$window, WarnAssertions => \$warnassertions, ); =pod Third, C<%optionAction> defines the subroutine to be called to process each option. =cut %optionAction = ( compactDump => \&dumpvar::compactDump, veryCompact => \&dumpvar::veryCompact, quote => \&dumpvar::quote, TTY => \&TTY, noTTY => \&noTTY, ReadLine => \&ReadLine, NonStop => \&NonStop, LineInfo => \&LineInfo, recallCommand => \&recallCommand, ShellBang => \&shellBang, pager => \&pager, signalLevel => \&signalLevel, warnLevel => \&warnLevel, dieLevel => \&dieLevel, tkRunning => \&tkRunning, ornaments => \&ornaments, RemotePort => \&RemotePort, DollarCaretP => \&DollarCaretP, OnlyAssertions=> \&OnlyAssertions, ); =pod Last, the C<%optionRequire> notes modules that must be Cd if an option is used. =cut # Note that this list is not complete: several options not listed here # actually require that dumpvar.pl be loaded for them to work, but are # not in the table. A subsequent patch will correct this problem; for # the moment, we're just recommenting, and we are NOT going to change # function. %optionRequire = ( compactDump => 'dumpvar.pl', veryCompact => 'dumpvar.pl', quote => 'dumpvar.pl', ); =pod There are a number of initialization-related variables which can be set by putting code to set them in a BEGIN block in the C environment variable. These are: =over 4 =item C<$rl> - readline control XXX needs more explanation =item C<$warnLevel> - whether or not debugger takes over warning handling =item C<$dieLevel> - whether or not debugger takes over die handling =item C<$signalLevel> - whether or not debugger takes over signal handling =item C<$pre> - preprompt actions (array reference) =item C<$post> - postprompt actions (array reference) =item C<$pretype> =item C<$CreateTTY> - whether or not to create a new TTY for this debugger =item C<$CommandSet> - which command set to use (defaults to new, documented set) =back =cut # These guys may be defined in $ENV{PERL5DB} : $rl = 1 unless defined $rl; $warnLevel = 1 unless defined $warnLevel; $dieLevel = 1 unless defined $dieLevel; $signalLevel = 1 unless defined $signalLevel; $pre = [] unless defined $pre; $post = [] unless defined $post; $pretype = [] unless defined $pretype; $CreateTTY = 3 unless defined $CreateTTY; $CommandSet = '580' unless defined $CommandSet; share($rl); share($warnLevel); share($dieLevel); share($signalLevel); share($pre); share($post); share($pretype); share($rl); share($CreateTTY); share($CommandSet); =pod The default C, C, and C handlers are set up. =cut warnLevel($warnLevel); dieLevel($dieLevel); signalLevel($signalLevel); =pod The pager to be used is needed next. We try to get it from the environment first. if it's not defined there, we try to find it in the Perl C. If it's not there, we default to C. We then call the C function to save the pager name. =cut # This routine makes sure $pager is set up so that '|' can use it. pager( # If PAGER is defined in the environment, use it. defined $ENV{PAGER} ? $ENV{PAGER} # If not, see if Config.pm defines it. : eval { require Config } && defined $Config::Config{pager} ? $Config::Config{pager} # If not, fall back to 'more'. : 'more' ) unless defined $pager; =pod We set up the command to be used to access the man pages, the command recall character (C unless otherwise defined) and the shell escape character (C unless otherwise defined). Yes, these do conflict, and neither works in the debugger at the moment. =cut setman(); # Set up defaults for command recall and shell escape (note: # these currently don't work in linemode debugging). &recallCommand("!") unless defined $prc; &shellBang("!") unless defined $psh; =pod We then set up the gigantic string containing the debugger help. We also set the limit on the number of arguments we'll display during a trace. =cut sethelp(); # If we didn't get a default for the length of eval/stack trace args, # set it here. $maxtrace = 400 unless defined $maxtrace; =head2 SETTING UP THE DEBUGGER GREETING The debugger I helps to inform the user how many debuggers are running, and whether the current debugger is the primary or a child. If we are the primary, we just hang onto our pid so we'll have it when or if we start a child debugger. If we are a child, we'll set things up so we'll have a unique greeting and so the parent will give us our own TTY later. We save the current contents of the C environment variable because we mess around with it. We'll also need to hang onto it because we'll need it if we restart. Child debuggers make a label out of the current PID structure recorded in PERLDB_PIDS plus the new PID. They also mark themselves as not having a TTY yet so the parent will give them one later via C. =cut # Save the current contents of the environment; we're about to # much with it. We'll need this if we have to restart. $ini_pids = $ENV{PERLDB_PIDS}; if ( defined $ENV{PERLDB_PIDS} ) { # We're a child. Make us a label out of the current PID structure # recorded in PERLDB_PIDS plus our (new) PID. Mark us as not having # a term yet so the parent will give us one later via resetterm(). $pids = "[$ENV{PERLDB_PIDS}]"; $ENV{PERLDB_PIDS} .= "->$$"; $term_pid = -1; } ## end if (defined $ENV{PERLDB_PIDS... else { # We're the parent PID. Initialize PERLDB_PID in case we end up with a # child debugger, and mark us as the parent, so we'll know to set up # more TTY's is we have to. $ENV{PERLDB_PIDS} = "$$"; $pids = "{pid=$$}"; $term_pid = $$; } $pidprompt = ''; # Sets up $emacs as a synonym for $slave_editor. *emacs = $slave_editor if $slave_editor; # May be used in afterinit()... =head2 READING THE RC FILE The debugger will read a file of initialization options if supplied. If running interactively, this is C<.perldb>; if not, it's C. =cut # As noted, this test really doesn't check accurately that the debugger # is running at a terminal or not. if ( -e "/dev/tty" ) { # this is the wrong metric! $rcfile = ".perldb"; } else { $rcfile = "perldb.ini"; } =pod The debugger does a safety test of the file to be read. It must be owned either by the current user or root, and must only be writable by the owner. =cut # This wraps a safety test around "do" to read and evaluate the init file. # # This isn't really safe, because there's a race # between checking and opening. The solution is to # open and fstat the handle, but then you have to read and # eval the contents. But then the silly thing gets # your lexical scope, which is unfortunate at best. sub safe_do { my $file = shift; # Just exactly what part of the word "CORE::" don't you understand? local $SIG{__WARN__}; local $SIG{__DIE__}; unless ( is_safe_file($file) ) { CORE::warn < command is invoked, it tries to capture all of the state it can into environment variables, and then sets C. When we start executing again, we check to see if C is there; if so, we reload all the information that the R command stuffed into the environment variables. PERLDB_RESTART - flag only, contains no restart data itself. PERLDB_HIST - command history, if it's available PERLDB_ON_LOAD - breakpoints set by the rc file PERLDB_POSTPONE - subs that have been loaded/not executed, and have actions PERLDB_VISITED - files that had breakpoints PERLDB_FILE_... - breakpoints for a file PERLDB_OPT - active options PERLDB_INC - the original @INC PERLDB_PRETYPE - preprompt debugger actions PERLDB_PRE - preprompt Perl code PERLDB_POST - post-prompt Perl code PERLDB_TYPEAHEAD - typeahead captured by readline() We chug through all these variables and plug the values saved in them back into the appropriate spots in the debugger. =cut if ( exists $ENV{PERLDB_RESTART} ) { # We're restarting, so we don't need the flag that says to restart anymore. delete $ENV{PERLDB_RESTART}; # $restart = 1; @hist = get_list('PERLDB_HIST'); %break_on_load = get_list("PERLDB_ON_LOAD"); %postponed = get_list("PERLDB_POSTPONE"); share(@hist); share(@truehist); share(%break_on_load); share(%postponed); # restore breakpoints/actions my @had_breakpoints = get_list("PERLDB_VISITED"); for ( 0 .. $#had_breakpoints ) { my %pf = get_list("PERLDB_FILE_$_"); $postponed_file{ $had_breakpoints[$_] } = \%pf if %pf; } # restore options my %opt = get_list("PERLDB_OPT"); my ( $opt, $val ); while ( ( $opt, $val ) = each %opt ) { $val =~ s/[\\\']/\\$1/g; parse_options("$opt'$val'"); } # restore original @INC @INC = get_list("PERLDB_INC"); @ini_INC = @INC; # return pre/postprompt actions and typeahead buffer $pretype = [ get_list("PERLDB_PRETYPE") ]; $pre = [ get_list("PERLDB_PRE") ]; $post = [ get_list("PERLDB_POST") ]; @typeahead = get_list( "PERLDB_TYPEAHEAD", @typeahead ); } ## end if (exists $ENV{PERLDB_RESTART... =head2 SETTING UP THE TERMINAL Now, we'll decide how the debugger is going to interact with the user. If there's no TTY, we set the debugger to run non-stop; there's not going to be anyone there to enter commands. =cut if ($notty) { $runnonstop = 1; share($runnonstop); } =pod If there is a TTY, we have to determine who it belongs to before we can proceed. If this is a slave editor or graphical debugger (denoted by the first command-line switch being '-emacs'), we shift this off and set C<$rl> to 0 (XXX ostensibly to do straight reads). =cut else { # Is Perl being run from a slave editor or graphical debugger? # If so, don't use readline, and set $slave_editor = 1. $slave_editor = ( ( defined $main::ARGV[0] ) and ( $main::ARGV[0] eq '-emacs' ) ); $rl = 0, shift(@main::ARGV) if $slave_editor; #require Term::ReadLine; =pod We then determine what the console should be on various systems: =over 4 =item * Cygwin - We use C instead of a separate device. =cut if ( $^O eq 'cygwin' ) { # /dev/tty is binary. use stdin for textmode undef $console; } =item * Unix - use C. =cut elsif ( -e "/dev/tty" ) { $console = "/dev/tty"; } =item * Windows or MSDOS - use C. =cut elsif ( $^O eq 'dos' or -e "con" or $^O eq 'MSWin32' ) { $console = "con"; } =item * MacOS - use C if this is the MPW version; C if not. Note that Mac OS X returns C, not C. Also note that the debugger doesn't do anything special for C. Maybe it should. =cut elsif ( $^O eq 'MacOS' ) { if ( $MacPerl::Version !~ /MPW/ ) { $console = "Dev:Console:Perl Debug"; # Separate window for application } else { $console = "Dev:Console"; } } ## end elsif ($^O eq 'MacOS') =item * VMS - use C. =cut else { # everything else is ... $console = "sys\$command"; } =pod =back Several other systems don't use a specific console. We C for those (Windows using a slave editor/graphical debugger, NetWare, OS/2 with a slave editor, Epoc). =cut if ( ( $^O eq 'MSWin32' ) and ( $slave_editor or defined $ENV{EMACS} ) ) { # /dev/tty is binary. use stdin for textmode $console = undef; } if ( $^O eq 'NetWare' ) { # /dev/tty is binary. use stdin for textmode $console = undef; } # In OS/2, we need to use STDIN to get textmode too, even though # it pretty much looks like Unix otherwise. if ( defined $ENV{OS2_SHELL} and ( $slave_editor or $ENV{WINDOWID} ) ) { # In OS/2 $console = undef; } # EPOC also falls into the 'got to use STDIN' camp. if ( $^O eq 'epoc' ) { $console = undef; } =pod If there is a TTY hanging around from a parent, we use that as the console. =cut $console = $tty if defined $tty; =head2 SOCKET HANDLING The debugger is capable of opening a socket and carrying out a debugging session over the socket. If C was defined in the options, the debugger assumes that it should try to start a debugging session on that port. It builds the socket and then tries to connect the input and output filehandles to it. =cut # Handle socket stuff. if ( defined $remoteport ) { # If RemotePort was defined in the options, connect input and output # to the socket. require IO::Socket; $OUT = new IO::Socket::INET( Timeout => '10', PeerAddr => $remoteport, Proto => 'tcp', ); if ( !$OUT ) { die "Unable to connect to remote host: $remoteport\n"; } $IN = $OUT; } ## end if (defined $remoteport) =pod If no C was defined, and we want to create a TTY on startup, this is probably a situation where multiple debuggers are running (for example, a backticked command that starts up another debugger). We create a new IN and OUT filehandle, and do the necessary mojo to create a new TTY if we know how and if we can. =cut # Non-socket. else { # Two debuggers running (probably a system or a backtick that invokes # the debugger itself under the running one). create a new IN and OUT # filehandle, and do the necessary mojo to create a new tty if we # know how, and we can. create_IN_OUT(4) if $CreateTTY & 4; if ($console) { # If we have a console, check to see if there are separate ins and # outs to open. (They are assumed identiical if not.) my ( $i, $o ) = split /,/, $console; $o = $i unless defined $o; # read/write on in, or just read, or read on STDIN. open( IN, "+<$i" ) || open( IN, "<$i" ) || open( IN, "<&STDIN" ); # read/write/create/clobber out, or write/create/clobber out, # or merge with STDERR, or merge with STDOUT. open( OUT, "+>$o" ) || open( OUT, ">$o" ) || open( OUT, ">&STDERR" ) || open( OUT, ">&STDOUT" ); # so we don't dongle stdout } ## end if ($console) elsif ( not defined $console ) { # No console. Open STDIN. open( IN, "<&STDIN" ); # merge with STDERR, or with STDOUT. open( OUT, ">&STDERR" ) || open( OUT, ">&STDOUT" ); # so we don't dongle stdout $console = 'STDIN/OUT'; } ## end elsif (not defined $console) # Keep copies of the filehandles so that when the pager runs, it # can close standard input without clobbering ours. $IN = \*IN, $OUT = \*OUT if $console or not defined $console; } ## end elsif (from if(defined $remoteport)) # Unbuffer DB::OUT. We need to see responses right away. my $previous = select($OUT); $| = 1; # for DB::OUT select($previous); # Line info goes to debugger output unless pointed elsewhere. # Pointing elsewhere makes it possible for slave editors to # keep track of file and position. We have both a filehandle # and a I/O description to keep track of. $LINEINFO = $OUT unless defined $LINEINFO; $lineinfo = $console unless defined $lineinfo; # share($LINEINFO); # <- unable to share globs share($lineinfo); # =pod To finish initialization, we show the debugger greeting, and then call the C subroutine if there is one. =cut # Show the debugger greeting. $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/; unless ($runnonstop) { local $\ = ''; local $, = ''; if ( $term_pid eq '-1' ) { print $OUT "\nDaughter DB session started...\n"; } else { print $OUT "\nLoading DB routines from $header\n"; print $OUT ( "Editor support ", $slave_editor ? "enabled" : "available", ".\n" ); print $OUT "\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n"; } ## end else [ if ($term_pid eq '-1') } ## end unless ($runnonstop) } ## end else [ if ($notty) # XXX This looks like a bug to me. # Why copy to @ARGS and then futz with @args? @ARGS = @ARGV; for (@args) { # Make sure backslashes before single quotes are stripped out, and # keep args unless they are numeric (XXX why?) # s/\'/\\\'/g; # removed while not justified understandably # s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto } # If there was an afterinit() sub defined, call it. It will get # executed in our scope, so it can fiddle with debugger globals. if ( defined &afterinit ) { # May be defined in $rcfile &afterinit(); } # Inform us about "Stack dump during die enabled ..." in dieLevel(). $I_m_init = 1; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/perl_regex-delims000066400000000000000000000027751250413007300272350ustar00rootroot00000000000000#! /usr/bin/env perl use strict; use warnings; # common delimiters print "a: "; my $a = "foo"; print $a, " - "; $a =~ s/foo/bar/; print $a, "\n"; print "b: "; my $b = "foo"; print $b, " - "; $b =~ s!foo!bar!; print $b, "\n"; print "c: "; my $c = "foo"; print $c, " - "; $c =~ s@foo@bar@; print $c, "\n"; print "d: "; my $d = "foo"; print $d, " - "; $d =~ s\foo\bar\; print $d, "\n"; print "\n"; # balanced delimiters print "e: "; my $e = "foo"; print $e, " - "; $e =~ s{foo}{bar}; print $e, "\n"; print "f: "; my $f = "foo"; print $f, " - "; $f =~ s(foo)(bar); print $f, "\n"; print "g: "; my $g = "foo"; print $g, " - "; $g =~ s; print $g, "\n"; print "h: "; my $h = "foo"; print $h, " - "; $h =~ s[foo][bar]; print $h, "\n"; print "\n"; # balanced delimiters with whitespace print "i: "; my $i = "foo"; print $i, " - "; $i =~ s{foo} {bar}; print $i, "\n"; print "j: "; my $j = "foo"; print $j, " - "; $j =~ s ; print $j, "\n"; print "k: "; my $k = "foo"; print $k, " - "; $k =~ s(foo) (bar); print $k, "\n"; print "\n"; # mixed delimiters print "l: "; my $l = "foo"; print $l, " - "; $l =~ s{foo} ; print $l, "\n"; print "m: "; my $m = "foo"; print $m, " - "; $m =~ s(foo) !bar!; print $m, "\n"; print "n: "; my $n = "foo"; print $n, " - "; $n =~ s[foo] $bar$; print $n, "\n"; print "\n"; # /x modifier print "o: "; my $o = "foo"; print $o, " - "; $o =~ s{ foo } {bar}x; print $o, "\n"; print "p: "; my $p = "foo"; print $p, " - "; $p =~ s% foo %bar%x; print $p, "\n"; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/perlfunc.1000066400000000000000000001251271250413007300256000ustar00rootroot00000000000000.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLFUNC 1" .TH PERLFUNC 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide" .SH "NAME" .IX Xref "function" perlfunc \- Perl builtin functions .SH "DESCRIPTION" .IX Header "DESCRIPTION" The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators. These differ in their precedence relationship with a following comma. (See the precedence table in perlop.) List operators take more than one argument, while unary operators can never take more than one argument. Thus, a comma terminates the argument of a unary operator, but merely separates the arguments of a list operator. A unary operator generally provides a scalar context to its argument, while a list operator may provide either scalar or list contexts for its arguments. If it does both, the scalar arguments will be first, and the list argument will follow. (Note that there can ever be only one such list argument.) For instance, \fIsplice()\fR has three scalar arguments followed by a list, whereas \fIgethostbyname()\fR has four scalar arguments. .PP In the syntax descriptions that follow, list operators that expect a list (and provide list context for the elements of the list) are shown with \s-1LIST\s0 as an argument. Such a list may consist of any combination of scalar arguments or list values; the list values will be included in the list as if each individual element were interpolated at that point in the list, forming a longer single-dimensional list value. Commas should separate elements of the \s-1LIST\s0. .PP Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use the parentheses, the simple (but occasionally surprising) rule is this: It \fIlooks\fR like a function, therefore it \fIis\fR a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. And whitespace between the function and left parenthesis doesn't count\*(--so you need to be careful sometimes: .PP .Vb 5 \& print 1+2+4; # Prints 7. \& print(1+2) + 4; # Prints 3. \& print (1+2)+4; # Also prints 3! \& print +(1+2)+4; # Prints 7. \& print ((1+2)+4); # Prints 7. .Ve .PP If you run Perl with the \fB\-w\fR switch it can warn you about this. For example, the third line above produces: .PP .Vb 2 \& print (...) interpreted as function at - line 1. \& Useless use of integer addition in void context at - line 1. .Ve .PP A few functions take no arguments at all, and therefore work as neither unary nor list operators. These include such functions as \f(CW\*(C`time\*(C'\fR and \f(CW\*(C`endpwent\*(C'\fR. For example, \f(CW\*(C`time+86_400\*(C'\fR always means \&\f(CW\*(C`time() + 86_400\*(C'\fR. .PP For functions that can be used in either a scalar or list context, nonabortive failure is generally indicated in a scalar context by returning the undefined value, and in a list context by returning the null list. .PP Remember the following important rule: There is \fBno rule\fR that relates the behavior of an expression in list context to its behavior in scalar context, or vice versa. It might do two totally different things. Each operator and function decides which sort of value it would be most appropriate to return in scalar context. Some operators return the length of the list that would have been returned in list context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations. In general, they do what you want, unless you want consistency. .IX Xref "context" .PP A named array in scalar context is quite different from what would at first glance appear to be a list in scalar context. You can't get a list like \f(CW\*(C`(1,2,3)\*(C'\fR into being in scalar context, because the compiler knows the context at compile time. It would generate the scalar comma operator there, not the list construction version of the comma. That means it was never a list to start with. .PP In general, functions in Perl that serve as wrappers for system calls of the same name (like \fIchown\fR\|(2), \fIfork\fR\|(2), \fIclosedir\fR\|(2), etc.) all return true when they succeed and \f(CW\*(C`undef\*(C'\fR otherwise, as is usually mentioned in the descriptions below. This is different from the C interfaces, which return \f(CW\*(C`\-1\*(C'\fR on failure. Exceptions to this rule are \f(CW\*(C`wait\*(C'\fR, \&\f(CW\*(C`waitpid\*(C'\fR, and \f(CW\*(C`syscall\*(C'\fR. System calls also set the special \f(CW$!\fR variable on failure. Other functions do not, except accidentally. .Sh "Perl Functions by Category" .IX Xref "function" .IX Subsection "Perl Functions by Category" Here are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category. Some functions appear in more than one place. .IP "Functions for SCALARs or strings" 4 .IX Xref "scalar string character" .IX Item "Functions for SCALARs or strings" \&\f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chop\*(C'\fR, \f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`index\*(C'\fR, \f(CW\*(C`lc\*(C'\fR, \f(CW\*(C`lcfirst\*(C'\fR, \&\f(CW\*(C`length\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`ord\*(C'\fR, \f(CW\*(C`pack\*(C'\fR, \f(CW\*(C`q/STRING/\*(C'\fR, \f(CW\*(C`qq/STRING/\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR, \&\f(CW\*(C`rindex\*(C'\fR, \f(CW\*(C`sprintf\*(C'\fR, \f(CW\*(C`substr\*(C'\fR, \f(CW\*(C`tr///\*(C'\fR, \f(CW\*(C`uc\*(C'\fR, \f(CW\*(C`ucfirst\*(C'\fR, \f(CW\*(C`y///\*(C'\fR .IP "Regular expressions and pattern matching" 4 .IX Xref "regular expression regex regexp" .IX Item "Regular expressions and pattern matching" \&\f(CW\*(C`m//\*(C'\fR, \f(CW\*(C`pos\*(C'\fR, \f(CW\*(C`quotemeta\*(C'\fR, \f(CW\*(C`s///\*(C'\fR, \f(CW\*(C`split\*(C'\fR, \f(CW\*(C`study\*(C'\fR, \f(CW\*(C`qr//\*(C'\fR .IP "Numeric functions" 4 .IX Xref "numeric number trigonometric trigonometry" .IX Item "Numeric functions" \&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`atan2\*(C'\fR, \f(CW\*(C`cos\*(C'\fR, \f(CW\*(C`exp\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`int\*(C'\fR, \f(CW\*(C`log\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`rand\*(C'\fR, \&\f(CW\*(C`sin\*(C'\fR, \f(CW\*(C`sqrt\*(C'\fR, \f(CW\*(C`srand\*(C'\fR .ie n .IP "Functions for real @ARRAYs" 4 .el .IP "Functions for real \f(CW@ARRAYs\fR" 4 .IX Xref "array" .IX Item "Functions for real @ARRAYs" \&\f(CW\*(C`pop\*(C'\fR, \f(CW\*(C`push\*(C'\fR, \f(CW\*(C`shift\*(C'\fR, \f(CW\*(C`splice\*(C'\fR, \f(CW\*(C`unshift\*(C'\fR .IP "Functions for list data" 4 .IX Xref "list" .IX Item "Functions for list data" \&\f(CW\*(C`grep\*(C'\fR, \f(CW\*(C`join\*(C'\fR, \f(CW\*(C`map\*(C'\fR, \f(CW\*(C`qw/STRING/\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR, \f(CW\*(C`sort\*(C'\fR, \f(CW\*(C`unpack\*(C'\fR .ie n .IP "Functions for real %HASHes" 4 .el .IP "Functions for real \f(CW%HASHes\fR" 4 .IX Xref "hash" .IX Item "Functions for real %HASHes" \&\f(CW\*(C`delete\*(C'\fR, \f(CW\*(C`each\*(C'\fR, \f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR .IP "Input and output functions" 4 .IX Xref "I O input output dbm" .IX Item "Input and output functions" \&\f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`close\*(C'\fR, \f(CW\*(C`closedir\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`eof\*(C'\fR, \&\f(CW\*(C`fileno\*(C'\fR, \f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`format\*(C'\fR, \f(CW\*(C`getc\*(C'\fR, \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`printf\*(C'\fR, \f(CW\*(C`read\*(C'\fR, \&\f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`rewinddir\*(C'\fR, \f(CW\*(C`seek\*(C'\fR, \f(CW\*(C`seekdir\*(C'\fR, \f(CW\*(C`select\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \&\f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`sysseek\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR, \f(CW\*(C`tell\*(C'\fR, \f(CW\*(C`telldir\*(C'\fR, \f(CW\*(C`truncate\*(C'\fR, \&\f(CW\*(C`warn\*(C'\fR, \f(CW\*(C`write\*(C'\fR .IP "Functions for fixed length data or records" 4 .IX Item "Functions for fixed length data or records" \&\f(CW\*(C`pack\*(C'\fR, \f(CW\*(C`read\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR, \f(CW\*(C`unpack\*(C'\fR, \f(CW\*(C`vec\*(C'\fR .IP "Functions for filehandles, files, or directories" 4 .IX Xref "file filehandle directory pipe link symlink" .IX Item "Functions for filehandles, files, or directories" \&\f(CW\*(C`\-\f(CIX\f(CW\*(C'\fR, \f(CW\*(C`chdir\*(C'\fR, \f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR, \f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, \&\f(CW\*(C`ioctl\*(C'\fR, \f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`mkdir\*(C'\fR, \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`opendir\*(C'\fR, \&\f(CW\*(C`readlink\*(C'\fR, \f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`rmdir\*(C'\fR, \f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \&\f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR, \f(CW\*(C`utime\*(C'\fR .IP "Keywords related to the control flow of your Perl program" 4 .IX Xref "control flow" .IX Item "Keywords related to the control flow of your Perl program" \&\f(CW\*(C`caller\*(C'\fR, \f(CW\*(C`continue\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR, \f(CW\*(C`exit\*(C'\fR, \&\f(CW\*(C`goto\*(C'\fR, \f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`redo\*(C'\fR, \f(CW\*(C`return\*(C'\fR, \f(CW\*(C`sub\*(C'\fR, \f(CW\*(C`wantarray\*(C'\fR .IP "Keywords related to scoping" 4 .IX Item "Keywords related to scoping" \&\f(CW\*(C`caller\*(C'\fR, \f(CW\*(C`import\*(C'\fR, \f(CW\*(C`local\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`use\*(C'\fR .IP "Miscellaneous functions" 4 .IX Item "Miscellaneous functions" \&\f(CW\*(C`defined\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR, \f(CW\*(C`formline\*(C'\fR, \f(CW\*(C`local\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`reset\*(C'\fR, \&\f(CW\*(C`scalar\*(C'\fR, \f(CW\*(C`undef\*(C'\fR, \f(CW\*(C`wantarray\*(C'\fR .IP "Functions for processes and process groups" 4 .IX Xref "process pid process id" .IX Item "Functions for processes and process groups" \&\f(CW\*(C`alarm\*(C'\fR, \f(CW\*(C`exec\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`kill\*(C'\fR, \&\f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`qx/STRING/\*(C'\fR, \f(CW\*(C`setpgrp\*(C'\fR, \f(CW\*(C`setpriority\*(C'\fR, \f(CW\*(C`sleep\*(C'\fR, \f(CW\*(C`system\*(C'\fR, \&\f(CW\*(C`times\*(C'\fR, \f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR .IP "Keywords related to perl modules" 4 .IX Xref "module" .IX Item "Keywords related to perl modules" \&\f(CW\*(C`do\*(C'\fR, \f(CW\*(C`import\*(C'\fR, \f(CW\*(C`no\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`require\*(C'\fR, \f(CW\*(C`use\*(C'\fR .IP "Keywords related to classes and object-orientedness" 4 .IX Xref "object class package" .IX Item "Keywords related to classes and object-orientedness" \&\f(CW\*(C`bless\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`ref\*(C'\fR, \f(CW\*(C`tie\*(C'\fR, \f(CW\*(C`tied\*(C'\fR, \&\f(CW\*(C`untie\*(C'\fR, \f(CW\*(C`use\*(C'\fR .IP "Low-level socket functions" 4 .IX Xref "socket sock" .IX Item "Low-level socket functions" \&\f(CW\*(C`accept\*(C'\fR, \f(CW\*(C`bind\*(C'\fR, \f(CW\*(C`connect\*(C'\fR, \f(CW\*(C`getpeername\*(C'\fR, \f(CW\*(C`getsockname\*(C'\fR, \&\f(CW\*(C`getsockopt\*(C'\fR, \f(CW\*(C`listen\*(C'\fR, \f(CW\*(C`recv\*(C'\fR, \f(CW\*(C`send\*(C'\fR, \f(CW\*(C`setsockopt\*(C'\fR, \f(CW\*(C`shutdown\*(C'\fR, \&\f(CW\*(C`socket\*(C'\fR, \f(CW\*(C`socketpair\*(C'\fR .IP "System V interprocess communication functions" 4 .IX Xref "IPC System V semaphore shared memory memory message" .IX Item "System V interprocess communication functions" \&\f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR, \f(CW\*(C`msgrcv\*(C'\fR, \f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`semctl\*(C'\fR, \f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR, \&\f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR, \f(CW\*(C`shmread\*(C'\fR, \f(CW\*(C`shmwrite\*(C'\fR .IP "Fetching user and group info" 4 .IX Xref "user group password uid gid passwd etc passwd" .IX Item "Fetching user and group info" \&\f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR, \f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR, \f(CW\*(C`getgrent\*(C'\fR, \&\f(CW\*(C`getgrgid\*(C'\fR, \f(CW\*(C`getgrnam\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR, \&\f(CW\*(C`getpwuid\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR .IP "Fetching network info" 4 .IX Xref "network protocol host hostname IP address service" .IX Item "Fetching network info" \&\f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`gethostbyaddr\*(C'\fR, \f(CW\*(C`gethostbyname\*(C'\fR, \&\f(CW\*(C`gethostent\*(C'\fR, \f(CW\*(C`getnetbyaddr\*(C'\fR, \f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR, \&\f(CW\*(C`getprotobyname\*(C'\fR, \f(CW\*(C`getprotobynumber\*(C'\fR, \f(CW\*(C`getprotoent\*(C'\fR, \&\f(CW\*(C`getservbyname\*(C'\fR, \f(CW\*(C`getservbyport\*(C'\fR, \f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR, \&\f(CW\*(C`setnetent\*(C'\fR, \f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setservent\*(C'\fR .IP "Time-related functions" 4 .IX Xref "time date" .IX Item "Time-related functions" \&\f(CW\*(C`gmtime\*(C'\fR, \f(CW\*(C`localtime\*(C'\fR, \f(CW\*(C`time\*(C'\fR, \f(CW\*(C`times\*(C'\fR .IP "Functions new in perl5" 4 .IX Xref "perl5" .IX Item "Functions new in perl5" \&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`bless\*(C'\fR, \f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`formline\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, \&\f(CW\*(C`import\*(C'\fR, \f(CW\*(C`lc\*(C'\fR, \f(CW\*(C`lcfirst\*(C'\fR, \f(CW\*(C`map\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`no\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`prototype\*(C'\fR, \&\f(CW\*(C`qx\*(C'\fR, \f(CW\*(C`qw\*(C'\fR, \f(CW\*(C`readline\*(C'\fR, \f(CW\*(C`readpipe\*(C'\fR, \f(CW\*(C`ref\*(C'\fR, \f(CW\*(C`sub*\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \f(CW\*(C`tie\*(C'\fR, \&\f(CW\*(C`tied\*(C'\fR, \f(CW\*(C`uc\*(C'\fR, \f(CW\*(C`ucfirst\*(C'\fR, \f(CW\*(C`untie\*(C'\fR, \f(CW\*(C`use\*(C'\fR .Sp * \- \f(CW\*(C`sub\*(C'\fR was a keyword in perl4, but in perl5 it is an operator, which can be used in expressions. .IP "Functions obsoleted in perl5" 4 .IX Item "Functions obsoleted in perl5" \&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR .Sh "Portability" .IX Xref "portability Unix portable" .IX Subsection "Portability" Perl was born in Unix and can therefore access all common Unix system calls. In non-Unix environments, the functionality of some Unix system calls may not be available, or details of the available functionality may differ slightly. The Perl functions affected by this are: .PP \&\f(CW\*(C`\-X\*(C'\fR, \f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR, \f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR, \&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR, \&\f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`exec\*(C'\fR, \&\f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, \f(CW\*(C`getgrent\*(C'\fR, \f(CW\*(C`getgrgid\*(C'\fR, \f(CW\*(C`gethostbyname\*(C'\fR, \&\f(CW\*(C`gethostent\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR, \f(CW\*(C`getnetbyaddr\*(C'\fR, \f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR, \&\f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`getprotobynumber\*(C'\fR, \&\f(CW\*(C`getprotoent\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR, \f(CW\*(C`getpwuid\*(C'\fR, \&\f(CW\*(C`getservbyport\*(C'\fR, \f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`getsockopt\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, \f(CW\*(C`ioctl\*(C'\fR, \&\f(CW\*(C`kill\*(C'\fR, \f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR, \f(CW\*(C`msgrcv\*(C'\fR, \&\f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`readlink\*(C'\fR, \f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`select\*(C'\fR, \f(CW\*(C`semctl\*(C'\fR, \&\f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR, \f(CW\*(C`setnetent\*(C'\fR, \&\f(CW\*(C`setpgrp\*(C'\fR, \f(CW\*(C`setpriority\*(C'\fR, \f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR, \&\f(CW\*(C`setservent\*(C'\fR, \f(CW\*(C`setsockopt\*(C'\fR, \f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR, \f(CW\*(C`shmread\*(C'\fR, \&\f(CW\*(C`shmwrite\*(C'\fR, \f(CW\*(C`socket\*(C'\fR, \f(CW\*(C`socketpair\*(C'\fR, \&\f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \f(CW\*(C`system\*(C'\fR, \&\f(CW\*(C`times\*(C'\fR, \f(CW\*(C`truncate\*(C'\fR, \f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR, \&\f(CW\*(C`utime\*(C'\fR, \f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR .PP For more information about the portability of these functions, see perlport and other available platform-specific documentation. .Sh "Alphabetical Listing of Perl Functions" .IX Subsection "Alphabetical Listing of Perl Functions" .IP "\-X \s-1FILEHANDLE\s0" 8 .IX Xref "-r -w -x -o -R -W -X -O -e -z -s -f -d -l -p -S -b -c -t -u -g -k -T -B -M -A -C" .IX Item "-X FILEHANDLE" .PD 0 .IP "\-X \s-1EXPR\s0" 8 .IX Item "-X EXPR" .IP "\-X" 8 .IX Item "-X" .PD A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename or a filehandle, and tests the associated file to see if something is true about it. If the argument is omitted, tests \f(CW$_\fR, except for \f(CW\*(C`\-t\*(C'\fR, which tests \s-1STDIN\s0. Unless otherwise documented, it returns \f(CW1\fR for true and \f(CW''\fR for false, or the undefined value if the file doesn't exist. Despite the funny names, precedence is the same as any other named unary operator, and the argument may be parenthesized like any other unary operator. The operator may be any of: .Sp .Vb 4 \& -r File is readable by effective uid/gid. \& -w File is writable by effective uid/gid. \& -x File is executable by effective uid/gid. \& -o File is owned by effective uid. .Ve .Sp .Vb 4 \& -R File is readable by real uid/gid. \& -W File is writable by real uid/gid. \& -X File is executable by real uid/gid. \& -O File is owned by real uid. .Ve .Sp .Vb 3 \& -e File exists. \& -z File has zero size (is empty). \& -s File has nonzero size (returns size in bytes). .Ve .Sp .Vb 8 \& -f File is a plain file. \& -d File is a directory. \& -l File is a symbolic link. \& -p File is a named pipe (FIFO), or Filehandle is a pipe. \& -S File is a socket. \& -b File is a block special file. \& -c File is a character special file. \& -t Filehandle is opened to a tty. .Ve .Sp .Vb 3 \& -u File has setuid bit set. \& -g File has setgid bit set. \& -k File has sticky bit set. .Ve .Sp .Vb 2 \& -T File is an ASCII text file (heuristic guess). \& -B File is a "binary" file (opposite of -T). .Ve .Sp .Vb 3 \& -M Script start time minus file modification time, in days. \& -A Same for access time. \& -C Same for inode change time (Unix, may differ for other platforms) .Ve .Sp Example: .Sp .Vb 5 \& while (<>) { \& chomp; \& next unless -f $_; # ignore specials \& #... \& } .Ve .Sp The interpretation of the file permission operators \f(CW\*(C`\-r\*(C'\fR, \f(CW\*(C`\-R\*(C'\fR, \&\f(CW\*(C`\-w\*(C'\fR, \f(CW\*(C`\-W\*(C'\fR, \f(CW\*(C`\-x\*(C'\fR, and \f(CW\*(C`\-X\*(C'\fR is by default based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write, or execute the file. Such reasons may be for example network filesystem access controls, ACLs (access control lists), read-only filesystems, and unrecognized executable formats. .Sp Also note that, for the superuser on the local filesystems, the \f(CW\*(C`\-r\*(C'\fR, \&\f(CW\*(C`\-R\*(C'\fR, \f(CW\*(C`\-w\*(C'\fR, and \f(CW\*(C`\-W\*(C'\fR tests always return 1, and \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a \fIstat()\fR to determine the actual mode of the file, or temporarily set their effective uid to something else. .Sp If you are using ACLs, there is a pragma called \f(CW\*(C`filetest\*(C'\fR that may produce more accurate results than the bare \fIstat()\fR mode bits. When under the \f(CW\*(C`use filetest 'access'\*(C'\fR the above-mentioned filetests will test whether the permission can (not) be granted using the \&\fIaccess()\fR family of system calls. Also note that the \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR may under this pragma return true even if there are no execute permission bits set (nor any extra execute permission ACLs). This strangeness is due to the underlying system calls' definitions. Read the documentation for the \f(CW\*(C`filetest\*(C'\fR pragma for more information. .Sp Note that \f(CW\*(C`\-s/a/b/\*(C'\fR does not do a negated substitution. Saying \&\f(CW\*(C`\-exp($foo)\*(C'\fR still works as expected, however\*(--only single letters following a minus are interpreted as file tests. .Sp The \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR switches work as follows. The first block or so of the file is examined for odd characters such as strange control codes or characters with the high bit set. If too many strange characters (>30%) are found, it's a \f(CW\*(C`\-B\*(C'\fR file; otherwise it's a \f(CW\*(C`\-T\*(C'\fR file. Also, any file containing null in the first block is considered a binary file. If \f(CW\*(C`\-T\*(C'\fR or \f(CW\*(C`\-B\*(C'\fR is used on a filehandle, the current \s-1IO\s0 buffer is examined rather than the first block. Both \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR return true on a null file, or a file at \s-1EOF\s0 when testing a filehandle. Because you have to read a file to do the \f(CW\*(C`\-T\*(C'\fR test, on most occasions you want to use a \f(CW\*(C`\-f\*(C'\fR against the file first, as in \f(CW\*(C`next unless \-f $file && \-T $file\*(C'\fR. .Sp If any of the file tests (or either the \f(CW\*(C`stat\*(C'\fR or \f(CW\*(C`lstat\*(C'\fR operators) are given the special filehandle consisting of a solitary underline, then the stat structure of the previous file test (or stat operator) is used, saving a system call. (This doesn't work with \f(CW\*(C`\-t\*(C'\fR, and you need to remember that \fIlstat()\fR and \f(CW\*(C`\-l\*(C'\fR will leave values in the stat structure for the symbolic link, not the real file.) (Also, if the stat buffer was filled by an \f(CW\*(C`lstat\*(C'\fR call, \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR will reset it with the results of \f(CW\*(C`stat _\*(C'\fR). Example: .Sp .Vb 1 \& print "Can do.\en" if -r $a || -w _ || -x _; .Ve .Sp .Vb 9 \& stat($filename); \& print "Readable\en" if -r _; \& print "Writable\en" if -w _; \& print "Executable\en" if -x _; \& print "Setuid\en" if -u _; \& print "Setgid\en" if -g _; \& print "Sticky\en" if -k _; \& print "Text\en" if -T _; \& print "Binary\en" if -B _; .Ve .IP "abs \s-1VALUE\s0" 8 .IX Xref "abs absolute" .IX Item "abs VALUE" .PD 0 .IP "abs" 8 .IX Item "abs" .PD Returns the absolute value of its argument. If \s-1VALUE\s0 is omitted, uses \f(CW$_\fR. .IP "accept \s-1NEWSOCKET\s0,GENERICSOCKET" 8 .IX Xref "accept" .IX Item "accept NEWSOCKET,GENERICSOCKET" Accepts an incoming socket connect, just as the \fIaccept\fR\|(2) system call does. Returns the packed address if it succeeded, false otherwise. See the example in \*(L"Sockets: Client/Server Communication\*(R" in perlipc. .Sp On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See \*(L"$^F\*(R" in perlvar. .IP "alarm \s-1SECONDS\s0" 8 .IX Xref "alarm SIGALRM timer" .IX Item "alarm SECONDS" .PD 0 .IP "alarm" 8 .IX Item "alarm" .PD Arranges to have a \s-1SIGALRM\s0 delivered to this process after the specified number of wallclock seconds has elapsed. If \s-1SECONDS\s0 is not specified, the value stored in \f(CW$_\fR is used. (On some machines, unfortunately, the elapsed time may be up to one second less or more than you specified because of how seconds are counted, and process scheduling may delay the delivery of the signal even further.) .Sp Only one timer may be counting at once. Each call disables the previous timer, and an argument of \f(CW0\fR may be supplied to cancel the previous timer without starting a new one. The returned value is the amount of time remaining on the previous timer. .Sp For delays of finer granularity than one second, you may use Perl's four-argument version of \fIselect()\fR leaving the first three arguments undefined, or you might be able to use the \f(CW\*(C`syscall\*(C'\fR interface to access \fIsetitimer\fR\|(2) if your system supports it. The Time::HiRes module (from \s-1CPAN\s0, and starting from Perl 5.8 part of the standard distribution) may also prove useful. .Sp It is usually a mistake to intermix \f(CW\*(C`alarm\*(C'\fR and \f(CW\*(C`sleep\*(C'\fR calls. (\f(CW\*(C`sleep\*(C'\fR may be internally implemented in your system with \f(CW\*(C`alarm\*(C'\fR) .Sp If you want to use \f(CW\*(C`alarm\*(C'\fR to time out a system call you need to use an \&\f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR pair. You can't rely on the alarm causing the system call to fail with \f(CW$!\fR set to \f(CW\*(C`EINTR\*(C'\fR because Perl sets up signal handlers to restart system calls on some systems. Using \f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR always works, modulo the caveats given in \*(L"Signals\*(R" in perlipc. .Sp .Vb 13 \& eval { \& local $SIG{ALRM} = sub { die "alarm\en" }; # NB: \en required \& alarm $timeout; \& $nread = sysread SOCKET, $buffer, $size; \& alarm 0; \& }; \& if ($@) { \& die unless $@ eq "alarm\en"; # propagate unexpected errors \& # timed out \& } \& else { \& # didn't \& } .Ve .Sp For more information see perlipc. .IP "atan2 Y,X" 8 .IX Xref "atan2 arctangent tan tangent" .IX Item "atan2 Y,X" Returns the arctangent of Y/X in the range \-PI to \s-1PI\s0. .Sp For the tangent operation, you may use the \f(CW\*(C`Math::Trig::tan\*(C'\fR function, or use the familiar relation: .Sp .Vb 1 \& sub tan { sin($_[0]) / cos($_[0]) } .Ve .Sp Note that atan2(0, 0) is not well\-defined. .IP "bind \s-1SOCKET\s0,NAME" 8 .IX Xref "bind" .IX Item "bind SOCKET,NAME" Binds a network address to a socket, just as the bind system call does. Returns true if it succeeded, false otherwise. \s-1NAME\s0 should be a packed address of the appropriate type for the socket. See the examples in \&\*(L"Sockets: Client/Server Communication\*(R" in perlipc. .IP "binmode \s-1FILEHANDLE\s0, \s-1LAYER\s0" 8 .IX Xref "binmode binary text DOS Windows" .IX Item "binmode FILEHANDLE, LAYER" .PD 0 .IP "binmode \s-1FILEHANDLE\s0" 8 .IX Item "binmode FILEHANDLE" .PD Arranges for \s-1FILEHANDLE\s0 to be read or written in \*(L"binary\*(R" or \*(L"text\*(R" mode on systems where the run-time libraries distinguish between binary and text files. If \s-1FILEHANDLE\s0 is an expression, the value is taken as the name of the filehandle. Returns true on success, otherwise it returns \f(CW\*(C`undef\*(C'\fR and sets \f(CW$!\fR (errno). .Sp On some systems (in general, \s-1DOS\s0 and Windows-based systems) \fIbinmode()\fR is necessary when you're not working with a text file. For the sake of portability it is a good idea to always use it when appropriate, and to never use it when it isn't appropriate. Also, people can set their I/O to be by default \s-1UTF\-8\s0 encoded Unicode, not bytes. .Sp In other words: regardless of platform, use \fIbinmode()\fR on binary data, like for example images. .Sp If \s-1LAYER\s0 is present it is a single string, but may contain multiple directives. The directives alter the behaviour of the file handle. When \s-1LAYER\s0 is present using binmode on text file makes sense. .Sp If \s-1LAYER\s0 is omitted or specified as \f(CW\*(C`:raw\*(C'\fR the filehandle is made suitable for passing binary data. This includes turning off possible \s-1CRLF\s0 translation and marking it as bytes (as opposed to Unicode characters). Note that, despite what may be implied in \fI\*(L"Programming Perl\*(R"\fR (the Camel) or elsewhere, \f(CW\*(C`:raw\*(C'\fR is \fInot\fR the simply inverse of \f(CW\*(C`:crlf\*(C'\fR \&\*(-- other layers which would affect binary nature of the stream are \&\fIalso\fR disabled. See PerlIO, perlrun and the discussion about the \&\s-1PERLIO\s0 environment variable. .Sp The \f(CW\*(C`:bytes\*(C'\fR, \f(CW\*(C`:crlf\*(C'\fR, and \f(CW\*(C`:utf8\*(C'\fR, and any other directives of the form \f(CW\*(C`:...\*(C'\fR, are called I/O \fIlayers\fR. The \f(CW\*(C`open\*(C'\fR pragma can be used to establish default I/O layers. See open. .Sp \&\fIThe \s-1LAYER\s0 parameter of the \fIbinmode()\fI function is described as \*(L"\s-1DISCIPLINE\s0\*(R" in \*(L"Programming Perl, 3rd Edition\*(R". However, since the publishing of this book, by many known as \*(L"Camel \s-1III\s0\*(R", the consensus of the naming of this functionality has moved from \*(L"discipline\*(R" to \*(L"layer\*(R". All documentation of this version of Perl therefore refers to \*(L"layers\*(R" rather than to \&\*(L"disciplines\*(R". Now back to the regularly scheduled documentation...\fR .Sp To mark \s-1FILEHANDLE\s0 as \s-1UTF\-8\s0, use \f(CW\*(C`:utf8\*(C'\fR. .Sp In general, \fIbinmode()\fR should be called after \fIopen()\fR but before any I/O is done on the filehandle. Calling \fIbinmode()\fR will normally flush any pending buffered output data (and perhaps pending input data) on the handle. An exception to this is the \f(CW\*(C`:encoding\*(C'\fR layer that changes the default character encoding of the handle, see open. The \f(CW\*(C`:encoding\*(C'\fR layer sometimes needs to be called in mid\-stream, and it doesn't flush the stream. The \f(CW\*(C`:encoding\*(C'\fR also implicitly pushes on top of itself the \f(CW\*(C`:utf8\*(C'\fR layer because internally Perl will operate on \s-1UTF\-8\s0 encoded Unicode characters. .Sp The operating system, device drivers, C libraries, and Perl run-time system all work together to let the programmer treat a single character (\f(CW\*(C`\en\*(C'\fR) as the line terminator, irrespective of the external representation. On many operating systems, the native text file representation matches the internal representation, but on some platforms the external representation of \f(CW\*(C`\en\*(C'\fR is made up of more than one character. .Sp Mac \s-1OS\s0, all variants of Unix, and Stream_LF files on \s-1VMS\s0 use a single character to end each line in the external representation of text (even though that single character is \s-1CARRIAGE\s0 \s-1RETURN\s0 on Mac \s-1OS\s0 and \s-1LINE\s0 \s-1FEED\s0 on Unix and most \s-1VMS\s0 files). In other systems like \s-1OS/2\s0, \s-1DOS\s0 and the various flavors of MS-Windows your program sees a \f(CW\*(C`\en\*(C'\fR as a simple \f(CW\*(C`\ecJ\*(C'\fR, but what's stored in text files are the two characters \f(CW\*(C`\ecM\ecJ\*(C'\fR. That means that, if you don't use \fIbinmode()\fR on these systems, \f(CW\*(C`\ecM\ecJ\*(C'\fR sequences on disk will be converted to \f(CW\*(C`\en\*(C'\fR on input, and any \f(CW\*(C`\en\*(C'\fR in your program will be converted back to \f(CW\*(C`\ecM\ecJ\*(C'\fR on output. This is what you want for text files, but it can be disastrous for binary files. .Sp Another consequence of using \fIbinmode()\fR (on some systems) is that special end-of-file markers will be seen as part of the data stream. For systems from the Microsoft family this means that if your binary data contains \f(CW\*(C`\ecZ\*(C'\fR, the I/O subsystem will regard it as the end of the file, unless you use \fIbinmode()\fR. .Sp \&\fIbinmode()\fR is not only important for \fIreadline()\fR and \fIprint()\fR operations, but also when using \fIread()\fR, \fIseek()\fR, \fIsysread()\fR, \fIsyswrite()\fR and \fItell()\fR (see perlport for more details). See the \f(CW$/\fR and \f(CW\*(C`$\e\*(C'\fR variables in perlvar for how to manually set your input and output line-termination sequences. .IP "bless \s-1REF\s0,CLASSNAME" 8 .IX Xref "bless" .IX Item "bless REF,CLASSNAME" .PD 0 .IP "bless \s-1REF\s0" 8 .IX Item "bless REF" .PD This function tells the thingy referenced by \s-1REF\s0 that it is now an object in the \s-1CLASSNAME\s0 package. If \s-1CLASSNAME\s0 is omitted, the current package is used. Because a \f(CW\*(C`bless\*(C'\fR is often the last thing in a constructor, it returns the reference for convenience. Always use the two-argument version if a derived class might inherit the function doing the blessing. See perltoot and perlobj for more about the blessing (and blessings) of objects. .Sp Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmata. Builtin types have all uppercase names. To prevent confusion, you may wish to avoid such package names as well. Make sure that \s-1CLASSNAME\s0 is a true value. .Sp See \*(L"Perl Modules\*(R" in perlmod. .IP "caller \s-1EXPR\s0" 8 .IX Xref "caller call stack stack stack trace" .IX Item "caller EXPR" .PD 0 .IP "caller" 8 .IX Item "caller" .PD Returns the context of the current subroutine call. In scalar context, returns the caller's package name if there is a caller, that is, if we're in a subroutine or \f(CW\*(C`eval\*(C'\fR or \f(CW\*(C`require\*(C'\fR, and the undefined value otherwise. In list context, returns .Sp .Vb 1 \& ($package, $filename, $line) = caller; .Ve .Sp With \s-1EXPR\s0, it returns some extra information that the debugger uses to print a stack trace. The value of \s-1EXPR\s0 indicates how many call frames to go back before the current one. .Sp .Vb 2 \& ($package, $filename, $line, $subroutine, $hasargs, \& $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller($i); .Ve .Sp Here \f(CW$subroutine\fR may be \f(CW\*(C`(eval)\*(C'\fR if the frame is not a subroutine call, but an \f(CW\*(C`eval\*(C'\fR. In such a case additional elements \f(CW$evaltext\fR and \&\f(CW$is_require\fR are set: \f(CW$is_require\fR is true if the frame is created by a \&\f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR statement, \f(CW$evaltext\fR contains the text of the \&\f(CW\*(C`eval EXPR\*(C'\fR statement. In particular, for an \f(CW\*(C`eval BLOCK\*(C'\fR statement, \&\f(CW$filename\fR is \f(CW\*(C`(eval)\*(C'\fR, but \f(CW$evaltext\fR is undefined. (Note also that each \f(CW\*(C`use\*(C'\fR statement creates a \f(CW\*(C`require\*(C'\fR frame inside an \f(CW\*(C`eval EXPR\*(C'\fR frame.) \f(CW$subroutine\fR may also be \f(CW\*(C`(unknown)\*(C'\fR if this particular subroutine happens to have been deleted from the symbol table. \&\f(CW$hasargs\fR is true if a new instance of \f(CW@_\fR was set up for the frame. \&\f(CW$hints\fR and \f(CW$bitmask\fR contain pragmatic hints that the caller was compiled with. The \f(CW$hints\fR and \f(CW$bitmask\fR values are subject to change between versions of Perl, and are not meant for external use. .Sp Furthermore, when called from within the \s-1DB\s0 package, caller returns more detailed information: it sets the list variable \f(CW@DB::args\fR to be the arguments with which the subroutine was invoked. .Sp Be aware that the optimizer might have optimized call frames away before \&\f(CW\*(C`caller\*(C'\fR had a chance to get the information. That means that \f(CWcaller(N)\fR might not return information about the call frame you expect it do, for \&\f(CW\*(C`N > 1\*(C'\fR. In particular, \f(CW@DB::args\fR might have information from the previous time \f(CW\*(C`caller\*(C'\fR was called. .IP "chdir \s-1EXPR\s0" 8 .IX Xref "chdir cd" .IX Item "chdir EXPR" .PD 0 .IP "chdir \s-1FILEHANDLE\s0" 8 .IX Item "chdir FILEHANDLE" .IP "chdir \s-1DIRHANDLE\s0" 8 .IX Item "chdir DIRHANDLE" .IP "chdir" 8 .IX Item "chdir" .PD Changes the working directory to \s-1EXPR\s0, if possible. If \s-1EXPR\s0 is omitted, changes to the directory specified by \f(CW$ENV{HOME}\fR, if set; if not, changes to the directory specified by \f(CW$ENV{LOGDIR}\fR. (Under \s-1VMS\s0, the variable \f(CW$ENV{SYS$LOGIN}\fR is also checked, and used if it is set.) If neither is set, \f(CW\*(C`chdir\*(C'\fR does nothing. It returns true upon success, false otherwise. See the example under \f(CW\*(C`die\*(C'\fR. .Sp On systems that support fchdir, you might pass a file handle or directory handle as argument. On systems that don't support fchdir, passing handles produces a fatal error at run time. .IP "chmod \s-1LIST\s0" 8 .IX Xref "chmod permission mode" .IX Item "chmod LIST" Changes the permissions of a list of files. The first element of the list must be the numerical mode, which should probably be an octal number, and which definitely should \fInot\fR be a string of octal digits: \&\f(CW0644\fR is okay, \f(CW'0644'\fR is not. Returns the number of files successfully changed. See also \*(L"oct\*(R", if all you have is a string. .Sp .Vb 6 \& $cnt = chmod 0755, 'foo', 'bar'; \& chmod 0755, @executables; \& $mode = '0644'; chmod $mode, 'foo'; # !!! sets mode to \& # --w----r-T \& $mode = '0644'; chmod oct($mode), 'foo'; # this is better \& $mode = 0644; chmod $mode, 'foo'; # this is best .Ve .Sp On systems that support fchmod, you might pass file handles among the files. On systems that don't support fchmod, passing file handles produces a fatal error at run time. .Sp .Vb 3 \& open(my $fh, "<", "foo"); \& my $perm = (stat $fh)[2] & 07777; \& chmod($perm | 0600, $fh); .Ve .Sp You can also import the symbolic \f(CW\*(C`S_I*\*(C'\fR constants from the Fcntl module: .Sp .Vb 1 \& use Fcntl ':mode'; .Ve .Sp .Vb 2 \& chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; \& # This is identical to the chmod 0755 of the above example. .Ve .IP "chomp \s-1VARIABLE\s0" 8 .IX Xref "chomp INPUT_RECORD_SEPARATOR $ newline eol" .IX Item "chomp VARIABLE" .PD 0 .IP "chomp( \s-1LIST\s0 )" 8 .IX Item "chomp( LIST )" .IP "chomp" 8 .IX Item "chomp" .PD This safer version of \*(L"chop\*(R" removes any trailing string that corresponds to the current value of \f(CW$/\fR (also known as \&\f(CW$INPUT_RECORD_SEPARATOR\fR in the \f(CW\*(C`English\*(C'\fR module). It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode (\f(CW\*(C`$/ = ""\*(C'\fR), it removes all trailing newlines from the string. When in slurp mode (\f(CW\*(C`$/ = undef\*(C'\fR) or fixed-length record mode (\f(CW$/\fR is a reference to an integer or the like, see perlvar) \fIchomp()\fR won't remove anything. If \s-1VARIABLE\s0 is omitted, it chomps \f(CW$_\fR. Example: .Sp .Vb 5 \& while (<>) { \& chomp; # avoid \en on last field \& @array = split(/:/); \& # ... \& } .Ve .Sp If \s-1VARIABLE\s0 is a hash, it chomps the hash's values, but not its keys. .Sp pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/phpMyAdmin.spec000066400000000000000000000142051250413007300266140ustar00rootroot00000000000000%define _myadminpath /var/www/myadmin %define pkgrelease rc1 %define microrelease 1 Name: phpMyAdmin Version: 3.1.1 Release: %{pkgrelease}.%{microrelease} License: GPL Group: Applications/Databases/Interfaces Source0: http://prdownloads.sourceforge.net/phpmyadmin/%{name}-%{version}-%{pkgrelease}.tar.bz2 Source1: phpMyAdmin-http.conf URL: http://sourceforge.net/projects/phpmyadmin/ Requires: mysql Requires: php-mysql Buildarch: noarch #BuildRoot: %{_tmppath}/%{name}-root Summary: phpMyAdmin - web-based MySQL administration %description phpMyAdmin can manage a whole MySQL-server (needs a super-user) but also a single database. To accomplish the latter you'll need a properly set up MySQL-user which can read/write only the desired database. It's up to you to look up the appropiate part in the MySQL manual. Currently phpMyAdmin can: - create and drop databases - create, copy, drop and alter tables - delete, edit and add fields - execute any SQL-statement, even batch-queries - manage keys on fields - load text files into tables - create (*) and read dumps of tables - export (*) and import data to CSV values - administer multiple servers and single databases - check referencial integrity - create complex queries automatically connecting required tables - create PDF graphics of your database layout - communicate in more than 38 different languages %prep %setup -q -n %{name}-%{version}-%{pkgrelease} %build %install [ "${RPM_BUILD_ROOT}" != "/" ] && [ -d "${RPM_BUILD_ROOT}" ] && \ rm -rf "${RPM_BUILD_ROOT}" # Create directories. install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/{css,js,lang,libraries,themes} install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/{auth,dbg,dbi,engines} install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/{export,tcpdf,import} install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/transformations install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/tcpdf/font install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/{darkblue_orange,original} install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/darkblue_orange/{css,img} install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/original/{css,img} # Install files. install libraries/config.default.php \ "${RPM_BUILD_ROOT}%{_myadminpath}"/config.inc.php install *.{php,ico} "${RPM_BUILD_ROOT}%{_myadminpath}"/ install ChangeLog LICENSE README "${RPM_BUILD_ROOT}%{_myadminpath}"/ install Documentation.html docs.css "${RPM_BUILD_ROOT}%{_myadminpath}"/ install css/* "${RPM_BUILD_ROOT}%{_myadminpath}/css"/ install js/* "${RPM_BUILD_ROOT}%{_myadminpath}/js"/ install lang/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/lang"/ install libraries/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries"/ install libraries/auth/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/auth"/ install libraries/dbg/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/dbg"/ install libraries/dbi/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/dbi"/ install libraries/engines/*.php \ "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/engines"/ install libraries/export/*.php \ "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/export"/ install libraries/tcpdf/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/tcpdf"/ install libraries/tcpdf/font/*.{php,z} \ "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/tcpdf/font"/ install libraries/import/*.php \ "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/import"/ install libraries/transformations/*.php \ "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/transformations"/ install themes/darkblue_orange/*.{php,png} \ "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange"/ install themes/darkblue_orange/css/*.php \ "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange/css"/ install themes/darkblue_orange/img/*.{png,ico} \ "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange/img"/ install themes/original/*.{php,png} \ "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original"/ install themes/original/css/*.php \ "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original/css"/ install themes/original/img/*.{png,ico} \ "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original/img"/ # Create documentation directories. DOCROOT="${RPM_BUILD_ROOT}%{_docdir}/%{name}-%{version}" install -d "${DOCROOT}" install -d "${DOCROOT}"/{lang,scripts,transformations} # Install documentation files. install RELEASE-DATE-* "${DOCROOT}"/ install CREDITS ChangeLog INSTALL LICENSE "${DOCROOT}"/ install README TODO "${DOCROOT}"/ install Documentation.* docs.css "${DOCROOT}"/ install translators.html "${DOCROOT}"/ install lang/*.sh "${DOCROOT}"/lang/ install scripts/* "${DOCROOT}"/scripts/ install libraries/tcpdf/README "${DOCROOT}"/README.tcpdf install libraries/import/README "${DOCROOT}"/README.import install libraries/transformations/README "${DOCROOT}"/transformations/ install libraries/transformations/TEMPLATE* "${DOCROOT}"/transformations/ install libraries/transformations/*.sh "${DOCROOT}"/transformations/ # Install configuration file for Apache. install -d "${RPM_BUILD_ROOT}%{_sysconfdir}/httpd/conf.d" install "%{SOURCE1}" \ "${RPM_BUILD_ROOT}%{_sysconfdir}/httpd/conf.d/phpMyAdmin.conf" # Generate non-configuration file list. (cd "${RPM_BUILD_ROOT}"; ls -d ."%{_myadminpath}"/*) | sed -e '/\/config\.inc\.php$/d' -e 's/^.//' > files.list %clean [ "${RPM_BUILD_ROOT}" != "/" ] && [ -d "${RPM_BUILD_ROOT}" ] && \ rm -rf "${RPM_BUILD_ROOT}" %files -f files.list %defattr(644, root, root, 755) %doc %{_docdir}/%{name}-%{version} %dir %{_myadminpath} %attr(640,root,apache) %config(noreplace) %verify(not size mtime md5) %{_myadminpath}/config.inc.php %config(noreplace) %verify(not size mtime md5) %{_sysconfdir}/httpd/conf.d/* %changelog * Thu Feb 23 2006 Patrick Monnerat - Version 2.8.0-rc1.1. * Thu Dec 22 2005 Patrick Monnerat - Path "nullpw" to allow trying connection with null password after failure. - Version 2.7.0-pl1.1. * Mon Aug 22 2005 Patrick Monnerat - Version 2.6.3-pl1. * Wed Jul 21 2004 Patrick Monnerat - Version 2.5.7-pl1. * Fri Nov 22 2002 Patrick Monnerat - Version 2.3.0-rc1. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/phpcomplete.vim000066400000000000000000000404241250413007300267310ustar00rootroot00000000000000" Vim completion script " Language: PHP " Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl ) " Last Change: 2006 May 9 " " TODO: " - Class aware completion: " a) caching? " - Switching to HTML (XML?) completion (SQL) inside of phpStrings " - allow also for XML completion <- better do html_flavor for HTML " completion " - outside of getting parent tag may cause problems. Heh, even in " perfect conditions GetLastOpenTag doesn't cooperate... Inside of " phpStrings this can be even a bonus but outside of it is not the " best situation function! phpcomplete#CompletePHP(findstart, base) if a:findstart unlet! b:php_menu " Check if we are inside of PHP markup let pos = getpos('.') let phpbegin = searchpairpos('', 'bWn', \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string\|comment"') let phpend = searchpairpos('', 'Wn', \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string\|comment"') if phpbegin == [0,0] && phpend == [0,0] " We are outside of any PHP markup. Complete HTML let htmlbegin = htmlcomplete#CompleteTags(1, '') let cursor_col = pos[2] let base = getline('.')[htmlbegin : cursor_col] let b:php_menu = htmlcomplete#CompleteTags(0, base) return htmlbegin else " locate the start of the word let line = getline('.') let start = col('.') - 1 let curline = line('.') let compl_begin = col('.') - 2 while start >= 0 && line[start - 1] =~ '[a-zA-Z_0-9\x7f-\xff$]' let start -= 1 endwhile let b:compl_context = getline('.')[0:compl_begin] return start " We can be also inside of phpString with HTML tags. Deal with " it later (time, not lines). endif endif " If exists b:php_menu it means completion was already constructed we " don't need to do anything more if exists("b:php_menu") return b:php_menu endif " Initialize base return lists let res = [] let res2 = [] " a:base is very short - we need context if exists("b:compl_context") let context = b:compl_context unlet! b:compl_context endif if !exists('g:php_builtin_functions') call phpcomplete#LoadData() endif let scontext = substitute(context, '\$\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*$', '', '') if scontext =~ '\(=\s*new\|extends\)\s\+$' " Complete class name " Internal solution for finding classes in current file. let file = getline(1, '$') call filter(file, \ 'v:val =~ "class\\s\\+[a-zA-Z_\\x7f-\\xff][a-zA-Z_0-9\\x7f-\\xff]*\\s*("') let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) let jfile = join(file, ' ') let int_values = split(jfile, 'class\s\+') let int_classes = {} for i in int_values let c_name = matchstr(i, '^[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*') if c_name != '' let int_classes[c_name] = '' endif endfor " Prepare list of classes from tags file let ext_classes = {} let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) if fnames != '' exe 'silent! vimgrep /^'.a:base.'.*\tc\(\t\|$\)/j '.fnames let qflist = getqflist() if len(qflist) > 0 for field in qflist " [:space:] thing: we don't have to be so strict when " dealing with tags files - entries there were already " checked by ctags. let item = matchstr(field['text'], '^[^[:space:]]\+') let ext_classes[item] = '' endfor endif endif " Prepare list of built in classes from g:php_builtin_functions if !exists("g:php_omni_bi_classes") let g:php_omni_bi_classes = {} for i in keys(g:php_builtin_object_functions) let g:php_omni_bi_classes[substitute(i, '::.*$', '', '')] = '' endfor endif let classes = sort(keys(int_classes)) let classes += sort(keys(ext_classes)) let classes += sort(keys(g:php_omni_bi_classes)) for m in classes if m =~ '^'.a:base call add(res, m) endif endfor let final_menu = [] for i in res let final_menu += [{'word':i, 'kind':'c'}] endfor return final_menu elseif scontext =~ '\(->\|::\)$' " Complete user functions and variables " Internal solution for current file. " That seems as unnecessary repeating of functions but there are " few not so subtle differences as not appending of $ and addition " of 'kind' tag (not necessary in regular completion) if scontext =~ '->$' && scontext !~ '\$this->$' " Get name of the class let classname = phpcomplete#GetClassName(scontext) " Get location of class definition, we have to iterate through all " tags files separately because we need relative path from current " file to the exact file (tags file can be in different dir) if classname != '' let classlocation = phpcomplete#GetClassLocation(classname) else let classlocation = '' endif if classlocation == 'VIMPHP_BUILTINOBJECT' for object in keys(g:php_builtin_object_functions) if object =~ '^'.classname let res += [{'word':substitute(object, '.*::', '', ''), \ 'info': g:php_builtin_object_functions[object]}] endif endfor return res endif if filereadable(classlocation) let classfile = readfile(classlocation) let classcontent = '' let classcontent .= "\n".phpcomplete#GetClassContents(classfile, classname) let sccontent = split(classcontent, "\n") " YES, YES, YES! - we have whole content including extends! " Now we need to get two elements: public functions and public " vars " NO, NO, NO! - third separate filtering looking for content " :(, but all of them have differences. To squeeze them into " one implementation would require many additional arguments " and ifs. No good solution " Functions declared with public keyword or without any " keyword are public let functions = filter(deepcopy(sccontent), \ 'v:val =~ "^\\s*\\(static\\s\\+\\|public\\s\\+\\)*function"') let jfuncs = join(functions, ' ') let sfuncs = split(jfuncs, 'function\s\+') let c_functions = {} for i in sfuncs let f_name = matchstr(i, \ '^&\?\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') let f_args = matchstr(i, \ '^&\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*(\zs.\{-}\ze)\_s*{') if f_name != '' let c_functions[f_name.'('] = f_args endif endfor " Variables declared with var or with public keyword are " public let variables = filter(deepcopy(sccontent), \ 'v:val =~ "^\\s*\\(public\\|var\\)\\s\\+\\$"') let jvars = join(variables, ' ') let svars = split(jvars, '\$') let c_variables = {} for i in svars let c_var = matchstr(i, \ '^\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') if c_var != '' let c_variables[c_var] = '' endif endfor let all_values = {} call extend(all_values, c_functions) call extend(all_values, c_variables) for m in sort(keys(all_values)) if m =~ '^'.a:base && m !~ '::' call add(res, m) elseif m =~ '::'.a:base call add(res2, m) endif endfor let start_list = res + res2 let final_list = [] for i in start_list if has_key(c_variables, i) let class = ' ' if all_values[i] != '' let class = i.' class ' endif let final_list += \ [{'word':i, \ 'info':class.all_values[i], \ 'kind':'v'}] else let final_list += \ [{'word':substitute(i, '.*::', '', ''), \ 'info':i.all_values[i].')', \ 'kind':'f'}] endif endfor return final_list endif endif if a:base =~ '^\$' let adddollar = '$' else let adddollar = '' endif let file = getline(1, '$') let jfile = join(file, ' ') let sfile = split(jfile, '\$') let int_vars = {} for i in sfile if i =~ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*=\s*new' let val = matchstr(i, '^[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*').'->' else let val = matchstr(i, '^[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*') endif if val !~ '' let int_vars[adddollar.val] = '' endif endfor " ctags has good support for PHP, use tags file for external " variables let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) let ext_vars = {} if fnames != '' let sbase = substitute(a:base, '^\$', '', '') exe 'silent! vimgrep /^'.sbase.'.*\tv\(\t\|$\)/j '.fnames let qflist = getqflist() if len(qflist) > 0 for field in qflist let item = matchstr(field['text'], '^[^[:space:]]\+') " Add -> if it is possible object declaration let classname = '' if field['text'] =~ item.'\s*=\s*new\s\+' let item = item.'->' let classname = matchstr(field['text'], \ '=\s*new\s\+\zs[a-zA-Z_0-9\x7f-\xff]\+\ze') endif let ext_vars[adddollar.item] = classname endfor endif endif " Now we have all variables in int_vars dictionary call extend(int_vars, ext_vars) " Internal solution for finding functions in current file. let file = getline(1, '$') call filter(file, \ 'v:val =~ "function\\s\\+&\\?[a-zA-Z_\\x7f-\\xff][a-zA-Z_0-9\\x7f-\\xff]*\\s*("') let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) let jfile = join(file, ' ') let int_values = split(jfile, 'function\s\+') let int_functions = {} for i in int_values let f_name = matchstr(i, \ '^&\?\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') let f_args = matchstr(i, \ '^&\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*(\zs.\{-}\ze)\_s*{') let int_functions[f_name.'('] = f_args.')' endfor " Prepare list of functions from tags file let ext_functions = {} if fnames != '' exe 'silent! vimgrep /^'.a:base.'.*\tf\(\t\|$\)/j '.fnames let qflist = getqflist() if len(qflist) > 0 for field in qflist " File name let item = matchstr(field['text'], '^[^[:space:]]\+') let fname = matchstr(field['text'], '\t\zs\f\+\ze') let prototype = matchstr(field['text'], \ 'function\s\+&\?[^[:space:]]\+\s*(\s*\zs.\{-}\ze\s*)\s*{\?') let ext_functions[item.'('] = prototype.') - '.fname endfor endif endif let all_values = {} call extend(all_values, int_functions) call extend(all_values, ext_functions) call extend(all_values, int_vars) " external variables are already in call extend(all_values, g:php_builtin_object_functions) for m in sort(keys(all_values)) if m =~ '\(^\|::\)'.a:base call add(res, m) endif endfor let start_list = res let final_list = [] for i in start_list if has_key(int_vars, i) let class = ' ' if all_values[i] != '' let class = i.' class ' endif let final_list += [{'word':i, 'info':class.all_values[i], 'kind':'v'}] else let final_list += \ [{'word':substitute(i, '.*::', '', ''), \ 'info':i.all_values[i], \ 'kind':'f'}] endif endfor return final_list endif if a:base =~ '^\$' " Complete variables " Built-in variables {{{ let g:php_builtin_vars = {'$GLOBALS':'', \ '$_SERVER':'', \ '$_GET':'', \ '$_POST':'', \ '$_COOKIE':'', \ '$_FILES':'', \ '$_ENV':'', \ '$_REQUEST':'', \ '$_SESSION':'', \ '$HTTP_SERVER_VARS':'', \ '$HTTP_ENV_VARS':'', \ '$HTTP_COOKIE_VARS':'', \ '$HTTP_GET_VARS':'', \ '$HTTP_POST_VARS':'', \ '$HTTP_POST_FILES':'', \ '$HTTP_SESSION_VARS':'', \ '$php_errormsg':'', \ '$this':'' \ } " }}} " Internal solution for current file. let file = getline(1, '$') let jfile = join(file, ' ') let int_vals = split(jfile, '\ze\$') let int_vars = {} for i in int_vals if i =~ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*=\s*new' let val = matchstr(i, \ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*').'->' else let val = matchstr(i, \ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*') endif if val != '' let int_vars[val] = '' endif endfor call extend(int_vars,g:php_builtin_vars) " ctags has support for PHP, use tags file for external variables let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) let ext_vars = {} if fnames != '' let sbase = substitute(a:base, '^\$', '', '') exe 'silent! vimgrep /^'.sbase.'.*\tv\(\t\|$\)/j '.fnames let qflist = getqflist() if len(qflist) > 0 for field in qflist let item = '$'.matchstr(field['text'], '^[^[:space:]]\+') let m_menu = '' " Add -> if it is possible object declaration if field['text'] =~ item.'\s*=\s*new\s\+' let item = item.'->' let m_menu = matchstr(field['text'], \ '=\s*new\s\+\zs[a-zA-Z_0-9\x7f-\xff]\+\ze') endif let ext_vars[item] = m_menu endfor endif endif call extend(int_vars, ext_vars) let g:a0 = keys(int_vars) for m in sort(keys(int_vars)) if m =~ '^\'.a:base call add(res, m) endif endfor let int_list = res let int_dict = [] for i in int_list if int_vars[i] != '' let class = ' ' if int_vars[i] != '' let class = i.' class ' endif let int_dict += [{'word':i, 'info':class.int_vars[i], 'kind':'v'}] else let int_dict += [{'word':i, 'kind':'v'}] endif endfor return int_dict else " Complete everything else - " + functions, DONE " + keywords of language DONE " + defines (constant definitions), DONE " + extend keywords for predefined constants, DONE " + classes (after new), DONE " + limit choice after -> and :: to funcs and vars DONE " Internal solution for finding functions in current file. let file = getline(1, '$') call filter(file, \ 'v:val =~ "function\\s\\+&\\?[a-zA-Z_\\x7f-\\xff][a-zA-Z_0-9\\x7f-\\xff]*\\s*("') let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) let jfile = join(file, ' ') let int_values = split(jfile, 'function\s\+') let int_functions = {} for i in int_values let f_name = matchstr(i, \ '^&\?\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') let f_args = matchstr(i, \ '^&\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*(\s*\zs.\{-}\ze\s*)\_s*{') let int_functions[f_name.'('] = f_args.')' endfor " Prepare list of functions from tags file let ext_functions = {} if fnames != '' exe 'silent! vimgrep /^'.a:base.'.*\tf\(\t\|$\)/j '.fnames let qflist = getqflist() if len(qflist) > 0 for field in qflist " File name let item = matchstr(field['text'], '^[^[:space:]]\+') let fname = matchstr(field['text'], '\t\zs\f\+\ze') let prototype = matchstr(field['text'], \ 'function\s\+&\?[^[:space:]]\+\s*(\s*\zs.\{-}\ze\s*)\s*{\?') let ext_functions[item.'('] = prototype.') - '.fname endfor endif endif " All functions call extend(int_functions, ext_functions) call extend(int_functions, g:php_builtin_functions) " Internal solution for finding constants in current file let file = getline(1, '$') call filter(file, 'v:val =~ "define\\s*("') let jfile = join(file, ' ') let int_values = split(jfile, 'define\s*(\s*') let int_constants = {} for i in int_values let c_name = matchstr(i, '\(["'']\)\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze\1') " let c_value = matchstr(i, " \ '\(["'']\)[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\1\s*,\s*\zs.\{-}\ze\s*)') if c_name != '' let int_constants[c_name] = '' " c_value endif endfor " Prepare list of constants from tags file let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) let ext_constants = {} if fnames != '' exe 'silent! vimgrep /^'.a:base.'.*\td\(\t\|$\)/j '.fnames let qflist = getqflist() if len(qflist) > 0 for field in qflist let item = matchstr(field['text'], '^[^[:space:]]\+') let ext_constants[item] = '' endfor endif endif " All constants call extend(int_constants, ext_constants) " Treat keywords as constants let all_values = {} " One big dictionary of functions call extend(all_values, int_functions) " Add constants call extend(all_values, int_constants) " Add keywords call extend(all_values, g:php_keywords) for m in sort(keys(all_values)) if m =~ '^'.a:base call add(res, m) endif endfor let int_list = res let final_list = [] for i in int_list if has_key(int_functions, i) let final_list += \ [{'word':i, \ 'info':i.int_functions[i], \ 'kind':'f'}] elseif has_key(int_constants, i) let final_list += [{'word':i, 'kind':'d'}] else let final_list += [{'word':i}] endif endfor return final_list endif endfunction " vim:set foldmethod=marker: pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/pleac.in.rb000066400000000000000000000710041250413007300257100ustar00rootroot00000000000000# -*- ruby -*- # Local variables: # indent-tabs-mode: nil # ruby-indent-level: 4 # End: # @@PLEAC@@_NAME # @@SKIP@@ Ruby # @@PLEAC@@_WEB # @@SKIP@@ http://www.ruby-lang.org # @@PLEAC@@_1.0 string = '\n' # two characters, \ and an n string = 'Jon \'Maddog\' Orwant' # literal single quotes string = "\n" # a "newline" character string = "Jon \"Maddog\" Orwant" # literal double quotes string = %q/Jon 'Maddog' Orwant/ # literal single quotes string = %q[Jon 'Maddog' Orwant] # literal single quotes string = %q{Jon 'Maddog' Orwant} # literal single quotes string = %q(Jon 'Maddog' Orwant) # literal single quotes string = %q # literal single quotes a = <<"EOF" This is a multiline here document terminated by EOF on a line by itself EOF # @@PLEAC@@_1.1 value = string[offset,count] value = string[offset..-1] string[offset,count] = newstring string[offset..-1] = newtail # in Ruby we can also specify intervals by their two offsets value = string[offset..offs2] string[offset..offs2] = newstring leading, s1, s2, trailing = data.unpack("A5 x3 A8 A8 A*") fivers = string.unpack("A5" * (string.length/5)) chars = string.unpack("A1" * string.length) string = "This is what you have" # +012345678901234567890 Indexing forwards (left to right) # 109876543210987654321- Indexing backwards (right to left) # note that 0 means 10 or 20, etc. above first = string[0, 1] # "T" start = string[5, 2] # "is" rest = string[13..-1] # "you have" last = string[-1, 1] # "e" end_ = string[-4..-1] # "have" piece = string[-8, 3] # "you" string[5, 2] = "wasn't" # change "is" to "wasn't" string[-12..-1] = "ondrous" # "This wasn't wondrous" string[0, 1] = "" # delete first character string[-10..-1] = "" # delete last 10 characters if string[-10..-1] =~ /pattern/ puts "Pattern matches in last 10 characters" end string[0, 5].gsub!(/is/, 'at') a = "make a hat" a[0, 1], a[-1, 1] = a[-1, 1], a[0, 1] a = "To be or not to be" b = a.unpack("x6 A6") b, c = a.unpack("x6 A2 X5 A2") puts "#{b}\n#{c}\n" def cut2fmt(*args) template = '' lastpos = 1 for place in args template += "A" + (place - lastpos).to_s + " " lastpos = place end template += "A*" return template end fmt = cut2fmt(8, 14, 20, 26, 30) # @@PLEAC@@_1.2 # careful! "b is true" doesn't mean "b != 0" (0 is true in Ruby) # thus no problem of "defined" later since only nil is false # the following sets to `c' if `b' is nil or false a = b || c # if you need Perl's behaviour (setting to `c' if `b' is 0) the most # effective way is to use Numeric#nonzero? (thanks to Dave Thomas!) a = b.nonzero? || c # you will still want to use defined? in order to test # for scope existence of a given object a = defined?(b) ? b : c dir = ARGV.shift || "/tmp" # @@PLEAC@@_1.3 v1, v2 = v2, v1 alpha, beta, production = %w(January March August) alpha, beta, production = beta, production, alpha # @@PLEAC@@_1.4 num = char[0] char = num.chr # Ruby also supports having a char from character constant num = ?r char = sprintf("%c", num) printf("Number %d is character %c\n", num, num) ascii = string.unpack("C*") string = ascii.pack("C*") hal = "HAL" ascii = hal.unpack("C*") # We can't use Array#each since we can't mutate a Fixnum ascii.collect! { |i| i + 1 # add one to each ASCII value } ibm = ascii.pack("C*") puts ibm # @@PLEAC@@_1.5 array = string.split('') array = string.unpack("C*") string.scan(/./) { |b| # do something with b } string = "an apple a day" print "unique chars are: ", string.split('').uniq.sort, "\n" sum = 0 for ascval in string.unpack("C*") # or use Array#each for a pure OO style :) sum += ascval end puts "sum is #{sum & 0xffffffff}" # since Ruby will go Bignum if necessary # @@INCLUDE@@ include/ruby/slowcat.rb # @@PLEAC@@_1.6 revbytes = string.reverse revwords = string.split(" ").reverse.join(" ") revwords = string.split(/(\s+)/).reverse.join # using the fact that IO is Enumerable, you can directly "select" it long_palindromes = File.open("/usr/share/dict/words"). select { |w| w.chomp!; w.reverse == w && w.length > 5 } # @@PLEAC@@_1.7 while string.sub!("\t+") { ' ' * ($&.length * 8 - $`.length % 8) } end # @@PLEAC@@_1.8 'You owe #{debt} to me'.gsub(/\#{(\w+)}/) { eval($1) } rows, cols = 24, 80 text = %q(I am #{rows} high and #{cols} long) text.gsub!(/\#{(\w+)}/) { eval("#{$1}") } puts text 'I am 17 years old'.gsub(/\d+/) { 2 * $&.to_i } # @@PLEAC@@_1.9 e = "bo peep".upcase e.downcase! e.capitalize! "thIS is a loNG liNE".gsub!(/\w+/) { $&.capitalize } # @@PLEAC@@_1.10 "I have #{n+1} guanacos." print "I have ", n+1, " guanacos." # @@PLEAC@@_1.11 var = <<'EOF'.gsub(/^\s+/, '') your text goes here EOF # @@PLEAC@@_1.12 string = "Folding and splicing is the work of an editor,\n"+ "not a mere collection of silicon\n"+ "and\n"+ "mobile electrons!" def wrap(str, max_size) all = [] line = '' for l in str.split if (line+l).length >= max_size all.push(line) line = '' end line += line == '' ? l : ' ' + l end all.push(line).join("\n") end print wrap(string, 20) #=> Folding and #=> splicing is the #=> work of an editor, #=> not a mere #=> collection of #=> silicon and mobile #=> electrons! # @@PLEAC@@_1.13 string = %q(Mom said, "Don't do that.") string.gsub(/['"]/) { '\\'+$& } string.gsub(/['"]/, '\&\&') string.gsub(/[^A-Z]/) { '\\'+$& } "is a test!".gsub(/\W/) { '\\'+$& } # no function like quotemeta? # @@PLEAC@@_1.14 string.strip! # @@PLEAC@@_1.15 def parse_csv(text) new = text.scan(/"([^\"\\]*(?:\\.[^\"\\]*)*)",?|([^,]+),?|,/) new << nil if text[-1] == ?, new.flatten.compact end line = %q fields = parse_csv(line) fields.each_with_index { |v,i| print "#{i} : #{v}\n"; } # @@PLEAC@@_1.16 # Use the soundex.rb Library from Michael Neumann. # http://www.s-direktnet.de/homepages/neumann/rb_prgs/Soundex.rb require 'Soundex' code = Text::Soundex.soundex(string) codes = Text::Soundex.soundex(array) # substitution function for getpwent(): # returns an array of user entries, # each entry contains the username and the full name def login_names result = [] File.open("/etc/passwd") { |file| file.each_line { |line| next if line.match(/^#/) cols = line.split(":") result.push([cols[0], cols[4]]) } } result end puts "Lookup user: " user = STDIN.gets user.chomp! exit unless user name_code = Text::Soundex.soundex(user) splitter = Regexp.new('(\w+)[^,]*\b(\w+)') for username, fullname in login_names do firstname, lastname = splitter.match(fullname)[1,2] if name_code == Text::Soundex.soundex(username) || name_code == Text::Soundex.soundex(firstname) || name_code == Text::Soundex.soundex(lastname) then puts "#{username}: #{firstname} #{lastname}" end end # @@PLEAC@@_1.17 # @@INCLUDE@@ include/ruby/fixstyle.rb # @@PLEAC@@_1.18 # @@INCLUDE@@ include/ruby/psgrep.rb # @@PLEAC@@_2.1 # Matz tells that you can use Integer() for strict checked conversion. Integer("abc") #=> `Integer': invalid value for Integer: "abc" (ArgumentError) Integer("567") #=> 567 # You may use Float() for floating point stuff Integer("56.7") #=> `Integer': invalid value for Integer: "56.7" (ArgumentError) Float("56.7") #=> 56.7 # You may also use a regexp for that if string =~ /^[+-]?\d+$/ p 'is an integer' else p 'is not' end if string =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ p 'is a decimal number' else p 'is not' end # @@PLEAC@@_2.2 # equal(num1, num2, accuracy) : returns true if num1 and num2 are # equal to accuracy number of decimal places def equal(i, j, a) sprintf("%.#{a}g", i) == sprintf("%.#{a}g", j) end wage = 536 # $5.36/hour week = 40 * wage # $214.40 printf("One week's wage is: \$%.2f\n", week/100.0) # @@PLEAC@@_2.3 num.round # rounds to integer a = 0.255 b = sprintf("%.2f", a) print "Unrounded: #{a}\nRounded: #{b}\n" printf "Unrounded: #{a}\nRounded: %.2f\n", a print "number\tint\tfloor\tceil\n" a = [ 3.3 , 3.5 , 3.7, -3.3 ] for n in a printf("% .1f\t% .1f\t% .1f\t% .1f\n", # at least I don't fake my output :) n, n.to_i, n.floor, n.ceil) end # @@PLEAC@@_2.4 def dec2bin(n) [n].pack("N").unpack("B32")[0].sub(/^0+(?=\d)/, '') end def bin2dec(n) [("0"*32+n.to_s)[-32..-1]].pack("B32").unpack("N")[0] end # @@PLEAC@@_2.5 for i in x .. y # i is set to every integer from x to y, inclusive end x.step(y,7) { |i| # i is set to every integer from x to y, stepsize = 7 } print "Infancy is: " (0..2).each { |i| print i, " " } print "\n" # @@PLEAC@@_2.6 # We can add conversion methods to the Integer class, # this makes a roman number just a representation for normal numbers. class Integer @@romanlist = [["M", 1000], ["CM", 900], ["D", 500], ["CD", 400], ["C", 100], ["XC", 90], ["L", 50], ["XL", 40], ["X", 10], ["IX", 9], ["V", 5], ["IV", 4], ["I", 1]] def to_roman remains = self roman = "" for sym, num in @@romanlist while remains >= num remains -= num roman << sym end end roman end def Integer.from_roman(roman) ustr = roman.upcase sum = 0 for entry in @@romanlist sym, num = entry[0], entry[1] while sym == ustr[0, sym.length] sum += num ustr.slice!(0, sym.length) end end sum end end roman_fifteen = 15.to_roman puts "Roman for fifteen is #{roman_fifteen}" i = Integer.from_roman(roman_fifteen) puts "Converted back, #{roman_fifteen} is #{i}" # check for i in (1..3900) r = i.to_roman j = Integer.from_roman(r) if i != j puts "error: #{i} : #{r} - #{j}" end end # @@PLEAC@@_2.7 random = rand(y-x+1)+x chars = ["A".."Z","a".."z","0".."9"].collect { |r| r.to_a }.join + %q(!@$%^&*) password = (1..8).collect { chars[rand(chars.size)] }.pack("C*") # @@PLEAC@@_2.8 srand # uses a combination of the time, the process id, and a sequence number srand(val) # for repeatable behaviour # @@PLEAC@@_2.9 # from the randomr lib: # http://raa.ruby-lang.org/project/randomr/ ----> http://raa.ruby-lang.org/project/randomr/ require 'random/mersenne_twister' mers = Random::MersenneTwister.new 123456789 puts mers.rand(0) # 0.550321932544541 puts mers.rand(10) # 2 # using online sources of random data via the realrand package: # http://raa.ruby-lang.org/project/realrand/ # **Note** # The following online services are used in this package: # http://www.random.org - source: atmospheric noise # http://www.fourmilab.ch/hotbits - source: radioactive decay timings # http://random.hd.org - source: entropy from local and network noise # Please visit the sites and respect the rules of each service. require 'random/online' generator1 = Random::RandomOrg.new puts generator1.randbyte(5).join(",") puts generator1.randnum(10, 1, 6).join(",") # Roll dice 10 times. generator2 = Random::FourmiLab.new puts generator2.randbyte(5).join(",") # randnum is not supported. generator3 = Random::EntropyPool.new puts generator3.randbyte(5).join(",") # randnum is not supported. # @@PLEAC@@_2.10 def gaussian_rand begin u1 = 2 * rand() - 1 u2 = 2 * rand() - 1 w = u1*u1 + u2*u2 end while (w >= 1) w = Math.sqrt((-2*Math.log(w))/w) [ u2*w, u1*w ] end mean = 25 sdev = 2 salary = gaussian_rand[0] * sdev + mean printf("You have been hired at \$%.2f\n", salary) # @@PLEAC@@_2.11 def deg2rad(d) (d/180.0)*Math::PI end def rad2deg(r) (r/Math::PI)*180 end # @@PLEAC@@_2.12 sin_val = Math.sin(angle) cos_val = Math.cos(angle) tan_val = Math.tan(angle) # AFAIK Ruby's Math module doesn't provide acos/asin # While we're at it, let's also define missing hyperbolic functions module Math def Math.asin(x) atan2(x, sqrt(1 - x**2)) end def Math.acos(x) atan2(sqrt(1 - x**2), x) end def Math.atan(x) atan2(x, 1) end def Math.sinh(x) (exp(x) - exp(-x)) / 2 end def Math.cosh(x) (exp(x) + exp(-x)) / 2 end def Math.tanh(x) sinh(x) / cosh(x) end end # The support for Complex numbers is not built-in y = Math.acos(3.7) #=> in `sqrt': square root for negative number (ArgumentError) # There is an implementation of Complex numbers in 'complex.rb' in current # Ruby distro, but it doesn't support atan2 with complex args, so it doesn't # solve this problem. # @@PLEAC@@_2.13 log_e = Math.log(val) log_10 = Math.log10(val) def log_base(base, val) Math.log(val)/Math.log(base) end answer = log_base(10, 10_000) puts "log10(10,000) = #{answer}" # @@PLEAC@@_2.14 require 'matrix.rb' a = Matrix[[3, 2, 3], [5, 9, 8]] b = Matrix[[4, 7], [9, 3], [8, 1]] c = a * b a.row_size a.column_size c.det a.transpose # @@PLEAC@@_2.15 require 'complex.rb' require 'rational.rb' a = Complex(3, 5) # 3 + 5i b = Complex(2, -2) # 2 - 2i puts "c = #{a*b}" c = a * b d = 3 + 4*Complex::I printf "sqrt(#{d}) = %s\n", Math.sqrt(d) # @@PLEAC@@_2.16 number = hexadecimal.hex number = octal.oct print "Gimme a number in decimal, octal, or hex: " num = gets.chomp exit unless defined?(num) num = num.oct if num =~ /^0/ # does both oct and hex printf "%d %x %o\n", num, num, num print "Enter file permission in octal: " permissions = gets.chomp raise "Exiting ...\n" unless defined?(permissions) puts "The decimal value is #{permissions.oct}" # @@PLEAC@@_2.17 def commify(n) n.to_s =~ /([^\.]*)(\..*)?/ int, dec = $1.reverse, $2 ? $2 : "" while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3') end int.reverse + dec end # @@PLEAC@@_2.18 printf "It took %d hour%s\n", time, time == 1 ? "" : "s" # dunno if an equivalent to Lingua::EN::Inflect exists... # @@PLEAC@@_2.19 #----------------------------- #!/usr/bin/ruby # bigfact - calculating prime factors def factorize(orig) factors = {} factors.default = 0 # return 0 instead nil if key not found in hash n = orig i = 2 sqi = 4 # square of i while sqi <= n do while n.modulo(i) == 0 do n /= i factors[i] += 1 # puts "Found factor #{i}" end # we take advantage of the fact that (i +1)**2 = i**2 + 2*i +1 sqi += 2 * i + 1 i += 1 end if (n != 1) && (n != orig) factors[n] += 1 end factors end def printfactorhash(orig, factorcount) print format("%-10d ", orig) if factorcount.length == 0 print "PRIME" else # sorts after number, because the hash keys are numbers factorcount.sort.each { |factor,exponent| print factor if exponent > 1 print "**", exponent end print " " } end puts end for arg in ARGV n = arg.to_i mfactors = factorize(n) printfactorhash(n, mfactors) end #----------------------------- # @@PLEAC@@_3.0 puts Time.now print "Today is day ", Time.now.yday, " of the current year.\n" print "Today is day ", Time.now.day, " of the current month.\n" # @@PLEAC@@_3.1 day, month, year = Time.now.day, Time.now.month, Time.now.year # or day, month, year = Time.now.to_a[3..5] tl = Time.now.localtime printf("The current date is %04d %02d %02d\n", tl.year, tl.month, tl.day) Time.now.localtime.strftime("%Y-%m-%d") # @@PLEAC@@_3.2 Time.local(year, month, day, hour, minute, second).tv_sec Time.gm(year, month, day, hour, minute, second).tv_sec # @@PLEAC@@_3.3 sec, min, hour, day, month, year, wday, yday, isdst, zone = Time.at(epoch_secs).to_a # @@PLEAC@@_3.4 when_ = now + difference # now -> Time ; difference -> Numeric (delta in seconds) then_ = now - difference # @@PLEAC@@_3.5 bree = 361535725 nat = 96201950 difference = bree - nat puts "There were #{difference} seconds between Nat and Bree" seconds = difference % 60 difference = (difference - seconds) / 60 minutes = difference % 60 difference = (difference - minutes) / 60 hours = difference % 24 difference = (difference - hours) / 24 days = difference % 7 weeks = (difference - days) / 7 puts "(#{weeks} weeks, #{days} days, #{hours}:#{minutes}:#{seconds})" # @@PLEAC@@_3.6 monthday, weekday, yearday = date.mday, date.wday, date.yday # AFAIK the week number is not just a division since week boundaries are on sundays weeknum = d.strftime("%U").to_i + 1 year = 1981 month = "jun" # or `6' if you want to emulate a broken language day = 16 t = Time.mktime(year, month, day) print "#{month}/#{day}/#{year} was a ", t.strftime("%A"), "\n" # @@PLEAC@@_3.7 yyyy, mm, dd = $1, $2, $3 if "1998-06-25" =~ /(\d+)-(\d+)-(\d+)/ epoch_seconds = Time.mktime(yyyy, mm, dd).tv_sec # dunno an equivalent to Date::Manip#ParseDate # @@PLEAC@@_3.8 string = Time.at(epoch_secs) Time.at(1234567890).gmtime # gives: Fri Feb 13 23:31:30 UTC 2009 time = Time.mktime(1973, "jan", 18, 3, 45, 50) print "In localtime it gives: ", time.localtime, "\n" # @@PLEAC@@_3.9 # Ruby provides micro-seconds in Time object Time.now.usec # Ruby gives the seconds in floating format when substracting two Time objects before = Time.now line = gets elapsed = Time.now - before puts "You took #{elapsed} seconds." # On my Celeron-400 with Linux-2.2.19-14mdk, average for three execs are: # This Ruby version: average 0.00321 sec # Cookbook's Perl version: average 0.00981 sec size = 500 number_of_times = 100 total_time = 0 number_of_times.times { # populate array array = [] size.times { array << rand } # sort it begin_ = Time.now array.sort! time = Time.now - begin_ total_time += time } printf "On average, sorting %d random numbers takes %.5f seconds\n", size, (total_time/Float(number_of_times)) # @@PLEAC@@_3.10 sleep(0.005) # Ruby is definitely not as broken as Perl :) # (may be interrupted by sending the process a SIGALRM) # @@PLEAC@@_3.11 #!/usr/bin/ruby -w # hopdelta - feed mail header, produce lines # showing delay at each hop. require 'time' class MailHopDelta def initialize(mail) @head = mail.gsub(/\n\s+/,' ') @topline = %w-Sender Recipient Time Delta- @start_from = mail.match(/^From.*\@([^\s>]*)/)[1] @date = Time.parse(mail.match(/^Date:\s+(.*)/)[1]) end def out(line) "%-20.20s %-20.20s %-20.20s %s" % line end def hop_date(day) day.strftime("%I:%M:%S %Y/%m/%d") end def puts_hops puts out(@topline) puts out(['Start', @start_from, hop_date(@date),'']) @head.split(/\n/).reverse.grep(/^Received:/).each do |hop| hop.gsub!(/\bon (.*?) (id.*)/,'; \1') whence = hop.match(/;\s+(.*)$/)[1] unless whence warn "Bad received line: #{hop}" next end from = $+ if hop =~ /from\s+(\S+)|\((.*?)\)/ by = $1 if hop =~ /by\s+(\S+\.\S+)/ next unless now = Time.parse(whence).localtime delta = now - @date puts out([from, by, hop_date(now), hop_time(delta)]) @date = now end end def hop_time(secs) sign = secs < 0 ? -1 : 1 days, secs = secs.abs.divmod(60 * 60 * 24) hours,secs = secs.abs.divmod(60 * 60) mins, secs = secs.abs.divmod(60) rtn = "%3ds" % [secs * sign] rtn << "%3dm" % [mins * sign] if mins != 0 rtn << "%3dh" % [hours * sign] if hours != 0 rtn << "%3dd" % [days * sign] if days != 0 rtn end end $/ = "" mail = MailHopDelta.new(ARGF.gets).puts_hops # @@PLEAC@@_4.0 single_level = [ "this", "that", "the", "other" ] # Ruby directly supports nested arrays double_level = [ "this", "that", [ "the", "other" ] ] still_single_level = [ "this", "that", [ "the", "other" ] ].flatten # @@PLEAC@@_4.1 a = [ "quick", "brown", "fox" ] a = %w(Why are you teasing me?) lines = <<"END_OF_HERE_DOC".gsub(/^\s*(.+)/, '\1') The boy stood on the burning deck, It was as hot as glass. END_OF_HERE_DOC bigarray = IO.readlines("mydatafile").collect { |l| l.chomp } name = "Gandalf" banner = %Q(Speak, #{name}, and welcome!) host_info = `host #{his_host}` %x(ps #{$$}) banner = 'Costs only $4.95'.split(' ') rax = %w! ( ) < > { } [ ] ! # @@PLEAC@@_4.2 def commify_series(arr) return '' if not arr case arr.size when 0 then '' when 1 then arr[0] when 2 then arr.join(' and ') else arr[0..-2].join(', ') + ', and ' + arr[-1] end end array = [ "red", "yellow", "green" ] print "I have ", array, " marbles\n" # -> I have redyellowgreen marbles # But unlike Perl: print "I have #{array} marbles\n" # -> I have redyellowgreen marbles # So, needs: print "I have #{array.join(' ')} marbles\n" # -> I have red yellow green marbles #!/usr/bin/ruby # communify_series - show proper comma insertion in list output def commify_series(arr) return '' if not arr sepchar = arr.find { |p| p =~ /,/ } ? '; ' : ', ' case arr.size when 0 then '' when 1 then arr[0] when 2 then arr.join(' and ') else arr[0..-2].join(sepchar) + sepchar + 'and ' + arr[-1] end end lists = [ [ 'just one thing' ], %w(Mutt Jeff), %w(Peter Paul Mary), [ 'To our parents', 'Mother Theresa', 'God' ], [ 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ], [ 'recycle tired, old phrases', 'ponder big, happy thoughts' ], [ 'recycle tired, old phrases', 'ponder big, happy thoughts', 'sleep and dream peacefully' ], ] for list in lists do puts "The list is: #{commify_series(list)}." end # @@PLEAC@@_4.3 # (note: AFAIK Ruby doesn't allow gory change of Array length) # grow the array by assigning nil to past the end of array ary[new_size-1] = nil # shrink the array by slicing it down ary.slice!(new_size..-1) # init the array with given size Array.new(number_of_elems) # assign to an element past the original end enlarges the array ary[index_new_last_elem] = value def what_about_that_array(a) print "The array now has ", a.size, " elements.\n" # Index of last element is not really interesting in Ruby print "Element #3 is `#{a[3]}'.\n" end people = %w(Crosby Stills Nash Young) what_about_that_array(people) # @@PLEAC@@_4.4 # OO style bad_users.each { |user| complain(user) } # or, functional style for user in bad_users complain(user) end for var in ENV.keys.sort puts "#{var}=#{ENV[var]}" end for user in all_users disk_space = get_usage(user) if (disk_space > MAX_QUOTA) complain(user) end end for l in IO.popen("who").readlines print l if l =~ /^gc/ end # we can mimic the obfuscated Perl way while fh.gets # $_ is set to the line just read chomp # $_ has a trailing \n removed, if it had one split.each { |w| # $_ is split on whitespace # but $_ is not set to each chunk as in Perl print w.reverse } end # ...or use a cleaner way for l in fh.readlines l.chomp.split.each { |w| print w.reverse } end # same drawback as in problem 1.4, we can't mutate a Numeric... array.collect! { |v| v - 1 } a = [ .5, 3 ]; b = [ 0, 1 ] for ary in [ a, b ] ary.collect! { |v| v * 7 } end puts "#{a.join(' ')} #{b.join(' ')}" # we can mutate Strings, cool; we need a trick for the scalar for ary in [ [ scalar ], array, hash.values ] ary.each { |v| v.strip! } # String#strip rules :) end # @@PLEAC@@_4.5 # not relevant in Ruby since we have always references for item in array # do somethingh with item end # @@PLEAC@@_4.6 unique = list.uniq # generate a list of users logged in, removing duplicates users = `who`.collect { |l| l =~ /(\w+)/; $1 }.sort.uniq puts("users logged in: #{commify_series(users)}") # see 4.2 for commify_series # @@PLEAC@@_4.7 a - b # [ 1, 1, 2, 2, 3, 3, 3, 4, 5 ] - [ 1, 2, 4 ] -> [3, 5] # @@PLEAC@@_4.8 union = a | b intersection = a & b difference = a - b # @@PLEAC@@_4.9 array1.concat(array2) # if you will assign to another object, better use: new_ary = array1 + array2 members = [ "Time", "Flies" ] initiates = [ "An", "Arrow" ] members += initiates members = [ "Time", "Flies" ] initiates = [ "An", "Arrow" ] members[2,0] = [ "Like", initiates ].flatten members[0] = "Fruit" members[3,2] = "A", "Banana" # @@PLEAC@@_4.10 reversed = ary.reverse ary.reverse_each { |e| # do something with e } descending = ary.sort.reverse descending = ary.sort { |a,b| b <=> a } # @@PLEAC@@_4.11 # remove n elements from front of ary (shift n) front = ary.slice!(0, n) # remove n elements from the end of ary (pop n) end_ = ary.slice!(-n .. -1) # let's extend the Array class, to make that useful class Array def shift2() slice!(0 .. 1) # more symetric with pop2... end def pop2() slice!(-2 .. -1) end end friends = %w(Peter Paul Mary Jim Tim) this, that = friends.shift2 beverages = %w(Dew Jolt Cola Sprite Fresca) pair = beverages.pop2 # @@PLEAC@@_4.12 # use Enumerable#detect (or the synonym Enumerable#find) highest_eng = employees.detect { |emp| emp.category == 'engineer' } # @@PLEAC@@_4.13 # use Enumerable#select (or the synonym Enumerable#find_all) bigs = nums.select { |i| i > 1_000_000 } pigs = users.keys.select { |k| users[k] > 1e7 } matching = `who`.select { |u| u =~ /^gnat / } engineers = employees.select { |e| e.position == 'Engineer' } secondary_assistance = applicants.select { |a| a.income >= 26_000 && a.income < 30_000 } # @@PLEAC@@_4.14 # normally you would have an array of Numeric (Float or # Fixnum or Bignum), so you would use: sorted = unsorted.sort # if you have strings representing Integers or Floats # you may specify another sort method: sorted = unsorted.sort { |a,b| a.to_f <=> b.to_f } # let's use the list of my own PID's `ps ux`.split("\n")[1..-1]. select { |i| i =~ /^#{ENV['USER']}/ }. collect { |i| i.split[1] }. sort { |a,b| a.to_i <=> b.to_i }.each { |i| puts i } puts "Select a process ID to kill:" pid = gets.chomp raise "Exiting ... \n" unless pid && pid =~ /^\d+$/ Process.kill('TERM', pid.to_i) sleep 2 Process.kill('KILL', pid.to_i) descending = unsorted.sort { |a,b| b.to_f <=> a.to_f } # @@PLEAC@@_4.15 ordered = unordered.sort { |a,b| compare(a,b) } precomputed = unordered.collect { |e| [compute, e] } ordered_precomputed = precomputed.sort { |a,b| a[0] <=> b[0] } ordered = ordered_precomputed.collect { |e| e[1] } ordered = unordered.collect { |e| [compute, e] }. sort { |a,b| a[0] <=> b[0] }. collect { |e| e[1] } for employee in employees.sort { |a,b| a.name <=> b.name } print employee.name, " earns \$ ", employee.salary, "\n" end # Beware! `0' is true in Ruby. # For chaining comparisons, you may use Numeric#nonzero?, which # returns num if num is not zero, nil otherwise sorted = employees.sort { |a,b| (a.name <=> b.name).nonzero? || b.age <=> a.age } users = [] # getpwent is not wrapped in Ruby... let's fallback IO.readlines('/etc/passwd').each { |u| users << u.split(':') } users.sort! { |a,b| a[0] <=> b[0] } for user in users puts user[0] end sorted = names.sort { |a,b| a[1, 1] <=> b[1, 1] } sorted = strings.sort { |a,b| a.length <=> b.length } # let's show only the compact version ordered = strings.collect { |e| [e.length, e] }. sort { |a,b| a[0] <=> b[0] }. collect { |e| e[1] } ordered = strings.collect { |e| [/\d+/.match(e)[0].to_i, e] }. sort { |a,b| a[0] <=> b[0] }. collect { |e| e[1] } print `cat /etc/passwd`.collect { |e| [e, e.split(':').indexes(3,2,0)].flatten }. sort { |a,b| (a[1] <=> b[1]).nonzero? || (a[2] <=> b[2]).nonzero? || a[3] <=> b[3] }. collect { |e| e[0] } # @@PLEAC@@_4.16 circular.unshift(circular.pop) # the last shall be first circular.push(circular.shift) # and vice versa def grab_and_rotate(l) l.push(ret = l.shift) ret end processes = [1, 2, 3, 4, 5] while (1) process = grab_and_rotate(processes) puts "Handling process #{process}" sleep 1 end # @@PLEAC@@_4.17 def fisher_yates_shuffle(a) (a.size-1).downto(1) { |i| j = rand(i+1) a[i], a[j] = a[j], a[i] if i != j } end def naive_shuffle(a) for i in 0...a.size j = rand(a.size) a[i], a[j] = a[j], a[i] end end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/postgresql_test.txt000066400000000000000000000014551250413007300277000ustar00rootroot00000000000000CREATE OR REPLACE FUNCTION something() RETURNS int4 AS $x$ BEGIN RETURN 42; END $x$ LANGUAGE 'plpgsql'; CREATE FUNCTION pymax (a integer, b integer) RETURNS integer AS $$ if a > b: return a return b $$ language plpythonu; CREATE FUNCTION nested_lexers (a integer, b integer) $function$ BEGIN SELECT ($1 ~ $q$[\t\r\n\v\\]$q$); END; $function$ LANGUAGE sql; CREATE OR REPLACE FUNCTION measurement_insert_trigger() RETURNS TRIGGER AS $$ BEGIN <> INSERT INTO measurement_y2008m01 VALUES (NEW.*); RETURN NULL; END; $$ LANGUAGE plpgsql; -- As returned by pg_dump CREATE FUNCTION test_function() RETURNS integer LANGUAGE plpgsql STABLE STRICT AS $$ begin return 42; end $$; -- Unicode names and strings SELECT U&'\0441\043B\043E\043D' FROM U&"\0441\043B\043E\043D"; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/pppoe.applescript000066400000000000000000000004661250413007300272710ustar00rootroot00000000000000tell application "System Events" tell network preferences tell current location set aPPPoEService to a reference to (first service whose kind is 10) if exists aPPPoEService then connect aPPPoEService end if end tell end tell end tell pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/psql_session.txt000066400000000000000000000053541250413007300271620ustar00rootroot00000000000000regression=# select foo; ERROR: column "foo" does not exist CONTEXT: PL/pgSQL function "test1" while casting return value to function's return type LINE 1: select foo; ^ regression=# \q peter@localhost testdb=> \a \t \x Output format is aligned. Tuples only is off. Expanded display is on. regression=# select '\x'; WARNING: nonstandard use of escape in a string literal LINE 1: select '\x'; ^ HINT: Use the escape string syntax for escapes, e.g., E'\r\n'. ?column? ---------- x (1 row) regression=# select E'\x'; piro=> \set foo 30; piro=> select * from test where foo <= :foo; foo | bar -----+----- 10 | 20 | (2 rows) testdb=> \set foo 'my_table' testdb=> SELECT * FROM :"foo"; testdb=> \set content `cat my_file.txt` testdb=> INSERT INTO my_table VALUES (:'content'); regression=# select ( regression(# 1); ?column? ---------- 1 (1 row) piro=> select ( piro(> ' piro'> ' || $$ piro$> $$) piro-> from " piro"> foo"; ERROR: relation " foo" does not exist LINE 5: from " ^ testdb=> CREATE TABLE my_table ( first integer not null default 0, second text) ; -- end of command CREATE TABLE -- Table output =# SELECT '0x10'::mpz AS "hex", '10'::mpz AS "dec", -# '010'::mpz AS oct, '0b10'::mpz AS bin; hex | dec | oct | bin -----+-----+-----+----- 16 | 10 | 8 | 2 (1 row) -- One field output regression=# select schemaname from pg_tables limit 3; schemaname ------------ pg_catalog pg_catalog pg_catalog (3 rows) -- TODO: prompt in multiline comments still not handled correctly test=> select 1 /* multiline test*> and 2 /* and 3 */ test*> end comment */, 2; ?column? | ?column? ----------+---------- 1 | 2 =# select 10.0, 1e-6, 1E+6; ?column? | ?column? | ?column? ----------+----------+---------- 10.0 | 0.000001 | 1000000 (1 row) regression=# begin; BEGIN regression=# create table asdf (foo serial primary key); NOTICE: CREATE TABLE will create implicit sequence "asdf_foo_seq" for serial column "asdf.foo" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "asdf_pkey" for table "asdf" CREATE TABLE regression=# insert into asdf values (10) returning foo; foo ----- 10 (1 row) INSERT 0 1 regression=# ROLLBACK ; ROLLBACK => EXPLAIN SELECT * FROM tenk1 -> WHERE unique1 < 100; -- Don't take -> in the plan as a prompt QUERY PLAN ------------------------------------------------------------------------------ Bitmap Heap Scan on tenk1 (cost=2.37..232.35 rows=106 width=244) Recheck Cond: (unique1 < 100) -> Bitmap Index Scan on tenk1_unique1 (cost=0.00..2.37 rows=106 width=0) Index Cond: (unique1 < 100) -- don't swallow the end of a malformed line test=> select 1, 'this line must be emitted' pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/py3_test.txt000066400000000000000000000000261250413007300262010ustar00rootroot00000000000000class Käse: pass pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/py3tb_test.py3tb000066400000000000000000000001031250413007300267450ustar00rootroot00000000000000 File "", line 1 1+ ^ SyntaxError: invalid syntax pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/pycon_test.pycon000066400000000000000000000002451250413007300271320ustar00rootroot00000000000000>>> : File "", line 1 : ^ SyntaxError: invalid syntax >>> KeyboardInterrupt >>> >>> 1/0 Traceback (most recent call last): ... ZeroDivisionError pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/pytb_test2.pytb000066400000000000000000000002571250413007300266730ustar00rootroot00000000000000 File "temp.py", line 1 SyntaxError: Non-ASCII character '\xc3' in file temp.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/pytb_test3.pytb000066400000000000000000000002211250413007300266630ustar00rootroot00000000000000>>> 3/"3" Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for /: 'int' and 'str' pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/python25-bsd.mak000066400000000000000000000164321250413007300266260ustar00rootroot00000000000000# New ports collection makefile for: python25 # Date created: 3 July 2003 # Whom: Hye-Shik Chang # # $FreeBSD: ports/lang/python25/Makefile,v 1.145 2007/10/03 23:22:04 edwin Exp $ PORTNAME= python25 PORTVERSION= 2.5.1 CATEGORIES= lang python ipv6 MASTER_SITES= ${PYTHON_MASTER_SITES} MASTER_SITE_SUBDIR= ${PYTHON_MASTER_SITE_SUBDIR} DISTFILES= ${PYTHON_DISTFILE} MAINTAINER= python@FreeBSD.org COMMENT?= An interpreted object-oriented programming language DIST_SUBDIR= python WRKSRC= ${PYTHON_WRKSRC}/portbld.static PATCH_WRKSRC= ${PYTHON_WRKSRC} GNU_CONFIGURE= yes CONFIGURE_TARGET= --build=${MACHINE_ARCH}-portbld-freebsd${OSREL} CONFIGURE_SCRIPT= ../configure # must be relative CONFIGURE_ENV= OPT="${CFLAGS}" SVNVERSION="echo freebsd" MAKE_ENV= VPATH="${PYTHON_WRKSRC}" INSTALLS_SHLIB= yes INSTALL_TARGET= altinstall MAN1= ${PYTHON_VERSION}.1 USE_PYTHON= yes PYTHON_VERSION= python2.5 PYTHON_NO_DEPENDS= yes SHARED_WRKSRC= ${PYTHON_WRKSRC}/portbld.shared PLIST= ${WRKDIR}/PLIST PLIST_TEMPLATE?=${PKGDIR}/pkg-plist PLIST_SUB= PYVER=${PYTHON_VERSION:S/python//} \ PYVER_WITHPAT=${PORTVERSION:S/.c/c/} DEMODIR= ${PREFIX}/share/examples/${PYTHON_VERSION} TOOLSDIR= ${PREFIX}/share/${PYTHON_VERSION} BIN_SCRIPTS= idle pydoc python python-shared smtpd.py python-config \ python-shared-config BINLINKS_SUB= -e 's,smtpd,smtpd${PYTHON_VER},' \ -e 's,(idle|pydoc|python-shared|python),\1${PYTHON_VER},' OPTIONS= THREADS "Enable thread support" on \ HUGE_STACK_SIZE "Use a larger thread stack" off \ UCS4 "Use UCS4 for unicode support" on \ PYMALLOC "Use python's internal malloc" on \ IPV6 "Enable IPv6 support" on \ FPECTL "Enable floating point exception handling" off .include .if ${PYTHON_VERSION} == ${PYTHON_DEFAULT_VERSION} MLINKS= ${PYTHON_VERSION}.1 python.1 PLIST_SUB+= IF_DEFAULT="" .else PLIST_SUB+= IF_DEFAULT="@comment " .endif # workaround for a bug in base curses.h. CFLAGS+= -D__wchar_t=wchar_t .if !defined(WITHOUT_THREADS) CONFIGURE_ARGS+= --with-threads CFLAGS+= ${PTHREAD_CFLAGS} .if defined(WITHOUT_HUGE_STACK_SIZE) CFLAGS+= -DTHREAD_STACK_SIZE=0x20000 .else CFLAGS+= -DTHREAD_STACK_SIZE=0x100000 .endif # defined(WITHOUT_HUGE_STACK_SIZE) CONFIGURE_ENV+= LDFLAGS="${PTHREAD_LIBS} ${LDFLAGS}" .else CONFIGURE_ARGS+= --without-threads .if defined(LDFLAGS) CONFIGURE_ENV+= LDFLAGS="${LDFLAGS}" .endif # defined(LDFLAGS) .endif # !defined(WITHOUT_THREADS) .if !defined(WITHOUT_UCS4) && !defined(WITH_UCS2) CONFIGURE_ARGS+= --enable-unicode=ucs4 .endif .if defined(WITHOUT_PYMALLOC) CONFIGURE_ARGS+= --without-pymalloc .endif .if ${ARCH} == i386 PLIST_SUB+= X86_ONLY="" .else PLIST_SUB+= X86_ONLY="@comment " .endif .if ${ARCH} == amd64 || ${ARCH} == ia64 || ${ARCH} == sparc64 || ${ARCH} == alpha PLIST_SUB+= 32BIT_ONLY="@comment " .else PLIST_SUB+= 32BIT_ONLY="" .endif .if ${ARCH} == sparc64 CFLAGS+= -DPYTHON_DEFAULT_RECURSION_LIMIT=900 .endif .if !exists(/usr/bin/ypcat) # the world with NO_NIS PLIST_SUB+= NO_NIS="@comment " .else PLIST_SUB+= NO_NIS="" .endif .if !defined(WITHOUT_IPV6) CONFIGURE_ARGS+= --enable-ipv6 .else CONFIGURE_ARGS+= --disable-ipv6 .endif .if defined(WITH_FPECTL) CONFIGURE_ARGS+= --with-fpectl .endif .if ${OSVERSION} >= 700000 PLATFORMS=plat-freebsd4 plat-freebsd5 plat-freebsd6 .elif ${OSVERSION} >= 600000 PLATFORMS=plat-freebsd4 plat-freebsd5 plat-freebsd7 .else PLATFORMS=plat-freebsd4 plat-freebsd6 plat-freebsd7 .endif pre-patch: ${MKDIR} ${WRKSRC} ${SHARED_WRKSRC}/Modules ${SED} -e '1s,^.*$$,#!${PREFIX}/bin/${PYTHON_VERSION},' \ ${PATCH_WRKSRC}/Tools/scripts/pydoc > ${WRKDIR}/pydoc2.5 ${SED} -e '1s,^.*$$,#!${PREFIX}/bin/${PYTHON_VERSION},' \ ${PATCH_WRKSRC}/Tools/scripts/idle > ${WRKDIR}/idle2.5 ${SED} -e '1s,^.*$$,#!${PREFIX}/bin/${PYTHON_VERSION},' \ ${PATCH_WRKSRC}/Lib/smtpd.py > ${WRKDIR}/smtpd2.5.py ${REINPLACE_CMD} -e \ 's,/usr/doc/python-docs-,${PREFIX}/share/doc/python,g' \ ${PATCH_WRKSRC}/Lib/pydoc.py ${REINPLACE_CMD} -e \ 's|^\( *prefixes = .*\)\]$$|\1, "${X11BASE}"]|g' \ ${PATCH_WRKSRC}/Lib/site.py ${REINPLACE_CMD} -e \ 's|^ \(..ASDLGEN.*\)$$| ${TRUE}|g' \ ${PATCH_WRKSRC}/Makefile.pre.in ${REINPLACE_CMD} -e \ 's|*\(..INSTALL_SCRIPT.*\)python-config$$|#port \1|' \ ${PATCH_WRKSRC}/Makefile.pre.in ${SED} -e 's|^#!.*|#!${PREFIX}/bin/${PYTHON_VERSION}|' \ ${PATCH_WRKSRC}/Misc/python-config.in > ${WRKDIR}/${PYTHON_VERSION}-config ${SED} -e 's|^#!.*|#!${PREFIX}/bin/${PYTHON_VERSION:S/thon/thon-shared/}|' \ ${PATCH_WRKSRC}/Misc/python-config.in > ${WRKDIR}/${PYTHON_VERSION:S/thon/thon-shared/}-config .if defined(WITH_FPECTL) && ${ARCH} == i386 ${MKDIR} ${WRKSRC}/Modules ${ECHO} "fpectl fpectlmodule.c" >> ${WRKSRC}/Modules/Setup.dist .endif post-configure: ${TAR} -C ${WRKSRC} -cf - . | ${TAR} -C ${SHARED_WRKSRC} -xf - ${LN} -sf ${PYTHON_WRKSRC}/Lib ${WRKSRC}/Lib ${SED} -e 's,^\(LDLIBRARY=\).*$$,\1libpython$$(VERSION).so,' \ -e 's,^\(BLDLIBRARY=\).*$$,\1-L. -lpython$$(VERSION),' \ -e 's,^\(CFLAGSFORSHARED=\).*$$,\1$$(CCSHARED),' \ -e 's,^\(Makefile Modules/config.c:.*\)Makefile.pre,\1,' \ -e 's,^\(.(BUILDPYTHON)\: .*\).(LIBRARY),\1,' \ -e 's,^\(.(BUILDPYTHON):.*\).(LIBRARY),\1,' \ ${WRKSRC}/Makefile > ${SHARED_WRKSRC}/Makefile pre-build: cd ${SHARED_WRKSRC}; \ ${SETENV} ${MAKE_ENV} ${MAKE} lib${PYTHON_VERSION}.so python; \ ${LN} -f lib${PYTHON_VERSION}.so lib${PYTHON_VERSION}.so.1; \ ${LN} -f python ${PYTHON_VERSION:S/thon/thon-shared/} pre-su-install: .for platform in ${PLATFORMS} ${MKDIR} ${PYTHONPREFIX_LIBDIR}/${platform} .for file in IN.py regen ${INSTALL_DATA} ${WRKSRC}/Lib/${platform}/${file} \ ${PYTHONPREFIX_LIBDIR}/${platform}/ .endfor .endfor pre-install: ${CAT} ${PLIST_TEMPLATE} | ${AWK} '{ print $$0; } \ /LIBDIR.*\.py$$/ && !/\/bad/ { print $$0 "o"; print $$0 "c"; }' > ${PLIST} @# if openssl 0.9.8 is detected, _sha{256,512} module won't be installed ([ -f ${WRKSRC}/.without_own_sha ] && \ ${GREP} -v 'lib-dynload/_sha' ${PLIST} > ${PLIST}.tmp && \ ${CAT} ${PLIST}.tmp > ${PLIST}) || ${TRUE} post-install: @# install config providers ${INSTALL_SCRIPT} ${WRKDIR}/${PYTHON_VERSION}-config ${PREFIX}/bin ${INSTALL_SCRIPT} ${WRKDIR}/${PYTHON_VERSION:S/thon/thon-shared/}-config ${PREFIX}/bin @# shared version of executable and library ${INSTALL_PROGRAM} ${SHARED_WRKSRC}/lib${PYTHON_VERSION}.so.1 \ ${PREFIX}/lib cd ${PREFIX}/lib; ${LN} -sf lib${PYTHON_VERSION}.so.1 \ lib${PYTHON_VERSION}.so ${LN} -sf ${PREFIX}/lib/lib${PYTHON_VERSION}.so ${PYTHONPREFIX_LIBDIR}/config ${INSTALL_PROGRAM} \ ${SHARED_WRKSRC}/${PYTHON_VERSION:S/thon/thon-shared/} \ ${PREFIX}/bin @# additional files installing by ports ${INSTALL_SCRIPT} ${WRKDIR}/pydoc2.5 ${WRKDIR}/idle2.5 \ ${WRKDIR}/smtpd2.5.py ${PREFIX}/bin @${MKDIR} ${MANPREFIX}/man/man1 ${INSTALL_MAN} ${PYTHON_WRKSRC}/Misc/python.man \ ${MANPREFIX}/man/man1/${PYTHON_VERSION}.1 .if ${PYTHON_VERSION} == ${PYTHON_DEFAULT_VERSION} for f in ${BIN_SCRIPTS}; do \ TARGET=`${ECHO_CMD} $$f | ${SED} -E ${BINLINKS_SUB}`; \ cd ${PREFIX}/bin && ${LN} -f $$TARGET $$f; \ done .endif .if !defined(NOPORTDOCS) @${MKDIR} ${TOOLSDIR} @cd ${PYTHON_WRKSRC}; ${TAR} -cf - Tools | \ (cd ${TOOLSDIR}; ${TAR} -xf -) @${MKDIR} ${DEMODIR} @cd ${PYTHON_WRKSRC}/Demo; ${TAR} -cf - * | \ (cd ${DEMODIR}; ${TAR} -xf -) .endif @${CAT} ${PKGMESSAGE} .include pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/qbasic_example000066400000000000000000000000521250413007300265650ustar00rootroot0000000000000010 print RIGHT$("hi there", 5) 20 goto 10 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/qsort.prolog000066400000000000000000000005661250413007300262730ustar00rootroot00000000000000partition([], _, [], []). partition([X|Xs], Pivot, Smalls, Bigs) :- ( X @< Pivot -> Smalls = [X|Rest], partition(Xs, Pivot, Rest, Bigs) ; Bigs = [X|Rest], partition(Xs, Pivot, Smalls, Rest) ). quicksort([]) --> []. quicksort([X|Xs]) --> { partition(Xs, X, Smaller, Bigger) }, quicksort(Smaller), [X], quicksort(Bigger). pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/r-console-transcript.Rout000066400000000000000000000015731250413007300306410ustar00rootroot00000000000000 R version 2.9.2 (2009-08-24) Copyright (C) 2009 The R Foundation for Statistical Computing ISBN 3-900051-07-0 R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. [R.app GUI 1.29 (5464) i386-apple-darwin8.11.1] > x <- function {} Error: syntax error > x <- function() {} > x <- function() { + cat("hello") + cat("world") + } > x function() { cat("hello") cat("world") } > x() helloworld > 2 + 2 [1] 4 > pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/r6rs-comments.scm000066400000000000000000000003611250413007300271130ustar00rootroot00000000000000#!r6rs #| The FACT procedure computes the factorial of a non-negative integer. |# (define fact (lambda (n) ;; base case (if (= n 0) #;(= n 1) 1 ; identity of * (* n (fact (- n 1)))))) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ragel-cpp_rlscan000066400000000000000000000103131250413007300270250ustar00rootroot00000000000000/* * Lexes Ragel input files. * * @LANG: c++ * * Test works with split code gen. */ #include #include #include #include using namespace std; void escapeXML( const char *data ) { while ( *data != 0 ) { switch ( *data ) { case '<': cout << "<"; break; case '>': cout << ">"; break; case '&': cout << "&"; break; default: cout << *data; break; } data += 1; } } void escapeXML( char c ) { switch ( c ) { case '<': cout << "<"; break; case '>': cout << ">"; break; case '&': cout << "&"; break; default: cout << c; break; } } void escapeXML( const char *data, int len ) { for ( const char *end = data + len; data != end; data++ ) { switch ( *data ) { case '<': cout << "<"; break; case '>': cout << ">"; break; case '&': cout << "&"; break; default: cout << *data; break; } } } inline void write( const char *data ) { cout << data; } inline void write( char c ) { cout << c; } inline void write( const char *data, int len ) { cout.write( data, len ); } %%{ machine RagelScan; word = [a-zA-Z_][a-zA-Z_0-9]*; integer = [0-9]+; hex = '0x' [0-9a-fA-F] [0-9a-fA-F]*; default = ^0; EOF = 0; # Handles comments in outside code and inline blocks. c_comment := ( default* :>> '*/' ) ${ escapeXML( fc ); } @{ fret; }; action emit { escapeXML( ts, te-ts ); } # # Inline action code # ilscan := |* "'" ( [^'\\] | /\\./ )* "'" => emit; '"' ( [^"\\] | /\\./ )* '"' => emit; '/*' { write( "/*" ); fcall c_comment; }; '//' [^\n]* '\n' => emit; '{' { write( '{' ); inline_depth += 1; }; '}' { write( '}' ); /* If dropping down to the last } then return * to ragel code. */ if ( --inline_depth == 0 ) { write( "\n" ); fgoto rlscan; } }; default => { escapeXML( *ts ); }; *|; # # Ragel Tokens # rlscan := |* '}%%' { if ( !single_line ) { write( "\n" ); fgoto main; } }; '\n' { if ( single_line ) { write( "\n" ); fgoto main; } }; # Word word { write( "" ); write( ts, te-ts ); write( "\n" ); }; # Decimal integer. integer { write( "" ); write( ts, te-ts ); write( "\n" ); }; # Hexidecimal integer. hex { write( "" ); write( ts, te-ts ); write( "\n" ); }; # Consume comments. '#' [^\n]* '\n'; # Single literal string. "'" ( [^'\\] | /\\./ )* "'" { write( "" ); escapeXML( ts, te-ts ); write( "\n" ); }; # Double literal string. '"' ( [^"\\] | /\\./ )* '"' { write( "" ); escapeXML( ts, te-ts ); write( "\n" ); }; # Or literal. '[' ( [^\]\\] | /\\./ )* ']' { write( "" ); escapeXML( ts, te-ts ); write( "\n" ); }; # Regex Literal. '/' ( [^/\\] | /\\./ ) * '/' { write( "" ); escapeXML( ts, te-ts ); write( "\n" ); }; # Open an inline block '{' { inline_depth = 1; write( "{" ); fgoto ilscan; }; punct { write( "" ); escapeXML( fc ); write( "\n" ); }; default; *|; # # Outside code. # main := |* "'" ( [^'\\] | /\\./ )* "'" => emit; '"' ( [^"\\] | /\\./ )* '"' => emit; '/*' { escapeXML( ts, te-ts ); fcall c_comment; }; '//' [^\n]* '\n' => emit; '%%{' { write( "
    \n" ); single_line = false; fgoto rlscan; }; '%%' { write( "
    \n" ); single_line = true; fgoto rlscan; }; default { escapeXML( *ts ); }; # EOF. EOF; *|; }%% %% write data nofinal; void test( const char *data ) { std::ios::sync_with_stdio(false); int cs, act; const char *ts, *te; int stack[1], top; bool single_line = false; int inline_depth = 0; %% write init; /* Read in a block. */ const char *p = data; const char *pe = data + strlen( data ); const char *eof = pe; %% write exec; if ( cs == RagelScan_error ) { /* Machine failed before finding a token. */ cerr << "PARSE ERROR" << endl; exit(1); } } #define BUFSIZE 2048 int main() { std::ios::sync_with_stdio(false); test("hi %%{ /'}%%'/ { /*{*/ {} } + '\\'' }%%there\n"); return 0; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ragel-cpp_snippet000066400000000000000000000000501250413007300272220ustar00rootroot00000000000000 %% write init; /* Read in a block. */ pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/regex.js000066400000000000000000000004131250413007300253360ustar00rootroot00000000000000// regex blah(/abc/); x = /abc/; x = /abc/.match; // math blah(1/2); //comment x = 1 / 2 / 3; x = 1/1/.1; // broken x=/1/; x=1/a/g; x=a/a/g; // real-world var x = 1/(1+Math.sqrt(sum)); // convert to number between 1-0 return Math.round((num / den) * 100)/100; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/reversi.lsp000066400000000000000000000267631250413007300261050ustar00rootroot00000000000000#!/usr/bin/env newlisp ;; @module reversi.lsp ;; @description a simple version of Reversi: you as white against newLISP as black ;; @version 0.1 alpha August 2007 ;; @author cormullion ;; ;; 2008-10-08 21:46:54 ;; updated for newLISP version 10. (changed nth-set to setf) ;; this now does not work with newLISP version 9! ;; ;; This is my first attempt at writing a simple application using newLISP-GS. ;; The game algorithms are basically by ;; Peter Norvig http://norvig.com/paip/othello.lisp ;; and all I've done is translate to newLISP and add the interface... ;; ;; To-Do: work out how to handle the end of the game properly... ;; To-Do: complete newlispdoc for the functions (constant 'empty 0) (constant 'black 1) (constant 'white 2) (constant 'outer 3) ; squares outside the 8x8 board (set '*board* '()) ; the master board is a 100 element list (set '*moves* '()) ; list of moves made ; these are the 8 different directions from a square on the board (set 'all-directions '(-11 -10 -9 -1 1 9 10 11)) ; return a list of all the playable squares (the 8 by 8 grid inside the 10by10 (define (all-squares) (local (result) (for (square 11 88) (if (<= 1 (mod square 10) 8) (push square result -1))) result)) ; make a board (define (make-board) (set '*board* (dup outer 100)) (dolist (s (all-squares)) (setf (*board* s) empty))) ; for testing and working at a terminal (define (print-board) (print { }) (for (c 1 8) (print c)) (set 'c 0) (for (i 0 99) (cond ((= (*board* i) 0) (print {.})) ((= (*board* i) 1) (print {b})) ((= (*board* i) 2) (print {w}))) (if (and (<= i 88) (= (mod (+ i 1) 10) 0)) ; newline (print "\n" (inc c)))) (println "\n")) ; the initial starting pattern (define (initial-board) (make-board) (setf (*board* 44) white) (setf (*board* 55) white) (setf (*board* 45) black) (setf (*board* 54) black)) (define (opponent player) (if (= player black) white black)) (define (player-name player) (if (= player white) "white" "black")) (define (valid-move? move) (and (integer? move) (<= 11 move 88) (<= 1 (mod move 10) 8))) (define (empty-square? square) (and (valid-move? square) (= (*board* square) empty))) ; test whether a move is legal. The square must be empty ; and it must flip at least one of the opponent's piece (define (legal-move? move player) (and (empty-square? move) (exists (fn (dir) (would-flip? move player dir)) all-directions))) ; would this move by player result in any flips in the given direction? ; if so, return the number of the 'opposite' (bracketing) piece's square (define (would-flip? move player dir) (let ((c (+ move dir))) (and (= (*board* c) (opponent player)) (find-bracketing-piece (+ c dir) player dir)))) (define (find-bracketing-piece square player dir) ; return the square of the bracketing piece, if any (cond ((= (*board* square) player) square) ((= (*board* square) (opponent player)) (find-bracketing-piece (+ square dir) player dir)) (true nil))) (define (make-flips move player dir) (let ((bracketer (would-flip? move player dir)) (c (+ move dir))) (if bracketer (do-until (= c bracketer) (setf (*board* c) player) (push c *flips* -1) (inc c dir))))) ; make the move on the master game board, not yet visually (define (make-move move player) (setf (*board* move) player) (push move *moves* -1) (set '*flips* '()) ; we're going to keep a record of the flips made (dolist (dir all-directions) (make-flips move player dir))) (define (next-to-play previous-player) (let ((opp (opponent previous-player))) (cond ((any-legal-move? opp) opp) ((any-legal-move? previous-player) (println (player-name opp) " has no moves") previous-player) (true nil)))) ; are there any legal moves (returns first) for this player? (define (any-legal-move? player) (exists (fn (move) (legal-move? move player)) (all-squares))) ; a list of all legal moves might be useful (define (legal-moves player) (let ((result '())) (dolist (move (all-squares)) (if (legal-move? move player) (push move result))) (unique result))) ; define any number of strategies that can be called on to calculate ; the next computer move. This is the only one I've done... - make ; any legal move at random! (define (random-strategy player) (seed (date-value)) (apply amb (legal-moves player))) ; get the next move using a particular strategy (define (get-move strategy player) (let ((move (apply strategy (list player)))) (cond ((and (valid-move? move) (legal-move? move player)) (make-move move player)) (true (println "no valid or legal move for " (player-name player) ) nil)) move)) ; that's about all the game algorithms for now ; now for the interface (if (= ostype "Win32") (load (string (env "PROGRAMFILES") "/newlisp/guiserver.lsp")) (load "/usr/share/newlisp/guiserver.lsp") ) (gs:init) (map set '(screen-width screen-height) (gs:get-screen)) (set 'board-width 540) ; center on screen (gs:frame 'Reversi (- (/ screen-width 2) (/ board-width 2)) 60 board-width 660 "Reversi") (gs:set-border-layout 'Reversi) (gs:canvas 'MyCanvas 'Reversi) (gs:set-background 'MyCanvas '(.8 .9 .7 .8)) (gs:mouse-released 'MyCanvas 'mouse-released-action true) (gs:panel 'Controls) (gs:button 'Start 'start-game "Start") (gs:panel 'Lower) (gs:label 'WhiteScore "") (gs:label 'BlackScore "") (gs:add-to 'Controls 'Start ) (gs:add-to 'Lower 'WhiteScore 'BlackScore) (gs:add-to 'Reversi 'MyCanvas "center" 'Controls "north" 'Lower "south") (gs:set-anti-aliasing true) (gs:set-visible 'Reversi true) ; size of board square, and radius/width of counter (set 'size 60 'width 30) ; initialize the master board (define (initial-board) (make-board) (setf (*board* 44) white) (setf (*board* 55) white) (setf (*board* 45) black) (setf (*board* 54) black) ) ; draw a graphical repesentation of the board (define (draw-board) (local (x y) (dolist (i (all-squares)) (map set '(x y) (square-to-xy i)) (gs:draw-rect (string x y) (- (* y size) width ) ; !!!!!! (- (* x size) width ) (* width 2) (* width 2) gs:white)))) (define (draw-first-four-pieces) (draw-piece 44 "white") (draw-piece 55 "white") (draw-piece 45 "black") (draw-piece 54 "black")) ; this next function can mark the legal moves available to a player (define (show-legal-moves player) (local (legal-move-list x y) (set 'legal-move-list (legal-moves player)) (dolist (m (all-squares)) (map set '(x y) (square-to-xy m)) (gs:draw-rect (string x y) (- (* y size) width ) ; !!!!!! (- (* x size) width ) (* width 2) (* width 2) (if (find m legal-move-list) gs:blue gs:white) ) ) ) ) ; convert the number of a square on the master board to coordinates (define (square-to-xy square) (list (/ square 10) (mod square 10))) ; draw one of the pieces (define (draw-piece square colour) (local (x y) (map set '(x y) (square-to-xy square)) (cond ((= colour "white") (gs:fill-circle (string x y) (* y size) ; !!!!!!! y first, cos y is x ;-) (* x size) width gs:white)) ((= colour "black") (gs:fill-circle (string x y) (* y size) (* x size) width gs:black)) ((= colour "empty") (gs:draw-rect (string x y) (- (* y size) width ) (- (* x size) width ) (* width 2) (* width 2) gs:white)) ))) ; animate the pieces flipping (define (flip-piece square player) ; flip by drawing thinner and fatter ellipses ; go from full disk in opposite colour to invisible ; then from invisible to full disk in true colour (local (x y colour) (map set '(x y) (square-to-xy square)) ; delete original piece (gs:delete-tag (string x y)) (set 'colour (if (= player 2) gs:black gs:white )) (for (i width 1 -3) (gs:fill-ellipse (string x y {flip} i) (* y size) ; y first :-) !!! (* x size) i width colour) (sleep 20) ; this might need adjusting... (gs:delete-tag (string x y {flip} i)) ) (set 'colour (if (= player 2) gs:white gs:black)) (for (i 1 width 3) (gs:fill-ellipse (string x y {flip} i) (* y size) ; :-) !!! (* x size) i width colour) (sleep 20) (gs:delete-tag (string x y {flip} i)) ) ; draw the piece again (gs:fill-circle (string x y) (* y size) (* x size) width colour) ) ) (define (do-move move player) (cond ; check if the move is good ... ((and (!= player nil) (valid-move? move) (legal-move? move player)) ; ... play it ; make move on board (make-move move player) ; and on screen (draw-piece move (player-name player)) (gs:update) ; do flipping stuff ; wait for a while (sleep 1000) ; then do flipping (dolist (f *flips*) (flip-piece f player)) (inc *move-number*) (draw-piece move (player-name player)) (gs:update) ; update scores (gs:set-text 'WhiteScore (string "White: " (first (count (list white) *board*)))) (gs:set-text 'BlackScore (string "Black: " (first (count (list black) *board*)))) ) ; or return nil (true nil))) ; the game is driven by the mouse clicks of the user ; in reply, the computer plays a black piece ; premature clicking is possible and possibly a bad thing... (define (mouse-released-action x y button modifiers tags) ; extract the tag of the clicked square (set 'move (int (string (first tags)) 0 10)) (if (do-move move player) (begin (set 'player (next-to-play player)) ; there is a training mode - legal squares are highlighted ; you can uncomment the next line... ; (show-legal-moves player) (gs:update) ; wait for black's reply (gs:set-cursor 'Reversi "wait") (gs:set-text 'Start "black's move - thinking...") ; give the illusion of Deep Thought... (sleep 2000) ; black's reply ; currently only the random strategy has been defined... (set 'strategy random-strategy) (set 'move (apply strategy (list player))) (do-move move player) (set 'player (next-to-play player)) ; (show-legal-moves player) ; to see black's moves (gs:set-text 'Start "your move") (gs:set-cursor 'Reversi "default") (gs:update)))) (define (start-game) (gs:set-text 'Start "Click a square to place a piece!") (gs:disable 'Start) (set 'player white)) (define (start) (gs:set-text 'Start "Start") (gs:enable 'Start) (set '*move-number* 1 '*flips* '()) (initial-board) (draw-board) (draw-first-four-pieces)) (start) (gs:listen)pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/robotframework_test.txt000066400000000000000000000017041250413007300305350ustar00rootroot00000000000000*** Settings *** Documentation Simple example demonstrating syntax highlighting. Library ExampleLibrary Test Setup Keyword argument argument with ${VARIABLE} *** Variables *** ${VARIABLE} Variable value @{LIST} List variable here *** Test Cases *** Keyword-driven example Initialize System Do Something Result Should Be 42 [Teardown] Cleanup System Data-driven example [Template] Keyword argument1 argument2 argument ${VARIABLE} @{LIST} Gherkin Given system is initialized When something is done Then result should be "42" | Pipes | | | [Documentation] | Also pipe separated format is supported. | | | Log | As this example demonstrates. | *** Keywords *** Result Should Be [Arguments] ${expected} ${actual} = Get Value Should be Equal ${actual} ${expected} Then result should be "${expected}" Result Should Be ${expected} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/rql-queries.rql000066400000000000000000000045671250413007300266750ustar00rootroot00000000000000Any N, N2 where N is Note, N2 is Note, N a_faire_par P1, P1 nom 'john', N2 a_faire_par P2, P2 nom 'jane' ; DISTINCT Any N, D, C, T, A ORDERBY D DESC LIMIT 40 where N is Note, N diem D, W is Workcase, W concerned_by N, N cost C, N text T, N author A, N diem <= today Bookmark B WHERE B owned_by G, G eid 5; Any X WHERE E eid 22762, NOT E is_in X, X modification_date D ORDERBY D DESC LIMIT 41; Any A, R, SUB ORDERBY R WHERE A is "Workcase", S is Division, S concerned_by A, A subject SUB, S eid 85, A ref R; Any D, T, L WHERE D is Document, A concerned_by D,A eid 14533, D title T, D location L; Any N,A,B,C,D ORDERBY A DESC WHERE N is Note, W concerned_by N, W eid 14533, N diem A,N author B,N text C,N cost D; Any X ORDERBY D DESC LIMIT 41 WHERE E eid 18134, NOT E concerned_by X, X modification_date D DISTINCT Any N, D, C, T, A ORDERBY D ASC LIMIT 40 WHERE N is Note, N diem D, P is Person, N to_be_contacted_by G, N cost C, N text T, N author A, G login "john"; INSERT Person X: X surname "Doe", X firstname "John"; Workcase W where W ref "ABCD12"; Workcase W where W ref LIKE "AB%"; Any X WHERE X X eid 53 Any X WHERE X Document X occurence_of F, F class C, C name 'Comics' X owned_by U, U login 'syt' X available true Person P WHERE P work_for P, S name 'Acme', P interested_by T, T name 'training' Note N WHERE N written_on D, D day> (today -10), N written_by P, P name 'joe' or P name 'jack' Person P WHERE (P interested_by T, T name 'training') or (P city 'Paris') Any N, P WHERE X is Person, X name N, X first_name P String N, P WHERE X is Person, X name N, X first_name P INSERT Person X: X name 'widget' INSERT Person X, Person Y: X name 'foo', Y name 'nice', X friend Y INSERT Person X: X name 'foo', X friend Y WHERE name 'nice' SET X name 'bar', X first_name 'original' where X is Person X name 'foo' SET X know Y WHERE X friend Y DELETE Person X WHERE X name 'foo' DELETE X friend Y WHERE X is Person, X name 'foo' Any X WHERE X name LIKE '%lt' Any X WHERE X name IN ( 'joe', 'jack', 'william', 'averell') Any X, V WHERE X concerns P, P eid 42, X corrected_in V? Any C, P WHERE C is Card, P? documented_by C Point P where P abs X, P ord Y, P value X+Y Document X where X class C, C name 'Cartoon', X owned_by U, U login 'joe', X available true (Any X WHERE X is Document) UNION (Any X WHERE X is File) Any A,B WHERE A creation_date B WITH A BEING (Any X WHERE X is Document) UNION (Any X WHERE X is File) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/ruby_func_def.rb000066400000000000000000000002641250413007300270310ustar00rootroot00000000000000class (get_foo("blub"))::Foo def (foo("bar") + bar("baz")).something argh, aaahaa 42 end end class get_the_fuck("out")::Of::My def parser_definition ruby! end end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/rust_example.rs000066400000000000000000000151431250413007300267520ustar00rootroot00000000000000// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // based on: // http://shootout.alioth.debian.org/u32/benchmark.php?test=nbody&lang=java extern mod std; use core::os; // Using sqrt from the standard library is way slower than using libc // directly even though std just calls libc, I guess it must be // because the the indirection through another dynamic linker // stub. Kind of shocking. Might be able to make it faster still with // an llvm intrinsic. #[nolink] extern mod libc { #[legacy_exports]; fn sqrt(n: float) -> float; } fn main() { let args = os::args(); let args = if os::getenv(~"RUST_BENCH").is_some() { ~[~"", ~"4000000"] } else if args.len() <= 1u { ~[~"", ~"100000"] } else { args }; let n = int::from_str(args[1]).get(); let mut bodies: ~[Body::props] = NBodySystem::make(); io::println(fmt!("%f", NBodySystem::energy(bodies))); let mut i = 0; while i < n { NBodySystem::advance(bodies, 0.01); i += 1; } io::println(fmt!("%f", NBodySystem::energy(bodies))); } mod NBodySystem { use Body; pub fn make() -> ~[Body::props] { let mut bodies: ~[Body::props] = ~[Body::sun(), Body::jupiter(), Body::saturn(), Body::uranus(), Body::neptune()]; let mut px = 0.0; let mut py = 0.0; let mut pz = 0.0; let mut i = 0; while i < 5 { px += bodies[i].vx * bodies[i].mass; py += bodies[i].vy * bodies[i].mass; pz += bodies[i].vz * bodies[i].mass; i += 1; } // side-effecting Body::offset_momentum(&mut bodies[0], px, py, pz); return bodies; } pub fn advance(bodies: &mut [Body::props], dt: float) { let mut i = 0; while i < 5 { let mut j = i + 1; while j < 5 { advance_one(&mut bodies[i], &mut bodies[j], dt); j += 1; } i += 1; } i = 0; while i < 5 { move_(&mut bodies[i], dt); i += 1; } } pub fn advance_one(bi: &mut Body::props, bj: &mut Body::props, dt: float) unsafe { let dx = bi.x - bj.x; let dy = bi.y - bj.y; let dz = bi.z - bj.z; let dSquared = dx * dx + dy * dy + dz * dz; let distance = ::libc::sqrt(dSquared); let mag = dt / (dSquared * distance); bi.vx -= dx * bj.mass * mag; bi.vy -= dy * bj.mass * mag; bi.vz -= dz * bj.mass * mag; bj.vx += dx * bi.mass * mag; bj.vy += dy * bi.mass * mag; bj.vz += dz * bi.mass * mag; } pub fn move_(b: &mut Body::props, dt: float) { b.x += dt * b.vx; b.y += dt * b.vy; b.z += dt * b.vz; } pub fn energy(bodies: &[Body::props]) -> float unsafe { let mut dx; let mut dy; let mut dz; let mut distance; let mut e = 0.0; let mut i = 0; while i < 5 { e += 0.5 * bodies[i].mass * (bodies[i].vx * bodies[i].vx + bodies[i].vy * bodies[i].vy + bodies[i].vz * bodies[i].vz); let mut j = i + 1; while j < 5 { dx = bodies[i].x - bodies[j].x; dy = bodies[i].y - bodies[j].y; dz = bodies[i].z - bodies[j].z; distance = ::libc::sqrt(dx * dx + dy * dy + dz * dz); e -= bodies[i].mass * bodies[j].mass / distance; j += 1; } i += 1; } return e; } } mod Body { use Body; pub const PI: float = 3.141592653589793; pub const SOLAR_MASS: float = 39.478417604357432; // was 4 * PI * PI originally pub const DAYS_PER_YEAR: float = 365.24; pub type props = {mut x: float, mut y: float, mut z: float, mut vx: float, mut vy: float, mut vz: float, mass: float}; pub fn jupiter() -> Body::props { return {mut x: 4.84143144246472090e+00, mut y: -1.16032004402742839e+00, mut z: -1.03622044471123109e-01, mut vx: 1.66007664274403694e-03 * DAYS_PER_YEAR, mut vy: 7.69901118419740425e-03 * DAYS_PER_YEAR, mut vz: -6.90460016972063023e-05 * DAYS_PER_YEAR, mass: 9.54791938424326609e-04 * SOLAR_MASS}; } pub fn saturn() -> Body::props { return {mut x: 8.34336671824457987e+00, mut y: 4.12479856412430479e+00, mut z: -4.03523417114321381e-01, mut vx: -2.76742510726862411e-03 * DAYS_PER_YEAR, mut vy: 4.99852801234917238e-03 * DAYS_PER_YEAR, mut vz: 2.30417297573763929e-05 * DAYS_PER_YEAR, mass: 2.85885980666130812e-04 * SOLAR_MASS}; } pub fn uranus() -> Body::props { return {mut x: 1.28943695621391310e+01, mut y: -1.51111514016986312e+01, mut z: -2.23307578892655734e-01, mut vx: 2.96460137564761618e-03 * DAYS_PER_YEAR, mut vy: 2.37847173959480950e-03 * DAYS_PER_YEAR, mut vz: -2.96589568540237556e-05 * DAYS_PER_YEAR, mass: 4.36624404335156298e-05 * SOLAR_MASS}; } pub fn neptune() -> Body::props { return {mut x: 1.53796971148509165e+01, mut y: -2.59193146099879641e+01, mut z: 1.79258772950371181e-01, mut vx: 2.68067772490389322e-03 * DAYS_PER_YEAR, mut vy: 1.62824170038242295e-03 * DAYS_PER_YEAR, mut vz: -9.51592254519715870e-05 * DAYS_PER_YEAR, mass: 5.15138902046611451e-05 * SOLAR_MASS}; } pub fn sun() -> Body::props { return {mut x: 0.0, mut y: 0.0, mut z: 0.0, mut vx: 0.0, mut vy: 0.0, mut vz: 0.0, mass: SOLAR_MASS}; } pub fn offset_momentum(props: &mut Body::props, px: float, py: float, pz: float) { props.vx = -px / SOLAR_MASS; props.vy = -py / SOLAR_MASS; props.vz = -pz / SOLAR_MASS; } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/scilab.sci000066400000000000000000000015731250413007300256330ustar00rootroot00000000000000// Scilab ( http://www.scilab.org/ ) // Copyright (C) INRIA - Serge STEER // function I=sub2ind(dims,varargin) //sub2ind is used to determine the equivalent single index //corresponding to a given set of subscript values. //I = sub2ind(dims,i1,i2,..) returns the linear index equivalent to the //row, column, ... subscripts in the arrays i1,i2,.. for an matrix of //size dims. //I = sub2ind(dims,Mi) returns the linear index //equivalent to the n subscripts in the columns of the matrix Mi for a matrix //of size dims. d=[1;cumprod(matrix(dims(1:$-1),-1,1))] for i=1:size(varargin) if varargin(i)==[] then I=[],return,end end if size(varargin)==1 then //subindices are the columns of the argument I=(varargin(1)-1)*d+1 else //subindices are given as separated arguments I=1 for i=1:size(varargin) I=I+(varargin(i)-1)*d(i) end end endfunction pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/scope.cirru000066400000000000000000000010101250413007300260370ustar00rootroot00000000000000 -- https://github.com/Cirru/cirru-gopher/blob/master/code/scope.cr set a (int 2) print (self) set c (child) under c under parent print a print $ get c a set c x (int 3) print $ get c x set just-print $ code print a print just-print eval (self) just-print eval just-print print (string "string with space") print (string "escapes \n \"\\") brackets ((((())))) "eval" $ string "eval" print (add $ (int 1) (int 2)) print $ unwrap $ map (a $ int 1) (b $ int 2) print a int 1 , b c int 2 , dpygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/session.dylan-console000066400000000000000000000002161250413007300300430ustar00rootroot00000000000000? 7 * 52; => 364 ? define variable *your-variable* = $foo; ? begin let yours = "apple"; let mine = yours; mine == yours; end; => #t pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/sibling.prolog000066400000000000000000000005541250413007300265470ustar00rootroot00000000000000/* Comments /* can nest */ still a comment */ :- module(maplist, maplist/3) assert(world:done). % asserts sibling(X, Y) :- parent_child(Z, X), parent_child(Z, Y). parent_child(X, Y) :- father_child(X, Y). parent_child(X, Y) :- mother_child(X, Y). mother_child(trude, sally). father_child(tom, sally). father_child(tom, erica). father_child(mike, tom). pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/simple.md000066400000000000000000000257621250413007300255170ustar00rootroot00000000000000module simple; // Importing stuff. { function loadMod(name, ns) { assert(name == "mod"); ns.x = "I'm x"; ns.foo = function foo() { writefln("foo"); }; ns.bar = function bar(x) { return x[0]; }; ns.baz = function baz() { writefln(x); }; foreach(k, v; ns) if(isFunction(v)) v.environment(ns); } setModuleLoader("mod", loadMod); import mod : foo, bar; foo(); writefln(bar([5])); mod.baz(); writefln(); } // Super calls. { class Base { function fork() { writefln("Base fork."); } } class Derived : Base { function fork() { writefln("Derived fork!"); super.fork(); } } local d = Derived(); d.fork(); writefln(); } // Coroutines and coroutine iteration. { local countDown = coroutine function countDown(x) { yield(); while(x > 0) { yield(x); x--; } }; foreach(v; countDown, 5) writefln(v); writefln(); local forEach = coroutine function forEach(t) { yield(); foreach(k, v; t) yield(k, v); }; foreach(_, k, v; forEach, {hi = 1, bye = 2}) writefln("key: ", k, ", value: ", v); writefln(); } // Testing tailcalls. { function recurse(x) { writefln("recurse: ", x); if(x == 0) return toString(x); else return recurse(x - 1); } writefln(recurse(5)); writefln(); class A { function f(x) { writefln("A.f: ", x); if(x == 0) return toString(x); else return this.f(x - 1); // call it as this.f to force a 'method' instruction to be generated } } local a = A(); writefln(a.f(5)); writefln(); } { // A function which lets us define properties for a class. // The varargs should be a bunch of tables, each with a 'name' field, and 'getter' and/or 'setter' fields. function mixinProperties(classType, vararg) { classType.mProps = { }; classType.opIndex = function opIndex(key) { local prop = mProps[key]; if(prop is null) throw format(classType, ".opIndex() - Property '%s' does not exist", key); local getter = prop.getter; if(getter is null) throw format(classType, ".opIndex() - Property '%s' has no getter", key); return getter(with this); }; classType.opIndexAssign = function opIndexAssign(key, value) { local prop = mProps[key]; if(prop is null) throw format(classType, ".opIndexAssign() - Property '%s' does not exist", key); local setter = prop.setter; if(setter is null) throw format(classType, ".opIndexAssign() - Property '%s' has no setter", key); setter(with this, value); }; foreach(i, prop; [vararg]) { if(!isTable(prop)) throw format("mixinProperties() - property ", i, " is not a table"); if(prop.name is null) throw format("mixinProperties() - property ", i, " has no name"); if(prop.setter is null && prop.getter is null) throw format("mixinProperties() - property '%s' has no getter or setter", prop.name); classType.mProps[prop.name] = prop; } } // Create a class to test out. class PropTest { mX = 0; mY = 0; mName = ""; function constructor(name) { mName = name; } function toString() { return format("name = '", mName, "' x = ", mX, " y = ", mY); } } // Mix in the properties. mixinProperties ( PropTest, { name = "x", function setter(value) { mX = value; } function getter() { return mX; } }, { name = "y", function setter(value) { mY = value; } function getter() { return mY; } }, { name = "name", function getter() { return mName; } } ); // Create an instance and try it out. local p = PropTest("hello"); writefln(p); p.x = 46; p.y = 123; p.x = p.x + p.y; writefln(p); // Try to access a nonexistent property. try p.name = "crap"; catch(e) { writefln("caught: ", e); writefln(getTraceback()); } writefln(); } // Some container classes. { class PQ { mData; mLength = 0; function constructor() { mData = array.new(15); } function insert(data) { resizeArray(); mData[mLength] = data; local index = mLength; local parentIndex = (index - 1) / 2; while(index > 0 && mData[parentIndex] > mData[index]) { local temp = mData[parentIndex]; mData[parentIndex] = mData[index]; mData[index] = temp; index = parentIndex; parentIndex = (index - 1) / 2; } mLength += 1; } function remove() { if(mLength == 0) throw "PQ.remove() - No items to remove"; local data = mData[0]; mLength -= 1; mData[0] = mData[mLength]; local index = 0; local left = 1; local right = 2; while(index < mLength) { local smaller; if(left >= mLength) { if(right >= mLength) break; else smaller = right; } else { if(right >= mLength) smaller = left; else { if(mData[left] < mData[right]) smaller = left; else smaller = right; } } if(mData[index] > mData[smaller]) { local temp = mData[index]; mData[index] = mData[smaller]; mData[smaller] = temp; index = smaller; left = (index * 2) + 1; right = left + 1; } else break; } return data; } function resizeArray() { if(mLength >= #mData) mData.length((#mData + 1) * 2 - 1); } function hasData() { return mLength != 0; } } class Stack { mHead = null; function push(data) { local t = { data = data, next = mHead }; mHead = t; } function pop() { if(mHead is null) throw "Stack.pop() - No items to pop"; local item = mHead; mHead = mHead.next; return item.data; } function hasData() { return mHead !is null; } } class Queue { mHead = null; mTail = null; function push(data) { local t = { data = data, next = null }; if(mTail is null) { mHead = t; mTail = t; } else { mTail.next = t; mTail = t; } } function pop() { if(mTail is null) throw "Queue.pop() - No items to pop"; local item = mHead; mHead = mHead.next; if(mHead is null) mTail = null; return item.data; } function hasData() { return mHead !is null; } } writefln("Priority queue (heap)"); local prioQ = PQ(); for(i : 0 .. 10) prioQ.insert(math.rand(0, 20)); while(prioQ.hasData()) writefln(prioQ.remove()); writefln(); writefln("Stack"); local stack = Stack(); for(i : 0 .. 5) stack.push(i + 1); while(stack.hasData()) writefln(stack.pop()); writefln(); writefln("Queue"); local queue = Queue(); for(i : 0 .. 5) queue.push(i + 1); while(queue.hasData()) writefln(queue.pop()); writefln(); } // opApply tests. { class Test { mData = [4, 5, 6]; function opApply(extra) { if(isString(extra) && extra == "reverse") { local function iterator_reverse(index) { index--; if(index < 0) return; return index, mData[index]; } return iterator_reverse, this, #mData; } else { local function iterator(index) { index++; if(index >= #mData) return; return index, mData[index]; } return iterator, this, -1; } } } local test = Test(); foreach(k, v; test) writefln("test[", k, "] = ", v); writefln(); foreach(k, v; test, "reverse") writefln("test[", k, "] = ", v); writefln(); test = { fork = 5, knife = 10, spoon = "hi" }; foreach(k, v; test) writefln("test[", k, "] = ", v); test = [5, 10, "hi"]; writefln(); foreach(k, v; test) writefln("test[", k, "] = ", v); writefln(); foreach(k, v; test, "reverse") writefln("test[", k, "] = ", v); writefln(); foreach(k, v; "hello") writefln("str[", k, "] = ", v); writefln(); foreach(k, v; "hello", "reverse") writefln("str[", k, "] = ", v); writefln(); } // Testing upvalues in for loops. { local arr = array.new(10); for(i : 0 .. 10) arr[i] = function() { return i; }; writefln("This should be the values 0 through 9:"); foreach(func; arr) writefln(func()); writefln(); } // Testing nested functions. { function outer() { local x = 3; function inner() { x++; writefln("inner x: ", x); } writefln("outer x: ", x); inner(); writefln("outer x: ", x); return inner; } local func = outer(); func(); writefln(); } // Testing Exceptions. { function thrower(x) { if(x >= 3) throw "Sorry, x is too big for me!"; } function tryCatch(iterations) { try { for(i : 0 .. iterations) { writefln("tryCatch: ", i); thrower(i); } } catch(e) { writefln("tryCatch caught: ", e); throw e; } finally writefln("tryCatch finally"); } try { tryCatch(2); tryCatch(5); } catch(e) writefln("caught: ", e); writefln(); } // Testing arrays. { local array = [7, 9, 2, 3, 6]; array.sort(); foreach(i, v; array) writefln("arr[", i, "] = ", v); array ~= ["foo", "far"]; writefln(); foreach(i, v; array) writefln("arr[", i, "] = ", v); writefln(); } // Testing vararg functions. { function vargs(vararg) { local args = [vararg]; writefln("num varargs: ", #args); foreach(i, v; args) writefln("args[", i, "] = ", v); } vargs(); writefln(); vargs(2, 3, 5, "foo", "bar"); writefln(); } // Testing switches. { foreach(v; ["hi", "bye", "foo"]) { switch(v) { case "hi": writefln("switched to hi"); break; case "bye": writefln("switched to bye"); break; default: writefln("switched to something else"); break; } } writefln(); foreach(v; [null, false, 1, 2.3, 'x', "hi"]) { switch(v) { case null: writefln("null"); break; case false: writefln("false"); break; case 1: writefln("1"); break; case 2.3: writefln("2.3"); break; case 'x': writefln("x"); break; case "hi": writefln("hi"); break; } } writefln(); class A { mValue; this(value) { mValue = value; } function opCmp(other) { assert(other as A); return mValue <=> other.mValue; } } local a1 = A(1); local a2 = A(2); local a3 = A(3); for(s : 1 .. 4) { local ss = A(s); switch(ss) { case a1: writefln(1); break; case a2: writefln(2); break; case a3: writefln(3); break; } } }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/smarty_example.html000066400000000000000000000215021250413007300276100ustar00rootroot00000000000000{php} include "some/php/file.php"; foreach ($rows as $row) { echo $row; } {/php} {* smarty comment *} {serendipity_hookPlugin hook="entries_header" addData="$entry_id"} {foreach from=$entries item="dategroup"} {foreachelse} {if not $plugin_clean_page} {$CONST.NO_ENTRIES_TO_PRINT} {/if} {/foreach} {if $footer_info} {/if} {serendipity_hookPlugin hook="entries_footer"} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/source.lgt000066400000000000000000000161341250413007300257050ustar00rootroot00000000000000 % this is a single-line comment /* this is a block comment */ :- encoding(some_encoding). :- op(Precedence, Associativity, Operator). :- object(prototype, implements(protocol), imports(category), extends(parent)). :- info([ version is 1.0, author is 'Paulo Moura', date is 2008/5/1, comment is 'Sample prototype for testing syntax coloring.']). :- threaded. :- synchronized. :- dynamic. :- initialization(some_goal(X, Y)). :- calls(some_other_protocol). :- uses(another_object). :- alias(set, member/2, set_member/2). :- alias(words, singular//0, peculiar//0). :- uses(list, [append/3, member/2]). :- uses(queues, [new/1::new_queue/1]). :- public(aaa/2). :- meta_predicate(aaa(::, *)). :- discontiguous(aaa/2). :- mode(aaa(+callable, ?integer), zero_or_one). :- info(position/2, [ comment is 'Predicate brief description.', arguments is ['Arg1'-'Arg1 description', 'Arg2'-'Arg2 description']]). :- protected(bbb/2). :- synchronized(bbb/2). :- mode(bbb(+integer, -float), one). :- info(bbb/2, [ comment is 'Predicate brief description.', argnames is ['Arg1', 'Arg2']]). :- private(ccc/2). :- dynamic(ccc/2). :- mode(ccc(@atom, ?atom), one_or_more). :- info(ccc/2, [ comment is 'Predicate brief description.', argnames is ['Arg1', 'Arg2']]). enumerating_entities(Object, Protocol, Category) :- current_category(Category), current_object(Object), current_protocol(Protocol). enumerating_properties :- category_property(Category, Property), object_property(Object, Property), protocol_property(Protocol, Property). creating_entities(Object, Protocol, Category) :- create_category(Category, Relations, Directives, Clauses), create_object(Object, Relations, Directives, Clauses), create_protocol(Protocol, Relations, Directives). abolishing_entities(Object, Protocol, Category) :- abolish_category(Category), abolish_object(Object), abolish_protocol(Protocol). entity_relations :- extends_object(Prototype, Parent, Scope), extends_protocol(Protocol1, Protocol2, Scope), extends_category(Category1, Category2, Scope), implements_protocol(Object, Protocol, Scope), imports_category(Object, Category, Scope), instantiates_class(Instance, Class, Scope), specializes_class(Class, Superclass, Scope), complements_object(Category, Object). event_handling :- abolish_events(Event, Object, Message, Sender, Monitor), current_event(Event, Object, Message, Sender, Monitor), define_events(Event, Object, Message, Sender, Monitor). multi_threading :- threaded(Goals), threaded_call(Goal), threaded_once(Goal), threaded_ignore(Goal), threaded_exit(Goal), threaded_peek(Goal), threaded_wait(Goal), threaded_notify(Notification). compiling_and_loading :- logtalk_compile(File, Options), logtalk_load(File, Options), logtalk_library_path(Library, Path). flags :- current_logtalk_flag(Flag, Value), set_logtalk_flag(Flag, Value). execution_context_methods :- parameter(N, Parameter), self(Self), sender(Sender), this(This). reflection_methods :- current_predicate(Predicate), predicate_property(Predicate, Property). database_methods :- abolish(Functor/Arity), asserta(Clause), assertz(Clause), clause(Head, Body), retract(Clause), retractall(Head). meta_call_methods :- call(Goal). all_solutions_methods :- bagof(Term, Goal, List), findall(Term, Goal, List), forall(Generate, Test), setof(Term, Goal, List). event_handler_methods :- before(Object, Message, Sender), after(Object, Message, Sender). dcg_rules_parsing_methods :- phrase(NonTerminal, Input, Rest). term_expansion_methods :- expand_term(Term, Expanded), term_expansion(Term, Expanded), goal_expansion(Goal, Expanded). message_sending :- Object::Message, ::Message, ^^Message. calling_external_code :- {goal1, goal2, goal3}. context_switching_calls :- Object< Then ; Else ). numbers :- X is 13, Y is 13.13, Z is 13.13e-23, C1 is 0'A, C2 is 0'', C3 is 0'", B is 0b1011101, O is 0o1234560, H is 0x1234567890abcDEF. functions :- A is atan(3.14) + sin(0.77) - cos(123.23), B is sign(-12) * abs(35/78), C is truncate(3.14) + round(-7.8) - ceiling(111.88), D is exp(3.8) - log(123.98) / sqrt(33) * 23 ** 4, E is rem(3, 2) + mod(5, 3) * 2 rem 2 // 5 mod 3, F is float_fractional_part(3.14) + float_integer_part(3.14), G is float(33) + floor(99.99). bitwise :- A is 16 >> 2, B is 16 << 2, C is 10 /\ 12, D is 10 \/ 12, E is \ 10. term_unification :- Term1 = Term2, Term1 \= Term2, unify_with_occurs_check(Term1, Term2). term_testing :- atom(Atom), atomic(Atomic), integer(Integer), float(Float), compound(Term), nonvar(Term), var(Term), number(Number). term_comparison :- Term1 == Term2, Term1 \== Term2, Term1 @< Term2, Term1 @=< Term2, Term1 @>= Term2, Term1 @> Term2. term_creation_and_decomposition :- functor(Term, Functor, Arity), arg(N, Term, Arg), Term =.. [Functor| Args], copy_term(Term, Copy). arithemtic_evaluation :- X is Expression. arithemtic_comparison :- Exp1 =:= Exp2, Exp1 =\= Exp2, Exp1 < Exp2, Exp1 =< Exp2, Exp1 > Exp2, Exp1 >= Exp2. stream_selection_and_control :- current_input(Stream), current_output(Stream), set_input(Stream), set_output(Stream), open(Source, Mode, Stream, Options), close(Stream), flush_output(Stream), stream_property(Stream, Property), at_end_of_stream(Stream), set_stream_position(Stream, Position), flush_output, at_end_of_stream. character_input_output :- get_char(Char), get_code(Code), peek_char(Char), peek_code(Code), put_char(Char), put_code(Code), nl(Stream), nl. byte_input_output :- get_byte(Byte), peek_byte(Byte), put_byte(Byte). term_input_output :- read(Term), read_term(Term), write(Term), write(Term), write_canonical(Term), write_term(Stream, Term, Options), current_op(Precedence, Associativity, Operator), op(Precedence, Associativity, Operator), current_char_conversion(InChar, OutChar), char_conversion(InChar, OutChar). logic_and_control :- \+ Goal, once(Goal), repeat, !. atomic_term_processing :- atom_length(Atom, Length), atom_chars(Atom, Chars), atom_codes(Atom, Codes), atom_concat(Atom1, Atom2, Atom), sub_atom(Atom, Before, Length, After, SubAtom), char_code(Char, Code), number_chars(Number, Chars), number_codes(Number, Codes). implementation_defined_hooks :- current_prolog_flag(Flag, Value), set_prolog_flag(Flag, Value), halt(ExitCode), halt. number(C) --> "+", number(C). number(C) --> "-", number(X), {C is -X}. number(X) --> [C], {0'0 =< C, C =< 0'9, X is C - 0'0}. :- end_object. :- object(class, implements(protocol), imports(category), instantiates(metaclass), specializes(superclass)). :- end_object. :- object(parametric(_Par1, _Par2), implements(protocol), imports(category), extends(parent(_Par))). :- end_object. :- category(category, implements(protocol), extends(other_category)). :- end_category. :- protocol(extended, extends(minimal)). :- end_protocol. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/sources.list000066400000000000000000000056161250413007300262600ustar00rootroot00000000000000## CD ROM deb cdrom:[Xubuntu 6.06.1 _Dapper Drake_ - Release i386 (20060807)]/ dapper main restricted deb http://archive.ubuntu.com/ubuntu/ dapper main restricted deb-src http://archive.ubuntu.com/ubuntu/ dapper main restricted deb http://foo.com/$(ARCH)/ main foo ## Major bug fix updates produced after the final release of the ## distribution. deb http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted deb-src http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted ## Uncomment the following two lines to add software from the 'universe' ## repository. ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## universe WILL NOT receive any review or updates from the Ubuntu security ## team. deb http://archive.ubuntu.com/ubuntu/ dapper universe multiverse deb-src http://archive.ubuntu.com/ubuntu/ dapper universe multiverse ## Uncomment the following two lines to add software from the 'backports' ## repository. ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb http://archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb-src http://archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu dapper-security main restricted deb-src http://security.ubuntu.com/ubuntu dapper-security main restricted deb http://security.ubuntu.com/ubuntu dapper-security universe multiverse deb-src http://security.ubuntu.com/ubuntu dapper-security universe multiverse ## dapper-commercial by canonical ## currently has realplay (realplayer 10) and opera (opera 9) deb http://archive.canonical.com/ubuntu dapper-commercial main ## Bleeding edge wine repository for Dapper ## only uncomment it if you need it ## deb http://wine.budgetdedicated.com/apt dapper main ## deb-src http://wine.budgetdedicated.com/apt dapper main ## skype ## only uncomment it if you need it ## deb http://download.skype.com/linux/repos/debian/ stable non-free deb http://de.archive.ubuntu.com/ubuntu/ edgy main restricted multiverse universe deb http://de.archive.ubuntu.com/ubuntu/ edgy-updates main restricted multiverse universe deb http://de.archive.ubuntu.com/ubuntu/ edgy-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu edgy-security main restricted universe multiverse deb http://wine.budgetdedicated.com/apt edgy main deb http://archive.czessi.net/ubuntu edgy main restricted universe multiverse i18n-de pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/sparql.rq000066400000000000000000000015421250413007300255400ustar00rootroot00000000000000# This is a test SPARQL query PREFIX foaf: PREFIX ex: PREFIX xsd: PREFIX dcterms: SELECT ?person (COUNT(?nick) AS ?nickCount) { ?person foaf:nick ?nick ; foaf:lastName "Smith" ; foaf:age "21"^^xsd:int ; ex:title 'Mr' ; # single-quoted string ex:height 1.80 ; # float ex:distanceToSun +1.4e8 ; # float with exponent ex:ownsACat true ; dcterms:description "Someone with a cat called \"cat\"."@en . OPTIONAL { ?person foaf:isPrimaryTopicOf ?page } OPTIONAL { ?person foaf:name ?name { ?person foaf:depiction ?img } UNION { ?person foaf:firstName ?firstN } } FILTER ( bound(?page) || bound(?img) || bound(?firstN) ) } GROUP BY ?person ORDER BY ?img pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/sphere.pov000066400000000000000000000003341250413007300257040ustar00rootroot00000000000000#include "colors.inc" background { color Cyan } camera { location <0, 2, -3> look_at <0, 1, 2> } sphere { <0, 1, 2>, 2 texture { pigment { color Yellow } } } light_source { <2, 4, -3> color White} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/sqlite3.sqlite3-console000066400000000000000000000011301250413007300302150ustar00rootroot00000000000000SQLite version 3.4.2 Enter ".help" for instructions sqlite> .schema CREATE TABLE paste (paste_id integer, code text, parsed_code text, pub_date varchar(24), language varchar(64), parent_id integer, url varchar(128)); CREATE TABLE vars (key varchar(24), value varchar(128)); sqlite> a ' ...> ' ...> ; SQL error: near "a": syntax error sqlite> %; SQL error: near "%": syntax error sqlite> select count(language), language from paste group by language order ...> by count(language) desc; 144|python 76|text 22|pycon 9|ruby 7|c 7|js 6|html+django 4|html 4|tex 2|html+php 1|cpp 1|scheme sqlite> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/squid.conf000066400000000000000000000016671250413007300256760ustar00rootroot00000000000000# Some multiline comments acl manager proto cache_object acl localhost src 127.0.0.1/32 ::1 acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1 acl SSL_ports port 443 acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 # https acl Safe_ports port 70 # gopher acl Safe_ports port 210 # wais acl Safe_ports port 1025-65535 # unregistered ports acl Safe_ports port 280 # http-mgmt acl Safe_ports port 488 # gss-http acl Safe_ports port 591 # filemaker acl Safe_ports port 777 # multiling http acl CONNECT method CONNECT http_access allow manager localhost http_access deny manager http_access deny !Safe_ports http_access deny CONNECT !SSL_ports http_access allow localhost http_access deny all http_port 3128 hierarchy_stoplist cgi-bin ? coredump_dir /var/spool/squid3 refresh_pattern ^ftp: 1440 20% 10080 refresh_pattern ^gopher: 1440 0% 1440 refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 refresh_pattern . 0 20% 4320 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/string.jl000066400000000000000000000660471250413007300255420ustar00rootroot00000000000000## core string functions ## length(s::String) = error("you must implement length(",typeof(s),")") next(s::String, i::Int) = error("you must implement next(",typeof(s),",Int)") next(s::DirectIndexString, i::Int) = (s[i],i+1) next(s::String, i::Integer) = next(s,int(i)) ## generic supplied functions ## start(s::String) = 1 done(s::String,i) = (i > length(s)) isempty(s::String) = done(s,start(s)) ref(s::String, i::Int) = next(s,i)[1] ref(s::String, i::Integer) = s[int(i)] ref(s::String, x::Real) = s[iround(x)] ref{T<:Integer}(s::String, r::Range1{T}) = s[int(first(r)):int(last(r))] symbol(s::String) = symbol(cstring(s)) string(s::String) = s print(s::String) = for c=s; print(c); end print(x...) = for i=x; print(i); end println(args...) = print(args..., '\n') show(s::String) = print_quoted(s) (*)(s::String...) = strcat(s...) (^)(s::String, r::Integer) = repeat(s,r) size(s::String) = (length(s),) size(s::String, d::Integer) = d==1 ? length(s) : error("in size: dimension ",d," out of range") strlen(s::DirectIndexString) = length(s) function strlen(s::String) i = start(s) if done(s,i) return 0 end n = 1 while true c, j = next(s,i) if done(s,j) return n end n += 1 i = j end end isvalid(s::DirectIndexString, i::Integer) = (start(s) <= i <= length(s)) function isvalid(s::String, i::Integer) try next(s,i) true catch false end end prevind(s::DirectIndexString, i::Integer) = i-1 thisind(s::DirectIndexString, i::Integer) = i nextind(s::DirectIndexString, i::Integer) = i+1 prevind(s::String, i::Integer) = thisind(s,thisind(s,i)-1) function thisind(s::String, i::Integer) for j = i:-1:1 if isvalid(s,j) return j end end return 0 # out of range end function nextind(s::String, i::Integer) for j = i+1:length(s) if isvalid(s,j) return j end end length(s)+1 # out of range end ind2chr(s::DirectIndexString, i::Integer) = i chr2ind(s::DirectIndexString, i::Integer) = i function ind2chr(s::String, i::Integer) s[i] # throws error if invalid j = 1 k = start(s) while true c, l = next(s,k) if i <= k return j end j += 1 k = l end end function chr2ind(s::String, i::Integer) if i < 1 return i end j = 1 k = start(s) while true c, l = next(s,k) if i == j return k end j += 1 k = l end end function strchr(s::String, c::Char, i::Integer) i = nextind(s,i) while !done(s,i) d, j = next(s,i) if c == d return i end i = j end return 0 end strchr(s::String, c::Char) = strchr(s, c, start(s)) contains(s::String, c::Char) = (strchr(s,c)!=0) function chars(s::String) cx = Array(Char,strlen(s)) i = 0 for c in s cx[i += 1] = c end return cx end function cmp(a::String, b::String) i = start(a) j = start(b) while !done(a,i) && !done(b,i) c, i = next(a,i) d, j = next(b,j) if c != d return c < d ? -1 : +1 end end done(a,i) && !done(b,j) ? -1 : !done(a,i) && done(b,j) ? +1 : 0 end isequal(a::String, b::String) = cmp(a,b) == 0 isless(a::String, b::String) = cmp(a,b) < 0 # faster comparisons for byte strings cmp(a::ByteString, b::ByteString) = lexcmp(a.data, b.data) isequal(a::ByteString, b::ByteString) = length(a)==length(b) && cmp(a,b)==0 ## character column width function ## charwidth(c::Char) = max(0,int(ccall(:wcwidth, Int32, (Char,), c))) strwidth(s::String) = (w=0; for c in s; w += charwidth(c); end; w) strwidth(s::ByteString) = ccall(:u8_strwidth, Int, (Ptr{Uint8},), s.data) # TODO: implement and use u8_strnwidth that takes a length argument ## generic string uses only length and next ## type GenericString <: String string::String end length(s::GenericString) = length(s.string) next(s::GenericString, i::Int) = next(s.string, i) ## plain old character arrays ## type CharString <: String chars::Array{Char,1} CharString(a::Array{Char,1}) = new(a) CharString(c::Char...) = new([ c[i] | i=1:length(c) ]) end CharString(x...) = CharString(map(char,x)...) next(s::CharString, i::Int) = (s.chars[i], i+1) length(s::CharString) = length(s.chars) strlen(s::CharString) = length(s) string(c::Char) = CharString(c) string(c::Char, x::Char...) = CharString(c, x...) ## substrings reference original strings ## type SubString <: String string::String offset::Int length::Int SubString(s::String, i::Int, j::Int) = new(s, i-1, j-i+1) SubString(s::SubString, i::Int, j::Int) = new(s.string, i-1+s.offset, j-i+1) end SubString(s::String, i::Integer, j::Integer) = SubString(s, int(i), int(j)) function next(s::SubString, i::Int) if i < 1 || i > s.length error("string index out of bounds") end c, i = next(s.string, i+s.offset) c, i-s.offset end length(s::SubString) = s.length # TODO: strlen(s::SubString) = ?? # default implementation will work but it's slow # can this be delegated efficiently somehow? # that may require additional string interfaces function ref(s::String, r::Range1{Int}) if first(r) < 1 || length(s) < last(r) error("in substring slice: index out of range") end SubString(s, first(r), last(r)) end ## efficient representation of repeated strings ## type RepString <: String string::String repeat::Integer end length(s::RepString) = length(s.string)*s.repeat strlen(s::RepString) = strlen(s.string)*s.repeat function next(s::RepString, i::Int) if i < 1 || i > length(s) error("string index out of bounds") end j = mod1(i,length(s.string)) c, k = next(s.string, j) c, k-j+i end function repeat(s::String, r::Integer) r < 0 ? error("can't repeat a string ",r," times") : r == 0 ? "" : r == 1 ? s : RepString(s,r) end ## reversed strings without data movement ## type RevString <: String string::String end length(s::RevString) = length(s.string) strlen(s::RevString) = strlen(s.string) start(s::RevString) = (n=length(s); n-thisind(s.string,n)+1) function next(s::RevString, i::Int) n = length(s); j = n-i+1 (s.string[j], n-thisind(s.string,j-1)+1) end reverse(s::String) = RevString(s) reverse(s::RevString) = s.string ## ropes for efficient concatenation, etc. ## # Idea: instead of this standard binary tree structure, # how about we keep an array of substrings, with an # offset array. We can do binary search on the offset # array so we get O(log(n)) indexing time still, but we # can compute the offsets lazily and avoid all the # futzing around while the string is being constructed. type RopeString <: String head::String tail::String depth::Int32 length::Int RopeString(h::RopeString, t::RopeString) = depth(h.tail) + depth(t) < depth(h.head) ? RopeString(h.head, RopeString(h.tail, t)) : new(h, t, max(h.depth,t.depth)+1, length(h)+length(t)) RopeString(h::RopeString, t::String) = depth(h.tail) < depth(h.head) ? RopeString(h.head, RopeString(h.tail, t)) : new(h, t, h.depth+1, length(h)+length(t)) RopeString(h::String, t::RopeString) = depth(t.head) < depth(t.tail) ? RopeString(RopeString(h, t.head), t.tail) : new(h, t, t.depth+1, length(h)+length(t)) RopeString(h::String, t::String) = new(h, t, 1, length(h)+length(t)) end depth(s::String) = 0 depth(s::RopeString) = s.depth function next(s::RopeString, i::Int) if i <= length(s.head) return next(s.head, i) else c, j = next(s.tail, i-length(s.head)) return c, j+length(s.head) end end length(s::RopeString) = s.length strlen(s::RopeString) = strlen(s.head) + strlen(s.tail) strcat() = "" strcat(s::String) = s strcat(x...) = strcat(map(string,x)...) strcat(s::String, t::String...) = (t = strcat(t...); isempty(s) ? t : isempty(t) ? s : RopeString(s, t)) print(s::RopeString) = print(s.head, s.tail) ## transformed strings ## type TransformedString <: String transform::Function string::String end length(s::TransformedString) = length(s.string) strlen(s::TransformedString) = strlen(s.string) function next(s::TransformedString, i::Int) c, j = next(s.string,i) c = s.transform(c, i) return c, j end ## uppercase and lowercase transformations ## uppercase(c::Char) = ccall(:towupper, Char, (Char,), c) lowercase(c::Char) = ccall(:towlower, Char, (Char,), c) uppercase(s::String) = TransformedString((c,i)->uppercase(c), s) lowercase(s::String) = TransformedString((c,i)->lowercase(c), s) ucfirst(s::String) = TransformedString((c,i)->i==1 ? uppercase(c) : c, s) lcfirst(s::String) = TransformedString((c,i)->i==1 ? lowercase(c) : c, s) const uc = uppercase const lc = lowercase ## string map ## function map(f::Function, s::String) out = memio(length(s)) for c in s write(out, f(c)::Char) end takebuf_string(out) end ## conversion of general objects to strings ## string(x) = print_to_string(show, x) cstring(x...) = print_to_string(print, x...) function cstring(p::Ptr{Uint8}) p == C_NULL ? error("cannot convert NULL to string") : ccall(:jl_cstr_to_string, Any, (Ptr{Uint8},), p)::ByteString end ## string promotion rules ## promote_rule(::Type{UTF8String} , ::Type{ASCIIString}) = UTF8String promote_rule(::Type{UTF8String} , ::Type{CharString} ) = UTF8String promote_rule(::Type{ASCIIString}, ::Type{CharString} ) = UTF8String ## printing literal quoted string data ## # TODO: this is really the inverse of print_unbackslashed function print_quoted_literal(s::String) print('"') for c = s; c == '"' ? print("\\\"") : print(c); end print('"') end ## string escaping & unescaping ## escape_nul(s::String, i::Int) = !done(s,i) && '0' <= next(s,i)[1] <= '7' ? L"\x00" : L"\0" is_hex_digit(c::Char) = '0'<=c<='9' || 'a'<=c<='f' || 'A'<=c<='F' need_full_hex(s::String, i::Int) = !done(s,i) && is_hex_digit(next(s,i)[1]) function print_escaped(s::String, esc::String) i = start(s) while !done(s,i) c, j = next(s,i) c == '\0' ? print(escape_nul(s,j)) : c == '\e' ? print(L"\e") : c == '\\' ? print("\\\\") : contains(esc,c) ? print('\\', c) : iswprint(c) ? print(c) : 7 <= c <= 13 ? print('\\', "abtnvfr"[c-6]) : c <= '\x7f' ? print(L"\x", hex(c, 2)) : c <= '\uffff' ? print(L"\u", hex(c, need_full_hex(s,j) ? 4 : 2)) : print(L"\U", hex(c, need_full_hex(s,j) ? 8 : 4)) i = j end end escape_string(s::String) = print_to_string(length(s), print_escaped, s, "\"") print_quoted(s::String) = (print('"'); print_escaped(s, "\"\$"); print('"')) #" # work around syntax highlighting problem quote_string(s::String) = print_to_string(length(s)+2, print_quoted, s) # bare minimum unescaping function unescapes only given characters function print_unescaped_chars(s::String, esc::String) if !contains(esc,'\\') esc = strcat("\\", esc) end i = start(s) while !done(s,i) c, i = next(s,i) if c == '\\' && !done(s,i) && contains(esc,s[i]) c, i = next(s,i) end print(c) end end unescape_chars(s::String, esc::String) = print_to_string(length(s), print_unescaped_chars, s, esc) # general unescaping of traditional C and Unicode escape sequences function print_unescaped(s::String) i = start(s) while !done(s,i) c, i = next(s,i) if !done(s,i) && c == '\\' c, i = next(s,i) if c == 'x' || c == 'u' || c == 'U' n = k = 0 m = c == 'x' ? 2 : c == 'u' ? 4 : 8 while (k+=1) <= m && !done(s,i) c, j = next(s,i) n = '0' <= c <= '9' ? n<<4 + c-'0' : 'a' <= c <= 'f' ? n<<4 + c-'a'+10 : 'A' <= c <= 'F' ? n<<4 + c-'A'+10 : break i = j end if k == 1 error("\\x used with no following hex digits") end if m == 2 # \x escape sequence write(uint8(n)) else print(char(n)) end elseif '0' <= c <= '7' k = 1 n = c-'0' while (k+=1) <= 3 && !done(s,i) c, j = next(s,i) n = '0' <= c <= '7' ? n<<3 + c-'0' : break i = j end if n > 255 error("octal escape sequence out of range") end write(uint8(n)) else print(c == 'a' ? '\a' : c == 'b' ? '\b' : c == 't' ? '\t' : c == 'n' ? '\n' : c == 'v' ? '\v' : c == 'f' ? '\f' : c == 'r' ? '\r' : c == 'e' ? '\e' : c) end else print(c) end end end unescape_string(s::String) = print_to_string(length(s), print_unescaped, s) ## checking UTF-8 & ACSII validity ## byte_string_classify(s::ByteString) = ccall(:u8_isvalid, Int32, (Ptr{Uint8}, Int), s.data, length(s)) # 0: neither valid ASCII nor UTF-8 # 1: valid ASCII # 2: valid UTF-8 is_valid_ascii(s::ByteString) = byte_string_classify(s) == 1 is_valid_utf8 (s::ByteString) = byte_string_classify(s) != 0 check_ascii(s::ByteString) = is_valid_ascii(s) ? s : error("invalid ASCII sequence") check_utf8 (s::ByteString) = is_valid_utf8(s) ? s : error("invalid UTF-8 sequence") ## string interpolation parsing ## function _jl_interp_parse(s::String, unescape::Function, printer::Function) sx = {} i = j = start(s) while !done(s,j) c, k = next(s,j) if c == '$' if !isempty(s[i:j-1]) push(sx, unescape(s[i:j-1])) end ex, j = parseatom(s,k) push(sx, ex) i = j elseif c == '\\' && !done(s,k) if s[k] == '$' if !isempty(s[i:j-1]) push(sx, unescape(s[i:j-1])) end i = k end c, j = next(s,k) else j = k end end if !isempty(s[i:]) push(sx, unescape(s[i:j-1])) end length(sx) == 1 && isa(sx[1],ByteString) ? sx[1] : expr(:call, :print_to_string, printer, sx...) end _jl_interp_parse(s::String, u::Function) = _jl_interp_parse(s, u, print) _jl_interp_parse(s::String) = _jl_interp_parse(s, x->check_utf8(unescape_string(x))) function _jl_interp_parse_bytes(s::String) writer(x...) = for w=x; write(w); end _jl_interp_parse(s, unescape_string, writer) end ## core string macros ## macro str(s); _jl_interp_parse(s); end macro S_str(s); _jl_interp_parse(s); end macro I_str(s); _jl_interp_parse(s, x->unescape_chars(x,"\"")); end macro E_str(s); check_utf8(unescape_string(s)); end macro B_str(s); _jl_interp_parse_bytes(s); end macro b_str(s); ex = _jl_interp_parse_bytes(s); :(($ex).data); end ## shell-like command parsing ## function _jl_shell_parse(s::String, interp::Bool) in_single_quotes = false in_double_quotes = false args = {} arg = {} i = start(s) j = i function update_arg(x) if !isa(x,String) || !isempty(x) push(arg, x) end end function append_arg() if isempty(arg); arg = {"",}; end push(args, arg) arg = {} end while !done(s,j) c, k = next(s,j) if !in_single_quotes && !in_double_quotes && iswspace(c) update_arg(s[i:j-1]) append_arg() j = k while !done(s,j) c, k = next(s,j) if !iswspace(c) i = j break end j = k end elseif interp && !in_single_quotes && c == '$' update_arg(s[i:j-1]); i = k; j = k if done(s,k) error("\$ right before end of command") end if iswspace(s[k]) error("space not allowed right after \$") end ex, j = parseatom(s,j) update_arg(ex); i = j else if !in_double_quotes && c == '\'' in_single_quotes = !in_single_quotes update_arg(s[i:j-1]); i = k elseif !in_single_quotes && c == '"' in_double_quotes = !in_double_quotes update_arg(s[i:j-1]); i = k elseif c == '\\' if in_double_quotes if done(s,k) error("unterminated double quote") end if s[k] == '"' || s[k] == '$' update_arg(s[i:j-1]); i = k c, k = next(s,k) end elseif !in_single_quotes if done(s,k) error("dangling backslash") end update_arg(s[i:j-1]); i = k c, k = next(s,k) end end j = k end end if in_single_quotes; error("unterminated single quote"); end if in_double_quotes; error("unterminated double quote"); end update_arg(s[i:]) append_arg() if !interp return args end # construct an expression exprs = {} for arg in args push(exprs, expr(:tuple, arg)) end expr(:tuple,exprs) end _jl_shell_parse(s::String) = _jl_shell_parse(s,true) function shell_split(s::String) parsed = _jl_shell_parse(s,false) args = String[] for arg in parsed push(args, strcat(arg...)) end args end function print_shell_word(word::String) if isempty(word) print("''") end has_single = false has_special = false for c in word if iswspace(c) || c=='\\' || c=='\'' || c=='"' || c=='$' has_special = true if c == '\'' has_single = true end end end if !has_special print(word) elseif !has_single print('\'', word, '\'') else print('"') for c in word if c == '"' || c == '$' print('\\') end print(c) end print('"') end end function print_shell_escaped(cmd::String, args::String...) print_shell_word(cmd) for arg in args print(' ') print_shell_word(arg) end end shell_escape(cmd::String, args::String...) = print_to_string(print_shell_escaped, cmd, args...) ## interface to parser ## function parse(s::String, pos, greedy) # returns (expr, end_pos). expr is () in case of parse error. ex, pos = ccall(:jl_parse_string, Any, (Ptr{Uint8}, Int32, Int32), cstring(s), pos-1, greedy ? 1:0) if isa(ex,Expr) && is(ex.head,:error) throw(ParseError(ex.args[1])) end if ex == (); throw(ParseError("end of input")); end ex, pos+1 # C is zero-based, Julia is 1-based end parse(s::String) = parse(s, 1, true) parse(s::String, pos) = parse(s, pos, true) parseatom(s::String) = parse(s, 1, false) parseatom(s::String, pos) = parse(s, pos, false) ## miscellaneous string functions ## function lpad(s::String, n::Integer, p::String) m = n - strlen(s) if m <= 0; return s; end l = strlen(p) if l==1 return p^m * s end q = div(m,l) r = m - q*l cstring(p^q*p[1:chr2ind(p,r)]*s) end function rpad(s::String, n::Integer, p::String) m = n - strlen(s) if m <= 0; return s; end l = strlen(p) if l==1 return s * p^m end q = div(m,l) r = m - q*l cstring(s*p^q*p[1:chr2ind(p,r)]) end lpad(s, n::Integer, p) = lpad(string(s), n, string(p)) rpad(s, n::Integer, p) = rpad(string(s), n, string(p)) lpad(s, n::Integer) = lpad(string(s), n, " ") rpad(s, n::Integer) = rpad(string(s), n, " ") function split(s::String, delims, include_empty::Bool) i = 1 strs = String[] len = length(s) while true tokstart = tokend = i while !done(s,i) (c,i) = next(s,i) if contains(delims, c) break end tokend = i end tok = s[tokstart:(tokend-1)] if include_empty || !isempty(tok) push(strs, tok) end if !((i <= len) || (i==len+1 && tokend!=i)) break end end strs end split(s::String) = split(s, (' ','\t','\n','\v','\f','\r'), false) split(s::String, x) = split(s, x, true) split(s::String, x::Char, incl::Bool) = split(s, (x,), incl) function print_joined(strings, delim, last) i = start(strings) if done(strings,i) return end str, i = next(strings,i) print(str) while !done(strings,i) str, i = next(strings,i) print(done(strings,i) ? last : delim) print(str) end end function print_joined(strings, delim) i = start(strings) while !done(strings,i) str, i = next(strings,i) print(str) if !done(strings,i) print(delim) end end end print_joined(strings) = print_joined(strings, "") join(args...) = print_to_string(print_joined, args...) chop(s::String) = s[1:thisind(s,length(s))-1] chomp(s::String) = (i=thisind(s,length(s)); s[i]=='\n' ? s[1:i-1] : s) chomp(s::ByteString) = s.data[end]==0x0a ? s[1:end-1] : s function lstrip(s::String) i = start(s) while !done(s,i) c, j = next(s,i) if !iswspace(c) return s[i:end] end i = j end "" end function rstrip(s::String) r = reverse(s) i = start(r) while !done(r,i) c, j = next(r,i) if !iswspace(c) return s[1:end-i+1] end i = j end "" end strip(s::String) = lstrip(rstrip(s)) ## string to integer functions ## function parse_int{T<:Integer}(::Type{T}, s::String, base::Integer) if !(2 <= base <= 36); error("invalid base: ",base); end i = start(s) if done(s,i) error("premature end of integer (in ",show_to_string(s),")") end c,i = next(s,i) sgn = one(T) if T <: Signed && c == '-' sgn = -sgn if done(s,i) error("premature end of integer (in ",show_to_string(s),")") end c,i = next(s,i) end base = convert(T,base) n::T = 0 while true d = '0' <= c <= '9' ? c-'0' : 'A' <= c <= 'Z' ? c-'A'+10 : 'a' <= c <= 'z' ? c-'a'+10 : typemax(Int) if d >= base error(show_to_string(c)," is not a valid digit (in ",show_to_string(s),")") end # TODO: overflow detection? n = n*base + d if done(s,i) break end c,i = next(s,i) end return flipsign(n,sgn) end parse_int(s::String, base::Integer) = parse_int(Int,s,base) parse_int(T::Type, s::String) = parse_int(T,s,10) parse_int(s::String) = parse_int(Int,s,10) parse_bin(T::Type, s::String) = parse_int(T,s,2) parse_oct(T::Type, s::String) = parse_int(T,s,8) parse_hex(T::Type, s::String) = parse_int(T,s,16) parse_bin(s::String) = parse_int(Int,s,2) parse_oct(s::String) = parse_int(Int,s,8) parse_hex(s::String) = parse_int(Int,s,16) integer (s::String) = int(s) unsigned(s::String) = uint(s) int (s::String) = parse_int(Int,s) uint (s::String) = parse_int(Uint,s) int8 (s::String) = parse_int(Int8,s) uint8 (s::String) = parse_int(Uint8,s) int16 (s::String) = parse_int(Int16,s) uint16 (s::String) = parse_int(Uint16,s) int32 (s::String) = parse_int(Int32,s) uint32 (s::String) = parse_int(Uint32,s) int64 (s::String) = parse_int(Int64,s) uint64 (s::String) = parse_int(Uint64,s) ## integer to string functions ## const _jl_dig_syms = "0123456789abcdefghijklmnopqrstuvwxyz".data function int2str(n::Union(Int64,Uint64), b::Integer, l::Int) if b < 2 || b > 36; error("int2str: invalid base ", b); end neg = n < 0 n = unsigned(abs(n)) b = convert(typeof(n), b) ndig = ndigits(n, b) sz = max(convert(Int, ndig), l) + neg data = Array(Uint8, sz) i = sz if ispow2(b) digmask = b-1 shift = trailing_zeros(b) while i > neg ch = n & digmask data[i] = _jl_dig_syms[int(ch)+1] n >>= shift i -= 1 end else while i > neg ch = n % b data[i] = _jl_dig_syms[int(ch)+1] n = div(n,b) i -= 1 end end if neg data[1] = '-' end ASCIIString(data) end int2str(n::Integer, b::Integer) = int2str(n, b, 0) int2str(n::Integer, b::Integer, l::Int) = int2str(int64(n), b, l) string(x::Signed) = dec(int64(x)) cstring(x::Signed) = dec(int64(x)) ## string to float functions ## function float64_isvalid(s::String, out::Array{Float64,1}) s = cstring(s) return (ccall(:jl_strtod, Int32, (Ptr{Uint8},Ptr{Float64}), s, out)==0) end function float32_isvalid(s::String, out::Array{Float32,1}) s = cstring(s) return (ccall(:jl_strtof, Int32, (Ptr{Uint8},Ptr{Float32}), s, out)==0) end begin local tmp::Array{Float64,1} = Array(Float64,1) local tmpf::Array{Float32,1} = Array(Float32,1) global float64, float32 function float64(s::String) if !float64_isvalid(s, tmp) throw(ArgumentError("float64(String): invalid number format")) end return tmp[1] end function float32(s::String) if !float32_isvalid(s, tmpf) throw(ArgumentError("float32(String): invalid number format")) end return tmpf[1] end end float(x::String) = float64(x) parse_float(x::String) = float64(x) parse_float(::Type{Float64}, x::String) = float64(x) parse_float(::Type{Float32}, x::String) = float32(x) # copying a byte string (generally not needed due to "immutability") strcpy{T<:ByteString}(s::T) = T(copy(s.data)) # lexicographically compare byte arrays (used by Latin-1 and UTF-8) function lexcmp(a::Array{Uint8,1}, b::Array{Uint8,1}) c = ccall(:memcmp, Int32, (Ptr{Uint8}, Ptr{Uint8}, Uint), a, b, min(length(a),length(b))) c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b)) end # find the index of the first occurrence of a byte value in a byte array function memchr(a::Array{Uint8,1}, b::Integer) p = pointer(a) q = ccall(:memchr, Ptr{Uint8}, (Ptr{Uint8}, Int32, Uint), p, b, length(a)) q == C_NULL ? 0 : q - p + 1 end # concatenate byte arrays into a single array memcat() = Array(Uint8,0) memcat(a::Array{Uint8,1}) = copy(a) function memcat(arrays::Array{Uint8,1}...) n = 0 for a in arrays n += length(a) end arr = Array(Uint8, n) ptr = pointer(arr) offset = 0 for a in arrays ccall(:memcpy, Ptr{Uint8}, (Ptr{Uint8}, Ptr{Uint8}, Uint), ptr+offset, a, length(a)) offset += length(a) end return arr end # concatenate the data fields of byte strings memcat(s::ByteString) = memcat(s.data) memcat(sx::ByteString...) = memcat(map(s->s.data, sx)...) pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/string_delimiters.d000066400000000000000000000010401250413007300275570ustar00rootroot00000000000000import std.stdio; void main() { // Nesting delimited strings auto a = q"{foo " {bar} baz}"; auto b = q"[foo [bar] " baz]"; auto c = q"(foo " (bar) baz)"; auto d = q" " baz>"; // Non-nesting delimited strings auto e = q"/foo " bar/"; auto f = q"-Another " string-"; // "heredoc" strings auto g = q"FOO This is a string! FOO"; // Token strings (only the q{} should be highlighted as a string) auto h = q{ int i; void foo() { writefln("Hello, world!"); } }; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/stripheredoc.sh000066400000000000000000000000451250413007300267160ustar00rootroot00000000000000cat <<-EOF Hello world $PATH EOF pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/swig_java.swg000066400000000000000000001331651250413007300263750ustar00rootroot00000000000000/* ----------------------------------------------------------------------------- * java.swg * * Java typemaps * ----------------------------------------------------------------------------- */ %include /* The jni, jtype and jstype typemaps work together and so there should be one of each. * The jni typemap contains the JNI type used in the JNI (C/C++) code. * The jtype typemap contains the Java type used in the JNI intermediary class. * The jstype typemap contains the Java type used in the Java proxy classes, type wrapper classes and module class. */ /* Fragments */ %fragment("SWIG_PackData", "header") { /* Pack binary data into a string */ SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } } %fragment("SWIG_UnPackData", "header") { /* Unpack binary data from a string */ SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } } /* Primitive types */ %typemap(jni) bool, const bool & "jboolean" %typemap(jni) char, const char & "jchar" %typemap(jni) signed char, const signed char & "jbyte" %typemap(jni) unsigned char, const unsigned char & "jshort" %typemap(jni) short, const short & "jshort" %typemap(jni) unsigned short, const unsigned short & "jint" %typemap(jni) int, const int & "jint" %typemap(jni) unsigned int, const unsigned int & "jlong" %typemap(jni) long, const long & "jint" %typemap(jni) unsigned long, const unsigned long & "jlong" %typemap(jni) long long, const long long & "jlong" %typemap(jni) unsigned long long, const unsigned long long & "jobject" %typemap(jni) float, const float & "jfloat" %typemap(jni) double, const double & "jdouble" %typemap(jni) void "void" %typemap(jtype) bool, const bool & "boolean" %typemap(jtype) char, const char & "char" %typemap(jtype) signed char, const signed char & "byte" %typemap(jtype) unsigned char, const unsigned char & "short" %typemap(jtype) short, const short & "short" %typemap(jtype) unsigned short, const unsigned short & "int" %typemap(jtype) int, const int & "int" %typemap(jtype) unsigned int, const unsigned int & "long" %typemap(jtype) long, const long & "int" %typemap(jtype) unsigned long, const unsigned long & "long" %typemap(jtype) long long, const long long & "long" %typemap(jtype) unsigned long long, const unsigned long long & "java.math.BigInteger" %typemap(jtype) float, const float & "float" %typemap(jtype) double, const double & "double" %typemap(jtype) void "void" %typemap(jstype) bool, const bool & "boolean" %typemap(jstype) char, const char & "char" %typemap(jstype) signed char, const signed char & "byte" %typemap(jstype) unsigned char, const unsigned char & "short" %typemap(jstype) short, const short & "short" %typemap(jstype) unsigned short, const unsigned short & "int" %typemap(jstype) int, const int & "int" %typemap(jstype) unsigned int, const unsigned int & "long" %typemap(jstype) long, const long & "int" %typemap(jstype) unsigned long, const unsigned long & "long" %typemap(jstype) long long, const long long & "long" %typemap(jstype) unsigned long long, const unsigned long long & "java.math.BigInteger" %typemap(jstype) float, const float & "float" %typemap(jstype) double, const double & "double" %typemap(jstype) void "void" %typemap(jni) char *, char *&, char[ANY], char[] "jstring" %typemap(jtype) char *, char *&, char[ANY], char[] "String" %typemap(jstype) char *, char *&, char[ANY], char[] "String" /* JNI types */ %typemap(jni) jboolean "jboolean" %typemap(jni) jchar "jchar" %typemap(jni) jbyte "jbyte" %typemap(jni) jshort "jshort" %typemap(jni) jint "jint" %typemap(jni) jlong "jlong" %typemap(jni) jfloat "jfloat" %typemap(jni) jdouble "jdouble" %typemap(jni) jstring "jstring" %typemap(jni) jobject "jobject" %typemap(jni) jbooleanArray "jbooleanArray" %typemap(jni) jcharArray "jcharArray" %typemap(jni) jbyteArray "jbyteArray" %typemap(jni) jshortArray "jshortArray" %typemap(jni) jintArray "jintArray" %typemap(jni) jlongArray "jlongArray" %typemap(jni) jfloatArray "jfloatArray" %typemap(jni) jdoubleArray "jdoubleArray" %typemap(jni) jobjectArray "jobjectArray" %typemap(jtype) jboolean "boolean" %typemap(jtype) jchar "char" %typemap(jtype) jbyte "byte" %typemap(jtype) jshort "short" %typemap(jtype) jint "int" %typemap(jtype) jlong "long" %typemap(jtype) jfloat "float" %typemap(jtype) jdouble "double" %typemap(jtype) jstring "String" %typemap(jtype) jobject "Object" %typemap(jtype) jbooleanArray "boolean[]" %typemap(jtype) jcharArray "char[]" %typemap(jtype) jbyteArray "byte[]" %typemap(jtype) jshortArray "short[]" %typemap(jtype) jintArray "int[]" %typemap(jtype) jlongArray "long[]" %typemap(jtype) jfloatArray "float[]" %typemap(jtype) jdoubleArray "double[]" %typemap(jtype) jobjectArray "Object[]" %typemap(jstype) jboolean "boolean" %typemap(jstype) jchar "char" %typemap(jstype) jbyte "byte" %typemap(jstype) jshort "short" %typemap(jstype) jint "int" %typemap(jstype) jlong "long" %typemap(jstype) jfloat "float" %typemap(jstype) jdouble "double" %typemap(jstype) jstring "String" %typemap(jstype) jobject "Object" %typemap(jstype) jbooleanArray "boolean[]" %typemap(jstype) jcharArray "char[]" %typemap(jstype) jbyteArray "byte[]" %typemap(jstype) jshortArray "short[]" %typemap(jstype) jintArray "int[]" %typemap(jstype) jlongArray "long[]" %typemap(jstype) jfloatArray "float[]" %typemap(jstype) jdoubleArray "double[]" %typemap(jstype) jobjectArray "Object[]" /* Non primitive types */ %typemap(jni) SWIGTYPE "jlong" %typemap(jtype) SWIGTYPE "long" %typemap(jstype) SWIGTYPE "$&javaclassname" %typemap(jni) SWIGTYPE [] "jlong" %typemap(jtype) SWIGTYPE [] "long" %typemap(jstype) SWIGTYPE [] "$javaclassname" %typemap(jni) SWIGTYPE * "jlong" %typemap(jtype) SWIGTYPE * "long" %typemap(jstype) SWIGTYPE * "$javaclassname" %typemap(jni) SWIGTYPE & "jlong" %typemap(jtype) SWIGTYPE & "long" %typemap(jstype) SWIGTYPE & "$javaclassname" /* pointer to a class member */ %typemap(jni) SWIGTYPE (CLASS::*) "jstring" %typemap(jtype) SWIGTYPE (CLASS::*) "String" %typemap(jstype) SWIGTYPE (CLASS::*) "$javaclassname" /* The following are the in, out, freearg, argout typemaps. These are the JNI code generating typemaps for converting from Java to C and visa versa. */ /* primitive types */ %typemap(in) bool %{ $1 = $input ? true : false; %} %typemap(directorout) bool %{ $result = $input ? true : false; %} %typemap(javadirectorin) bool "$jniinput" %typemap(javadirectorout) bool "$javacall" %typemap(in) char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, float, double %{ $1 = ($1_ltype)$input; %} %typemap(directorout) char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, float, double %{ $result = ($1_ltype)$input; %} %typemap(directorin, descriptor="Z") bool "$input = (jboolean) $1;" %typemap(directorin, descriptor="C") char "$input = (jint) $1;" %typemap(directorin, descriptor="B") signed char "$input = (jbyte) $1;" %typemap(directorin, descriptor="S") unsigned char "$input = (jshort) $1;" %typemap(directorin, descriptor="S") short "$input = (jshort) $1;" %typemap(directorin, descriptor="I") unsigned short "$input = (jint) $1;" %typemap(directorin, descriptor="I") int "$input = (jint) $1;" %typemap(directorin, descriptor="J") unsigned int "$input = (jlong) $1;" %typemap(directorin, descriptor="I") long "$input = (jint) $1;" %typemap(directorin, descriptor="J") unsigned long "$input = (jlong) $1;" %typemap(directorin, descriptor="J") long long "$input = (jlong) $1;" %typemap(directorin, descriptor="F") float "$input = (jfloat) $1;" %typemap(directorin, descriptor="D") double "$input = (jdouble) $1;" %typemap(javadirectorin) char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, float, double "$jniinput" %typemap(javadirectorout) char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, float, double "$javacall" %typemap(out) bool %{ $result = (jboolean)$1; %} %typemap(out) char %{ $result = (jchar)$1; %} %typemap(out) signed char %{ $result = (jbyte)$1; %} %typemap(out) unsigned char %{ $result = (jshort)$1; %} %typemap(out) short %{ $result = (jshort)$1; %} %typemap(out) unsigned short %{ $result = (jint)$1; %} %typemap(out) int %{ $result = (jint)$1; %} %typemap(out) unsigned int %{ $result = (jlong)$1; %} %typemap(out) long %{ $result = (jint)$1; %} %typemap(out) unsigned long %{ $result = (jlong)$1; %} %typemap(out) long long %{ $result = (jlong)$1; %} %typemap(out) float %{ $result = (jfloat)$1; %} %typemap(out) double %{ $result = (jdouble)$1; %} /* unsigned long long */ /* Convert from BigInteger using the toByteArray member function */ %typemap(in) unsigned long long { jclass clazz; jmethodID mid; jbyteArray ba; jbyte* bae; jsize sz; int i; if (!$input) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); return $null; } clazz = JCALL1(GetObjectClass, jenv, $input); mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); bae = JCALL2(GetByteArrayElements, jenv, ba, 0); sz = JCALL1(GetArrayLength, jenv, ba); $1 = 0; for(i=0; i", "([B)V"); jobject bigint; int i; bae[0] = 0; for(i=1; i<9; i++ ) { bae[i] = (jbyte)($1>>8*(8-i)); } JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); bigint = JCALL3(NewObject, jenv, clazz, mid, ba); $result = bigint; } /* Convert to BigInteger (see out typemap) */ %typemap(directorin, descriptor="Ljava/math/BigInteger;") unsigned long long, const unsigned long long & { jbyteArray ba = JCALL1(NewByteArray, jenv, 9); jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0); jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger"); jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "", "([B)V"); jobject bigint; int swig_i; bae[0] = 0; for(swig_i=1; swig_i<9; swig_i++ ) { bae[swig_i] = (jbyte)($1>>8*(8-swig_i)); } JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); bigint = JCALL3(NewObject, jenv, clazz, mid, ba); $input = bigint; } %typemap(javadirectorin) unsigned long long "$jniinput" %typemap(javadirectorout) unsigned long long "$javacall" /* char * - treat as String */ %typemap(in, noblock=1) char * { $1 = 0; if ($input) { $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); if (!$1) return $null; } } %typemap(directorout, noblock=1, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) char * { $1 = 0; if ($input) { $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); if (!$result) return $null; } } %typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * { $input = 0; if ($1) { $input = JCALL1(NewStringUTF, jenv, (const char *)$1); if (!$input) return $null; } } %typemap(freearg, noblock=1) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); } %typemap(out, noblock=1) char * { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); } %typemap(javadirectorin) char * "$jniinput" %typemap(javadirectorout) char * "$javacall" /* char *& - treat as String */ %typemap(in, noblock=1) char *& ($*1_ltype temp = 0) { $1 = 0; if ($input) { temp = ($*1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); if (!temp) return $null; } $1 = &temp; } %typemap(freearg, noblock=1) char *& { if ($1 && *$1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)*$1); } %typemap(out, noblock=1) char *& { if (*$1) $result = JCALL1(NewStringUTF, jenv, (const char *)*$1); } %typemap(out) void "" %typemap(javadirectorin) void "$jniinput" %typemap(javadirectorout) void "$javacall" %typemap(directorin, descriptor="V") void "" /* primitive types by reference */ %typemap(in) const bool & ($*1_ltype temp) %{ temp = $input ? true : false; $1 = &temp; %} %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const bool & %{ static $*1_ltype temp; temp = $input ? true : false; $result = &temp; %} %typemap(javadirectorin) const bool & "$jniinput" %typemap(javadirectorout) const bool & "$javacall" %typemap(in) const char & ($*1_ltype temp), const signed char & ($*1_ltype temp), const unsigned char & ($*1_ltype temp), const short & ($*1_ltype temp), const unsigned short & ($*1_ltype temp), const int & ($*1_ltype temp), const unsigned int & ($*1_ltype temp), const long & ($*1_ltype temp), const unsigned long & ($*1_ltype temp), const long long & ($*1_ltype temp), const float & ($*1_ltype temp), const double & ($*1_ltype temp) %{ temp = ($*1_ltype)$input; $1 = &temp; %} %typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const char &, const signed char &, const unsigned char &, const short &, const unsigned short &, const int &, const unsigned int &, const long &, const unsigned long &, const long long &, const float &, const double & %{ static $*1_ltype temp; temp = ($*1_ltype)$input; $result = &temp; %} %typemap(directorin, descriptor="Z") const bool & "$input = (jboolean)$1;" %typemap(directorin, descriptor="C") const char & "$input = (jchar)$1;" %typemap(directorin, descriptor="B") const signed char & "$input = (jbyte)$1;" %typemap(directorin, descriptor="S") const unsigned char & "$input = (jshort)$1;" %typemap(directorin, descriptor="S") const short & "$input = (jshort)$1;" %typemap(directorin, descriptor="I") const unsigned short & "$input = (jint)$1;" %typemap(directorin, descriptor="I") const int & "$input = (jint)$1;" %typemap(directorin, descriptor="J") const unsigned int & "$input = (jlong)$1;" %typemap(directorin, descriptor="I") const long & "$input = (jint)$1;" %typemap(directorin, descriptor="J") const unsigned long & "$input = (jlong)$1;" %typemap(directorin, descriptor="J") const long long & "$input = (jlong)$1;" %typemap(directorin, descriptor="F") const float & "$input = (jfloat)$1;" %typemap(directorin, descriptor="D") const double & "$input = (jdouble)$1;" %typemap(javadirectorin) const char & ($*1_ltype temp), const signed char & ($*1_ltype temp), const unsigned char & ($*1_ltype temp), const short & ($*1_ltype temp), const unsigned short & ($*1_ltype temp), const int & ($*1_ltype temp), const unsigned int & ($*1_ltype temp), const long & ($*1_ltype temp), const unsigned long & ($*1_ltype temp), const long long & ($*1_ltype temp), const float & ($*1_ltype temp), const double & ($*1_ltype temp) "$jniinput" %typemap(javadirectorout) const char & ($*1_ltype temp), const signed char & ($*1_ltype temp), const unsigned char & ($*1_ltype temp), const short & ($*1_ltype temp), const unsigned short & ($*1_ltype temp), const int & ($*1_ltype temp), const unsigned int & ($*1_ltype temp), const long & ($*1_ltype temp), const unsigned long & ($*1_ltype temp), const long long & ($*1_ltype temp), const float & ($*1_ltype temp), const double & ($*1_ltype temp) "$javacall" %typemap(out) const bool & %{ $result = (jboolean)*$1; %} %typemap(out) const char & %{ $result = (jchar)*$1; %} %typemap(out) const signed char & %{ $result = (jbyte)*$1; %} %typemap(out) const unsigned char & %{ $result = (jshort)*$1; %} %typemap(out) const short & %{ $result = (jshort)*$1; %} %typemap(out) const unsigned short & %{ $result = (jint)*$1; %} %typemap(out) const int & %{ $result = (jint)*$1; %} %typemap(out) const unsigned int & %{ $result = (jlong)*$1; %} %typemap(out) const long & %{ $result = (jint)*$1; %} %typemap(out) const unsigned long & %{ $result = (jlong)*$1; %} %typemap(out) const long long & %{ $result = (jlong)*$1; %} %typemap(out) const float & %{ $result = (jfloat)*$1; %} %typemap(out) const double & %{ $result = (jdouble)*$1; %} /* const unsigned long long & */ /* Similar to unsigned long long */ %typemap(in) const unsigned long long & ($*1_ltype temp) { jclass clazz; jmethodID mid; jbyteArray ba; jbyte* bae; jsize sz; int i; if (!$input) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); return $null; } clazz = JCALL1(GetObjectClass, jenv, $input); mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); bae = JCALL2(GetByteArrayElements, jenv, ba, 0); sz = JCALL1(GetArrayLength, jenv, ba); $1 = &temp; temp = 0; for(i=0; i", "([B)V"); jobject bigint; int i; bae[0] = 0; for(i=1; i<9; i++ ) { bae[i] = (jbyte)(*$1>>8*(8-i)); } JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); bigint = JCALL3(NewObject, jenv, clazz, mid, ba); $result = bigint; } %typemap(javadirectorin) const unsigned long long & "$jniinput" %typemap(javadirectorout) const unsigned long long & "$javacall" /* Default handling. Object passed by value. Convert to a pointer */ %typemap(in) SWIGTYPE ($&1_type argp) %{ argp = *($&1_ltype*)&$input; if (!argp) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type"); return $null; } $1 = *argp; %} %typemap(directorout) SWIGTYPE ($&1_type argp) %{ argp = *($&1_ltype*)&$input; if (!argp) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); return $null; } $result = *argp; %} %typemap(out) SWIGTYPE #ifdef __cplusplus %{ *($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %} #else { $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype)); memmove($1ptr, &$1, sizeof($1_type)); *($&1_ltype*)&$result = $1ptr; } #endif %typemap(directorin,descriptor="L$packagepath/$&javaclassname;") SWIGTYPE %{ $input = 0; *(($&1_ltype*)&$input) = &$1; %} %typemap(javadirectorin) SWIGTYPE "new $&javaclassname($jniinput, false)" %typemap(javadirectorout) SWIGTYPE "$&javaclassname.getCPtr($javacall)" /* Generic pointers and references */ %typemap(in) SWIGTYPE * %{ $1 = *($&1_ltype)&$input; %} %typemap(in, fragment="SWIG_UnPackData") SWIGTYPE (CLASS::*) { const char *temp = 0; if ($input) { temp = JCALL2(GetStringUTFChars, jenv, $input, 0); if (!temp) return $null; } SWIG_UnpackData(temp, (void *)&$1, sizeof($1)); } %typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input; if (!$1) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null"); return $null; } %} %typemap(out) SWIGTYPE * %{ *($&1_ltype)&$result = $1; %} %typemap(out, fragment="SWIG_PackData", noblock=1) SWIGTYPE (CLASS::*) { char buf[128]; char *data = SWIG_PackData(buf, (void *)&$1, sizeof($1)); *data = '\0'; $result = JCALL1(NewStringUTF, jenv, buf); } %typemap(out) SWIGTYPE & %{ *($&1_ltype)&$result = $1; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE * %{ $result = *($&1_ltype)&$input; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE (CLASS::*) %{ $result = *($&1_ltype)&$input; %} %typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE * %{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} %typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE (CLASS::*) %{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} %typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE & %{ if (!$input) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); return $null; } $result = *($&1_ltype)&$input; %} %typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE & %{ *($&1_ltype)&$input = ($1_ltype) &$1; %} %typemap(javadirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($jniinput == 0) ? null : new $javaclassname($jniinput, false)" %typemap(javadirectorin) SWIGTYPE & "new $javaclassname($jniinput, false)" %typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$javaclassname.getCPtr($javacall)" /* Default array handling */ %typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %} %typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %} %typemap(freearg) SWIGTYPE [ANY], SWIGTYPE [] "" /* char arrays - treat as String */ %typemap(in, noblock=1) char[ANY], char[] { $1 = 0; if ($input) { $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); if (!$1) return $null; } } %typemap(directorout, noblock=1) char[ANY], char[] { $1 = 0; if ($input) { $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); if (!$result) return $null; } } %typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char[ANY], char[] { $input = 0; if ($1) { $input = JCALL1(NewStringUTF, jenv, (const char *)$1); if (!$input) return $null; } } %typemap(argout) char[ANY], char[] "" %typemap(freearg, noblock=1) char[ANY], char[] { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); } %typemap(out, noblock=1) char[ANY], char[] { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); } %typemap(javadirectorin) char[ANY], char[] "$jniinput" %typemap(javadirectorout) char[ANY], char[] "$javacall" /* JNI types */ %typemap(in) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray %{ $1 = $input; %} %typemap(directorout) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray %{ $result = $input; %} %typemap(out) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray %{ $result = $1; %} %typemap(directorin,descriptor="Z") jboolean "$input = $1;" %typemap(directorin,descriptor="C") jchar "$input = $1;" %typemap(directorin,descriptor="B") jbyte "$input = $1;" %typemap(directorin,descriptor="S") jshort "$input = $1;" %typemap(directorin,descriptor="I") jint "$input = $1;" %typemap(directorin,descriptor="J") jlong "$input = $1;" %typemap(directorin,descriptor="F") jfloat "$input = $1;" %typemap(directorin,descriptor="D") jdouble "$input = $1;" %typemap(directorin,descriptor="Ljava/lang/String;") jstring "$input = $1;" %typemap(directorin,descriptor="Ljava/lang/Object;",nouse="1") jobject "$input = $1;" %typemap(directorin,descriptor="[Z") jbooleanArray "$input = $1;" %typemap(directorin,descriptor="[C") jcharArray "$input = $1;" %typemap(directorin,descriptor="[B") jbyteArray "$input = $1;" %typemap(directorin,descriptor="[S") jshortArray "$input = $1;" %typemap(directorin,descriptor="[I") jintArray "$input = $1;" %typemap(directorin,descriptor="[J") jlongArray "$input = $1;" %typemap(directorin,descriptor="[F") jfloatArray "$input = $1;" %typemap(directorin,descriptor="[D") jdoubleArray "$input = $1;" %typemap(directorin,descriptor="[Ljava/lang/Object;",nouse="1") jobjectArray "$input = $1;" %typemap(javadirectorin) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray "$jniinput" %typemap(javadirectorout) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray "$javacall" /* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions * that cannot be overloaded in Java as more than one C++ type maps to a single Java type */ %typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */ jboolean, bool, const bool & "" %typecheck(SWIG_TYPECHECK_CHAR) /* Java char */ jchar, char, const char & "" %typecheck(SWIG_TYPECHECK_INT8) /* Java byte */ jbyte, signed char, const signed char & "" %typecheck(SWIG_TYPECHECK_INT16) /* Java short */ jshort, unsigned char, short, const unsigned char &, const short & "" %typecheck(SWIG_TYPECHECK_INT32) /* Java int */ jint, unsigned short, int, long, const unsigned short &, const int &, const long & "" %typecheck(SWIG_TYPECHECK_INT64) /* Java long */ jlong, unsigned int, unsigned long, long long, const unsigned int &, const unsigned long &, const long long & "" %typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */ unsigned long long, const unsigned long long & "" %typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */ jfloat, float, const float & "" %typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */ jdouble, double, const double & "" %typecheck(SWIG_TYPECHECK_STRING) /* Java String */ jstring, char *, char *&, char[ANY], char [] "" %typecheck(SWIG_TYPECHECK_BOOL_ARRAY) /* Java boolean[] */ jbooleanArray "" %typecheck(SWIG_TYPECHECK_CHAR_ARRAY) /* Java char[] */ jcharArray "" %typecheck(SWIG_TYPECHECK_INT8_ARRAY) /* Java byte[] */ jbyteArray "" %typecheck(SWIG_TYPECHECK_INT16_ARRAY) /* Java short[] */ jshortArray "" %typecheck(SWIG_TYPECHECK_INT32_ARRAY) /* Java int[] */ jintArray "" %typecheck(SWIG_TYPECHECK_INT64_ARRAY) /* Java long[] */ jlongArray "" %typecheck(SWIG_TYPECHECK_FLOAT_ARRAY) /* Java float[] */ jfloatArray "" %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY) /* Java double[] */ jdoubleArray "" %typecheck(SWIG_TYPECHECK_OBJECT_ARRAY) /* Java jobject[] */ jobjectArray "" %typecheck(SWIG_TYPECHECK_POINTER) /* Default */ SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE *const&, SWIGTYPE [], SWIGTYPE (CLASS::*) "" /* Exception handling */ %typemap(throws) int, long, short, unsigned int, unsigned long, unsigned short %{ char error_msg[256]; sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1); SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg); return $null; %} %typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] %{ (void)$1; SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); return $null; %} %typemap(throws) char * %{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1); return $null; %} /* Typemaps for code generation in proxy classes and Java type wrapper classes */ /* The javain typemap is used for converting function parameter types from the type * used in the proxy, module or type wrapper class to the type used in the JNI class. */ %typemap(javain) bool, const bool &, char, const char &, signed char, const signed char &, unsigned char, const unsigned char &, short, const short &, unsigned short, const unsigned short &, int, const int &, unsigned int, const unsigned int &, long, const long &, unsigned long, const unsigned long &, long long, const long long &, unsigned long long, const unsigned long long &, float, const float &, double, const double & "$javainput" %typemap(javain) char *, char *&, char[ANY], char[] "$javainput" %typemap(javain) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray "$javainput" %typemap(javain) SWIGTYPE "$&javaclassname.getCPtr($javainput)" %typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$javaclassname.getCPtr($javainput)" %typemap(javain) SWIGTYPE (CLASS::*) "$javaclassname.getCMemberPtr($javainput)" /* The javaout typemap is used for converting function return types from the return type * used in the JNI class to the type returned by the proxy, module or type wrapper class. */ %typemap(javaout) bool, const bool &, char, const char &, signed char, const signed char &, unsigned char, const unsigned char &, short, const short &, unsigned short, const unsigned short &, int, const int &, unsigned int, const unsigned int &, long, const long &, unsigned long, const unsigned long &, long long, const long long &, unsigned long long, const unsigned long long &, float, const float &, double, const double & { return $jnicall; } %typemap(javaout) char *, char *&, char[ANY], char[] { return $jnicall; } %typemap(javaout) jboolean, jchar, jbyte, jshort, jint, jlong, jfloat, jdouble, jstring, jobject, jbooleanArray, jcharArray, jbyteArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectArray { return $jnicall; } %typemap(javaout) void { $jnicall; } %typemap(javaout) SWIGTYPE { return new $&javaclassname($jnicall, true); } %typemap(javaout) SWIGTYPE & { return new $javaclassname($jnicall, $owner); } %typemap(javaout) SWIGTYPE *, SWIGTYPE [] { long cPtr = $jnicall; return (cPtr == 0) ? null : new $javaclassname(cPtr, $owner); } %typemap(javaout) SWIGTYPE (CLASS::*) { String cMemberPtr = $jnicall; return (cMemberPtr == null) ? null : new $javaclassname(cMemberPtr, $owner); } /* Pointer reference typemaps */ %typemap(jni) SWIGTYPE *const& "jlong" %typemap(jtype) SWIGTYPE *const& "long" %typemap(jstype) SWIGTYPE *const& "$*javaclassname" %typemap(javain) SWIGTYPE *const& "$*javaclassname.getCPtr($javainput)" %typemap(javaout) SWIGTYPE *const& { long cPtr = $jnicall; return (cPtr == 0) ? null : new $*javaclassname(cPtr, $owner); } %typemap(in) SWIGTYPE *const& ($*1_ltype temp = 0) %{ temp = *($1_ltype)&$input; $1 = ($1_ltype)&temp; %} %typemap(out) SWIGTYPE *const& %{ *($1_ltype)&$result = *$1; %} /* Typemaps used for the generation of proxy and type wrapper class code */ %typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(javaclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" %typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(javaimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" %typemap(javainterfaces) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" /* javabody typemaps */ %define SWIG_JAVABODY_METHODS(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE) %enddef // legacy name %define SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) // Base proxy classes %typemap(javabody) TYPE %{ private long swigCPtr; protected boolean swigCMemOwn; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } CPTR_VISIBILITY static long getCPtr($javaclassname obj) { return (obj == null) ? 0 : obj.swigCPtr; } %} // Derived proxy classes %typemap(javabody_derived) TYPE %{ private long swigCPtr; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { super($imclassname.$javaclazznameSWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } CPTR_VISIBILITY static long getCPtr($javaclassname obj) { return (obj == null) ? 0 : obj.swigCPtr; } %} %enddef %define SWIG_JAVABODY_TYPEWRAPPER(PTRCTOR_VISIBILITY, DEFAULTCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) // Typewrapper classes %typemap(javabody) TYPE *, TYPE &, TYPE [] %{ private long swigCPtr; PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean futureUse) { swigCPtr = cPtr; } DEFAULTCTOR_VISIBILITY $javaclassname() { swigCPtr = 0; } CPTR_VISIBILITY static long getCPtr($javaclassname obj) { return (obj == null) ? 0 : obj.swigCPtr; } %} %typemap(javabody) TYPE (CLASS::*) %{ private String swigCMemberPtr; PTRCTOR_VISIBILITY $javaclassname(String cMemberPtr, boolean futureUse) { swigCMemberPtr = cMemberPtr; } DEFAULTCTOR_VISIBILITY $javaclassname() { swigCMemberPtr = null; } CPTR_VISIBILITY static String getCMemberPtr($javaclassname obj) { return obj.swigCMemberPtr; } %} %enddef /* Set the default javabody typemaps to use protected visibility. Use the macros to change to public if using multiple modules. */ SWIG_JAVABODY_PROXY(protected, protected, SWIGTYPE) SWIG_JAVABODY_TYPEWRAPPER(protected, protected, protected, SWIGTYPE) %typemap(javafinalize) SWIGTYPE %{ protected void finalize() { delete(); } %} /* * Java constructor typemaps: * * The javaconstruct typemap is inserted when a proxy class's constructor is generated. * This typemap allows control over what code is executed in the constructor as * well as specifying who owns the underlying C/C++ object. Normally, Java has * ownership and the underlying C/C++ object is deallocated when the Java object * is finalized (swigCMemOwn is true.) If swigCMemOwn is false, C/C++ is * ultimately responsible for deallocating the underlying object's memory. * * The SWIG_PROXY_CONSTRUCTOR macro defines the javaconstruct typemap for a proxy * class for a particular TYPENAME. OWNERSHIP is passed as the value of * swigCMemOwn to the pointer constructor method. WEAKREF determines which kind * of Java object reference will be used by the C++ director class (WeakGlobalRef * vs. GlobalRef.) * * The SWIG_DIRECTOR_OWNED macro sets the ownership of director-based proxy * classes and the weak reference flag to false, meaning that the underlying C++ * object will be reclaimed by C++. */ %define SWIG_PROXY_CONSTRUCTOR(OWNERSHIP, WEAKREF, TYPENAME...) %typemap(javaconstruct,directorconnect="\n $imclassname.$javaclazznamedirector_connect(this, swigCPtr, swigCMemOwn, WEAKREF);") TYPENAME { this($imcall, OWNERSHIP);$directorconnect } %enddef %define SWIG_DIRECTOR_OWNED(TYPENAME...) SWIG_PROXY_CONSTRUCTOR(true, false, TYPENAME) %enddef // Set the default for SWIGTYPE: Java owns the C/C++ object. SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE) %typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; $jnicall; } swigCPtr = 0; } } %typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; $jnicall; } swigCPtr = 0; } super.delete(); } %typemap(directordisconnect, methodname="swigDirectorDisconnect") SWIGTYPE %{ protected void $methodname() { swigCMemOwn = false; $jnicall; } %} %typemap(directorowner_release, methodname="swigReleaseOwnership") SWIGTYPE %{ public void $methodname() { swigCMemOwn = false; $jnicall; } %} %typemap(directorowner_take, methodname="swigTakeOwnership") SWIGTYPE %{ public void $methodname() { swigCMemOwn = true; $jnicall; } %} /* Java specific directives */ #define %javaconst(flag) %feature("java:const","flag") #define %javaconstvalue(value) %feature("java:constvalue",value) #define %javaenum(wrapapproach) %feature("java:enum","wrapapproach") #define %javamethodmodifiers %feature("java:methodmodifiers") #define %javaexception(exceptionclasses) %feature("except",throws=exceptionclasses) #define %nojavaexception %feature("except","0",throws="") #define %clearjavaexception %feature("except","",throws="") %pragma(java) jniclassclassmodifiers="public class" %pragma(java) moduleclassmodifiers="public class" /* Some ANSI C typemaps */ %apply unsigned long { size_t }; %apply const unsigned long & { const size_t & }; /* Array reference typemaps */ %apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } /* const pointers */ %apply SWIGTYPE * { SWIGTYPE *const } /* String & length */ %typemap(jni) (char *STRING, size_t LENGTH) "jbyteArray" %typemap(jtype) (char *STRING, size_t LENGTH) "byte[]" %typemap(jstype) (char *STRING, size_t LENGTH) "byte[]" %typemap(javain) (char *STRING, size_t LENGTH) "$javainput" %typemap(freearg) (char *STRING, size_t LENGTH) "" %typemap(in) (char *STRING, size_t LENGTH) { if ($input) { $1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0); $2 = (size_t) JCALL1(GetArrayLength, jenv, $input); } else { $1 = 0; $2 = 0; } } %typemap(argout) (char *STRING, size_t LENGTH) { if ($input) JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *)$1, 0); } %typemap(directorin, descriptor="[B") (char *STRING, size_t LENGTH) { jbyteArray jb = (jenv)->NewByteArray($2); (jenv)->SetByteArrayRegion(jb, 0, $2, (jbyte *)$1); $input = jb; } %typemap(directorargout) (char *STRING, size_t LENGTH) %{(jenv)->GetByteArrayRegion($input, 0, $2, (jbyte *)$1); %} %apply (char *STRING, size_t LENGTH) { (char *STRING, int LENGTH) } /* java keywords */ %include // Default enum handling %include pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/swig_std_vector.i000066400000000000000000000140111250413007300272440ustar00rootroot00000000000000// // std::vector // %include // Vector %define %std_vector_methods(vector...) %std_sequence_methods(vector) void reserve(size_type n); size_type capacity() const; %enddef %define %std_vector_methods_val(vector...) %std_sequence_methods_val(vector) void reserve(size_type n); size_type capacity() const; %enddef // ------------------------------------------------------------------------ // std::vector // // The aim of all that follows would be to integrate std::vector with // as much as possible, namely, to allow the user to pass and // be returned tuples or lists. // const declarations are used to guess the intent of the function being // exported; therefore, the following rationale is applied: // // -- f(std::vector), f(const std::vector&): // the parameter being read-only, either a sequence or a // previously wrapped std::vector can be passed. // -- f(std::vector&), f(std::vector*): // the parameter may be modified; therefore, only a wrapped std::vector // can be passed. // -- std::vector f(), const std::vector& f(): // the vector is returned by copy; therefore, a sequence of T:s // is returned which is most easily used in other functions // -- std::vector& f(), std::vector* f(): // the vector is returned by reference; therefore, a wrapped std::vector // is returned // -- const std::vector* f(), f(const std::vector*): // for consistency, they expect and return a plain vector pointer. // ------------------------------------------------------------------------ %{ #include %} // exported classes namespace std { template > class vector { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Alloc allocator_type; %traits_swigtype(_Tp); %traits_enum(_Tp); %fragment(SWIG_Traits_frag(std::vector<_Tp, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdVectorTraits") { namespace swig { template <> struct traits > { typedef pointer_category category; static const char* type_name() { return "std::vector<" #_Tp "," #_Alloc " >"; } }; } } %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp, _Alloc >); #ifdef %swig_vector_methods // Add swig/language extra methods %swig_vector_methods(std::vector<_Tp, _Alloc >); #endif %std_vector_methods(vector); }; // *** // This specialization should disappear or get simplified when // a 'const SWIGTYPE*&' can be defined // *** template class vector<_Tp*, _Alloc > { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type reference; typedef value_type const_reference; typedef _Alloc allocator_type; %traits_swigtype(_Tp); %fragment(SWIG_Traits_frag(std::vector<_Tp*, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdVectorTraits") { namespace swig { template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::vector<" #_Tp " *," #_Alloc " >"; } }; } } %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp*, _Alloc >); #ifdef %swig_vector_methods_val // Add swig/language extra methods %swig_vector_methods_val(std::vector<_Tp*, _Alloc >); #endif %std_vector_methods_val(vector); }; // *** // const pointer specialization // *** template class vector<_Tp const *, _Alloc > { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp const * value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type reference; typedef value_type const_reference; typedef _Alloc allocator_type; %traits_swigtype(_Tp); %fragment(SWIG_Traits_frag(std::vector<_Tp const*, _Alloc >), "header", fragment=SWIG_Traits_frag(_Tp), fragment="StdVectorTraits") { namespace swig { template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::vector<" #_Tp " const*," #_Alloc " >"; } }; } } %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp const*, _Alloc >); #ifdef %swig_vector_methods_val // Add swig/language extra methods %swig_vector_methods_val(std::vector<_Tp const*, _Alloc >); #endif %std_vector_methods_val(vector); }; // *** // bool specialization // *** template class vector { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef bool value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type reference; typedef value_type const_reference; typedef _Alloc allocator_type; %traits_swigtype(bool); %fragment(SWIG_Traits_frag(std::vector), "header", fragment=SWIG_Traits_frag(bool), fragment="StdVectorTraits") { namespace swig { template <> struct traits > { typedef value_category category; static const char* type_name() { return "std::vector"; } }; } } %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); #ifdef %swig_vector_methods_val // Add swig/language extra methods %swig_vector_methods_val(std::vector); #endif %std_vector_methods_val(vector); #if defined(SWIG_STD_MODERN_STL) && !defined(SWIG_STD_NOMODERN_STL) void flip(); #endif }; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.R000066400000000000000000000045731250413007300250030ustar00rootroot00000000000000#!/usr/bin/env Rscript ### Example R script for syntax highlighting # This is also a comment ## Valid names abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV0123456789._a <- NULL .foo_ <- NULL ._foo <- NULL ## Invalid names 0abc <- NULL .0abc <- NULL abc+cde <- NULL ## Reserved Words NA NA_integer_ NA_real_ NA_character_ NA_complex_ NULL NaN Inf ## Not reserved NULLa <- NULL NULL1 <- NULL NULL. <- NULL NA_foo_ <- NULL ## Numbers 12345678901 123456.78901 123e3 123E3 6.02e23 1.6e-35 1.E12 .1234 ## integers 123L 1.23L ## imaginary numbers 123i -123i 123e4i 123e-4i ## Hex numbers 0xabcdefABCDEF01234 0xabcp123 0xabcP123 ## Not hex 0xg ## Special operators %xyz% ## %xyz% 1 %% 2 diag(2) %*% diag(2) 1 %/% 2 1 %in% 1:10 diag(2) %o% diag(2) diag(2) %x% diag(2) `%foo bar%` <- function(x, y) x + y 1 %foo bar% 2 ## Control Structures (3.2) and Function ## if, else if (TRUE) print("foo") else print("bar") ## For, in for(i in 1:5) { print(i) } ## While, break i <- 1 while (TRUE) { i <- i + 1 if (i > 3) break } ## Repeat repeat {1+1} ## Switch x <- 3 switch(x, 2+2, mean(1:10), rnorm(5)) ## Function, dot-dot-dot, return, sum foo <- function(...) { return(sum(...)) } # Not keywords functiona <- 2 + 2 function. <- 2 + 2 function1 <- 2 + 2 ## Grouping Tokens 10.3.7 ## Parentheses 1 + (2 + 3) ## brackets foo <- function(a) { a + 1 } ## Indexing 10.3.8 ## [] bar <- 1:10 bar[3] ## [[]] foo <- list(a=1, b=2, c=3) foo[["a"]] ## $ foo$a foo$"a" ## Operators 2 - 2 2 + 2 2 ~ 2 ! TRUE ?"help" 1:2 2 * 2 2 / 2 2^2 2 < 2 2 > 2 2 == 2 2 >= 2 2 <= 2 2 != 2 TRUE & FALSE TRUE && FALSE TRUE | FALSE TRUE || FALSE foo <- 2 + 2 foo = 2 + 2 2 + 2 -> foo foo <<- 2 + 2 2 + 2 ->> foo base:::sum base::sum ## Strings foo <- "hello, world!" foo <- 'hello, world!' foo <- "Hello, 'world!" foo <- 'Hello, "world!' foo <- 'Hello, \'world!\'' foo <- "Hello, \"world!\"" foo <- "Hello, world!" foo <- 'Hello, world!' ## Backtick strings `foo123 +!"bar'baz` <- 2 + 2 ## Builtin funcitons file.create() gamma() grep() paste() rbind() rownames() R.Version() R.version.string() sample() sapply() save.image() seq() setwd() sin() ## Data structures servo <- matrix(1:25, nrow = 5) numeric() vector(servo) data.frame() list1 <- list(time = 1:40) # multidimensional array array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) ## Namespace library(ggplot2) require(plyr) attach(cars) source("test.R") pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.adb000066400000000000000000000120311250413007300253140ustar00rootroot00000000000000-- Model IED Simulator -- COL Gene Ressler, 1 December 2007 with Ada.Text_IO; with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings; with Ada.Strings.Bounded; with Binary_Search; with Ada.Containers.Generic_Array_Sort; package body Scanner is Constant_123 : constant Character := Character'Val (16#00#); MAX_KEYWORD_LENGTH_C : constant Natural := 24; New_Constant : constant New_Type := 2; KEYWORDS_C : constant Keyword_Array_T := (To_BS("description"), To_BS("with")); procedure Blah; procedure blah is begin Declaration: declare Joe : Type_Type := Random; begin Do_Something; end Declaration; Loop_ID: loop Loop_Do; exit when 1=2; end loop Loop_ID; if True or else False then Do_This(); elsif not False and then True then Do_That; else Panic; end if; end blah; function "*" (Left, Right : in Integer) return Integer is begin <> goto Goto_Label; return Left + Right; end "*"; function Function_Specification (Param_1 : in Blah; Param2, param3 : in access Blah_Type := 0) return It_Type; package Rename_Check renames Ada.Text_IO; type New_Float is delta 0.001 digits 12; package Package_Inst is new Ada.Strings.Bounded.Generic_Bounded_Length (Max => MAX_KEYWORD_LENGTH_C); type Array_Decl12 is array (Positive range <>) of SB.Bounded_String; type Array_Decl3 is array (New_Type range Thing_1 .. Thing_2) of SB.Bounded_String; type Boring_Type is (Start, End_Error); subtype Sub_Type_check is Character range '0' .. '9'; Initialized_Array : constant Transistion_Array_T := (Start => (Letter_Lower | Letter_Upper => Saw_Alpha, ' ' | HT | CR | LF => Start, others => Begin_Error), End_Error => (others => Start) ); type Recorder is record Advance : Boolean; Return_Token : Token_T; end record; for Recorder use 8; type Null_Record is null record; type Discriminated_Record (Size : Natural) is record A : String (1 .. Size); end record; pragma Unchecked_Union (Union); pragma Convention (C, Union); type Person is tagged record Name : String (1 .. 10); Gender : Gender_Type; end record; type Programmer is new Person with record Skilled_In : Language_List; Favorite_Langauge : Python_Type; end record; type Programmer is new Person and Printable with record Skilled_In : Language_List; Blah : aliased Integer; end record; --------------------- -- Scan_Next_Token -- --------------------- task Cyclic_Buffer_Task_Type is entry Insert (An_Item : in Item); entry Remove (An_Item : out Item); end Cyclic_Buffer_Task_Type; task body Cyclic_Buffer_Task_Type is Q_Size : constant := 100; subtype Q_Range is Positive range 1 .. Q_Size; Length : Natural range 0 .. Q_Size := 0; Head, Tail : Q_Range := 1; Data : array (Q_Range) of Item; begin loop select when Length < Q_Size => accept Insert (An_Item : in Item) do Data(Tail) := An_Item; end Insert; Tail := Tail mod Q_Size + 1; Length := Length + 1; or when Length > 0 => accept Remove (An_Item : out Item) do An_Item := Data(Head); end Remove; Head := Head mod Q_Size + 1; Length := Length - 1; end select; end loop; end Cyclic_Buffer_Task_Type; procedure Scan_Next_Token (S : in String; Start_Index : out Positive; End_Index : in out Natural; -- Tricky comment Line_Number : in out Positive; Token : out Token_T); procedure Scan_Next_Token (S : in String; Start_Index : out Positive; End_Index : in out Natural; -- Another comment Line_Number : in out Positive; Token : out Token_T) is begin Scanner_Loop: loop if New_State = End_Error then exit Scanner_Loop; end if; if State = Start and New_State /= Start then Start_Index := Peek_Index; end if; end loop Scanner_Loop; end Scan_Next_Token; procedure Advance is begin Peek_Index := Peek_Index + 1; end Advance; -- Eliminate the leading space that Ada puts in front of positive -- integer images. function Image(N : in Integer) return String is S : String := Integer'Image(N); begin if S(1) = ' ' then return S(2 .. S'Last); end if; return S; end Image; end Scanner; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.agda000066400000000000000000000052121250413007300254650ustar00rootroot00000000000000-- An Agda example file module test where open import Coinduction open import Data.Bool open import {- pointless comment between import and module name -} Data.Char open import Data.Nat open import Data.Nat.Properties open import Data.String open import Data.List hiding ([_]) open import Data.Vec hiding ([_]) open import Relation.Nullary.Core open import Relation.Binary.PropositionalEquality using (_≡_; refl; cong; trans; inspect; [_]) open SemiringSolver {- this is a {- nested -} comment -} -- Factorial _! : â„• → â„• 0 ! = 1 (suc n) ! = (suc n) * n ! -- The binomial coefficient _choose_ : â„• → â„• → â„• _ choose 0 = 1 0 choose _ = 0 (suc n) choose (suc m) = (n choose m) + (n choose (suc m)) -- Pascal's rule choose-too-many : ∀ n m → n ≤ m → n choose (suc m) ≡ 0 choose-too-many .0 m z≤n = refl choose-too-many (suc n) (suc m) (s≤s le) with n choose (suc m) | choose-too-many n m le | n choose (suc (suc m)) | choose-too-many n (suc m) (≤-step le) ... | .0 | refl | .0 | refl = refl _++'_ : ∀ {a n m} {A : Set a} → Vec A n → Vec A m → Vec A (m + n) _++'_ {_} {n} {m} vâ‚ vâ‚‚ rewrite solve 2 (λ a b → b :+ a := a :+ b) refl n m = vâ‚ Data.Vec.++ vâ‚‚ ++'-test : (1 ∷ 2 ∷ 3 ∷ []) ++' (4 ∷ 5 ∷ []) ≡ (1 ∷ 2 ∷ 3 ∷ 4 ∷ 5 ∷ []) ++'-test = refl data Coâ„• : Set where co0 : Coâ„• cosuc : ∞ Coâ„• → Coâ„• nanana : Coâ„• nanana = let two = ♯ cosuc (♯ (cosuc (♯ co0))) in cosuc two abstract data VacuumCleaner : Set where Roomba : VacuumCleaner pointlessLemmaAboutBoolFunctions : (f : Bool → Bool) → f (f (f true)) ≡ f true pointlessLemmaAboutBoolFunctions f with f true | inspect f true ... | true | [ eqâ‚ ] = trans (cong f eqâ‚) eqâ‚ ... | false | [ eqâ‚ ] with f false | inspect f false ... | true | _ = eqâ‚ ... | false | [ eqâ‚‚ ] = eqâ‚‚ mutual isEven : â„• → Bool isEven 0 = true isEven (suc n) = not (isOdd n) isOdd : â„• → Bool isOdd 0 = false isOdd (suc n) = not (isEven n) foo : String foo = "Hello World!" nl : Char nl = '\n' private intersperseString : Char → List String → String intersperseString c [] = "" intersperseString c (x ∷ xs) = Data.List.foldl (λ a b → a Data.String.++ Data.String.fromList (c ∷ []) Data.String.++ b) x xs baz : String baz = intersperseString nl (Data.List.replicate 5 foo) postulate Float : Set {-# BUILTIN FLOAT Float #-} pi : Float pi = 3.141593 -- Astronomical unit au : Float au = 1.496e11 -- m plusFloat : Float → Float → Float plusFloat a b = {! !} record Subset (A : Set) (P : A → Set) : Set where constructor _#_ field elem : A .proof : P elem pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.apl000066400000000000000000000011131250413007300253410ustar00rootroot00000000000000∇ Râ†M COMBIN N;D;E;F;G;P â Returns a matrix of every possible â combination of M elements from the â vector â³N. That is, returns a â matrix with M!N rows and N columns. â Eâ†(â³Pâ†N-Râ†M-1)-⎕IO Dâ†R+â³P Râ†(P,1)â´D Pâ†Pâ´1 L1:→(⎕IO>1↑Dâ†D-1)â´0 Pâ†+\P Gâ†+\¯1↓0,Fâ†âŒ½P Eâ†F/E-G Râ†(F/D),R[E+â³â´E;] Eâ†G →L1 ∇ ∇ Râ†M QUICKEXP N â Matrix exponentiation B ↠⌊ 1 + 2 ⟠N V ↠(B â´ 2) ⊤ N L ↠⊂ M R ↠⊃ +.× / V / L ⊣ { L ↠(⊂ A +.× A ↠↑L) , L }¨ â³ B-1 ∇ pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.asy000066400000000000000000000237421250413007300253750ustar00rootroot00000000000000// example file for roundedpath() in roundedpath.asy // written by stefan knorr // import needed packages import roundedpath; // function definition picture CreateKOOS(real Scale, string legend) // draw labeled coordinate system as picture { picture ReturnPic; real S = 1.2*Scale; draw(ReturnPic, ((-S,0)--(S,0)), bar = EndArrow); // x axis draw(ReturnPic, ((0,-S)--(0,S)), bar = EndArrow); // y axis label(ReturnPic, "$\varepsilon$", (S,0), SW); // x axis label label(ReturnPic, "$\sigma$", (0,S), SW); // y axis label label(ReturnPic, legend, (0.7S, -S), NW); // add label 'legend' return ReturnPic; // return picture } // some global definitions real S = 13mm; // universal scale factor for the whole file real grad = 0.25; // gradient for lines real radius = 0.04; // radius for the rounded path' real lw = 2; // linewidth pair A = (-1, -1); // start point for graphs pair E = ( 1, 1); // end point for graphs path graph; // local graph pen ActPen; // actual pen for each drawing picture T[]; // vector of all four diagrams real inc = 2.8; // increment-offset for combining pictures //////////////////////////////////////// 1st diagram T[1] = CreateKOOS(S, "$T_1$"); // initialise T[1] as empty diagram with label $T_1$ graph = A; // # pointwise definition of current path 'graph' graph = graph -- (A.x + grad*1.6, A.y + 1.6); // # graph = graph -- (E.x - grad*0.4, E.y - 0.4); // # graph = graph -- E; // # graph = roundedpath(graph, radius, S); // round edges of 'graph' using roundedpath() in roundedpath.asy ActPen = rgb(0,0,0.6) + linewidth(lw); // define pen for drawing in 1st diagram draw(T[1], graph, ActPen); // draw 'graph' with 'ActPen' into 'T[1]' (1st hysteresis branch) draw(T[1], rotate(180,(0,0))*graph, ActPen); // draw rotated 'graph' (2nd hysteresis branch) graph = (0,0) -- (grad*0.6, 0.6) -- ( (grad*0.6, 0.6) + (0.1, 0) ); // define branch from origin to hysteresis graph = roundedpath(graph, radius, S); // round this path draw(T[1], graph, ActPen); // draw this path into 'T[1]' //////////////////////////////////////// 2nd diagram T[2] = CreateKOOS(S, "$T_2$"); // initialise T[2] as empty diagram with label $T_2$ graph = A; // # pointwise definition of current path 'graph' graph = graph -- (A.x + grad*1.3, A.y + 1.3); // # graph = graph -- (E.x - grad*0.7 , E.y - 0.7); // # graph = graph -- E; // # graph = roundedpath(graph, radius, S); // round edges of 'graph' using roundedpath() in roundedpath.asy ActPen = rgb(0.2,0,0.4) + linewidth(lw); // define pen for drawing in 2nd diagram draw(T[2], graph, ActPen); // draw 'graph' with 'ActPen' into 'T[2]' (1st hysteresis branch) draw(T[2], rotate(180,(0,0))*graph, ActPen); // draw rotated 'graph' (2nd hysteresis branch) graph = (0,0) -- (grad*0.3, 0.3) -- ( (grad*0.3, 0.3) + (0.1, 0) ); // define branch from origin to hysteresis graph = roundedpath(graph, radius, S); // round this path draw(T[2], graph, ActPen); // draw this path into 'T[2]' //////////////////////////////////////// 3rd diagram T[3] = CreateKOOS(S, "$T_3$"); // initialise T[3] as empty diagram with label $T_3$ graph = A; // # pointwise definition of current path 'graph' graph = graph -- (A.x + grad*0.7, A.y + 0.7); // # graph = graph -- ( - grad*0.3 , - 0.3); // # graph = graph -- (0,0); // # graph = graph -- (grad*0.6, 0.6); // # graph = graph -- (E.x - grad*0.4, E.y - 0.4); // # graph = graph -- E; // # graph = roundedpath(graph, radius, S); // round edges of 'graph' using roundedpath() in roundedpath.asy ActPen = rgb(0.6,0,0.2) + linewidth(lw); // define pen for drawing in 3rd diagram draw(T[3], graph, ActPen); // draw 'graph' with 'ActPen' into 'T[3]' (1st hysteresis branch) draw(T[3], rotate(180,(0,0))*graph, ActPen); // draw rotated 'graph' (2nd hysteresis branch) //////////////////////////////////////// 4th diagram T[4] = CreateKOOS(S, "$T_4$"); // initialise T[4] as empty diagram with label $T_4$ graph = A; // # pointwise definition of current path 'graph' graph = graph -- (A.x + grad*0.4, A.y + 0.4); // # graph = graph -- ( - grad*0.6 , - 0.6); // # graph = graph -- (0,0); // # graph = graph -- (grad*0.9, 0.9); // # graph = graph -- (E.x - grad*0.1, E.y - 0.1); // # graph = graph -- E; // # graph = roundedpath(graph, radius, S); // round edges of 'graph' using roundedpath() in roundedpath.asy ActPen = rgb(0.6,0,0) + linewidth(lw); // define pen for drawing in 4th diagram draw(T[4], graph, ActPen); // draw 'graph' with 'ActPen' into 'T[4]' (1st hysteresis branch) draw(T[4], rotate(180,(0,0))*graph, ActPen); // draw rotated 'graph' (3nd hysteresis branch) // add some labels and black dots to the first two pictures pair SWW = (-0.8, -0.6); label(T[1], "$\sigma_f$", (0, 0.6S), NE); // sigma_f draw(T[1], (0, 0.6S), linewidth(3) + black); label(T[2], "$\sigma_f$", (0, 0.3S), NE); // sigma_f draw(T[2], (0, 0.3S), linewidth(3) + black); label(T[1], "$\varepsilon_p$", (0.7S, 0), SWW); // epsilon_p draw(T[1], (0.75S, 0), linewidth(3) + black); label(T[2], "$\varepsilon_p$", (0.7S, 0), SWW); // epsilon_p draw(T[2], (0.75S, 0), linewidth(3) + black); // add all pictures T[1...4] to the current one add(T[1],(0,0)); add(T[2],(1*inc*S,0)); add(T[3],(2*inc*S,0)); add(T[4],(3*inc*S,0)); // draw line of constant \sigma and all intersection points with the graphs in T[1...4] ActPen = linewidth(1) + dashed + gray(0.5); // pen definition draw((-S, 0.45*S)--((3*inc+1)*S, 0.45*S), ActPen); // draw backgoundline label("$\sigma_s$", (-S, 0.45S), W); // label 'sigma_s' path mark = scale(2)*unitcircle; // define mark-symbol to be used for intersections ActPen = linewidth(1) + gray(0.5); // define pen for intersection mark draw(shift(( 1 - grad*0.55 + 0*inc)*S, 0.45*S)*mark, ActPen); // # draw all intersections draw(shift((-1 + grad*1.45 + 0*inc)*S, 0.45*S)*mark, ActPen); // # draw(shift(( 1 - grad*0.55 + 1*inc)*S, 0.45*S)*mark, ActPen); // # draw(shift(( 1 - grad*0.55 + 2*inc)*S, 0.45*S)*mark, ActPen); // # draw(shift(( grad*0.45 + 2*inc)*S, 0.45*S)*mark, ActPen); // # draw(shift(( grad*0.45 + 3*inc)*S, 0.45*S)*mark, ActPen); // # pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.awk000066400000000000000000000106601250413007300253560ustar00rootroot00000000000000#!/bin/awk -f BEGIN { # It is not possible to define output file names here because # FILENAME is not define in the BEGIN section n = ""; printf "Generating data files ..."; network_max_bandwidth_in_byte = 10000000; network_max_packet_per_second = 1000000; last3 = 0; last4 = 0; last5 = 0; last6 = 0; } { if ($1 ~ /Average/) { # Skip the Average values n = ""; next; } if ($2 ~ /all/) { # This is the cpu info print $3 > FILENAME".cpu.user.dat"; # print $4 > FILENAME".cpu.nice.dat"; print $5 > FILENAME".cpu.system.dat"; # print $6 > FILENAME".cpu.iowait.dat"; print $7 > FILENAME".cpu.idle.dat"; print 100-$7 > FILENAME".cpu.busy.dat"; } if ($2 ~ /eth0/) { # This is the eth0 network info if ($3 > network_max_packet_per_second) print last3 > FILENAME".net.rxpck.dat"; # Total number of packets received per second. else { last3 = $3; print $3 > FILENAME".net.rxpck.dat"; # Total number of packets received per second. } if ($4 > network_max_packet_per_second) print last4 > FILENAME".net.txpck.dat"; # Total number of packets transmitted per second. else { last4 = $4; print $4 > FILENAME".net.txpck.dat"; # Total number of packets transmitted per second. } if ($5 > network_max_bandwidth_in_byte) print last5 > FILENAME".net.rxbyt.dat"; # Total number of bytes received per second. else { last5 = $5; print $5 > FILENAME".net.rxbyt.dat"; # Total number of bytes received per second. } if ($6 > network_max_bandwidth_in_byte) print last6 > FILENAME".net.txbyt.dat"; # Total number of bytes transmitted per second. else { last6 = $6; print $6 > FILENAME".net.txbyt.dat"; # Total number of bytes transmitted per second. } # print $7 > FILENAME".net.rxcmp.dat"; # Number of compressed packets received per second (for cslip etc.). # print $8 > FILENAME".net.txcmp.dat"; # Number of compressed packets transmitted per second. # print $9 > FILENAME".net.rxmcst.dat"; # Number of multicast packets received per second. } # Detect which is the next info to be parsed if ($2 ~ /proc|cswch|tps|kbmemfree|totsck/) { n = $2; } # Only get lines with numbers (real data !) if ($2 ~ /[0-9]/) { if (n == "proc/s") { # This is the proc/s info print $2 > FILENAME".proc.dat"; # n = ""; } if (n == "cswch/s") { # This is the context switches per second info print $2 > FILENAME".ctxsw.dat"; # n = ""; } if (n == "tps") { # This is the disk info print $2 > FILENAME".disk.tps.dat"; # total transfers per second print $3 > FILENAME".disk.rtps.dat"; # read requests per second print $4 > FILENAME".disk.wtps.dat"; # write requests per second print $5 > FILENAME".disk.brdps.dat"; # block reads per second print $6 > FILENAME".disk.bwrps.dat"; # block writes per second # n = ""; } if (n == "kbmemfree") { # This is the mem info print $2 > FILENAME".mem.kbmemfree.dat"; # Amount of free memory available in kilobytes. print $3 > FILENAME".mem.kbmemused.dat"; # Amount of used memory in kilobytes. This does not take into account memory used by the kernel itself. print $4 > FILENAME".mem.memused.dat"; # Percentage of used memory. # It appears the kbmemshrd has been removed from the sysstat output - ntolia # print $X > FILENAME".mem.kbmemshrd.dat"; # Amount of memory shared by the system in kilobytes. Always zero with 2.4 kernels. # print $5 > FILENAME".mem.kbbuffers.dat"; # Amount of memory used as buffers by the kernel in kilobytes. print $6 > FILENAME".mem.kbcached.dat"; # Amount of memory used to cache data by the kernel in kilobytes. # print $7 > FILENAME".mem.kbswpfree.dat"; # Amount of free swap space in kilobytes. # print $8 > FILENAME".mem.kbswpused.dat"; # Amount of used swap space in kilobytes. print $9 > FILENAME".mem.swpused.dat"; # Percentage of used swap space. # n = ""; } if (n == "totsck") { # This is the socket info print $2 > FILENAME".sock.totsck.dat"; # Total number of used sockets. print $3 > FILENAME".sock.tcpsck.dat"; # Number of TCP sockets currently in use. # print $4 > FILENAME".sock.udpsck.dat"; # Number of UDP sockets currently in use. # print $5 > FILENAME".sock.rawsck.dat"; # Number of RAW sockets currently in use. # print $6 > FILENAME".sock.ip-frag.dat"; # Number of IP fragments currently in use. # n = ""; } } } END { print " '" FILENAME "' done."; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.bb000066400000000000000000000034401250413007300251550ustar00rootroot00000000000000 ;foobar! ;Include "blurg/blurg.bb" Const ca = $10000000 ; Hex Const cb = %10101010 ; Binary Global ga$ = "blargh" Local a = 124, b$ = "abcdef" Function name_123#(zorp$, ll = False, blah#, waffles% = 100) Return 235.7804 ; comment End Function Function TestString$() End Function Function hub(blah$, abc = Pi) End Function Function Blar%() Local aa %, ab # ,ac #, ad# ,ae$,af% ; Intentional mangling Local ba#, bb.TBlarf , bc%,bd#,be. TFooBar,ff = True End Function abc() Function abc() Print "abc" ; I cannot find a way to parse these as function calls without messing something up Print ; Anyhow, they're generally not used in this way Goto Eww_Goto .Eww_Goto End Function Type TBlarf End Type Type TFooBar End Type Local myinst.MyClass = New MyClass TestMethod(myinst) Type MyClass Field m_foo.MyClass Field m_bar.MyClass ; abc ; def End Type Function TestMethod(self.MyClass) ; foobar self\m_foo = self self\m_bar = Object.MyClass(Handle self\m_foo) Yell self\m_foo\m_bar\m_foo\m_bar End Function Function Yell(self.MyClass) Print("huzzah!") End Function Function Wakka$(foo$) Return foo + "bar" End Function Print("blah " + "blah " + "blah.") Local i : For i = 0 To 10 Step 1 Print("Index: " + i) Next Local array$[5] array[0] = "foo": array[1] = "bar":array[2] = "11":array[3] = "22":array[4] = "33" For i = 0 To 4 Local value$ = array[i] Print("Value: " + value) Next Local foobar = Not (1 Or (2 And (4 Shl 5 Shr 6)) Sar 7) Mod (8+2) Local az = 1234567890 az = az + 1 az = az - 2 az = az* 3 az = az/ 4 az = az And 5 az = az Or 6 az= ~ 7 az = az Shl 8 az= az Shr 9 az = az Sar 10 az = az Mod 11 az = ((10-5+2/4*2)>(((8^2)) < 2)) And 12 Or 2 ;~IDEal Editor Parameters: ;~C#Blitz3Dpygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.bmx000066400000000000000000000045231250413007300253630ustar00rootroot00000000000000 Rem foobar EndRem Rem foobar! End Rem Rem End Rem SuperStrict Framework brl.blitz Import brl.standardio 'Import "blah.bmx" 'Import "blah/blah.bmx" 'Include "blurg/blurg.bmx" Const ca:Long = $10000000 ' Hex Const cb:Int = %10101010 ' Binary Global ga:String = "blargh" Local a:Int = 124, b$ = "abcdef" ?Not Debug Print(_name123(ga, a, 100.2)) ? Function _name123 : Float (zorp:String, ll:Int = False, blah#, waffles% = 100) Return 235.7804 ' Single-line comment End Function Function TestString:String() End Function Function TestByte:Byte() End Function Function hub(blah:String, .. abc:Int = Pi) End Function Function Blar%() Local aa !, ab @ ,ac @@, ad# ,ae$,af% ' Intentional mangling Local ba:Double, bb :Byte, bc: Short,bd:Float,be: String,ff:Int = True End Function ?Win32 abc() ?Linux abc() ? Function abc() Print "abc" ' I cannot find a way to parse these as function calls without messing something up Print ' Anyhow, they're generally not used in this way Goto Eww_Goto #Eww_Goto End Function Type TBlarf Abstract End Type Type TFooBar End Type New MyClass.TestMethod() New(MyClass).TestMethod() Local myinst:MyClass = New MyClass myinst.TestMethod() Type MyClass Extends TFooBar Field m_foo:MyClass Field m_bar:MyClass Rem abc def End Rem Method New() Rem abcdef endrem End Method Method TestMethod() ' foobar m_foo = Self m_bar = MyClass(m_foo) m_foo.m_bar.m_foo.m_bar.Yell() End Method Method Yell() Print("huzzah!") End Method Function Wakka$(foo:String) Return foo + "bar" End Function End Type Extern "c" Function vesper!(a:Int) = "vesper@4" Function bubbles@@(a%) End Extern Print("blah " + .. "blah " + .. "blah.") Try Throw("blar!") Catch exception:String Print("Caught: " + exception) End Try For Local i:Int = 0 To 10 Step 1 Print("Index: " + i) Next Local array:String[] = ["foo", "bar", "11", "22", "33"] For Local value:String = EachIn array Print("Value: " + value) Next Local foobar:Int = Not (1 Or (2 And (4 Shl 5 Shr 6)) Sar 7) Mod (8+2) Local az:Int = 1234567890 az : + 1 az: - 2 az :* 3 az:/ 4 az:& 5 az:| 6 az: ~ 7 az : Shl 8 az: Shr 9 az :Sar 10 az:Mod 11 az = ((10-5+2/4*2)>(((8^2)) < 2)) & 12|2 Function flub(fah Ptr, eah:Int Ptr, blu@@ Ptr) End Function Function Foob:Int Ptr(blar:Byte Ptr, Saffon@Ptr, blaus#Ptr) End Function Function zauus@Ptr() End Function pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.boo000066400000000000000000000021271250413007300253520ustar00rootroot00000000000000import System import Boo.Lang.Interpreter from Boo.Lang.Interpreter class ObjectInterpreter(AbstractInterpreter): _context as object [getter(Value)] _value as object def constructor(context): _context = context self.RememberLastValue = true override def Lookup(name as string): property = _context.GetType().GetProperty(name) return property.PropertyType if property is not null override def GetValue(name as string): return _context.GetType().GetProperty(name).GetValue( _context, null) override def SetLastValue(value): _value = value override def SetValue(name as string, value): raise InvalidOperationException() override def Declare(name as string, type as Type): raise InvalidOperationException() class Person: [property(FirstName)] _fname as string = "" p = Person(FirstName: "Homer") i = ObjectInterpreter(p) i.Eval('"Hello, ${FirstName.ToUpper()}!"') print i.Value pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.bro000066400000000000000000000162511250413007300253600ustar00rootroot00000000000000@load notice @load utils/thresholds module SSH; export { redef enum Log::ID += { SSH }; redef enum Notice::Type += { Login, Password_Guessing, Login_By_Password_Guesser, Login_From_Interesting_Hostname, Bytecount_Inconsistency, }; type Info: record { ts: time &log; uid: string &log; id: conn_id &log; status: string &log &optional; direction: string &log &optional; remote_location: geo_location &log &optional; client: string &log &optional; server: string &log &optional; resp_size: count &log &default=0; ## Indicate if the SSH session is done being watched. done: bool &default=F; }; const password_guesses_limit = 30 &redef; # The size in bytes at which the SSH connection is presumed to be # successful. const authentication_data_size = 5500 &redef; # The amount of time to remember presumed non-successful logins to build # model of a password guesser. const guessing_timeout = 30 mins &redef; # The set of countries for which you'd like to throw notices upon successful login # requires Bro compiled with libGeoIP support const watched_countries: set[string] = {"RO"} &redef; # Strange/bad host names to originate successful SSH logins const interesting_hostnames = /^d?ns[0-9]*\./ | /^smtp[0-9]*\./ | /^mail[0-9]*\./ | /^pop[0-9]*\./ | /^imap[0-9]*\./ | /^www[0-9]*\./ | /^ftp[0-9]*\./ &redef; # This is a table with orig subnet as the key, and subnet as the value. const ignore_guessers: table[subnet] of subnet &redef; # If true, we tell the event engine to not look at further data # packets after the initial SSH handshake. Helps with performance # (especially with large file transfers) but precludes some # kinds of analyses (e.g., tracking connection size). const skip_processing_after_detection = F &redef; # Keeps count of how many rejections a host has had global password_rejections: table[addr] of TrackCount &write_expire=guessing_timeout &synchronized; # Keeps track of hosts identified as guessing passwords # TODO: guessing_timeout doesn't work correctly here. If a user redefs # the variable, it won't take effect. global password_guessers: set[addr] &read_expire=guessing_timeout+1hr &synchronized; global log_ssh: event(rec: Info); } # Configure DPD and the packet filter redef capture_filters += { ["ssh"] = "tcp port 22" }; redef dpd_config += { [ANALYZER_SSH] = [$ports = set(22/tcp)] }; redef record connection += { ssh: Info &optional; }; event bro_init() { Log::create_stream(SSH, [$columns=Info, $ev=log_ssh]); } function set_session(c: connection) { if ( ! c?$ssh ) { local info: Info; info$ts=network_time(); info$uid=c$uid; info$id=c$id; c$ssh = info; } } function check_ssh_connection(c: connection, done: bool) { # If done watching this connection, just return. if ( c$ssh$done ) return; # If this is still a live connection and the byte count has not # crossed the threshold, just return and let the resheduled check happen later. if ( !done && c$resp$size < authentication_data_size ) return; # Make sure the server has sent back more than 50 bytes to filter out # hosts that are just port scanning. Nothing is ever logged if the server # doesn't send back at least 50 bytes. if ( c$resp$size < 50 ) return; local status = "failure"; local direction = Site::is_local_addr(c$id$orig_h) ? "to" : "from"; local location: geo_location; location = (direction == "to") ? lookup_location(c$id$resp_h) : lookup_location(c$id$orig_h); if ( done && c$resp$size < authentication_data_size ) { # presumed failure if ( c$id$orig_h !in password_rejections ) password_rejections[c$id$orig_h] = new_track_count(); # Track the number of rejections if ( !(c$id$orig_h in ignore_guessers && c$id$resp_h in ignore_guessers[c$id$orig_h]) ) ++password_rejections[c$id$orig_h]$n; if ( default_check_threshold(password_rejections[c$id$orig_h]) ) { add password_guessers[c$id$orig_h]; NOTICE([$note=Password_Guessing, $conn=c, $msg=fmt("SSH password guessing by %s", c$id$orig_h), $sub=fmt("%d failed logins", password_rejections[c$id$orig_h]$n), $n=password_rejections[c$id$orig_h]$n]); } } # TODO: This is to work around a quasi-bug in Bro which occasionally # causes the byte count to be oversized. # Watch for Gregors work that adds an actual counter of bytes transferred. else if ( c$resp$size < 20000000 ) { # presumed successful login status = "success"; c$ssh$done = T; if ( c$id$orig_h in password_rejections && password_rejections[c$id$orig_h]$n > password_guesses_limit && c$id$orig_h !in password_guessers ) { add password_guessers[c$id$orig_h]; NOTICE([$note=Login_By_Password_Guesser, $conn=c, $n=password_rejections[c$id$orig_h]$n, $msg=fmt("Successful SSH login by password guesser %s", c$id$orig_h), $sub=fmt("%d failed logins", password_rejections[c$id$orig_h]$n)]); } local message = fmt("SSH login %s %s \"%s\" \"%s\" %f %f %s (triggered with %d bytes)", direction, location$country_code, location$region, location$city, location$latitude, location$longitude, id_string(c$id), c$resp$size); NOTICE([$note=Login, $conn=c, $msg=message, $sub=location$country_code]); # Check to see if this login came from an interesting hostname when ( local hostname = lookup_addr(c$id$orig_h) ) { if ( interesting_hostnames in hostname ) { NOTICE([$note=Login_From_Interesting_Hostname, $conn=c, $msg=fmt("Strange login from %s", hostname), $sub=hostname]); } } if ( location$country_code in watched_countries ) { } } else if ( c$resp$size >= 200000000 ) { NOTICE([$note=Bytecount_Inconsistency, $conn=c, $msg="During byte counting in SSH analysis, an overly large value was seen.", $sub=fmt("%d",c$resp$size)]); } c$ssh$remote_location = location; c$ssh$status = status; c$ssh$direction = direction; c$ssh$resp_size = c$resp$size; Log::write(SSH, c$ssh); # Set the "done" flag to prevent the watching event from rescheduling # after detection is done. c$ssh$done; # Stop watching this connection, we don't care about it anymore. if ( skip_processing_after_detection ) { skip_further_processing(c$id); set_record_packets(c$id, F); } } event connection_state_remove(c: connection) &priority=-5 { if ( c?$ssh ) check_ssh_connection(c, T); } event ssh_watcher(c: connection) { local id = c$id; # don't go any further if this connection is gone already! if ( !connection_exists(id) ) return; check_ssh_connection(c, F); if ( ! c$ssh$done ) schedule +15secs { ssh_watcher(c) }; } event ssh_server_version(c: connection, version: string) &priority=5 { set_session(c); c$ssh$server = version; } event ssh_client_version(c: connection, version: string) &priority=5 { set_session(c); c$ssh$client = version; schedule +15secs { ssh_watcher(c) }; } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.cs000066400000000000000000000425701250413007300252060ustar00rootroot00000000000000//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. // // // // Permission is hereby granted, free of charge, to any person obtaining a // // copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation // // the rights to use, copy, modify, merge, publish, distribute, sublicense, // // and/or sell copies of the Software, and to permit persons to whom the // // Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included // // in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // // USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Core { using System; using Widgets; using System.Xml; using Util; using System.Collections.Generic; using System.Collections; using Basics; public class OpenerTask : Task, IBoilProvider { // Private structs //////////////////////////////////////////// struct ObjectInfo { public ObjectContainer Container; public int[] Depends; public string SystemType; public int RefId; /* CONSTRUCTOR */ public ObjectInfo (ObjectContainer container) { Container = container; Depends = container.Depends.ToArray (); SystemType = container.SystemType; RefId = container.RefId; } public override string ToString () { return String.Format ("Type: {0} Deps count: {1} Id: {2}", SystemType, Depends.Length, RefId); } public bool IsUnBoilable (IBoilProvider provider) { if (Depends.Length == 0) return true; foreach (int id in Depends) if (! (provider.Contains (id))) return false; return true; } } // Enums ////////////////////////////////////////////////////// enum OpenerTaskStep { Init, Header, ProjectInfoRead, ObjectListRead, ObjectListParse, ObjectListUnBoil, FindRoots, Finished }; // Fields ///////////////////////////////////////////////////// string fileName; // Filename we're reading XmlDocument xmlDocument; // Our document //XmlNode projectInfoNode; // node IEnumerator objectsEnumerator; // Enumerator List objectsList; // Objects list ObjectListContainer objectListContainer; OpenerTaskStep currentStep; // Our current step Dictionary idToObject; // Id -> object Dictionary objectToId; // Object -> Id string projectName = String.Empty; string projectDirectory = String.Empty; TagList projectTagList; StuffList projectStuffList; TrackList projectTrackList; ClipList projectClipList; MediaItemList projectMediaItemList; Commander projectCommander; Gdv.Pipeline projectPipeline; Gdv.ProjectFormat projectFormat; // Properties ///////////////////////////////////////////////// public string ProjectName { get { return projectName; } } public string ProjectDirectory { get { return projectDirectory; } } public TagList ProjectTagList { get { return projectTagList; } } public StuffList ProjectStuffList { get { return projectStuffList; } } public TrackList ProjectTrackList { get { return projectTrackList; } } public ClipList ProjectClipList { get { return projectClipList; } } public MediaItemList ProjectMediaItemList { get { return projectMediaItemList; } } public Commander ProjectCommander { get { return projectCommander; } } public Gdv.Pipeline ProjectPipeline { get { return projectPipeline; } } public Gdv.ProjectFormat ProjectFormat { get { return projectFormat; } } // Public methods ///////////////////////////////////////////// /* CONSTRUCTOR */ public OpenerTask (string fileName) { this.fileName = fileName; var verbatimString = @"c:\test\"; var verbatimStringWithNewline = @"test \\ \n \t \r a b c"; var verbatimStringWithEscapedQuotes = @"He said ""she says \"" is not an escaped character in verbatimstrings"" "; int[] numbers = { 5,6,4,2,4,6,8,9,7,0 }; var linqExample = from n in numbers where n > 5 select n; var anotherlinqExample = from n in numbers orderby n descending select n; int[] someMoreNumbers = { 8,2,17,34,8,9,9,5,3,4,2,1,5 }; var moreLinq = from n in numbers join mn in moreNumbers on n equals mn + 2 select new {n, mn}; } public override void Reset () { objectToId = new Dictionary (); idToObject = new Dictionary (); xmlDocument = null; //projectInfoNode = null; currentStep = OpenerTaskStep.Init; base.Reset (); } public int GetIdForObject (object o) { return objectToId [o]; } public object GetObjectForId (int id) { return idToObject [id]; } public bool Contains (int id) { return idToObject.ContainsKey (id); } // Private methods //////////////////////////////////////////// protected override TaskStatus ExecuteStep (int s) { bool cont = true; // Main switch (currentStep) { case OpenerTaskStep.Init: objectsList = new List (); xmlDocument = new XmlDocument (); xmlDocument.Load (fileName); currentStep = OpenerTaskStep.Header; break; case OpenerTaskStep.Header: //ReadHeader (); currentStep = OpenerTaskStep.ProjectInfoRead; break; case OpenerTaskStep.ProjectInfoRead: foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes) if (node.Name == "projectinfo") ResolveProjectInfoNode (node); // FIXME: Fail if not found/not resolved currentStep = OpenerTaskStep.ObjectListRead; break; case OpenerTaskStep.ObjectListRead: foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes) if (node.Name == "objectlist") objectListContainer = (ObjectListContainer) DataFactory.MakeDataElement (node as XmlElement); if (objectListContainer == null) throw new Exception ("ObjectListContainer not found!"); currentStep = OpenerTaskStep.ObjectListParse; break; case OpenerTaskStep.ObjectListParse: bool flush = EnumerateSomeObjects (); if (flush) currentStep = OpenerTaskStep.ObjectListUnBoil; break; case OpenerTaskStep.ObjectListUnBoil: bool done = UnBoilSomeObjects (); if (done) currentStep = OpenerTaskStep.FindRoots; break; case OpenerTaskStep.FindRoots: projectTrackList = (TrackList) FindRoot ("tracklist"); projectTagList = (TagList) FindRoot ("taglist"); projectStuffList = (StuffList) FindRoot ("stufflist"); projectClipList = (ClipList) FindRoot ("cliplist"); projectMediaItemList = (MediaItemList) FindRoot ("mediaitemlist"); projectPipeline = (Gdv.Pipeline) FindRoot ("pipeline"); projectCommander = (Commander) FindRoot ("commander"); projectFormat = (Gdv.ProjectFormat) FindRoot ("projectformat"); currentStep = OpenerTaskStep.Finished; break; case OpenerTaskStep.Finished: cont = false; break; default: break; } // Post if (cont) return TaskStatus.Running; else return TaskStatus.Done; } /* void ReadHeader () { // FIXME: Read all the attributes from the element }*/ void ResolveProjectInfoNode (XmlNode node) { foreach (XmlNode childNode in node) { switch (childNode.Name) { case "name": projectName = childNode.FirstChild.Value; break; case "directory": projectDirectory = childNode.FirstChild.Value; break; // FIXME: Duration etc. } } } bool EnumerateSomeObjects () { if (objectsEnumerator == null) objectsEnumerator = objectListContainer.FindAllObjects ().GetEnumerator (); for (int i = 0; i < 10; i++) { if (objectsEnumerator.MoveNext () == false) return true; ObjectContainer container = (ObjectContainer) objectsEnumerator.Current; ObjectInfo newInfo = new ObjectInfo (container); objectsList.Add (newInfo); } return false; } ObjectInfo GetNextCandidate () { foreach (ObjectInfo objInfo in objectsList) if (objInfo.IsUnBoilable (this)) return objInfo; throw new Exception ("FIXME: No more unboilable objects found. Recursive?"); } bool UnBoilSomeObjects () { for (int i = 0; i < 5; i++) { // All unboiled if (objectsList.Count == 0) return true; ObjectInfo objInfo = GetNextCandidate (); object o = BoilFactory.UnBoil (objInfo.Container, this); objectsList.Remove (objInfo); // Add idToObject [objInfo.RefId] = o; objectToId [o] = objInfo.RefId; } return false; } object FindRoot (string rootString) { ObjectContainer container = objectListContainer.FindObjectContainer (rootString); return idToObject [container.RefId]; } } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.css000066400000000000000000000016451250413007300253670ustar00rootroot00000000000000body { font-size: 12pt; background: #fff url(temp.png) top left no-repeat; } * html body { font-size: 14pt; } #nav .new { display: block; -webkit-border-radius: 5px; -moz-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px; } ul#nav li.new { font-weight: bold; } :link { color: #f00; } :link:hover { color: #0f0; } @media screen { body { background: #ccc; } } @namespace "http://www.w3.org/1999/xhtml"; @import url("mystyle.css"); @charset "ISO-8859-1"; @font-face { font-family: "Example Font"; src: url("http://www.example.com/fonts/example"); } @media screen { body { font-size: 16px } } @media print { body { font-size: 12pt } } @page { body { margin: 1in 1.5in; } } @page linke-seite:left { body { margin:20mm; margin-right:25mm; } } @-moz-document url-prefix(http://pygments.org) { a {font-style: normal !important;} } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.cu000066400000000000000000000014101250413007300251740ustar00rootroot00000000000000#include // __device__ function __device__ void func() { short* array0 = (short*)array; float* array1 = (float*)&array0[127]; } /* __global__ function */ __global__ static void reduction(const float* __restrict__ input, float *output, clock_t *timer) { // __shared__ float shared[2 * blockDim.x]; extern __shared__ float shared[]; const int tid = threadIdx.x; const int bid = blockIdx.x; if (threadIdx.x == 0) { __threadfence(); } // Perform reduction to find minimum. for (int d = blockDim.x; d > 0; d /= 2) { __syncthreads(); } } int main(int argc, char **argv) { dim3 dimBlock(8, 8, 1); timedReduction<<>>(dinput, doutput, dtimer); cudaDeviceReset(); } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.cyp000066400000000000000000000064451250413007300253750ustar00rootroot00000000000000//test comment START a = node(*) MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) RETURN a.name, m.title, d.name; START a = node(*) MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) WITH d,m,count(a) as Actors WHERE Actors > 4 RETURN d.name as Director,m.title as Movie, Actors ORDER BY Actors; START a=node(*) MATCH p=(a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) return p; START a = node(*) MATCH p1=(a)-[:ACTED_IN]->(m), p2=d-[:DIRECTED]->(m) WHERE m.title="The Matrix" RETURN p1, p2; START a = node(*) MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) WHERE a=d RETURN a.name; START a = node(*) MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) WHERE a=d RETURN a.name; START a=node(*) MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d) RETURN a.name, d.name, count(*) as Movies,collect(m.title) as Titles ORDER BY (Movies) DESC LIMIT 5; START keanu=node:node_auto_index(name="Keanu Reeves") RETURN keanu; START keanu=node:node_auto_index(name="Keanu Reeves") MATCH (keanu)-[:ACTED_IN]->(movie) RETURN movie.title; START keanu=node:node_auto_index(name="Keanu Reeves") MATCH (keanu)-[r:ACTED_IN]->(movie) WHERE "Neo" in r.roles RETURN DISTINCT movie.title; START keanu=node:node_auto_index(name="Keanu Reeves") MATCH (keanu)-[:ACTED_IN]->()<-[:DIRECTED]-(director) RETURN director.name; START keanu=node:node_auto_index(name="Keanu Reeves") MATCH (keanu)-[:ACTED_IN]->(movie)<-[:ACTED_IN]-(n) WHERE n.born < keanu.born RETURN DISTINCT n.name, keanu.born ,n.born; START keanu=node:node_auto_index(name="Keanu Reeves"), hugo=node:node_auto_index(name="Hugo Weaving") MATCH (keanu)-[:ACTED_IN]->(movie) WHERE NOT((hugo)-[:ACTED_IN]->(movie)) RETURN DISTINCT movie.title; START a = node(*) MATCH (a)-[:ACTED_IN]->(m) WITH a,count(m) as Movies RETURN a.name as Actor, Movies ORDER BY Movies; START keanu=node:node_auto_index(name="Keanu Reeves"),actor MATCH past=(keanu)-[:ACTED_IN]->()<-[:ACTED_IN]-(), actors=(actor)-[:ACTED_IN]->() WHERE hasnt=actors NOT IN past RETURN hasnt; START keanu=node:node_auto_index(name="Keanu Reeves") MATCH (keanu)-[:ACTED_IN]->()<-[:ACTED_IN]-(c), (c)-[:ACTED_IN]->()<-[:ACTED_IN]-(coc) WHERE NOT((keanu)-[:ACTED_IN]->()<-[:ACTED_IN]-(coc)) AND coc > keanu RETURN coc.name, count(coc) ORDER BY count(coc) DESC LIMIT 3; START kevin=node:node_auto_index(name="Kevin Bacon"), movie=node:node_auto_index(name="Mystic River") MATCH (kevin)-[:ACTED_IN]->(movie) RETURN DISTINCT movie.title; CREATE (n { title:"Mystic River", released:1993, tagline:"We bury our sins here, Dave. We wash them clean." } ) RETURN n; START movie=node:node_auto_index(title="Mystic River") SET movie.released = 2003 RETURN movie; start emil=node:node_auto_index(name="Emil Eifrem") MATCH emil-[r]->(n) DELETE r, emil; START a=node(*) MATCH (a)-[:ACTED_IN]->()<-[:ACTED_IN]-(b) CREATE UNIQUE (a)-[:KNOWS]->(b); START keanu=node:node_auto_index(name="Keanu Reeves") MATCH (keanu)-[:KNOWS*2]->(fof) WHERE keanu <> fof RETURN distinct fof.name; START charlize=node:node_auto_index(name="Charlize Theron"), bacon=node:node_auto_index(name="Kevin Bacon") MATCH p=shortestPath((charlize)-[:KNOWS*]->(bacon)) RETURN extract(n in nodes(p) | n.name)[1]; START actors=node: MATCH (alice)-[:`REALLY LIKES`]->(bob) MATCH (alice)-[:`REALLY ``LIKES```]->(bob) myFancyIdentifier.`(weird property name)` "string\t\n\b\f\\\''\"" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.d000066400000000000000000000115031250413007300250140ustar00rootroot00000000000000// Created by Lionello Lunesu and placed in the public domain. // This file has been modified from its original version. // It has been formatted to fit your screen. module phoneno; // optional import std.stdio; // writefln import std.ctype; // isdigit import std.stream; // BufferedFile // Just for readability (imagine char[][][char[]]) alias char[] string; alias string[] stringarray; /// Strips non-digit characters from the string (COW) string stripNonDigit( in string line ) { string ret; foreach(uint i, c; line) { // Error: std.ctype.isdigit at C:\dmd\src\phobos\std\ctype.d(37) // conflicts with std.stream.isdigit at C:\dmd\src\phobos\std\stream.d(2924) if (!std.ctype.isdigit(c)) { if (!ret) ret = line[0..i]; } else if (ret) ret ~= c; } return ret?ret:line; } unittest { assert( stripNonDigit("asdf") == "" ); assert( stripNonDigit("\'13-=2 4kop") == "1324" ); } /// Converts a word into a number, ignoring all non alpha characters string wordToNum( in string word ) { // translation table for the task at hand const char[256] TRANSLATE = " " // 0 " 0123456789 " // 32 " 57630499617851881234762239 " // 64 " 57630499617851881234762239 " " " " " " " " "; string ret; foreach(c; cast(ubyte[])word) if (TRANSLATE[c] != ' ') ret ~= TRANSLATE[c]; return ret; } unittest { // Test wordToNum using the table from the task description. assert( "01112223334455666777888999" == wordToNum("E | J N Q | R W X | D S Y | F T | A M | C I V | B K U | L O P | G H Z")); assert( "01112223334455666777888999" == wordToNum("e | j n q | r w x | d s y | f t | a m | c i v | b k u | l o p | g h z")); assert( "0123456789" == wordToNum("0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9")); } void main( string[] args ) { // This associative array maps a number to an array of words. stringarray[string] num2words; foreach(string word; new BufferedFile("dictionary.txt" ) ) num2words[ wordToNum(word) ] ~= word.dup; // must dup /// Finds all alternatives for the given number /// (should have been stripped from non-digit characters) stringarray _FindWords( string numbers, bool digitok ) in { assert(numbers.length > 0); } out(result) { foreach (a; result) assert( wordToNum(a) == numbers ); } body { stringarray ret; bool foundword = false; for (uint t=1; t<=numbers.length; ++t) { auto alternatives = numbers[0..t] in num2words; if (!alternatives) continue; foundword = true; if (numbers.length > t) { // Combine all current alternatives with all alternatives // of the rest (next piece can start with a digit) foreach (a2; _FindWords( numbers[t..$], true ) ) foreach(a1; *alternatives) ret ~= a1 ~ " " ~ a2; } else ret ~= *alternatives; // append these alternatives } // Try to keep 1 digit, only if we're allowed and no other // alternatives were found // Testing "ret.length" makes more sense than testing "foundword", // but the other implementations seem to do just this. if (digitok && !foundword) { //ret.length == 0 if(numbers.length > 1) { // Combine 1 digit with all altenatives from the rest // (next piece can not start with a digit) foreach (a; _FindWords( numbers[1..$], false ) ) ret ~= numbers[0..1] ~ " " ~ a; } else ret ~= numbers[0..1]; // just append this digit } return ret; } /// (This function was inlined in the original program) /// Finds all alternatives for the given phone number /// Returns: array of strings stringarray FindWords( string phone_number ) { if (!phone_number.length) return null; // Strip the non-digit characters from the phone number, and // pass it to the recursive function (leading digit is allowed) return _FindWords( stripNonDigit(phone_number), true ); } // Read the phone numbers foreach(string phone; new BufferedFile("input.txt" ) ) foreach(alternative; FindWords( phone ) ) writefln(phone, ": ", alternative ); } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.dart000066400000000000000000000011171250413007300255230ustar00rootroot00000000000000// Greeter example from // class Greeter implements Comparable { String prefix = 'Hello,'; Greeter() {} Greeter.withPrefix(this.prefix); greet(String name) => print('$prefix $name'); int compareTo(Greeter other) => prefix.compareTo(other.prefix); } void main() { Greeter greeter = new Greeter(); Greeter greeter2 = new Greeter.withPrefix('Hi,'); num result = greeter2.compareTo(greeter); if (result == 0) { greeter2.greet('you are the same.'); } else { greeter2.greet('you are different.'); } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.dtd000066400000000000000000000042631250413007300253510ustar00rootroot00000000000000 ]> ]]> ]]> ]> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.ebnf000066400000000000000000000017221250413007300255050ustar00rootroot00000000000000letter = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" ; digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; symbol = "[" | "]" | "{" | "}" | "(" | ")" | "<" | ">" | "'" | '"' | "=" | "|" | "." | "," | ";" ; character = letter | digit | symbol | " " ; identifier = letter , { letter | digit | " " } ; terminal = "'" , character , { character } , "'" | '"' , character , { character } , '"' ; special = "?" , any , "?" ; comment = (* this is a comment "" *) "(*" , any-symbol , "*)" ; any-symbol = ? any visible character ? ; (* ? ... ? *) lhs = identifier ; rhs = identifier | terminal | comment , rhs | rhs , comment | "[" , rhs , "]" | "{" , rhs , "}" | "(" , rhs , ")" | rhs , "|" , rhs | rhs , "," , rhs ; rule = lhs , "=" , rhs , ";" | comment ; grammar = { rule } ; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.ec000066400000000000000000000453371250413007300251740ustar00rootroot00000000000000namespace gui; import "Window" public struct AnchorValue { AnchorValueType type; union { int distance; float percent; }; property int { set { distance = value; type = offset; } get { return distance; } } property double { set { percent = (float) value; type = relative; } get { return (double) percent; } } char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) { if(type == offset) { sprintf(stringOutput, "%d", distance); } else if(type == relative) { int c; int last = 0; sprintf(stringOutput, "%f", percent); c = strlen(stringOutput)-1; for( ; c >= 0; c--) { if(stringOutput[c] != '0') last = Max(last, c); if(stringOutput[c] == '.') { if(last == c) { stringOutput[c+1] = '0'; stringOutput[c+2] = 0; } else stringOutput[last+1] = 0; break; } } } if(needClass) *needClass = false; return stringOutput; } bool OnGetDataFromString(char * stringOutput) { char * end; if(strchr(stringOutput, '.')) { float percent = (float)strtod(stringOutput, &end); if(end != stringOutput) { this.percent = percent; type = relative; return true; } } else if(stringOutput[0]) { int distance = strtol(stringOutput, &end, 0); if(end != stringOutput) { this.distance = distance; type = offset; return true; } } else { distance = 0; type = 0; } return false; } }; public struct MiddleAnchorValue { AnchorValueType type; union { int distance; float percent; }; property int { set { distance = value; type = none; } get { return distance; } } property double { set { percent = (float) value; type = middleRelative; } get { return (double) percent; } } char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) { if(type == middleRelative) { int c; int last = 0; sprintf(stringOutput, "%f", percent); c = strlen(stringOutput)-1; for( ; c >= 0; c--) { if(stringOutput[c] != '0') last = Max(last, c); if(stringOutput[c] == '.') { if(last == c) { stringOutput[c+1] = '0'; stringOutput[c+2] = 0; } else stringOutput[last+1] = 0; break; } } } else if(type == none && distance) { sprintf(stringOutput, "%d", distance); } if(needClass) *needClass = false; return stringOutput; } bool OnGetDataFromString(char * stringOutput) { if(strchr(stringOutput, '.')) { percent = (float)strtod(stringOutput, null); type = middleRelative; } else { distance = strtol(stringOutput, null, 0); type = none; } return true; } }; public enum AnchorValueType { none, offset, relative, middleRelative, cascade, vTiled, hTiled }; public struct Anchor { union { AnchorValue left; MiddleAnchorValue horz; }; union { AnchorValue top; MiddleAnchorValue vert; }; AnchorValue right, bottom; char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) { char tempString[256]; char * anchorValue; bool subNeedClass; tempString[0] = '\0'; anchorValue = left.OnGetString(tempString, null, &subNeedClass); if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "left = "); strcat(stringOutput, anchorValue); } //if(((!left.type && !right.type) && horz.distance) || horz.type == middleRelative) if(!right.type && ((!left.type && horz.distance) || horz.type == middleRelative)) { tempString[0] = '\0'; anchorValue = horz.OnGetString(tempString, null, &subNeedClass); if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "horz = "); strcat(stringOutput, anchorValue); } } tempString[0] = '\0'; anchorValue = top.OnGetString(tempString, null, &subNeedClass); if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "top = "); strcat(stringOutput, anchorValue); } tempString[0] = '\0'; anchorValue = right.OnGetString(tempString, null, &subNeedClass); if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "right = "); strcat(stringOutput, anchorValue); } // if(((!top.type && !bottom.type) && vert.distance) || vert.type == middleRelative) if(!bottom.type && ((!top.type && vert.distance) || vert.type == middleRelative)) { tempString[0] = '\0'; anchorValue = vert.OnGetString(tempString, null, &subNeedClass); if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "vert = "); strcat(stringOutput, anchorValue); } } tempString[0] = '\0'; anchorValue = bottom.OnGetString(tempString, null, &subNeedClass); if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "bottom = "); strcat(stringOutput, anchorValue); } return stringOutput; } bool OnGetDataFromString(char * string) { this = Anchor {}; return class::OnGetDataFromString(string); } bool OnSaveEdit(DropBox dropBox, void * object) { return dropBox.Save(); } Window OnEdit(Window listBox, Window master, int x, int y, int w, int h, Window control) { char * string = ""; AnchorDropBox comboBox { editText = true; parent = listBox; master = master; position = Point { x, y }; //clientSize = Size { h = h }; //size.w = w; size = { w, h }; anchorValue = this; control = control; borderStyle = 0; }; comboBox.Create(); { char tempString[MAX_F_STRING] = ""; bool needClass = false; char * result = OnGetString(tempString, null, &needClass); if(result) string = result; } comboBox.contents = string; return comboBox; } }; private class AnchorButton : Button { toggle = true, bevel = false; void OnRedraw(Surface surface) { int cw = clientSize.w; int ch = clientSize.h; surface.SetForeground(black); if(checked) { surface.SetBackground(Color { 85,85,85 }); surface.Area(0,0, cw-1, ch-1); } else surface.LineStipple(0xAAAA); surface.Rectangle(0,0,cw-1,ch-1); if(active) { surface.LineStipple(0xAAAA); surface.Rectangle(2,2,cw-3,ch-3); } } bool AnchorEditor::NotifyClicked(Button button, int x, int y, Modifiers mods) { AnchorDropBox anchorDropBox = (AnchorDropBox)master; Anchor anchor = anchorDropBox.anchorValue; Window control = anchorDropBox.control; DataBox dropMaster = (DataBox)anchorDropBox.master; int id = button.id; switch(id) { case 0: anchor.left.type = button.checked ? offset : none; break; case 1: anchor.top.type = button.checked ? offset : none; break; case 2: anchor.right.type = button.checked ? offset : none; break; case 3: anchor.bottom.type = button.checked ? offset : none; break; } if(anchor.horz.type == middleRelative && (id == 0 || id == 2)) { anchorDropBox.relButtons[0].checked = false; anchorDropBox.relButtons[2].checked = false; } if(anchor.vert.type == middleRelative && (id == 1 || id == 3)) { anchorDropBox.relButtons[1].checked = false; anchorDropBox.relButtons[3].checked = false; } anchorDropBox.relButtons[id].checked = false; //anchor.horz.type = none; //anchor.vert.type = none; { int vpw, vph; int x,y,w,h; Window parent = control.parent; // Fix Anchor x = control.position.x; y = control.position.y; w = control.size.w; h = control.size.h; vpw = parent.clientSize.w; vph = parent.clientSize.h; if(control.nonClient) { vpw = parent.size.w; vph = parent.size.h; } else if(((BorderBits)control.borderStyle).fixed) { if(!control.dontScrollHorz && parent.scrollArea.w) vpw = parent.scrollArea.w; if(!control.dontScrollVert && parent.scrollArea.h) vph = parent.scrollArea.h; } if(anchor.left.type == offset) anchor.left.distance = x; else if(anchor.left.type == relative) anchor.left.percent = (float)x / vpw; if(anchor.top.type == offset) anchor.top.distance = y; else if(anchor.top.type == relative) anchor.top.percent = (float)y / vph; if(anchor.right.type == offset) anchor.right.distance = vpw - (x + w); //else if(anchor.right.type == relative) anchor.right.percent = (float) (x + w) / vpw; else if(anchor.right.type == relative) anchor.right.percent = (float) (vpw - (x + w)) / vpw; if(anchor.bottom.type == offset) anchor.bottom.distance = vph - (y + h); //else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (y + h) / vph; else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (vph - (y + h)) / vph; if(!anchor.left.type && !anchor.right.type) { anchor.horz.distance = (x + w / 2) - (vpw / 2); //anchor.horz.type = anchor.horz.distance ? offset : 0; } else if(anchor.horz.type == middleRelative) anchor.horz.percent = (float) ((x + w / 2) - (vpw / 2)) / vpw; if(!anchor.top.type && !anchor.bottom.type) { anchor.vert.distance = (y + h / 2) - (vph / 2); //anchor.vert.type = anchor.vert.distance ? offset : 0; } else if(anchor.vert.type == middleRelative) anchor.vert.percent = (float)((y + h / 2) - (vph / 2)) / vph; } { char tempString[1024] = ""; bool needClass = false; char * string = anchor.OnGetString(tempString, null, &needClass); anchorDropBox.contents = string; } dropMaster.SetData(&anchor, false); anchorDropBox.anchorValue = anchor; return true; } } private class AnchorRelButton : Button { toggle = true; bevel = false; text = "%"; //bevelOver = true; void OnRedraw(Surface surface) { int cw = clientSize.w; int ch = clientSize.h; if(checked) { surface.SetForeground(black); } else { surface.SetForeground(Color{170,170,170}); } surface.WriteText(5,2, "%", 1); if(active) { surface.LineStipple(0xAAAA); surface.Rectangle(3,3,cw-4,ch-4); } } bool AnchorEditor::NotifyClicked(Button button, int x, int y, Modifiers mods) { AnchorDropBox anchorDropBox = (AnchorDropBox)master; Anchor anchor = anchorDropBox.anchorValue; Window control = anchorDropBox.control; DataBox dropMaster = (DataBox)anchorDropBox.master; int id = button.id; if((id == 0 || id == 2) && ((!anchor.left.type && !anchor.right.type) || anchor.left.type == middleRelative)) { if(button.checked) anchor.horz.type = middleRelative; else anchor.horz.type = none; anchorDropBox.relButtons[(id + 2)%4].checked = button.checked; } else if((id == 1 || id == 3) && ((!anchor.top.type && !anchor.bottom.type) || anchor.top.type == middleRelative)) { if(button.checked) anchor.vert.type = middleRelative; else anchor.vert.type = none; anchorDropBox.relButtons[(id + 2)%4].checked = button.checked; } else { switch(id) { case 0: anchor.left.type = button.checked ? relative : (anchor.left.type ? offset : none); break; case 1: anchor.top.type = button.checked ? relative : (anchor.top.type ? offset : none); break; case 2: anchor.right.type = button.checked ? relative : (anchor.right.type ? offset : none); break; case 3: anchor.bottom.type = button.checked ? relative : (anchor.bottom.type ? offset : none); break; } anchorDropBox.buttons[id].checked = true; if(anchor.horz.type == middleRelative) anchor.horz.type = none; if(anchor.vert.type == middleRelative) anchor.vert.type = none; } { int vpw, vph; int x,y,w,h; Window parent = control.parent; // Fix Anchor x = control.position.x; y = control.position.y; w = control.size.w; h = control.size.h; vpw = parent.clientSize.w; vph = parent.clientSize.h; if(control.nonClient) { vpw = parent.size.w; vph = parent.size.h; } else if(((BorderBits)control.borderStyle).fixed) { if(!control.dontScrollHorz && parent.scrollArea.w) vpw = parent.scrollArea.w; if(!control.dontScrollVert && parent.scrollArea.h) vph = parent.scrollArea.h; } if(anchor.left.type == offset) anchor.left.distance = x; else if(anchor.left.type == relative) anchor.left.percent = (float)x / vpw; if(anchor.top.type == offset) anchor.top.distance = y; else if(anchor.top.type == relative) anchor.top.percent = (float)y / vph; if(anchor.right.type == offset) anchor.right.distance = vpw - (x + w); //else if(anchor.right.type == relative) anchor.right.percent = (float) (x + w) / vpw; else if(anchor.right.type == relative) anchor.right.percent = (float) (vpw - (x + w)) / vpw; if(anchor.bottom.type == offset) anchor.bottom.distance = vph - (y + h); //else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (y + h) / vph; else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (vph - (y + h)) / vph; if(!anchor.left.type && !anchor.right.type) { anchor.horz.distance = (x + w / 2) - (vpw / 2); //anchor.horz.type = anchor.horz.distance ? offset : none; } else if(anchor.horz.type == middleRelative) anchor.horz.percent = (float) ((x + w / 2) - (vpw / 2)) / vpw; if(!anchor.top.type && !anchor.bottom.type) { anchor.vert.distance = (y + h / 2) - (vph / 2); //anchor.vert.type = anchor.vert.distance ? offset : none; } else if(anchor.vert.type == middleRelative) anchor.vert.percent = (float)((y + h / 2) - (vph / 2)) / vph; } { char tempString[1024] = ""; bool needClass = false; char * string = anchor.OnGetString(tempString, null, &needClass); anchorDropBox.contents = string; } dropMaster.SetData(&anchor, false); anchorDropBox.anchorValue = anchor; return true; } } private class AnchorEditor : Window { interim = true; borderStyle = deepContour; size.h = 92; bool OnKeyDown(Key key, unichar ch) { if(key == escape) return master.OnKeyDown(key, ch); return true; } } private class AnchorDropBox : DropBox { Anchor anchorValue; Window control; Button relButtons[4], buttons[4]; AnchorEditor anchorEditor { master = this; autoCreate = false; }; Window OnDropDown() { int c; Button { anchorEditor, anchor = Anchor { left = 28, top = 28, right = 28, bottom = 28 }, inactive = true, disabled = true }; for(c = 0; c<4; c++) { Button button = buttons[c] = AnchorButton { anchorEditor, id = c, size = Size { (c%2)?10:28, (c%2)?28:10 } }; Button relButton = relButtons[c] = AnchorRelButton { anchorEditor, id = c; }; switch(c) { case 0: if(anchorValue.left.type && anchorValue.left.type != middleRelative) button.checked = true; if(anchorValue.left.type == relative || anchorValue.horz.type == middleRelative) relButton.checked = true; button.anchor = Anchor { left = 0 }; relButton.anchor = Anchor { left = 5, vert = 16 }; break; case 1: if(anchorValue.top.type && anchorValue.top.type != middleRelative) button.checked = true; if(anchorValue.top.type == relative || anchorValue.vert.type == middleRelative) relButton.checked = true; button.anchor = Anchor { top = 0 }; relButton.anchor = Anchor { top = 5, horz = 16 }; break; case 2: if(anchorValue.right.type && anchorValue.right.type != middleRelative) button.checked = true; if(anchorValue.right.type == relative || anchorValue.horz.type == middleRelative) relButton.checked = true; button.anchor = Anchor { right = 0 }; relButton.anchor = Anchor { right = 5, vert = 16 }; break; case 3: if(anchorValue.bottom.type && anchorValue.bottom.type != middleRelative) button.checked = true; if(anchorValue.bottom.type == relative || anchorValue.vert.type == middleRelative) relButton.checked = true; button.anchor = Anchor { bottom = 0 }; relButton.anchor = Anchor { bottom = 5, horz = 16 }; break; } } anchorEditor.Create(); return anchorEditor; } void OnCloseDropDown(Window anchorEditor) { // TOFIX: Patch for update bug master.Update(null); anchorEditor.Destroy(0); } bool DataBox::NotifyTextEntry(AnchorDropBox dropBox, char * string, bool save) { Anchor anchor = dropBox.anchorValue; Window control = dropBox.control; if(save) { if(anchor.OnGetDataFromString(string)) { SetData(&anchor, false); dropBox.anchorValue = anchor; } } else { char tempString[1024] = ""; bool needClass = false; char * string = anchor.OnGetString(tempString, null, &needClass); dropBox.contents = string; } return true; } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.ecl000066400000000000000000000050471250413007300253420ustar00rootroot00000000000000/*############################################################################## Copyright (C) 2011 HPCC Systems. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . ############################################################################## */ #option ('slidingJoins', true); namesRecord := RECORD string20 surname; string10 forename; integer2 age; integer2 dadAge; integer2 mumAge; END; namesRecord2 := record string10 extra; namesRecord; end; namesTable := dataset('x',namesRecord,FLAT); namesTable2 := dataset('y',namesRecord2,FLAT); integer2 aveAgeL(namesRecord l) := (l.dadAge+l.mumAge)/2; integer2 aveAgeR(namesRecord2 r) := (r.dadAge+r.mumAge)/2; // Standard join on a function of left and right output(join(namesTable, namesTable2, aveAgeL(left) = aveAgeR(right))); //Several simple examples of sliding join syntax output(join(namesTable, namesTable2, left.age >= right.age - 10 and left.age <= right.age +10)); output(join(namesTable, namesTable2, left.age between right.age - 10 and right.age +10)); output(join(namesTable, namesTable2, left.age between right.age + 10 and right.age +30)); output(join(namesTable, namesTable2, left.age between (right.age + 20) - 10 and (right.age +20) + 10)); output(join(namesTable, namesTable2, aveAgeL(left) between aveAgeR(right)+10 and aveAgeR(right)+40)); //Same, but on strings. Also includes age to ensure sort is done by non-sliding before sliding. output(join(namesTable, namesTable2, left.surname between right.surname[1..10]+'AAAAAAAAAA' and right.surname[1..10]+'ZZZZZZZZZZ' and left.age=right.age)); output(join(namesTable, namesTable2, left.surname between right.surname[1..10]+'AAAAAAAAAA' and right.surname[1..10]+'ZZZZZZZZZZ' and left.age=right.age,all)); //This should not generate a self join output(join(namesTable, namesTable, left.age between right.age - 10 and right.age +10)); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.eh000066400000000000000000000160651250413007300251750ustar00rootroot00000000000000/* A Bison parser, made by GNU Bison 2.0. */ /* Skeleton parser for Yacc-like parsing with Bison, Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* As a special exception, when this file is copied by Bison into a Bison output file, you may use that output file without restriction. This special exception was added by the Free Software Foundation in version 1.24 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { IDENTIFIER = 258, CONSTANT = 259, STRING_LITERAL = 260, SIZEOF = 261, PTR_OP = 262, INC_OP = 263, DEC_OP = 264, LEFT_OP = 265, RIGHT_OP = 266, LE_OP = 267, GE_OP = 268, EQ_OP = 269, NE_OP = 270, AND_OP = 271, OR_OP = 272, MUL_ASSIGN = 273, DIV_ASSIGN = 274, MOD_ASSIGN = 275, ADD_ASSIGN = 276, SUB_ASSIGN = 277, LEFT_ASSIGN = 278, RIGHT_ASSIGN = 279, AND_ASSIGN = 280, XOR_ASSIGN = 281, OR_ASSIGN = 282, TYPE_NAME = 283, TYPEDEF = 284, EXTERN = 285, STATIC = 286, AUTO = 287, REGISTER = 288, CHAR = 289, SHORT = 290, INT = 291, UINT = 292, INT64 = 293, LONG = 294, SIGNED = 295, UNSIGNED = 296, FLOAT = 297, DOUBLE = 298, CONST = 299, VOLATILE = 300, VOID = 301, VALIST = 302, STRUCT = 303, UNION = 304, ENUM = 305, ELLIPSIS = 306, CASE = 307, DEFAULT = 308, IF = 309, SWITCH = 310, WHILE = 311, DO = 312, FOR = 313, GOTO = 314, CONTINUE = 315, BREAK = 316, RETURN = 317, IFX = 318, ELSE = 319, CLASS = 320, THISCLASS = 321, CLASS_NAME = 322, PROPERTY = 323, SETPROP = 324, GETPROP = 325, NEWOP = 326, RENEW = 327, DELETE = 328, EXT_DECL = 329, EXT_STORAGE = 330, IMPORT = 331, DEFINE = 332, VIRTUAL = 333, EXT_ATTRIB = 334, PUBLIC = 335, PRIVATE = 336, TYPED_OBJECT = 337, ANY_OBJECT = 338, _INCREF = 339, EXTENSION = 340, ASM = 341, TYPEOF = 342, WATCH = 343, STOPWATCHING = 344, FIREWATCHERS = 345, WATCHABLE = 346, CLASS_DESIGNER = 347, CLASS_NO_EXPANSION = 348, CLASS_FIXED = 349, ISPROPSET = 350, CLASS_DEFAULT_PROPERTY = 351, PROPERTY_CATEGORY = 352, CLASS_DATA = 353, CLASS_PROPERTY = 354, SUBCLASS = 355, NAMESPACE = 356, NEW0OP = 357, RENEW0 = 358, VAARG = 359, DBTABLE = 360, DBFIELD = 361, DBINDEX = 362, DATABASE_OPEN = 363 }; #endif #define IDENTIFIER 258 #define CONSTANT 259 #define STRING_LITERAL 260 #define SIZEOF 261 #define PTR_OP 262 #define INC_OP 263 #define DEC_OP 264 #define LEFT_OP 265 #define RIGHT_OP 266 #define LE_OP 267 #define GE_OP 268 #define EQ_OP 269 #define NE_OP 270 #define AND_OP 271 #define OR_OP 272 #define MUL_ASSIGN 273 #define DIV_ASSIGN 274 #define MOD_ASSIGN 275 #define ADD_ASSIGN 276 #define SUB_ASSIGN 277 #define LEFT_ASSIGN 278 #define RIGHT_ASSIGN 279 #define AND_ASSIGN 280 #define XOR_ASSIGN 281 #define OR_ASSIGN 282 #define TYPE_NAME 283 #define TYPEDEF 284 #define EXTERN 285 #define STATIC 286 #define AUTO 287 #define REGISTER 288 #define CHAR 289 #define SHORT 290 #define INT 291 #define UINT 292 #define INT64 293 #define LONG 294 #define SIGNED 295 #define UNSIGNED 296 #define FLOAT 297 #define DOUBLE 298 #define CONST 299 #define VOLATILE 300 #define VOID 301 #define VALIST 302 #define STRUCT 303 #define UNION 304 #define ENUM 305 #define ELLIPSIS 306 #define CASE 307 #define DEFAULT 308 #define IF 309 #define SWITCH 310 #define WHILE 311 #define DO 312 #define FOR 313 #define GOTO 314 #define CONTINUE 315 #define BREAK 316 #define RETURN 317 #define IFX 318 #define ELSE 319 #define CLASS 320 #define THISCLASS 321 #define CLASS_NAME 322 #define PROPERTY 323 #define SETPROP 324 #define GETPROP 325 #define NEWOP 326 #define RENEW 327 #define DELETE 328 #define EXT_DECL 329 #define EXT_STORAGE 330 #define IMPORT 331 #define DEFINE 332 #define VIRTUAL 333 #define EXT_ATTRIB 334 #define PUBLIC 335 #define PRIVATE 336 #define TYPED_OBJECT 337 #define ANY_OBJECT 338 #define _INCREF 339 #define EXTENSION 340 #define ASM 341 #define TYPEOF 342 #define WATCH 343 #define STOPWATCHING 344 #define FIREWATCHERS 345 #define WATCHABLE 346 #define CLASS_DESIGNER 347 #define CLASS_NO_EXPANSION 348 #define CLASS_FIXED 349 #define ISPROPSET 350 #define CLASS_DEFAULT_PROPERTY 351 #define PROPERTY_CATEGORY 352 #define CLASS_DATA 353 #define CLASS_PROPERTY 354 #define SUBCLASS 355 #define NAMESPACE 356 #define NEW0OP 357 #define RENEW0 358 #define VAARG 359 #define DBTABLE 360 #define DBFIELD 361 #define DBINDEX 362 #define DATABASE_OPEN 363 #if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED) #line 42 "grammar.y" typedef union YYSTYPE { SpecifierType specifierType; int i; AccessMode declMode; Identifier id; Expression exp; Specifier specifier; OldList * list; Enumerator enumerator; Declarator declarator; Pointer pointer; Initializer initializer; InitDeclarator initDeclarator; TypeName typeName; Declaration declaration; Statement stmt; FunctionDefinition function; External external; Context context; AsmField asmField; Instantiation instance; MembersInit membersInit; MemberInit memberInit; ClassFunction classFunction; ClassDefinition _class; ClassDef classDef; PropertyDef prop; char * string; Symbol symbol; PropertyWatch propertyWatch; TemplateParameter templateParameter; TemplateArgument templateArgument; TemplateDatatype templateDatatype; DBTableEntry dbtableEntry; DBIndexItem dbindexItem; DBTableDef dbtableDef; } YYSTYPE; /* Line 1318 of yacc.c. */ #line 293 "grammar.eh" # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif extern YYSTYPE yylval; #if ! defined (YYLTYPE) && ! defined (YYLTYPE_IS_DECLARED) typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif extern YYLTYPE yylloc; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.erl000066400000000000000000000131621250413007300253560ustar00rootroot00000000000000-module(test). -export([listen/1, handle_client/1, maintain_clients/1, start/1, stop/0, controller/1]). -author("jerith"). -define(TCP_OPTIONS,[list, {packet, 0}, {active, false}, {reuseaddr, true}]). -record(player, {name=none, socket, mode}). %% To allow incoming connections, we need to listen on a TCP port. %% This is also the entry point for our server as a whole, so it %% starts the client_manager process and gives it a name so the rest %% of the code can get to it easily. listen(Port) -> {ok, LSocket} = gen_tcp:listen(Port, ?TCP_OPTIONS), register(client_manager, spawn(?MODULE, maintain_clients, [[]])), do_accept(LSocket). %% Accepting a connection gives us a connection socket with the %% newly-connected client on the other end. Since we want to accept %% more than one client, we spawn a new process for each and then wait %% for another connection on our listening socket. do_accept(LSocket) -> case gen_tcp:accept(LSocket) of {ok, Socket} -> spawn(?MODULE, handle_client, [Socket]), client_manager ! {connect, Socket}; {error, Reason} -> io:format("Socket accept error: ~s~n", [Reason]) end, do_accept(LSocket). %% All the client-socket process needs to do is wait for data and %% forward it to the client_manager process which decides what to do %% with it. If the client disconnects, we let client_manager know and %% then quietly go away. handle_client(Socket) -> case gen_tcp:recv(Socket, 0) of {ok, Data} -> client_manager ! {data, Socket, Data}, handle_client(Socket); {error, closed} -> client_manager ! {disconnect, Socket} end. %% This is the main loop of the client_manager process. It maintains %% the list of "players" and calls the handler for client input. maintain_clients(Players) -> io:format("Players:~n", []), lists:foreach(fun(P) -> io:format(">>> ~w~n", [P]) end, Players), receive {connect, Socket} -> Player = #player{socket=Socket, mode=connect}, send_prompt(Player), io:format("client connected: ~w~n", [Player]), NewPlayers = [Player | Players]; {disconnect, Socket} -> Player = find_player(Socket, Players), io:format("client disconnected: ~w~n", [Player]), NewPlayers = lists:delete(Player, Players); {data, Socket, Data} -> Player = find_player(Socket, Players), NewPlayers = parse_data(Player, Players, Data), NewPlayer = find_player(Socket, NewPlayers), send_prompt(NewPlayer) end, maintain_clients(NewPlayers). %% find_player is a utility function to get a player record associated %% with a particular socket out of the player list. find_player(Socket, Players) -> {value, Player} = lists:keysearch(Socket, #player.socket, Players), Player. %% delete_player returns the player list without the given player. It %% deletes the player from the list based on the socket rather than %% the whole record because the list might hold a different version. delete_player(Player, Players) -> lists:keydelete(Player#player.socket, #player.socket, Players). %% Sends an appropriate prompt to the player. Currently the only %% prompt we send is the initial "Name: " when the player connects. send_prompt(Player) -> case Player#player.mode of connect -> gen_tcp:send(Player#player.socket, "Name: "); active -> ok end. %% Sends the given data to all players in active mode. send_to_active(Prefix, Players, Data) -> ActivePlayers = lists:filter(fun(P) -> P#player.mode == active end, Players), lists:foreach(fun(P) -> gen_tcp:send(P#player.socket, Prefix ++ Data) end, ActivePlayers), ok. %% We don't really do much parsing, but that will probably change as %% more features are added. Currently this handles naming the player %% when he first connects and treats everything else as a message to %% send. parse_data(Player, Players, Data) -> case Player#player.mode of active -> send_to_active(Player#player.name ++ ": ", delete_player(Player, Players), Data), Players; connect -> UPlayer = Player#player{name=bogostrip(Data), mode=active}, [UPlayer | delete_player(Player, Players)] end. %% Utility methods to clean up the name before we apply it. Called %% bogostrip rather than strip because it returns the first continuous %% block of non-matching characters rather stripping matching %% characters off the front and back. bogostrip(String) -> bogostrip(String, "\r\n\t "). bogostrip(String, Chars) -> LStripped = string:substr(String, string:span(String, Chars)+1), string:substr(LStripped, 1, string:cspan(LStripped, Chars)). %% Here we have some extra code to test other bits of pygments' Erlang %% lexer. get_timestamp() -> {{Year,Month,Day},{Hour,Min,Sec}} = erlang:universaltime(), lists:flatten(io_lib:format( "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", [Year, Month, Day, Hour, Min, Sec])). a_binary() -> << 100:16/integer, 16#7f >>. a_list_comprehension() -> [X*2 || X <- [1,2,3]]. map(Fun, [H|T]) -> [Fun(H) | map(Fun, T)]; map(Fun, []) -> []. %% pmap, just because it's cool. pmap(F, L) -> Parent = self(), [receive {Pid, Result} -> Result end || Pid <- [spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]]. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.evoque000066400000000000000000000016301250413007300260750ustar00rootroot00000000000000$overlay{name=site_base} $begin{table_row} $for{ col in row } ${col}\ $else empty row $rof $end{table_row} $for{ i, row in enumerate(rows) } #[ "odd" rows get a special style ]# $evoque{#table_row} $evoque{ #table_row } $evoque{'#table_row'} $evoque{ '#table_row', collection=None, quoting="str"} $evoque{name="#table_row"} $evoque{name=var_table_row} $evoque{%#table_row%} $evoque{% #table_row %} $rof
    $evoque{disclaimer, collection="legals"} $evoque{ disclaimer , collection="legals", abc=123} $evoque{% disclaimer, collection="legals"%} $test{% site_base="site.html", rows=[("a", "b", 3.0, {"one":1}, "", "i", "j")] %} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.fan000077500000000000000000000613631250413007300253510ustar00rootroot00000000000000// // Copyright (c) 2008, Brian Frank and Andy Frank // Licensed under the Academic Free License version 3.0 // // History: // 17 Nov 08 Brian Frank Creation // using compiler ** ** JavaBridge is the compiler plugin for bringing Java ** classes into the Fantom type system. ** class JavaBridge : CBridge { ////////////////////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////////////////////////////////////// ** ** Construct a JavaBridge for current environment ** new make(Compiler c, ClassPath cp := ClassPath.makeForCurrent) : super(c) { this.cp = cp } ////////////////////////////////////////////////////////////////////////// // Namespace ////////////////////////////////////////////////////////////////////////// ** ** Map a FFI "podName" to a Java package. ** override CPod resolvePod(Str name, Loc? loc) { // the empty package is used to represent primitives if (name == "") return primitives // look for package name in classpatch classes := cp.classes[name] if (classes == null) throw CompilerErr("Java package '$name' not found", loc) // map package to JavaPod return JavaPod(this, name, classes) } ** ** Map class meta-data and Java members to Fantom slots ** for the specified JavaType. ** virtual Void loadType(JavaType type, Str:CSlot slots) { JavaReflect.loadType(type, slots) } ////////////////////////////////////////////////////////////////////////// // Call Resolution ////////////////////////////////////////////////////////////////////////// ** ** Resolve a construction call to a Java constructor. ** override Expr resolveConstruction(CallExpr call) { // if the last argument is an it-block, then we know // right away that we will not be passing it thru to Java, // so strip it off to be appended as call to Obj.with itBlock := call.args.last as ClosureExpr if (itBlock != null && itBlock.isItBlock) call.args.removeAt(-1) else itBlock = null // if this is an interop array like IntArray/int[] use make // factory otherwise look for Java constructor called JavaType base := call.target.ctype if (base.isInteropArray) call.method = base.method("make") else call.method = base.method("") // call resolution to deal with overloading call = resolveCall(call) // we need to create an implicit target for the Java runtime // to perform the new opcode to ensure it is on the stack // before the args (we don't do this for interop Array classes) if (!base.isInteropArray) { loc := call.loc call.target = CallExpr.makeWithMethod(loc, null, base.newMethod) { synthetic=true } } // if we stripped an it-block argument, // add it as trailing call to Obj.with if (itBlock != null) return itBlock.toWith(call) return call } ** ** Resolve a construction chain call where a Fantom constructor ** calls the super-class constructor. Type check the arguments ** and insert any conversions needed. ** override Expr resolveConstructorChain(CallExpr call) { // we don't allow chaining to a this ctor for Java FFI if (call.target.id !== ExprId.superExpr) throw err("Must use super constructor call in Java FFI", call.loc) // route to a superclass constructor JavaType base := call.target.ctype.deref call.method = base.method("") // call resolution to deal with overloading return resolveCall(call) } ** ** Given a dot operator slot access on the given foreign ** base type, determine the appopriate slot to use based on ** whether parens were used ** base.name => noParens = true ** base.name() => noParens = false ** ** In Java a given name could be bound to both a field and ** a method. In this case we only resolve the field if ** no parens are used. We also handle the special case of ** Java annotations here because their element methods are ** also mapped as Fantom fields (instance based mixin field). ** override CSlot? resolveSlotAccess(CType base, Str name, Bool noParens) { // first try to resolve as a field field := base.field(name) if (field != null) { // if no () we used and this isn't an annotation field if (noParens && (field.isStatic || !base.isMixin)) return field // if we did find a field, then make sure we use that // field's parent type to resolve a method (becuase the // base type might be a sub-class of a Java type in which // case it is unware of field/method overloads) return field.parent.method(name) } // lookup method return base.method(name) } ** ** Resolve a method call: try to find the best match ** and apply any coercions needed. ** override CallExpr resolveCall(CallExpr call) { // try to match against all the overloaded methods matches := CallMatch[,] CMethod? m := call.method while (m != null) { match := matchCall(call, m) if (match != null) matches.add(match) m = m is JavaMethod ? ((JavaMethod)m).next : null } // if we have exactly one match use then use that one if (matches.size == 1) return matches[0].apply(call) // if we have multiple matches; resolve to // most specific match according to JLS rules // TODO: this does not correct resolve when using Fantom implicit casting if (matches.size > 1) { best := resolveMostSpecific(matches) if (best != null) return best.apply(call) } // zero or multiple ambiguous matches is a compiler error s := StrBuf() s.add(matches.isEmpty ? "Invalid args " : "Ambiguous call ") s.add(call.name).add("(") s.add(call.args.join(", ") |Expr arg->Str| { return arg.toTypeStr }) s.add(")") throw err(s.toStr, call.loc) } ** ** Check if the call matches the specified overload method. ** If so return method and coerced args otherwise return null. ** internal CallMatch? matchCall(CallExpr call, CMethod m) { // first check if have matching numbers of args and params args := call.args if (m.params.size < args.size) return null // check if each argument is ok or can be coerced isErr := false newArgs := args.dup m.params.each |CParam p, Int i| { if (i >= args.size) { // param has a default value, then that is ok if (!p.hasDefault) isErr = true } else { // ensure arg fits parameter type (or auto-cast) newArgs[i] = coerce(args[i], p.paramType) |->| { isErr = true } } } if (isErr) return null return CallMatch { it.method = m; it.args = newArgs } } ** ** Given a list of overloaed methods find the most specific method ** according to Java Language Specification 15.11.2.2. The "informal ** intuition" rule is that a method is more specific than another ** if the first could be could be passed onto the second one. ** internal static CallMatch? resolveMostSpecific(CallMatch[] matches) { CallMatch? best := matches[0] for (i:=1; iBool| { bp := b.method.params[i] return ap.paramType.fits(bp.paramType) } } ////////////////////////////////////////////////////////////////////////// // Overrides ////////////////////////////////////////////////////////////////////////// ** ** Called during Inherit step when a Fantom slot overrides a FFI slot. ** Log and throw compiler error if there is a problem. ** override Void checkOverride(TypeDef t, CSlot base, SlotDef def) { // we don't allow Fantom to override Java methods with multiple // overloaded versions since the Fantom type system can't actually // override all the overloaded versions jslot := base as JavaSlot if (jslot?.next != null) throw err("Cannot override Java overloaded method: '$jslot.name'", def.loc) // route to method override checking if (base is JavaMethod && def is MethodDef) checkMethodOverride(t, base, def) } ** ** Called on method/method overrides in the checkOverride callback. ** private Void checkMethodOverride(TypeDef t, JavaMethod base, MethodDef def) { // bail early if we know things aren't going to work out if (base.params.size != def.params.size) return // if the return type is primitive or Java array and the // Fantom declaration matches how it is inferred into the Fan // type system, then just change the return type - the compiler // will impliclty do all the return coercions if (isOverrideInferredType(base.returnType, def.returnType)) { def.ret = def.inheritedRet = base.returnType } // if any of the parameters is a primitive or Java array // and the Fantom declaration matches how it is inferred into // the Fantom type type, then change the parameter type to // the Java override type and make the Fantom type a local // variable: // Java: void foo(int a) { ... } // Fantom: Void foo(Int a) { ... } // Result: Void foo(int a_$J) { Int a := a_$J; ... } // base.params.eachr |CParam bp, Int i| { dp := def.paramDefs[i] if (!isOverrideInferredType(bp.paramType, dp.paramType)) return // add local variable: Int bar := bar_$J local := LocalDefStmt(def.loc) local.ctype = dp.paramType local.name = dp.name local.init = UnknownVarExpr(def.loc, null, dp.name + "_\$J") def.code.stmts.insert(0, local) // rename parameter Int bar -> int bar_$J dp.name = dp.name + "_\$J" dp.paramType = bp.paramType } } ** ** When overriding a Java method check if the base type is ** is a Java primitive or array and the override definition is ** matches how the Java type is inferred in the Fantom type system. ** If we have a match return true and we'll swizzle things in ** checkMethodOverride. ** static private Bool isOverrideInferredType(CType base, CType def) { // check if base class slot is a JavaType java := base.toNonNullable as JavaType if (java != null) { // allow primitives is it matches the inferred type if (java.isPrimitive) return java.inferredAs == def // allow arrays if mapped as Foo[] -> Foo?[]? if (java.isArray) return java.inferredAs == def.toNonNullable && def.isNullable } return false } ////////////////////////////////////////////////////////////////////////// // CheckErrors ////////////////////////////////////////////////////////////////////////// ** ** Called during CheckErrors step for a type which extends ** a FFI class or implements any FFI mixins. ** override Void checkType(TypeDef def) { // can't subclass a primitive array like ByteArray/byte[] if (def.base.deref is JavaType && def.base.deref->isInteropArray) { err("Cannot subclass from Java interop array: $def.base", def.loc) return } // we don't allow deep inheritance of Java classes because // the Fantom constructor and Java constructor model don't match // up past one level of inheritance // NOTE: that that when we remove this restriction we need to // test how field initialization works because instance$init // is almost certain to break with the current emit design javaBase := def.base while (javaBase != null && !javaBase.isForeign) javaBase = javaBase.base if (javaBase != null && javaBase !== def.base) { err("Cannot subclass Java class more than one level: $javaBase", def.loc) return } // ensure that when we map Fantom constructors to Java // constructors that we don't have duplicate signatures ctors := def.ctorDefs ctors.each |MethodDef a, Int i| { ctors.each |MethodDef b, Int j| { if (i > j && areParamsSame(a, b)) err("Duplicate Java FFI constructor signatures: '$b.name' and '$a.name'", a.loc) } } } ** ** Do the two methods have the exact same parameter types. ** static Bool areParamsSame(CMethod a, CMethod b) { if (a.params.size != b.params.size) return false for (i:=0; i| { fits=false } return fits } ** ** Coerce expression to expected type. If not a type match ** then run the onErr function. ** override Expr coerce(Expr expr, CType expected, |->| onErr) { // handle easy case actual := expr.ctype expected = expected.deref if (actual == expected) return expr // handle null literal if (expr.id === ExprId.nullLiteral && expected.isNullable) return expr // handle Fantom to Java primitives if (expected.pod == primitives) return coerceToPrimitive(expr, expected, onErr) // handle Java primitives to Fan if (actual.pod == primitives) return coerceFromPrimitive(expr, expected, onErr) // handle Java array to Fantom list if (actual.name[0] == '[') return coerceFromArray(expr, expected, onErr) // handle Fantom list to Java array if (expected.name[0] == '[') return coerceToArray(expr, expected, onErr) // handle sys::Func -> Java interface if (actual is FuncType && expected.isMixin && expected.toNonNullable is JavaType) return coerceFuncToInterface(expr, expected.toNonNullable, onErr) // handle special classes and interfaces for built-in Fantom // classes which actually map directly to Java built-in types if (actual.isBool && boolTypes.contains(expected.toNonNullable.signature)) return box(expr) if (actual.isInt && intTypes.contains(expected.toNonNullable.signature)) return box(expr) if (actual.isFloat && floatTypes.contains(expected.toNonNullable.signature)) return box(expr) if (actual.isDecimal && decimalTypes.contains(expected.toNonNullable.signature)) return expr if (actual.isStr && strTypes.contains(expected.toNonNullable.signature)) return expr // use normal Fantom coercion behavior return super.coerce(expr, expected, onErr) } ** ** Ensure value type is boxed. ** private Expr box(Expr expr) { if (expr.ctype.isVal) return TypeCheckExpr.coerce(expr, expr.ctype.toNullable) else return expr } ** ** Coerce a fan expression to a Java primitive (other ** than the ones we support natively) ** Expr coerceToPrimitive(Expr expr, JavaType expected, |->| onErr) { actual := expr.ctype // sys::Int (long) -> int, short, byte if (actual.isInt && expected.isPrimitiveIntLike) return TypeCheckExpr.coerce(expr, expected) // sys::Float (double) -> float if (actual.isFloat && expected.isPrimitiveFloat) return TypeCheckExpr.coerce(expr, expected) // no coercion - type error onErr() return expr } ** ** Coerce a Java primitive to a Fantom type. ** Expr coerceFromPrimitive(Expr expr, CType expected, |->| onErr) { actual := (JavaType)expr.ctype // int, short, byte -> sys::Int (long) if (actual.isPrimitiveIntLike) { if (expected.isInt || expected.isObj) return TypeCheckExpr.coerce(expr, expected) } // float -> sys::Float (float) if (actual.isPrimitiveFloat) { if (expected.isFloat || expected.isObj) return TypeCheckExpr.coerce(expr, expected) } // no coercion - type error onErr() return expr } ** ** Coerce a Java array to a Fantom list. ** Expr coerceFromArray(Expr expr, CType expected, |->| onErr) { actual := (JavaType)expr.ctype.toNonNullable // if expected is array type if (expected is JavaType && ((JavaType)expected).isArray) if (actual.arrayOf.fits(((JavaType)expected).arrayOf)) return expr // if expected is Obj if (expected.isObj) return arrayToList(expr, actual.inferredArrayOf) // if expected is list type if (expected.toNonNullable is ListType) { expectedOf := ((ListType)expected.toNonNullable).v if (actual.inferredArrayOf.fits(expectedOf)) return arrayToList(expr, expectedOf) } // no coercion available onErr() return expr } ** ** Generate List.make(of, expr) where expr is Object[] ** private Expr arrayToList(Expr expr, CType of) { loc := expr.loc ofExpr := LiteralExpr(loc, ExprId.typeLiteral, ns.typeType, of) call := CallExpr.makeWithMethod(loc, null, listMakeFromArray, [ofExpr, expr]) call.synthetic = true return call } ** ** Coerce a Fantom list to Java array. ** Expr coerceToArray(Expr expr, CType expected, |->| onErr) { loc := expr.loc expectedOf := ((JavaType)expected.toNonNullable).inferredArrayOf actual := expr.ctype // if actual is list type if (actual.toNonNullable is ListType) { actualOf := ((ListType)actual.toNonNullable).v if (actualOf.fits(expectedOf)) { // (Foo[])list.asArray(cls) clsLiteral := CallExpr.makeWithMethod(loc, null, JavaType.classLiteral(this, expectedOf)) asArray := CallExpr.makeWithMethod(loc, expr, listAsArray, [clsLiteral]) return TypeCheckExpr.coerce(asArray, expected) } } // no coercion available onErr() return expr } ** ** Attempt to coerce a parameterized sys::Func expr to a Java ** interface if the interface supports exactly one matching method. ** Expr coerceFuncToInterface(Expr expr, JavaType expected, |->| onErr) { // check if we have exactly one abstract method in the expected type loc := expr.loc abstracts := expected.methods.findAll |CMethod m->Bool| { return m.isAbstract } if (abstracts.size != 1) { onErr(); return expr } method := abstracts.first // check if we have a match FuncType funcType := (FuncType)expr.ctype if (!isFuncToInterfaceMatch(funcType, method)) { onErr(); return expr } // check if we've already generated a wrapper for this combo key := "${funcType.signature}+${method.qname}" ctor := funcWrappers[key] if (ctor == null) { ctor = generateFuncToInterfaceWrapper(expr.loc, funcType, expected, method) funcWrappers[key] = ctor } // replace expr with FuncWrapperX(expr) call := CallExpr.makeWithMethod(loc, null, ctor, [expr]) call.synthetic = true return call } ** ** Return if the specified function type can be used to implement ** the specified interface method. ** Bool isFuncToInterfaceMatch(FuncType funcType, CMethod method) { // sanity check to map to callX method - can't handle more than 8 args if (method.params.size > 8) return false // check if method is match for function; first check is that // method must supply all the arguments required by the function if (funcType.params.size > method.params.size) return false // check that func return type fits method return retOk := method.returnType.isVoid || fits(funcType.ret, method.returnType) if (!retOk) return false // check all the method parameters fit the function parameters paramsOk := funcType.params.all |CType f, Int i->Bool| { return fits(f, method.params[i].paramType) } if (!paramsOk) return false return true } ** ** Generate the wrapper which implements the specified expected interface ** and overrides the specified method which calls the function. ** CMethod generateFuncToInterfaceWrapper(Loc loc, FuncType funcType, CType expected, CMethod method) { // Fantom: func typed as |Str| // Java: interface Foo { void bar(String) } // Result: FuncWrapperX(func) // // class FuncWrapperX : Foo // { // new make(Func f) { _func = f } // override Void bar(Str a) { _func.call(a) } // Func _func // } // generate FuncWrapper class name := "FuncWrapper" + funcWrappers.size cls := TypeDef(ns, loc, compiler.types[0].unit, name, FConst.Internal + FConst.Synthetic) cls.base = ns.objType cls.mixins = [expected] addTypeDef(cls) // generate FuncWrapper._func field field := FieldDef(loc, cls) ((SlotDef)field).name = "_func" ((DefNode)field).flags = FConst.Private + FConst.Storage + FConst.Synthetic field.fieldType = funcType cls.addSlot(field) // generate FuncWrapper.make constructor ctor := MethodDef(loc, cls, "make", FConst.Internal + FConst.Ctor + FConst.Synthetic) ctor.ret = ns.voidType ctor.paramDefs = [ParamDef(loc, funcType, "f")] ctor.code = Block.make(loc) ctor.code.stmts.add(BinaryExpr.makeAssign( FieldExpr(loc, ThisExpr(loc), field), UnknownVarExpr(loc, null, "f")).toStmt) ctor.code.stmts.add(ReturnStmt.make(loc)) cls.addSlot(ctor) // generate FuncWrapper override of abstract method over := MethodDef(loc, cls, method.name, FConst.Public + FConst.Override + FConst.Synthetic) over.ret = method.returnType over.paramDefs = ParamDef[,] over.code = Block.make(loc) callArity := "call" call := CallExpr.makeWithMethod(loc, FieldExpr(loc, ThisExpr(loc), field), funcType.method(callArity)) method.params.each |CParam param, Int i| { paramName := "p$i" over.params.add(ParamDef(loc, param.paramType, paramName)) if (i < funcType.params.size) call.args.add(UnknownVarExpr(loc, null, paramName)) } if (method.returnType.isVoid) over.code.stmts.add(call.toStmt).add(ReturnStmt(loc)) else over.code.stmts.add(ReturnStmt(loc, call)) cls.addSlot(over) // return the ctor which we use for coercion return ctor } ////////////////////////////////////////////////////////////////////////// // Reflection ////////////////////////////////////////////////////////////////////////// ** ** Get a CMethod representation for 'List.make(Type, Object[])' ** once CMethod listMakeFromArray() { return JavaMethod( this.ns.listType, "make", FConst.Public + FConst.Static, this.ns.listType.toNullable, [ JavaParam("of", this.ns.typeType), JavaParam("array", objectArrayType) ]) } ** ** Get a CMethod representation for 'Object[] List.asArray()' ** once CMethod listAsArray() { return JavaMethod( this.ns.listType, "asArray", FConst.Public, objectArrayType, [JavaParam("cls", classType)]) } ** ** Get a CType representation for 'java.lang.Class' ** once JavaType classType() { return ns.resolveType("[java]java.lang::Class") } ** ** Get a CType representation for 'java.lang.Object[]' ** once JavaType objectArrayType() { return ns.resolveType("[java]java.lang::[Object") } ////////////////////////////////////////////////////////////////////////// // Fields ////////////////////////////////////////////////////////////////////////// const static Str[] boolTypes := Str[ "[java]java.io::Serializable", "[java]java.lang::Comparable", ] const static Str[] intTypes := Str[ "[java]java.lang::Number", "[java]java.io::Serializable", "[java]java.lang::Comparable", ] const static Str[] floatTypes := Str[ "[java]java.lang::Number", "[java]java.io::Serializable", "[java]java.lang::Comparable", ] const static Str[] decimalTypes := Str[ "[java]java.lang::Number", "[java]java.io::Serializable", "[java]java.lang::Comparable", ] const static Str[] strTypes := Str[ "[java]java.io::Serializable", "[java]java.lang::CharSequence", "[java]java.lang::Comparable", ] JavaPrimitives primitives := JavaPrimitives(this) ClassPath cp private Str:CMethod funcWrappers := Str:CMethod[:] // funcType+method:ctor } ************************************************************************** ** CallMatch ************************************************************************** internal class CallMatch { CallExpr apply(CallExpr call) { call.args = args call.method = method call.ctype = method.isCtor ? method.parent : method.returnType return call } override Str toStr() { return method.signature } CMethod? method // matched method Expr[]? args // coerced arguments }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.flx000066400000000000000000000016231250413007300253640ustar00rootroot00000000000000type tiny = "%i8"; type int = "%i32"; typedef bool = 2; fun add : int*int -> int = "%add"; fun sub : int*int -> int = "%sub"; fun eq : int*int -> bool = "%eq"; fun lnot : bool -> bool = "%lnot"; proc exit : int = "exit"; // comment 1 /* /* foo bar */ asdas */ noinline fun foo (x:int) = { val y = 6; return x + y; } noinline proc fake_exit (x:int) { exit x; return; } noinline fun bar (x:int) = { var y = 10; noinline proc baz () { y = 20; return; } baz (); return x + y; } noinline fun x (a:int, b:int, c:tiny) = { val x1 = a; val x2 = b; val x3 = c; noinline fun y (d:int, e:int, f:tiny) = { val y1 = x1; val y2 = x2; val y3 = f; noinline fun z (g:int, h:int, i:tiny) = { val z1 = x1; val z2 = x2; val z3 = i; return z1; } return z (y1,y2,y3); } return y (x1,x2,x3); } fake_exit $ (foo 2) + (bar 3) + (x (1,2,3t)); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.gdc000066400000000000000000000012171250413007300253270ustar00rootroot00000000000000# Execute the date dimension MAQL script ExecuteMaql(maqlFile="examples/quotes/quote_date.maql"); # load the stock quotes data file # the data file config has been generated LoadCsv(csvDataFile="examples/quotes/quotes.csv", header="true", configFile="examples/quotes/quotes.config.xml"); # transfer the stock quotes data TransferLastSnapshot(); LoadGoogleAnalytics(configFile="examples/ga/ga.config.xml",username="example@gmail.com",password="******",profileId="ga:7468896",dimensions="ga:date|ga:browser|ga:browserVersion|ga:country|ga:isMobile",metrics="ga:bounces|ga:newVisits|ga:pageViews|ga:visits",startDate="2008-01-01",endDate="2010-06-15"); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.groovy000066400000000000000000000047561250413007300261320ustar00rootroot00000000000000// This source code comes from http://www.odelia-technologies.com/node/200 package com.odelia.groovy.simpleworkflow class SimpleWorkflowEngine { def workflowMap = [:] def context = [:] def beforeActivityName = 'beforeActivity' def afterActivityName = 'afterActivity' SimpleWorkflowEngine(workflow, context = [:]) { this.context = context parseWorkflow(workflow) } def parseWorkflow(workflow) { workflowMap = new WorkflowParser().parse(workflow) } def getActivityValue(activity) { assert activity instanceof String if (!workflowMap[activity]) throw new RuntimeException("$activity activity doesn't exist") workflowMap[activity] } def execute(activity, pause) { if (workflowMap[beforeActivityName]) { getActivityValue(beforeActivityName)(context, activity) } def activityValue = getActivityValue(activity) // Determine the next activity to execute def nextActivity switch (activityValue) { case String: nextActivity = activityValue; break case Closure: nextActivity = activityValue(context); break case Class: nextActivity = activityValue.newInstance()(context) } if (workflowMap[afterActivityName]) { getActivityValue(afterActivityName)(context, activity, nextActivity) } if (!pause && nextActivity) call(nextActivity) else nextActivity } def call(activity) { execute(activity, false) } def nextActivity(activity) { execute(activity, true) } static void main(String[] args) { if (args.size() != 2) { println 'Usage: com.odelia.groovy.simpleworkflow.SimpleWorkflowEngine ' return } SimpleWorkflowEngine.newInstance(new File(args[0]))(args[1]) } } private class WorkflowParser { def map = [:] def methodMissing(String name, args) { map[name] = args[0] } def parse(Closure wf) { wf.delegate = this wf.resolveStrategy = Closure.DELEGATE_FIRST wf() map } def workflow = { it -> it.delegate = this it.resolveStrategy = Closure.DELEGATE_FIRST it() } def parse(File workflowDef) { def binding = new Binding([workflow: workflow]) def shell = new GroovyShell(binding) shell.evaluate(workflowDef) map } }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.html000066400000000000000000001053421250413007300255420ustar00rootroot00000000000000
    # -*- coding: utf-8 -*-
    """
        pocoo.pkg.core.acl
        ~~~~~~~~~~~~~~~~~~
    
        Pocoo ACL System.
    
    """
    
    from pocoo.db import meta
    
    from pocoo.pkg.core.forum import Site, Forum, Thread
    from pocoo.pkg.core.user import User, Group
    
    from pocoo.pkg.core.db import users, groups, group_members, privileges, \
         forums, posts, acl_mapping, acl_subjects, acl_objects
    
    
    class AclManager(object):
        """
        Manager object to manage ALCs.
        """
        STRONG_NO = -1
    
        WEAK_NO = 0
        WEAK_YES = 1
        STRONG_YES = 2
    
        def __init__(self, ctx, subject):
            self.ctx = ctx
    
            self.subject = subject
            if isinstance(subject, User):
                self._type = 'user'
    
            elif isinstance(subject, Group):
                self._type = 'group'
    
            else:
                raise ValueError('neither user or group specified')
    
        def allow(self, privilege, obj, force=False):
            """Allows the subject privilege on obj."""
    
            return self._set(privilege, obj, 1 + bool(force))
    
        def default(self, privilege, obj):
            """Sets the state for privilege on obj back to weak yes."""
    
            return self._set(privilege, obj, 0)
    
        def deny(self, privilege, obj, force=False):
            """Denies the subject privilege on obj."""
    
            return self._set(privilege, obj, -1 - bool(force))
    
        def can_access(self, privilege, obj):
            """Checks if the current subject with the required privilege
            somehow. Either directly or when the subject is a user and
            one of its groups can access it."""
    
            #XXX: maybe this could be one big query instead of 4
            #XXX: this currently does not work correctly, therefore return True
            return True
    
            if not isinstance(obj, (Forum, Thread, Site.__class__)):
                raise TypeError('obj must be a forum, thread or site')
            privilege = privilege.upper()
            s = self._get_subject_join().alias('s').c
    
            def do_check(obj, tendency):
                db = self.ctx.engine
    
                o = self._get_object_join(obj).alias('o').c
    
                # self check
                r = db.execute(meta.select([acl_mapping.c.state],
                    (acl_mapping.c.priv_id == privileges.c.priv_id) &
    
                    (acl_mapping.c.subject_id == s.subject_id) &
                    (acl_mapping.c.object_id == o.object_id) &
    
                    (privileges.c.name == privilege)
                ))
                row = r.fetchone()
                if row is not None:
                    if row['state'] in (self.STRONG_NO, self.STRONG_YES):
                        return row['state'] == self.STRONG_YES
    
                    tendency = row['state']
    
                # if the controlled subject is a user check all groups
                if isinstance(self.subject, User):
                    r = db.execute(meta.select([acl_mapping.c.state],
                        (acl_mapping.c.object_id == o.object_id) &
    
                        (acl_mapping.c.subject_id == groups.c.subject_id) &
    
                        (groups.c.group_id == group_members.c.group_id) &
    
                        (group_members.c.user_id == self.subject.user_id)
                    ))
                    while True:
                        row = r.fetchone()
                        if row is None:
                            break
    
                        state = row[0]
                        if state in (self.STRONG_YES, self.STRONG_NO):
                            return state == self.STRONG_YES
    
                        if tendency is None:
                            tendency = state
                        elif tendency == self.WEAK_NO and state == self.WEAK_YES:
                            tendency = self.WEAK_YES
    
                # check related objects
                if isinstance(obj, Thread):
                    return do_check(obj.forum, tendency)
                elif isinstance(obj, Forum):
                    return do_check(Site, tendency)
                else:
                    return tendency
    
            return do_check(obj, None) in (self.WEAK_YES, self.STRONG_YES)
    
        def _set(self, privilege, obj, state):
            """Helper functions for settings privileges."""
    
            privilege = privilege.upper()
            if self.subject.subject_id is None:
                self._bootstrap()
            if obj.object_id is None:
                self._bootstrap_object(obj)
            # special state "0" which means delete
    
            if not state:
                p = meta.select([privileges.c.priv_id], privileges.c.name == privilege)
                self.ctx.engine.execute(acl_mapping.delete(
                    (acl_mapping.c.priv_id == p.c.priv_id) &
    
                    (acl_mapping.c.subject_id == self.subject.subject_id) &
    
                    (acl_mapping.c.object_id == obj.object_id)
                ))
                return
            # touch privilege and check existing mapping
    
            priv_id = self._fetch_privilege(privilege)
            r = self.ctx.engine.execute(meta.select([acl_mapping.c.state],
                (acl_mapping.c.priv_id == priv_id) &
    
                (acl_mapping.c.subject_id == self.subject.subject_id) &
    
                (acl_mapping.c.object_id == obj.object_id)
            ))
            row = r.fetchone()
            if row is not None:
                # this rule exists already
    
                if row['state'] == state:
                    return
                # goddamn, same rule - different state, delete old first
                self._set(privilege, obj, 0)
            # insert new rule
    
            self.ctx.engine.execute(acl_mapping.insert(),
                priv_id = priv_id,
                subject_id = self.subject.subject_id,
                object_id = obj.object_id,
                state = state
    
            )
    
        def _bootstrap(self):
            """This method is automatically called when subject_id is
            None and an subject_id is required."""
            r = self.ctx.engine.execute(acl_subjects.insert(),
                subject_type = self._type
    
            )
            self.subject.subject_id = r.last_inserted_ids()[0]
            self.subject.save()
    
        def _bootstrap_object(self, obj):
            """Like _bootstrap but works for objects."""
    
            objtype = self._get_object_type(obj)
            r = self.ctx.engine.execute(acl_objects.insert(),
                object_type = objtype
    
            )
            obj.object_id = r.last_inserted_ids()[0]
            obj.save()
    
        def _get_object_type(self, obj):
            if isinstance(obj, Forum):
                return 'forum'
    
            elif isinstance(obj, Thread):
                return 'thread'
            elif obj is Site:
                return 'site'
    
            raise TypeError('obj isn\'t a forum or thread')
    
        def _get_object_join(self, obj):
            """Returns a subjoin for the object id."""
    
            t = self._get_object_type(obj)
            if t == 'forum':
                return meta.select([forums.c.object_id],
                    forums.c.forum_id == obj.forum_id
    
                )
            elif t == 'thread':
                return meta.select([posts.c.object_id],
                    posts.c.post_id == obj.post_id
    
                )
            else:
                # XXX: it works ^^
                # i really want something like meta.select('0 as group_id')
                class Fake(object):
                    def alias(self, n):
                        class _C(object):
                            class c(object):
                                object_id = 0
    
                        return _C
                return Fake()
    
        def _get_subject_join(self):
            """Returns a subjoin for the subject id."""
    
            if self._type == 'user':
                return meta.select([users.c.subject_id],
                    users.c.user_id == self.subject.user_id
    
                )
            return meta.select([groups.c.subject_id],
                groups.c.group_id == self.subject.group_id
    
            )
    
        def _fetch_privilege(self, name):
            """Returns the priv_id for the given privilege. If it
            doesn\'t exist by now the system will create a new
            privilege."""
            r = self.ctx.engine.execute(meta.select([privileges.c.priv_id],
                privileges.c.name == name
    
            ))
            row = r.fetchone()
            if row is not None:
                return row[0]
            r = self.ctx.engine.execute(privileges.insert(),
                name = name
    
            )
            return r.last_inserted_ids()[0]
    
        def __repr__(self):
            if self._type == 'user':
                id_ = self.subject.user_id
    
            else:
                id_ = self.subject.group_id
            if self.subject.subject_id is None:
                return '<%s %s:%d inactive>' % (
                    self.__class__.__name__,
                    self._type,
                    id_
    
                )
            return '<%s %s:%d active as %d>' % (
                self.__class__.__name__,
                self._type,
                id_,
                self.subject.subject_id
    
            )
    
    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.idr000066400000000000000000000050371250413007300253540ustar00rootroot00000000000000module Main
    
    data Ty = TyInt | TyBool | TyFun Ty Ty
    
    interpTy : Ty -> Type
    interpTy TyInt       = Int
    interpTy TyBool      = Bool
    interpTy (TyFun s t) = interpTy s -> interpTy t
    
    using (G : Vect n Ty)
    
      data Env : Vect n Ty -> Type where
          Nil  : Env Nil
          (::) : interpTy a -> Env G -> Env (a :: G)
    
      data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where
          stop : HasType fZ (t :: G) t
          pop  : HasType k G t -> HasType (fS k) (u :: G) t
    
      lookup : HasType i G t -> Env G -> interpTy t
      lookup stop    (x :: xs) = x
      lookup (pop k) (x :: xs) = lookup k xs
    
      data Expr : Vect n Ty -> Ty -> Type where
          Var : HasType i G t -> Expr G t
          Val : (x : Int) -> Expr G TyInt
          Lam : Expr (a :: G) t -> Expr G (TyFun a t)
          App : Expr G (TyFun a t) -> Expr G a -> Expr G t
          Op  : (interpTy a -> interpTy b -> interpTy c) -> Expr G a -> Expr G b ->
                Expr G c
          If  : Expr G TyBool -> Expr G a -> Expr G a -> Expr G a
          Bind : Expr G a -> (interpTy a -> Expr G b) -> Expr G b
    
      dsl expr
          lambda      = Lam
          variable    = Var
          index_first = stop
          index_next  = pop
    
      (<$>) : |(f : Expr G (TyFun a t)) -> Expr G a -> Expr G t
      (<$>) = \f, a => App f a
    
      pure : Expr G a -> Expr G a
      pure = id
    
      syntax IF [x] THEN [t] ELSE [e] = If x t e
    
      (==) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool
      (==) = Op (==)
    
      (<) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool
      (<) = Op (<)
    
      instance Num (Expr G TyInt) where
        (+) x y = Op (+) x y
        (-) x y = Op (-) x y
        (*) x y = Op (*) x y
    
        abs x = IF (x < 0) THEN (-x) ELSE x
    
        fromInteger = Val . fromInteger
    
      interp : Env G -> {static} Expr G t -> interpTy t
      interp env (Var i)     = lookup i env
      interp env (Val x)     = x
      interp env (Lam sc)    = \x => interp (x :: env) sc
      interp env (App f s)   = (interp env f) (interp env s)
      interp env (Op op x y) = op (interp env x) (interp env y)
      interp env (If x t e)  = if (interp env x) then (interp env t) else (interp env e)
      interp env (Bind v f)  = interp env (f (interp env v))
    
      eId : Expr G (TyFun TyInt TyInt)
      eId = expr (\x => x)
    
      eTEST : Expr G (TyFun TyInt (TyFun TyInt TyInt))
      eTEST = expr (\x, y => y)
    
      eAdd : Expr G (TyFun TyInt (TyFun TyInt TyInt))
      eAdd = expr (\x, y => Op (+) x y)
    
      eDouble : Expr G (TyFun TyInt TyInt)
      eDouble = expr (\x => App (App eAdd x) (Var stop))
    
      eFac : Expr G (TyFun TyInt TyInt)
      eFac = expr (\x => IF x == 0 THEN 1 ELSE [| eFac (x - 1) |] * x)
    
    testFac : Int
    testFac = interp [] eFac 4
    
    main : IO ()
    main = print testFac
    
    
    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.ini000066400000000000000000000001201250413007300253410ustar00rootroot00000000000000[section]
    
    foo = bar
    continued = foo
      baz
    conttwo =
      foo
    ; comment
    # comment
    
    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.java000066400000000000000000000457511250413007300255260ustar00rootroot00000000000000/*
     * Created on 13-Mar-2004
     * Created by James Yeh
     * Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved.
     *
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * as published by the Free Software Foundation; either version 2
     * of the License, or (at your option) any later version.
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
     * 
     * AELITIS, SAS au capital de 46,603.30 euros
     * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
     *
     */
    
    package org.gudy.azureus2.platform.macosx;
    
    import org.gudy.azureus2.core3.logging.*;
    import org.gudy.azureus2.core3.util.AEMonitor;
    import org.gudy.azureus2.core3.util.Debug;
    import org.gudy.azureus2.core3.util.SystemProperties;
    import org.gudy.azureus2.platform.PlatformManager;
    import org.gudy.azureus2.platform.PlatformManagerCapabilities;
    import org.gudy.azureus2.platform.PlatformManagerListener;
    import org.gudy.azureus2.platform.macosx.access.jnilib.OSXAccess;
    
    import org.gudy.azureus2.plugins.platform.PlatformManagerException;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.text.MessageFormat;
    import java.util.HashSet;
    
    
    /**
     * Performs platform-specific operations with Mac OS X
     *
     * @author James Yeh
     * @version 1.0 Initial Version
     * @see PlatformManager
     */
    public class PlatformManagerImpl implements PlatformManager
    {
        private static final LogIDs LOGID = LogIDs.CORE;
    
        protected static PlatformManagerImpl singleton;
        protected static AEMonitor class_mon = new AEMonitor("PlatformManager");
    
        private static final String USERDATA_PATH = new File(System.getProperty("user.home") + "/Library/Application Support/").getPath();
    
        //T: PlatformManagerCapabilities
        private final HashSet capabilitySet = new HashSet();
    
        /**
         * Gets the platform manager singleton, which was already initialized
         */
        public static PlatformManagerImpl getSingleton()
        {
            return singleton;
        }
    
        /**
         * Tries to enable cocoa-java access and instantiates the singleton
         */
        static
        {
            initializeSingleton();
        }
    
        /**
         * Instantiates the singleton
         */
        private static void initializeSingleton()
        {
            try
            {
                class_mon.enter();
                singleton = new PlatformManagerImpl();
            }
            catch (Throwable e)
            {
            	Logger.log(new LogEvent(LOGID, "Failed to initialize platform manager"
    					+ " for Mac OS X", e));
            }
            finally
            {
                class_mon.exit();
            }
        }
    
        /**
         * Creates a new PlatformManager and initializes its capabilities
         */
        public PlatformManagerImpl()
        {
            capabilitySet.add(PlatformManagerCapabilities.RecoverableFileDelete);
            capabilitySet.add(PlatformManagerCapabilities.ShowFileInBrowser);
            capabilitySet.add(PlatformManagerCapabilities.ShowPathInCommandLine);
            capabilitySet.add(PlatformManagerCapabilities.CreateCommandLineProcess);
            capabilitySet.add(PlatformManagerCapabilities.GetUserDataDirectory);
            capabilitySet.add(PlatformManagerCapabilities.UseNativeScripting);
            capabilitySet.add(PlatformManagerCapabilities.PlaySystemAlert);
            
            if (OSXAccess.isLoaded()) {
    	        capabilitySet.add(PlatformManagerCapabilities.GetVersion);
            }
        }
    
        /**
         * {@inheritDoc}
         */
        public int getPlatformType()
        {
            return PT_MACOSX;
        }
    
        /**
         * {@inheritDoc}
         */
        public String getVersion() throws PlatformManagerException
        {
        	if (!OSXAccess.isLoaded()) {
            throw new PlatformManagerException("Unsupported capability called on platform manager");
        	}
        	
        	return OSXAccess.getVersion();
        }
    
        /**
         * {@inheritDoc}
         * @see org.gudy.azureus2.core3.util.SystemProperties#getUserPath()
         */
        public String getUserDataDirectory() throws PlatformManagerException
        {
            return USERDATA_PATH;
        }
    
    	public File
    	getLocation(
    		long	location_id )
    	
    		throws PlatformManagerException
    	{
    		if ( location_id == LOC_USER_DATA ){
    			
    			return( new File( USERDATA_PATH ));
    		}
    		
    		return( null );
    	}
        /**
         * Not implemented; returns True
         */
        public boolean isApplicationRegistered() throws PlatformManagerException
        {
            return true;
        }
    
        
    	public String
    	getApplicationCommandLine()
    		throws PlatformManagerException
    	{
    		try{	    
    			String	bundle_path = System.getProperty("user.dir") +SystemProperties.SEP+ SystemProperties.getApplicationName() + ".app";
    
    			File osx_app_bundle = new File( bundle_path ).getAbsoluteFile();
    			
    			if( !osx_app_bundle.exists() ) {
    				String msg = "OSX app bundle not found: [" +osx_app_bundle.toString()+ "]";
    				System.out.println( msg );
    				if (Logger.isEnabled())
    					Logger.log(new LogEvent(LOGID, msg));		
    				throw new PlatformManagerException( msg );
    			}
    			
    			return "open -a \"" +osx_app_bundle.toString()+ "\"";
    			//return osx_app_bundle.toString() +"/Contents/MacOS/JavaApplicationStub";
    			
    		}
    		catch( Throwable t ){	
    			t.printStackTrace();
    			return null;
    		}
    	}
    	
    	
    	public boolean
    	isAdditionalFileTypeRegistered(
    		String		name,				// e.g. "BitTorrent"
    		String		type )				// e.g. ".torrent"
    	
    		throws PlatformManagerException
    	{
    	    throw new PlatformManagerException("Unsupported capability called on platform manager");
    	}
    	
    	public void
    	unregisterAdditionalFileType(
    		String		name,				// e.g. "BitTorrent"
    		String		type )				// e.g. ".torrent"
    		
    		throws PlatformManagerException
    	{
    		throw new PlatformManagerException("Unsupported capability called on platform manager");
    	}
    	
    	public void
    	registerAdditionalFileType(
    		String		name,				// e.g. "BitTorrent"
    		String		description,		// e.g. "BitTorrent File"
    		String		type,				// e.g. ".torrent"
    		String		content_type )		// e.g. "application/x-bittorrent"
    	
    		throws PlatformManagerException
    	{
    	   throw new PlatformManagerException("Unsupported capability called on platform manager");
    	}
    	
        /**
         * Not implemented; does nothing
         */
        public void registerApplication() throws PlatformManagerException
        {
            // handled by LaunchServices and/0r user interaction
        }
    
        /**
         * {@inheritDoc}
         */
        public void createProcess(String cmd, boolean inheritsHandles) throws PlatformManagerException
        {
            try
            {
                performRuntimeExec(cmd.split(" "));
            }
            catch (Throwable e)
            {
                throw new PlatformManagerException("Failed to create process", e);
            }
        }
    
        /**
         * {@inheritDoc}
         */
        public void performRecoverableFileDelete(String path) throws PlatformManagerException
        {
            File file = new File(path);
            if(!file.exists())
            {
    	        	if (Logger.isEnabled())
    							Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
    									+ file.getName()));
                return;
            }
    
            boolean useOSA = !NativeInvocationBridge.sharedInstance().isEnabled() || !NativeInvocationBridge.sharedInstance().performRecoverableFileDelete(file);
    
            if(useOSA)
            {
                try
                {
                    StringBuffer sb = new StringBuffer();
                    sb.append("tell application \"");
                    sb.append("Finder");
                    sb.append("\" to move (posix file \"");
                    sb.append(path);
                    sb.append("\" as alias) to the trash");
    
                    performOSAScript(sb);
                }
                catch (Throwable e)
                {
                    throw new PlatformManagerException("Failed to move file", e);
                }
            }
        }
    
        /**
         * {@inheritDoc}
         */
        public boolean hasCapability(PlatformManagerCapabilities capability)
        {
            return capabilitySet.contains(capability);
        }
    
        /**
         * {@inheritDoc}
         */
        public void dispose()
        {
            NativeInvocationBridge.sharedInstance().dispose();
        }
    
        /**
         * {@inheritDoc}
         */
        public void setTCPTOSEnabled(boolean enabled) throws PlatformManagerException
        {
            throw new PlatformManagerException("Unsupported capability called on platform manager");
        }
    
    	public void
        copyFilePermissions(
    		String	from_file_name,
    		String	to_file_name )
    	
    		throws PlatformManagerException
    	{
    	    throw new PlatformManagerException("Unsupported capability called on platform manager");		
    	}
    	
        /**
         * {@inheritDoc}
         */
        public void showFile(String path) throws PlatformManagerException
        {
            File file = new File(path);
            if(!file.exists())
            {
            	if (Logger.isEnabled())
            		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
            				+ file.getName()));
                throw new PlatformManagerException("File not found");
            }
    
            showInFinder(file);
        }
    
        // Public utility methods not shared across the interface
    
        /**
         * Plays the system alert (the jingle is specified by the user in System Preferences)
         */
        public void playSystemAlert()
        {
            try
            {
                performRuntimeExec(new String[]{"beep"});
            }
            catch (IOException e)
            {
            	if (Logger.isEnabled())
            		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING,
    						"Cannot play system alert"));
            	Logger.log(new LogEvent(LOGID, "", e));
            }
        }
    
        /**
         * 

    Shows the given file or directory in Finder

    * @param path Absolute path to the file or directory */ public void showInFinder(File path) { boolean useOSA = !NativeInvocationBridge.sharedInstance().isEnabled() || !NativeInvocationBridge.sharedInstance().showInFinder(path); if(useOSA) { StringBuffer sb = new StringBuffer(); sb.append("tell application \""); sb.append(getFileBrowserName()); sb.append("\" to reveal (posix file \""); sb.append(path); sb.append("\" as alias)"); try { performOSAScript(sb); } catch (IOException e) { Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, e .getMessage())); } } } /** *

    Shows the given file or directory in Terminal by executing cd /absolute/path/to

    * @param path Absolute path to the file or directory */ public void showInTerminal(String path) { showInTerminal(new File(path)); } /** *

    Shows the given file or directory in Terminal by executing cd /absolute/path/to

    * @param path Absolute path to the file or directory */ public void showInTerminal(File path) { if (path.isFile()) { path = path.getParentFile(); } if (path != null && path.isDirectory()) { StringBuffer sb = new StringBuffer(); sb.append("tell application \""); sb.append("Terminal"); sb.append("\" to do script \"cd "); sb.append(path.getAbsolutePath().replaceAll(" ", "\\ ")); sb.append("\""); try { performOSAScript(sb); } catch (IOException e) { Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, e .getMessage())); } } else { if (Logger.isEnabled()) Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find " + path.getName())); } } // Internal utility methods /** * Compiles a new AppleScript instance and runs it * @param cmd AppleScript command to execute; do not surround command with extra quotation marks * @return Output of the script * @throws IOException If the script failed to execute */ protected static String performOSAScript(CharSequence cmd) throws IOException { return performOSAScript(new CharSequence[]{cmd}); } /** * Compiles a new AppleScript instance and runs it * @param cmds AppleScript Sequence of commands to execute; do not surround command with extra quotation marks * @return Output of the script * @throws IOException If the script failed to execute */ protected static String performOSAScript(CharSequence[] cmds) throws IOException { long start = System.currentTimeMillis(); Debug.outNoStack("Executing OSAScript: "); for (int i = 0; i < cmds.length; i++) { Debug.outNoStack("\t" + cmds[i]); } String[] cmdargs = new String[2 * cmds.length + 1]; cmdargs[0] = "osascript"; for (int i = 0; i < cmds.length; i++) { cmdargs[i * 2 + 1] = "-e"; cmdargs[i * 2 + 2] = String.valueOf(cmds[i]); } Process osaProcess = performRuntimeExec(cmdargs); BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getInputStream())); String line = reader.readLine(); reader.close(); Debug.outNoStack("OSAScript Output: " + line); reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream())); String errorMsg = reader.readLine(); reader.close(); Debug.outNoStack("OSAScript Error (if any): " + errorMsg); Debug.outNoStack(MessageFormat.format("OSAScript execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)})); if (errorMsg != null) { throw new IOException(errorMsg); } return line; } /** * Compiles a new AppleScript instance and runs it * @param script AppleScript file (.scpt) to execute * @return Output of the script * @throws IOException If the script failed to execute */ protected static String performOSAScript(File script) throws IOException { long start = System.currentTimeMillis(); Debug.outNoStack("Executing OSAScript from file: " + script.getPath()); Process osaProcess = performRuntimeExec(new String[]{"osascript", script.getPath()}); BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getInputStream())); String line = reader.readLine(); reader.close(); Debug.outNoStack("OSAScript Output: " + line); reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream())); String errorMsg = reader.readLine(); reader.close(); Debug.outNoStack("OSAScript Error (if any): " + errorMsg); Debug.outNoStack(MessageFormat.format("OSAScript execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)})); if (errorMsg != null) { throw new IOException(errorMsg); } return line; } /** * Compiles a new AppleScript instance to the specified location * @param cmd Command to compile; do not surround command with extra quotation marks * @param destination Destination location of the AppleScript file * @return True if compiled successfully */ protected static boolean compileOSAScript(CharSequence cmd, File destination) { return compileOSAScript(new CharSequence[]{cmd}, destination); } /** * Compiles a new AppleScript instance to the specified location * @param cmds Sequence of commands to compile; do not surround command with extra quotation marks * @param destination Destination location of the AppleScript file * @return True if compiled successfully */ protected static boolean compileOSAScript(CharSequence[] cmds, File destination) { long start = System.currentTimeMillis(); Debug.outNoStack("Compiling OSAScript: " + destination.getPath()); for (int i = 0; i < cmds.length; i++) { Debug.outNoStack("\t" + cmds[i]); } String[] cmdargs = new String[2 * cmds.length + 3]; cmdargs[0] = "osacompile"; for (int i = 0; i < cmds.length; i++) { cmdargs[i * 2 + 1] = "-e"; cmdargs[i * 2 + 2] = String.valueOf(cmds[i]); } cmdargs[cmdargs.length - 2] = "-o"; cmdargs[cmdargs.length - 1] = destination.getPath(); String errorMsg; try { Process osaProcess = performRuntimeExec(cmdargs); BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream())); errorMsg = reader.readLine(); reader.close(); } catch (IOException e) { Debug.outNoStack("OSACompile Execution Failed: " + e.getMessage()); Debug.printStackTrace(e); return false; } Debug.outNoStack("OSACompile Error (if any): " + errorMsg); Debug.outNoStack(MessageFormat.format("OSACompile execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)})); return (errorMsg == null); } /** * @see Runtime#exec(String[]) */ protected static Process performRuntimeExec(String[] cmdargs) throws IOException { try { return Runtime.getRuntime().exec(cmdargs); } catch (IOException e) { Logger.log(new LogAlert(LogAlert.UNREPEATABLE, e.getMessage(), e)); throw e; } } /** *

    Gets the preferred file browser name

    *

    Currently supported browsers are Path Finder and Finder. If Path Finder is currently running * (not just installed), then "Path Finder is returned; else, "Finder" is returned.

    * @return "Path Finder" if it is currently running; else "Finder" */ private static String getFileBrowserName() { try { // slowwwwwwww if ("true".equalsIgnoreCase(performOSAScript("tell application \"System Events\" to exists process \"Path Finder\""))) { Debug.outNoStack("Path Finder is running"); return "Path Finder"; } else { return "Finder"; } } catch (IOException e) { Debug.printStackTrace(e); Logger.log(new LogEvent(LOGID, e.getMessage(), e)); return "Finder"; } } public boolean testNativeAvailability( String name ) throws PlatformManagerException { throw new PlatformManagerException("Unsupported capability called on platform manager"); } public void addListener( PlatformManagerListener listener ) { } public void removeListener( PlatformManagerListener listener ) { } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.jsp000066400000000000000000000011631250413007300253660ustar00rootroot00000000000000 <%= var x = 1; %> <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %> <% String name = null; if (request.getParameter("name") == null) { %> <%@ include file="error.html" %> <% } else { foo.setName(request.getParameter("name")); if (foo.getName().equalsIgnoreCase("integra")) name = "acura"; if (name.equalsIgnoreCase( "acura" )) { %>

    Calendar of

    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.maql000066400000000000000000000027651250413007300255350ustar00rootroot00000000000000# MAQL script CREATE DATASET {dataset.quotes} VISUAL(TITLE "St\\tock Qu\totes Data"); # A comment CREATE DATASET {dataset.quotes} VISUAL(TITLE "Stock Qu\"otes Data"); CREATE DATASET {dataset.quotes} VISUAL(TITLE "Stock Quotes Data"); ALTER DATASET {dataset.quotes} ADD {attribute.sector}; ALTER DATASET {dataset.quotes} DROP {attribute.symbol}; ALTER DATASET {dataset.quotes} VISUAL(TITLE "Internal Quotes Data"); CREATE ATTRIBUTE {attr.quotes.symbol} VISUAL(TITLE "Symbol", FOLDER {folder.quotes.attr}) AS {d_quotes_symbol.nm_symbol}; ALTER ATTRIBUTE {attr.quotes.symbol} ADD LABELS {attr.quotes.company} VISUAL(TITLE "Company") AS {d_quotes_symbol.nm_company}; CREATE FACT {fact.quotes.open_price} VISUAL( TITLE "Open Price", FOLDER {folder.quotes.fact}) AS {f_quotes.f_open_price}; ALTER FACT {fact.quotes.open_price} ADD {f_quotes2.f_open_price}; CREATE FOLDER {folder.quotes.attr} VISUAL ( TITLE "Stock Quotes Data", DESCRIPTION "Stock quotes data obtained from John Doe etc." ) TYPE ATTRIBUTE; ALTER DATATYPE {d_quotes_symbol.nm_symbol} VARCHAR(4), {d_quotes_symbol.nm_symbol} VARCHAR(80), {f_quotes.f_open_price} DECIMAL(10,2); INCLUDE TEMPLATE "URN:GOODDATA:DATE" MODIFY (IDENTIFIER "my-date", TITLE "quote") ALTER ATTRIBUTE {attr.quotes.symbol} ADD KEYS {d_quotes_symbol.nm_symbol} PRIMARY; ALTER ATTRIBUTE {attr.quotes.symbol} DROP KEYS {d_quotes_symbol.nm_symbol}; ALTER FACT {fact.quotes.open_price} ADD {f_quotes2.f_open_price}; # Another comment pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.mask000066400000000000000000000015271250413007300255310ustar00rootroot00000000000000 // comment h4.class-1#id.class-2.other checked='true' disabled name = x param > 'Enter ..' input placeholder=Password type=password > :dualbind x-signal='dom:create' value=user.passord; % each='flowers' > div style=' position: absolute; display: inline-block; background: url("image.png") center center no-repeat; '; #skippedDiv.other { img src='~[url]'; div style="text-align:center;" { '~[: $obj.foo("username", name) + 2]' "~[Localize: stringId]" } p > """ Hello "world" """ p > ' Hello "world" ' p > "Hello 'world'" :customComponent x-value='tt'; /* footer > '(c) 2014' */ } .skippedDiv > span > #skipped > table > td > tr > ';)' br;pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.mod000066400000000000000000000271741250413007300253630ustar00rootroot00000000000000(* LIFO Storage Library * * @file LIFO.mod * LIFO implementation * * Universal Dynamic Stack * * Author: Benjamin Kowarsch * * Copyright (C) 2009 Benjamin Kowarsch. All rights reserved. * * License: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met * * 1) NO FEES may be charged for the provision of the software. The software * may NOT be published on websites that contain advertising, unless * specific prior written permission has been obtained. * * 2) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 3) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and other materials provided with the distribution. * * 4) Neither the author's name nor the names of any contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * 5) Where this list of conditions or the following disclaimer, in part or * as a whole is overruled or nullified by applicable law, no permission * is granted to use the software. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *) IMPLEMENTATION (* OF *) MODULE LIFO; FROM SYSTEM IMPORT ADDRESS, ADR, TSIZE; FROM Storage IMPORT ALLOCATE, DEALLOCATE; (* --------------------------------------------------------------------------- // Private type : ListEntry // --------------------------------------------------------------------------- *) TYPE ListPtr = POINTER TO ListEntry; TYPE ListEntry = RECORD value : DataPtr; next : ListPtr END; (* ListEntry *) (* --------------------------------------------------------------------------- // Opaque type : LIFO.Stack // --------------------------------------------------------------------------- // CAUTION: Modula-2 does not support the use of variable length array fields // in records. VLAs can only be implemented using pointer arithmetic which // means there is no type checking and no boundary checking on the array. // It also means that array notation cannot be used on the array which makes // the code difficult to read and maintain. As a result, Modula-2 is less // safe and less readable than C when it comes to using VLAs. Great care must // be taken to make sure that the code accessing VLA fields is safe. Boundary // checks must be inserted manually. Size checks must be inserted manually to // compensate for the absence of type checks. *) TYPE Stack = POINTER TO StackDescriptor; TYPE StackDescriptor = RECORD overflow : ListPtr; entryCount : StackSize; arraySize : StackSize; array : ADDRESS (* ARRAY OF DataPtr *) END; (* StackDescriptor *) (* --------------------------------------------------------------------------- // function: LIFO.new( initial_size, status ) // --------------------------------------------------------------------------- // // Creates and returns a new LIFO stack object with an initial capacity of // . If zero is passed in for , then the stack // will be created with an initial capacity of LIFO.defaultStackSize. The // function fails if a value greater than LIFO.maximumStackSize is passed // in for or if memory could not be allocated. // // The initial capacity of a stack is the number of entries that can be stored // in the stack without enlargement. // // The status of the operation is passed back in . *) PROCEDURE new ( initialSize : StackSize; VAR status : Status ) : Stack; VAR newStack : Stack; BEGIN (* zero size means default *) IF initialSize = 0 THEN initialSize := defaultStackSize; END; (* IF *) (* bail out if initial size is too high *) IF initialSize > maximumStackSize THEN status := invalidSize; RETURN NIL; END; (* IF *) (* allocate new stack object *) ALLOCATE(newStack, TSIZE(Stack) + TSIZE(DataPtr) * (initialSize - 1)); (* bail out if allocation failed *) IF newStack = NIL THEN status := allocationFailed; RETURN NIL; END; (* IF *) (* initialise meta data *) newStack^.arraySize := initialSize; newStack^.entryCount := 0; newStack^.overflow := NIL; (* pass status and new stack to caller *) status := success; RETURN newStack END new; (* --------------------------------------------------------------------------- // function: LIFO.push( stack, value, status ) // --------------------------------------------------------------------------- // // Adds a new entry to the top of stack . The new entry is // added by reference, no data is copied. However, no entry is added if the // the stack is full, that is when the number of entries stored in the stack // has reached LIFO.maximumStackSize. The function fails if NIL is passed in // for or , or if memory could not be allocated. // // New entries are allocated dynamically if the number of entries exceeds the // initial capacity of the stack. // // The status of the operation is passed back in . *) PROCEDURE push ( VAR stack : Stack; value : DataPtr; VAR status : Status ); VAR newEntry : ListPtr; valuePtr : POINTER TO DataPtr; BEGIN (* bail out if stack is NIL *) IF stack = NIL THEN status := invalidStack; RETURN; END; (* IF *) (* bail out if value is NIL *) IF value = NIL THEN status := invalidData; RETURN; END; (* IF *) (* bail out if stack is full *) IF stack^.entryCount >= maximumStackSize THEN status := stackFull; RETURN; END; (* IF *) (* check if index falls within array segment *) IF stack^.entryCount < stack^.arraySize THEN (* store value in array segment *) (* stack^.array^[stack^.entryCount] := value; *) valuePtr := ADR(stack^.array) + TSIZE(DataPtr) * stack^.entryCount; valuePtr^ := value; ELSE (* index falls within overflow segment *) (* allocate new entry slot *) NEW(newEntry); (* bail out if allocation failed *) IF newEntry = NIL THEN status := allocationFailed; RETURN; END; (* IF *) (* initialise new entry *) newEntry^.value := value; (* link new entry into overflow list *) newEntry^.next := stack^.overflow; stack^.overflow := newEntry; END; (* IF *) (* update entry counter *) INC(stack^.entryCount); (* pass status to caller *) status := success; RETURN END push; (* --------------------------------------------------------------------------- // function: LIFO.pop( stack, status ) // --------------------------------------------------------------------------- // // Removes the top most value from stack and returns it. If the stack // is empty, that is when the number of entries stored in the stack has // reached zero, then NIL is returned. // // Entries which were allocated dynamically (above the initial capacity) are // deallocated when their values are popped. // // The status of the operation is passed back in . *) PROCEDURE pop ( VAR stack : Stack; VAR status : Status ) : DataPtr; VAR thisValue : DataPtr; thisEntry : ListPtr; valuePtr : POINTER TO DataPtr; BEGIN (* bail out if stack is NIL *) IF stack = NIL THEN status := invalidStack; RETURN NIL; END; (* IF *) (* bail out if stack is empty *) IF stack^.entryCount = 0 THEN status := stackEmpty; RETURN NIL; END; (* IF *) DEC(stack^.entryCount); (* check if index falls within array segment *) IF stack^.entryCount < stack^.arraySize THEN (* obtain value at index entryCount in array segment *) (* thisValue := stack^.array^[stack^.entryCount]; *) valuePtr := ADR(stack^.array) + TSIZE(DataPtr) * stack^.entryCount; thisValue := valuePtr^; ELSE (* index falls within overflow segment *) (* obtain value of first entry in overflow list *) thisValue := stack^.overflow^.value; (* isolate first entry in overflow list *) thisEntry := stack^.overflow; stack^.overflow := stack^.overflow^.next; (* remove the entry from overflow list *) DISPOSE(thisEntry); END; (* IF *) (* return value and status to caller *) status := success; RETURN thisValue END pop; (* --------------------------------------------------------------------------- // function: LIFO.stackSize( stack ) // --------------------------------------------------------------------------- // // Returns the current capacity of . The current capacity is the total // number of allocated entries. Returns zero if NIL is passed in for . *) PROCEDURE stackSize( VAR stack : Stack ) : StackSize; BEGIN (* bail out if stack is NIL *) IF stack = NIL THEN RETURN 0; END; (* IF *) IF stack^.entryCount < stack^.arraySize THEN RETURN stack^.arraySize; ELSE RETURN stack^.entryCount; END; (* IF *) END stackSize; (* --------------------------------------------------------------------------- // function: LIFO.stackEntries( stack ) // --------------------------------------------------------------------------- // // Returns the number of entries stored in stack , returns zero if // NIL is passed in for . *) PROCEDURE stackEntries( VAR stack : Stack ) : StackSize; BEGIN (* bail out if stack is NIL *) IF stack = NIL THEN RETURN 0; END; (* IF *) RETURN stack^.entryCount END stackEntries; (* --------------------------------------------------------------------------- // function: LIFO.dispose( stack ) // --------------------------------------------------------------------------- // // Disposes of LIFO stack object . Returns NIL. *) PROCEDURE dispose ( VAR stack : Stack ) : Stack; VAR thisEntry : ListPtr; BEGIN (* bail out if stack is NIL *) IF stack = NIL THEN RETURN NIL; END; (* IF *) (* deallocate any entries in stack's overflow list *) WHILE stack^.overflow # NIL DO (* isolate first entry in overflow list *) thisEntry := stack^.overflow; stack^.overflow := stack^.overflow^.next; (* deallocate the entry *) DISPOSE(thisEntry); END; (* WHILE *) (* deallocate stack object and pass NIL to caller *) DEALLOCATE(stack, TSIZE(Stack) + TSIZE(DataPtr) * (stack^.arraySize - 1)); RETURN NIL END dispose; END LIFO. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.moo000066400000000000000000000044501250413007300253660ustar00rootroot00000000000000you_lose_msg = "Either that person does not exist, or has a different password."; if (!(caller in {#0, this})) return E_PERM; "...caller isn't :do_login_command..."; elseif (args && (args[1] == "test")) return this:test(@listdelete(args, 1)); elseif (!(length(args) in {1, 2})) notify(player, tostr("Usage: ", verb, " ")); elseif (!valid(candidate = this:_match_player(name = strsub(args[1], " ", "_")))) if (name == "guest") "must be no guests"; this:notify_lines(this:registration_text("guest")); else notify(player, you_lose_msg); endif "...unknown player..."; elseif (is_clear_property(candidate, "password") || ((typeof(candidate.password) == STR) && ((length(candidate.password) < 2) || (crypt({@args, ""}[2], candidate.password) != candidate.password)))) notify(player, you_lose_msg); "...bad password..."; server_log(tostr("FAILED CONNECT: ", args[1], " (", candidate, ") on ", connection_name(player), ($string_utils:connection_hostname(connection_name(player)) in candidate.all_connect_places) ? "" | "******")); elseif (((candidate.name == "guest") && this.sitematch_guests) && valid(foreigner = $country_db:get_guest())) notify(player, tostr("Okay,... Logging you in as `", foreigner:name(), "'")); this:record_connection(foreigner); return foreigner; elseif ((parent(candidate) == $guest) && (!valid(candidate = candidate:defer()))) if (candidate == #-3) notify(player, "Sorry, guest characters are not allowed from your site right now."); elseif (candidate == #-2) this:notify_lines(this:registration_text("blacklisted", "Sorry, guest characters are not allowed from your site.")); elseif (candidate == #-4) this:notify_lines(this:registration_text("guest")); else notify(player, "Sorry, all of our guest characters are in use right now."); endif else if ((!(name in candidate.aliases)) && (name != tostr(candidate))) notify(player, tostr("Okay,... ", name, " is in use. Logging you in as `", candidate:name(), "'")); endif if (this:is_newted(candidate)) notify(player, ""); notify(player, this:newt_message_for(candidate)); notify(player, ""); else this:record_connection(candidate); if (verb[1] == "s") candidate.use_do_command = 0; endif return candidate; endif endif return 0;pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.myt000066400000000000000000000075431250413007300254130ustar00rootroot00000000000000<%doc>formatting.myt - Provides section formatting elements, syntax-highlighted code blocks, and other special filters. <%global> import string, re import highlight <%method section> <%doc>Main section formatting element. <%args> toc path description=None onepage=False <%init> item = toc.get_by_path(path) if item is None: raise "path: " + path
    <%python> content = m.content() re2 = re.compile(r"'''PYESC(.+?)PYESC'''", re.S) content = re2.sub(lambda m: m.group(1), content) % if item.depth > 1:

    <% description or item.description %>

    %
    <% content %>
    % if onepage or item.depth > 1: % if (item.next and item.next.depth >= item.depth): back to section top % % else: back to section top <& nav.myt:pagenav, item=item, onepage=onepage &> %
    <%method formatplain> <%filter> import re f = re.sub(r'\n[\s\t]*\n[\s\t]*', '

    \n

    ', f) f = "

    " + f + "

    " return f <% m.content() | h%> <%method codeline trim="both"> <% m.content() %> <%method code autoflush=False> <%args> title = None syntaxtype = 'python' html_escape = False use_sliders = False <%init> def fix_indent(f): f =string.expandtabs(f, 4) g = '' lines = string.split(f, "\n") whitespace = None for line in lines: if whitespace is None: match = re.match(r"^([ ]*).+", line) if match is not None: whitespace = match.group(1) if whitespace is not None: line = re.sub(r"^%s" % whitespace, "", line) if whitespace is not None or re.search(r"\w", line) is not None: g += (line + "\n") return g.rstrip() p = re.compile(r'
    (.*?)
    ', re.S) def hlight(match): return "
    " + highlight.highlight(fix_indent(match.group(1)), html_escape = html_escape, syntaxtype = syntaxtype) + "
    " content = p.sub(hlight, "
    " + m.content() + "
    ")
    "> % if title is not None:
    <% title %>
    % <% content %>
    <%method popboxlink trim="both"> <%args> name=None show='show' hide='hide' <%init> if name is None: name = m.attributes.setdefault('popbox_name', 0) name += 1 m.attributes['popbox_name'] = name name = "popbox_" + repr(name) javascript:togglePopbox('<% name %>', '<% show %>', '<% hide %>') <%method popbox trim="both"> <%args> name = None class_ = None <%init> if name is None: name = 'popbox_' + repr(m.attributes['popbox_name']) <%method poplink trim="both"> <%args> link='sql' <%init> href = m.scomp('SELF:popboxlink') '''PYESC<& nav.myt:link, href=href, text=link, class_="codepoplink" &>PYESC''' <%method codepopper trim="both"> <%init> c = m.content() c = re.sub(r'\n', '
    \n', c.strip())
    <&|SELF:popbox, class_="codepop" &><% c %>
    
    
    <%method poppedcode trim="both">
    	<%init>
    		c = m.content()
    		c = re.sub(r'\n', '
    \n', c.strip())
    <% c %>
    
    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.nim000066400000000000000000000040061250413007300253540ustar00rootroot00000000000000import re
    
    for x in lines("myfile.txt"):
      if x =~ re"(\w+)=(.*)":
        echo "Key: ", matches[0],
             " Value: ", matches[1]
    
    Echo("What's your name? ")
    var name: string = readLine(stdin)
    if name == "":
      echo("Poor soul, you lost your name?")
    elif name == "name":
      echo("Very funny, your name is name.")
    else:
      Echo("Hi, ", name, "!")
    
    var name = readLine(stdin)
    case name
    of "":
      echo("Poor soul, you lost your name?")
    of "name":
      echo("Very funny, your name is name.")
    else:
      Echo("Hi, ", name, "!")
    
    from strutils import parseInt
    
    Echo("A number please: ")
    var n = parseInt(readLine(stdin))
    case n
    of 0..2, 4..7: Echo("The number is in the set: {0, 1, 2, 4, 5, 6, 7}")
    of 3, 8: Echo("The number is 3 or 8")
    
    Echo("Counting to 10: ")
    var i = 1
    while i <= 10:
      Echo($i)
      inc(i)
    
    proc yes(question: string): bool =
      Echo(question, " (y/n)")
      while true:
        case readLine(stdin)
        of "y", "Y", "yes", "Yes": return true
        of "n", "N", "no", "No": return false
        else: Echo("Please be clear: yes or no")
    
    proc even(n: int): bool
    
    proc odd(n: int): bool =
      if n == 1: return true
      else: return even(n-1)
    
    iterator countup(a, b: int): int =
      var res = a
      while res <= b:
        yield res
        inc(res)
    
    type
      TPerson = object of TObject
        name*: string  # the * means that `name` is accessible from other modules
        age: int       # no * means that the field is hidden from other modules
    
      TStudent = object of TPerson # TStudent inherits from TPerson
        id: int                    # with an id field
    
    var
      student: TStudent
      person: TPerson
    assert(student is TStudent)
    
    echo({'a', 'b', 'c'}.card)
    stdout.writeln("Hallo")
    var
      f: TFile
    if open(f, "numbers.txt"):
      try:
        var a = readLine(f)
        var b = readLine(f)
        echo("sum: " & $(parseInt(a) + parseInt(b)))
      except EOverflow:
        echo("overflow!")
      except EInvalidValue:
        echo("could not convert string to integer")
      except EIO:
        echo("IO error!")
      except:
        echo("Unknown exception!")
        # reraise the unknown exception:
        raise
      finally:
        close(f)pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.opa000066400000000000000000000002541250413007300253510ustar00rootroot00000000000000function sample_page() {
      

    HTML in Opa

    Learning by examples.

    } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.p6000066400000000000000000000070151250413007300251210ustar00rootroot00000000000000#!/usr/bin/env perl6 use v6; my $string = 'I look like a # comment!'; if $string eq 'foo' { say 'hello'; } regex http-verb { 'GET' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'OPTIONS' | 'HEAD' } # a sample comment say 'Hello from Perl 6!' #`{ multi-line comment! } say 'here'; #`( multi-line comment! ) say 'here'; #`{{{ I'm a special comment! }}} say 'there'; #`{{ I'm { even } specialer! }} say 'there'; #`{{ does {{nesting}} work? }} #`«< trying mixed delimiters » my $string = qq; my $string = qq«Hooray, arbitrary delimiter!»; my $string = q ; my $string = qq<>; my %hash := Hash.new; =begin pod Here's some POD! Wooo =end pod =for Testing This is POD (see? role isn't highlighted) say('this is not!'); =table Of role things say('not in your table'); #= A single line declarator "block" (with a keyword like role) #| Another single line declarator "block" (with a keyword like role) #={ A declarator block (with a keyword like role) } #|{ Another declarator block (with a keyword like role) } #= { A single line declarator "block" with a brace (with a keyword like role) #=« More declarator blocks! (with a keyword like role) » #|« More declarator blocks! (with a keyword like role) » say 'Moar code!'; my $don't = 16; sub don't($x) { !$x } say don't 'foo'; my %hash = ( :foo(1), ); say %hash; say %hash<>; say %hash«foo»; say %*hash; say %*hash<>; say %*hash«foo»; say $; say $; for (@A Z @B) -> $a, $b { say $a + $b; } Q:PIR { .loadlib "somelib" } my $longstring = q/ lots of text /; my $heredoc = q:to/END_SQL/; SELECT * FROM Users WHERE first_name = 'Rob' END_SQL my $hello; # Fun with regexen if 'food' ~~ /foo/ { say 'match!' } my $re = /foo/; my $re2 = m/ foo /; my $re3 = m:i/ FOO /; call-a-sub(/ foo /); call-a-sub(/ foo \/ bar /); my $re4 = rx/something | something-else/; my $result = ms/regexy stuff/; my $sub0 = s/regexy stuff/more stuff/; my $sub = ss/regexy stuff/more stuff/; my $trans = tr/regexy stuff/more stuff/; my @values = ; call-sub(); call-sub ; my $result = $a < $b; for -> $letter { say $letter; } sub test-sub { say @_; say $!; say $/; say $0; say $1; say @*ARGS; say $*ARGFILES; say &?BLOCK; say ::?CLASS; say $?CLASS; say @=COMMENT; say %?CONFIG; say $*CWD; say $=data; say %?DEEPMAGIC; say $?DISTRO; say $*DISTRO; say $*EGID; say %*ENV; say $*ERR; say $*EUID; say $*EXECUTABLE_NAME; say $?FILE; say $?GRAMMAR; say $*GID; say $*IN; say @*INC; say %?LANG; say $*LANG; say $?LINE; say %*META-ARGS; say $?MODULE; say %*OPTS; say %*OPT; say $?KERNEL; say $*KERNEL; say $*OUT; say $?PACKAGE; say $?PERL; say $*PERL; say $*PID; say %=pod; say $*PROGRAM_NAME; say %*PROTOCOLS; say ::?ROLE; say $?ROLE; say &?ROUTINE; say $?SCOPE; say $*TZ; say $*UID; say $?USAGE; say $?VM; say $?XVM; } say ; my $perl5_re = m:P5/ fo{2} /; my $re5 = rx«something | something-else»; my $M := %*COMPILING<%?OPTIONS>; say $M; sub regex-name { ... } my $pair = role-name => 'foo'; $pair = rolesque => 'foo'; my sub something(Str:D $value) { ... } my $s = q«< some string stuff »; my $regex = m«< some chars »; # after say $/; roleq; pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.pan000066400000000000000000000023311250413007300253460ustar00rootroot00000000000000object template pantest; # Very simple pan test file "/long/decimal" = 123; "/long/octal" = 0755; "/long/hexadecimal" = 0xFF; "/double/simple" = 0.01; "/double/pi" = 3.14159; "/double/exponent" = 1e-8; "/double/scientific" = 1.3E10; "/string/single" = 'Faster, but escapes like \t, \n and \x3d don''t work, but '' should work.'; "/string/double" = "Slower, but escapes like \t, \n and \x3d do work"; variable TEST = 2; "/x2" = to_string(TEST); "/x2" ?= 'Default value'; "/x3" = 1 + 2 + value("/long/decimal"); "/x4" = undef; "/x5" = null; variable e ?= error("Test error message"); # include gmond config for services-monitoring include { 'site/ganglia/gmond/services-monitoring' }; "/software/packages"=pkg_repl("httpd","2.2.3-43.sl5.3",PKG_ARCH_DEFAULT); "/software/packages"=pkg_repl("php"); # Example function function show_things_view_for_stuff = { thing = ARGV[0]; foreach( i; mything; STUFF ) { if ( thing == mything ) { return( true ); } else { return SELF; }; }; false; }; variable HERE = < '\' then RootFolder := RootFolder + '\'; ZeroMemory(@wfd, sizeof(wfd)); wfd.dwFileAttributes := FILE_ATTRIBUTE_NORMAL; if Recurse then begin hFindFile := FindFirstFile(pointer(RootFolder + '*.*'), wfd); if hFindFile <> 0 then try repeat if wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then begin if (string(wfd.cFileName) <> '.') and (string(wfd.cFileName) <> '..') then begin CountFolders(Handle, RootFolder + wfd.cFileName, Recurse); end; end; until FindNextFile(hFindFile, wfd) = False; Inc(CntFolders); finally Windows.FindClose(hFindFile); end; end; end; //////////////////////////////////////////////////////////////////////////////// // // FindAllFiles // procedure FindAllFiles(Handle: THandle; RootFolder: string; Mask: string; Recurse: Boolean = True); var hFindFile : THandle; wfd : TWin32FindData; begin if RootFolder[length(RootFolder)] <> '\' then RootFolder := RootFolder + '\'; ZeroMemory(@wfd, sizeof(wfd)); wfd.dwFileAttributes := FILE_ATTRIBUTE_NORMAL; if Recurse then begin hFindFile := FindFirstFile(pointer(RootFolder + '*.*'), wfd); if hFindFile <> 0 then try repeat if wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then begin if (string(wfd.cFileName) <> '.') and (string(wfd.cFileName) <> '..') then begin FindAllFiles(Handle, RootFolder + wfd.cFileName, Mask, Recurse); end; end; until FindNextFile(hFindFile, wfd) = False; Inc(NumFolder); SendMessage(Handle, FFM_ONDIRFOUND, NumFolder, lParam(string(RootFolder))); finally Windows.FindClose(hFindFile); end; end; hFindFile := FindFirstFile(pointer(RootFolder + Mask), wfd); if hFindFile <> INVALID_HANDLE_VALUE then try repeat if (wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> FILE_ATTRIBUTE_DIRECTORY) then begin SendMessage(Handle, FFM_ONFILEFOUND, 0, lParam(string(RootFolder + wfd.cFileName))); end; until FindNextFile(hFindFile, wfd) = False; finally Windows.FindClose(hFindFile); end; end; property test: boolean read ftest write ftest; procedure test: boolean read ftest write ftest; // // This sourcecode is part of omorphia // Function IsValidHandle(Const Handle: THandle): Boolean; {$IFDEF OMORPHIA_FEATURES_USEASM} Assembler; Asm TEST EAX, EAX JZ @@Finish NOT EAX TEST EAX, EAX SETNZ AL {$IFDEF WINDOWS} JZ @@Finish //Save the handle against modifications or loss PUSH EAX //reserve some space for a later duplicate PUSH EAX //Check if we are working on NT-Platform CALL IsWindowsNTSystem TEST EAX, EAX JZ @@NoNTSystem PUSH DWORD PTR [ESP] LEA EAX, DWORD PTR [ESP+$04] PUSH EAX CALL GetHandleInformation TEST EAX, EAX JNZ @@Finish2 @@NoNTSystem: //Result := DuplicateHandle(GetCurrentProcess, Handle, GetCurrentProcess, // @Duplicate, 0, False, DUPLICATE_SAME_ACCESS); PUSH DUPLICATE_SAME_ACCESS PUSH $00000000 PUSH $00000000 LEA EAX, DWORD PTR [ESP+$0C] PUSH EAX CALL GetCurrentProcess PUSH EAX PUSH DWORD PTR [ESP+$18] PUSH EAX CALL DuplicateHandle TEST EAX, EAX JZ @@Finish2 // Result := CloseHandle(Duplicate); PUSH DWORD PTR [ESP] CALL CloseHandle @@Finish2: POP EDX POP EDX PUSH EAX PUSH $00000000 CALL SetLastError POP EAX {$ENDIF} @@Finish: End; {$ELSE} Var Duplicate: THandle; Flags: DWORD; Begin If IsWinNT Then Result := GetHandleInformation(Handle, Flags) Else Result := False; If Not Result Then Begin // DuplicateHandle is used as an additional check for those object types not // supported by GetHandleInformation (e.g. according to the documentation, // GetHandleInformation doesn't support window stations and desktop although // tests show that it does). GetHandleInformation is tried first because its // much faster. Additionally GetHandleInformation is only supported on NT... Result := DuplicateHandle(GetCurrentProcess, Handle, GetCurrentProcess, @Duplicate, 0, False, DUPLICATE_SAME_ACCESS); If Result Then Result := CloseHandle(Duplicate); End; End; {$ENDIF} {*******************************************************} { } { Delphi Supplemental Components } { ZLIB Data Compression Interface Unit } { } { Copyright (c) 1997 Borland International } { } {*******************************************************} { Modified for zlib 1.1.3 by Davide Moretti Z_STREAM_END do begin P := OutBuf; Inc(OutBytes, 256); ReallocMem(OutBuf, OutBytes); strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); strm.avail_out := 256; end; finally CCheck(deflateEnd(strm)); end; ReallocMem(OutBuf, strm.total_out); OutBytes := strm.total_out; except FreeMem(OutBuf); raise end; end; procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); var strm: TZStreamRec; P: Pointer; BufInc: Integer; begin FillChar(strm, sizeof(strm), 0); BufInc := (InBytes + 255) and not 255; if OutEstimate = 0 then OutBytes := BufInc else OutBytes := OutEstimate; GetMem(OutBuf, OutBytes); try strm.next_in := InBuf; strm.avail_in := InBytes; strm.next_out := OutBuf; strm.avail_out := OutBytes; DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); try while DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END do begin P := OutBuf; Inc(OutBytes, BufInc); ReallocMem(OutBuf, OutBytes); strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); strm.avail_out := BufInc; end; finally DCheck(inflateEnd(strm)); end; ReallocMem(OutBuf, strm.total_out); OutBytes := strm.total_out; except FreeMem(OutBuf); raise end; end; // TCustomZlibStream constructor TCustomZLibStream.Create(Strm: TStream); begin inherited Create; FStrm := Strm; FStrmPos := Strm.Position; end; procedure TCustomZLibStream.Progress(Sender: TObject); begin if Assigned(FOnProgress) then FOnProgress(Sender); end; // TCompressionStream constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel; Dest: TStream); const Levels: array [TCompressionLevel] of ShortInt = (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION); begin inherited Create(Dest); FZRec.next_out := FBuffer; FZRec.avail_out := sizeof(FBuffer); CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec))); end; destructor TCompressionStream.Destroy; begin FZRec.next_in := nil; FZRec.avail_in := 0; try if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END) and (FZRec.avail_out = 0) do begin FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); FZRec.next_out := FBuffer; FZRec.avail_out := sizeof(FBuffer); end; if FZRec.avail_out < sizeof(FBuffer) then FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out); finally deflateEnd(FZRec); end; inherited Destroy; end; function TCompressionStream.Read(var Buffer; Count: Longint): Longint; begin raise ECompressionError.Create('Invalid stream operation'); end; function TCompressionStream.Write(const Buffer; Count: Longint): Longint; begin FZRec.next_in := @Buffer; FZRec.avail_in := Count; if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; while (FZRec.avail_in > 0) do begin CCheck(deflate(FZRec, 0)); if FZRec.avail_out = 0 then begin FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); FZRec.next_out := FBuffer; FZRec.avail_out := sizeof(FBuffer); FStrmPos := FStrm.Position; Progress(Self); end; end; Result := Count; end; function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Offset = 0) and (Origin = soFromCurrent) then Result := FZRec.total_in else raise ECompressionError.Create('Invalid stream operation'); end; function TCompressionStream.GetCompressionRate: Single; begin if FZRec.total_in = 0 then Result := 0 else Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0; end; // TDecompressionStream constructor TDecompressionStream.Create(Source: TStream); begin inherited Create(Source); FZRec.next_in := FBuffer; FZRec.avail_in := 0; DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec))); end; destructor TDecompressionStream.Destroy; begin inflateEnd(FZRec); inherited Destroy; end; function TDecompressionStream.Read(var Buffer; Count: Longint): Longint; begin FZRec.next_out := @Buffer; FZRec.avail_out := Count; if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; while (FZRec.avail_out > 0) do begin if FZRec.avail_in = 0 then begin FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer)); if FZRec.avail_in = 0 then begin Result := Count - FZRec.avail_out; Exit; end; FZRec.next_in := FBuffer; FStrmPos := FStrm.Position; Progress(Self); end; DCheck(inflate(FZRec, 0)); end; Result := Count; end; function TDecompressionStream.Write(const Buffer; Count: Longint): Longint; begin raise EDecompressionError.Create('Invalid stream operation'); end; function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint; var I: Integer; Buf: array [0..4095] of Char; begin if (Offset = 0) and (Origin = soFromBeginning) then begin DCheck(inflateReset(FZRec)); FZRec.next_in := FBuffer; FZRec.avail_in := 0; FStrm.Position := 0; FStrmPos := 0; end else if ( (Offset >= 0) and (Origin = soFromCurrent)) or ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then begin if Origin = soFromBeginning then Dec(Offset, FZRec.total_out); if Offset > 0 then begin for I := 1 to Offset div sizeof(Buf) do ReadBuffer(Buf, sizeof(Buf)); ReadBuffer(Buf, Offset mod sizeof(Buf)); end; end else raise EDecompressionError.Create('Invalid stream operation'); Result := FZRec.total_out; end; end. pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.php000066400000000000000000000414411250413007300253640ustar00rootroot00000000000000 * @copyright Copyright (c) 2006, Manni * @version 1.0 * @link http://www.pkware.com/business_and_developers/developer/popups/appnote.txt * @link http://mannithedark.is-a-geek.net/ * @since 1.0 * @package fnord.bb * @subpackage archive */ class Zip extends Archive { /** * Outputs the zip file * * This function creates the zip file with the dirs and files given. * If the optional parameter $file is given, the zip file is will be * saved at that location. Otherwise the function returns the zip file's content. * * @access public * * @link http://www.pkware.com/business_and_developers/developer/popups/appnote.txt * @param string $filename The path where the zip file will be saved * * @return bool|string Returns either true if the fil is sucessfully created or the content of the zip file */ function out($filename = false) { // Empty output $file_data = array(); // Data of the file part $cd_data = array(); // Data of the central directory // Sort dirs and files by path length uksort($this->dirs, 'sort_by_length'); uksort($this->files, 'sort_by_length'); // Handle dirs foreach($this->dirs as $dir) { $dir .= '/'; // File part // Reset dir data $dir_data = ''; // Local file header $dir_data .= "\x50\x4b\x03\x04"; // Local file header signature $dir_data .= pack("v", 10); // Version needed to extract $dir_data .= pack("v", 0); // General purpose bit flag $dir_data .= pack("v", 0); // Compression method $dir_data .= pack("v", 0); // Last mod file time $dir_data .= pack("v", 0); // Last mod file date $dir_data .= pack("V", 0); // crc-32 $dir_data .= pack("V", 0); // Compressed size $dir_data .= pack("V", 0); // Uncompressed size $dir_data .= pack("v", strlen($dir)); // File name length $dir_data .= pack("v", 0); // Extra field length $dir_data .= $dir; // File name $dir_data .= ''; // Extra field (is empty) // File data $dir_data .= ''; // Dirs have no file data // Data descriptor $dir_data .= pack("V", 0); // crc-32 $dir_data .= pack("V", 0); // Compressed size $dir_data .= pack("V", 0); // Uncompressed size // Save current offset $offset = strlen(implode('', $file_data)); // Append dir data to the file part $file_data[] = $dir_data; // Central directory // Reset dir data $dir_data = ''; // File header $dir_data .= "\x50\x4b\x01\x02"; // Local file header signature $dir_data .= pack("v", 0); // Version made by $dir_data .= pack("v", 10); // Version needed to extract $dir_data .= pack("v", 0); // General purpose bit flag $dir_data .= pack("v", 0); // Compression method $dir_data .= pack("v", 0); // Last mod file time $dir_data .= pack("v", 0); // Last mod file date $dir_data .= pack("V", 0); // crc-32 $dir_data .= pack("V", 0); // Compressed size $dir_data .= pack("V", 0); // Uncompressed size $dir_data .= pack("v", strlen($dir)); // File name length $dir_data .= pack("v", 0); // Extra field length $dir_data .= pack("v", 0); // File comment length $dir_data .= pack("v", 0); // Disk number start $dir_data .= pack("v", 0); // Internal file attributes $dir_data .= pack("V", 16); // External file attributes $dir_data .= pack("V", $offset); // Relative offset of local header $dir_data .= $dir; // File name $dir_data .= ''; // Extra field (is empty) $dir_data .= ''; // File comment (is empty) /* // Data descriptor $dir_data .= pack("V", 0); // crc-32 $dir_data .= pack("V", 0); // Compressed size $dir_data .= pack("V", 0); // Uncompressed size */ // Append dir data to the central directory data $cd_data[] = $dir_data; } // Handle files foreach($this->files as $name => $file) { // Get values $content = $file[0]; // File part // Reset file data $fd = ''; // Detect possible compressions // Use deflate if(function_exists('gzdeflate')) { $method = 8; // Compress file content $compressed_data = gzdeflate($content); // Use bzip2 } elseif(function_exists('bzcompress')) { $method = 12; // Compress file content $compressed_data = bzcompress($content); // No compression } else { $method = 0; // Do not compress the content :P $compressed_data = $content; } // Local file header $fd .= "\x50\x4b\x03\x04"; // Local file header signature $fd .= pack("v", 20); // Version needed to extract $fd .= pack("v", 0); // General purpose bit flag $fd .= pack("v", $method); // Compression method $fd .= pack("v", 0); // Last mod file time $fd .= pack("v", 0); // Last mod file date $fd .= pack("V", crc32($content)); // crc-32 $fd .= pack("V", strlen($compressed_data)); // Compressed size $fd .= pack("V", strlen($content)); // Uncompressed size $fd .= pack("v", strlen($name)); // File name length $fd .= pack("v", 0); // Extra field length $fd .= $name; // File name $fd .= ''; // Extra field (is empty) // File data $fd .= $compressed_data; // Data descriptor $fd .= pack("V", crc32($content)); // crc-32 $fd .= pack("V", strlen($compressed_data)); // Compressed size $fd .= pack("V", strlen($content)); // Uncompressed size // Save current offset $offset = strlen(implode('', $file_data)); // Append file data to the file part $file_data[] = $fd; // Central directory // Reset file data $fd = ''; // File header $fd .= "\x50\x4b\x01\x02"; // Local file header signature $fd .= pack("v", 0); // Version made by $fd .= pack("v", 20); // Version needed to extract $fd .= pack("v", 0); // General purpose bit flag $fd .= pack("v", $method); // Compression method $fd .= pack("v", 0); // Last mod file time $fd .= pack("v", 0); // Last mod file date $fd .= pack("V", crc32($content)); // crc-32 $fd .= pack("V", strlen($compressed_data)); // Compressed size $fd .= pack("V", strlen($content)); // Uncompressed size $fd .= pack("v", strlen($name)); // File name length $fd .= pack("v", 0); // Extra field length $fd .= pack("v", 0); // File comment length $fd .= pack("v", 0); // Disk number start $fd .= pack("v", 0); // Internal file attributes $fd .= pack("V", 32); // External file attributes $fd .= pack("V", $offset); // Relative offset of local header $fd .= $name; // File name $fd .= ''; // Extra field (is empty) $fd .= ''; // File comment (is empty) /* // Data descriptor $fd .= pack("V", crc32($content)); // crc-32 $fd .= pack("V", strlen($compressed_data)); // Compressed size $fd .= pack("V", strlen($content)); // Uncompressed size */ // Append file data to the central directory data $cd_data[] = $fd; } // Digital signature $digital_signature = ''; $digital_signature .= "\x50\x4b\x05\x05"; // Header signature $digital_signature .= pack("v", 0); // Size of data $digital_signature .= ''; // Signature data (is empty) $tmp_file_data = implode('', $file_data); // File data $tmp_cd_data = implode('', $cd_data). // Central directory $digital_signature; // Digital signature // End of central directory $eof_cd = ''; $eof_cd .= "\x50\x4b\x05\x06"; // End of central dir signature $eof_cd .= pack("v", 0); // Number of this disk $eof_cd .= pack("v", 0); // Number of the disk with the start of the central directory $eof_cd .= pack("v", count($cd_data)); // Total number of entries in the central directory on this disk $eof_cd .= pack("v", count($cd_data)); // Total number of entries in the central directory $eof_cd .= pack("V", strlen($tmp_cd_data)); // Size of the central directory $eof_cd .= pack("V", strlen($tmp_file_data)); // Offset of start of central directory with respect to the starting disk number $eof_cd .= pack("v", 0); // .ZIP file comment length $eof_cd .= ''; // .ZIP file comment (is empty) // Content of the zip file $data = $tmp_file_data. // $extra_data_record. $tmp_cd_data. $eof_cd; // Return content? if(!$filename) return $data; // Write to file return file_put_contents($filename, $data); } /** * Load a zip file * * This function loads the files and dirs from a zip file from the harddrive. * * @access public * * @param string $file The path to the zip file * @param bool $reset Reset the files and dirs before adding the zip file's content? * * @return bool Returns true if the file was loaded sucessfully */ function load_file($file, $reset = true) { // Check whether the file exists if(!file_exists($file)) return false; // Load the files content $content = @file_get_contents($file); // Return false if the file cannot be opened if(!$content) return false; // Read the zip return $this->load_string($content, $reset); } /** * Load a zip string * * This function loads the files and dirs from a string * * @access public * * @param string $string The string the zip is generated from * @param bool $reset Reset the files and dirs before adding the zip file's content? * * @return bool Returns true if the string was loaded sucessfully */ function load_string($string, $reset = true) { // Reset the zip? if($reset) { $this->dirs = array(); $this->files = array(); } // Get the starting position of the end of central directory record $start = strpos($string, "\x50\x4b\x05\x06"); // Error if($start === false) die('Could not find the end of central directory record'); // Get the ecdr $eof_cd = substr($string, $start+4, 18); // Unpack the ecdr infos $eof_cd = unpack('vdisc1/'. 'vdisc2/'. 'ventries1/'. 'ventries2/'. 'Vsize/'. 'Voffset/'. 'vcomment_lenght', $eof_cd); // Do not allow multi disc zips if($eof_cd['disc1'] != 0) die('multi disk stuff is not yet implemented :/'); // Save the interesting values $cd_entries = $eof_cd['entries1']; $cd_size = $eof_cd['size']; $cd_offset = $eof_cd['offset']; // Get the central directory record $cdr = substr($string, $cd_offset, $cd_size); // Reset the position and the list of the entries $pos = 0; $entries = array(); // Handle cdr while($pos < strlen($cdr)) { // Check header signature // Digital signature if(substr($cdr, $pos, 4) == "\x50\x4b\x05\x05") { // Get digital signature size $tmp_info = unpack('vsize', substr($cdr, $pos + 4, 2)); // Read out the digital signature $digital_sig = substr($header, $pos + 6, $tmp_info['size']); break; } // Get file header $header = substr($cdr, $pos, 46); // Unpack the header information $header_info = @unpack('Vheader/'. 'vversion_made_by/'. 'vversion_needed/'. 'vgeneral_purpose/'. 'vcompression_method/'. 'vlast_mod_time/'. 'vlast_mod_date/'. 'Vcrc32/'. 'Vcompressed_size/'. 'Vuncompressed_size/'. 'vname_length/'. 'vextra_length/'. 'vcomment_length/'. 'vdisk_number/'. 'vinternal_attributes/'. 'Vexternal_attributes/'. 'Voffset', $header); // Valid header? if($header_info['header'] != 33639248) return false; // New position $pos += 46; // Read out the file name $header_info['name'] = substr($cdr, $pos, $header_info['name_length']); // New position $pos += $header_info['name_length']; // Read out the extra stuff $header_info['extra'] = substr($cdr, $pos, $header_info['extra_length']); // New position $pos += $header_info['extra_length']; // Read out the comment $header_info['comment'] = substr($cdr, $pos, $header_info['comment_length']); // New position $pos += $header_info['comment_length']; // Append this file/dir to the entry list $entries[] = $header_info; } // Check whether all entries where read sucessfully if(count($entries) != $cd_entries) return false; // Handle files/dirs foreach($entries as $entry) { // Is a dir? if($entry['external_attributes'] & 16) { $this->add_dir($entry['name']); continue; } // Get local file header $header = substr($string, $entry['offset'], 30); // Unpack the header information $header_info = @unpack('Vheader/'. 'vversion_needed/'. 'vgeneral_purpose/'. 'vcompression_method/'. 'vlast_mod_time/'. 'vlast_mod_date/'. 'Vcrc32/'. 'Vcompressed_size/'. 'Vuncompressed_size/'. 'vname_length/'. 'vextra_length', $header); // Valid header? if($header_info['header'] != 67324752) return false; // Get content start position $start = $entry['offset'] + 30 + $header_info['name_length'] + $header_info['extra_length']; // Get the compressed data $data = substr($string, $start, $header_info['compressed_size']); // Detect compression type switch($header_info['compression_method']) { // No compression case 0: // Ne decompression needed $content = $data; break; // Gzip case 8: if(!function_exists('gzinflate')) return false; // Uncompress data $content = gzinflate($data); break; // Bzip2 case 12: if(!function_exists('bzdecompress')) return false; // Decompress data $content = bzdecompress($data); break; // Compression not supported -> error default: return false; } // Try to add file if(!$this->add_file($entry['name'], $content)) return false; } return true; } } function &byref() { $x = array(); return $x; } ?> pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.pig000066400000000000000000000150011250413007300253450ustar00rootroot00000000000000/** * This script is an example recommender (using made up data) showing how you might modify item-item links * by defining similar relations between items in a dataset and customizing the change in weighting. * This example creates metadata by using the genre field as the metadata_field. The items with * the same genre have it's weight cut in half in order to boost the signals of movies that do not have the same genre. * This technique requires a customization of the standard GetItemItemRecommendations macro */ import 'recommenders.pig'; %default INPUT_PATH_PURCHASES '../data/retail/purchases.json' %default INPUT_PATH_WISHLIST '../data/retail/wishlists.json' %default INPUT_PATH_INVENTORY '../data/retail/inventory.json' %default OUTPUT_PATH '../data/retail/out/modify_item_item' /******** Custom GetItemItemRecommnedations *********/ define recsys__GetItemItemRecommendations_ModifyCustom(user_item_signals, metadata) returns item_item_recs { -- Convert user_item_signals to an item_item_graph ii_links_raw, item_weights = recsys__BuildItemItemGraph( $user_item_signals, $LOGISTIC_PARAM, $MIN_LINK_WEIGHT, $MAX_LINKS_PER_USER ); -- NOTE this function is added in order to combine metadata with item-item links -- See macro for more detailed explination ii_links_metadata = recsys__AddMetadataToItemItemLinks( ii_links_raw, $metadata ); /********* Custom Code starts here ********/ --The code here should adjust the weights based on an item-item link and the equality of metadata. -- In this case, if the metadata is the same, the weight is reduced. Otherwise the weight is left alone. ii_links_adjusted = foreach ii_links_metadata generate item_A, item_B, -- the amount of weight adjusted is dependant on the domain of data and what is expected -- It is always best to adjust the weight by multiplying it by a factor rather than addition with a constant (metadata_B == metadata_A ? (weight * 0.5): weight) as weight; /******** Custom Code stops here *********/ -- remove negative numbers just incase ii_links_adjusted_filt = foreach ii_links_adjusted generate item_A, item_B, (weight <= 0 ? 0: weight) as weight; -- Adjust the weights of the graph to improve recommendations. ii_links = recsys__AdjustItemItemGraphWeight( ii_links_adjusted_filt, item_weights, $BAYESIAN_PRIOR ); -- Use the item-item graph to create item-item recommendations. $item_item_recs = recsys__BuildItemItemRecommendationsFromGraph( ii_links, $NUM_RECS_PER_ITEM, $NUM_RECS_PER_ITEM ); }; /******* Load Data **********/ --Get purchase signals purchase_input = load '$INPUT_PATH_PURCHASES' using org.apache.pig.piggybank.storage.JsonLoader( 'row_id: int, movie_id: chararray, movie_name: chararray, user_id: chararray, purchase_price: int'); --Get wishlist signals wishlist_input = load '$INPUT_PATH_WISHLIST' using org.apache.pig.piggybank.storage.JsonLoader( 'row_id: int, movie_id: chararray, movie_name: chararray, user_id: chararray'); /******* Convert Data to Signals **********/ -- Start with choosing 1 as max weight for a signal. purchase_signals = foreach purchase_input generate user_id as user, movie_name as item, 1.0 as weight; -- Start with choosing 0.5 as weight for wishlist items because that is a weaker signal than -- purchasing an item. wishlist_signals = foreach wishlist_input generate user_id as user, movie_name as item, 0.5 as weight; user_signals = union purchase_signals, wishlist_signals; /******** Changes for Modifying item-item links ******/ inventory_input = load '$INPUT_PATH_INVENTORY' using org.apache.pig.piggybank.storage.JsonLoader( 'movie_title: chararray, genres: bag{tuple(content:chararray)}'); metadata = foreach inventory_input generate FLATTEN(genres) as metadata_field, movie_title as item; -- requires the macro to be written seperately --NOTE this macro is defined within this file for clarity item_item_recs = recsys__GetItemItemRecommendations_ModifyCustom(user_signals, metadata); /******* No more changes ********/ user_item_recs = recsys__GetUserItemRecommendations(user_signals, item_item_recs); --Completely unrelated code stuck in the middle data = LOAD 's3n://my-s3-bucket/path/to/responses' USING org.apache.pig.piggybank.storage.JsonLoader(); responses = FOREACH data GENERATE object#'response' AS response: map[]; out = FOREACH responses GENERATE response#'id' AS id: int, response#'thread' AS thread: chararray, response#'comments' AS comments: {t: (comment: chararray)}; STORE out INTO 's3n://path/to/output' USING PigStorage('|'); /******* Store recommendations **********/ -- If your output folder exists already, hadoop will refuse to write data to it. rmf $OUTPUT_PATH/item_item_recs; rmf $OUTPUT_PATH/user_item_recs; store item_item_recs into '$OUTPUT_PATH/item_item_recs' using PigStorage(); store user_item_recs into '$OUTPUT_PATH/user_item_recs' using PigStorage(); -- STORE the item_item_recs into dynamo STORE item_item_recs INTO '$OUTPUT_PATH/unused-ii-table-data' USING com.mortardata.pig.storage.DynamoDBStorage('$II_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY'); -- STORE the user_item_recs into dynamo STORE user_item_recs INTO '$OUTPUT_PATH/unused-ui-table-data' USING com.mortardata.pig.storage.DynamoDBStorage('$UI_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY'); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.plot000066400000000000000000000242101250413007300255460ustar00rootroot00000000000000# # $Id: prob2.dem,v 1.9 2006/06/14 03:24:09 sfeam Exp $ # # Demo Statistical Approximations version 1.1 # # Copyright (c) 1991, Jos van der Woude, jvdwoude@hut.nl # History: # -- --- 1991 Jos van der Woude: 1st version # 06 Jun 2006 Dan Sebald: Added plot methods for better visual effect. print "" print "" print "" print "" print "" print "" print " Statistical Approximations, version 1.1" print "" print " Copyright (c) 1991, 1992, Jos van de Woude, jvdwoude@hut.nl" print "" print "" print "" print "" print "" print "" print "" print "" print "" print "" print "" print " NOTE: contains 10 plots and consequently takes some time to run" print " Press Ctrl-C to exit right now" print "" pause -1 " Press Return to start demo ..." load "stat.inc" rnd(x) = floor(x+0.5) r_xmin = -1 r_sigma = 4.0 # Binomial PDF using normal approximation n = 25; p = 0.15 mu = n * p sigma = sqrt(n * p * (1.0 - p)) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * binom(floor((n+1)*p), n, p) #mode of binomial PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "binomial PDF using normal approximation" set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot binom(rnd(x), n, p) with histeps, normal(x, mu, sigma) pause -1 "Hit return to continue" unset arrow unset label # Binomial PDF using poisson approximation n = 50; p = 0.1 mu = n * p sigma = sqrt(mu) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * binom(floor((n+1)*p), n, p) #mode of binomial PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample (xmax - xmin + 3) set title "binomial PDF using poisson approximation" set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot binom(x, n, p) with histeps, poisson(x, mu) with histeps pause -1 "Hit return to continue" unset arrow unset label # Geometric PDF using gamma approximation p = 0.3 mu = (1.0 - p) / p sigma = sqrt(mu / p) lambda = p rho = 1.0 - p xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * p set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "geometric PDF using gamma approximation" set arrow from mu, 0 to mu, gmm(mu, rho, lambda) nohead set arrow from mu, gmm(mu + sigma, rho, lambda) \ to mu + sigma, gmm(mu + sigma, rho, lambda) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, gmm(mu + sigma, rho, lambda) plot geometric(rnd(x),p) with histeps, gmm(x, rho, lambda) pause -1 "Hit return to continue" unset arrow unset label # Geometric PDF using normal approximation p = 0.3 mu = (1.0 - p) / p sigma = sqrt(mu / p) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * p set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "geometric PDF using normal approximation" set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot geometric(rnd(x),p) with histeps, normal(x, mu, sigma) pause -1 "Hit return to continue" unset arrow unset label # Hypergeometric PDF using binomial approximation nn = 75; mm = 25; n = 10 p = real(mm) / nn mu = n * p sigma = sqrt(real(nn - n) / (nn - 1.0) * n * p * (1.0 - p)) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * hypgeo(floor(mu), nn, mm, n) #mode of binom PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample (xmax - xmin + 3) set title "hypergeometric PDF using binomial approximation" set arrow from mu, 0 to mu, binom(floor(mu), n, p) nohead set arrow from mu, binom(floor(mu + sigma), n, p) \ to mu + sigma, binom(floor(mu + sigma), n, p) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, binom(floor(mu + sigma), n, p) plot hypgeo(x, nn, mm, n) with histeps, binom(x, n, p) with histeps pause -1 "Hit return to continue" unset arrow unset label # Hypergeometric PDF using normal approximation nn = 75; mm = 25; n = 10 p = real(mm) / nn mu = n * p sigma = sqrt(real(nn - n) / (nn - 1.0) * n * p * (1.0 - p)) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * hypgeo(floor(mu), nn, mm, n) #mode of binom PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "hypergeometric PDF using normal approximation" set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot hypgeo(rnd(x), nn, mm, n) with histeps, normal(x, mu, sigma) pause -1 "Hit return to continue" unset arrow unset label # Negative binomial PDF using gamma approximation r = 8; p = 0.6 mu = r * (1.0 - p) / p sigma = sqrt(mu / p) lambda = p rho = r * (1.0 - p) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * gmm((rho - 1) / lambda, rho, lambda) #mode of gamma PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "negative binomial PDF using gamma approximation" set arrow from mu, 0 to mu, gmm(mu, rho, lambda) nohead set arrow from mu, gmm(mu + sigma, rho, lambda) \ to mu + sigma, gmm(mu + sigma, rho, lambda) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, gmm(mu + sigma, rho, lambda) plot negbin(rnd(x), r, p) with histeps, gmm(x, rho, lambda) pause -1 "Hit return to continue" unset arrow unset label # Negative binomial PDF using normal approximation r = 8; p = 0.4 mu = r * (1.0 - p) / p sigma = sqrt(mu / p) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * negbin(floor((r-1)*(1-p)/p), r, p) #mode of gamma PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "negative binomial PDF using normal approximation" set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot negbin(rnd(x), r, p) with histeps, normal(x, mu, sigma) pause -1 "Hit return to continue" unset arrow unset label # Normal PDF using logistic approximation mu = 1.0; sigma = 1.5 a = mu lambda = pi / (sqrt(3.0) * sigma) xmin = mu - r_sigma * sigma xmax = mu + r_sigma * sigma ymax = 1.1 * logistic(mu, a, lambda) #mode of logistic PDF used set key box unset zeroaxis set xrange [xmin: xmax] set yrange [0 : ymax] set xlabel "x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%.1f" set format y "%.2f" set sample 200 set title "normal PDF using logistic approximation" set arrow from mu,0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot logistic(x, a, lambda), normal(x, mu, sigma) pause -1 "Hit return to continue" unset arrow unset label # Poisson PDF using normal approximation mu = 5.0 sigma = sqrt(mu) xmin = floor(mu - r_sigma * sigma) xmin = xmin < r_xmin ? r_xmin : xmin xmax = ceil(mu + r_sigma * sigma) ymax = 1.1 * poisson(mu, mu) #mode of poisson PDF used set key box unset zeroaxis set xrange [xmin - 1 : xmax + 1] set yrange [0 : ymax] set xlabel "k, x ->" set ylabel "probability density ->" set ytics 0, ymax / 10.0, ymax set format x "%2.0f" set format y "%3.2f" set sample 200 set title "poisson PDF using normal approximation" set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead set arrow from mu, normal(mu + sigma, mu, sigma) \ to mu + sigma, normal(mu + sigma, mu, sigma) nohead set label "mu" at mu + 0.5, ymax / 10 set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) plot poisson(rnd(x), mu) with histeps, normal(x, mu, sigma) pause -1 "Hit return to continue" reset pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.ps1000066400000000000000000000113071250413007300252760ustar00rootroot00000000000000<# .SYNOPSIS Runs a T-SQL Query and optional outputs results to a delimited file. .DESCRIPTION Invoke-Sql script will run a T-SQL query or stored procedure and optionally outputs a delimited file. .EXAMPLE PowerShell.exe -File "C:\Scripts\Invoke-Sql.ps1" -ServerInstance "Z003\sqlprod2" -Database orders -Query "EXEC usp_accounts '12445678'" This example connects to Z003\sqlprod2.Orders and executes a stored procedure which does not return a result set .EXAMPLE PowerShell.exe -File "C:\Scripts\Invoke-Sql.ps1" -ServerInstance "Z003\sqlprod2" -Database orders -Query "SELECT * FROM dbo.accounts" -FilePath "C:\Scripts\accounts.txt" -Delimiter "," This example connects to Z003\sqlprod2.Orders and selects the records from the accounts tables, the data is outputed to a CSV file .NOTES Version History v1.0 - Chad Miller - 12/14/2010 - Initial release IMPORTANT!!! The EventLog source which is set to the application needs to be registered with the Event log: New-EventLog -LogName Application -Source $Application #> param( #ServerInstance is Mandatory! [Parameter(Position=0, Mandatory=$false)] [string]$ServerInstance, #Database is Mandatory! [Parameter(Position=1, Mandatory=$false)] [string]$Database, #Query is Mandatory! [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Application="Invoke-Sql.ps1", [Parameter(Position=4, Mandatory=$false)] [string]$FilePath, [Parameter(Position=7, Mandatory=$false)] [string]$Delimiter="|", #If UserName isn't supplied a trusted connection will be used [Parameter(Position=5, Mandatory=$false)] [string]$UserName, [Parameter(Position=6, Mandatory=$false)] [string]$Password, [Parameter(Position=8, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=9, Mandatory=$false)] [Int32]$ConnectionTimeout=15 ) #This must be run as administrator on Windows 2008 and higher! New-EventLog -LogName Application -Source $Application -EA SilentlyContinue $Error.Clear() ####################### function Invoke-SqlCmd2 { param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$UserName, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout ) try { if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn=new-object System.Data.SqlClient.SQLConnection $conn.ConnectionString=$ConnectionString $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) Write-Output ($ds.Tables[0]) } finally { $conn.Dispose() } } #Invoke-SqlCmd2 ####################### # MAIN # ####################### if ($PSBoundParameters.Count -eq 0) { get-help $myInvocation.MyCommand.Path -full break } try { $msg = $null $msg += "Application/Job Name: $Application`n" $msg += "Query: $Query`n" $msg += "ServerInstance: $ServerInstance`n" $msg += "Database: $Database`n" $msg += "FilePath: $FilePath`n" Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Starting`n$msg" $dt = Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database $Database -Query $Query -UserName $UserName -Password $Password -QueryTimeOut $QueryTimeOut -ConnectionTimeout $ConnectionTimeout if ($FilePath) { if ($dt) { $dt | export-csv -Delimiter $Delimiter -Path $FilePath -NoTypeInformation } else #Query Returned No Output! {Write-EventLog -LogName Application -Source "$Application" -EntryType Warning -EventId 12345 -Message "NoOutput`n$msg" } } Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Completed`n$msg" } catch { $Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" ) Write-EventLog -LogName Application -Source "$Application" -EntryType Error -EventId 12345 -Message "Error`n$msg`n$Exception" throw } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.pwn000066400000000000000000000146331250413007300254040ustar00rootroot00000000000000#include // Single line comment /* Multi line comment */ /// documentation /** documentation multi line **/ public OnGameModeInit() { printf("Hello, World!"); } enum info { Float:ex; exa, exam[5], } new arr[5][info]; stock Float:test_func() { new a = 5, Float:b = 10.3; if (a == b) { } else { } for (new i = 0; i < 10; i++) { continue; } do { a--; } while (a > 0); while (a < 5) { a++; break; } switch (a) { case 0: { } case 0..4: { } case 5, 6: { } } static x; new xx = a > 5 ? 5 : 0; new array[sizeof arr] = {0}; tagof a; state a; goto label; new byte[2 char]; byte{0} = 'a'; return (float(a) + b); } // float.inc /* Float arithmetic * * (c) Copyright 1999, Artran, Inc. * Written by Greg Garner (gmg@artran.com) * Modified in March 2001 to include user defined * operators for the floating point functions. * * This file is provided as is (no warranties). */ #if defined _Float_included #endinput #endif #define _Float_included #pragma library Float /* Different methods of rounding */ enum floatround_method { floatround_round, floatround_floor, floatround_ceil, floatround_tozero, floatround_unbiased } enum anglemode { radian, degrees, grades } /**************************************************/ /* Convert an integer into a floating point value */ native Float:float(value); /**************************************************/ /* Convert a string into a floating point value */ native Float:floatstr(const string[]); /**************************************************/ /* Multiple two floats together */ native Float:floatmul(Float:oper1, Float:oper2); /**************************************************/ /* Divide the dividend float by the divisor float */ native Float:floatdiv(Float:dividend, Float:divisor); /**************************************************/ /* Add two floats together */ native Float:floatadd(Float:oper1, Float:oper2); /**************************************************/ /* Subtract oper2 float from oper1 float */ native Float:floatsub(Float:oper1, Float:oper2); /**************************************************/ /* Return the fractional part of a float */ native Float:floatfract(Float:value); /**************************************************/ /* Round a float into a integer value */ native floatround(Float:value, floatround_method:method=floatround_round); /**************************************************/ /* Compare two integers. If the two elements are equal, return 0. If the first argument is greater than the second argument, return 1, If the first argument is less than the second argument, return -1. */ native floatcmp(Float:oper1, Float:oper2); /**************************************************/ /* Return the square root of the input value, same as floatpower(value, 0.5) */ native Float:floatsqroot(Float:value); /**************************************************/ /* Return the value raised to the power of the exponent */ native Float:floatpower(Float:value, Float:exponent); /**************************************************/ /* Return the logarithm */ native Float:floatlog(Float:value, Float:base=10.0); /**************************************************/ /* Return the sine, cosine or tangent. The input angle may be in radian, degrees or grades. */ native Float:floatsin(Float:value, anglemode:mode=radian); native Float:floatcos(Float:value, anglemode:mode=radian); native Float:floattan(Float:value, anglemode:mode=radian); /**************************************************/ /* Return the absolute value */ native Float:floatabs(Float:value); /**************************************************/ #pragma rational Float /* user defined operators */ native Float:operator*(Float:oper1, Float:oper2) = floatmul; native Float:operator/(Float:oper1, Float:oper2) = floatdiv; native Float:operator+(Float:oper1, Float:oper2) = floatadd; native Float:operator-(Float:oper1, Float:oper2) = floatsub; native Float:operator=(oper) = float; stock Float:operator++(Float:oper) return oper+1.0; stock Float:operator--(Float:oper) return oper-1.0; stock Float:operator-(Float:oper) return oper^Float:cellmin; /* IEEE values are sign/magnitude */ stock Float:operator*(Float:oper1, oper2) return floatmul(oper1, float(oper2)); /* "*" is commutative */ stock Float:operator/(Float:oper1, oper2) return floatdiv(oper1, float(oper2)); stock Float:operator/(oper1, Float:oper2) return floatdiv(float(oper1), oper2); stock Float:operator+(Float:oper1, oper2) return floatadd(oper1, float(oper2)); /* "+" is commutative */ stock Float:operator-(Float:oper1, oper2) return floatsub(oper1, float(oper2)); stock Float:operator-(oper1, Float:oper2) return floatsub(float(oper1), oper2); stock bool:operator==(Float:oper1, Float:oper2) return floatcmp(oper1, oper2) == 0; stock bool:operator==(Float:oper1, oper2) return floatcmp(oper1, float(oper2)) == 0; /* "==" is commutative */ stock bool:operator!=(Float:oper1, Float:oper2) return floatcmp(oper1, oper2) != 0; stock bool:operator!=(Float:oper1, oper2) return floatcmp(oper1, float(oper2)) != 0; /* "!=" is commutative */ stock bool:operator>(Float:oper1, Float:oper2) return floatcmp(oper1, oper2) > 0; stock bool:operator>(Float:oper1, oper2) return floatcmp(oper1, float(oper2)) > 0; stock bool:operator>(oper1, Float:oper2) return floatcmp(float(oper1), oper2) > 0; stock bool:operator>=(Float:oper1, Float:oper2) return floatcmp(oper1, oper2) >= 0; stock bool:operator>=(Float:oper1, oper2) return floatcmp(oper1, float(oper2)) >= 0; stock bool:operator>=(oper1, Float:oper2) return floatcmp(float(oper1), oper2) >= 0; stock bool:operator<(Float:oper1, Float:oper2) return floatcmp(oper1, oper2) < 0; stock bool:operator<(Float:oper1, oper2) return floatcmp(oper1, float(oper2)) < 0; stock bool:operator<(oper1, Float:oper2) return floatcmp(float(oper1), oper2) < 0; stock bool:operator<=(Float:oper1, Float:oper2) return floatcmp(oper1, oper2) <= 0; stock bool:operator<=(Float:oper1, oper2) return floatcmp(oper1, float(oper2)) <= 0; stock bool:operator<=(oper1, Float:oper2) return floatcmp(float(oper1), oper2) <= 0; stock bool:operator!(Float:oper) return (_:oper & cellmax) == 0; /* forbidden operations */ forward operator%(Float:oper1, Float:oper2); forward operator%(Float:oper1, oper2); forward operator%(oper1, Float:oper2); pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.pypylog000066400000000000000000005776111250413007300263150ustar00rootroot00000000000000[5ed621f277b8] {jit-backend-counts [5ed621f309bc] jit-backend-counts} [5ed622c957b0] {jit-log-opt-loop # Loop 0 : loop with 145 ops [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, f11, p12, p13, p14, p15, i16, f17, i18, i19, i20, i21, i22, i23, i24, i25, i26, f27, i28, f29, f30] debug_merge_point(' #125 FOR_ITER', 0) i32 = int_gt(i18, 0) guard_true(i32, descr=) [p1, p0, p5, p2, p3, p4, p6, p7, p8, p9, p10, p12, p13, p14, p15, i16, f17, f11] i33 = int_add(i19, i20) i35 = int_sub(i18, 1) debug_merge_point(' #128 STORE_FAST', 0) debug_merge_point(' #131 LOAD_FAST', 0) debug_merge_point(' #134 LOAD_FAST', 0) debug_merge_point(' #137 LOAD_FAST', 0) debug_merge_point(' #140 BINARY_MULTIPLY', 0) setfield_gc(p5, i33, descr=) setfield_gc(p5, i35, descr=) i36 = int_mul_ovf(i21, i22) guard_no_overflow(, descr=) [p1, p0, p12, p15, i36, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p13, i19, None, f17, f11] debug_merge_point(' #141 LOAD_FAST', 0) debug_merge_point(' #144 BINARY_ADD', 0) i38 = int_add_ovf(i36, i19) guard_no_overflow(, descr=) [p1, p0, i38, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i36, i19, None, f17, f11] debug_merge_point(' #145 BINARY_SUBSCR', 0) i40 = int_lt(i38, 0) guard_false(i40, descr=) [p1, p0, p14, i38, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, i19, None, f17, f11] i41 = int_lt(i38, i23) guard_true(i41, descr=) [p1, p0, p14, i38, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, i19, None, f17, f11] f42 = getarrayitem_raw(i24, i38, descr=) debug_merge_point(' #146 STORE_FAST', 0) debug_merge_point(' #149 LOAD_FAST', 0) debug_merge_point(' #152 LOAD_FAST', 0) debug_merge_point(' #155 LOAD_CONST', 0) debug_merge_point(' #158 BINARY_SUBTRACT', 0) debug_merge_point(' #159 LOAD_FAST', 0) debug_merge_point(' #162 BINARY_MULTIPLY', 0) debug_merge_point(' #163 LOAD_FAST', 0) debug_merge_point(' #166 BINARY_ADD', 0) i43 = int_add_ovf(i25, i19) guard_no_overflow(, descr=) [p1, p0, i43, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f42, i25, None, i19, None, None, f11] debug_merge_point(' #167 BINARY_SUBSCR', 0) i45 = int_lt(i43, 0) guard_false(i45, descr=) [p1, p0, p14, i43, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f42, None, None, i19, None, None, f11] i46 = int_lt(i43, i23) guard_true(i46, descr=) [p1, p0, p14, i43, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f42, None, None, i19, None, None, f11] f47 = getarrayitem_raw(i24, i43, descr=) debug_merge_point(' #168 LOAD_FAST', 0) debug_merge_point(' #171 LOAD_FAST', 0) debug_merge_point(' #174 LOAD_CONST', 0) debug_merge_point(' #177 BINARY_ADD', 0) debug_merge_point(' #178 LOAD_FAST', 0) debug_merge_point(' #181 BINARY_MULTIPLY', 0) debug_merge_point(' #182 LOAD_FAST', 0) debug_merge_point(' #185 BINARY_ADD', 0) i48 = int_add_ovf(i26, i19) guard_no_overflow(, descr=) [p1, p0, i48, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i26, f47, f42, None, None, i19, None, None, f11] debug_merge_point(' #186 BINARY_SUBSCR', 0) i50 = int_lt(i48, 0) guard_false(i50, descr=) [p1, p0, p14, i48, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f47, f42, None, None, i19, None, None, f11] i51 = int_lt(i48, i23) guard_true(i51, descr=) [p1, p0, p14, i48, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f47, f42, None, None, i19, None, None, f11] f52 = getarrayitem_raw(i24, i48, descr=) debug_merge_point(' #187 BINARY_ADD', 0) f53 = float_add(f47, f52) debug_merge_point(' #188 LOAD_FAST', 0) debug_merge_point(' #191 BINARY_MULTIPLY', 0) f54 = float_mul(f53, f27) debug_merge_point(' #192 LOAD_FAST', 0) debug_merge_point(' #195 LOAD_FAST', 0) debug_merge_point(' #198 LOAD_FAST', 0) debug_merge_point(' #201 BINARY_MULTIPLY', 0) debug_merge_point(' #202 LOAD_FAST', 0) debug_merge_point(' #205 BINARY_ADD', 0) i55 = int_add_ovf(i28, i19) guard_no_overflow(, descr=) [p1, p0, i55, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f54, i28, None, None, f42, None, None, i19, None, None, f11] debug_merge_point(' #206 LOAD_CONST', 0) debug_merge_point(' #209 BINARY_SUBTRACT', 0) i57 = int_sub_ovf(i55, 1) guard_no_overflow(, descr=) [p1, p0, i57, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i55, f54, None, None, None, f42, None, None, i19, None, None, f11] debug_merge_point(' #210 BINARY_SUBSCR', 0) i59 = int_lt(i57, 0) guard_false(i59, descr=) [p1, p0, p14, i57, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f54, None, None, None, f42, None, None, i19, None, None, f11] i60 = int_lt(i57, i23) guard_true(i60, descr=) [p1, p0, p14, i57, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f54, None, None, None, f42, None, None, i19, None, None, f11] f61 = getarrayitem_raw(i24, i57, descr=) debug_merge_point(' #211 LOAD_FAST', 0) debug_merge_point(' #214 LOAD_FAST', 0) debug_merge_point(' #217 LOAD_FAST', 0) debug_merge_point(' #220 BINARY_MULTIPLY', 0) debug_merge_point(' #221 LOAD_FAST', 0) debug_merge_point(' #224 BINARY_ADD', 0) debug_merge_point(' #225 LOAD_CONST', 0) debug_merge_point(' #228 BINARY_ADD', 0) i63 = int_add_ovf(i55, 1) guard_no_overflow(, descr=) [p1, p0, i63, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f61, i55, f54, None, None, None, f42, None, None, i19, None, None, f11] debug_merge_point(' #229 BINARY_SUBSCR', 0) i64 = int_lt(i63, i23) guard_true(i64, descr=) [p1, p0, p14, i63, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f61, None, f54, None, None, None, f42, None, None, i19, None, None, f11] f65 = getarrayitem_raw(i24, i63, descr=) debug_merge_point(' #230 BINARY_ADD', 0) f66 = float_add(f61, f65) debug_merge_point(' #231 LOAD_FAST', 0) debug_merge_point(' #234 BINARY_MULTIPLY', 0) f67 = float_mul(f66, f29) debug_merge_point(' #235 BINARY_ADD', 0) f68 = float_add(f54, f67) debug_merge_point(' #236 LOAD_FAST', 0) debug_merge_point(' #239 BINARY_MULTIPLY', 0) f69 = float_mul(f68, f30) debug_merge_point(' #240 LOAD_FAST', 0) debug_merge_point(' #243 LOAD_FAST', 0) debug_merge_point(' #246 LOAD_FAST', 0) debug_merge_point(' #249 BINARY_MULTIPLY', 0) debug_merge_point(' #250 LOAD_FAST', 0) debug_merge_point(' #253 BINARY_ADD', 0) debug_merge_point(' #254 STORE_SUBSCR', 0) i70 = int_lt(i55, i23) guard_true(i70, descr=) [p1, p0, p14, i55, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f69, None, None, None, None, None, None, f42, None, None, i19, None, None, f11] setarrayitem_raw(i24, i55, f69, descr=) debug_merge_point(' #255 LOAD_FAST', 0) debug_merge_point(' #258 LOAD_GLOBAL', 0) debug_merge_point(' #261 LOAD_FAST', 0) debug_merge_point(' #264 LOAD_FAST', 0) debug_merge_point(' #267 LOAD_FAST', 0) debug_merge_point(' #270 BINARY_MULTIPLY', 0) debug_merge_point(' #271 LOAD_FAST', 0) debug_merge_point(' #274 BINARY_ADD', 0) debug_merge_point(' #275 BINARY_SUBSCR', 0) f71 = getarrayitem_raw(i24, i55, descr=) debug_merge_point(' #276 LOAD_FAST', 0) debug_merge_point(' #279 BINARY_SUBTRACT', 0) f72 = float_sub(f71, f42) debug_merge_point(' #280 CALL_FUNCTION', 0) i73 = force_token() debug_merge_point(' #0 LOAD_FAST', 1) debug_merge_point(' #3 LOAD_FAST', 1) debug_merge_point(' #6 BINARY_MULTIPLY', 1) f74 = float_mul(f72, f72) debug_merge_point(' #7 RETURN_VALUE', 1) debug_merge_point(' #283 INPLACE_ADD', 0) f75 = float_add(f11, f74) debug_merge_point(' #284 STORE_FAST', 0) debug_merge_point(' #287 JUMP_ABSOLUTE', 0) i77 = getfield_raw(38968960, descr=) i79 = int_sub(i77, 26) setfield_raw(38968960, i79, descr=) i81 = int_lt(i79, 0) guard_false(i81, descr=) [p1, p0, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p14, p15, f75, None, None, None, None, None, None, None, f42, None, None, i19, None, None, None] debug_merge_point(' #125 FOR_ITER', 0) jump(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, f75, p12, p13, p14, p15, i19, f42, i35, i33, i20, i21, i22, i23, i24, i25, i26, f27, i36, f29, f30, descr=) [5ed622d5187e] jit-log-opt-loop} [5ed622e116d0] {jit-log-opt-loop # Loop 1 : entry bridge with 188 ops [p0, p1, p2, p3, i4, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] debug_merge_point(' #125 FOR_ITER', 0) guard_value(i4, 2, descr=) [i4, p1, p0, p2, p3, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] guard_class(p9, 19861240, descr=) [p1, p0, p9, p2, p3, p5, i6, p8, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] i29 = getfield_gc(p9, descr=) i31 = int_gt(i29, 0) guard_true(i31, descr=) [p1, p0, p9, p2, p3, p5, i6, p8, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] i32 = getfield_gc(p9, descr=) i33 = getfield_gc(p9, descr=) i34 = int_add(i32, i33) i36 = int_sub(i29, 1) setfield_gc(p9, i34, descr=) setfield_gc(p9, i36, descr=) guard_value(i6, 0, descr=) [i6, p1, p0, p2, p3, p5, p8, p9, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, i32] debug_merge_point(' #128 STORE_FAST', 0) debug_merge_point(' #131 LOAD_FAST', 0) guard_nonnull_class(p23, 19886912, descr=) [p1, p0, p23, p2, p3, p5, p8, p9, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, i32] debug_merge_point(' #134 LOAD_FAST', 0) guard_nonnull_class(p24, ConstClass(W_IntObject), descr=) [p1, p0, p24, p2, p3, p5, p8, p9, p23, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p26, i32] debug_merge_point(' #137 LOAD_FAST', 0) guard_nonnull_class(p21, ConstClass(W_IntObject), descr=) [p1, p0, p21, p2, p3, p5, p8, p9, p23, p24, p12, p13, p14, p15, p16, p17, p18, p19, p20, p22, p26, i32] debug_merge_point(' #140 BINARY_MULTIPLY', 0) i41 = getfield_gc_pure(p24, descr=) i42 = getfield_gc_pure(p21, descr=) i43 = int_mul_ovf(i41, i42) guard_no_overflow(, descr=) [p1, p0, p21, p24, i43, p2, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p22, p26, i32] debug_merge_point(' #141 LOAD_FAST', 0) debug_merge_point(' #144 BINARY_ADD', 0) i44 = int_add_ovf(i43, i32) guard_no_overflow(, descr=) [p1, p0, i44, p2, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, i43, i32] debug_merge_point(' #145 BINARY_SUBSCR', 0) i45 = getfield_gc(p23, descr=) i47 = int_lt(i44, 0) guard_false(i47, descr=) [p1, p0, p23, i44, i45, p2, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, None, i32] i49 = int_lt(i44, i45) guard_true(i49, descr=) [p1, p0, p23, i44, p2, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, None, i32] i50 = getfield_gc(p23, descr=) f51 = getarrayitem_raw(i50, i44, descr=) debug_merge_point(' #146 STORE_FAST', 0) debug_merge_point(' #149 LOAD_FAST', 0) debug_merge_point(' #152 LOAD_FAST', 0) debug_merge_point(' #155 LOAD_CONST', 0) guard_value(p2, ConstPtr(ptr52), descr=) [p1, p0, p2, p3, p5, p8, p9, p23, p24, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, f51, None, i32] debug_merge_point(' #158 BINARY_SUBTRACT', 0) i54 = int_sub_ovf(i41, 1) guard_no_overflow(, descr=) [p1, p0, p24, i54, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, f51, None, i32] debug_merge_point(' #159 LOAD_FAST', 0) debug_merge_point(' #162 BINARY_MULTIPLY', 0) i55 = int_mul_ovf(i54, i42) guard_no_overflow(, descr=) [p1, p0, p21, i55, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p22, p24, i54, f51, None, i32] debug_merge_point(' #163 LOAD_FAST', 0) debug_merge_point(' #166 BINARY_ADD', 0) i56 = int_add_ovf(i55, i32) guard_no_overflow(, descr=) [p1, p0, i56, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, i55, None, f51, None, i32] debug_merge_point(' #167 BINARY_SUBSCR', 0) i58 = int_lt(i56, 0) guard_false(i58, descr=) [p1, p0, p23, i56, i45, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f51, None, i32] i59 = int_lt(i56, i45) guard_true(i59, descr=) [p1, p0, p23, i56, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f51, None, i32] f60 = getarrayitem_raw(i50, i56, descr=) debug_merge_point(' #168 LOAD_FAST', 0) debug_merge_point(' #171 LOAD_FAST', 0) debug_merge_point(' #174 LOAD_CONST', 0) debug_merge_point(' #177 BINARY_ADD', 0) i62 = int_add_ovf(i41, 1) guard_no_overflow(, descr=) [p1, p0, p24, i62, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p21, p22, f60, None, None, f51, None, i32] debug_merge_point(' #178 LOAD_FAST', 0) debug_merge_point(' #181 BINARY_MULTIPLY', 0) i63 = int_mul_ovf(i62, i42) guard_no_overflow(, descr=) [p1, p0, p21, i63, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p22, p24, i62, f60, None, None, f51, None, i32] debug_merge_point(' #182 LOAD_FAST', 0) debug_merge_point(' #185 BINARY_ADD', 0) i64 = int_add_ovf(i63, i32) guard_no_overflow(, descr=) [p1, p0, i64, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, i63, None, f60, None, None, f51, None, i32] debug_merge_point(' #186 BINARY_SUBSCR', 0) i66 = int_lt(i64, 0) guard_false(i66, descr=) [p1, p0, p23, i64, i45, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f60, None, None, f51, None, i32] i67 = int_lt(i64, i45) guard_true(i67, descr=) [p1, p0, p23, i64, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f60, None, None, f51, None, i32] f68 = getarrayitem_raw(i50, i64, descr=) debug_merge_point(' #187 BINARY_ADD', 0) f69 = float_add(f60, f68) debug_merge_point(' #188 LOAD_FAST', 0) guard_nonnull_class(p18, 19800744, descr=) [p1, p0, p18, p3, p5, p8, p9, p14, p15, p16, p17, p19, p20, p21, p22, p23, p24, f69, None, None, None, None, None, f51, None, i32] debug_merge_point(' #191 BINARY_MULTIPLY', 0) f71 = getfield_gc_pure(p18, descr=) f72 = float_mul(f69, f71) debug_merge_point(' #192 LOAD_FAST', 0) debug_merge_point(' #195 LOAD_FAST', 0) debug_merge_point(' #198 LOAD_FAST', 0) debug_merge_point(' #201 BINARY_MULTIPLY', 0) debug_merge_point(' #202 LOAD_FAST', 0) debug_merge_point(' #205 BINARY_ADD', 0) debug_merge_point(' #206 LOAD_CONST', 0) debug_merge_point(' #209 BINARY_SUBTRACT', 0) i74 = int_sub(i44, 1) debug_merge_point(' #210 BINARY_SUBSCR', 0) i76 = int_lt(i74, 0) guard_false(i76, descr=) [p1, p0, p23, i74, i45, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, f72, None, None, None, None, None, None, f51, None, i32] i77 = int_lt(i74, i45) guard_true(i77, descr=) [p1, p0, p23, i74, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, f72, None, None, None, None, None, None, f51, None, i32] f78 = getarrayitem_raw(i50, i74, descr=) debug_merge_point(' #211 LOAD_FAST', 0) debug_merge_point(' #214 LOAD_FAST', 0) debug_merge_point(' #217 LOAD_FAST', 0) debug_merge_point(' #220 BINARY_MULTIPLY', 0) debug_merge_point(' #221 LOAD_FAST', 0) debug_merge_point(' #224 BINARY_ADD', 0) debug_merge_point(' #225 LOAD_CONST', 0) debug_merge_point(' #228 BINARY_ADD', 0) i80 = int_add(i44, 1) debug_merge_point(' #229 BINARY_SUBSCR', 0) i81 = int_lt(i80, i45) guard_true(i81, descr=) [p1, p0, p23, i80, p3, p5, p8, p9, p15, p16, p17, p18, p19, p20, p21, p22, p24, f78, f72, None, None, None, None, None, None, f51, None, i32] f82 = getarrayitem_raw(i50, i80, descr=) debug_merge_point(' #230 BINARY_ADD', 0) f83 = float_add(f78, f82) debug_merge_point(' #231 LOAD_FAST', 0) guard_nonnull_class(p17, 19800744, descr=) [p1, p0, p17, p3, p5, p8, p9, p15, p16, p18, p19, p20, p21, p22, p23, p24, f83, None, f72, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #234 BINARY_MULTIPLY', 0) f85 = getfield_gc_pure(p17, descr=) f86 = float_mul(f83, f85) debug_merge_point(' #235 BINARY_ADD', 0) f87 = float_add(f72, f86) debug_merge_point(' #236 LOAD_FAST', 0) guard_nonnull_class(p19, 19800744, descr=) [p1, p0, p19, p3, p5, p8, p9, p15, p16, p17, p18, p20, p21, p22, p23, p24, f87, None, None, None, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #239 BINARY_MULTIPLY', 0) f89 = getfield_gc_pure(p19, descr=) f90 = float_mul(f87, f89) debug_merge_point(' #240 LOAD_FAST', 0) debug_merge_point(' #243 LOAD_FAST', 0) debug_merge_point(' #246 LOAD_FAST', 0) debug_merge_point(' #249 BINARY_MULTIPLY', 0) debug_merge_point(' #250 LOAD_FAST', 0) debug_merge_point(' #253 BINARY_ADD', 0) debug_merge_point(' #254 STORE_SUBSCR', 0) setarrayitem_raw(i50, i44, f90, descr=) debug_merge_point(' #255 LOAD_FAST', 0) guard_nonnull_class(p20, 19800744, descr=) [p1, p0, p20, p3, p5, p8, p9, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #258 LOAD_GLOBAL', 0) p92 = getfield_gc(p0, descr=) guard_value(p92, ConstPtr(ptr93), descr=) [p1, p0, p92, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] p94 = getfield_gc(p92, descr=) guard_isnull(p94, descr=) [p1, p0, p94, p92, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] p96 = getfield_gc(ConstPtr(ptr95), descr=) guard_nonnull_class(p96, ConstClass(Function), descr=) [p1, p0, p96, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #261 LOAD_FAST', 0) debug_merge_point(' #264 LOAD_FAST', 0) debug_merge_point(' #267 LOAD_FAST', 0) debug_merge_point(' #270 BINARY_MULTIPLY', 0) debug_merge_point(' #271 LOAD_FAST', 0) debug_merge_point(' #274 BINARY_ADD', 0) debug_merge_point(' #275 BINARY_SUBSCR', 0) f98 = getarrayitem_raw(i50, i44, descr=) debug_merge_point(' #276 LOAD_FAST', 0) debug_merge_point(' #279 BINARY_SUBTRACT', 0) f99 = float_sub(f98, f51) debug_merge_point(' #280 CALL_FUNCTION', 0) p100 = getfield_gc(p96, descr=) guard_value(p100, ConstPtr(ptr101), descr=) [p1, p0, p100, p96, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] p102 = getfield_gc(p96, descr=) p103 = getfield_gc(p96, descr=) p105 = call(ConstClass(getexecutioncontext), descr=) p106 = getfield_gc(p105, descr=) i107 = force_token() p108 = getfield_gc(p105, descr=) guard_isnull(p108, descr=) [p1, p0, p105, p108, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] i109 = getfield_gc(p105, descr=) i110 = int_is_zero(i109) guard_true(i110, descr=) [p1, p0, p105, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #0 LOAD_FAST', 1) debug_merge_point(' #3 LOAD_FAST', 1) debug_merge_point(' #6 BINARY_MULTIPLY', 1) f111 = float_mul(f99, f99) debug_merge_point(' #7 RETURN_VALUE', 1) i112 = int_is_true(i109) guard_false(i112, descr=) [p1, p0, p105, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, f111, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #283 INPLACE_ADD', 0) f113 = getfield_gc_pure(p20, descr=) f114 = float_add(f113, f111) debug_merge_point(' #284 STORE_FAST', 0) debug_merge_point(' #287 JUMP_ABSOLUTE', 0) i116 = getfield_raw(38968960, descr=) i118 = int_sub(i116, 26) setfield_raw(38968960, i118, descr=) i120 = int_lt(i118, 0) guard_false(i120, descr=) [p1, p0, p3, p5, p8, p9, p15, p16, p17, p18, p19, p21, p22, p23, p24, f114, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f51, None, i32] debug_merge_point(' #125 FOR_ITER', 0) jump(p0, p1, p3, p5, p8, p9, p15, p16, p17, p18, p19, f114, p21, p22, p23, p24, i32, f51, i36, i34, i33, i41, i42, i45, i50, i55, i63, f71, i43, f85, f89, descr=) [5ed622ea316e] jit-log-opt-loop} [5ed62326a846] {jit-log-opt-bridge # bridge out of Guard 21 with 13 ops [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] i18 = force_token() setfield_gc(p1, i18, descr=) call_may_force(ConstClass(action_dispatcher), p0, p1, descr=) guard_not_forced(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i17, f16, f15] guard_no_exception(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i17, f16, f15] debug_merge_point(' #125 FOR_ITER', 0) p21 = new_with_vtable(19800744) setfield_gc(p21, f15, descr=) p23 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p23, i17, descr=) p25 = new_with_vtable(19800744) setfield_gc(p25, f16, descr=) jump(p1, p0, ConstPtr(ptr26), p2, 2, p3, 0, 125, p4, p5, ConstPtr(ptr30), ConstPtr(ptr31), ConstPtr(ptr32), ConstPtr(ptr33), ConstPtr(ptr34), p6, p7, p8, p9, p10, p21, p11, p12, p13, p14, p23, p25, descr=) [5ed62327d096] jit-log-opt-bridge} [5ed623eb929c] {jit-log-opt-bridge # bridge out of Guard 3 with 260 ops [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] debug_merge_point(' #290 POP_BLOCK', 0) p18 = getfield_gc(p3, descr=) guard_class(p3, 19865144, descr=) [p0, p1, p3, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] i20 = getfield_gc(p3, descr=) guard_value(i20, 1, descr=) [p0, p1, i20, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] debug_merge_point(' #291 JUMP_ABSOLUTE', 0) i23 = getfield_raw(38968960, descr=) i25 = int_sub(i23, 1) setfield_raw(38968960, i25, descr=) i27 = int_lt(i25, 0) guard_false(i27, descr=) [p0, p1, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] debug_merge_point(' #99 FOR_ITER', 0) guard_class(p5, 19861240, descr=) [p0, p1, p5, p18, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] i29 = getfield_gc(p5, descr=) i31 = int_gt(i29, 0) guard_true(i31, descr=) [p0, p1, p5, p18, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] i32 = getfield_gc(p5, descr=) i33 = getfield_gc(p5, descr=) i34 = int_add(i32, i33) i36 = int_sub(i29, 1) debug_merge_point(' #102 STORE_FAST', 0) debug_merge_point(' #105 SETUP_LOOP', 0) debug_merge_point(' #108 LOAD_GLOBAL', 0) p37 = getfield_gc(p1, descr=) setfield_gc(p5, i34, descr=) setfield_gc(p5, i36, descr=) guard_value(p37, ConstPtr(ptr38), descr=) [p0, p1, p37, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] p39 = getfield_gc(p37, descr=) guard_isnull(p39, descr=) [p0, p1, p39, p37, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] p41 = getfield_gc(ConstPtr(ptr40), descr=) guard_isnull(p41, descr=) [p0, p1, p41, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] p43 = getfield_gc(ConstPtr(ptr42), descr=) guard_value(p43, ConstPtr(ptr44), descr=) [p0, p1, p43, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] p45 = getfield_gc(p43, descr=) guard_isnull(p45, descr=) [p0, p1, p45, p43, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] p47 = getfield_gc(ConstPtr(ptr46), descr=) guard_value(p47, ConstPtr(ptr48), descr=) [p0, p1, p47, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] debug_merge_point(' #111 LOAD_CONST', 0) debug_merge_point(' #114 LOAD_FAST', 0) guard_nonnull_class(p12, ConstClass(W_IntObject), descr=) [p0, p1, p12, p4, p5, p47, p6, p7, p8, p9, p10, p11, p13, i32, p18, i15, f16, f17] debug_merge_point(' #117 LOAD_CONST', 0) debug_merge_point(' #120 BINARY_SUBTRACT', 0) i50 = getfield_gc_pure(p12, descr=) i52 = int_sub_ovf(i50, 1) guard_no_overflow(, descr=) [p0, p1, p12, i52, p4, p5, p47, p6, p7, p8, p9, p10, p11, p13, i32, p18, i15, f16, f17] debug_merge_point(' #121 CALL_FUNCTION', 0) p54 = getfield_gc(ConstPtr(ptr53), descr=) p55 = getfield_gc(ConstPtr(ptr53), descr=) i56 = getfield_gc_pure(p55, descr=) guard_false(i56, descr=) [p0, p1, p54, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] p57 = getfield_gc_pure(p55, descr=) i58 = arraylen_gc(p57, descr=) i60 = int_sub(4, i58) i62 = int_ge(3, i60) guard_true(i62, descr=) [p0, p1, p54, i60, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] i63 = int_sub(3, i60) i64 = getfield_gc_pure(p55, descr=) guard_false(i64, descr=) [p0, p1, p54, i63, i60, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] p65 = getfield_gc_pure(p55, descr=) p66 = getarrayitem_gc(p65, i63, descr=) guard_class(p66, ConstClass(W_IntObject), descr=) [p0, p1, p66, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] i68 = getfield_gc_pure(p66, descr=) i69 = int_is_zero(i68) guard_false(i69, descr=) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] i72 = int_lt(i68, 0) guard_false(i72, descr=) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] i74 = int_lt(1, i52) guard_true(i74, descr=) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] i75 = int_sub(i52, 1) i77 = int_sub(i75, 1) i78 = uint_floordiv(i77, i68) i80 = int_add(i78, 1) i82 = int_lt(i80, 0) guard_false(i82, descr=) [p0, p1, i68, i80, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, i52, i32, p18, i15, f16, f17] debug_merge_point(' #124 GET_ITER', 0) debug_merge_point(' #125 FOR_ITER', 0) i84 = int_gt(i80, 0) guard_true(i84, descr=) [p0, p1, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i80, i68, None, None, i32, p18, i15, f16, f17] i85 = int_add(1, i68) debug_merge_point(' #128 STORE_FAST', 0) debug_merge_point(' #131 LOAD_FAST', 0) guard_nonnull_class(p13, 19886912, descr=) [p0, p1, p13, p4, p5, p6, p7, p8, p9, p10, p11, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] debug_merge_point(' #134 LOAD_FAST', 0) debug_merge_point(' #137 LOAD_FAST', 0) guard_nonnull_class(p11, ConstClass(W_IntObject), descr=) [p0, p1, p11, p4, p5, p13, p6, p7, p8, p9, p10, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] debug_merge_point(' #140 BINARY_MULTIPLY', 0) i88 = getfield_gc_pure(p11, descr=) i89 = int_mul_ovf(i32, i88) guard_no_overflow(, descr=) [p0, p1, p11, i89, p4, p5, p13, p6, p7, p8, p9, p10, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] debug_merge_point(' #141 LOAD_FAST', 0) debug_merge_point(' #144 BINARY_ADD', 0) i90 = int_add_ovf(i89, 1) guard_no_overflow(, descr=) [p0, p1, i90, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i89, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] debug_merge_point(' #145 BINARY_SUBSCR', 0) i91 = getfield_gc(p13, descr=) i93 = int_lt(i90, 0) guard_false(i93, descr=) [p0, p1, p13, i90, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] i94 = int_lt(i90, i91) guard_true(i94, descr=) [p0, p1, p13, i90, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] i95 = getfield_gc(p13, descr=) f96 = getarrayitem_raw(i95, i90, descr=) debug_merge_point(' #146 STORE_FAST', 0) debug_merge_point(' #149 LOAD_FAST', 0) debug_merge_point(' #152 LOAD_FAST', 0) debug_merge_point(' #155 LOAD_CONST', 0) debug_merge_point(' #158 BINARY_SUBTRACT', 0) i98 = int_sub_ovf(i32, 1) guard_no_overflow(, descr=) [p0, p1, i98, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #159 LOAD_FAST', 0) debug_merge_point(' #162 BINARY_MULTIPLY', 0) i99 = int_mul_ovf(i98, i88) guard_no_overflow(, descr=) [p0, p1, p11, i99, p4, p5, p13, p6, p7, p8, p9, p10, p12, i98, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #163 LOAD_FAST', 0) debug_merge_point(' #166 BINARY_ADD', 0) i100 = int_add_ovf(i99, 1) guard_no_overflow(, descr=) [p0, p1, i100, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i99, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #167 BINARY_SUBSCR', 0) i102 = int_lt(i100, 0) guard_false(i102, descr=) [p0, p1, p13, i100, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] i103 = int_lt(i100, i91) guard_true(i103, descr=) [p0, p1, p13, i100, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] f104 = getarrayitem_raw(i95, i100, descr=) debug_merge_point(' #168 LOAD_FAST', 0) debug_merge_point(' #171 LOAD_FAST', 0) debug_merge_point(' #174 LOAD_CONST', 0) debug_merge_point(' #177 BINARY_ADD', 0) i106 = int_add_ovf(i32, 1) guard_no_overflow(, descr=) [p0, p1, i106, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #178 LOAD_FAST', 0) debug_merge_point(' #181 BINARY_MULTIPLY', 0) i107 = int_mul_ovf(i106, i88) guard_no_overflow(, descr=) [p0, p1, p11, i107, p4, p5, p13, p6, p7, p8, p9, p10, p12, i106, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #182 LOAD_FAST', 0) debug_merge_point(' #185 BINARY_ADD', 0) i108 = int_add_ovf(i107, 1) guard_no_overflow(, descr=) [p0, p1, i108, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i107, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #186 BINARY_SUBSCR', 0) i110 = int_lt(i108, 0) guard_false(i110, descr=) [p0, p1, p13, i108, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] i111 = int_lt(i108, i91) guard_true(i111, descr=) [p0, p1, p13, i108, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] f112 = getarrayitem_raw(i95, i108, descr=) debug_merge_point(' #187 BINARY_ADD', 0) f113 = float_add(f104, f112) debug_merge_point(' #188 LOAD_FAST', 0) guard_nonnull_class(p9, 19800744, descr=) [p0, p1, p9, p4, p5, p6, p7, p8, p10, p11, p12, p13, f113, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #191 BINARY_MULTIPLY', 0) f115 = getfield_gc_pure(p9, descr=) f116 = float_mul(f113, f115) debug_merge_point(' #192 LOAD_FAST', 0) debug_merge_point(' #195 LOAD_FAST', 0) debug_merge_point(' #198 LOAD_FAST', 0) debug_merge_point(' #201 BINARY_MULTIPLY', 0) debug_merge_point(' #202 LOAD_FAST', 0) debug_merge_point(' #205 BINARY_ADD', 0) debug_merge_point(' #206 LOAD_CONST', 0) debug_merge_point(' #209 BINARY_SUBTRACT', 0) debug_merge_point(' #210 BINARY_SUBSCR', 0) i118 = int_lt(i89, 0) guard_false(i118, descr=) [p0, p1, p13, i89, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] i119 = int_lt(i89, i91) guard_true(i119, descr=) [p0, p1, p13, i89, p4, p5, p6, p7, p8, p9, p10, p11, p12, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] f120 = getarrayitem_raw(i95, i89, descr=) debug_merge_point(' #211 LOAD_FAST', 0) debug_merge_point(' #214 LOAD_FAST', 0) debug_merge_point(' #217 LOAD_FAST', 0) debug_merge_point(' #220 BINARY_MULTIPLY', 0) debug_merge_point(' #221 LOAD_FAST', 0) debug_merge_point(' #224 BINARY_ADD', 0) debug_merge_point(' #225 LOAD_CONST', 0) debug_merge_point(' #228 BINARY_ADD', 0) i122 = int_add(i90, 1) debug_merge_point(' #229 BINARY_SUBSCR', 0) i123 = int_lt(i122, i91) guard_true(i123, descr=) [p0, p1, p13, i122, p4, p5, p6, p7, p8, p9, p10, p11, p12, f120, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] f124 = getarrayitem_raw(i95, i122, descr=) debug_merge_point(' #230 BINARY_ADD', 0) f125 = float_add(f120, f124) debug_merge_point(' #231 LOAD_FAST', 0) guard_nonnull_class(p8, 19800744, descr=) [p0, p1, p8, p4, p5, p6, p7, p9, p10, p11, p12, p13, f125, None, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #234 BINARY_MULTIPLY', 0) f127 = getfield_gc_pure(p8, descr=) f128 = float_mul(f125, f127) debug_merge_point(' #235 BINARY_ADD', 0) f129 = float_add(f116, f128) debug_merge_point(' #236 LOAD_FAST', 0) guard_nonnull_class(p10, 19800744, descr=) [p0, p1, p10, p4, p5, p6, p7, p8, p9, p11, p12, p13, f129, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #239 BINARY_MULTIPLY', 0) f131 = getfield_gc_pure(p10, descr=) f132 = float_mul(f129, f131) debug_merge_point(' #240 LOAD_FAST', 0) debug_merge_point(' #243 LOAD_FAST', 0) debug_merge_point(' #246 LOAD_FAST', 0) debug_merge_point(' #249 BINARY_MULTIPLY', 0) debug_merge_point(' #250 LOAD_FAST', 0) debug_merge_point(' #253 BINARY_ADD', 0) debug_merge_point(' #254 STORE_SUBSCR', 0) setarrayitem_raw(i95, i90, f132, descr=) debug_merge_point(' #255 LOAD_FAST', 0) debug_merge_point(' #258 LOAD_GLOBAL', 0) p134 = getfield_gc(ConstPtr(ptr133), descr=) guard_nonnull_class(p134, ConstClass(Function), descr=) [p0, p1, p134, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #261 LOAD_FAST', 0) debug_merge_point(' #264 LOAD_FAST', 0) debug_merge_point(' #267 LOAD_FAST', 0) debug_merge_point(' #270 BINARY_MULTIPLY', 0) debug_merge_point(' #271 LOAD_FAST', 0) debug_merge_point(' #274 BINARY_ADD', 0) debug_merge_point(' #275 BINARY_SUBSCR', 0) f136 = getarrayitem_raw(i95, i90, descr=) debug_merge_point(' #276 LOAD_FAST', 0) debug_merge_point(' #279 BINARY_SUBTRACT', 0) f137 = float_sub(f136, f96) debug_merge_point(' #280 CALL_FUNCTION', 0) p138 = getfield_gc(p134, descr=) guard_value(p138, ConstPtr(ptr139), descr=) [p0, p1, p138, p134, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] p140 = getfield_gc(p134, descr=) p141 = getfield_gc(p134, descr=) p143 = call(ConstClass(getexecutioncontext), descr=) p144 = getfield_gc(p143, descr=) i145 = force_token() p146 = getfield_gc(p143, descr=) guard_isnull(p146, descr=) [p0, p1, p143, p146, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] i147 = getfield_gc(p143, descr=) i148 = int_is_zero(i147) guard_true(i148, descr=) [p0, p1, p143, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #0 LOAD_FAST', 1) debug_merge_point(' #3 LOAD_FAST', 1) debug_merge_point(' #6 BINARY_MULTIPLY', 1) f149 = float_mul(f137, f137) debug_merge_point(' #7 RETURN_VALUE', 1) i150 = int_is_true(i147) guard_false(i150, descr=) [p0, p1, p143, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, f149, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] debug_merge_point(' #283 INPLACE_ADD', 0) f151 = float_add(f17, f149) debug_merge_point(' #284 STORE_FAST', 0) debug_merge_point(' #287 JUMP_ABSOLUTE', 0) i153 = getfield_raw(38968960, descr=) i155 = int_sub(i153, 35) setfield_raw(38968960, i155, descr=) i157 = int_lt(i155, 0) guard_false(i157, descr=) [p0, p1, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f151, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, None] debug_merge_point(' #125 FOR_ITER', 0) p159 = new_with_vtable(19865144) setfield_gc(p159, 291, descr=) setfield_gc(p159, 1, descr=) setfield_gc(p159, p18, descr=) p163 = new_with_vtable(19861240) setfield_gc(p163, i85, descr=) setfield_gc(p163, i78, descr=) setfield_gc(p163, i68, descr=) p165 = new_with_vtable(19800744) setfield_gc(p165, f151, descr=) p167 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p167, i32, descr=) p169 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p169, 1, descr=) p171 = new_with_vtable(19800744) setfield_gc(p171, f96, descr=) jump(p1, p0, ConstPtr(ptr172), p159, 2, p4, 0, 125, p5, p163, ConstPtr(ptr176), ConstPtr(ptr177), ConstPtr(ptr178), ConstPtr(ptr179), ConstPtr(ptr180), p6, p7, p8, p9, p10, p165, p11, p12, p13, p167, p169, p171, descr=) [5ed623fc609b] jit-log-opt-bridge} [5ed63ea5fa94] {jit-log-opt-bridge # bridge out of Guard 110 with 23 ops [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, f12, f13, i14, i15, i16, i17, p18] i19 = force_token() setfield_gc(p1, i19, descr=) call_may_force(ConstClass(action_dispatcher), p0, p1, descr=) guard_not_forced(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, i14, i17, i16, i15, f12, f13, p18] guard_no_exception(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, i14, i17, i16, i15, f12, f13, p18] debug_merge_point(' #125 FOR_ITER', 0) p22 = new_with_vtable(19865144) setfield_gc(p22, 291, descr=) setfield_gc(p22, p18, descr=) setfield_gc(p22, 1, descr=) p26 = new_with_vtable(19861240) setfield_gc(p26, i15, descr=) setfield_gc(p26, i14, descr=) setfield_gc(p26, i16, descr=) p28 = new_with_vtable(19800744) setfield_gc(p28, f12, descr=) p30 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p30, i17, descr=) p32 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p32, 1, descr=) p35 = new_with_vtable(19800744) setfield_gc(p35, f13, descr=) jump(p1, p0, ConstPtr(ptr36), p22, 2, p2, 0, 125, p3, p26, ConstPtr(ptr40), ConstPtr(ptr41), ConstPtr(ptr42), ConstPtr(ptr43), ConstPtr(ptr44), p4, p5, p6, p7, p8, p28, p9, p10, p11, p30, p32, p35, descr=) [5ed63ea8ea04] jit-log-opt-bridge} [5ed640a0a34c] {jit-log-opt-bridge # bridge out of Guard 58 with 13 ops [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] i18 = force_token() setfield_gc(p1, i18, descr=) call_may_force(ConstClass(action_dispatcher), p0, p1, descr=) guard_not_forced(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] guard_no_exception(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] debug_merge_point(' #125 FOR_ITER', 0) p21 = new_with_vtable(19800744) setfield_gc(p21, f15, descr=) p23 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p23, i17, descr=) p25 = new_with_vtable(19800744) setfield_gc(p25, f16, descr=) jump(p1, p0, ConstPtr(ptr26), p2, 2, p3, 0, 125, p4, p5, ConstPtr(ptr30), ConstPtr(ptr31), ConstPtr(ptr32), ConstPtr(ptr33), ConstPtr(ptr34), p6, p7, p8, p9, p10, p21, p11, p12, p13, p14, p23, p25, descr=) [5ed640a1e8c2] jit-log-opt-bridge} [5ed6431fc824] {jit-log-opt-bridge # bridge out of Guard 24 with 264 ops [p0, p1, p2, p3, p4, p5, i6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] guard_value(i6, 0, descr=) [i6, p0, p1, p3, p4, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] debug_merge_point(' #290 POP_BLOCK', 0) p26 = getfield_gc(p4, descr=) guard_class(p4, 19865144, descr=) [p0, p1, p4, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] i28 = getfield_gc(p4, descr=) guard_value(i28, 1, descr=) [p0, p1, i28, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] debug_merge_point(' #291 JUMP_ABSOLUTE', 0) i31 = getfield_raw(38968960, descr=) i33 = int_sub(i31, 1) setfield_raw(38968960, i33, descr=) i35 = int_lt(i33, 0) guard_false(i35, descr=) [p0, p1, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] guard_value(p3, ConstPtr(ptr36), descr=) [p0, p1, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] debug_merge_point(' #99 FOR_ITER', 0) guard_class(p7, 19861240, descr=) [p0, p1, p7, p26, p5, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] i38 = getfield_gc(p7, descr=) i40 = int_gt(i38, 0) guard_true(i40, descr=) [p0, p1, p7, p26, p5, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] i41 = getfield_gc(p7, descr=) i42 = getfield_gc(p7, descr=) i43 = int_add(i41, i42) i45 = int_sub(i38, 1) debug_merge_point(' #102 STORE_FAST', 0) debug_merge_point(' #105 SETUP_LOOP', 0) debug_merge_point(' #108 LOAD_GLOBAL', 0) p46 = getfield_gc(p1, descr=) setfield_gc(p7, i43, descr=) setfield_gc(p7, i45, descr=) guard_value(p46, ConstPtr(ptr47), descr=) [p0, p1, p46, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] p48 = getfield_gc(p46, descr=) guard_isnull(p48, descr=) [p0, p1, p48, p46, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] p50 = getfield_gc(ConstPtr(ptr49), descr=) guard_isnull(p50, descr=) [p0, p1, p50, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] p52 = getfield_gc(ConstPtr(ptr51), descr=) guard_value(p52, ConstPtr(ptr53), descr=) [p0, p1, p52, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] p54 = getfield_gc(p52, descr=) guard_isnull(p54, descr=) [p0, p1, p54, p52, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] p56 = getfield_gc(ConstPtr(ptr55), descr=) guard_value(p56, ConstPtr(ptr57), descr=) [p0, p1, p56, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] debug_merge_point(' #111 LOAD_CONST', 0) debug_merge_point(' #114 LOAD_FAST', 0) guard_nonnull_class(p20, ConstClass(W_IntObject), descr=) [p0, p1, p20, p5, p7, p56, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p21, p23, p24, p26, i41] debug_merge_point(' #117 LOAD_CONST', 0) debug_merge_point(' #120 BINARY_SUBTRACT', 0) i59 = getfield_gc_pure(p20, descr=) i61 = int_sub_ovf(i59, 1) guard_no_overflow(, descr=) [p0, p1, p20, i61, p5, p7, p56, p11, p12, p13, p14, p15, p16, p17, p18, p19, p21, p23, p24, p26, i41] debug_merge_point(' #121 CALL_FUNCTION', 0) p63 = getfield_gc(ConstPtr(ptr62), descr=) p64 = getfield_gc(ConstPtr(ptr62), descr=) i65 = getfield_gc_pure(p64, descr=) guard_false(i65, descr=) [p0, p1, p63, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] p66 = getfield_gc_pure(p64, descr=) i67 = arraylen_gc(p66, descr=) i69 = int_sub(4, i67) i71 = int_ge(3, i69) guard_true(i71, descr=) [p0, p1, p63, i69, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] i72 = int_sub(3, i69) i73 = getfield_gc_pure(p64, descr=) guard_false(i73, descr=) [p0, p1, p63, i72, i69, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] p74 = getfield_gc_pure(p64, descr=) p75 = getarrayitem_gc(p74, i72, descr=) guard_class(p75, ConstClass(W_IntObject), descr=) [p0, p1, p75, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] i77 = getfield_gc_pure(p75, descr=) i78 = int_is_zero(i77) guard_false(i78, descr=) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] i81 = int_lt(i77, 0) guard_false(i81, descr=) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] i83 = int_lt(1, i61) guard_true(i83, descr=) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] i84 = int_sub(i61, 1) i86 = int_sub(i84, 1) i87 = uint_floordiv(i86, i77) i89 = int_add(i87, 1) i91 = int_lt(i89, 0) guard_false(i91, descr=) [p0, p1, i77, i89, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, i61, p26, i41] debug_merge_point(' #124 GET_ITER', 0) debug_merge_point(' #125 FOR_ITER', 0) i93 = int_gt(i89, 0) guard_true(i93, descr=) [p0, p1, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i89, i77, None, None, p26, i41] i94 = int_add(1, i77) debug_merge_point(' #128 STORE_FAST', 0) debug_merge_point(' #131 LOAD_FAST', 0) guard_nonnull_class(p21, 19886912, descr=) [p0, p1, p21, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #134 LOAD_FAST', 0) debug_merge_point(' #137 LOAD_FAST', 0) guard_nonnull_class(p19, ConstClass(W_IntObject), descr=) [p0, p1, p19, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, p24, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #140 BINARY_MULTIPLY', 0) i97 = getfield_gc_pure(p19, descr=) i98 = int_mul_ovf(i41, i97) guard_no_overflow(, descr=) [p0, p1, p19, i98, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, p24, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #141 LOAD_FAST', 0) debug_merge_point(' #144 BINARY_ADD', 0) i99 = int_add_ovf(i98, 1) guard_no_overflow(, descr=) [p0, p1, i99, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, i98, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #145 BINARY_SUBSCR', 0) i100 = getfield_gc(p21, descr=) i102 = int_lt(i99, 0) guard_false(i102, descr=) [p0, p1, p21, i99, i100, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, None, i87, i94, None, i77, None, None, p26, i41] i103 = int_lt(i99, i100) guard_true(i103, descr=) [p0, p1, p21, i99, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, None, i87, i94, None, i77, None, None, p26, i41] i104 = getfield_gc(p21, descr=) f105 = getarrayitem_raw(i104, i99, descr=) debug_merge_point(' #146 STORE_FAST', 0) debug_merge_point(' #149 LOAD_FAST', 0) debug_merge_point(' #152 LOAD_FAST', 0) debug_merge_point(' #155 LOAD_CONST', 0) debug_merge_point(' #158 BINARY_SUBTRACT', 0) i107 = int_sub_ovf(i41, 1) guard_no_overflow(, descr=) [p0, p1, i107, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #159 LOAD_FAST', 0) debug_merge_point(' #162 BINARY_MULTIPLY', 0) i108 = int_mul_ovf(i107, i97) guard_no_overflow(, descr=) [p0, p1, p19, i108, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, i107, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #163 LOAD_FAST', 0) debug_merge_point(' #166 BINARY_ADD', 0) i109 = int_add_ovf(i108, 1) guard_no_overflow(, descr=) [p0, p1, i109, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, i108, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #167 BINARY_SUBSCR', 0) i111 = int_lt(i109, 0) guard_false(i111, descr=) [p0, p1, p21, i109, i100, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] i112 = int_lt(i109, i100) guard_true(i112, descr=) [p0, p1, p21, i109, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] f113 = getarrayitem_raw(i104, i109, descr=) debug_merge_point(' #168 LOAD_FAST', 0) debug_merge_point(' #171 LOAD_FAST', 0) debug_merge_point(' #174 LOAD_CONST', 0) debug_merge_point(' #177 BINARY_ADD', 0) i115 = int_add_ovf(i41, 1) guard_no_overflow(, descr=) [p0, p1, i115, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p19, p20, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #178 LOAD_FAST', 0) debug_merge_point(' #181 BINARY_MULTIPLY', 0) i116 = int_mul_ovf(i115, i97) guard_no_overflow(, descr=) [p0, p1, p19, i116, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p20, i115, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #182 LOAD_FAST', 0) debug_merge_point(' #185 BINARY_ADD', 0) i117 = int_add_ovf(i116, 1) guard_no_overflow(, descr=) [p0, p1, i117, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p19, p20, i116, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #186 BINARY_SUBSCR', 0) i119 = int_lt(i117, 0) guard_false(i119, descr=) [p0, p1, p21, i117, i100, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] i120 = int_lt(i117, i100) guard_true(i120, descr=) [p0, p1, p21, i117, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] f121 = getarrayitem_raw(i104, i117, descr=) debug_merge_point(' #187 BINARY_ADD', 0) f122 = float_add(f113, f121) debug_merge_point(' #188 LOAD_FAST', 0) guard_nonnull_class(p16, 19800744, descr=) [p0, p1, p16, p5, p7, p12, p13, p14, p15, p17, p18, p19, p20, p21, f122, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #191 BINARY_MULTIPLY', 0) f124 = getfield_gc_pure(p16, descr=) f125 = float_mul(f122, f124) debug_merge_point(' #192 LOAD_FAST', 0) debug_merge_point(' #195 LOAD_FAST', 0) debug_merge_point(' #198 LOAD_FAST', 0) debug_merge_point(' #201 BINARY_MULTIPLY', 0) debug_merge_point(' #202 LOAD_FAST', 0) debug_merge_point(' #205 BINARY_ADD', 0) debug_merge_point(' #206 LOAD_CONST', 0) debug_merge_point(' #209 BINARY_SUBTRACT', 0) debug_merge_point(' #210 BINARY_SUBSCR', 0) i127 = int_lt(i98, 0) guard_false(i127, descr=) [p0, p1, p21, i98, i100, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] i128 = int_lt(i98, i100) guard_true(i128, descr=) [p0, p1, p21, i98, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] f129 = getarrayitem_raw(i104, i98, descr=) debug_merge_point(' #211 LOAD_FAST', 0) debug_merge_point(' #214 LOAD_FAST', 0) debug_merge_point(' #217 LOAD_FAST', 0) debug_merge_point(' #220 BINARY_MULTIPLY', 0) debug_merge_point(' #221 LOAD_FAST', 0) debug_merge_point(' #224 BINARY_ADD', 0) debug_merge_point(' #225 LOAD_CONST', 0) debug_merge_point(' #228 BINARY_ADD', 0) i131 = int_add(i99, 1) debug_merge_point(' #229 BINARY_SUBSCR', 0) i132 = int_lt(i131, i100) guard_true(i132, descr=) [p0, p1, p21, i131, p5, p7, p13, p14, p15, p16, p17, p18, p19, p20, f129, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] f133 = getarrayitem_raw(i104, i131, descr=) debug_merge_point(' #230 BINARY_ADD', 0) f134 = float_add(f129, f133) debug_merge_point(' #231 LOAD_FAST', 0) guard_nonnull_class(p15, 19800744, descr=) [p0, p1, p15, p5, p7, p13, p14, p16, p17, p18, p19, p20, p21, f134, None, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #234 BINARY_MULTIPLY', 0) f136 = getfield_gc_pure(p15, descr=) f137 = float_mul(f134, f136) debug_merge_point(' #235 BINARY_ADD', 0) f138 = float_add(f125, f137) debug_merge_point(' #236 LOAD_FAST', 0) guard_nonnull_class(p17, 19800744, descr=) [p0, p1, p17, p5, p7, p13, p14, p15, p16, p18, p19, p20, p21, f138, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #239 BINARY_MULTIPLY', 0) f140 = getfield_gc_pure(p17, descr=) f141 = float_mul(f138, f140) debug_merge_point(' #240 LOAD_FAST', 0) debug_merge_point(' #243 LOAD_FAST', 0) debug_merge_point(' #246 LOAD_FAST', 0) debug_merge_point(' #249 BINARY_MULTIPLY', 0) debug_merge_point(' #250 LOAD_FAST', 0) debug_merge_point(' #253 BINARY_ADD', 0) debug_merge_point(' #254 STORE_SUBSCR', 0) setarrayitem_raw(i104, i99, f141, descr=) debug_merge_point(' #255 LOAD_FAST', 0) guard_nonnull_class(p18, 19800744, descr=) [p0, p1, p18, p5, p7, p13, p14, p15, p16, p17, p19, p20, p21, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #258 LOAD_GLOBAL', 0) p144 = getfield_gc(ConstPtr(ptr143), descr=) guard_nonnull_class(p144, ConstClass(Function), descr=) [p0, p1, p144, p5, p7, p18, p13, p14, p15, p16, p17, p19, p20, p21, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #261 LOAD_FAST', 0) debug_merge_point(' #264 LOAD_FAST', 0) debug_merge_point(' #267 LOAD_FAST', 0) debug_merge_point(' #270 BINARY_MULTIPLY', 0) debug_merge_point(' #271 LOAD_FAST', 0) debug_merge_point(' #274 BINARY_ADD', 0) debug_merge_point(' #275 BINARY_SUBSCR', 0) f146 = getarrayitem_raw(i104, i99, descr=) debug_merge_point(' #276 LOAD_FAST', 0) debug_merge_point(' #279 BINARY_SUBTRACT', 0) f147 = float_sub(f146, f105) debug_merge_point(' #280 CALL_FUNCTION', 0) p148 = getfield_gc(p144, descr=) guard_value(p148, ConstPtr(ptr149), descr=) [p0, p1, p148, p144, p5, p7, p18, p13, p14, p15, p16, p17, p19, p20, p21, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] p150 = getfield_gc(p144, descr=) p151 = getfield_gc(p144, descr=) p153 = call(ConstClass(getexecutioncontext), descr=) p154 = getfield_gc(p153, descr=) i155 = force_token() p156 = getfield_gc(p153, descr=) guard_isnull(p156, descr=) [p0, p1, p153, p156, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] i157 = getfield_gc(p153, descr=) i158 = int_is_zero(i157) guard_true(i158, descr=) [p0, p1, p153, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #0 LOAD_FAST', 1) debug_merge_point(' #3 LOAD_FAST', 1) debug_merge_point(' #6 BINARY_MULTIPLY', 1) f159 = float_mul(f147, f147) debug_merge_point(' #7 RETURN_VALUE', 1) i160 = int_is_true(i157) guard_false(i160, descr=) [p0, p1, p153, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, f159, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #283 INPLACE_ADD', 0) f161 = getfield_gc_pure(p18, descr=) f162 = float_add(f161, f159) debug_merge_point(' #284 STORE_FAST', 0) debug_merge_point(' #287 JUMP_ABSOLUTE', 0) i164 = getfield_raw(38968960, descr=) i166 = int_sub(i164, 34) setfield_raw(38968960, i166, descr=) i168 = int_lt(i166, 0) guard_false(i168, descr=) [p0, p1, p5, p7, p13, p14, p15, p16, p17, p19, p20, p21, f162, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] debug_merge_point(' #125 FOR_ITER', 0) p170 = new_with_vtable(19865144) setfield_gc(p170, 291, descr=) setfield_gc(p170, 1, descr=) setfield_gc(p170, p26, descr=) p174 = new_with_vtable(19861240) setfield_gc(p174, i94, descr=) setfield_gc(p174, i87, descr=) setfield_gc(p174, i77, descr=) p176 = new_with_vtable(19800744) setfield_gc(p176, f162, descr=) p178 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p178, i41, descr=) p180 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p180, 1, descr=) p182 = new_with_vtable(19800744) setfield_gc(p182, f105, descr=) jump(p1, p0, ConstPtr(ptr183), p170, 2, p5, 0, 125, p7, p174, ConstPtr(ptr187), ConstPtr(ptr188), ConstPtr(ptr189), ConstPtr(ptr190), ConstPtr(ptr191), p13, p14, p15, p16, p17, p176, p19, p20, p21, p178, p180, p182, descr=) [5ed6432f4a2c] jit-log-opt-bridge} [5ed66199330c] {jit-log-opt-bridge # bridge out of Guard 65 with 72 ops [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i14, f15, f16] debug_merge_point(' #294 POP_BLOCK', 0) p17 = getfield_gc(p3, descr=) guard_class(p3, 19865144, descr=) [p0, p1, p3, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] i19 = getfield_gc(p3, descr=) guard_value(i19, 0, descr=) [p0, p1, i19, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] debug_merge_point(' #295 LOAD_GLOBAL', 0) p21 = getfield_gc(p1, descr=) guard_value(p21, ConstPtr(ptr22), descr=) [p0, p1, p21, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] p23 = getfield_gc(p21, descr=) guard_isnull(p23, descr=) [p0, p1, p23, p21, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] p25 = getfield_gc(ConstPtr(ptr24), descr=) guard_nonnull_class(p25, 19905496, descr=) [p0, p1, p25, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] debug_merge_point(' #298 LOOKUP_METHOD', 0) p27 = getfield_gc(p25, descr=) guard_value(p27, ConstPtr(ptr28), descr=) [p0, p1, p25, p27, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] p29 = getfield_gc(p27, descr=) guard_isnull(p29, descr=) [p0, p1, p25, p29, p27, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] p31 = getfield_gc(ConstPtr(ptr30), descr=) guard_value(p31, ConstPtr(ptr32), descr=) [p0, p1, p31, p25, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] debug_merge_point(' #301 LOAD_FAST', 0) debug_merge_point(' #304 CALL_METHOD', 0) call(ConstClass(set_errno), 0, descr=) f36 = call(ConstClass(sqrt), f16, descr=) i38 = call(ConstClass(get_errno), descr=) i39 = float_ne(f36, f36) guard_false(i39, descr=) [p0, p1, i38, f36, f16, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, i14, f15] i42 = float_eq(f36, inf) i44 = float_eq(f36, -inf) i45 = int_or(i42, i44) i46 = int_is_true(i45) guard_false(i46, descr=) [p0, p1, i38, f36, f16, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, i14, f15] i47 = int_is_true(i38) guard_false(i47, descr=) [p0, p1, i38, f36, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] debug_merge_point(' #307 RETURN_VALUE', 0) guard_isnull(p17, descr=) [p0, p1, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f36, f16, i14, f15] p48 = getfield_gc(p1, descr=) setarrayitem_gc(p48, 0, ConstPtr(ptr50), descr=) setarrayitem_gc(p48, 1, ConstPtr(ptr52), descr=) setarrayitem_gc(p48, 2, ConstPtr(ptr52), descr=) setarrayitem_gc(p48, 3, ConstPtr(ptr55), descr=) setarrayitem_gc(p48, 4, ConstPtr(ptr55), descr=) setarrayitem_gc(p48, 5, ConstPtr(ptr55), descr=) setarrayitem_gc(p48, 6, ConstPtr(ptr55), descr=) setarrayitem_gc(p48, 7, p5, descr=) p60 = getfield_gc(p1, descr=) setarrayitem_gc(p60, 0, p6, descr=) setarrayitem_gc(p60, 1, p7, descr=) setarrayitem_gc(p60, 2, p8, descr=) setarrayitem_gc(p60, 3, p9, descr=) p66 = new_with_vtable(19800744) setfield_gc(p66, f16, descr=) setarrayitem_gc(p60, 4, p66, descr=) setarrayitem_gc(p60, 5, p10, descr=) setarrayitem_gc(p60, 6, p11, descr=) setarrayitem_gc(p60, 7, p12, descr=) setarrayitem_gc(p60, 8, p13, descr=) p73 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p73, i14, descr=) setarrayitem_gc(p60, 9, p73, descr=) p76 = new_with_vtable(19800744) setfield_gc(p76, f15, descr=) setarrayitem_gc(p60, 10, p76, descr=) setfield_gc(p1, 1, descr=) setfield_gc(p1, ConstPtr(ptr79), descr=) setfield_gc(p1, ConstPtr(ptr55), descr=) setfield_gc(p1, 0, descr=) setfield_gc(p1, p4, descr=) setfield_gc(p1, 0, descr=) setfield_gc(p1, 307, descr=) p84 = new_with_vtable(19800744) setfield_gc(p84, f36, descr=) finish(p84, descr=) [5ed6619e9448] jit-log-opt-bridge} [5ed74f2eef6e] {jit-log-opt-loop # Loop 2 : loop with 394 ops [p0, p1, p2, p3, p4, p5, p6, p7, i8, f9, i10, i11, p12, p13] debug_merge_point(' #21 LOAD_FAST', 0) guard_nonnull_class(p7, 19800744, descr=) [p1, p0, p7, p2, p3, p4, p5, p6, i8] debug_merge_point(' #24 LOAD_FAST', 0) debug_merge_point(' #27 COMPARE_OP', 0) f15 = getfield_gc_pure(p7, descr=) i16 = float_gt(f15, f9) guard_true(i16, descr=) [p1, p0, p6, p7, p2, p3, p4, p5, i8] debug_merge_point(' #30 POP_JUMP_IF_FALSE', 0) debug_merge_point(' #33 LOAD_FAST', 0) debug_merge_point(' #36 POP_JUMP_IF_FALSE', 0) debug_merge_point(' #39 LOAD_FAST', 0) debug_merge_point(' #42 LOAD_FAST', 0) debug_merge_point(' #45 COMPARE_OP', 0) i17 = int_ge(i8, i10) guard_false(i17, descr=) [p1, p0, p5, p2, p3, p4, p6, p7, i8] debug_merge_point(' #48 POP_JUMP_IF_FALSE', 0) debug_merge_point(' #55 LOAD_GLOBAL', 0) p18 = getfield_gc(p0, descr=) guard_value(p18, ConstPtr(ptr19), descr=) [p1, p0, p18, p2, p3, p4, p5, p6, p7, i8] p20 = getfield_gc(p18, descr=) guard_isnull(p20, descr=) [p1, p0, p20, p18, p2, p3, p4, p5, p6, p7, i8] p22 = getfield_gc(ConstPtr(ptr21), descr=) guard_nonnull_class(p22, ConstClass(Function), descr=) [p1, p0, p22, p2, p3, p4, p5, p6, p7, i8] debug_merge_point(' #58 LOAD_FAST', 0) debug_merge_point(' #61 CALL_FUNCTION', 0) p24 = getfield_gc(p22, descr=) guard_value(p24, ConstPtr(ptr25), descr=) [p1, p0, p24, p22, p2, p3, p4, p5, p6, p7, i8] p26 = getfield_gc(p22, descr=) p27 = getfield_gc(p22, descr=) i28 = force_token() i29 = int_is_zero(i11) guard_true(i29, descr=) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, p26, p13, i28, i8] debug_merge_point(' #0 LOAD_FAST', 1) debug_merge_point(' #3 LOAD_ATTR', 1) p30 = getfield_gc(p4, descr=) guard_value(p30, ConstPtr(ptr31), descr=) [p1, p0, p12, p4, p30, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8] p33 = getfield_gc(ConstPtr(ptr32), descr=) guard_value(p33, ConstPtr(ptr34), descr=) [p1, p0, p12, p4, p33, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8] p35 = getfield_gc(p4, descr=) guard_nonnull_class(p35, 19800744, descr=) [p1, p0, p12, p35, p4, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8] debug_merge_point(' #6 LOAD_FAST', 1) debug_merge_point(' #9 LOAD_ATTR', 1) debug_merge_point(' #12 BINARY_MULTIPLY', 1) f37 = getfield_gc_pure(p35, descr=) f38 = float_mul(f37, f37) debug_merge_point(' #13 STORE_FAST', 1) debug_merge_point(' #16 LOAD_FAST', 1) debug_merge_point(' #19 LOAD_ATTR', 1) p39 = getfield_gc(p4, descr=) guard_nonnull_class(p39, 19800744, descr=) [p1, p0, p12, p39, p4, p2, p3, p22, p5, p6, p7, f38, p26, p13, i28, i8] debug_merge_point(' #22 LOAD_FAST', 1) debug_merge_point(' #25 LOAD_ATTR', 1) debug_merge_point(' #28 BINARY_MULTIPLY', 1) f41 = getfield_gc_pure(p39, descr=) f42 = float_mul(f41, f41) debug_merge_point(' #29 STORE_FAST', 1) debug_merge_point(' #32 LOAD_CONST', 1) debug_merge_point(' #35 LOAD_FAST', 1) debug_merge_point(' #38 LOAD_FAST', 1) debug_merge_point(' #41 BINARY_ADD', 1) f43 = float_add(f38, f42) debug_merge_point(' #42 BINARY_DIVIDE', 1) i45 = float_eq(f43, 0.000000) guard_false(i45, descr=) [p1, p0, p12, f43, p2, p3, p22, p4, p5, p6, p7, f42, f38, p26, p13, i28, i8] f47 = float_truediv(0.500000, f43) debug_merge_point(' #43 STORE_FAST', 1) debug_merge_point(' #46 LOAD_CONST', 1) debug_merge_point(' #49 STORE_FAST', 1) debug_merge_point(' #52 LOAD_FAST', 1) debug_merge_point(' #55 LOAD_ATTR', 1) p48 = getfield_gc(p4, descr=) guard_nonnull_class(p48, ConstClass(W_IntObject), descr=) [p1, p0, p12, p48, p4, p2, p3, p22, p5, p6, p7, f47, f42, f38, p26, p13, i28, i8] debug_merge_point(' #58 STORE_FAST', 1) debug_merge_point(' #61 LOAD_FAST', 1) debug_merge_point(' #64 LOAD_ATTR', 1) p50 = getfield_gc(p4, descr=) guard_nonnull_class(p50, ConstClass(W_IntObject), descr=) [p1, p0, p12, p50, p4, p2, p3, p22, p5, p6, p7, p48, f47, f42, f38, p26, p13, i28, i8] debug_merge_point(' #67 STORE_FAST', 1) debug_merge_point(' #70 LOAD_FAST', 1) debug_merge_point(' #73 LOAD_ATTR', 1) p52 = getfield_gc(p4, descr=) guard_nonnull_class(p52, 19886912, descr=) [p1, p0, p12, p52, p4, p2, p3, p22, p5, p6, p7, p50, p48, f47, f42, f38, p26, p13, i28, i8] debug_merge_point(' #76 STORE_FAST', 1) debug_merge_point(' #79 SETUP_LOOP', 1) debug_merge_point(' #82 LOAD_GLOBAL', 1) guard_value(p26, ConstPtr(ptr54), descr=) [p1, p0, p12, p26, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p56 = getfield_gc(p26, descr=) guard_isnull(p56, descr=) [p1, p0, p12, p56, p26, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p58 = getfield_gc(ConstPtr(ptr57), descr=) guard_isnull(p58, descr=) [p1, p0, p12, p58, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p60 = getfield_gc(ConstPtr(ptr59), descr=) guard_value(p60, ConstPtr(ptr61), descr=) [p1, p0, p12, p60, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p62 = getfield_gc(p60, descr=) guard_isnull(p62, descr=) [p1, p0, p12, p62, p60, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p64 = getfield_gc(ConstPtr(ptr63), descr=) guard_value(p64, ConstPtr(ptr65), descr=) [p1, p0, p12, p64, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #85 LOAD_CONST', 1) debug_merge_point(' #88 LOAD_FAST', 1) debug_merge_point(' #91 LOAD_CONST', 1) debug_merge_point(' #94 BINARY_SUBTRACT', 1) i66 = getfield_gc_pure(p48, descr=) i68 = int_sub_ovf(i66, 1) guard_no_overflow(, descr=) [p1, p0, p12, p48, i68, p2, p3, p22, p4, p5, p6, p7, p64, p52, p50, None, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #95 CALL_FUNCTION', 1) p70 = getfield_gc(ConstPtr(ptr69), descr=) p71 = getfield_gc(ConstPtr(ptr69), descr=) i72 = getfield_gc_pure(p71, descr=) guard_false(i72, descr=) [p1, p0, p12, p70, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p73 = getfield_gc_pure(p71, descr=) i74 = arraylen_gc(p73, descr=) i76 = int_sub(4, i74) i78 = int_ge(3, i76) guard_true(i78, descr=) [p1, p0, p12, p70, i76, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i79 = int_sub(3, i76) i80 = getfield_gc_pure(p71, descr=) guard_false(i80, descr=) [p1, p0, p12, p70, i79, i76, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p81 = getfield_gc_pure(p71, descr=) p82 = getarrayitem_gc(p81, i79, descr=) guard_class(p82, ConstClass(W_IntObject), descr=) [p1, p0, p12, p82, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i84 = getfield_gc_pure(p82, descr=) i85 = int_is_zero(i84) guard_false(i85, descr=) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i87 = int_lt(i84, 0) guard_false(i87, descr=) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i89 = int_lt(1, i68) guard_true(i89, descr=) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i90 = int_sub(i68, 1) i92 = int_sub(i90, 1) i93 = uint_floordiv(i92, i84) i95 = int_add(i93, 1) i97 = int_lt(i95, 0) guard_false(i97, descr=) [p1, p0, p12, i84, i95, p2, p3, p22, p4, p5, p6, p7, p82, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #98 GET_ITER', 1) debug_merge_point(' #99 FOR_ITER', 1) i99 = int_gt(i95, 0) guard_true(i99, descr=) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, i84, i95, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i100 = int_add(1, i84) debug_merge_point(' #102 STORE_FAST', 1) debug_merge_point(' #105 SETUP_LOOP', 1) debug_merge_point(' #108 LOAD_GLOBAL', 1) debug_merge_point(' #111 LOAD_CONST', 1) debug_merge_point(' #114 LOAD_FAST', 1) debug_merge_point(' #117 LOAD_CONST', 1) debug_merge_point(' #120 BINARY_SUBTRACT', 1) i101 = getfield_gc_pure(p50, descr=) i103 = int_sub_ovf(i101, 1) guard_no_overflow(, descr=) [p1, p0, p12, p50, i103, p2, p3, p22, p4, p5, p6, p7, i100, i93, i84, None, None, None, None, p52, None, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #121 CALL_FUNCTION', 1) i104 = getfield_gc_pure(p71, descr=) guard_false(i104, descr=) [p1, p0, p12, p70, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p105 = getfield_gc_pure(p71, descr=) i106 = arraylen_gc(p105, descr=) i108 = int_sub(4, i106) i110 = int_ge(3, i108) guard_true(i110, descr=) [p1, p0, p12, p70, i108, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i111 = int_sub(3, i108) i112 = getfield_gc_pure(p71, descr=) guard_false(i112, descr=) [p1, p0, p12, p70, i111, i108, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p113 = getfield_gc_pure(p71, descr=) p114 = getarrayitem_gc(p113, i111, descr=) guard_class(p114, ConstClass(W_IntObject), descr=) [p1, p0, p12, p114, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i116 = getfield_gc_pure(p114, descr=) i117 = int_is_zero(i116) guard_false(i117, descr=) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i119 = int_lt(i116, 0) guard_false(i119, descr=) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i121 = int_lt(1, i103) guard_true(i121, descr=) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i122 = int_sub(i103, 1) i124 = int_sub(i122, 1) i125 = uint_floordiv(i124, i116) i127 = int_add(i125, 1) i129 = int_lt(i127, 0) guard_false(i129, descr=) [p1, p0, p12, i116, i127, p2, p3, p22, p4, p5, p6, p7, p114, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #124 GET_ITER', 1) debug_merge_point(' #125 FOR_ITER', 1) i131 = int_gt(i127, 0) guard_true(i131, descr=) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, i116, i127, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] i132 = int_add(1, i116) debug_merge_point(' #128 STORE_FAST', 1) debug_merge_point(' #131 LOAD_FAST', 1) debug_merge_point(' #134 LOAD_FAST', 1) debug_merge_point(' #137 LOAD_FAST', 1) debug_merge_point(' #140 BINARY_MULTIPLY', 1) debug_merge_point(' #141 LOAD_FAST', 1) debug_merge_point(' #144 BINARY_ADD', 1) i133 = int_add_ovf(i66, 1) guard_no_overflow(, descr=) [p1, p0, p12, i133, p2, p3, p22, p4, p5, p6, p7, i132, i125, i66, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #145 BINARY_SUBSCR', 1) i134 = getfield_gc(p52, descr=) i135 = int_lt(i133, i134) guard_true(i135, descr=) [p1, p0, p12, p52, i133, p2, p3, p22, p4, p5, p6, p7, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] i136 = getfield_gc(p52, descr=) f137 = getarrayitem_raw(i136, i133, descr=) debug_merge_point(' #146 STORE_FAST', 1) debug_merge_point(' #149 LOAD_FAST', 1) debug_merge_point(' #152 LOAD_FAST', 1) debug_merge_point(' #155 LOAD_CONST', 1) debug_merge_point(' #158 BINARY_SUBTRACT', 1) debug_merge_point(' #159 LOAD_FAST', 1) debug_merge_point(' #162 BINARY_MULTIPLY', 1) debug_merge_point(' #163 LOAD_FAST', 1) debug_merge_point(' #166 BINARY_ADD', 1) debug_merge_point(' #167 BINARY_SUBSCR', 1) f138 = getarrayitem_raw(i136, 1, descr=) debug_merge_point(' #168 LOAD_FAST', 1) debug_merge_point(' #171 LOAD_FAST', 1) debug_merge_point(' #174 LOAD_CONST', 1) debug_merge_point(' #177 BINARY_ADD', 1) debug_merge_point(' #178 LOAD_FAST', 1) debug_merge_point(' #181 BINARY_MULTIPLY', 1) i140 = int_mul_ovf(2, i66) guard_no_overflow(, descr=) [p1, p0, p12, p48, i140, p2, p3, p22, p4, p5, p6, p7, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, None, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #182 LOAD_FAST', 1) debug_merge_point(' #185 BINARY_ADD', 1) i141 = int_add_ovf(i140, 1) guard_no_overflow(, descr=) [p1, p0, p12, i141, p2, p3, p22, p4, p5, p6, p7, i140, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #186 BINARY_SUBSCR', 1) i143 = int_lt(i141, 0) guard_false(i143, descr=) [p1, p0, p12, p52, i141, i134, p2, p3, p22, p4, p5, p6, p7, None, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] i144 = int_lt(i141, i134) guard_true(i144, descr=) [p1, p0, p12, p52, i141, p2, p3, p22, p4, p5, p6, p7, None, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] f145 = getarrayitem_raw(i136, i141, descr=) debug_merge_point(' #187 BINARY_ADD', 1) f146 = float_add(f138, f145) debug_merge_point(' #188 LOAD_FAST', 1) debug_merge_point(' #191 BINARY_MULTIPLY', 1) f147 = float_mul(f146, f42) debug_merge_point(' #192 LOAD_FAST', 1) debug_merge_point(' #195 LOAD_FAST', 1) debug_merge_point(' #198 LOAD_FAST', 1) debug_merge_point(' #201 BINARY_MULTIPLY', 1) debug_merge_point(' #202 LOAD_FAST', 1) debug_merge_point(' #205 BINARY_ADD', 1) debug_merge_point(' #206 LOAD_CONST', 1) debug_merge_point(' #209 BINARY_SUBTRACT', 1) debug_merge_point(' #210 BINARY_SUBSCR', 1) i148 = int_lt(i66, i134) guard_true(i148, descr=) [p1, p0, p12, p52, i66, p2, p3, p22, p4, p5, p6, p7, f147, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] f149 = getarrayitem_raw(i136, i66, descr=) debug_merge_point(' #211 LOAD_FAST', 1) debug_merge_point(' #214 LOAD_FAST', 1) debug_merge_point(' #217 LOAD_FAST', 1) debug_merge_point(' #220 BINARY_MULTIPLY', 1) debug_merge_point(' #221 LOAD_FAST', 1) debug_merge_point(' #224 BINARY_ADD', 1) debug_merge_point(' #225 LOAD_CONST', 1) debug_merge_point(' #228 BINARY_ADD', 1) i151 = int_add(i133, 1) debug_merge_point(' #229 BINARY_SUBSCR', 1) i152 = int_lt(i151, i134) guard_true(i152, descr=) [p1, p0, p12, p52, i151, p2, p3, p22, p4, p5, p6, p7, f149, f147, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] f153 = getarrayitem_raw(i136, i151, descr=) debug_merge_point(' #230 BINARY_ADD', 1) f154 = float_add(f149, f153) debug_merge_point(' #231 LOAD_FAST', 1) debug_merge_point(' #234 BINARY_MULTIPLY', 1) f155 = float_mul(f154, f38) debug_merge_point(' #235 BINARY_ADD', 1) f156 = float_add(f147, f155) debug_merge_point(' #236 LOAD_FAST', 1) debug_merge_point(' #239 BINARY_MULTIPLY', 1) f157 = float_mul(f156, f47) debug_merge_point(' #240 LOAD_FAST', 1) debug_merge_point(' #243 LOAD_FAST', 1) debug_merge_point(' #246 LOAD_FAST', 1) debug_merge_point(' #249 BINARY_MULTIPLY', 1) debug_merge_point(' #250 LOAD_FAST', 1) debug_merge_point(' #253 BINARY_ADD', 1) debug_merge_point(' #254 STORE_SUBSCR', 1) setarrayitem_raw(i136, i133, f157, descr=) debug_merge_point(' #255 LOAD_FAST', 1) debug_merge_point(' #258 LOAD_GLOBAL', 1) p159 = getfield_gc(ConstPtr(ptr158), descr=) guard_nonnull_class(p159, ConstClass(Function), descr=) [p1, p0, p12, p159, p2, p3, p22, p4, p5, p6, p7, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #261 LOAD_FAST', 1) debug_merge_point(' #264 LOAD_FAST', 1) debug_merge_point(' #267 LOAD_FAST', 1) debug_merge_point(' #270 BINARY_MULTIPLY', 1) debug_merge_point(' #271 LOAD_FAST', 1) debug_merge_point(' #274 BINARY_ADD', 1) debug_merge_point(' #275 BINARY_SUBSCR', 1) f161 = getarrayitem_raw(i136, i133, descr=) debug_merge_point(' #276 LOAD_FAST', 1) debug_merge_point(' #279 BINARY_SUBTRACT', 1) f162 = float_sub(f161, f137) debug_merge_point(' #280 CALL_FUNCTION', 1) p163 = getfield_gc(p159, descr=) guard_value(p163, ConstPtr(ptr164), descr=) [p1, p0, p12, p163, p159, p2, p3, p22, p4, p5, p6, p7, f162, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] p165 = getfield_gc(p159, descr=) p166 = getfield_gc(p159, descr=) i167 = force_token() debug_merge_point(' #0 LOAD_FAST', 2) debug_merge_point(' #3 LOAD_FAST', 2) debug_merge_point(' #6 BINARY_MULTIPLY', 2) f168 = float_mul(f162, f162) debug_merge_point(' #7 RETURN_VALUE', 2) debug_merge_point(' #283 INPLACE_ADD', 1) f170 = float_add(0.000000, f168) debug_merge_point(' #284 STORE_FAST', 1) debug_merge_point(' #287 JUMP_ABSOLUTE', 1) i172 = getfield_raw(38968960, descr=) i174 = int_sub(i172, 100) setfield_raw(38968960, i174, descr=) i176 = int_lt(i174, 0) guard_false(i176, descr=) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, f170, None, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] debug_merge_point(' #125 FOR_ITER', 1) i177 = force_token() p179 = new_with_vtable(19809200) setfield_gc(p179, i28, descr=) setfield_gc(p12, p179, descr=) setfield_gc(p0, i177, descr=) p181 = new_with_vtable(19863424) setfield_gc(p181, p13, descr=) setfield_gc(p181, ConstPtr(ptr54), descr=) setfield_gc(p181, 34, descr=) setfield_gc(p181, ConstPtr(ptr25), descr=) p184 = new_array(8, descr=) p186 = new_with_vtable(19861240) setfield_gc(p186, i100, descr=) setfield_gc(p186, i93, descr=) setfield_gc(p186, i84, descr=) setarrayitem_gc(p184, 0, p186, descr=) p189 = new_with_vtable(19861240) setfield_gc(p189, i132, descr=) setfield_gc(p189, i125, descr=) setfield_gc(p189, i116, descr=) setarrayitem_gc(p184, 1, p189, descr=) setfield_gc(p181, p184, descr=) setfield_gc(p181, 125, descr=) p193 = new_with_vtable(19865144) setfield_gc(p193, 291, descr=) setfield_gc(p193, 1, descr=) p197 = new_with_vtable(19865144) setfield_gc(p197, 295, descr=) setfield_gc(p193, p197, descr=) setfield_gc(p181, p193, descr=) p200 = new_array(11, descr=) setarrayitem_gc(p200, 0, p4, descr=) p203 = new_with_vtable(19800744) setfield_gc(p203, f38, descr=) setarrayitem_gc(p200, 1, p203, descr=) p206 = new_with_vtable(19800744) setfield_gc(p206, f42, descr=) setarrayitem_gc(p200, 2, p206, descr=) p209 = new_with_vtable(19800744) setfield_gc(p209, f47, descr=) setarrayitem_gc(p200, 3, p209, descr=) p212 = new_with_vtable(19800744) setfield_gc(p212, f170, descr=) setarrayitem_gc(p200, 4, p212, descr=) setarrayitem_gc(p200, 5, p48, descr=) setarrayitem_gc(p200, 6, p50, descr=) setarrayitem_gc(p200, 7, p52, descr=) p218 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p218, 1, descr=) setarrayitem_gc(p200, 8, p218, descr=) p221 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p221, 1, descr=) setarrayitem_gc(p200, 9, p221, descr=) p224 = new_with_vtable(19800744) setfield_gc(p224, f137, descr=) setarrayitem_gc(p200, 10, p224, descr=) setfield_gc(p181, p200, descr=) setfield_gc(p181, 2, descr=) p235 = call_assembler(p181, p12, ConstPtr(ptr25), p193, 2, ConstPtr(ptr227), 0, 125, p186, p189, ConstPtr(ptr229), ConstPtr(ptr230), ConstPtr(ptr231), ConstPtr(ptr232), ConstPtr(ptr233), ConstPtr(ptr234), p4, p203, p206, p209, p212, p48, p50, p52, p218, p221, p224, descr=) guard_not_forced(, descr=) [p1, p0, p12, p181, p235, p179, p2, p3, p22, p4, p5, p6, p7, i8] guard_no_exception(, descr=) [p1, p0, p12, p181, p235, p179, p2, p3, p22, p4, p5, p6, p7, i8] p236 = getfield_gc(p12, descr=) guard_isnull(p236, descr=) [p1, p0, p12, p235, p181, p236, p179, p2, p3, p22, p4, p5, p6, p7, i8] i237 = ptr_eq(p181, p0) guard_false(i237, descr=) [p1, p0, p12, p235, p181, p179, p2, p3, p22, p4, p5, p6, p7, i8] i238 = getfield_gc(p12, descr=) setfield_gc(p181, ConstPtr(ptr239), descr=) i240 = int_is_true(i238) guard_false(i240, descr=) [p1, p0, p235, p181, p12, p179, p2, p3, p22, p4, p5, p6, p7, i8] p241 = getfield_gc(p181, descr=) debug_merge_point(' #64 STORE_FAST', 0) debug_merge_point(' #67 LOAD_FAST', 0) debug_merge_point(' #70 LOAD_CONST', 0) debug_merge_point(' #73 INPLACE_ADD', 0) i243 = int_add(i8, 1) debug_merge_point(' #74 STORE_FAST', 0) debug_merge_point(' #77 JUMP_ABSOLUTE', 0) i245 = getfield_raw(38968960, descr=) i247 = int_sub(i245, 100) setfield_raw(38968960, i247, descr=) setfield_gc(p12, p241, descr=) setfield_gc(p179, p181, descr=) setfield_gc(p179, -3, descr=) i250 = int_lt(i247, 0) guard_false(i250, descr=) [p1, p0, p2, p3, p4, p5, p6, p235, i243, None] debug_merge_point(' #21 LOAD_FAST', 0) jump(p0, p1, p2, p3, p4, p5, p6, p235, i243, f9, i10, i238, p12, p241, descr=) [5ed74fc965fa] jit-log-opt-loop} [5ed74fe43ee0] {jit-log-opt-loop # Loop 3 : entry bridge with 413 ops [p0, p1, p2, p3, i4, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14] debug_merge_point(' #21 LOAD_FAST', 0) guard_value(i4, 0, descr=) [i4, p1, p0, p2, p3, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14] guard_nonnull_class(p13, 19800744, descr=) [p1, p0, p13, p2, p3, p5, i6, p8, p9, p10, p11, p12, p14] guard_value(i6, 0, descr=) [i6, p1, p0, p2, p3, p5, p13, p9, p10, p11, p12, p14] debug_merge_point(' #24 LOAD_FAST', 0) guard_nonnull_class(p12, 19800744, descr=) [p1, p0, p12, p2, p3, p5, p13, p9, p10, p11, p14] debug_merge_point(' #27 COMPARE_OP', 0) f19 = getfield_gc_pure(p13, descr=) f20 = getfield_gc_pure(p12, descr=) i21 = float_gt(f19, f20) guard_true(i21, descr=) [p1, p0, p12, p13, p2, p3, p5, p10, p11, p14] debug_merge_point(' #30 POP_JUMP_IF_FALSE', 0) debug_merge_point(' #33 LOAD_FAST', 0) guard_nonnull_class(p11, ConstClass(W_IntObject), descr=) [p1, p0, p11, p2, p3, p5, p10, p12, p13, p14] debug_merge_point(' #36 POP_JUMP_IF_FALSE', 0) i23 = getfield_gc_pure(p11, descr=) i24 = int_is_true(i23) guard_true(i24, descr=) [p1, p0, p11, p2, p3, p5, p10, p12, p13, p14] debug_merge_point(' #39 LOAD_FAST', 0) guard_nonnull_class(p14, ConstClass(W_IntObject), descr=) [p1, p0, p14, p2, p3, p5, p10, p11, p12, p13] debug_merge_point(' #42 LOAD_FAST', 0) debug_merge_point(' #45 COMPARE_OP', 0) i26 = getfield_gc_pure(p14, descr=) i27 = int_ge(i26, i23) guard_false(i27, descr=) [p1, p0, p11, p14, p2, p3, p5, p10, p12, p13] debug_merge_point(' #48 POP_JUMP_IF_FALSE', 0) debug_merge_point(' #55 LOAD_GLOBAL', 0) guard_value(p2, ConstPtr(ptr28), descr=) [p1, p0, p2, p3, p5, p10, p11, p12, p13, p14] p29 = getfield_gc(p0, descr=) guard_value(p29, ConstPtr(ptr30), descr=) [p1, p0, p29, p3, p5, p10, p11, p12, p13, p14] p31 = getfield_gc(p29, descr=) guard_isnull(p31, descr=) [p1, p0, p31, p29, p3, p5, p10, p11, p12, p13, p14] p33 = getfield_gc(ConstPtr(ptr32), descr=) guard_nonnull_class(p33, ConstClass(Function), descr=) [p1, p0, p33, p3, p5, p10, p11, p12, p13, p14] debug_merge_point(' #58 LOAD_FAST', 0) guard_nonnull_class(p10, 19852624, descr=) [p1, p0, p10, p3, p5, p33, p11, p12, p13, p14] debug_merge_point(' #61 CALL_FUNCTION', 0) p36 = getfield_gc(p33, descr=) guard_value(p36, ConstPtr(ptr37), descr=) [p1, p0, p36, p33, p3, p5, p10, p11, p12, p13, p14] p38 = getfield_gc(p33, descr=) p39 = getfield_gc(p33, descr=) p41 = call(ConstClass(getexecutioncontext), descr=) p42 = getfield_gc(p41, descr=) i43 = force_token() p44 = getfield_gc(p41, descr=) guard_isnull(p44, descr=) [p1, p0, p41, p44, p3, p5, p33, p10, p11, p12, p13, p14, i43, p42, p38] i45 = getfield_gc(p41, descr=) i46 = int_is_zero(i45) guard_true(i46, descr=) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i43, p42, p38] debug_merge_point(' #0 LOAD_FAST', 1) debug_merge_point(' #3 LOAD_ATTR', 1) p47 = getfield_gc(p10, descr=) guard_value(p47, ConstPtr(ptr48), descr=) [p1, p0, p41, p10, p47, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38] p50 = getfield_gc(ConstPtr(ptr49), descr=) guard_value(p50, ConstPtr(ptr51), descr=) [p1, p0, p41, p10, p50, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38] p52 = getfield_gc(p10, descr=) guard_nonnull_class(p52, 19800744, descr=) [p1, p0, p41, p52, p10, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38] debug_merge_point(' #6 LOAD_FAST', 1) debug_merge_point(' #9 LOAD_ATTR', 1) debug_merge_point(' #12 BINARY_MULTIPLY', 1) f54 = getfield_gc_pure(p52, descr=) f55 = float_mul(f54, f54) debug_merge_point(' #13 STORE_FAST', 1) debug_merge_point(' #16 LOAD_FAST', 1) debug_merge_point(' #19 LOAD_ATTR', 1) p56 = getfield_gc(p10, descr=) guard_nonnull_class(p56, 19800744, descr=) [p1, p0, p41, p56, p10, p3, p5, p33, p11, p12, p13, p14, f55, i43, p42, p38] debug_merge_point(' #22 LOAD_FAST', 1) debug_merge_point(' #25 LOAD_ATTR', 1) debug_merge_point(' #28 BINARY_MULTIPLY', 1) f58 = getfield_gc_pure(p56, descr=) f59 = float_mul(f58, f58) debug_merge_point(' #29 STORE_FAST', 1) debug_merge_point(' #32 LOAD_CONST', 1) debug_merge_point(' #35 LOAD_FAST', 1) debug_merge_point(' #38 LOAD_FAST', 1) debug_merge_point(' #41 BINARY_ADD', 1) f60 = float_add(f55, f59) debug_merge_point(' #42 BINARY_DIVIDE', 1) i62 = float_eq(f60, 0.000000) guard_false(i62, descr=) [p1, p0, p41, f60, p3, p5, p33, p10, p11, p12, p13, p14, f59, f55, i43, p42, p38] f64 = float_truediv(0.500000, f60) debug_merge_point(' #43 STORE_FAST', 1) debug_merge_point(' #46 LOAD_CONST', 1) debug_merge_point(' #49 STORE_FAST', 1) debug_merge_point(' #52 LOAD_FAST', 1) debug_merge_point(' #55 LOAD_ATTR', 1) p65 = getfield_gc(p10, descr=) guard_nonnull_class(p65, ConstClass(W_IntObject), descr=) [p1, p0, p41, p65, p10, p3, p5, p33, p11, p12, p13, p14, f64, f59, f55, i43, p42, p38] debug_merge_point(' #58 STORE_FAST', 1) debug_merge_point(' #61 LOAD_FAST', 1) debug_merge_point(' #64 LOAD_ATTR', 1) p67 = getfield_gc(p10, descr=) guard_nonnull_class(p67, ConstClass(W_IntObject), descr=) [p1, p0, p41, p67, p10, p3, p5, p33, p11, p12, p13, p14, p65, f64, f59, f55, i43, p42, p38] debug_merge_point(' #67 STORE_FAST', 1) debug_merge_point(' #70 LOAD_FAST', 1) debug_merge_point(' #73 LOAD_ATTR', 1) p69 = getfield_gc(p10, descr=) guard_nonnull_class(p69, 19886912, descr=) [p1, p0, p41, p69, p10, p3, p5, p33, p11, p12, p13, p14, p67, p65, f64, f59, f55, i43, p42, p38] debug_merge_point(' #76 STORE_FAST', 1) debug_merge_point(' #79 SETUP_LOOP', 1) debug_merge_point(' #82 LOAD_GLOBAL', 1) guard_value(p38, ConstPtr(ptr71), descr=) [p1, p0, p41, p38, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] p73 = getfield_gc(p38, descr=) guard_isnull(p73, descr=) [p1, p0, p41, p73, p38, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] p75 = getfield_gc(ConstPtr(ptr74), descr=) guard_isnull(p75, descr=) [p1, p0, p41, p75, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] p77 = getfield_gc(ConstPtr(ptr76), descr=) guard_value(p77, ConstPtr(ptr78), descr=) [p1, p0, p41, p77, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] p79 = getfield_gc(p77, descr=) guard_isnull(p79, descr=) [p1, p0, p41, p79, p77, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] p81 = getfield_gc(ConstPtr(ptr80), descr=) guard_value(p81, ConstPtr(ptr82), descr=) [p1, p0, p41, p81, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #85 LOAD_CONST', 1) debug_merge_point(' #88 LOAD_FAST', 1) debug_merge_point(' #91 LOAD_CONST', 1) debug_merge_point(' #94 BINARY_SUBTRACT', 1) i83 = getfield_gc_pure(p65, descr=) i85 = int_sub_ovf(i83, 1) guard_no_overflow(, descr=) [p1, p0, p41, p65, i85, p3, p5, p33, p10, p11, p12, p13, p14, p81, p69, p67, None, f64, f59, f55, i43, p42, None] debug_merge_point(' #95 CALL_FUNCTION', 1) p87 = getfield_gc(ConstPtr(ptr86), descr=) p88 = getfield_gc(ConstPtr(ptr86), descr=) i89 = getfield_gc_pure(p88, descr=) guard_false(i89, descr=) [p1, p0, p41, p87, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] p90 = getfield_gc_pure(p88, descr=) i91 = arraylen_gc(p90, descr=) i93 = int_sub(4, i91) i95 = int_ge(3, i93) guard_true(i95, descr=) [p1, p0, p41, p87, i93, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i96 = int_sub(3, i93) i97 = getfield_gc_pure(p88, descr=) guard_false(i97, descr=) [p1, p0, p41, p87, i96, i93, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] p98 = getfield_gc_pure(p88, descr=) p99 = getarrayitem_gc(p98, i96, descr=) guard_class(p99, ConstClass(W_IntObject), descr=) [p1, p0, p41, p99, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i101 = getfield_gc_pure(p99, descr=) i102 = int_is_zero(i101) guard_false(i102, descr=) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i104 = int_lt(i101, 0) guard_false(i104, descr=) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i106 = int_lt(1, i85) guard_true(i106, descr=) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i107 = int_sub(i85, 1) i109 = int_sub(i107, 1) i110 = uint_floordiv(i109, i101) i112 = int_add(i110, 1) i114 = int_lt(i112, 0) guard_false(i114, descr=) [p1, p0, p41, i101, i112, p3, p5, p33, p10, p11, p12, p13, p14, p99, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #98 GET_ITER', 1) debug_merge_point(' #99 FOR_ITER', 1) i116 = int_gt(i112, 0) guard_true(i116, descr=) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i112, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i117 = int_add(1, i101) debug_merge_point(' #102 STORE_FAST', 1) debug_merge_point(' #105 SETUP_LOOP', 1) debug_merge_point(' #108 LOAD_GLOBAL', 1) debug_merge_point(' #111 LOAD_CONST', 1) debug_merge_point(' #114 LOAD_FAST', 1) debug_merge_point(' #117 LOAD_CONST', 1) debug_merge_point(' #120 BINARY_SUBTRACT', 1) i118 = getfield_gc_pure(p67, descr=) i120 = int_sub_ovf(i118, 1) guard_no_overflow(, descr=) [p1, p0, p41, p67, i120, p3, p5, p33, p10, p11, p12, p13, p14, i110, i117, None, i101, None, None, None, p69, None, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #121 CALL_FUNCTION', 1) i121 = getfield_gc_pure(p88, descr=) guard_false(i121, descr=) [p1, p0, p41, p87, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] p122 = getfield_gc_pure(p88, descr=) i123 = arraylen_gc(p122, descr=) i125 = int_sub(4, i123) i127 = int_ge(3, i125) guard_true(i127, descr=) [p1, p0, p41, p87, i125, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i128 = int_sub(3, i125) i129 = getfield_gc_pure(p88, descr=) guard_false(i129, descr=) [p1, p0, p41, p87, i128, i125, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] p130 = getfield_gc_pure(p88, descr=) p131 = getarrayitem_gc(p130, i128, descr=) guard_class(p131, ConstClass(W_IntObject), descr=) [p1, p0, p41, p131, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i133 = getfield_gc_pure(p131, descr=) i134 = int_is_zero(i133) guard_false(i134, descr=) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i136 = int_lt(i133, 0) guard_false(i136, descr=) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i138 = int_lt(1, i120) guard_true(i138, descr=) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i139 = int_sub(i120, 1) i141 = int_sub(i139, 1) i142 = uint_floordiv(i141, i133) i144 = int_add(i142, 1) i146 = int_lt(i144, 0) guard_false(i146, descr=) [p1, p0, p41, i133, i144, p3, p5, p33, p10, p11, p12, p13, p14, p131, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #124 GET_ITER', 1) debug_merge_point(' #125 FOR_ITER', 1) i148 = int_gt(i144, 0) guard_true(i148, descr=) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i144, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] i149 = int_add(1, i133) debug_merge_point(' #128 STORE_FAST', 1) debug_merge_point(' #131 LOAD_FAST', 1) debug_merge_point(' #134 LOAD_FAST', 1) debug_merge_point(' #137 LOAD_FAST', 1) debug_merge_point(' #140 BINARY_MULTIPLY', 1) debug_merge_point(' #141 LOAD_FAST', 1) debug_merge_point(' #144 BINARY_ADD', 1) i150 = int_add_ovf(i83, 1) guard_no_overflow(, descr=) [p1, p0, p41, i150, p3, p5, p33, p10, p11, p12, p13, p14, i83, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #145 BINARY_SUBSCR', 1) i151 = getfield_gc(p69, descr=) i152 = int_lt(i150, i151) guard_true(i152, descr=) [p1, p0, p41, p69, i150, p3, p5, p33, p10, p11, p12, p13, p14, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] i153 = getfield_gc(p69, descr=) f154 = getarrayitem_raw(i153, i150, descr=) debug_merge_point(' #146 STORE_FAST', 1) debug_merge_point(' #149 LOAD_FAST', 1) debug_merge_point(' #152 LOAD_FAST', 1) debug_merge_point(' #155 LOAD_CONST', 1) debug_merge_point(' #158 BINARY_SUBTRACT', 1) debug_merge_point(' #159 LOAD_FAST', 1) debug_merge_point(' #162 BINARY_MULTIPLY', 1) debug_merge_point(' #163 LOAD_FAST', 1) debug_merge_point(' #166 BINARY_ADD', 1) debug_merge_point(' #167 BINARY_SUBSCR', 1) f155 = getarrayitem_raw(i153, 1, descr=) debug_merge_point(' #168 LOAD_FAST', 1) debug_merge_point(' #171 LOAD_FAST', 1) debug_merge_point(' #174 LOAD_CONST', 1) debug_merge_point(' #177 BINARY_ADD', 1) debug_merge_point(' #178 LOAD_FAST', 1) debug_merge_point(' #181 BINARY_MULTIPLY', 1) i157 = int_mul_ovf(2, i83) guard_no_overflow(, descr=) [p1, p0, p41, p65, i157, p3, p5, p33, p10, p11, p12, p13, p14, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, None, f64, f59, f55, i43, p42, None] debug_merge_point(' #182 LOAD_FAST', 1) debug_merge_point(' #185 BINARY_ADD', 1) i158 = int_add_ovf(i157, 1) guard_no_overflow(, descr=) [p1, p0, p41, i158, p3, p5, p33, p10, p11, p12, p13, p14, i157, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #186 BINARY_SUBSCR', 1) i160 = int_lt(i158, 0) guard_false(i160, descr=) [p1, p0, p41, p69, i158, i151, p3, p5, p33, p10, p11, p12, p13, p14, None, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] i161 = int_lt(i158, i151) guard_true(i161, descr=) [p1, p0, p41, p69, i158, p3, p5, p33, p10, p11, p12, p13, p14, None, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] f162 = getarrayitem_raw(i153, i158, descr=) debug_merge_point(' #187 BINARY_ADD', 1) f163 = float_add(f155, f162) debug_merge_point(' #188 LOAD_FAST', 1) debug_merge_point(' #191 BINARY_MULTIPLY', 1) f164 = float_mul(f163, f59) debug_merge_point(' #192 LOAD_FAST', 1) debug_merge_point(' #195 LOAD_FAST', 1) debug_merge_point(' #198 LOAD_FAST', 1) debug_merge_point(' #201 BINARY_MULTIPLY', 1) debug_merge_point(' #202 LOAD_FAST', 1) debug_merge_point(' #205 BINARY_ADD', 1) debug_merge_point(' #206 LOAD_CONST', 1) debug_merge_point(' #209 BINARY_SUBTRACT', 1) debug_merge_point(' #210 BINARY_SUBSCR', 1) i165 = int_lt(i83, i151) guard_true(i165, descr=) [p1, p0, p41, p69, i83, p3, p5, p33, p10, p11, p12, p13, p14, f164, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] f166 = getarrayitem_raw(i153, i83, descr=) debug_merge_point(' #211 LOAD_FAST', 1) debug_merge_point(' #214 LOAD_FAST', 1) debug_merge_point(' #217 LOAD_FAST', 1) debug_merge_point(' #220 BINARY_MULTIPLY', 1) debug_merge_point(' #221 LOAD_FAST', 1) debug_merge_point(' #224 BINARY_ADD', 1) debug_merge_point(' #225 LOAD_CONST', 1) debug_merge_point(' #228 BINARY_ADD', 1) i168 = int_add(i150, 1) debug_merge_point(' #229 BINARY_SUBSCR', 1) i169 = int_lt(i168, i151) guard_true(i169, descr=) [p1, p0, p41, p69, i168, p3, p5, p33, p10, p11, p12, p13, p14, f166, f164, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] f170 = getarrayitem_raw(i153, i168, descr=) debug_merge_point(' #230 BINARY_ADD', 1) f171 = float_add(f166, f170) debug_merge_point(' #231 LOAD_FAST', 1) debug_merge_point(' #234 BINARY_MULTIPLY', 1) f172 = float_mul(f171, f55) debug_merge_point(' #235 BINARY_ADD', 1) f173 = float_add(f164, f172) debug_merge_point(' #236 LOAD_FAST', 1) debug_merge_point(' #239 BINARY_MULTIPLY', 1) f174 = float_mul(f173, f64) debug_merge_point(' #240 LOAD_FAST', 1) debug_merge_point(' #243 LOAD_FAST', 1) debug_merge_point(' #246 LOAD_FAST', 1) debug_merge_point(' #249 BINARY_MULTIPLY', 1) debug_merge_point(' #250 LOAD_FAST', 1) debug_merge_point(' #253 BINARY_ADD', 1) debug_merge_point(' #254 STORE_SUBSCR', 1) setarrayitem_raw(i153, i150, f174, descr=) debug_merge_point(' #255 LOAD_FAST', 1) debug_merge_point(' #258 LOAD_GLOBAL', 1) p176 = getfield_gc(ConstPtr(ptr175), descr=) guard_nonnull_class(p176, ConstClass(Function), descr=) [p1, p0, p41, p176, p3, p5, p33, p10, p11, p12, p13, p14, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #261 LOAD_FAST', 1) debug_merge_point(' #264 LOAD_FAST', 1) debug_merge_point(' #267 LOAD_FAST', 1) debug_merge_point(' #270 BINARY_MULTIPLY', 1) debug_merge_point(' #271 LOAD_FAST', 1) debug_merge_point(' #274 BINARY_ADD', 1) debug_merge_point(' #275 BINARY_SUBSCR', 1) f178 = getarrayitem_raw(i153, i150, descr=) debug_merge_point(' #276 LOAD_FAST', 1) debug_merge_point(' #279 BINARY_SUBTRACT', 1) f179 = float_sub(f178, f154) debug_merge_point(' #280 CALL_FUNCTION', 1) p180 = getfield_gc(p176, descr=) guard_value(p180, ConstPtr(ptr181), descr=) [p1, p0, p41, p180, p176, p3, p5, p33, p10, p11, p12, p13, p14, f179, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] p182 = getfield_gc(p176, descr=) p183 = getfield_gc(p176, descr=) i184 = force_token() debug_merge_point(' #0 LOAD_FAST', 2) debug_merge_point(' #3 LOAD_FAST', 2) debug_merge_point(' #6 BINARY_MULTIPLY', 2) f185 = float_mul(f179, f179) debug_merge_point(' #7 RETURN_VALUE', 2) i186 = int_is_true(i45) guard_false(i186, descr=) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, p182, i184, p176, f185, f179, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #283 INPLACE_ADD', 1) f188 = float_add(0.000000, f185) debug_merge_point(' #284 STORE_FAST', 1) debug_merge_point(' #287 JUMP_ABSOLUTE', 1) i190 = getfield_raw(38968960, descr=) i192 = int_sub(i190, 100) setfield_raw(38968960, i192, descr=) i194 = int_lt(i192, 0) guard_false(i194, descr=) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, f188, None, None, None, None, None, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] debug_merge_point(' #125 FOR_ITER', 1) i195 = force_token() p197 = new_with_vtable(19809200) setfield_gc(p197, i43, descr=) setfield_gc(p41, p197, descr=) setfield_gc(p0, i195, descr=) p199 = new_with_vtable(19863424) setfield_gc(p199, p42, descr=) setfield_gc(p199, ConstPtr(ptr71), descr=) setfield_gc(p199, 34, descr=) setfield_gc(p199, ConstPtr(ptr37), descr=) p202 = new_array(8, descr=) p204 = new_with_vtable(19861240) setfield_gc(p204, i117, descr=) setfield_gc(p204, i110, descr=) setfield_gc(p204, i101, descr=) setarrayitem_gc(p202, 0, p204, descr=) p207 = new_with_vtable(19861240) setfield_gc(p207, i149, descr=) setfield_gc(p207, i142, descr=) setfield_gc(p207, i133, descr=) setarrayitem_gc(p202, 1, p207, descr=) setfield_gc(p199, p202, descr=) setfield_gc(p199, 125, descr=) p211 = new_with_vtable(19865144) setfield_gc(p211, 291, descr=) setfield_gc(p211, 1, descr=) p215 = new_with_vtable(19865144) setfield_gc(p215, 295, descr=) setfield_gc(p211, p215, descr=) setfield_gc(p199, p211, descr=) p218 = new_array(11, descr=) setarrayitem_gc(p218, 0, p10, descr=) p221 = new_with_vtable(19800744) setfield_gc(p221, f55, descr=) setarrayitem_gc(p218, 1, p221, descr=) p224 = new_with_vtable(19800744) setfield_gc(p224, f59, descr=) setarrayitem_gc(p218, 2, p224, descr=) p227 = new_with_vtable(19800744) setfield_gc(p227, f64, descr=) setarrayitem_gc(p218, 3, p227, descr=) p230 = new_with_vtable(19800744) setfield_gc(p230, f188, descr=) setarrayitem_gc(p218, 4, p230, descr=) setarrayitem_gc(p218, 5, p65, descr=) setarrayitem_gc(p218, 6, p67, descr=) setarrayitem_gc(p218, 7, p69, descr=) p236 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p236, 1, descr=) setarrayitem_gc(p218, 8, p236, descr=) p239 = new_with_vtable(ConstClass(W_IntObject)) setfield_gc(p239, 1, descr=) setarrayitem_gc(p218, 9, p239, descr=) p242 = new_with_vtable(19800744) setfield_gc(p242, f154, descr=) setarrayitem_gc(p218, 10, p242, descr=) setfield_gc(p199, p218, descr=) setfield_gc(p199, 2, descr=) p253 = call_assembler(p199, p41, ConstPtr(ptr37), p211, 2, ConstPtr(ptr245), 0, 125, p204, p207, ConstPtr(ptr247), ConstPtr(ptr248), ConstPtr(ptr249), ConstPtr(ptr250), ConstPtr(ptr251), ConstPtr(ptr252), p10, p221, p224, p227, p230, p65, p67, p69, p236, p239, p242, descr=) guard_not_forced(, descr=) [p1, p0, p41, p199, p253, p197, p3, p5, p33, p10, p11, p12, p13, p14] guard_no_exception(, descr=) [p1, p0, p41, p199, p253, p197, p3, p5, p33, p10, p11, p12, p13, p14] p254 = getfield_gc(p41, descr=) guard_isnull(p254, descr=) [p1, p0, p41, p253, p199, p254, p197, p3, p5, p33, p10, p11, p12, p13, p14] i255 = ptr_eq(p199, p0) guard_false(i255, descr=) [p1, p0, p41, p253, p199, p197, p3, p5, p33, p10, p11, p12, p13, p14] i256 = getfield_gc(p41, descr=) setfield_gc(p199, ConstPtr(ptr257), descr=) i258 = int_is_true(i256) guard_false(i258, descr=) [p1, p0, p253, p199, p41, p197, p3, p5, p33, p10, p11, p12, p13, p14] p259 = getfield_gc(p199, descr=) debug_merge_point(' #64 STORE_FAST', 0) debug_merge_point(' #67 LOAD_FAST', 0) debug_merge_point(' #70 LOAD_CONST', 0) debug_merge_point(' #73 INPLACE_ADD', 0) i261 = int_add(i26, 1) debug_merge_point(' #74 STORE_FAST', 0) debug_merge_point(' #77 JUMP_ABSOLUTE', 0) i263 = getfield_raw(38968960, descr=) i265 = int_sub(i263, 100) setfield_raw(38968960, i265, descr=) setfield_gc(p41, p259, descr=) setfield_gc(p197, p199, descr=) setfield_gc(p197, -3, descr=) i268 = int_lt(i265, 0) guard_false(i268, descr=) [p1, p0, p3, p5, p10, p11, p12, p253, i261] debug_merge_point(' #21 LOAD_FAST', 0) jump(p0, p1, p3, p5, p10, p11, p12, p253, i261, f20, i23, i256, p41, p259, descr=) [5ed74ff695c8] jit-log-opt-loop} [5ed8737e9776] {jit-backend-counts 0:493724565 1:2281802 2:1283242 3:993105 4:2933 5:2163 6:2492 7:1799 8:963 9:36 [5ed8737ee19c] jit-backend-counts} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.r3000066400000000000000000000035371250413007300251250ustar00rootroot00000000000000preface.... everything what is before header is not evaluated so this should not be colorized: 1 + 2 REBOL [] ;<- this is minimal header, everything behind it must be colorized ;## String tests ## print "Hello ^"World" ;<- with escaped char multiline-string: { bla bla "bla" {bla} } char-a: #"a" escaped-a: #"^(61)" new-line: #"^/" ;## Binaries ## print decompress 64#{eJzLSM3JyQcABiwCFQUAAAA=} ;2#{0000 00000} ;<- this one is invalid! 2#{} #{FF00} ;##Date + time ## 1-Feb-2009 1-Feb-2009/2:24:46+1:0 1:0 1:1:1 -0:1.1 ;## Tuple ## red: 255.0.0 red-with-alpha: 255.0.0.100 ;## url!, file! and email! ## aaa@bbb.cz http:// dns:// tcp://127.0.0.1 %/c/rebol/ %"c:\Program Files\" %/c/Program%20Files/ to-rebol-file "c:\Program Files\" suffix? %bla.swf ;## Money ## $1 -$1.2 USA$100 ;## Tag! ## ;## Pair! ## 10x200 ;## Issue! ## type? #ff0000 ;== issue! ;## some numbers ## to integer! (1 + (x / 4.5) * 1E-4) ;## some spec comments 1 + 1 comment "aa" 2 + 2 comment {aa} 3 + 3 comment {a^{} 4 + 4 comment {{}} 5 + 5 comment { foo: 6 } 6 + 6 comment [foo: 6] 7 + 7 comment [foo: "[" ] 8 + 8 comment [foo: {^{} ] 9 + 9 comment [foo: {boo} ] 10 + 10 comment 5-May-2014/11:17:34+2:00 5-May-2014/11:17:34+2:00 11 + 11 ;## other tests ## ---: 1 x/(1 + n)/y b/:1 ;## and... REBOL [ purpose: { reads css file and creates html from it so one can see how the styles looks like } ] style: %default out: rejoin [{ Pygments style: } style {.css
    }]
    css: read/lines join style %.css
    foreach line css [
        parse line [".syntax ." copy c to " " thru "/*" copy t to "*/" to end (
            append out rejoin ["" t "^/"])
        ]
    ]
    write join style %.html join out "
    " halt pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.rb000066400000000000000000000103771250413007300252040ustar00rootroot00000000000000a.each{|el|anz[el]=anz[el]?anz[el]+1:1} while x<10000 #a bis f dienen dazu die Nachbarschaft festzulegen. Man stelle sich die #Zahl von 1 bis 64 im Binärcode vor 1 bedeutet an 0 aus b=(p[x]%32)/16<1 ? 0 : 1 (x-102>=0? n[x-102].to_i : 0)*a+(x-101>=0?n[x-101].to_i : 0)*e+n[x-100].to_i+(x-99>=0? n[x-99].to_i : 0)*f+(x-98>=0? n[x-98].to_i : 0)*a+ n[x+199].to_i*b+n[x+200].to_i*d+n[x+201].to_i*b #und die Ausgabe folgt g=%w{} x=0 #leere regex test //, 123 while x<100 puts"#{g[x]}" x+=1 end puts"" sleep(10) 1E1E1 puts 30.send(:/, 5) # prints 6 # fun with class attributes class Foo def self.blub x if not x.nil? self.new end end def another_way_to_get_class self.class end end # ruby 1.9 "call operator" a = Proc.new { 42 } a.() "instance variables can be #@included, #@@class_variables\n and #$globals as well." `instance variables can be #@included, #@@class_variables\n and #$globals as well.` 'instance variables can be #@included, #@@class_variables\n and #$globals as well.' /instance variables can be #@included, #@@class_variables\n and #$globals as well./mousenix :"instance variables can be #@included, #@@class_variables\n and #$globals as well." :'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %q'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %Q'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %w'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %W'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %s'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %r'instance variables can be #@included, #@@class_variables\n and #$globals as well.' %x'instance variables can be #@included, #@@class_variables\n and #$globals as well.' #%W[ but #@0illegal_values look strange.] %s#ruby allows strange#{constructs} %s#ruby allows strange#$constructs %s#ruby allows strange#@@constructs ################################################################## # HEREDOCS foo(<<-A, <<-B) this is the text of a A and this is the text of b B a = <<"EOF" This is a multiline #$here document terminated by EOF on a line by itself EOF a = <<'EOF' This is a multiline #$here document terminated by EOF on a line by itself EOF b=(p[x] %32)/16<1 ? 0 : 1 <<"" #{test} #@bla #die suppe!!! \xfffff super <<-EOE % [ foo EOE < [1, 2, 3, 4, 5, 6] p [1,2,3].`(:concat, [4,5,6]) # => [1, 2, 3, 4, 5, 6] p "Hurra! ".`(:*, 3) # => "Hurra! Hurra! Hurra! " p "Hurra! ".`('*', 3) # => "Hurra! Hurra! Hurra! " # Leider geht nicht die Wunschform # [1,2,3] `concat` [4,5,6] class Object @@infixops = [] alias :xeq :` def addinfix(operator) @@infixops << operator end def `(expression) @@infixops.each{|op|break if expression.match(/^(.*?) (#{op}) (.*)$/)} raise "unknown infix operator in expression: #{expression}" if $2 == nil eval($1).method($2.to_sym).call(eval($3)) end end addinfix("concat") p `[1,2,3] concat [4,5,6]` # => [1, 2, 3, 4, 5, 6] # HEREDOC FUN!!!!!!!1111 foo(< <% rows.each do |row| %>
    <%= item.title %> <%= item.description %> <% end %>

    Pages

    <% if @homepage -%> <%= render_node @homepage -%> <% else -%> <% end -%>
    Page Status Modify
    No Pages

    <% unless @homepage -%> <%= link_to image_tag('new-homepage', :alt => 'New Homepage'), homepage_new_url %> <% end -%> <%= image_submit_tag 'clear-page-cache' %>

    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.rsl000066400000000000000000000060151250413007300253730ustar00rootroot00000000000000scheme COMPILER = class type Prog == mk_Prog(stmt : Stmt), Stmt == mk_Asgn(ide : Identifier, expr : Expr) | mk_If(cond : Expr, s1 : Stmt, s2 : Stmt) | mk_Seq(head : Stmt, last : Stmt), Expr == mk_Const(const : Int) | mk_Plus(fst : Expr, snd : Expr) | mk_Id(ide : Identifier), Identifier = Text type /* storage for program variables */ `Sigma = Identifier -m-> Int value m : Prog -> `Sigma -> `Sigma m(p)(`sigma) is m(stmt(p))(`sigma), m : Stmt -> `Sigma -> `Sigma m(s)(`sigma) is case s of mk_Asgn(i, e) -> `sigma !! [i +> m(e)(`sigma)], mk_Seq(s1, s2) -> m(s2)(m(s1)(`sigma)), mk_If(c, s1, s2) -> if m(c)(`sigma) ~= 0 then m(s1)(`sigma) else m(s2)(`sigma) end end, m : Expr -> `Sigma -> Int m(e)(`sigma) is case e of mk_Const(n) -> n, mk_Plus(e1, e2) -> m(e1)(`sigma) + m(e2)(`sigma), mk_Id(id) -> if id isin dom `sigma then `sigma(id) else 0 end end type MProg = Inst-list, Inst == mk_Push(ide1 : Identifier) | mk_Pop(Unit) | mk_Add(Unit) | mk_Cnst(val : Int) | mk_Store(ide2 : Identifier) | mk_Jumpfalse(off1 : Int) | mk_Jump(off2 : Int) /* An interpreter for SMALL instructions */ type Stack = Int-list value I : MProg >< Int >< Stack -> (`Sigma ->`Sigma) I(mp, pc, s)(`sigma) is if pc <= 0 \/ pc > len mp then `sigma else case mp(pc) of mk_Push(x) -> if x isin dom `sigma then I(mp, pc + 1, <.`sigma(x).> ^ s)(`sigma) else I(mp, pc + 1, <.0.> ^ s)(`sigma) end, mk_Pop(()) -> if len s = 0 then `sigma else I(mp, pc + 1, tl s)(`sigma) end, mk_Cnst(n) -> I(mp, pc + 1, <.n.> ^ s)(`sigma), mk_Add(()) -> if len s < 2 then `sigma else I(mp, pc + 1,<.s(1) + s(2).> ^ tl tl s)(`sigma) end, mk_Store(x) -> if len s = 0 then `sigma else I(mp, pc + 1, s)(`sigma !! [x +> s(1)]) end, mk_Jumpfalse(n) -> if len s = 0 then `sigma elsif hd s ~= 0 then I(mp, pc + 1, s)(`sigma) else I(mp, pc + n, s)(`sigma) end, mk_Jump(n) -> I(mp, pc + n, s)(`sigma) end end value comp_Prog : Prog -> MProg comp_Prog(p) is comp_Stmt(stmt(p)), comp_Stmt : Stmt -> MProg comp_Stmt(s) is case s of mk_Asgn(id, e) -> comp_Expr(e) ^ <. mk_Store(id), mk_Pop() .>, mk_Seq(s1, s2) -> comp_Stmt(s1) ^ comp_Stmt(s2), mk_If(e, s1, s2) -> let ce = comp_Expr(e), cs1 = comp_Stmt(s1), cs2 = comp_Stmt(s2) in ce ^ <. mk_Jumpfalse(len cs1 + 3) .> ^ <. mk_Pop() .> ^ cs1 ^ <. mk_Jump(len cs2 + 2) .> ^ <. mk_Pop() .> ^ cs2 end end, comp_Expr : Expr -> MProg comp_Expr(e) is case e of mk_Const(n) -> <. mk_Cnst(n) .>, mk_Plus(e1, e2) -> comp_Expr(e1) ^ comp_Expr(e2) ^ <. mk_Add() .>, mk_Id(id) -> <. mk_Push(id) .> end end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.scaml000066400000000000000000000002461250413007300256720ustar00rootroot00000000000000-@ import val city:String = "Tampa" - val name:String = "Hiram" %html %body %p Hello #{name} from #{city} %ul - for ( i <- 1 to 10 ) %li Item #{i}pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.ssp000066400000000000000000000003171250413007300253770ustar00rootroot00000000000000<%@ val someName: String = "someDefaultValue" %> <% import com.acme.MySnippets._ %>

    Hello ${someName}%

      <%= for (person <- people) { %>
    • ${person.name}
    • <% } %>
    pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.swift000066400000000000000000000037631250413007300257360ustar00rootroot00000000000000// // test.swift // from https://github.com/fullstackio/FlappySwift // // Created by Nate Murray on 6/2/14. // Copyright (c) 2014 Fullstack.io. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil) var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene archiver.finishDecoding() return scene } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw()) } else { return Int(UIInterfaceOrientationMask.All.toRaw()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.tcsh000066400000000000000000001031471250413007300255400ustar00rootroot00000000000000# # $Id: complete.tcsh,v 1.2 1998/05/11 10:40:54 luisgh Exp $ # example file using the new completion code # # Debian GNU/Linux # file: /usr/share/doc/examples/tcsh/complete.tcsh # # This file may be read from user's .cshrc file by decompressing it into # the home directory as ~/.complete and then adding the line # "source ${HOME}/.complete" and maybe defining some of # the shell variables described below. # # Debian enhancements by Vadim Vygonets : # # Added two Debian-specific completions: dpkg and dpkg-deb (who wrote # them?). To turn it off, define no_debian_complete before loading # this file. # # Added some new completions. To turn them off, define # no_new_complete before loading this file. # # Changed completions of several commands. The ones are evaluated if # the following shell variables are defined: # # traditional_cp_mv_complete # for traditional completion of cp and mv commands # traditional_zcat_complete # for traditional completion of zcat command # traditional_nm_complete # for traditional completion of nm command # traditilnal_tex_complete # for traditional completion of tex command # traditional_find_complete # for traditional completion of find command # traditional_configure_complete # for traditional completion of ./configure command # foolproof_rm_complete or traditional_rm_complete # for traditional completion of rm command # traditional_complete # all of the above if ($?traditional_complete) then set traditional_cp_mv_complete set traditional_zcat_complete set traditional_nm_complete set traditilnal_tex_complete set traditional_find_complete set traditional_configure_complete set foolproof_rm_complete endif if ($?traditional_rm_complete) then set foolproof_rm_complete endif onintr - if (! $?prompt) goto end if ($?tcsh) then if ($tcsh != 1) then set rev=$tcsh:r set rel=$rev:e set pat=$tcsh:e set rev=$rev:r endif if ($rev > 5 && $rel > 1) then set complete=1 endif unset rev rel pat endif if ($?complete) then set noglob set hosts foreach f ($HOME/.hosts /usr/local/etc/csh.hosts $HOME/.rhosts /etc/hosts.equiv) if ( -r $f ) then set hosts=($hosts `cut -d " " -f 1 $f | grep -v +`) endif end if ( -r $HOME/.netrc ) then set f=`awk '/machine/ { print $2 }' < $HOME/.netrc` >& /dev/null set hosts=($hosts $f) endif unset f if ( ! $?hosts ) then set hosts=(hyperion.ee.cornell.edu phaeton.ee.cornell.edu \ guillemin.ee.cornell.edu vangogh.cs.berkeley.edu \ ftp.uu.net prep.ai.mit.edu export.lcs.mit.edu \ labrea.stanford.edu sumex-aim.stanford.edu \ tut.cis.ohio-state.edu) endif complete ywho n/*/\$hosts/ # argument from list in $hosts complete rsh p/1/\$hosts/ c/-/"(l n)"/ n/-l/u/ N/-l/c/ n/-/c/ p/2/c/ p/*/f/ complete xrsh p/1/\$hosts/ c/-/"(l 8 e)"/ n/-l/u/ N/-l/c/ n/-/c/ p/2/c/ p/*/f/ complete rlogin p/1/\$hosts/ c/-/"(l 8 e)"/ n/-l/u/ complete telnet p/1/\$hosts/ p/2/x:''/ n/*/n/ complete cd p/1/d/ # Directories only complete chdir p/1/d/ complete pushd p/1/d/ complete popd p/1/d/ complete pu p/1/d/ complete po p/1/d/ complete complete p/1/X/ # Completions only complete uncomplete n/*/X/ complete exec p/1/c/ # Commands only complete trace p/1/c/ complete strace p/1/c/ complete which n/*/c/ complete where n/*/c/ complete skill p/1/c/ complete dde p/1/c/ complete adb c/-I/d/ n/-/c/ N/-/"(core)"/ p/1/c/ p/2/"(core)"/ complete sdb p/1/c/ complete dbx c/-I/d/ n/-/c/ N/-/"(core)"/ p/1/c/ p/2/"(core)"/ complete xdb p/1/c/ complete gdb n/-d/d/ n/*/c/ complete ups p/1/c/ complete set 'c/*=/f/' 'p/1/s/=' 'n/=/f/' complete unset n/*/s/ complete alias p/1/a/ # only aliases are valid complete unalias n/*/a/ complete xdvi n/*/f:*.dvi/ # Only files that match *.dvi complete dvips n/*/f:*.dvi/ if ($?traditilnal_tex_complete) then complete tex n/*/f:*.tex/ # Only files that match *.tex else complete tex n/*/f:*.{tex,texi}/ # Files that match *.tex and *.texi endif complete latex n/*/f:*.{tex,ltx}/ complete su c/--/"(login fast preserve-environment command shell \ help version)"/ c/-/"(f l m p c s -)"/ \ n/{-c,--command}/c/ \ n@{-s,--shell}@'`cat /etc/shells`'@ n/*/u/ complete cc c/-[IL]/d/ \ c@-l@'`\ls -1 /usr/lib/lib*.a | sed s%^.\*/lib%%\;s%\\.a\$%%`'@ \ c/-/"(o l c g L I D U)"/ n/*/f:*.[coasi]/ complete acc c/-[IL]/d/ \ c@-l@'`\ls -1 /usr/lang/SC1.0/lib*.a | sed s%^.\*/lib%%\;s%\\.a\$%%`'@ \ c/-/"(o l c g L I D U)"/ n/*/f:*.[coasi]/ complete gcc c/-[IL]/d/ \ c/-f/"(caller-saves cse-follow-jumps delayed-branch \ elide-constructors expensive-optimizations \ float-store force-addr force-mem inline \ inline-functions keep-inline-functions \ memoize-lookups no-default-inline \ no-defer-pop no-function-cse omit-frame-pointer \ rerun-cse-after-loop schedule-insns \ schedule-insns2 strength-reduce \ thread-jumps unroll-all-loops \ unroll-loops syntax-only all-virtual \ cond-mismatch dollars-in-identifiers \ enum-int-equiv no-asm no-builtin \ no-strict-prototype signed-bitfields \ signed-char this-is-variable unsigned-bitfields \ unsigned-char writable-strings call-saved-reg \ call-used-reg fixed-reg no-common \ no-gnu-binutils nonnull-objects \ pcc-struct-return pic PIC shared-data \ short-enums short-double volatile)"/ \ c/-W/"(all aggregate-return cast-align cast-qual \ comment conversion enum-clash error format \ id-clash-len implicit missing-prototypes \ no-parentheses pointer-arith return-type shadow \ strict-prototypes switch uninitialized unused \ write-strings)"/ \ c/-m/"(68000 68020 68881 bitfield fpa nobitfield rtd \ short c68000 c68020 soft-float g gnu unix fpu \ no-epilogue)"/ \ c/-d/"(D M N)"/ \ c/-/"(f W vspec v vpath ansi traditional \ traditional-cpp trigraphs pedantic x o l c g L \ I D U O O2 C E H B b V M MD MM i dynamic \ nodtdlib static nostdinc undef)"/ \ c/-l/f:*.a/ \ n/*/f:*.{c,C,cc,o,a,s,i}/ complete g++ n/*/f:*.{C,cc,o,s,i}/ complete CC n/*/f:*.{C,cc,o,s,i}/ if ($?foolproof_rm_complete) then complete rm c/--/"(directory force interactive verbose \ recursive help version)"/ c/-/"(d f i v r R -)"/ \ n/*/f:^*.{c,cc,C,h,in}/ # Protect precious files else complete rm c/--/"(directory force interactive verbose \ recursive help version)"/ c/-/"(d f i v r R -)"/ endif complete vi n/*/f:^*.[oa]/ complete bindkey N/-a/b/ N/-c/c/ n/-[ascr]/'x:'/ \ n/-[svedlr]/n/ c/-[vedl]/n/ c/-/"(a s k c v e d l r)"/\ n/-k/"(left right up down)"/ p/2-/b/ \ p/1/'x:'/ if ($?traditional_find_complete) then complete find n/-fstype/"(nfs 4.2)"/ n/-name/f/ \ n/-type/"(c b d f p l s)"/ n/-user/u/ n/-group/g/ \ n/-exec/c/ n/-ok/c/ n/-cpio/f/ n/-ncpio/f/ n/-newer/f/ \ c/-/"(fstype name perm prune type user nouser \ group nogroup size inum atime mtime ctime exec \ ok print ls cpio ncpio newer xdev depth \ daystart follow maxdepth mindepth noleaf version \ anewer cnewer amin cmin mmin true false uid gid \ ilname iname ipath iregex links lname empty path \ regex used xtype fprint fprint0 fprintf \ print0 printf not a and o or)"/ \ n/*/d/ else complete find n/-fstype/"(ufs nfs tmp mfs minix ext2 msdos umsdos vfat proc iso9660 4.2 4.3 local)"/ \ n/-name/f/ \ n/-type/"(c b d f p l s)"/ n/-user/u/ n/-group/g/ \ n/-exec/c/ n/-ok/c/ n/-cpio/f/ n/-ncpio/f/ n/-newer/f/ \ c/-/"(fstype name perm prune type user nouser \ group nogroup size inum atime mtime ctime exec \ ok print ls cpio ncpio newer xdev depth \ daystart follow maxdepth mindepth noleaf version \ anewer cnewer amin cmin mmin true false uid gid \ ilname iname ipath iregex links lname empty path \ regex used xtype fprint fprint0 fprintf \ print0 printf not a and o or)"/ \ n/*/d/ endif complete -%* c/%/j/ # fill in the jobs builtin complete {fg,bg,stop} c/%/j/ p/1/"(%)"// complete limit c/-/"(h)"/ n/*/l/ complete unlimit c/-/"(h)"/ n/*/l/ complete -co* p/0/"(compress)"/ # make compress completion # not ambiguous if ($?traditional_zcat_complete) then complete zcat n/*/f:*.Z/ else complete zcat c/--/"(force help license quiet version)"/ \ c/-/"(f h L q V -)"/ n/*/f:*.{gz,Z,z,zip}/ endif if ($?traditional_nm_complete) then complete nm n/*/f:^*.{h,C,c,cc}/ else complete nm 'c/--radix=/x:/' \ 'c/--target=/x:/' \ 'c/--format=/(bsd sysv posix)/n/' \ 'c/--/(debugsyms extern-only demangle dynamic print-armap \ print-file-name numeric-sort no-sort reverse-sort \ size-sort undefined-only portability target= radix= \ format= defined-only\ line-numbers no-demangle version \ help)//' \ 'n/*/f:^*.{h,c,cc,s,S}/' endif complete finger c/*@/\$hosts/ n/*/u/@ complete ping p/1/\$hosts/ complete traceroute p/1/\$hosts/ complete {talk,ntalk,phone} p/1/'`users | tr " " "\012" | uniq`'/ \ n/*/\`who\ \|\ grep\ \$:1\ \|\ awk\ \'\{\ print\ \$2\ \}\'\`/ complete ftp c/-/"(d i g n v)"/ n/-/\$hosts/ p/1/\$hosts/ n/*/n/ # this one is simple... #complete rcp c/*:/f/ C@[./\$~]*@f@ n/*/\$hosts/: # From Michael Schroeder # This one will rsh to the file to fetch the list of files! complete rcp 'c%*@*:%`set q=$:-0;set q="$q:s/@/ /";set q="$q:s/:/ /";set q=($q " ");rsh $q[2] -l $q[1] ls -dp $q[3]\*`%' 'c%*:%`set q=$:-0;set q="$q:s/:/ /";set q=($q " ");rsh $q[1] ls -dp $q[2]\*`%' 'c%*@%$hosts%:' 'C@[./$~]*@f@' 'n/*/$hosts/:' complete dd c/--/"(help version)"/ c/[io]f=/f/ \ c/conv=*,/"(ascii ebcdic ibm block unblock \ lcase ucase swab noerror sync)"/,\ c/conv=/"(ascii ebcdic ibm block unblock \ lcase ucase swab noerror sync)"/,\ c/*=/x:''/ \ n/*/"(if of conv ibs obs bs cbs files skip file seek count)"/= complete nslookup p/1/x:''/ p/2/\$hosts/ complete ar c/[dmpqrtx]/"(c l o u v a b i)"/ p/1/"(d m p q r t x)"// \ p/2/f:*.a/ p/*/f:*.o/ complete {refile,sprev,snext,scan,pick,rmm,inc,folder,show} \ c@+@F:$HOME/Mail/@ # these and interrupt handling from Jaap Vermeulen complete {rexec,rxexec,rxterm,rmterm} \ 'p/1/$hosts/' 'c/-/(l L E)/' 'n/-l/u/' 'n/-L/f/' \ 'n/-E/e/' 'n/*/c/' complete kill 'c/-/S/' 'c/%/j/' \ 'n/*/`ps -u $LOGNAME | awk '"'"'{print $1}'"'"'`/' # these from Marc Horowitz complete attach 'n/-mountpoint/d/' 'n/-m/d/' 'n/-type/(afs nfs rvd ufs)/' \ 'n/-t/(afs nfs rvd ufs)/' 'n/-user/u/' 'n/-U/u/' \ 'c/-/(verbose quiet force printpath lookup debug map \ nomap remap zephyr nozephyr readonly write \ mountpoint noexplicit explicit type mountoptions \ nosetuid setuid override skipfsck lock user host)/' \ 'n/-e/f/' 'n/*/()/' complete hesinfo 'p/1/u/' \ 'p/2/(passwd group uid grplist pcap pobox cluster \ filsys sloc service)/' # these from E. Jay Berkenbilt if ($?traditional_configure_complete) then complete ./configure 'c/--*=/f/' 'c/--{cache-file,prefix,srcdir}/(=)//' \ 'c/--/(cache-file verbose prefix srcdir)//' else complete ./configure \ 'c@--{prefix,exec-prefix,bindir,sbindir,libexecdir,datadir,sysconfdir,sharedstatedir,localstatedir,infodir,mandir,srcdir,x-includes,x-libraries}=*@x:'@ \ 'c/--cachefile=*/x:/' \ 'c/--{enable,disable,with}-*/x://' \ 'c/--*=/x:/' \ 'c/--/(prefix= exec-prefix= bindir= sbindir= \ libexecdir= datadir= sysconfdir= \ sharedstatedir= localstatedir= infodir= \ mandir= srcdir= x-includes= x-libraries= \ enable- disable- with- )//' \ 'c/--(help no-create quiet silent version \ verbose)/' endif complete gs 'c/-sDEVICE=/(x11 cdjmono cdj550 epson eps9high epsonc \ dfaxhigh dfaxlow laserjet ljet4 sparc pbm \ pbmraw pgm pgmraw ppm ppmraw bit)/' \ 'c/-sOutputFile=/f/' 'c/-s/(DEVICE OutputFile)/=' \ 'c/-d/(NODISPLAY NOPLATFONTS NOPAUSE)/' 'n/*/f/' complete perl 'n/-S/c/' complete printenv 'n/*/e/' complete sccs p/1/"(admin cdc check clean comb deledit delget \ delta diffs edit enter fix get help info \ print prs prt rmdel sccsdiff tell unedit \ unget val what)"/ complete setenv 'p/1/e/' 'c/*:/f/' # these and method of setting hosts from Kimmo Suominen if ( -f $HOME/.mh_profile && -x "`which folders`" ) then if ( ! $?FOLDERS ) setenv FOLDERS "`folders -fast -recurse`" if ( ! $?MHA ) setenv MHA "`ali | sed -e '/^ /d' -e 's/:.*//'`" set folders = ( $FOLDERS ) set mha = ( $MHA ) complete ali \ 'c/-/(alias nolist list nonormalize normalize nouser user help)/' \ 'n,-alias,f,' complete anno \ 'c/-/(component noinplace inplace nodate date text help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete burst \ 'c/-/(noinplace inplace noquiet quiet noverbose verbose help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete comp \ 'c/-/(draftfolder draftmessage nodraftfolder editor noedit file form nouse use whatnowproc nowhatnowproc help)/' \ 'c,+,$folders,' \ 'n,-whatnowproc,c,' \ 'n,-file,f,'\ 'n,-form,f,'\ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete dist \ 'c/-/(noannotate annotate draftfolder draftmessage nodraftfolder editor noedit form noinplace inplace whatnowproc nowhatnowproc help)/' \ 'c,+,$folders,' \ 'n,-whatnowproc,c,' \ 'n,-form,f,'\ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete folder \ 'c/-/(all nofast fast noheader header nopack pack noverbose verbose norecurse recurse nototal total noprint print nolist list push pop help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete folders \ 'c/-/(all nofast fast noheader header nopack pack noverbose verbose norecurse recurse nototal total noprint print nolist list push pop help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete forw \ 'c/-/(noannotate annotate draftfolder draftmessage nodraftfolder editor noedit filter form noformat format noinplace inplace digest issue volume whatnowproc nowhatnowproc help)/' \ 'c,+,$folders,' \ 'n,-whatnowproc,c,' \ 'n,-filter,f,'\ 'n,-form,f,'\ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete inc \ 'c/-/(audit file noaudit nochangecur changecur file form format nosilent silent notruncate truncate width help)/' \ 'c,+,$folders,' \ 'n,-audit,f,'\ 'n,-form,f,' complete mark \ 'c/-/(add delete list sequence nopublic public nozero zero help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete mhmail \ 'c/-/(body cc from subject help)/' \ 'n,-cc,$mha,' \ 'n,-from,$mha,' \ 'n/*/$mha/' complete mhpath \ 'c/-/(help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete msgchk \ 'c/-/(nodate date nonotify notify help)/' complete msh \ 'c/-/(prompt noscan scan notopcur topcur help)/' complete next \ 'c/-/(draft form moreproc nomoreproc length width showproc noshowproc header noheader help)/' \ 'c,+,$folders,' \ 'n,-moreproc,c,' \ 'n,-showproc,c,' \ 'n,-form,f,' complete packf \ 'c/-/(file help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete pick \ 'c/-/(and or not lbrace rbrace cc date from search subject to othercomponent after before datefield sequence nopublic public nozero zero nolist list help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete prev \ 'c/-/(draft form moreproc nomoreproc length width showproc noshowproc header noheader help)/' \ 'c,+,$folders,' \ 'n,-moreproc,c,' \ 'n,-showproc,c,' \ 'n,-form,f,' complete prompter \ 'c/-/(erase kill noprepend prepend norapid rapid nodoteof doteof help)/' complete refile \ 'c/-/(draft nolink link nopreserve preserve src file help)/' \ 'c,+,$folders,' \ 'n,-file,f,'\ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete rmf \ 'c/-/(nointeractive interactive help)/' \ 'c,+,$folders,' complete rmm \ 'c/-/(help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete scan \ 'c/-/(noclear clear form format noheader header width noreverse reverse file help)/' \ 'c,+,$folders,' \ 'n,-form,f,'\ 'n,-file,f,'\ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete send \ 'c/-/(alias draft draftfolder draftmessage nodraftfolder filter nofilter noformat format noforward forward nomsgid msgid nopush push noverbose verbose nowatch watch width help)/' \ 'n,-alias,f,'\ 'n,-filter,f,' complete show \ 'c/-/(draft form moreproc nomoreproc length width showproc noshowproc header noheader help)/' \ 'c,+,$folders,' \ 'n,-moreproc,c,' \ 'n,-showproc,c,' \ 'n,-form,f,'\ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete sortm \ 'c/-/(datefield textfield notextfield limit nolimit noverbose verbose help)/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete vmh \ 'c/-/(prompt vmhproc novmhproc help)/' \ 'n,-vmhproc,c,' complete whatnow \ 'c/-/(draftfolder draftmessage nodraftfolder editor noedit prompt help)/' complete whom \ 'c/-/(alias nocheck check draft draftfolder draftmessage nodraftfolder help)/' \ 'n,-alias,f,' complete plum \ 'c/-/()/' \ 'c,+,$folders,' \ 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' complete mail \ 'c/-/()/' \ 'n/*/$mha/' endif # these from Tom Warzeka # you may need to set the following variables for your host set _elispdir = /usr/lib/emacs/19.34/lisp # GNU Emacs lisp directory set _maildir = /var/spool/mail # Post Office: /var/spool/mail or /usr/mail set _ypdir = /var/yp # directory where NIS (YP) maps are kept set _domain = "`dnsdomainname`" # this one works but is slow and doesn't descend into subdirectories # complete cd C@[./\$~]*@d@ \ # p@1@'`\ls -1F . $cdpath | grep /\$ | sort -u`'@ n@*@n@ if ( -r /etc/shells ) then complete setenv p@1@e@ n@DISPLAY@\$hosts@: n@SHELL@'`cat /etc/shells`'@ else complete setenv p@1@e@ n@DISPLAY@\$hosts@: endif complete unsetenv n/*/e/ if (-r $HOME/.mailrc) then complete mail c/-/"(e i f n s u v)"/ c/*@/\$hosts/ \ c@+@F:$HOME/Mail@ C@[./\$~]@f@ n/-s/x:''/ \ n@-u@T:$_maildir@ n/-f/f/ \ n@*@'`sed -n s/alias//p $HOME/.mailrc | tr -s " " " " | cut -f 2`'@ else complete mail c/-/"(e i f n s u v)"/ c/*@/\$hosts/ \ c@+@F:$HOME/Mail@ C@[./\$~]@f@ n/-s/x:''/ \ n@-u@T:$_maildir@ n/-f/f/ n/*/u/ endif complete man n@1@'`\ls -1 /usr/man/man1 | sed s%\\.1.\*\$%%`'@ \ n@2@'`\ls -1 /usr/man/man2 | sed s%\\.2.\*\$%%`'@ \ n@3@'`\ls -1 /usr/man/man3 | sed s%\\.3.\*\$%%`'@ \ n@4@'`\ls -1 /usr/man/man4 | sed s%\\.4.\*\$%%`'@ \ n@5@'`\ls -1 /usr/man/man5 | sed s%\\.5.\*\$%%`'@ \ n@6@'`\ls -1 /usr/man/man6 | sed s%\\.6.\*\$%%`'@ \ n@7@'`\ls -1 /usr/man/man7 | sed s%\\.7.\*\$%%`'@ \ n@8@'`\ls -1 /usr/man/man8 | sed s%\\.8.\*\$%%`'@ \ n@9@'`[ -r /usr/man/man9 ] && \ls -1 /usr/man/man9 | sed s%\\.9.\*\$%%`'@ \ n@0@'`[ -r /usr/man/man0 ] && \ls -1 /usr/man/man0 | sed s%\\.0.\*\$%%`'@ \ n@new@'`[ -r /usr/man/mann ] && \ls -1 /usr/man/mann | sed s%\\.n.\*\$%%`'@ \ n@old@'`[ -r /usr/man/mano ] && \ls -1 /usr/man/mano | sed s%\\.o.\*\$%%`'@ \ n@local@'`[ -r /usr/man/manl ] && \ls -1 /usr/man/manl | sed s%\\.l.\*\$%%`'@ \ n@public@'`[ -r /usr/man/manp ]&& \ls -1 /usr/man/manp | sed s%\\.p.\*\$%%`'@ \ c/-/"(- f k P s t)"/ n/-f/c/ n/-k/x:''/ n/-P/d/ \ N@-P@'`\ls -1 $:-1/man? | sed s%\\..\*\$%%`'@ n/*/c/ complete ps c/-t/x:''/ c/-/"(a c C e g k l S t u v w x)"/ \ n/-k/x:''/ N/-k/x:''/ n/*/x:''/ complete compress c/-/"(c f v b)"/ n/-b/x:''/ n/*/f:^*.Z/ complete uncompress c/-/"(c f v)"/ n/*/f:*.Z/ complete xhost c/[+-]/\$hosts/ n/*/\$hosts/ # these conform to the latest GNU versions available at press time ... complete emacs c/-/"(batch d f funcall i insert kill l load \ no-init-file nw q t u user)"/ c/+/x:''/ \ n/-d/x:''/ n/-f/x:''/ n/-i/f/ \ n@-l@F:$_elispdir@ n/-t/x:''/ \ n/-u/u/ n/*/f:^*[\#~]/ complete gzcat c/--/"(force help license quiet version)"/ \ c/-/"(f h L q V -)"/ n/*/f:*.{gz,Z,z,zip}/ complete gzip c/--/"(stdout to-stdout decompress uncompress \ force help list license no-name quiet recurse \ suffix test verbose version fast best)"/ \ c/-/"(c d f h l L n q r S t v V 1 2 3 4 5 6 7 8 9 -)"/\ n/{-S,--suffix}/x:''/ \ n/{-d,--{de,un}compress}/f:*.{gz,Z,z,zip,taz,tgz}/ \ N/{-d,--{de,un}compress}/f:*.{gz,Z,z,zip,taz,tgz}/ \ n/*/f:^*.{gz,Z,z,zip,taz,tgz}/ complete {gunzip,ungzip} c/--/"(stdout to-stdout force help list license \ no-name quiet recurse suffix test verbose version)"/ \ c/-/"(c f h l L n q r S t v V -)"/ \ n/{-S,--suffix}/x:''/ \ n/*/f:*.{gz,Z,z,zip,taz,tgz}/ complete zgrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ c/-/"(A b B c C e f h i l n s v V w x)"/ \ p/1/x:''/ \ n/-*e/x:''/ n/-*f/f/ n/*/f/ complete zegrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ c/-/"(A b B c C e f h i l n s v V w x)"/ \ p/1/x:''/ \ n/-*e/x:''/ n/-*f/f/ n/*/f/ complete zfgrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ c/-/"(A b B c C e f h i l n s v V w x)"/ \ p/1/x:''/ \ n/-*e/x:''/ n/-*f/f/ n/*/f/ complete znew c/-/"(f t v 9 P K)"/ n/*/f:*.Z/ complete zmore n/*/f:*.{gz,Z,z,zip}/ complete zfile n/*/f:*.{gz,Z,z,zip,taz,tgz}/ complete ztouch n/*/f:*.{gz,Z,z,zip,taz,tgz}/ complete zforce n/*/f:^*.{gz,tgz}/ complete grep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ c/-/"(A b B c C e f h i l n s v V w x)"/ \ p/1/x:''/ \ n/-*e/x:''/ n/-*f/f/ n/*/f/ complete egrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ c/-/"(A b B c C e f h i l n s v V w x)"/ \ p/1/x:''/ \ n/-*e/x:''/ n/-*f/f/ n/*/f/ complete fgrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ c/-/"(A b B c C e f h i l n s v V w x)"/ \ p/1/x:''/ \ n/-*e/x:''/ n/-*f/f/ n/*/f/ complete users c/--/"(help version)"/ p/1/x:''/ complete who c/--/"(heading mesg idle count help message version \ writable)"/ c/-/"(H T w i u m q s -)"/ \ p/1/x:''/ n/am/"(i)"/ n/are/"(you)"/ complete chown c/--/"(changes silent quiet verbose recursive help \ version)"/ c/-/"(c f v R -)"/ C@[./\$~]@f@ c/*[.:]/g/ \ n/-/u/. p/1/u/. n/*/f/ complete chgrp c/--/"(changes silent quiet verbose recursive help \ version)"/ c/-/"(c f v R -)"/ n/-/g/ p/1/g/ n/*/f/ complete cat c/--/"(number-nonblank number squeeze-blank show-all \ show-nonprinting show-ends show-tabs help version)"/ \ c/-/"(b e n s t u v A E T -)"/ n/*/f/ if ($?traditional_cp_mv_complete) then complete mv c/--/"(backup force interactive update verbose suffix \ version-control help version)"/ \ c/-/"(b f i u v S V -)"/ \ n/{-S,--suffix}/x:''/ \ n/{-V,--version-control}/"(t numbered nil existing \ never simple)"/ n/-/f/ N/-/d/ p/1/f/ p/2/d/ n/*/f/ complete cp c/--/"(archive backup no-dereference force interactive \ link preserve symbolic-link update verbose parents \ one-file-system recursive suffix version-control help \ version)"/ c/-/"(a b d f i l p r s u v x P R S V -)"/ \ n/-*r/d/ n/{-S,--suffix}/x:''/ \ n/{-V,--version-control}/"(t numbered nil existing \ never simple)"/ n/-/f/ N/-/d/ p/1/f/ p/2/d/ n/*/f/ else complete mv c/--/"(backup force interactive update verbose suffix \ version-control help version)"/ \ c/-/"(b f i u v S V -)"/ \ n/{-S,--suffix}/x:''/ \ n/{-V,--version-control}/"(t numbered nil existing \ never simple)"/ n/-/f/ N/-/d/ n/*/f/ complete cp c/--/"(archive backup no-dereference force interactive \ link preserve symbolic-link update verbose parents \ one-file-system recursive suffix version-control help \ version)"/ c/-/"(a b d f i l p r s u v x P R S V -)"/ \ n/-*r/d/ n/{-S,--suffix}/x:''/ \ n/{-V,--version-control}/"(t numbered nil existing \ never simple)"/ n/-/f/ N/-/d/ n/*/f/ endif complete ln c/--/"(backup directory force interactive symbolic \ verbose suffix version-control help version)"/ \ c/-/"(b d F f i s v S V -)"/ \ n/{-S,--suffix}/x:''/ \ n/{-V,--version-control}/"(t numbered nil existing \ never simple)"/ n/-/f/ N/-/x:''/ \ p/1/f/ p/2/x:''/ complete touch c/--/"(date file help time version)"/ \ c/-/"(a c d f m r t -)"/ \ n/{-d,--date}/x:''/ \ c/--time/"(access atime mtime modify use)"/ \ n/{-r,--file}/f/ n/-t/x:''/ n/*/f/ complete mkdir c/--/"(parents help version mode)"/ c/-/"(p m -)"/ \ n/{-m,--mode}/x:''/ n/*/d/ complete rmdir c/--/"(parents help version)"/ c/-/"(p -)"/ n/*/d/ complete tar c/-[Acru]*/"(b B C f F g G h i l L M N o P \ R S T v V w W X z Z)"/ \ c/-[dtx]*/"( B C f F g G i k K m M O p P \ R s S T v w x X z Z)"/ \ p/1/"(A c d r t u x -A -c -d -r -t -u -x \ --catenate --concatenate --create --diff --compare \ --delete --append --list --update --extract --get)"/ \ c/--/"(catenate concatenate create diff compare \ delete append list update extract get atime-preserve \ block-size read-full-blocks directory checkpoint file \ force-local info-script new-volume-script incremental \ listed-incremental dereference ignore-zeros \ ignore-failed-read keep-old-files starting-file \ one-file-system tape-length modification-time \ multi-volume after-date newer old-archive portability \ to-stdout same-permissions preserve-permissions \ absolute-paths preserve record-number remove-files \ same-order preserve-order same-owner sparse \ files-from null totals verbose label version \ interactive confirmation verify exclude exclude-from \ compress uncompress gzip ungzip use-compress-program \ block-compress)"/ \ c/-/"(b B C f F g G h i k K l L m M N o O p P R s S \ T v V w W X z Z 0 1 2 3 4 5 6 7 -)"/ \ n/-c*f/x:''/ \ n/{-[Adrtux]*f,--file}/f:*.tar/ \ N/{-x*f,--file}/'`tar -tf $:-1`'/ \ n/--use-compress-program/c/ \ n/{-b,--block-size}/x:''/ \ n/{-V,--label}/x:''/ \ n/{-N,--{after-date,newer}}/x:''/ \ n/{-L,--tape-length}/x:''/ \ n/{-C,--directory}/d/ \ N/{-C,--directory}/'`\ls $:-1`'/ \ n/-[0-7]/"(l m h)"/ # BSD 4.3 filesystems complete mount c/-/"(a h v t r)"/ n/-h/\$hosts/ n/-t/"(4.2 nfs)"/ \ n@*@'`cut -d " " -f 2 /etc/fstab`'@ complete umount c/-/"(a h v t)"/ n/-h/\$hosts/ n/-t/"(4.2 nfs)"/ \ n/*/'`mount | cut -d " " -f 3`'/ # BSD 4.2 filesystems #complete mount c/-/"(a h v t r)"/ n/-h/\$hosts/ n/-t/"(ufs nfs)"/ \ # n@*@'`cut -d ":" -f 2 /etc/fstab`'@ #complete umount c/-/"(a h v t)"/ n/-h/\$hosts/ n/-t/"(ufs nfs)"/ \ # n/*/'`mount | cut -d " " -f 3`'/ # these deal with NIS (formerly YP); if it's not running you don't need 'em complete domainname p@1@D:$_ypdir@" " n@*@n@ complete ypcat c@-@"(d k t x)"@ n@-x@n@ n@-d@D:$_ypdir@" " \ N@-d@\`\\ls\ -1\ $_ypdir/\$:-1\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ \ n@*@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ complete ypmatch c@-@"(d k t x)"@ n@-x@n@ n@-d@D:$_ypdir@" " \ N@-d@x:''@ n@-@x:''@ p@1@x:''@ \ n@*@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ complete ypwhich c@-@"(d m t x V1 V2)"@ n@-x@n@ n@-d@D:$_ypdir@" " \ n@-m@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ \ N@-m@n@ n@*@\$hosts@ # there's no need to clutter the user's shell with these unset _elispdir _maildir _ypdir _domain complete make \ 'n/-f/f/' \ 'c/*=/f/' \ 'n@*@`cat -s GNUmakefile Makefile makefile |& sed -n -e "/No such file/d" -e "/^[^ #].*:/s/:.*//p"`@' if ( -f /etc/printcap ) then set printers=(`sed -n -e "/^[^ #].*:/s/:.*//p" /etc/printcap`) complete lpr 'c/-P/$printers/' complete lpq 'c/-P/$printers/' complete lprm 'c/-P/$printers/' complete lpquota 'p/1/(-Qprlogger)/' 'c/-P/$printers/' complete dvips 'c/-P/$printers/' 'n/-o/f:*.{ps,PS}/' 'n/*/f:*.dvi/' endif # New if (! $?no_new_complete) then uncomplete vi complete {vi,vim,gvim,nvi,elvis} n/*/f:^*.{o,a,so,sa,aux,dvi,log,fig,bbl,blg,bst,idx,ilg,ind,toc}/ complete {ispell,spell,spellword} 'n@-d@`ls /usr/lib/ispell/*.aff | sed -e "s/\.aff//" `@' 'n/*/f:^*.{o,a,so,sa,aux,dvi,log,fig,bbl,blg,bst,idx,ilg,ind,toc}/' complete mutt 'n/-[ai]/f/' 'n/-c/u/' c@=@F:$HOME/Mail/@ \ 'n/-s/x:\/' 'n/[^-]/u/' complete elm 'n/-[Ai]/f/' 'c@=@F:$HOME/Mail/@' 'n/-s/x:\/' complete ncftp 'n@*@`sed -e '1,2d' $HOME/.ncftp/bookmarks | cut -f 1,2 -d "," | tr "," "\012" | sort | uniq ` '@ complete bibtex 'n@*@`ls *.aux | sed -e "s/\.aux//"`'@ complete dvi2tty n/*/f:*.dvi/ # Only files that match *.dvi complete {xpdf,acroread} 'n/*/f:*.pdf/' complete {gv,ghostview} 'n/*/f:*.{ps,eps,epsi}/' complete enscript \ 'c/--/(columns= pages= header= no-header truncate-lines \ line-numbers setpagedevice= escapes font= \ header-font= fancy-header no-job-header \ highlight-bars indent= filter= borders page-prefeed \ no-page-prefeed lineprinter lines-per-page= mail \ media= copies= newline= output= missing-characters \ printer= quiet silent landscape portrait \ baselineskip= statusdict= title= tabsize= underlay= \ verbose version encoding pass-through download-font= \ filter-stdin= help highlight-bar-gray= list-media \ list-options non-printable-format= page-label-format= \ printer-options= ul-angle= ul-font= ul-gray= \ ul-position= ul-style= \ )/' endif # ! $?no_new_complete # Debian specific if (! $?no_debian_complete) then complete dpkg 'c/--{admindir,instdir,root}=/d/' \ 'c/--debug=/n/' \ 'c/--{admindir,debug,instdir,root}/(=)//' \ 'c/--/(admindir= debug= instdir= root= \ assert-support-predepends assert-working-epoch \ audit auto-deconfigure clear-avail \ compare-versions configure contents control \ extract force-bad-path field \ force-configure-any force-conflicts \ force-depends force-depends-version force-help \ force-hold force-non-root \ force-overwrite-diverted \ force-remove-essential force-remove-reinstreq \ forget-old-unavail fsys-tarfile get-selections \ help ignore-depends info install largemem \ license list listfiles merge-avail no-act \ pending predep-package print-architecture \ print-gnu-build-architecture \ print-installation-architecture print-avail \ purge record-avail recursive refuse-downgrade \ remove search set-selections selected-only \ skip-same-version smallmem status unpack \ update-avail version vextract \ )//' \ 'n/*/f:*.deb'/ complete dpkg-deb 'c/--{build}=/d/' \ 'c/--/"( build contents info field control extract \ vextract fsys-tarfile help version \ license )"' \ 'n/*/f:*.deb/' endif # ! $?no_debian_complete unset noglob unset complete unset traditional_complete unset traditional_cp_mv_complete unset traditional_zcat_complete unset traditional_nm_complete unset traditilnal_tex_complete unset traditional_find_complete unset traditional_configure_complete unset traditional_rm_complete unset foolproof_rm_complete unset no_new_complete unset no_debian_complete endif end: onintr pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.vb000066400000000000000000000377541250413007300252200ustar00rootroot00000000000000' Copyright (c) 2008 Silken Web - Free BSD License ' All rights reserved. ' ' Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ' * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer ' * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. ' * Neither the name of Silken Web nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. ' ' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ' THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS ' BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ' GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ' LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ' DAMAGE. Imports System.Net.Mail Imports SilkenWeb.Entities Imports System.Text.RegularExpressions Imports System.Reflection Imports SilkenWeb.Validation Imports System.Globalization Imports SilkenWeb.Reflection Namespace SilkenWeb ''' ''' Represents an Email and what you can do with it. ''' ''' ''' Keith Jackson ''' 11/04/2008 ''' ''' This class is intended to be inherrited for providing all manner of system generated emails, each represented by it's own class. ''' Public MustInherit Class EmailBase : Implements IValidatable, IDisposable #Region " Constants " Public Const LenientRegexPattern As String = "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Public Const StrictRegexPattern As String = "^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$" Public Const InvalidEmailAddressError As String = "The Email address provided was invalid" Public Const InvalidEmailAddressErrorWithAddress As String = "The Email address, {0}, provided was invalid" Public Const NullEmailAddressError As String = "The Email address was not provided" #End Region #Region " Fields " Private disposedValue As Boolean Private _message As MailMessage = New MailMessage() Private _mailClient As SmtpClient Private _useStrictValidation As Boolean #End Region #Region " Construction " ''' ''' Instantiates a new Email of the derived type. ''' ''' The email address of the sender of the message. ''' The email addresses of the recipients of the message. ''' The subject of the message. ''' The body of the message. Protected Sub New(ByVal sender As String, ByVal subject As String, ByVal body As String, ByVal ParamArray recipients As String()) _message.From = New MailAddress(sender) For i As Integer = 0 To recipients.Length - 1 _message.To.Add(recipients(i)) Next _message.Subject = subject _message.Body = body End Sub #End Region #Region " Properties " ''' ''' Gets the Attachments for the message. ''' Protected Overridable ReadOnly Property Attachments() As AttachmentCollection Get Return _message.Attachments End Get End Property ''' ''' The email addresses of the BCC recipients of the message. ''' Public Property BccRecipients() As String() Get Return _message.Bcc.ToAddressStringArray() End Get Set(ByVal value As String()) _message.Bcc.Clear() _message.Bcc.Add(value.ToDelimitedString()) End Set End Property ''' ''' The body of the message. ''' Protected Overridable Property Body() As String Get Return _message.Body End Get Set(ByVal value As String) _message.Body = value End Set End Property ''' ''' The email addresses of the CC recipients of the message. ''' Public Property CCRecipients() As String() Get Return _message.CC.ToAddressStringArray() End Get Set(ByVal value As String()) _message.CC.Clear() _message.CC.Add(value.ToDelimitedString()) End Set End Property ''' ''' Gets or Sets a flag to indicate if the body of the message is HTML. ''' Public Property IsBodyHtml() As Boolean Get Return _message.IsBodyHtml End Get Set(ByVal value As Boolean) _message.IsBodyHtml = value End Set End Property ''' ''' Gets the Mail message wrapped by the EmailBase class. ''' Protected ReadOnly Property Message() As MailMessage Get Return _message End Get End Property ''' ''' Gets or Sets the Priority of the message. ''' Public Property Priority() As MailPriority Get Return _message.Priority End Get Set(ByVal value As MailPriority) _message.Priority = value End Set End Property ''' ''' The email addresses of the recipients of the message. ''' Public Property Recipients() As String() Get Return _message.To.ToAddressStringArray() End Get Set(ByVal value As String()) _message.To.Clear() _message.To.Add(value.ToDelimitedString()) End Set End Property ''' ''' The reply email address of the sender of the message. ''' Public Property ReplyTo() As String Get If _message.ReplyTo Is Nothing Then Return String.Empty Else Return _message.ReplyTo.Address End If End Get Set(ByVal value As String) If _message.ReplyTo Is Nothing Then _message.ReplyTo = New MailAddress(value) Else _message.ReplyTo = New MailAddress(value, _message.ReplyTo.DisplayName) End If End Set End Property ''' ''' The reply display name of the sender of the message. ''' Public Property ReplyToDisplayName() As String Get If _message.ReplyTo Is Nothing Then Return String.Empty Else Return _message.ReplyTo.DisplayName End If End Get Set(ByVal value As String) If _message.ReplyTo Is Nothing Then _message.ReplyTo = New MailAddress(_message.From.Address, value) Else _message.ReplyTo = New MailAddress(_message.ReplyTo.Address, value) End If End Set End Property ''' ''' The email address of the sender of the message. ''' Public Overridable Property Sender() As String Get Return _message.From.Address End Get Protected Set(ByVal value As String) _message.From = New MailAddress(value, _message.From.DisplayName) End Set End Property ''' ''' The display name of the sender of the message. ''' Public Overridable Property SenderDisplayName() As String Get Return _message.From.DisplayName End Get Protected Set(ByVal value As String) _message.From = New MailAddress(_message.From.Address, value) End Set End Property ''' ''' The subject of the message. ''' Public Overridable Property Subject() As String Get Return _message.Subject End Get Protected Set(ByVal value As String) _message.Subject = value End Set End Property #End Region #Region " Methods " #Region " Send Methods " ''' ''' Sends this email ''' ''' The SMTP server to use to send the email. Public Sub Send(ByVal mailServer As String) _mailClient = New SmtpClient(mailServer) _mailClient.Send(_message) End Sub ''' ''' Sends this email asynchronously. ''' ''' The SMTP server to use to send the email. ''' A user defined token passed to the recieving method on completion of the asynchronous task. Public Sub SendAsync(ByVal mailServer As String, ByVal userToken As Object) _mailClient = New SmtpClient(mailServer) _mailClient.SendAsync(_message, userToken) End Sub ''' ''' Cancels an attempt to send this email asynchronously. ''' Public Sub SendAsyncCancel() _mailClient.SendAsyncCancel() End Sub #End Region #End Region #Region " IValidatable Implementation " ''' ''' gets and Sets a flag to indicate whether to use strict validation. ''' Public Property UseStrictValidation() As Boolean Get Return _useStrictValidation End Get Set(ByVal value As Boolean) _useStrictValidation = value End Set End Property ''' ''' Validates this email. ''' ''' A ValidationResponse, containing a flag to indicate if validation was passed and a collection of Property Names and validation errors. Public Function Validate() As ValidationResponse Implements IValidatable.Validate Dim retVal As New ValidationResponse() Dim mailRegEx As String = If(_useStrictValidation, StrictRegexPattern, LenientRegexPattern) ValidateAddress("Sender", retVal, mailRegEx, True) ValidateAddresses("Recipients", retVal, mailRegEx, True) ValidateAddresses("CcRecipients", retVal, mailRegEx) ValidateAddresses("BccRecipients", retVal, mailRegEx) ValidateAddress("ReplyTo", retVal, mailRegEx) Return retVal End Function ''' ''' Validates a single Email Address property. ''' ''' The name of the property to validate. ''' The validation response object. ''' The regular expression pattern to use for validation. Private Overloads Sub ValidateAddress(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String) ValidateAddress(propertyName, retVal, mailRegEx, False) End Sub ''' ''' Validates a single Email Address property. ''' ''' The name of the property to validate. ''' The validation response object. ''' The regular expression pattern to use for validation. ''' Indicates if the address is required; False if not specified. Private Overloads Sub ValidateAddress(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String, ByVal required As Boolean) Dim emailAddress As String = ReflectionHelper.Properties.GetProperty(Of String)(Me, propertyName) If emailAddress Is Nothing OrElse emailAddress.Length = 0 Then If required Then retVal.Add(New KeyValuePair(Of String, String)(propertyName, NullEmailAddressError)) Else If (Not Regex.IsMatch(emailAddress, mailRegEx)) Then retVal.Add(New KeyValuePair(Of String, String)(propertyName, InvalidEmailAddressError)) End If End If End Sub ''' ''' Validates a string array of Email Address property. ''' ''' The name of the property to validate. ''' The validation response object. ''' The regular expression pattern to use for validation. Private Overloads Sub ValidateAddresses(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String) ValidateAddresses(propertyName, retVal, mailRegEx, False) End Sub ''' ''' Validates a string array of Email Address property. ''' ''' The name of the property to validate. ''' The validation response object. ''' The regular expression pattern to use for validation. ''' Indicates if the address is required; False if not specified. Private Overloads Sub ValidateAddresses(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String, ByVal required As Boolean) Dim emailAddresses() As String = ReflectionHelper.Properties.GetProperty(Of String())(Me, propertyName) If emailAddresses Is Nothing OrElse emailAddresses.Length = 0 Then If required Then retVal.Add(New KeyValuePair(Of String, String)(propertyName, String.Format(CultureInfo.CurrentCulture, NullEmailAddressError))) Else For i As Integer = 0 To emailAddresses.Length - 1 If (Not Regex.IsMatch(emailAddresses(i), mailRegEx)) Then retVal.Add(New KeyValuePair(Of String, String)(propertyName, String.Format(CultureInfo.CurrentCulture, InvalidEmailAddressErrorWithAddress, emailAddresses(i)))) End If Next End If End Sub #End Region #Region " IDisposable Implementation " Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not Me.disposedValue Then If disposing Then _message.Dispose() End If _mailClient = Nothing _message = Nothing End If Me.disposedValue = True End Sub Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class End Namespace pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.vhdl000066400000000000000000000105361250413007300255330ustar00rootroot00000000000000library ieee; use ieee.std_logic_unsigned.all; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity top_testbench is --test generic ( -- test n : integer := 8 -- test ); -- test end top_testbench; -- test architecture top_testbench_arch of top_testbench is component top is generic ( n : integer ) ; port ( clk : in std_logic; rst : in std_logic; d1 : in std_logic_vector (n-1 downto 0); d2 : in std_logic_vector (n-1 downto 0); operation : in std_logic; result : out std_logic_vector (2*n-1 downto 0) ); end component; signal clk : std_logic; signal rst : std_logic; signal operation : std_logic; signal d1 : std_logic_vector (n-1 downto 0); signal d2 : std_logic_vector (n-1 downto 0); signal result : std_logic_vector (2*n-1 downto 0); type test_type is ( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); attribute enum_encoding of my_state : type is "001 010 011 100 111"; begin TESTUNIT : top generic map (n => n) port map (clk => clk, rst => rst, d1 => d1, d2 => d2, operation => operation, result => result); clock_process : process begin clk <= '0'; wait for 5 ns; clk <= '1'; wait for 5 ns; end process; data_process : process begin -- test case #1 operation <= '0'; rst <= '1'; wait for 5 ns; rst <= '0'; wait for 5 ns; d1 <= std_logic_vector(to_unsigned(60, d1'length)); d2 <= std_logic_vector(to_unsigned(12, d2'length)); wait for 360 ns; assert (result = std_logic_vector(to_unsigned(720, result'length))) report "Test case #1 failed" severity error; -- test case #2 operation <= '0'; rst <= '1'; wait for 5 ns; rst <= '0'; wait for 5 ns; d1 <= std_logic_vector(to_unsigned(55, d1'length)); d2 <= std_logic_vector(to_unsigned(1, d2'length)); wait for 360 ns; assert (result = std_logic_vector(to_unsigned(55, result'length))) report "Test case #2 failed" severity error; -- etc end process; end top_testbench_arch; configuration testbench_for_top of top_testbench is for top_testbench_arch for TESTUNIT : top use entity work.top(top_arch); end for; end for; end testbench_for_top; function compare(A: std_logic, B: std_Logic) return std_logic is constant pi : real := 3.14159; constant half_pi : real := pi / 2.0; constant cycle_time : time := 2 ns; constant N, N5 : integer := 5; begin if (A = '0' and B = '1') then return B; else return A; end if ; end compare; procedure print(P : std_logic_vector(7 downto 0); U : std_logic_vector(3 downto 0)) is variable my_line : line; alias swrite is write [line, string, side, width] ; begin swrite(my_line, "sqrt( "); write(my_line, P); swrite(my_line, " )= "); write(my_line, U); writeline(output, my_line); end print; entity add32csa is -- one stage of carry save adder for multiplier port( b : in std_logic; -- a multiplier bit a : in std_logic_vector(31 downto 0); -- multiplicand sum_in : in std_logic_vector(31 downto 0); -- sums from previous stage cin : in std_logic_vector(31 downto 0); -- carrys from previous stage sum_out : out std_logic_vector(31 downto 0); -- sums to next stage cout : out std_logic_vector(31 downto 0)); -- carrys to next stage end add32csa; ARCHITECTURE circuits of add32csa IS SIGNAL zero : STD_LOGIC_VECTOR(31 downto 0) := X"00000000"; SIGNAL aa : std_logic_vector(31 downto 0) := X"00000000"; COMPONENT fadd -- duplicates entity port PoRT(a : in std_logic; b : in std_logic; cin : in std_logic; s : out std_logic; cout : out std_logic); end comPonent fadd; begin -- circuits of add32csa aa <= a when b='1' else zero after 1 ns; stage: for I in 0 to 31 generate sta: fadd port map(aa(I), sum_in(I), cin(I) , sum_out(I), cout(I)); end generate stage; end architecture circuits; -- of add32csa pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.xqy000066400000000000000000000103011250413007300254050ustar00rootroot00000000000000(: made up functions, etc just to test xquery parsing (: even embedded comments on multiple :) lines :) xquery version "1.0"; module namespace xqueryexample "http://example.com/namespace"; import module namespace importedns = "http://example.com/ns/imported" at "no/such/file.xqy"; declare namespace sess = "com.example.session"; declare variable $amazing := "awesome"; declare variable $SESSIONS as element(sess:session)* := c:sessions(); declare option sess:clear "false"; define function whatsit($param as xs:string) as xs:string { let $var1 := 1 let $var2 := 2 return (1 + 2 div ($var1 + $var2)) let $let := "test" return (: some whitespace :) element element { attribute attribute { 1 }, element test { 'a' }, attribute foo { "bar" }, fn:doc()[ foo/@bar eq $let ], //x/with/another/*/*:version/xpath/@attr } }; let $bride := "Bride" let $test := validate lax { html } let $test := validate strict { html } let $test := validate { html } let $test := $var1/*:Article (: comment here :) [fn:not()] let $test := $var1/@*:name/fn:string() let $noop := ordered { $test } let $noop := unordered { $test } let $noop := for $version at $i in $versions/version let $row := if($i mod 2 eq 0) then "even" else "odd" order by $version descending return return { The Princess { fn:capitalize($bride) }
    { (: placeholder for local sessions :) element div { attribute id { "sessions-local" }, attribute class { "hidden" }, element h1 { "Local Sessions" }, element p { 'These sessions use storage provided by your browser.', 'You can also ', element a { attribute href { 'session-import-local.xqy' }, 'import' }, ' sessions from local XML files.' } } } { for $i in $sessions let $id := c:session-id($i) let $uri := c:session-uri($i) (: we only care about the lock that expires last :) let $conflicting := c:conflicting-locks($uri, 1) let $name as xs:string := ($i/sess:name, "(unnamed)")[1] return element tr { element td { $name }, element td { string($i/sec:user) }, element td { data($i/sess:created) }, element td { data($i/sess:last-modified) }, element td { if (empty($conflicting)) then () else text { "by", $conflicting/lock:owner, "until", adjust-dateTime-to-timezone( x:epoch-seconds-to-dateTime( $conflicting/lock:timestamp + $conflicting/lock:timeout ) ) }, (: only show resume button if there are no conflicting locks :) element input { attribute type { "button" }, attribute title { data($i/sess:query-buffers/sess:query[1]) }, attribute onclick { concat("list.resumeSession('", $id, "')") }, attribute value { "Resume", (' ', $id)[ $d:DEBUG ] } }[ not($conflicting) ], $x:NBSP, (: clone button :) element input { attribute type { "button" }, attribute title { "clone this session" }, attribute onclick { concat("list.cloneSession('", $id, "', this)") }, attribute value { "Clone", (' ', $id)[ $d:DEBUG ] } }, $x:NBSP, (: export button :) element input { attribute type { "button" }, attribute title { "export this session" }, attribute onclick { concat("list.exportServerSession('", $id, "', this)") }, attribute value { "Export", (' ', $id)[ $d:DEBUG ] } }, $x:NBSP, (: only show delete button if there are no conflicting locks :) element input { attribute type { "button" }, attribute title { "permanently delete this session" }, attribute onclick { concat("list.deleteSession('", $id, "', this)") }, attribute value { "Delete", (' ', $id)[ $d:DEBUG ] } }[ not($conflicting) ] } } }
    }   pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.xsl000066400000000000000000000013631250413007300254020ustar00rootroot00000000000000 pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.zep000066400000000000000000000007451250413007300253750ustar00rootroot00000000000000namespace Test; use Test\Foo; class Bar { protected a; private b; public c {set, get}; public function __construct(string str, boolean bool) { let this->c = str; this->setC(bool); let this->b = []; } public function sayHello(string name) { echo "Hello " . name; } protected function loops() { for a in b { echo a; } loop { return "boo!"; } } }pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test2.pypylog000066400000000000000000000201061250413007300263550ustar00rootroot00000000000000[2f1dd6c3b8b7] {jit-log-opt-loop # Loop 0 ( ds1dr4 dsdr3 ds1dr4) : loop with 115 ops [p0, p1] +33: label(p0, p1, descr=TargetToken(-1223434224)) debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') +33: guard_nonnull_class(p1, 138371488, descr=) [p1, p0] +54: p3 = getfield_gc_pure(p1, descr=) +57: guard_value(p3, ConstPtr(ptr4), descr=) [p1, p0, p3] +69: p5 = getfield_gc_pure(p1, descr=) +72: p7 = getarrayitem_gc(p5, 0, descr=) +75: guard_class(p7, 138371552, descr=) [p0, p5, p7] +88: p9 = getfield_gc(p7, descr=) +91: guard_nonnull_class(p9, 138373024, descr=) [p0, p5, p7, p9] +109: p12 = getarrayitem_gc(p5, 1, descr=) +112: guard_class(p12, 138371552, descr=) [p0, p5, p12, p7] +125: p14 = getfield_gc(p12, descr=) +128: guard_nonnull_class(p14, 138373024, descr=) [p0, p5, p12, p14, p7] debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') +146: p16 = getfield_gc_pure(p9, descr=) +149: guard_value(p16, ConstPtr(ptr17), descr=) [p16, p9, p0, p12, p7] +161: p18 = getfield_gc_pure(p9, descr=) +164: guard_class(p18, 138371648, descr=) [p18, p9, p0, p12, p7] +177: p20 = getfield_gc_pure(p9, descr=) +180: guard_class(p20, 138371648, descr=) [p20, p9, p18, p0, p12, p7] +193: p22 = getfield_gc_pure(p9, descr=) +196: guard_class(p22, 138371936, descr=) [p22, p9, p20, p18, p0, p12, p7] debug_merge_point(0, 0, 'None') +209: p24 = getfield_gc_pure(p22, descr=) +215: guard_value(p24, ConstPtr(ptr25), descr=) [p24, p22, p9, None, None, p0, p12, p7] +227: p27 = getfield_gc_pure(p22, descr=) +230: guard_class(p27, 138371648, descr=) [p22, p27, p9, None, None, p0, p12, p7] debug_merge_point(0, 0, '_') debug_merge_point(0, 0, 'None') +243: p30 = getfield_gc(ConstPtr(ptr29), descr=) +249: i34 = call(ConstClass(ll_dict_lookup_trampoline__v64___simple_call__function_ll), p30, ConstPtr(ptr32), 360200661, descr=) +281: guard_no_exception(, descr=) [p27, p20, p18, i34, p30, None, None, None, p0, p12, p7] +294: i36 = int_and(i34, -2147483648) +302: i37 = int_is_true(i36) guard_false(i37, descr=) [p27, p20, p18, i34, p30, None, None, None, p0, p12, p7] +311: p38 = getfield_gc(p30, descr=) +314: p39 = getinteriorfield_gc(p38, i34, descr=>) +318: i40 = instance_ptr_eq(p18, p39) guard_true(i40, descr=) [p27, p20, None, None, None, p0, p12, p7] debug_merge_point(0, 0, 'None') +327: i41 = getfield_gc_pure(p20, descr=) +330: i42 = getfield_gc_pure(p27, descr=) +333: i43 = int_sub(i41, i42) debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') +335: i45 = int_eq(0, i43) guard_false(i45, descr=) [p0, i43, None, None, None, None, p12, p7] p47 = new_with_vtable(138371648) +393: setfield_gc(p47, i43, descr=) setfield_gc(p7, p47, descr=) +414: p48 = getfield_gc(p12, descr=) +420: guard_nonnull_class(p48, 138371648, descr=) [p0, p48, p12, p47, p7] debug_merge_point(0, 0, ' 1 1 1 dsdr3 1') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, '_') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, ' dsdr3 dsdr3') debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') +438: label(p0, p48, p30, p38, descr=TargetToken(-1223434176)) debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, '_') debug_merge_point(0, 0, 'None') +438: i50 = call(ConstClass(ll_dict_lookup_trampoline__v64___simple_call__function_ll), p30, ConstPtr(ptr32), 360200661, descr=) +464: guard_no_exception(, descr=) [p48, i50, p30, p0] +477: i51 = int_and(i50, -2147483648) +485: i52 = int_is_true(i51) guard_false(i52, descr=) [p48, i50, p30, p0] +494: p53 = getinteriorfield_gc(p38, i50, descr=>) +501: i55 = instance_ptr_eq(ConstPtr(ptr54), p53) guard_true(i55, descr=) [p48, p0] debug_merge_point(0, 0, 'None') +513: i56 = getfield_gc_pure(p48, descr=) +516: i58 = int_sub(i56, 1) debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') +519: i59 = int_eq(0, i58) guard_false(i59, descr=) [i58, p48, p0] debug_merge_point(0, 0, ' 1 1 1 dsdr3 1') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, '_') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, 'None') debug_merge_point(0, 0, ' dsdr3 dsdr3') debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') p61 = new_with_vtable(138371700) p63 = new_with_vtable(138373024) p65 = new_with_vtable(138371936) +606: setfield_gc(p63, ConstPtr(ptr66), descr=) p68 = new_with_vtable(138373024) +632: setfield_gc(p65, ConstPtr(ptr69), descr=) p71 = new_with_vtable(138371936) +658: setfield_gc(p68, ConstPtr(ptr17), descr=) +665: setfield_gc(p71, ConstPtr(ptr72), descr=) +672: setfield_gc(p68, p71, descr=) +675: setfield_gc(p68, p48, descr=) +678: setfield_gc(p68, ConstPtr(ptr54), descr=) p73 = new_with_vtable(138371648) +701: setfield_gc(p61, p0, descr=) +716: setfield_gc(p61, 2, descr=) +723: setfield_gc(p71, ConstPtr(ptr25), descr=) +730: setfield_gc(p65, p68, descr=) +733: setfield_gc(p63, p65, descr=) +736: setfield_gc(p63, ConstPtr(ptr75), descr=) +743: setfield_gc(p63, ConstPtr(ptr54), descr=) +750: setfield_gc(p61, p63, descr=) +753: setfield_gc(p73, i58, descr=) +762: jump(p61, p73, p30, p38, descr=TargetToken(-1223434176)) +775: --end of the loop-- [2f1dd6da3b99] jit-log-opt-loop} pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/truncated.pytb000066400000000000000000000016151250413007300265640ustar00rootroot00000000000000 File "/usr/lib/python2.3/site-packages/trac/web/main.py", line 314, in dispatch_request dispatcher.dispatch(req) File "/usr/lib/python2.3/site-packages/trac/web/main.py", line 186, in dispatch req.session = Session(self.env, req) File "/usr/lib/python2.3/site-packages/trac/web/session.py", line 52, in __init__ self.promote_session(sid) File "/usr/lib/python2.3/site-packages/trac/web/session.py", line 125, in promote_session "AND authenticated=0", (sid,)) File "/usr/lib/python2.3/site-packages/trac/db/util.py", line 47, in execute return self.cursor.execute(sql_escape_percent(sql), args) File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 44, in execute args or []) File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 36, in _rollback_on_error return function(self, *args, **kwargs) OperationalError: database is locked pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/type.lisp000066400000000000000000001375711250413007300255600ustar00rootroot00000000000000;;;; TYPEP und Verwandtes ;;;; Michael Stoll, 21. 10. 1988 ;;;; Bruno Haible, 10.6.1989 ;;;; Sam Steingold 2000-2005 ;;; Datenstrukturen für TYPEP: ;;; - Ein Type-Specifier-Symbol hat auf seiner Propertyliste unter dem ;;; Indikator SYS::TYPE-SYMBOL eine Funktion von einem Argument, die ;;; testet, ob ein Objekt vom richtigen Typ ist. ;;; - Ein Symbol, das eine Type-Specifier-Liste beginnen kann, hat auf seiner ;;; Propertyliste unter dem Indikator SYS::TYPE-LIST eine Funktion von ;;; einem Argument für das zu testende Objekt und zusätzlichen Argumenten ;;; für die Listenelemente. ;;; - Ein Symbol, das als Typmacro definiert wurde, hat auf seiner Property- ;;; liste unter dem Indikator SYSTEM::DEFTYPE-EXPANDER den zugehörigen ;;; Expander: eine Funktion, die den zu expandierenden Type-Specifier (eine ;;; mindestens einelementige Liste) als Argument bekommt. (in-package "EXT") (export '(type-expand)) (in-package "SYSTEM") ; vorläufig, solange bis clos.lisp geladen wird: (eval-when (eval) (predefun clos::built-in-class-p (object) (declare (ignore object)) nil)) (unless (fboundp 'clos::class-name) (defun clos::class-name (c) (declare (ignore c)) nil) ) (defun typespec-error (fun type) (error-of-type 'error (TEXT "~S: invalid type specification ~S") fun type ) ) ;; ============================================================================ ;; return the CLOS class named by TYPESPEC or NIL (defun clos-class (typespec) (let ((cc (get typespec 'CLOS::CLOSCLASS))) (when (and cc (clos::defined-class-p cc) (eq (clos:class-name cc) typespec)) cc))) ;;; TYPEP, CLTL S. 72, S. 42-51 (defun typep (x y &optional env &aux f) ; x = Objekt, y = Typ (declare (ignore env)) (setq y (expand-deftype y)) (cond ((symbolp y) (cond ((setq f (get y 'TYPE-SYMBOL)) (funcall f x)) ((setq f (get y 'TYPE-LIST)) (funcall f x)) ((setq f (get y 'DEFSTRUCT-DESCRIPTION)) (ds-typep x y f)) ((setq f (clos-class y)) ; It's not worth handling structure classes specially here. (clos::typep-class x f)) (t (typespec-error 'typep y)) ) ) ((and (consp y) (symbolp (first y))) (cond ((and (eq (first y) 'SATISFIES) (eql (length y) 2)) (unless (symbolp (second y)) (error-of-type 'error (TEXT "~S: argument to SATISFIES must be a symbol: ~S") 'typep (second y) ) ) (if (funcall (symbol-function (second y)) x) t nil) ) ((eq (first y) 'MEMBER) (if (member x (rest y)) t nil) ) ((and (eq (first y) 'EQL) (eql (length y) 2)) (eql x (second y)) ) ((and (eq (first y) 'NOT) (eql (length y) 2)) (not (typep x (second y))) ) ((eq (first y) 'AND) (dolist (type (rest y) t) (unless (typep x type) (return nil)) ) ) ((eq (first y) 'OR) (dolist (type (rest y) nil) (when (typep x type) (return t)) ) ) ((setq f (get (first y) 'TYPE-LIST)) (apply f x (rest y))) (t (typespec-error 'typep y)) ) ) ((clos::defined-class-p y) (clos::typep-class x y)) ((clos::eql-specializer-p y) (eql x (clos::eql-specializer-singleton y))) ((encodingp y) (charset-typep x y)) (t (typespec-error 'typep y)) ) ) ;; ---------------------------------------------------------------------------- ;; UPGRADED-ARRAY-ELEMENT-TYPE is a lattice homomorphism, see ;; ANSI CL 15.1.2.1. (defun upgraded-array-element-type (type &optional environment) (declare (ignore environment)) ;; see array.d (case type ((BIT) 'BIT) ((CHARACTER) 'CHARACTER) ((T) 'T) ((NIL) 'NIL) (t (if (subtypep type 'NIL) 'NIL (multiple-value-bind (low high) (sys::subtype-integer type) ; Es gilt (or (null low) (subtypep type `(INTEGER ,low ,high))) (if (and (integerp low) (not (minusp low)) (integerp high)) (let ((l (integer-length high))) ; Es gilt (subtypep type `(UNSIGNED-BYTE ,l)) (cond ((<= l 1) 'BIT) ((<= l 2) '(UNSIGNED-BYTE 2)) ((<= l 4) '(UNSIGNED-BYTE 4)) ((<= l 8) '(UNSIGNED-BYTE 8)) ((<= l 16) '(UNSIGNED-BYTE 16)) ((<= l 32) '(UNSIGNED-BYTE 32)) (t 'T))) (if (subtypep type 'CHARACTER) 'CHARACTER 'T))))))) ;; ---------------------------------------------------------------------------- ;; UPGRADED-COMPLEX-PART-TYPE is a lattice homomorphism, see ;; HyperSpec/Body/fun_complex.html and HyperSpec/Body/syscla_complex.html, ;; and an idempotent. Therefore ;; (subtypep (upgraded-complex-part-type T1) (upgraded-complex-part-type T2)) ;; is equivalent to ;; (subtypep T1 (upgraded-complex-part-type T2)) ;; (Proof: Let U T be an abbreviation for (upgraded-complex-part-type T). ;; If U T1 <= U T2, then T1 <= U T1 <= U T2. ;; If T1 <= U T2, then by homomorphism U T1 <= U U T2 = U T2.) ;; ;; For _any_ CL implementation, you could define ;; (defun upgraded-complex-part-type (type) 'REAL) ;; Likewise for _any_ CL implementation, you could define ;; (defun upgraded-complex-part-type (type) type) ;; or - again for _any_ CL implementation: ;; (defun upgraded-complex-part-type (type) ;; (cond ((subtypep type 'NIL) 'NIL) ;; ((subtypep type 'SHORT-FLOAT) 'SHORT-FLOAT) ;; ((subtypep type 'SINGLE-FLOAT) 'SINGLE-FLOAT) ;; ((subtypep type 'DOUBLE-FLOAT) 'DOUBLE-FLOAT) ;; ((subtypep type 'LONG-FLOAT) 'LONG-FLOAT) ;; ((subtypep type 'RATIONAL) 'RATIONAL) ;; ((subtypep type 'REAL) 'REAL) ;; (t (error ...)))) ;; The reason is that a complex number is immutable: no setters for the ;; realpart and imagpart exist. ;; ;; We choose the second implementation because it allows the most precise ;; type inference. (defun upgraded-complex-part-type (type &optional environment) (declare (ignore environment)) (if (subtypep type 'REAL) type (error-of-type 'error (TEXT "~S: type ~S is not a subtype of ~S") 'upgraded-complex-part-type type 'real))) ;; ---------------------------------------------------------------------------- ;; Macros for defining the various built-in "atomic type specifier"s and ;; "compound type specifier"s. The following macros add information for both ;; the TYPEP function above and the c-TYPEP in the compiler. ; Alist symbol -> funname, used by the compiler. (defparameter c-typep-alist1 '()) ; Alist symbol -> lambdabody, used by the compiler. (defparameter c-typep-alist2 '()) ; Alist symbol -> expander function, used by the compiler. (defparameter c-typep-alist3 '()) ; (def-atomic-type symbol function-name) ; defines an atomic type. The function-name designates a function taking one ; argument and returning a generalized boolean value. It can be either a ; symbol or a lambda expression. (defmacro def-atomic-type (symbol funname) (let ((lambdap (and (consp funname) (eq (car funname) 'LAMBDA)))) `(PROGN (SETF (GET ',symbol 'TYPE-SYMBOL) ,(if lambdap `(FUNCTION ,(concat-pnames "TYPE-SYMBOL-" symbol) ,funname) `(FUNCTION ,funname) ) ) ,(if lambdap `(SETQ C-TYPEP-ALIST2 (NCONC C-TYPEP-ALIST2 (LIST (CONS ',symbol ',(cdr funname)))) ) `(SETQ C-TYPEP-ALIST1 (NCONC C-TYPEP-ALIST1 (LIST (CONS ',symbol ',funname))) ) ) ',symbol ) ) ) ; (def-compound-type symbol lambda-list (x) check-form typep-form c-typep-form) ; defines a compound type. The lambda-list is of the form (&optional ...) ; where the arguments come from the CDR of the type specifier. ; For typep-form, x is an object. ; For c-typep-form, x is a multiply evaluatable form (actually a gensym). ; check-form is a form performing error checking, may call `error'. ; typep-form should return a generalized boolean value. ; c-typep-form should produce a form returning a generalized boolean value. (defmacro def-compound-type (symbol lambdalist (var) check-form typep-form c-typep-form) `(PROGN (SETF (GET ',symbol 'TYPE-LIST) (FUNCTION ,(concat-pnames "TYPE-LIST-" symbol) (LAMBDA (,var ,@lambdalist) ,@(if check-form `((MACROLET ((ERROR (&REST ERROR-ARGS) (LIST* 'ERROR-OF-TYPE ''ERROR ERROR-ARGS) )) ,check-form )) ) ,typep-form ) ) ) (SETQ C-TYPEP-ALIST3 (NCONC C-TYPEP-ALIST3 (LIST (CONS ',symbol #'(LAMBDA (,var ,@lambdalist &REST ILLEGAL-ARGS) (DECLARE (IGNORE ILLEGAL-ARGS)) ,@(if check-form `((MACROLET ((ERROR (&REST ERROR-ARGS) (LIST 'PROGN (LIST* 'C-WARN ERROR-ARGS) '(THROW 'C-TYPEP NIL) )) ) ,check-form )) ) ,c-typep-form ) ) ) ) ) ',symbol ) ) ; CLtL1 p. 43 (def-atomic-type ARRAY arrayp) (def-atomic-type ATOM atom) (def-atomic-type BASE-CHAR #+BASE-CHAR=CHARACTER characterp #-BASE-CHAR=CHARACTER (lambda (x) (and (characterp x) (base-char-p x))) ) (def-atomic-type BASE-STRING (lambda (x) (and (stringp x) (eq (array-element-type x) #+BASE-CHAR=CHARACTER 'CHARACTER #-BASE-CHAR=CHARACTER 'BASE-CHAR ) ) ) ) (def-atomic-type BIGNUM (lambda (x) (and (integerp x) (not (fixnump x)))) ) (def-atomic-type BIT (lambda (x) (or (eql x 0) (eql x 1))) ) (def-atomic-type BIT-VECTOR bit-vector-p) (def-atomic-type BOOLEAN (lambda (x) (or (eq x 'nil) (eq x 't))) ) (def-atomic-type CHARACTER characterp) (def-atomic-type COMPILED-FUNCTION compiled-function-p) (def-atomic-type COMPLEX complexp) (def-atomic-type CONS consp) (def-atomic-type DOUBLE-FLOAT double-float-p) (def-atomic-type ENCODING encodingp) (def-atomic-type EXTENDED-CHAR #+BASE-CHAR=CHARACTER (lambda (x) (declare (ignore x)) nil) #-BASE-CHAR=CHARACTER (lambda (x) (and (characterp x) (not (base-char-p x)))) ) (def-atomic-type FIXNUM fixnump) (def-atomic-type FLOAT floatp) (def-atomic-type FUNCTION functionp) (def-atomic-type HASH-TABLE hash-table-p) (def-atomic-type INTEGER integerp) (def-atomic-type KEYWORD keywordp) (def-atomic-type LIST listp) #+LOGICAL-PATHNAMES (def-atomic-type LOGICAL-PATHNAME logical-pathname-p) (def-atomic-type LONG-FLOAT long-float-p) (def-atomic-type NIL (lambda (x) (declare (ignore x)) nil) ) (def-atomic-type NULL null) (def-atomic-type NUMBER numberp) (def-atomic-type PACKAGE packagep) (def-atomic-type PATHNAME pathnamep) (def-atomic-type RANDOM-STATE random-state-p) (def-atomic-type RATIO (lambda (x) (and (rationalp x) (not (integerp x)))) ) (def-atomic-type RATIONAL rationalp) (def-atomic-type READTABLE readtablep) (def-atomic-type REAL realp) (def-atomic-type SEQUENCE sequencep) (def-atomic-type SHORT-FLOAT short-float-p) (def-atomic-type SIMPLE-ARRAY simple-array-p) (def-atomic-type SIMPLE-BASE-STRING (lambda (x) (and (simple-string-p x) (eq (array-element-type x) #+BASE-CHAR=CHARACTER 'CHARACTER #-BASE-CHAR=CHARACTER 'BASE-CHAR ) ) ) ) (def-atomic-type SIMPLE-BIT-VECTOR simple-bit-vector-p) (def-atomic-type SIMPLE-STRING simple-string-p) (def-atomic-type SIMPLE-VECTOR simple-vector-p) (def-atomic-type SINGLE-FLOAT single-float-p) (defun %standard-char-p (x) (and (characterp x) (standard-char-p x))) ; ABI (def-atomic-type STANDARD-CHAR %standard-char-p) (def-atomic-type CLOS:STANDARD-OBJECT clos::std-instance-p) (def-atomic-type STREAM streamp) (def-atomic-type FILE-STREAM file-stream-p) (def-atomic-type SYNONYM-STREAM synonym-stream-p) (def-atomic-type BROADCAST-STREAM broadcast-stream-p) (def-atomic-type CONCATENATED-STREAM concatenated-stream-p) (def-atomic-type TWO-WAY-STREAM two-way-stream-p) (def-atomic-type ECHO-STREAM echo-stream-p) (def-atomic-type STRING-STREAM string-stream-p) (def-atomic-type STRING stringp) (def-atomic-type STRING-CHAR characterp) (def-atomic-type CLOS:STRUCTURE-OBJECT clos::structure-object-p) (def-atomic-type SYMBOL symbolp) (def-atomic-type T (lambda (x) (declare (ignore x)) t)) ;; foreign1.lisp is loaded after this file, ;; so these symbols are not external yet #+ffi (def-atomic-type ffi::foreign-function (lambda (x) (eq 'ffi::foreign-function (type-of x)))) #+ffi (def-atomic-type ffi::foreign-variable (lambda (x) (eq 'ffi::foreign-variable (type-of x)))) #+ffi (def-atomic-type ffi::foreign-address (lambda (x) (eq 'ffi::foreign-address (type-of x)))) ;; see lispbibl.d (#define FOREIGN) and predtype.d (TYPE-OF): #+(or unix ffi affi win32) (def-atomic-type foreign-pointer (lambda (x) (eq 'foreign-pointer (type-of x)))) (def-atomic-type VECTOR vectorp) (def-atomic-type PLIST (lambda (x) (multiple-value-bind (length tail) (list-length-dotted x) (and (null tail) (evenp length))))) (defmacro ensure-dim (type dim) ;; make sure DIM is a valid dimension `(unless (or (eq ,dim '*) (typep ,dim `(INTEGER 0 (,ARRAY-DIMENSION-LIMIT)))) (error (TEXT "~S: dimension ~S is invalid") ',type ,dim))) (defmacro ensure-rank (type rank) ;; make sure RANK is a valid rank `(unless (typep ,rank `(INTEGER 0 (,ARRAY-RANK-LIMIT))) (error (TEXT "~S: rank ~S is invalid") ',type ,rank))) ; CLtL1 p. 46-50 (defun c-typep-array (tester el-type dims x) `(AND (,tester ,x) ,@(if (eq el-type '*) '() `((EQUAL (ARRAY-ELEMENT-TYPE ,x) ',(upgraded-array-element-type el-type))) ) ,@(if (eq dims '*) '() (if (numberp dims) `((EQL ,dims (ARRAY-RANK ,x))) `((EQL ,(length dims) (ARRAY-RANK ,x)) ,@(let ((i 0)) (mapcap #'(lambda (dim) (prog1 (if (eq dim '*) '() `((EQL ',dim (ARRAY-DIMENSION ,x ,i))) ) (incf i) ) ) dims ) ) ) ) ) ) ) (defun c-typep-vector (tester size x) `(AND (,tester ,x) ,@(if (eq size '*) '() `((EQL ',size (ARRAY-DIMENSION ,x 0))) ) ) ) (defun typep-number-test (x low high test type) (and (funcall test x) (cond ((eq low '*)) ((funcall test low) (<= low x)) ((and (consp low) (null (rest low)) (funcall test (first low))) (< (first low) x) ) (t (error-of-type 'error #1=(TEXT "~S: argument to ~S must be *, ~S or a list of ~S: ~S") 'typep type type type low ) ) ) (cond ((eq high '*)) ((funcall test high) (>= high x)) ((and (consp high) (null (rest high)) (funcall test (first high))) (> (first high) x) ) (t (error-of-type 'error #1# 'typep type type type high ) ) ) ) ) (defun c-typep-number (caller tester low high x) `(AND (,tester ,x) ,@(cond ((eq low '*) '()) ((funcall tester low) `((<= ,low ,x))) ((and (consp low) (null (rest low)) (funcall tester (first low))) `((< ,(first low) ,x)) ) (t (c-warn #1=(TEXT "~S: argument to ~S must be *, ~S or a list of ~S: ~S") 'typep caller caller caller low ) (throw 'c-TYPEP nil) ) ) ,@(cond ((eq high '*) '()) ((funcall tester high) `((>= ,high ,x))) ((and (consp high) (null (rest high)) (funcall tester (first high))) `((> ,(first high) ,x)) ) (t (c-warn #1# 'typep caller caller caller high) (throw 'c-TYPEP nil) ) ) ) ) (def-compound-type ARRAY (&optional (el-type '*) (dims '*)) (x) (unless (eq dims '*) (if (numberp dims) (ensure-rank ARRAY dims) (dolist (dim dims) (ensure-dim ARRAY dim)))) (and (arrayp x) (or (eq el-type '*) (equal (array-element-type x) (upgraded-array-element-type el-type)) ) (or (eq dims '*) (if (numberp dims) (eql dims (array-rank x)) (and (eql (length dims) (array-rank x)) (every #'(lambda (a b) (or (eq a '*) (eql a b))) dims (array-dimensions x) ) ) ) ) ) (c-typep-array 'ARRAYP el-type dims x) ) (def-compound-type SIMPLE-ARRAY (&optional (el-type '*) (dims '*)) (x) (unless (eq dims '*) (if (numberp dims) (ensure-rank SIMPLE-ARRAY dims) (dolist (dim dims) (ensure-dim SIMPLE-ARRAY dim)))) (and (simple-array-p x) (or (eq el-type '*) (equal (array-element-type x) (upgraded-array-element-type el-type)) ) (or (eq dims '*) (if (numberp dims) (eql dims (array-rank x)) (and (eql (length dims) (array-rank x)) (every #'(lambda (a b) (or (eq a '*) (eql a b))) dims (array-dimensions x) ) ) ) ) ) (c-typep-array 'SIMPLE-ARRAY-P el-type dims x) ) (def-compound-type VECTOR (&optional (el-type '*) (size '*)) (x) (ensure-dim VECTOR size) (and (vectorp x) (or (eq el-type '*) (equal (array-element-type x) (upgraded-array-element-type el-type)) ) (or (eq size '*) (eql (array-dimension x 0) size)) ) `(AND (VECTORP ,x) ,@(if (eq el-type '*) '() `((EQUAL (ARRAY-ELEMENT-TYPE ,x) ',(upgraded-array-element-type el-type))) ) ,@(if (eq size '*) '() `((EQL (ARRAY-DIMENSION ,x 0) ',size)) ) ) ) (def-compound-type SIMPLE-VECTOR (&optional (size '*)) (x) (ensure-dim SIMLPE-VECTOR size) (and (simple-vector-p x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'SIMPLE-VECTOR-P size x) ) (def-compound-type COMPLEX (&optional (rtype '*) (itype rtype)) (x) nil (and (complexp x) (or (eq rtype '*) (typep (realpart x) (upgraded-complex-part-type rtype))) (or (eq itype '*) (typep (imagpart x) (upgraded-complex-part-type itype)))) `(AND (COMPLEXP ,x) ,@(if (eq rtype '*) '() `((TYPEP (REALPART ,x) ',(upgraded-complex-part-type rtype)))) ,@(if (eq itype '*) '() `((TYPEP (IMAGPART ,x) ',(upgraded-complex-part-type itype)))))) (def-compound-type INTEGER (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'integerp 'INTEGER) (c-typep-number 'INTEGER 'INTEGERP low high x) ) (def-compound-type MOD (n) (x) (unless (integerp n) (error (TEXT "~S: argument to MOD must be an integer: ~S") 'typep n ) ) (and (integerp x) (<= 0 x) (< x n)) `(AND (INTEGERP ,x) (NOT (MINUSP ,x)) (< ,x ,n)) ) (def-compound-type SIGNED-BYTE (&optional (n '*)) (x) (unless (or (eq n '*) (integerp n)) (error (TEXT "~S: argument to SIGNED-BYTE must be an integer or * : ~S") 'typep n ) ) (and (integerp x) (or (eq n '*) (< (integer-length x) n))) `(AND (INTEGERP ,x) ,@(if (eq n '*) '() `((< (INTEGER-LENGTH ,x) ,n))) ) ) (def-compound-type UNSIGNED-BYTE (&optional (n '*)) (x) (unless (or (eq n '*) (integerp n)) (error (TEXT "~S: argument to UNSIGNED-BYTE must be an integer or * : ~S") 'typep n ) ) (and (integerp x) (not (minusp x)) (or (eq n '*) (<= (integer-length x) n)) ) `(AND (INTEGERP ,x) (NOT (MINUSP ,x)) ,@(if (eq n '*) '() `((<= (INTEGER-LENGTH ,x) ,n))) ) ) (def-compound-type REAL (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'realp 'REAL) (c-typep-number 'REAL 'REALP low high x) ) (def-compound-type RATIONAL (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'rationalp 'RATIONAL) (c-typep-number 'RATIONAL 'RATIONALP low high x) ) (def-compound-type FLOAT (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'floatp 'FLOAT) (c-typep-number 'FLOAT 'FLOATP low high x) ) (def-compound-type SHORT-FLOAT (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'short-float-p 'SHORT-FLOAT) (c-typep-number 'SHORT-FLOAT 'SHORT-FLOAT-P low high x) ) (def-compound-type SINGLE-FLOAT (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'single-float-p 'SINGLE-FLOAT) (c-typep-number 'SINGLE-FLOAT 'SINGLE-FLOAT-P low high x) ) (def-compound-type DOUBLE-FLOAT (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'double-float-p 'DOUBLE-FLOAT) (c-typep-number 'DOUBLE-FLOAT 'DOUBLE-FLOAT-P low high x) ) (def-compound-type LONG-FLOAT (&optional (low '*) (high '*)) (x) nil (typep-number-test x low high #'long-float-p 'LONG-FLOAT) (c-typep-number 'LONG-FLOAT 'LONG-FLOAT-P low high x) ) (def-compound-type STRING (&optional (size '*)) (x) (ensure-dim STRING size) (and (stringp x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'STRINGP size x) ) (def-compound-type SIMPLE-STRING (&optional (size '*)) (x) (ensure-dim SIMPLE-STRING size) (and (simple-string-p x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'SIMPLE-STRING-P size x) ) (def-compound-type BASE-STRING (&optional (size '*)) (x) (ensure-dim BASE-STRING size) (and (stringp x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'STRINGP size x) ) (def-compound-type SIMPLE-BASE-STRING (&optional (size '*)) (x) (ensure-dim SIMPLE-BASE-STRING size) (and (simple-string-p x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'SIMPLE-STRING-P size x) ) (def-compound-type BIT-VECTOR (&optional (size '*)) (x) (ensure-dim BIT-VECTOR size) (and (bit-vector-p x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'BIT-VECTOR-P size x) ) (def-compound-type SIMPLE-BIT-VECTOR (&optional (size '*)) (x) (ensure-dim SIMPLE-BIT-VECTOR size) (and (simple-bit-vector-p x) (or (eq size '*) (eql size (array-dimension x 0))) ) (c-typep-vector 'SIMPLE-BIT-VECTOR-P size x) ) (def-compound-type CONS (&optional (car-type '*) (cdr-type '*)) (x) nil (and (consp x) (or (eq car-type '*) (typep (car x) car-type)) (or (eq cdr-type '*) (typep (cdr x) cdr-type)) ) `(AND (CONSP ,x) ,@(if (eq car-type '*) '() `((TYPEP (CAR ,x) ',car-type))) ,@(if (eq cdr-type '*) '() `((TYPEP (CDR ,x) ',cdr-type))) ) ) (fmakunbound 'def-compound-type) ;; ---------------------------------------------------------------------------- ; Typtest ohne Gefahr einer Fehlermeldung. Für SIGNAL und HANDLER-BIND. (defun safe-typep (x y &optional env) (let ((*error-handler* #'(lambda (&rest error-args) (declare (ignore error-args)) (return-from safe-typep (values nil nil)) )) ) (values (typep x y env) t) ) ) ; Umwandlung eines "type for declaration" in einen "type for discrimination". (defun type-for-discrimination (y &optional (notp nil) &aux f) (cond ((symbolp y) (cond ((get y 'TYPE-SYMBOL) y) ((get y 'TYPE-LIST) y) ((setq f (get y 'DEFTYPE-EXPANDER)) (let* ((z (funcall f (list y))) (zx (type-for-discrimination z notp))) (if (eql zx z) y zx) )) (t y) ) ) ((and (consp y) (symbolp (first y))) (case (first y) ((SATISFIES MEMBER EQL) y) (NOT (let* ((z (second y)) (zx (type-for-discrimination z (not notp)))) (if (eql zx z) y `(NOT ,zx)) )) ((AND OR COMPLEX VALUES) (let* ((z (rest y)) (zx (mapcar #'(lambda (x) (type-for-discrimination x notp)) z))) (if (every #'eql z zx) y (cons (first y) zx)) )) (FUNCTION ;; (FUNCTION arg-types res-type) is somewhere between ;; NIL and FUNCTION, but undecidable. (if notp 'NIL 'FUNCTION) ) (t (cond ((get (first y) 'TYPE-LIST) y) ((setq f (get (first y) 'DEFTYPE-EXPANDER)) (let* ((z (funcall f y)) (zx (type-for-discrimination z notp))) (if (eql zx z) y zx) )) (t y) ) ) ) ) (t y) ) ) ; Testet eine Liste von Werten auf Erfüllen eines Type-Specifiers. Für THE. (defun %the (values type) ; ABI (macrolet ((near-typep (objform typform) ;; near-typep ist wie typep, nur dass das Objekt auch ein ;; Read-Label sein darf. Das tritt z.B. auf bei ;; (read-from-string "#1=#S(FOO :X #1#)") ;; im Konstruktor MAKE-FOO. Die Implementation ist aber ;; nicht gezwungen, bei fehlerhaftem THE zwingend einen ;; Fehler zu melden, darum ist ein lascherer Typcheck hier ;; erlaubt. (let ((g (gensym))) `(let ((,g ,objform)) (or (typep ,g ,typform) (eq (type-of ,g) 'READ-LABEL)))))) (if (and (consp type) (eq (car type) 'VALUES)) ;; The VALUES type specifier is ill-defined in ANSI CL. ;; ;; There are two possibilities to define a VALUES type specifier in a ;; sane way: ;; - (EXACT-VALUES type1 ... [&optional ...]) describes the exact shape ;; of the values list, as received by MULTIPLE-VALUE-LIST. ;; For example, (EXACT-VALUES SYMBOL) is matched by (values 'a) but not ;; by (values 'a 'b) or (values). ;; - (ASSIGNABLE-VALUES type1 ... [&optional ...]) describes the values ;; as received by a set of variables through MULTIPLE-VALUE-BIND or ;; MULTIPLE-VALUE-SETQ. For example, (ASSIGNABLE-VALUES SYMBOL) is ;; defined by whether ;; (MULTIPLE-VALUE-BIND (var1) values (DECLARE (TYPE SYMBOL var1)) ...) ;; is valid or not; therefore (ASSIGNABLE-VALUES SYMBOL) is matched by ;; (values 'a) and (values 'a 'b) and (values). ;; Note that &OPTIONAL is actually redundant here: ;; (ASSIGNABLE-VALUES type1 ... &optional otype1 ...) ;; is equivalent to ;; (ASSIGNABLE-VALUES type1 ... (OR NULL otype1) ...) ;; HyperSpec/Body/typspe_values.html indicates that VALUES means ;; EXACT-VALUES; however, HyperSpec/Body/speope_the.html indicates that ;; VALUES means ASSIGNABLE-VALUES. ;; ;; SBCL interprets the VALUES type specifier to mean EXACT-VALUES when ;; it contains &OPTIONAL or &REST, but ASSIGNABLE-VALUES when it has ;; only a tuple of type specifiers. This is utter nonsense, in particular ;; because it makes (VALUES type1 ... typek &OPTIONAL) ;; different from (VALUES type1 ... typek). ;; ;; Here we use the ASSIGNABLE-VALUES interpretation. ;; In SUBTYPEP we just punt and don't assume any interpretation. (let ((vals values) (types (cdr type))) ;; required: (loop (when (or (atom types) (atom vals)) (return-from %the t)) (when (memq (car types) lambda-list-keywords) (return)) (unless (near-typep (pop vals) (pop types)) (return-from %the nil))) ;; &optional: (when (and (consp types) (eq (car types) '&optional)) (setq types (cdr types)) (loop (when (or (atom types) (atom vals)) (return-from %the t)) (when (memq (car types) lambda-list-keywords) (return)) (unless (near-typep (pop vals) (pop types)) (return-from %the nil)))) ;; &rest &key: (case (car types) (&rest (setq types (cdr types)) (when (atom types) (typespec-error 'the type)) (unless (near-typep (pop vals) (pop types)) (return-from %the nil))) (&key) (t (typespec-error 'the type))) (if (eq (car types) '&key) (progn (setq types (cdr types)) (when (oddp (length vals)) (return-from %the nil)) (let ((keywords nil)) (loop (when (or (atom types) (atom vals)) (return-from %the t)) (when (memq (car types) lambda-list-keywords) (return)) (let ((item (pop types))) (unless (and (listp item) (eql (length item) 2) (symbolp (first item))) (typespec-error 'the type)) (let ((kw (symbol-to-keyword (first item)))) (unless (near-typep (getf vals kw) (second item)) (return-from %the nil)) (push kw keywords)))) (if (and (consp types) (eq (car types) '&allow-other-keys)) (setq types (cdr types)) (unless (getf vals ':allow-other-keys) (do ((L vals (cddr L))) ((atom L)) (unless (memq (car L) keywords) (return-from %the nil))))))) (when (consp types) (typespec-error 'the type))) t) (near-typep (if (consp values) (car values) nil) type)))) ;;; =========================================================================== ;; SUBTYPEP (load "subtypep") ;; Returns the number of bytes that are needed to represent #\Null in a ;; given encoding. (defun encoding-zeroes (encoding) #+UNICODE ;; this should use min_bytes_per_char for cache, not the hash table (let ((name (ext:encoding-charset encoding)) (table #.(make-hash-table :key-type '(or string symbol) :value-type 'fixnum :test 'stablehash-equal :warn-if-needs-rehash-after-gc t :initial-contents '(("UTF-7" . 1)))) (tester #.(make-string 2 :initial-element (code-char 0)))) (or (gethash name table) (setf (gethash name table) (- (length (ext:convert-string-to-bytes tester encoding)) (length (ext:convert-string-to-bytes tester encoding :end 1)))))) #-UNICODE 1) ;; Determines two values low,high such that ;; (subtypep type `(INTEGER ,low ,high)) ;; holds and low is as large as possible and high is as small as possible. ;; low = * means -infinity, high = * means infinity. ;; When (subtypep type 'INTEGER) is false, the values NIL,NIL are returned. ;; We need this function only for MAKE-ARRAY, UPGRADED-ARRAY-ELEMENT-TYPE and ;; OPEN and can therefore w.l.o.g. replace ;; type with `(OR ,type (MEMBER 0)) #| ;; The original implementation calls canonicalize-type and then applies ;; a particular SUBTYPE variant: (defun subtype-integer (type) (macrolet ((yes () '(return-from subtype-integer (values low high))) (no () '(return-from subtype-integer nil)) (unknown () '(return-from subtype-integer nil))) (setq type (canonicalize-type type)) (if (consp type) (case (first type) (MEMBER ; (MEMBER &rest objects) ;; All elements must be of type INTEGER. (let ((low 0) (high 0)) ; wlog! (dolist (x (rest type) (yes)) (unless (typep x 'INTEGER) (return (no))) (setq low (min low x) high (max high x))))) (OR ; (OR type*) ;; Every type must be subtype of INTEGER. (let ((low 0) (high 0)) ; wlog! (dolist (type1 (rest type) (yes)) (multiple-value-bind (low1 high1) (subtype-integer type1) (unless low1 (return (no))) (setq low (if (or (eq low '*) (eq low1 '*)) '* (min low low1)) high (if (or (eq high '*) (eq high1 '*)) '* (max high high1))))))) (AND ; (AND type*) ;; If one of the types is subtype of INTEGER, then yes, ;; otherwise unknown. (let ((low nil) (high nil)) (dolist (type1 (rest type)) (multiple-value-bind (low1 high1) (subtype-integer type1) (when low1 (if low (setq low (if (eq low '*) low1 (if (eq low1 '*) low (max low low1))) high (if (eq high '*) high1 (if (eq high1 '*) high (min high high1)))) (setq low low1 high high1))))) (if low (progn (when (and (numberp low) (numberp high) (not (<= low high))) (setq low 0 high 0) ; type equivalent to NIL) (yes)) (unknown))))) (setq type (list type))) (if (eq (first type) 'INTEGER) (let ((low (if (rest type) (second type) '*)) (high (if (cddr type) (third type) '*))) (when (consp low) (setq low (first low)) (when (numberp low) (incf low))) (when (consp high) (setq high (first high)) (when (numberp high) (decf high))) (when (and (numberp low) (numberp high) (not (<= low high))) ; type leer? (setq low 0 high 0)) (yes)) (if (and (eq (first type) 'INTERVALS) (eq (second type) 'INTEGER)) (let ((low (third type)) (high (car (last type)))) (when (consp low) (setq low (first low)) (when (numberp low) (incf low))) (when (consp high) (setq high (first high)) (when (numberp high) (decf high))) (yes)) (unknown))))) |# ;; This implementation inlines the (tail-recursive) canonicalize-type ;; function. Its advantage is that it doesn't cons as much. ;; (For example, (subtype-integer '(UNSIGNED-BYTE 8)) doesn't cons.) (defun subtype-integer (type) (macrolet ((yes () '(return-from subtype-integer (values low high))) (no () '(return-from subtype-integer nil)) (unknown () '(return-from subtype-integer nil))) (setq type (expand-deftype type)) (cond ((symbolp type) (case type (BIT (let ((low 0) (high 1)) (yes))) (FIXNUM (let ((low '#,most-negative-fixnum) (high '#,most-positive-fixnum)) (yes))) ((INTEGER BIGNUM SIGNED-BYTE) (let ((low '*) (high '*)) (yes))) (UNSIGNED-BYTE (let ((low 0) (high '*)) (yes))) ((NIL) (let ((low 0) (high 0)) (yes))) ; wlog! (t (no)))) ((and (consp type) (symbolp (first type))) (unless (and (list-length type) (null (cdr (last type)))) (typespec-error 'subtypep type)) (case (first type) (MEMBER ; (MEMBER &rest objects) ;; All elements must be of type INTEGER. (let ((low 0) (high 0)) ; wlog! (dolist (x (rest type) (yes)) (unless (typep x 'INTEGER) (return (no))) (setq low (min low x) high (max high x))))) (EQL ; (EQL object) (let ((x (second type))) (if (typep x 'INTEGER) (let ((low (min 0 x)) (high (max 0 x))) (yes)) (no)))) (OR ; (OR type*) ;; Every type must be subtype of INTEGER. (let ((low 0) (high 0)) ; wlog! (dolist (type1 (rest type) (yes)) (multiple-value-bind (low1 high1) (subtype-integer type1) (unless low1 (return (no))) (setq low (if (or (eq low '*) (eq low1 '*)) '* (min low low1)) high (if (or (eq high '*) (eq high1 '*)) '* (max high high1))))))) (AND ; (AND type*) ;; If one of the types is subtype of INTEGER, then yes, ;; otherwise unknown. (let ((low nil) (high nil)) (dolist (type1 (rest type)) (multiple-value-bind (low1 high1) (subtype-integer type1) (when low1 (if low (setq low (if (eq low '*) low1 (if (eq low1 '*) low (max low low1))) high (if (eq high '*) high1 (if (eq high1 '*) high (min high high1)))) (setq low low1 high high1))))) (if low (progn (when (and (numberp low) (numberp high) (not (<= low high))) (setq low 0 high 0)) ; type equivalent to NIL (yes)) (unknown)))) (INTEGER (let ((low (if (rest type) (second type) '*)) (high (if (cddr type) (third type) '*))) (when (consp low) (setq low (first low)) (when (numberp low) (incf low))) (when (consp high) (setq high (first high)) (when (numberp high) (decf high))) (when (and (numberp low) (numberp high) (not (<= low high))) (setq low 0 high 0)) ; type equivalent to NIL (yes))) (INTERVALS (if (eq (second type) 'INTEGER) (let ((low (third type)) (high (car (last type)))) (when (consp low) (setq low (first low)) (when (numberp low) (incf low))) (when (consp high) (setq high (first high)) (when (numberp high) (decf high))) (yes)) (unknown))) (MOD ; (MOD n) (let ((n (second type))) (unless (and (integerp n) (>= n 0)) (typespec-error 'subtypep type)) (if (eql n 0) (no) (let ((low 0) (high (1- n))) (yes))))) (SIGNED-BYTE ; (SIGNED-BYTE &optional s) (let ((s (if (cdr type) (second type) '*))) (if (eq s '*) (let ((low '*) (high '*)) (yes)) (progn (unless (and (integerp s) (plusp s)) (typespec-error 'subtypep type)) (let ((n (ash 1 (1- s)))) ; (ash 1 *) == (expt 2 *) (let ((low (- n)) (high (1- n))) (yes))))))) (UNSIGNED-BYTE ; (UNSIGNED-BYTE &optional s) (let ((s (if (cdr type) (second type) '*))) (if (eq s '*) (let ((low 0) (high '*)) (yes)) (progn (unless (and (integerp s) (>= s 0)) (typespec-error 'subtypep type)) (let ((n (ash 1 s))) ; (ash 1 *) == (expt 2 *) (let ((low 0) (high (1- n))) (yes))))))) (t (no)))) ((clos::defined-class-p type) (if (and (clos::built-in-class-p type) (eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type)) (return-from subtype-integer (subtype-integer (clos:class-name type))) (no))) ((clos::eql-specializer-p type) (let ((x (clos::eql-specializer-singleton type))) (if (typep x 'INTEGER) (let ((low (min 0 x)) (high (max 0 x))) (yes)) (no)))) ((encodingp type) (no)) (t (typespec-error 'subtypep type))))) #| TODO: Fix subtype-integer such that this works. Henry Baker: (defun type-null (x) (values (and (eq 'bit (upgraded-array-element-type `(or bit ,x))) (not (typep 0 x)) (not (typep 1 x))) t)) (type-null '(and symbol number)) (type-null '(and integer symbol)) (type-null '(and integer character)) |# ;; Determines a sequence kind (an atom, as defined in defseq.lisp: one of ;; LIST - stands for LIST ;; VECTOR - stands for (VECTOR T) ;; STRING - stands for (VECTOR CHARACTER) ;; 1, 2, 4, 8, 16, 32 - stands for (VECTOR (UNSIGNED-BYTE n)) ;; 0 - stands for (VECTOR NIL)) ;; that indicates the sequence type meant by the given type. Other possible ;; return values are ;; SEQUENCE - denoting a type whose intersection with (OR LIST VECTOR) is not ;; subtype of LIST or VECTOR, or ;; NIL - indicating a type whose intersection with (OR LIST VECTOR) is empty. ;; When the type is (OR (VECTOR eltype1) ... (VECTOR eltypeN)), the chosen ;; element type is the smallest element type that contains all of eltype1 ... ;; eltypeN. ;; ;; User-defined sequence types are not supported here. ;; ;; This implementation inlines the (tail-recursive) canonicalize-type ;; function. Its advantage is that it doesn't cons as much. Also it employs ;; some heuristics and does not have the full power of SUBTYPEP. (defun subtype-sequence (type) (setq type (expand-deftype type)) (cond ((symbolp type) (case type ((LIST CONS NULL) 'LIST) ((NIL) 'NIL) ((BIT-VECTOR SIMPLE-BIT-VECTOR) '1) ((STRING SIMPLE-STRING BASE-STRING SIMPLE-BASE-STRING) 'STRING) ((VECTOR SIMPLE-VECTOR ARRAY SIMPLE-ARRAY) 'VECTOR) ((SEQUENCE) 'SEQUENCE) (t 'NIL))) ((and (consp type) (symbolp (first type))) (unless (and (list-length type) (null (cdr (last type)))) (typespec-error 'subtypep type)) (case (first type) (MEMBER ; (MEMBER &rest objects) (let ((kind 'NIL)) (dolist (x (rest type)) (setq kind (sequence-type-union kind (type-of-sequence x)))) kind)) (EQL ; (EQL object) (unless (eql (length type) 2) (typespec-error 'subtypep type)) (type-of-sequence (second type))) (OR ; (OR type*) (let ((kind 'NIL)) (dolist (x (rest type)) (setq kind (sequence-type-union kind (subtype-sequence x)))) kind)) (AND ; (AND type*) (let ((kind 'SEQUENCE)) (dolist (x (rest type)) (setq kind (sequence-type-intersection kind (subtype-sequence x)))) kind)) ((SIMPLE-BIT-VECTOR BIT-VECTOR) ; (SIMPLE-BIT-VECTOR &optional size) (when (cddr type) (typespec-error 'subtypep type)) '1) ((SIMPLE-STRING STRING SIMPLE-BASE-STRING BASE-STRING) ; (SIMPLE-STRING &optional size) (when (cddr type) (typespec-error 'subtypep type)) 'STRING) (SIMPLE-VECTOR ; (SIMPLE-VECTOR &optional size) (when (cddr type) (typespec-error 'subtypep type)) 'VECTOR) ((VECTOR ARRAY SIMPLE-ARRAY) ; (VECTOR &optional el-type size), (ARRAY &optional el-type dimensions) (when (cdddr type) (typespec-error 'subtypep type)) (let ((el-type (if (cdr type) (second type) '*))) (if (eq el-type '*) 'VECTOR (let ((eltype (upgraded-array-element-type el-type))) (cond ((eq eltype 'T) 'VECTOR) ((eq eltype 'CHARACTER) 'STRING) ((eq eltype 'BIT) '1) ((and (consp eltype) (eq (first eltype) 'UNSIGNED-BYTE)) (second eltype)) ((eq eltype 'NIL) '0) (t (error (TEXT "~S is not up-to-date with ~S for element type ~S") 'subtypep-sequence 'upgraded-array-element-type eltype))))))) ((CONS) ; (CONS &optional cartype cdrtype) (when (cdddr type) (typespec-error 'subtypep type)) 'LIST) (t 'NIL))) ((clos::defined-class-p type) (if (and (clos::built-in-class-p type) (eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type)) (subtype-sequence (clos:class-name type)) 'NIL)) ((clos::eql-specializer-p type) (type-of-sequence (clos::eql-specializer-singleton type))) (t 'NIL))) (defun type-of-sequence (x) (cond ((listp x) 'LIST) ((vectorp x) (let ((eltype (array-element-type x))) (cond ((eq eltype 'T) 'VECTOR) ((eq eltype 'CHARACTER) 'STRING) ((eq eltype 'BIT) '1) ((and (consp eltype) (eq (first eltype) 'UNSIGNED-BYTE)) (second eltype)) ((eq eltype 'NIL) '0) (t (error (TEXT "~S is not up-to-date with ~S for element type ~S") 'type-of-sequence 'array-element-type eltype))))) (t 'NIL))) (defun sequence-type-union (t1 t2) (cond ; Simple general rules. ((eql t1 t2) t1) ((eq t1 'NIL) t2) ((eq t2 'NIL) t1) ; Now the union of two different types. ((or (eq t1 'SEQUENCE) (eq t2 'SEQUENCE)) 'SEQUENCE) ((or (eq t1 'LIST) (eq t2 'LIST)) ; union of LIST and a vector type 'SEQUENCE) ((or (eq t1 'VECTOR) (eq t2 'VECTOR)) 'VECTOR) ((eql t1 0) t2) ((eql t2 0) t1) ((or (eq t1 'STRING) (eq t2 'STRING)) ; union of STRING and an integer-vector type 'VECTOR) (t (max t1 t2)))) (defun sequence-type-intersection (t1 t2) (cond ; Simple general rules. ((eql t1 t2) t1) ((or (eq t1 'NIL) (eq t2 'NIL)) 'NIL) ; Now the intersection of two different types. ((eq t1 'SEQUENCE) t2) ((eq t2 'SEQUENCE) t1) ((or (eq t1 'LIST) (eq t2 'LIST)) ; intersection of LIST and a vector type 'NIL) ((eq t1 'VECTOR) t2) ((eq t2 'VECTOR) t1) ((or (eql t1 0) (eql t2 0)) '0) ((or (eq t1 'STRING) (eq t2 'STRING)) ; intersection of STRING and an integer-vector type '0) (t (min t1 t2)))) ;; ============================================================================ (defun type-expand (typespec &optional once-p) (multiple-value-bind (expanded user-defined-p) (expand-deftype typespec once-p) (if user-defined-p (values expanded user-defined-p) (cond ((symbolp typespec) (cond ((or (get typespec 'TYPE-SYMBOL) (get typespec 'TYPE-LIST)) (values typespec nil)) ((or (get typespec 'DEFSTRUCT-DESCRIPTION) (clos-class typespec)) (values typespec nil)) (t (typespec-error 'type-expand typespec)))) ((and (consp typespec) (symbolp (first typespec))) (case (first typespec) ((SATISFIES MEMBER EQL NOT AND OR) (values typespec nil)) (t (cond ((get (first typespec) 'TYPE-LIST) (values typespec nil)) (t (typespec-error 'type-expand typespec)))))) ((clos::defined-class-p typespec) (values typespec nil)) (t (typespec-error 'type-expand typespec)))))) ;; ============================================================================ (unless (clos::funcallable-instance-p #'clos::class-name) (fmakunbound 'clos::class-name)) (keywordp :junk) T (keywordp ::junk) T (symbol-name ::junk) "JUNK" (symbol-name :#junk) "#JUNK" (symbol-name :#.junk) "#.JUNK" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/underscore.coffee000066400000000000000000000466721250413007300272310ustar00rootroot00000000000000 # Underscore.coffee # (c) 2010 Jeremy Ashkenas, DocumentCloud Inc. # Underscore is freely distributable under the terms of the MIT license. # Portions of Underscore are inspired by or borrowed from Prototype.js, # Oliver Steele's Functional, and John Resig's Micro-Templating. # For all details and documentation: # http://documentcloud.github.com/underscore/ # ------------------------- Baseline setup --------------------------------- # Establish the root object, "window" in the browser, or "global" on the server. root: this # Save the previous value of the "_" variable. previousUnderscore: root._ # If Underscore is called as a function, it returns a wrapped object that # can be used OO-style. This wrapper holds altered versions of all the # underscore functions. Wrapped objects may be chained. wrapper: (obj) -> this._wrapped: obj this # Establish the object that gets thrown to break out of a loop iteration. breaker: if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration # Create a safe reference to the Underscore object forreference below. _: root._: (obj) -> new wrapper(obj) # Export the Underscore object for CommonJS. if typeof(exports) != 'undefined' then exports._: _ # Create quick reference variables for speed access to core prototypes. slice: Array::slice unshift: Array::unshift toString: Object::toString hasOwnProperty: Object::hasOwnProperty propertyIsEnumerable: Object::propertyIsEnumerable # Current version. _.VERSION: '0.5.7' # ------------------------ Collection Functions: --------------------------- # The cornerstone, an each implementation. # Handles objects implementing forEach, arrays, and raw objects. _.each: (obj, iterator, context) -> index: 0 try return obj.forEach(iterator, context) if obj.forEach if _.isArray(obj) or _.isArguments(obj) return iterator.call(context, obj[i], i, obj) for i in [0...obj.length] iterator.call(context, val, key, obj) for key, val of obj catch e throw e if e isnt breaker obj # Return the results of applying the iterator to each element. Use JavaScript # 1.6's version of map, if possible. _.map: (obj, iterator, context) -> return obj.map(iterator, context) if (obj and _.isFunction(obj.map)) results: [] _.each obj, (value, index, list) -> results.push(iterator.call(context, value, index, list)) results # Reduce builds up a single result from a list of values. Also known as # inject, or foldl. Uses JavaScript 1.8's version of reduce, if possible. _.reduce: (obj, memo, iterator, context) -> return obj.reduce(_.bind(iterator, context), memo) if (obj and _.isFunction(obj.reduce)) _.each obj, (value, index, list) -> memo: iterator.call(context, memo, value, index, list) memo # The right-associative version of reduce, also known as foldr. Uses # JavaScript 1.8's version of reduceRight, if available. _.reduceRight: (obj, memo, iterator, context) -> return obj.reduceRight(_.bind(iterator, context), memo) if (obj and _.isFunction(obj.reduceRight)) _.each _.clone(_.toArray(obj)).reverse(), (value, index) -> memo: iterator.call(context, memo, value, index, obj) memo # Return the first value which passes a truth test. _.detect: (obj, iterator, context) -> result: null _.each obj, (value, index, list) -> if iterator.call(context, value, index, list) result: value _.breakLoop() result # Return all the elements that pass a truth test. Use JavaScript 1.6's # filter(), if it exists. _.select: (obj, iterator, context) -> if obj and _.isFunction(obj.filter) then return obj.filter(iterator, context) results: [] _.each obj, (value, index, list) -> results.push(value) if iterator.call(context, value, index, list) results # Return all the elements for which a truth test fails. _.reject: (obj, iterator, context) -> results: [] _.each obj, (value, index, list) -> results.push(value) if not iterator.call(context, value, index, list) results # Determine whether all of the elements match a truth test. Delegate to # JavaScript 1.6's every(), if it is present. _.all: (obj, iterator, context) -> iterator ||= _.identity return obj.every(iterator, context) if obj and _.isFunction(obj.every) result: true _.each obj, (value, index, list) -> _.breakLoop() unless (result: result and iterator.call(context, value, index, list)) result # Determine if at least one element in the object matches a truth test. Use # JavaScript 1.6's some(), if it exists. _.any: (obj, iterator, context) -> iterator ||= _.identity return obj.some(iterator, context) if obj and _.isFunction(obj.some) result: false _.each obj, (value, index, list) -> _.breakLoop() if (result: iterator.call(context, value, index, list)) result # Determine if a given value is included in the array or object, # based on '==='. _.include: (obj, target) -> return _.indexOf(obj, target) isnt -1 if _.isArray(obj) for key, val of obj return true if val is target false # Invoke a method with arguments on every item in a collection. _.invoke: (obj, method) -> args: _.rest(arguments, 2) (if method then val[method] else val).apply(val, args) for val in obj # Convenience version of a common use case of map: fetching a property. _.pluck: (obj, key) -> _.map(obj, ((val) -> val[key])) # Return the maximum item or (item-based computation). _.max: (obj, iterator, context) -> return Math.max.apply(Math, obj) if not iterator and _.isArray(obj) result: {computed: -Infinity} _.each obj, (value, index, list) -> computed: if iterator then iterator.call(context, value, index, list) else value computed >= result.computed and (result: {value: value, computed: computed}) result.value # Return the minimum element (or element-based computation). _.min: (obj, iterator, context) -> return Math.min.apply(Math, obj) if not iterator and _.isArray(obj) result: {computed: Infinity} _.each obj, (value, index, list) -> computed: if iterator then iterator.call(context, value, index, list) else value computed < result.computed and (result: {value: value, computed: computed}) result.value # Sort the object's values by a criteria produced by an iterator. _.sortBy: (obj, iterator, context) -> _.pluck(((_.map obj, (value, index, list) -> {value: value, criteria: iterator.call(context, value, index, list)} ).sort((left, right) -> a: left.criteria; b: right.criteria if a < b then -1 else if a > b then 1 else 0 )), 'value') # Use a comparator function to figure out at what index an object should # be inserted so as to maintain order. Uses binary search. _.sortedIndex: (array, obj, iterator) -> iterator ||= _.identity low: 0; high: array.length while low < high mid: (low + high) >> 1 if iterator(array[mid]) < iterator(obj) then low: mid + 1 else high: mid low # Convert anything iterable into a real, live array. _.toArray: (iterable) -> return [] if (!iterable) return iterable.toArray() if (iterable.toArray) return iterable if (_.isArray(iterable)) return slice.call(iterable) if (_.isArguments(iterable)) _.values(iterable) # Return the number of elements in an object. _.size: (obj) -> _.toArray(obj).length # -------------------------- Array Functions: ------------------------------ # Get the first element of an array. Passing "n" will return the first N # values in the array. Aliased as "head". The "guard" check allows it to work # with _.map. _.first: (array, n, guard) -> if n and not guard then slice.call(array, 0, n) else array[0] # Returns everything but the first entry of the array. Aliased as "tail". # Especially useful on the arguments object. Passing an "index" will return # the rest of the values in the array from that index onward. The "guard" # check allows it to work with _.map. _.rest: (array, index, guard) -> slice.call(array, if _.isUndefined(index) or guard then 1 else index) # Get the last element of an array. _.last: (array) -> array[array.length - 1] # Trim out all falsy values from an array. _.compact: (array) -> array[i] for i in [0...array.length] when array[i] # Return a completely flattened version of an array. _.flatten: (array) -> _.reduce array, [], (memo, value) -> return memo.concat(_.flatten(value)) if _.isArray(value) memo.push(value) memo # Return a version of the array that does not contain the specified value(s). _.without: (array) -> values: _.rest(arguments) val for val in _.toArray(array) when not _.include(values, val) # Produce a duplicate-free version of the array. If the array has already # been sorted, you have the option of using a faster algorithm. _.uniq: (array, isSorted) -> memo: [] for el, i in _.toArray(array) memo.push(el) if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el)) memo # Produce an array that contains every item shared between all the # passed-in arrays. _.intersect: (array) -> rest: _.rest(arguments) _.select _.uniq(array), (item) -> _.all rest, (other) -> _.indexOf(other, item) >= 0 # Zip together multiple lists into a single array -- elements that share # an index go together. _.zip: -> length: _.max(_.pluck(arguments, 'length')) results: new Array(length) for i in [0...length] results[i]: _.pluck(arguments, String(i)) results # If the browser doesn't supply us with indexOf (I'm looking at you, MSIE), # we need this function. Return the position of the first occurence of an # item in an array, or -1 if the item is not included in the array. _.indexOf: (array, item) -> return array.indexOf(item) if array.indexOf i: 0; l: array.length while l - i if array[i] is item then return i else i++ -1 # Provide JavaScript 1.6's lastIndexOf, delegating to the native function, # if possible. _.lastIndexOf: (array, item) -> return array.lastIndexOf(item) if array.lastIndexOf i: array.length while i if array[i] is item then return i else i-- -1 # Generate an integer Array containing an arithmetic progression. A port of # the native Python range() function. See: # http://docs.python.org/library/functions.html#range _.range: (start, stop, step) -> a: arguments solo: a.length <= 1 i: start: if solo then 0 else a[0]; stop: if solo then a[0] else a[1]; step: a[2] or 1 len: Math.ceil((stop - start) / step) return [] if len <= 0 range: new Array(len) idx: 0 while true return range if (if step > 0 then i - stop else stop - i) >= 0 range[idx]: i idx++ i+= step # ----------------------- Function Functions: ----------------------------- # Create a function bound to a given object (assigning 'this', and arguments, # optionally). Binding with arguments is also known as 'curry'. _.bind: (func, obj) -> args: _.rest(arguments, 2) -> func.apply(obj or root, args.concat(arguments)) # Bind all of an object's methods to that object. Useful for ensuring that # all callbacks defined on an object belong to it. _.bindAll: (obj) -> funcs: if arguments.length > 1 then _.rest(arguments) else _.functions(obj) _.each(funcs, (f) -> obj[f]: _.bind(obj[f], obj)) obj # Delays a function for the given number of milliseconds, and then calls # it with the arguments supplied. _.delay: (func, wait) -> args: _.rest(arguments, 2) setTimeout((-> func.apply(func, args)), wait) # Defers a function, scheduling it to run after the current call stack has # cleared. _.defer: (func) -> _.delay.apply(_, [func, 1].concat(_.rest(arguments))) # Returns the first function passed as an argument to the second, # allowing you to adjust arguments, run code before and after, and # conditionally execute the original function. _.wrap: (func, wrapper) -> -> wrapper.apply(wrapper, [func].concat(arguments)) # Returns a function that is the composition of a list of functions, each # consuming the return value of the function that follows. _.compose: -> funcs: arguments -> args: arguments for i in [(funcs.length - 1)..0] args: [funcs[i].apply(this, args)] args[0] # ------------------------- Object Functions: ---------------------------- # Retrieve the names of an object's properties. _.keys: (obj) -> return _.range(0, obj.length) if _.isArray(obj) key for key, val of obj # Retrieve the values of an object's properties. _.values: (obj) -> _.map(obj, _.identity) # Return a sorted list of the function names available in Underscore. _.functions: (obj) -> _.select(_.keys(obj), (key) -> _.isFunction(obj[key])).sort() # Extend a given object with all of the properties in a source object. _.extend: (destination, source) -> for key, val of source destination[key]: val destination # Create a (shallow-cloned) duplicate of an object. _.clone: (obj) -> return obj.slice(0) if _.isArray(obj) _.extend({}, obj) # Invokes interceptor with the obj, and then returns obj. # The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. _.tap: (obj, interceptor) -> interceptor(obj) obj # Perform a deep comparison to check if two objects are equal. _.isEqual: (a, b) -> # Check object identity. return true if a is b # Different types? atype: typeof(a); btype: typeof(b) return false if atype isnt btype # Basic equality test (watch out for coercions). return true if `a == b` # One is falsy and the other truthy. return false if (!a and b) or (a and !b) # One of them implements an isEqual()? return a.isEqual(b) if a.isEqual # Check dates' integer values. return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b) # Both are NaN? return true if _.isNaN(a) and _.isNaN(b) # Compare regular expressions. if _.isRegExp(a) and _.isRegExp(b) return a.source is b.source and a.global is b.global and a.ignoreCase is b.ignoreCase and a.multiline is b.multiline # If a is not an object by this point, we can't handle it. return false if atype isnt 'object' # Check for different array lengths before comparing contents. return false if a.length and (a.length isnt b.length) # Nothing else worked, deep compare the contents. aKeys: _.keys(a); bKeys: _.keys(b) # Different object sizes? return false if aKeys.length isnt bKeys.length # Recursive comparison of contents. # for (var key in a) if (!_.isEqual(a[key], b[key])) return false; return true # Is a given array or object empty? _.isEmpty: (obj) -> _.keys(obj).length is 0 # Is a given value a DOM element? _.isElement: (obj) -> obj and obj.nodeType is 1 # Is a given value an array? _.isArray: (obj) -> !!(obj and obj.concat and obj.unshift) # Is a given variable an arguments object? _.isArguments: (obj) -> obj and _.isNumber(obj.length) and not obj.concat and not obj.substr and not obj.apply and not propertyIsEnumerable.call(obj, 'length') # Is the given value a function? _.isFunction: (obj) -> !!(obj and obj.constructor and obj.call and obj.apply) # Is the given value a string? _.isString: (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr)) # Is a given value a number? _.isNumber: (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]' # Is a given value a Date? _.isDate: (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear) # Is the given value a regular expression? _.isRegExp: (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false)) # Is the given value NaN -- this one is interesting. NaN != NaN, and # isNaN(undefined) == true, so we make sure it's a number first. _.isNaN: (obj) -> _.isNumber(obj) and window.isNaN(obj) # Is a given value equal to null? _.isNull: (obj) -> obj is null # Is a given variable undefined? _.isUndefined: (obj) -> typeof obj is 'undefined' # -------------------------- Utility Functions: -------------------------- # Run Underscore.js in noConflict mode, returning the '_' variable to its # previous owner. Returns a reference to the Underscore object. _.noConflict: -> root._: previousUnderscore this # Keep the identity function around for default iterators. _.identity: (value) -> value # Break out of the middle of an iteration. _.breakLoop: -> throw breaker # Generate a unique integer id (unique within the entire client session). # Useful for temporary DOM ids. idCounter: 0 _.uniqueId: (prefix) -> (prefix or '') + idCounter++ # By default, Underscore uses ERB-style template delimiters, change the # following template settings to use alternative delimiters. _.templateSettings: { start: '<%' end: '%>' interpolate: /<%=(.+?)%>/g } # JavaScript templating a-la ERB, pilfered from John Resig's # "Secrets of the JavaScript Ninja", page 83. # Single-quotea fix from Rick Strahl's version. _.template: (str, data) -> c: _.templateSettings fn: new Function 'obj', 'var p=[],print=function(){p.push.apply(p,arguments);};' + 'with(obj){p.push(\'' + str.replace(/[\r\t\n]/g, " ") .replace(new RegExp("'(?=[^"+c.end[0]+"]*"+c.end+")","g"),"\t") .split("'").join("\\'") .split("\t").join("'") .replace(c.interpolate, "',$1,'") .split(c.start).join("');") .split(c.end).join("p.push('") + "');}return p.join('');" if data then fn(data) else fn # ------------------------------- Aliases ---------------------------------- _.forEach: _.each _.foldl: _.inject: _.reduce _.foldr: _.reduceRight _.filter: _.select _.every: _.all _.some: _.any _.head: _.first _.tail: _.rest _.methods: _.functions # /*------------------------ Setup the OOP Wrapper: --------------------------*/ # Helper function to continue chaining intermediate results. result: (obj, chain) -> if chain then _(obj).chain() else obj # Add all of the Underscore functions to the wrapper object. _.each _.functions(_), (name) -> method: _[name] wrapper.prototype[name]: -> unshift.call(arguments, this._wrapped) result(method.apply(_, arguments), this._chain) # Add all mutator Array functions to the wrapper. _.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) -> method: Array.prototype[name] wrapper.prototype[name]: -> method.apply(this._wrapped, arguments) result(this._wrapped, this._chain) # Add all accessor Array functions to the wrapper. _.each ['concat', 'join', 'slice'], (name) -> method: Array.prototype[name] wrapper.prototype[name]: -> result(method.apply(this._wrapped, arguments), this._chain) # Start chaining a wrapped Underscore object. wrapper::chain: -> this._chain: true this # Extracts the result from a wrapped and chained object. wrapper::value: -> this._wrapped pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/unicode.applescript000066400000000000000000000001571250413007300275710ustar00rootroot00000000000000set jp to "日本語" set ru to "РуÑÑкий" jp & " and " & ru -- returns "日本語 and РуÑÑкий" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/unicode.go000066400000000000000000000002541250413007300256460ustar00rootroot00000000000000package main import "fmt" func main() { 世界 := "Hello, world!" ã•よã†ãªã‚‰ := "Goodbye, world!" fmt.Println(世界) fmt.Println(ã•よã†ãªã‚‰) } pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/unicodedoc.py000066400000000000000000000001711250413007300263550ustar00rootroot00000000000000def foo(): ur"""unicode-raw""" def bar(): u"""unicode""" def baz(): r'raw' def zap(): """docstring""" pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/unix-io.lid000066400000000000000000000017131250413007300257540ustar00rootroot00000000000000Library: io Synopsis: A portable IO library Author: Gail Zacharias Files: library streams/defs streams/stream streams/sequence-stream streams/native-buffer streams/buffer streams/typed-stream streams/external-stream streams/buffered-stream streams/convenience streams/wrapper-stream streams/cleanup-streams streams/native-speed streams/async-writes streams/file-stream streams/multi-buffered-streams pprint print print-double-integer-kludge format buffered-format format-condition unix-file-accessor unix-standard-io unix-interface format-out C-Source-Files: unix-portability.c Major-Version: 2 Minor-Version: 1 Target-Type: dll Copyright: Original Code is Copyright (c) 1995-2004 Functional Objects, Inc. All rights reserved. License: See License.txt in this distribution for details. Warranty: Distributed WITHOUT WARRANTY OF ANY KIND pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/vbnet_test.bas000066400000000000000000000015161250413007300265370ustar00rootroot00000000000000Public Class Form1 Inherits System.Windows.Forms.Form Private t As New System.Timers.Timer(2000) Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Load AddHandler t.Elapsed, AddressOf TimerFired End Sub Private Sub btnStart_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStart.Click t.Enabled = True End Sub Private Sub btnStop_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStop.Click t.Enabled = False End Sub Public Sub TimerFired(ByVal sender As Object, _ ByVal e As System.Timers.ElapsedEventArgs) Label1.Text = "Signal Time = " & e.SignalTime.ToString End Sub End Class pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/vctreestatus_hg000066400000000000000000000000631250413007300270240ustar00rootroot00000000000000M LICENSE M setup.py ! setup.cfg ? vctreestatus_hg pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/vimrc000066400000000000000000000004061250413007300247330ustar00rootroot00000000000000" A comment :py print "py" ::pyt print 'pyt' pyth print '''pyth''' : pytho print "pytho" python print """python""" : : python<, .5 } #declare Index2 = Index2 + 1; #end #declare Index1 = Index1 + 1; #end pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/wiki.factor000066400000000000000000000237221250413007300260410ustar00rootroot00000000000000! Copyright (C) 2008 Slava Pestov ! See http://factorcode.org/license.txt for BSD license. USING: accessors kernel hashtables calendar random assocs namespaces make splitting sequences sorting math.order present io.files io.directories io.encodings.ascii syndication farkup html.components html.forms http.server http.server.dispatchers furnace.actions furnace.utilities furnace.redirection furnace.auth furnace.auth.login furnace.boilerplate furnace.syndication validators db.types db.tuples lcs urls ; IN: webapps.wiki : wiki-url ( rest path -- url ) [ "$wiki/" % % "/" % present % ] "" make swap >>path ; : view-url ( title -- url ) "view" wiki-url ; : edit-url ( title -- url ) "edit" wiki-url ; : revisions-url ( title -- url ) "revisions" wiki-url ; : revision-url ( id -- url ) "revision" wiki-url ; : user-edits-url ( author -- url ) "user-edits" wiki-url ; TUPLE: wiki < dispatcher ; SYMBOL: can-delete-wiki-articles? can-delete-wiki-articles? define-capability TUPLE: article title revision ; article "ARTICLES" { { "title" "TITLE" { VARCHAR 256 } +not-null+ +user-assigned-id+ } { "revision" "REVISION" INTEGER +not-null+ } ! revision id } define-persistent :
    ( title -- article ) article new swap >>title ; TUPLE: revision id title author date content description ; revision "REVISIONS" { { "id" "ID" INTEGER +db-assigned-id+ } { "title" "TITLE" { VARCHAR 256 } +not-null+ } ! article id { "author" "AUTHOR" { VARCHAR 256 } +not-null+ } ! uid { "date" "DATE" TIMESTAMP +not-null+ } { "content" "CONTENT" TEXT +not-null+ } { "description" "DESCRIPTION" TEXT } } define-persistent M: revision feed-entry-title [ title>> ] [ drop " by " ] [ author>> ] tri 3append ; M: revision feed-entry-date date>> ; M: revision feed-entry-url id>> revision-url ; : reverse-chronological-order ( seq -- sorted ) [ date>> ] inv-sort-with ; : ( id -- revision ) revision new swap >>id ; : validate-title ( -- ) { { "title" [ v-one-line ] } } validate-params ; : validate-author ( -- ) { { "author" [ v-username ] } } validate-params ; : ( responder -- responder' ) { wiki "page-common" } >>template ; : ( -- action ) [ "Front Page" view-url ] >>display ; : latest-revision ( title -- revision/f )
    select-tuple dup [ revision>> select-tuple ] when ; : ( -- action ) "title" >>rest [ validate-title ] >>init [ "title" value dup latest-revision [ from-object { wiki "view" } ] [ edit-url ] ?if ] >>display ; : ( -- action ) "id" >>rest [ validate-integer-id "id" value select-tuple from-object ] >>init { wiki "view" } >>template ; : ( -- action ) [ article new select-tuples random [ title>> ] [ "Front Page" ] if* view-url ] >>display ; : amend-article ( revision article -- ) swap id>> >>revision update-tuple ; : add-article ( revision -- ) [ title>> ] [ id>> ] bi article boa insert-tuple ; : add-revision ( revision -- ) [ insert-tuple ] [ dup title>>
    select-tuple [ amend-article ] [ add-article ] if* ] bi ; : ( -- action ) "title" >>rest [ validate-title "title" value
    select-tuple [ revision>> select-tuple ] [ f "title" value >>title ] if* [ title>> "title" set-value ] [ content>> "content" set-value ] bi ] >>init { wiki "edit" } >>template ; : ( -- action ) [ validate-title { { "content" [ v-required ] } { "description" [ [ v-one-line ] v-optional ] } } validate-params f "title" value >>title now >>date username >>author "content" value >>content "description" value >>description [ add-revision ] [ title>> view-url ] bi ] >>submit "edit wiki articles" >>description ; : ( responder -- responder ) { wiki "revisions-common" } >>template ; : list-revisions ( -- seq ) f "title" value >>title select-tuples reverse-chronological-order ; : ( -- action ) "title" >>rest [ validate-title list-revisions "revisions" set-value ] >>init { wiki "revisions" } >>template ; : ( -- action ) "title" >>rest [ validate-title ] >>init [ "Revisions of " "title" value append ] >>title [ "title" value revisions-url ] >>url [ list-revisions ] >>entries ; : rollback-description ( description -- description' ) [ "Rollback of '" "'" surround ] [ "Rollback" ] if* ; : ( -- action ) [ validate-integer-id ] >>validate [ "id" value select-tuple f >>id now >>date username >>author [ rollback-description ] change-description [ add-revision ] [ title>> revisions-url ] bi ] >>submit "rollback wiki articles" >>description ; : list-changes ( -- seq ) f select-tuples reverse-chronological-order ; : ( -- action ) [ list-changes "revisions" set-value ] >>init { wiki "changes" } >>template ; : ( -- action ) [ URL" $wiki/changes" ] >>url [ "All changes" ] >>title [ list-changes ] >>entries ; : ( -- action ) [ validate-title ] >>validate [ "title" value
    delete-tuples f "title" value >>title delete-tuples URL" $wiki" ] >>submit "delete wiki articles" >>description { can-delete-wiki-articles? } >>capabilities ; : ( -- action ) [ { { "old-id" [ v-integer ] } { "new-id" [ v-integer ] } } validate-params "old-id" "new-id" [ value select-tuple ] bi@ [ over title>> "title" set-value [ "old" [ from-object ] nest-form ] [ "new" [ from-object ] nest-form ] bi* ] [ [ content>> string-lines ] bi@ diff "diff" set-value ] 2bi ] >>init { wiki "diff" } >>template ; : ( -- action ) [ f
    select-tuples [ title>> ] sort-with "articles" set-value ] >>init { wiki "articles" } >>template ; : list-user-edits ( -- seq ) f "author" value >>author select-tuples reverse-chronological-order ; : ( -- action ) "author" >>rest [ validate-author list-user-edits "revisions" set-value ] >>init { wiki "user-edits" } >>template ; : ( -- action ) "author" >>rest [ validate-author ] >>init [ "Edits by " "author" value append ] >>title [ "author" value user-edits-url ] >>url [ list-user-edits ] >>entries ; : init-sidebars ( -- ) "Contents" latest-revision [ "contents" [ from-object ] nest-form ] when* "Footer" latest-revision [ "footer" [ from-object ] nest-form ] when* ; : init-relative-link-prefix ( -- ) URL" $wiki/view/" adjust-url present relative-link-prefix set ; : ( -- dispatcher ) wiki new-dispatcher "" add-responder "view" add-responder "revision" add-responder "random" add-responder "revisions" add-responder "revisions.atom" add-responder "diff" add-responder "edit" add-responder "submit" add-responder "rollback" add-responder "user-edits" add-responder "articles" add-responder "changes" add-responder "user-edits.atom" add-responder "changes.atom" add-responder "delete" add-responder [ init-sidebars init-relative-link-prefix ] >>init { wiki "wiki-common" } >>template ; : init-wiki ( -- ) "resource:extra/webapps/wiki/initial-content" [ [ dup ".txt" ?tail [ swap ascii file-contents f swap >>content swap >>title "slava" >>author now >>date add-revision ] [ 2drop ] if ] each ] with-directory-files ;pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/xml_example000066400000000000000000002453011250413007300261330ustar00rootroot00000000000000 abort abs abstract accept access aliased all and array at begin body constant declare delay delta digits do else elsif end entry exception exit for function generic goto in is limited mod new not null of or others out package pragma private procedure protected raise range rem record renames requeue return reverse separate subtype tagged task terminate then type until use when while with xor BEGIN END if else while do for in continue break print printf getline function return next exit ARGC ARGV CONVFMT ENVIRON FILENAME FNR FS NF NR OFMT OFS ORS RS RSTART RLENGTH SUBSEP gsub index length match split sprintf sub substr tolower toupper atan2 cos exp int log rand sin sqrt srand close fflush system break case else esac exit export for function in return select then until while . done do elif fi if cp date echo eval dcop dcopstart dcopfind break case continue default do else enum extern for goto if inline return sizeof struct switch typedef union while auto char const double float int long register restrict short signed static unsigned void volatile _Imaginary _Complex _Bool FIXME TODO ### aaa access-list address alias arp async-bootp banner boot bridge buffers busy-message call-history-mib cdp chat-script class-map clock cns config-register controller crypto default default-value dialer dialer-list dnsix-dmdp dnsix-nat downward-compatible-config enable end exception exit file frame-relay help hostname interface ip isdn isdn-mib kerberos key line logging login-string map-class map-list memory-size menu modemcap multilink netbios no ntp partition policy-map priority-list privilege process-max-time prompt queue-list resume-string rlogin rmon route-map router rtr scheduler service snmp-server sntp stackmaker state-machine subscriber-policy tacacs-server template terminal-queue tftp-server time-range username virtual-profile virtual-template vpdn vpdn-group x25 x29 accounting accounting-list accounting-threshold accounting-transits address-pool as-path audit auth-proxy authentication authorization bgp-community bootp cef classless community-list default-gateway default-network dhcp dhcp-server domain-list domain-lookup domain-name dvmrp exec-callback extcommunity-list finger flow-aggregation flow-cache flow-export forward-protocol ftp gratuitous-arps host host-routing hp-host http icmp inspect local mrm mroute msdp multicast multicast-routing name-server nat new-model ospf password password-encryption pgm pim port-map prefix-list radius rcmd reflexive-list route routing rsvp rtcp sap sdr security source-route subnet-zero tacacs tcp tcp-small-servers telnet tftp timestamps udp-small-servers vrf wccp accounting accounting-list accounting-threshold accounting-transits address-pool as-path audit auth-proxy authentication authorization bgp-community bootp cef classless community-list default-gateway default-network dhcp dhcp-server domain-list domain-lookup domain-name dvmrp exec-callback extcommunity-list finger flow-aggregation flow-cache flow-export forward-protocol ftp gratuitous-arps host host-routing hp-host http icmp inspect local mrm mroute msdp multicast multicast-routing name-server nat new-model ospf password password-encryption pgm pim port-map prefix-list radius rcmd reflexive-list route routing rsvp rtcp sap sdr security source-route subnet-zero tacacs tcp tcp-small-servers telnet tftp timestamps udp-small-servers vrf wccp if else for in while do continue break with try catch switch case new var function return this delete true false void throw typeof const default Anchor Applet Area Array Boolean Button Checkbox Date Document Event FileUpload Form Frame Function Hidden History Image Layer Linke Location Math Navigator Number Object Option Password Radio RegExp Reset Screen Select String Submit Text Textarea Window abs acos alert anchor apply asin atan atan2 back blur call captureEvents ceil charAt charCodeAt clearInterval clearTimeout click close compile concat confirm cos disableExternalCapture enableExternalCapture eval exec exp find floor focus forward fromCharCode getDate getDay getFullYear getHours getMilliseconds getMinutes getMonth getSeconds getSelection getTime getTimezoneOffset getUTCDate getUTCDay getUTCFullYear getUTCHours getUTCMilliseconds getUTCMinutes getUTCMonth getUTCSeconds go handleEvent home indexOf javaEnabled join lastIndexOf link load log match max min moveAbove moveBelow moveBy moveTo moveToAbsolute open parse plugins.refresh pop pow preference print prompt push random releaseEvents reload replace reset resizeBy resizeTo reverse round routeEvent scrollBy scrollTo search select setDate setFullYear setHours setInterval setMilliseconds setMinutes setMonth setSeconds setTime setTimeout setUTCDate setUTCFullYear setUTCHours setUTCMilliseconds setUTCMinutes setUTCMonth setUTCSeconds shift sin slice sort splice split sqrt stop String formatting submit substr substring taintEnabled tan test toLocaleString toLowerCase toSource toString toUpperCase toUTCString unshift unwatch UTC valueOf watch write writeln break case catch continue default do else for function if in return switch try var while Abs ACos ArrayAppend ArrayAvg ArrayClear ArrayDeleteAt ArrayInsertAt ArrayIsEmpty ArrayLen ArrayMax ArrayMin ArrayNew ArrayPrepend ArrayResize ArraySet ArraySort ArraySum ArraySwap ArrayToList Asc ASin Atn BitAnd BitMaskClear BitMaskRead BitMaskSet BitNot BitOr BitSHLN BitSHRN BitXor Ceiling Chr CJustify Compare CompareNoCase Cos CreateDate CreateDateTime CreateObject CreateODBCDate CreateODBCDateTime CreateODBCTime CreateTime CreateTimeSpan CreateUUID DateAdd DateCompare DateConvert DateDiff DateFormat DatePart Day DayOfWeek DayOfWeekAsString DayOfYear DaysInMonth DaysInYear DE DecimalFormat DecrementValue Decrypt DeleteClientVariable DirectoryExists DollarFormat Duplicate Encrypt Evaluate Exp ExpandPath FileExists Find FindNoCase FindOneOf FirstDayOfMonth Fix FormatBaseN GetAuthUser GetBaseTagData GetBaseTagList GetBaseTemplatePath GetClientVariablesList GetCurrentTemplatePath GetDirectoryFromPath GetException GetFileFromPath GetFunctionList GetHttpRequestData GetHttpTimeString GetK2ServerDocCount GetK2ServerDocCountLimit GetLocale GetMetaData GetMetricData GetPageContext GetProfileSections GetProfileString GetServiceSettings GetTempDirectory GetTempFile GetTemplatePath GetTickCount GetTimeZoneInfo GetToken Hash Hour HTMLCodeFormat HTMLEditFormat IIf IncrementValue InputBaseN Insert Int IsArray IsBinary IsBoolean IsCustomFunction IsDate IsDebugMode IsDefined IsK2ServerABroker IsK2ServerDocCountExceeded IsK2ServerOnline IsLeapYear IsNumeric IsNumericDate IsObject IsQuery IsSimpleValue IsStruct IsUserInRole IsWDDX IsXmlDoc IsXmlElement IsXmlRoot JavaCast JSStringFormat LCase Left Len ListAppend ListChangeDelims ListContains ListContainsNoCase ListDeleteAt ListFind ListFindNoCase ListFirst ListGetAt ListInsertAt ListLast ListLen ListPrepend ListQualify ListRest ListSetAt ListSort ListToArray ListValueCount ListValueCountNoCase LJustify Log Log10 LSCurrencyFormat LSDateFormat LSEuroCurrencyFormat LSIsCurrency LSIsDate LSIsNumeric LSNumberFormat LSParseCurrency LSParseDateTime LSParseEuroCurrency LSParseNumber LSTimeFormat LTrim Max Mid Min Minute Month MonthAsString Now NumberFormat ParagraphFormat ParameterExists ParseDateTime Pi PreserveSingleQuotes Quarter QueryAddColumn QueryAddRow QueryNew QuerySetCell QuotedValueList Rand Randomize RandRange REFind REFindNoCase RemoveChars RepeatString Replace ReplaceList ReplaceNoCase REReplace REReplaceNoCase Reverse Right RJustify Round RTrim Second SetEncoding SetLocale SetProfileString SetVariable Sgn Sin SpanExcluding SpanIncluding Sqr StripCR StructAppend StructClear StructCopy StructCount StructDelete StructFind StructFindKey StructFindValue StructGet StructInsert StructIsEmpty StructKeyArray StructKeyExists StructKeyList StructNew StructSort StructUpdate Tan TimeFormat ToBase64 ToBinary ToString Trim UCase URLDecode URLEncodedFormat URLSessionFormat Val ValueList Week WriteOutput XmlChildPos XmlElemNew XmlFormat XmlNew XmlParse XmlSearch XmlTransform Year YesNoFormat BEGIN BY CASE CLOSE CONST DO ELSE ELSIF END FOR IF IMPORT LOOP MODULE NEW OF OUT PROCEDURE REPEAT THEN TO TYPE UNTIL VAR WHILE WITH ASSERT EXIT HALT RETURN ANYPTR ANYREC ARRAY BOOLEAN SHORTCHAR CHAR BYTE SHORTINT INTEGER LONGINT POINTER RECORD SHORTREAL REAL SET ABSTRACT EMPTY EXTENSIBLE LIMITED ABS ASH BITS CAP CHR DEC ENTIER EXCL INC INCL LEN LONG MAX MIN ODD ORD SHORT SIZE FALSE INF NIL TRUE pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/zmlrpc.f90000066400000000000000000000660641250413007300255330ustar00rootroot00000000000000!!$ !!$ !!$ MD2P4 !!$ Multilevel Domain Decomposition Parallel Preconditioner Package for PSBLAS !!$ for !!$ Parallel Sparse BLAS v2.0 !!$ (C) Copyright 2006 Salvatore Filippone University of Rome Tor Vergata !!$ Alfredo Buttari University of Rome Tor Vergata !!$ Daniela Di Serafino II University of Naples !!$ Pasqua D'Ambra ICAR-CNR !!$ !!$ Redistribution and use in source and binary forms, with or without !!$ modification, are permitted provided that the following conditions !!$ are met: !!$ 1. Redistributions of source code must retain the above copyright !!$ notice, this list of conditions and the following disclaimer. !!$ 2. Redistributions in binary form must reproduce the above copyright !!$ notice, this list of conditions, and the following disclaimer in the !!$ documentation and/or other materials provided with the distribution. !!$ 3. The name of the MD2P4 group or the names of its contributors may !!$ not be used to endorse or promote products derived from this !!$ software without specific written permission. !!$ !!$ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS !!$ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED !!$ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR !!$ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE MD2P4 GROUP OR ITS CONTRIBUTORS !!$ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR !!$ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF !!$ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS !!$ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN !!$ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) !!$ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE !!$ POSSIBILITY OF SUCH DAMAGE. !!$ !!$ subroutine psb_zmlprc_aply(alpha,baseprecv,x,beta,y,desc_data,trans,work,info) ! ! Compute Y <- beta*Y + alpha*K^-1 X ! where K is a multilevel preconditioner stored in baseprecv ! ! cfr.: Smith, Biorstad & Gropp ! Domain Decomposition ! Cambridge Univ. Press ! ! To each level I there corresponds a matrix A(I) and a preconditioner K(I) ! ! A notational difference: in the DD reference above the preconditioner for ! a given level K(I) is written out as a sum over the subdomains ! ! SUM_k(R_k^T A_k R_k) ! ! whereas in this code the sum is implicit in the parallelization, ! i.e. each process takes care of one subdomain, and for each level we have ! as many subdomains as there are processes (except for the coarsest level where ! we might have a replicated index space). Thus the sum apparently disappears ! from our code, but only apparently, because it is implicit in the call ! to psb_baseprc_aply. ! ! A bit of description of the baseprecv(:) data structure: ! 1. Number of levels = NLEV = size(baseprecv(:)) ! 2. baseprecv(ilev)%av(:) sparse matrices needed for the current level. ! Includes: ! 2.1.: baseprecv(ilev)%av(l_pr_) L factor of ILU preconditioners ! 2.2.: baseprecv(ilev)%av(u_pr_) U factor of ILU preconditioners ! 2.3.: baseprecv(ilev)%av(ap_nd_) Off-diagonal part of A for Jacobi sweeps ! 2.4.: baseprecv(ilev)%av(ac_) Aggregated matrix of level ILEV ! 2.5.: baseprecv(ilev)%av(sm_pr_t_) Smoother prolongator transpose; maps vectors ! (ilev-1) ---> (ilev) ! 2.6.: baseprecv(ilev)%av(sm_pr_) Smoother prolongator; maps vectors ! (ilev) ---> (ilev-1) ! Shouldn't we keep just one of them and handle transpose in the sparse BLAS? maybe ! ! 3. baseprecv(ilev)%desc_data comm descriptor for level ILEV ! 4. baseprecv(ilev)%base_a Pointer (really a pointer!) to the base matrix ! of the current level, i.e.: if ILEV=1 then A ! else the aggregated matrix av(ac_); so we have ! a unified treatment of residuals. Need this to ! avoid passing explicitly matrix A to the ! outer prec. routine ! 5. baseprecv(ilev)%mlia The aggregation map from (ilev-1)-->(ilev) ! if no smoother, it is used instead of sm_pr_ ! 6. baseprecv(ilev)%nlaggr Number of aggregates on the various procs. ! use psb_serial_mod use psb_descriptor_type use psb_prec_type use psb_psblas_mod use psb_penv_mod use psb_const_mod use psb_error_mod use psb_penv_mod implicit none type(psb_desc_type),intent(in) :: desc_data type(psb_zbaseprc_type), intent(in) :: baseprecv(:) complex(kind(1.d0)),intent(in) :: alpha,beta complex(kind(1.d0)),intent(inout) :: x(:), y(:) character :: trans complex(kind(1.d0)),target :: work(:) integer, intent(out) :: info ! Local variables integer :: n_row,n_col complex(kind(1.d0)), allocatable :: tx(:),ty(:),t2l(:),w2l(:),& & x2l(:),b2l(:),tz(:),tty(:) character ::diagl, diagu integer :: ictxt,np,me,i, isz, nrg,nr2l,err_act, iptype, int_err(5) real(kind(1.d0)) :: omega real(kind(1.d0)) :: t1, t2, t3, t4, t5, t6, t7, mpi_wtime logical, parameter :: debug=.false., debugprt=.false. integer :: ismth, nlev, ilev external mpi_wtime character(len=20) :: name, ch_err type psb_mlprec_wrk_type complex(kind(1.d0)), pointer :: tx(:)=>null(),ty(:)=>null(),& & x2l(:)=>null(),y2l(:)=>null(),& & b2l(:)=>null(),tty(:)=>null() end type psb_mlprec_wrk_type type(psb_mlprec_wrk_type), pointer :: mlprec_wrk(:) interface psb_baseprc_aply subroutine psb_zbaseprc_aply(alpha,prec,x,beta,y,desc_data,trans,work,info) use psb_descriptor_type use psb_prec_type type(psb_desc_type),intent(in) :: desc_data type(psb_zbaseprc_type), intent(in) :: prec complex(kind(1.d0)),intent(inout) :: x(:), y(:) complex(kind(1.d0)),intent(in) :: alpha,beta character(len=1) :: trans complex(kind(1.d0)),target :: work(:) integer, intent(out) :: info end subroutine psb_zbaseprc_aply end interface name='psb_mlprc_aply' info = 0 call psb_erractionsave(err_act) ictxt=desc_data%matrix_data(psb_ctxt_) call psb_info(ictxt, me, np) nlev = size(baseprecv) allocate(mlprec_wrk(nlev),stat=info) if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if select case(baseprecv(2)%iprcparm(ml_type_)) case(no_ml_) ! Should not really get here. call psb_errpush(4010,name,a_err='no_ml_ in mlprc_aply?') goto 9999 case(add_ml_prec_) ! ! Additive is very simple. ! 1. X(1) = Xext ! 2. DO ILEV=2,NLEV ! X(ILEV) = AV(PR_SM_T_)*X(ILEV-1) ! 3. Y(ILEV) = (K(ILEV)**(-1))*X(ILEV) ! 4. DO ILEV=NLEV-1,1,-1 ! Y(ILEV) = AV(PR_SM_)*Y(ILEV+1) ! 5. Yext = beta*Yext + Y(1) ! ! Note: level numbering reversed wrt ref. DD, i.e. ! 1..NLEV <=> (j) <-> 0 call psb_baseprc_aply(alpha,baseprecv(1),x,beta,y,& & baseprecv(1)%base_desc,trans,work,info) if(info /=0) goto 9999 allocate(mlprec_wrk(1)%x2l(size(x)),mlprec_wrk(1)%y2l(size(y))) mlprec_wrk(1)%x2l(:) = x(:) do ilev = 2, nlev n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) allocate(mlprec_wrk(ilev)%x2l(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& & mlprec_wrk(ilev)%tx(max(n_row,n_col)),& & mlprec_wrk(ilev)%ty(max(n_row,n_col)), stat=info) if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if mlprec_wrk(ilev)%x2l(:) = zzero mlprec_wrk(ilev)%y2l(:) = zzero mlprec_wrk(ilev)%tx(1:n_row) = mlprec_wrk(ilev-1)%x2l(1:n_row) mlprec_wrk(ilev)%tx(n_row+1:max(n_row,n_col)) = zzero mlprec_wrk(ilev)%ty(:) = zzero ismth=baseprecv(ilev)%iprcparm(smth_kind_) if (ismth /= no_smth_) then ! ! Smoothed aggregation ! if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then call psb_halo(mlprec_wrk(ilev-1)%x2l,baseprecv(ilev-1)%base_desc,& & info,work=work) if(info /=0) goto 9999 else mlprec_wrk(ilev-1)%x2l(n_row+1:max(n_row,n_col)) = zzero end if call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%x2l,& & zzero,mlprec_wrk(ilev)%x2l,info) if(info /=0) goto 9999 else ! ! Raw aggregation, may take shortcut ! do i=1,n_row mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & & mlprec_wrk(ilev-1)%x2l(i) end do end if if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) Then call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) Then write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& & baseprecv(ilev)%iprcparm(coarse_mat_) endif call psb_baseprc_aply(zone,baseprecv(ilev),& & mlprec_wrk(ilev)%x2l,zzero,mlprec_wrk(ilev)%y2l,& & baseprecv(ilev)%desc_data, 'N',work,info) enddo do ilev =nlev,2,-1 ismth=baseprecv(ilev)%iprcparm(smth_kind_) n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) if (ismth /= no_smth_) then call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_),mlprec_wrk(ilev)%y2l,& & zone,mlprec_wrk(ilev-1)%y2l,info) if(info /=0) goto 9999 else do i=1, n_row mlprec_wrk(ilev-1)%y2l(i) = mlprec_wrk(ilev-1)%y2l(i) + & & mlprec_wrk(ilev)%y2l(baseprecv(ilev)%mlia(i)) enddo end if end do call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,zone,y,baseprecv(1)%base_desc,info) if(info /=0) goto 9999 case(mult_ml_prec_) ! ! Multiplicative multilevel ! Pre/post smoothing versions. ! select case(baseprecv(2)%iprcparm(smth_pos_)) case(post_smooth_) ! ! Post smoothing. ! 1. X(1) = Xext ! 2. DO ILEV=2, NLEV :: X(ILEV) = AV(PR_SM_T_,ILEV)*X(ILEV-1) ! 3. Y(NLEV) = (K(NLEV)**(-1))*X(NLEV) ! 4. DO ILEV=NLEV-1,1,-1 ! Y(ILEV) = AV(PR_SM_,ILEV+1)*Y(ILEV+1) ! Y(ILEV) = Y(ILEV) + (K(ILEV)**(-1))*(X(ILEV)-A(ILEV)*Y(ILEV)) ! ! 5. Yext = beta*Yext + Y(1) ! ! Note: level numbering reversed wrt ref. DD, i.e. ! 1..NLEV <=> (j) <-> 0 ! ! Also: post smoothing is not spelled out in detail in DD. ! ! n_col = desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(1)%desc_data%matrix_data(psb_n_col_) allocate(mlprec_wrk(1)%x2l(nr2l),mlprec_wrk(1)%y2l(nr2l), & & mlprec_wrk(1)%tx(nr2l), stat=info) mlprec_wrk(1)%x2l(:) = zzero mlprec_wrk(1)%y2l(:) = zzero mlprec_wrk(1)%tx(:) = zzero call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%tx,& & baseprecv(1)%base_desc,info) call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%x2l,& & baseprecv(1)%base_desc,info) do ilev=2, nlev n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) ismth = baseprecv(ilev)%iprcparm(smth_kind_) allocate(mlprec_wrk(ilev)%tx(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& & mlprec_wrk(ilev)%x2l(nr2l), stat=info) if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if mlprec_wrk(ilev)%x2l(:) = zzero mlprec_wrk(ilev)%y2l(:) = zzero mlprec_wrk(ilev)%tx(:) = zzero if (ismth /= no_smth_) then ! ! Smoothed aggregation ! if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then call psb_halo(mlprec_wrk(ilev-1)%x2l,& & baseprecv(ilev-1)%base_desc,info,work=work) if(info /=0) goto 9999 else mlprec_wrk(ilev-1)%x2l(n_row+1:max(n_row,n_col)) = zzero end if call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%x2l, & & zzero,mlprec_wrk(ilev)%x2l,info) if(info /=0) goto 9999 else ! ! Raw aggregation, may take shortcut ! do i=1,n_row mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & & mlprec_wrk(ilev-1)%x2l(i) end do end if if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) Then call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) Then write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& & baseprecv(ilev)%iprcparm(coarse_mat_) endif call psb_geaxpby(zone,mlprec_wrk(ilev)%x2l,zzero,mlprec_wrk(ilev)%tx,& & baseprecv(ilev)%base_desc,info) if(info /=0) goto 9999 enddo call psb_baseprc_aply(zone,baseprecv(nlev),mlprec_wrk(nlev)%x2l, & & zzero, mlprec_wrk(nlev)%y2l,baseprecv(nlev)%desc_data,'N',work,info) if(info /=0) goto 9999 do ilev=nlev-1, 1, -1 ismth = baseprecv(ilev+1)%iprcparm(smth_kind_) if (ismth /= no_smth_) then if (ismth == smth_omg_) & & call psb_halo(mlprec_wrk(ilev+1)%y2l,baseprecv(ilev+1)%desc_data,& & info,work=work) call psb_csmm(zone,baseprecv(ilev+1)%av(sm_pr_),mlprec_wrk(ilev+1)%y2l,& & zzero,mlprec_wrk(ilev)%y2l,info) if(info /=0) goto 9999 else n_row = baseprecv(ilev)%base_desc%matrix_data(psb_n_row_) mlprec_wrk(ilev)%y2l(:) = zzero do i=1, n_row mlprec_wrk(ilev)%y2l(i) = mlprec_wrk(ilev)%y2l(i) + & & mlprec_wrk(ilev+1)%y2l(baseprecv(ilev+1)%mlia(i)) enddo end if call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& & zone,mlprec_wrk(ilev)%tx,baseprecv(ilev)%base_desc,info,work=work) if(info /=0) goto 9999 call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%tx,& & zone,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%base_desc, trans, work,info) if(info /=0) goto 9999 enddo call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,beta,y,baseprecv(1)%base_desc,info) if(info /=0) goto 9999 case(pre_smooth_) ! ! Pre smoothing. ! 1. X(1) = Xext ! 2. Y(1) = (K(1)**(-1))*X(1) ! 3. TX(1) = X(1) - A(1)*Y(1) ! 4. DO ILEV=2, NLEV ! X(ILEV) = AV(PR_SM_T_,ILEV)*TX(ILEV-1) ! Y(ILEV) = (K(ILEV)**(-1))*X(ILEV) ! TX(ILEV) = (X(ILEV)-A(ILEV)*Y(ILEV)) ! 5. DO ILEV=NLEV-1,1,-1 ! Y(ILEV) = Y(ILEV) + AV(PR_SM_,ILEV+1)*Y(ILEV+1) ! 6. Yext = beta*Yext + Y(1) ! ! Note: level numbering reversed wrt ref. DD, i.e. ! 1..NLEV <=> (j) <-> 0 ! ! n_col = desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(1)%desc_data%matrix_data(psb_n_col_) allocate(mlprec_wrk(1)%x2l(nr2l),mlprec_wrk(1)%y2l(nr2l), & & mlprec_wrk(1)%tx(nr2l), stat=info) if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if mlprec_wrk(1)%y2l(:) = zzero mlprec_wrk(1)%x2l(:) = x call psb_baseprc_aply(zone,baseprecv(1),mlprec_wrk(1)%x2l,& & zzero,mlprec_wrk(1)%y2l,& & baseprecv(1)%base_desc,& & trans,work,info) if(info /=0) goto 9999 mlprec_wrk(1)%tx = mlprec_wrk(1)%x2l call psb_spmm(-zone,baseprecv(1)%base_a,mlprec_wrk(1)%y2l,& & zone,mlprec_wrk(1)%tx,baseprecv(1)%base_desc,info,work=work) if(info /=0) goto 9999 do ilev = 2, nlev n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) ismth = baseprecv(ilev)%iprcparm(smth_kind_) allocate(mlprec_wrk(ilev)%tx(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& & mlprec_wrk(ilev)%x2l(nr2l), stat=info) if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if mlprec_wrk(ilev)%x2l(:) = zzero mlprec_wrk(ilev)%y2l(:) = zzero mlprec_wrk(ilev)%tx(:) = zzero if (ismth /= no_smth_) then ! !Smoothed Aggregation ! if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then call psb_halo(mlprec_wrk(ilev-1)%tx,baseprecv(ilev-1)%base_desc,& & info,work=work) if(info /=0) goto 9999 else mlprec_wrk(ilev-1)%tx(n_row+1:max(n_row,n_col)) = zzero end if call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%tx,zzero,& & mlprec_wrk(ilev)%x2l,info) if(info /=0) goto 9999 else ! ! Raw aggregation, may take shortcuts ! mlprec_wrk(ilev)%x2l = zzero do i=1,n_row mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & & mlprec_wrk(ilev-1)%tx(i) end do end if if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) then call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) then write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& & baseprecv(ilev)%iprcparm(coarse_mat_) endif call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%x2l,& & zzero,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%desc_data, 'N',work,info) if(info /=0) goto 9999 if(ilev < nlev) then mlprec_wrk(ilev)%tx = mlprec_wrk(ilev)%x2l call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& & zone,mlprec_wrk(ilev)%tx,baseprecv(ilev)%base_desc,info,work=work) if(info /=0) goto 9999 endif enddo do ilev = nlev-1, 1, -1 ismth=baseprecv(ilev+1)%iprcparm(smth_kind_) if (ismth /= no_smth_) then if (ismth == smth_omg_) & & call psb_halo(mlprec_wrk(ilev+1)%y2l,& & baseprecv(ilev+1)%desc_data,info,work=work) call psb_csmm(zone,baseprecv(ilev+1)%av(sm_pr_),mlprec_wrk(ilev+1)%y2l,& & zone,mlprec_wrk(ilev)%y2l,info) if(info /=0) goto 9999 else n_row = baseprecv(ilev+1)%base_desc%matrix_data(psb_n_row_) do i=1, n_row mlprec_wrk(ilev)%y2l(i) = mlprec_wrk(ilev)%y2l(i) + & & mlprec_wrk(ilev+1)%y2l(baseprecv(ilev+1)%mlia(i)) enddo end if enddo call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,beta,y,& & baseprecv(1)%base_desc,info) if(info /=0) goto 9999 case(smooth_both_) ! ! Symmetrized smoothing. ! 1. X(1) = Xext ! 2. Y(1) = (K(1)**(-1))*X(1) ! 3. TX(1) = X(1) - A(1)*Y(1) ! 4. DO ILEV=2, NLEV ! X(ILEV) = AV(PR_SM_T_,ILEV)*TX(ILEV-1) ! Y(ILEV) = (K(ILEV)**(-1))*X(ILEV) ! TX(ILEV) = (X(ILEV)-A(ILEV)*Y(ILEV)) ! 5. DO ILEV=NLEV-1,1,-1 ! Y(ILEV) = Y(ILEV) + AV(PR_SM_,ILEV+1)*Y(ILEV+1) ! Y(ILEV) = Y(ILEV) + (K(ILEV)**(-1))*(X(ILEV)-A(ILEV)*Y(ILEV)) ! 6. Yext = beta*Yext + Y(1) ! ! Note: level numbering reversed wrt ref. DD, i.e. ! 1..NLEV <=> (j) <-> 0 ! ! n_col = desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(1)%desc_data%matrix_data(psb_n_col_) allocate(mlprec_wrk(1)%x2l(nr2l),mlprec_wrk(1)%y2l(nr2l), & & mlprec_wrk(1)%ty(nr2l), mlprec_wrk(1)%tx(nr2l), stat=info) mlprec_wrk(1)%x2l(:) = zzero mlprec_wrk(1)%y2l(:) = zzero mlprec_wrk(1)%tx(:) = zzero mlprec_wrk(1)%ty(:) = zzero if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%x2l,& & baseprecv(1)%base_desc,info) call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%tx,& & baseprecv(1)%base_desc,info) call psb_baseprc_aply(zone,baseprecv(1),mlprec_wrk(1)%x2l,& & zzero,mlprec_wrk(1)%y2l,& & baseprecv(1)%base_desc,& & trans,work,info) if(info /=0) goto 9999 mlprec_wrk(1)%ty = mlprec_wrk(1)%x2l call psb_spmm(-zone,baseprecv(1)%base_a,mlprec_wrk(1)%y2l,& & zone,mlprec_wrk(1)%ty,baseprecv(1)%base_desc,info,work=work) if(info /=0) goto 9999 do ilev = 2, nlev n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) ismth=baseprecv(ilev)%iprcparm(smth_kind_) allocate(mlprec_wrk(ilev)%ty(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& & mlprec_wrk(ilev)%x2l(nr2l), stat=info) mlprec_wrk(ilev)%x2l(:) = zzero mlprec_wrk(ilev)%y2l(:) = zzero mlprec_wrk(ilev)%tx(:) = zzero mlprec_wrk(ilev)%ty(:) = zzero if (info /= 0) then call psb_errpush(4010,name,a_err='Allocate') goto 9999 end if if (ismth /= no_smth_) then ! !Smoothed Aggregation ! if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then call psb_halo(mlprec_wrk(ilev-1)%ty,baseprecv(ilev-1)%base_desc,& & info,work=work) if(info /=0) goto 9999 else mlprec_wrk(ilev-1)%ty(n_row+1:max(n_row,n_col)) = zzero end if call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%ty,zzero,& & mlprec_wrk(ilev)%x2l,info) if(info /=0) goto 9999 else ! ! Raw aggregation, may take shortcuts ! mlprec_wrk(ilev)%x2l = zzero do i=1,n_row mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & & mlprec_wrk(ilev-1)%ty(i) end do end if if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) then call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) then write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& & baseprecv(ilev)%iprcparm(coarse_mat_) endif call psb_geaxpby(zone,mlprec_wrk(ilev)%x2l,zzero,mlprec_wrk(ilev)%tx,& & baseprecv(ilev)%base_desc,info) if(info /=0) goto 9999 call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%x2l,& & zzero,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%desc_data, 'N',work,info) if(info /=0) goto 9999 if(ilev < nlev) then mlprec_wrk(ilev)%ty = mlprec_wrk(ilev)%x2l call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& & zone,mlprec_wrk(ilev)%ty,baseprecv(ilev)%base_desc,info,work=work) if(info /=0) goto 9999 endif enddo do ilev=nlev-1, 1, -1 ismth=baseprecv(ilev+1)%iprcparm(smth_kind_) if (ismth /= no_smth_) then if (ismth == smth_omg_) & & call psb_halo(mlprec_wrk(ilev+1)%y2l,baseprecv(ilev+1)%desc_data,& & info,work=work) call psb_csmm(zone,baseprecv(ilev+1)%av(sm_pr_),mlprec_wrk(ilev+1)%y2l,& & zone,mlprec_wrk(ilev)%y2l,info) if(info /=0) goto 9999 else n_row = baseprecv(ilev)%base_desc%matrix_data(psb_n_row_) do i=1, n_row mlprec_wrk(ilev)%y2l(i) = mlprec_wrk(ilev)%y2l(i) + & & mlprec_wrk(ilev+1)%y2l(baseprecv(ilev+1)%mlia(i)) enddo end if call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& & zone,mlprec_wrk(ilev)%tx,baseprecv(ilev)%base_desc,info,work=work) if(info /=0) goto 9999 call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%tx,& & zone,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%base_desc, trans, work,info) if(info /=0) goto 9999 enddo call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,beta,y,& & baseprecv(1)%base_desc,info) if(info /=0) goto 9999 case default call psb_errpush(4013,name,a_err='wrong smooth_pos',& & i_Err=(/baseprecv(2)%iprcparm(smth_pos_),0,0,0,0/)) goto 9999 end select case default call psb_errpush(4013,name,a_err='wrong mltype',& & i_Err=(/baseprecv(2)%iprcparm(ml_type_),0,0,0,0/)) goto 9999 end select call mlprec_wrk_free(mlprec_wrk) deallocate(mlprec_wrk) call psb_erractionrestore(err_act) return 9999 continue call psb_errpush(info,name) call psb_erractionrestore(err_act) if (err_act.eq.act_abort) then call psb_error() return end if return contains subroutine mlprec_wrk_free(wrk) type(psb_mlprec_wrk_type) :: wrk(:) ! This will not be needed when we have allocatables, as ! it is sufficient to deallocate the container, and ! the compiler is supposed to recursively deallocate the ! various components. integer i do i=1, size(wrk) if (associated(wrk(i)%tx)) deallocate(wrk(i)%tx) if (associated(wrk(i)%ty)) deallocate(wrk(i)%ty) if (associated(wrk(i)%x2l)) deallocate(wrk(i)%x2l) if (associated(wrk(i)%y2l)) deallocate(wrk(i)%y2l) if (associated(wrk(i)%b2l)) deallocate(wrk(i)%b2l) if (associated(wrk(i)%tty)) deallocate(wrk(i)%tty) end do end subroutine mlprec_wrk_free end subroutine psb_zmlprc_aply pygments.rb-0.6.3/vendor/pygments-main/tests/run.py000066400000000000000000000016671250413007300224020ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Pygments unit tests ~~~~~~~~~~~~~~~~~~ Usage:: python run.py [testfile ...] :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import print_function import sys, os # only find tests in this directory if os.path.dirname(__file__): os.chdir(os.path.dirname(__file__)) try: import nose except ImportError: print('nose is required to run the Pygments test suite') sys.exit(1) try: # make sure the current source is first on sys.path sys.path.insert(0, '..') import pygments except SyntaxError as err: print('Syntax error: %s' % err) sys.exit(1) except ImportError as err: print('Cannot find Pygments to test: %s' % err) sys.exit(1) else: print('Pygments %s test suite running (Python %s)...' % (pygments.__version__, sys.version.split()[0])) nose.main() pygments.rb-0.6.3/vendor/pygments-main/tests/string_asserts.py000066400000000000000000000013261250413007300246400ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Pygments string assert utility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ class StringTests(object): def assertStartsWith(self, haystack, needle, msg=None): if msg is None: msg = "'{}' does not start with '{}'".format(haystack, needle) if not haystack.startswith(needle): raise(AssertionError(msg)) def assertEndsWith(self, haystack, needle, msg=None): if msg is None: msg = "'{}' does not end with '{}'".format(haystack, needle) if not haystack.endswith(needle): raise(AssertionError(msg)) pygments.rb-0.6.3/vendor/pygments-main/tests/support.py000066400000000000000000000005021250413007300232750ustar00rootroot00000000000000# coding: utf-8 """ Support for Pygments tests """ import os def location(mod_name): """ Return the file and directory that the code for *mod_name* is in. """ source = mod_name.endswith("pyc") and mod_name[:-1] or mod_name source = os.path.abspath(source) return source, os.path.dirname(source) pygments.rb-0.6.3/vendor/pygments-main/tests/support/000077500000000000000000000000001250413007300227265ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/pygments-main/tests/support/tags000066400000000000000000000035411250413007300236120ustar00rootroot00000000000000!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ !_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ !_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ !_TAG_PROGRAM_NAME Exuberant Ctags // !_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ !_TAG_PROGRAM_VERSION 5.8 // HtmlFormatter test_html_formatter.py 19;" i HtmlFormatterTest test_html_formatter.py 34;" c NullFormatter test_html_formatter.py 19;" i PythonLexer test_html_formatter.py 18;" i StringIO test_html_formatter.py 13;" i dirname test_html_formatter.py 16;" i escape_html test_html_formatter.py 20;" i fp test_html_formatter.py 27;" v inspect test_html_formatter.py 15;" i isfile test_html_formatter.py 16;" i join test_html_formatter.py 16;" i os test_html_formatter.py 10;" i re test_html_formatter.py 11;" i subprocess test_html_formatter.py 125;" i support test_html_formatter.py 23;" i tempfile test_html_formatter.py 14;" i test_all_options test_html_formatter.py 72;" m class:HtmlFormatterTest test_correct_output test_html_formatter.py 35;" m class:HtmlFormatterTest test_ctags test_html_formatter.py 165;" m class:HtmlFormatterTest test_external_css test_html_formatter.py 48;" m class:HtmlFormatterTest test_get_style_defs test_html_formatter.py 141;" m class:HtmlFormatterTest test_lineanchors test_html_formatter.py 98;" m class:HtmlFormatterTest test_lineanchors_with_startnum test_html_formatter.py 106;" m class:HtmlFormatterTest test_linenos test_html_formatter.py 82;" m class:HtmlFormatterTest test_linenos_with_startnum test_html_formatter.py 90;" m class:HtmlFormatterTest test_unicode_options test_html_formatter.py 155;" m class:HtmlFormatterTest test_valid_output test_html_formatter.py 114;" m class:HtmlFormatterTest tokensource test_html_formatter.py 29;" v uni_open test_html_formatter.py 21;" i unittest test_html_formatter.py 12;" i pygments.rb-0.6.3/vendor/pygments-main/tests/test_basic_api.py000066400000000000000000000251151250413007300245410ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Pygments basic API tests ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import print_function import random import unittest from pygments import lexers, formatters, filters, format from pygments.token import _TokenType, Text from pygments.lexer import RegexLexer from pygments.formatters.img import FontNotFound from pygments.util import text_type, StringIO, xrange, ClassNotFound import support TESTFILE, TESTDIR = support.location(__file__) test_content = [chr(i) for i in xrange(33, 128)] * 5 random.shuffle(test_content) test_content = ''.join(test_content) + '\n' def test_lexer_import_all(): # instantiate every lexer, to see if the token type defs are correct for x in lexers.LEXERS: c = getattr(lexers, x)() def test_lexer_classes(): # test that every lexer class has the correct public API def verify(cls): assert type(cls.name) is str for attr in 'aliases', 'filenames', 'alias_filenames', 'mimetypes': assert hasattr(cls, attr) assert type(getattr(cls, attr)) is list, \ "%s: %s attribute wrong" % (cls, attr) result = cls.analyse_text("abc") assert isinstance(result, float) and 0.0 <= result <= 1.0 result = cls.analyse_text(".abc") assert isinstance(result, float) and 0.0 <= result <= 1.0 assert all(al.lower() == al for al in cls.aliases) inst = cls(opt1="val1", opt2="val2") if issubclass(cls, RegexLexer): if not hasattr(cls, '_tokens'): # if there's no "_tokens", the lexer has to be one with # multiple tokendef variants assert cls.token_variants for variant in cls.tokens: assert 'root' in cls.tokens[variant] else: assert 'root' in cls._tokens, \ '%s has no root state' % cls if cls.name in ['XQuery', 'Opa']: # XXX temporary return try: tokens = list(inst.get_tokens(test_content)) except KeyboardInterrupt: raise KeyboardInterrupt('interrupted %s.get_tokens(): test_content=%r' % (cls.__name__, test_content)) txt = "" for token in tokens: assert isinstance(token, tuple) assert isinstance(token[0], _TokenType) if isinstance(token[1], str): print(repr(token[1])) assert isinstance(token[1], text_type) txt += token[1] assert txt == test_content, "%s lexer roundtrip failed: %r != %r" % \ (cls.name, test_content, txt) for lexer in lexers._iter_lexerclasses(): yield verify, lexer def test_lexer_options(): # test that the basic options work def ensure(tokens, output): concatenated = ''.join(token[1] for token in tokens) assert concatenated == output, \ '%s: %r != %r' % (lexer, concatenated, output) def verify(cls): inst = cls(stripnl=False) ensure(inst.get_tokens('a\nb'), 'a\nb\n') ensure(inst.get_tokens('\n\n\n'), '\n\n\n') inst = cls(stripall=True) ensure(inst.get_tokens(' \n b\n\n\n'), 'b\n') # some lexers require full lines in input if cls.__name__ not in ( 'PythonConsoleLexer', 'RConsoleLexer', 'RubyConsoleLexer', 'SqliteConsoleLexer', 'MatlabSessionLexer', 'ErlangShellLexer', 'BashSessionLexer', 'LiterateHaskellLexer', 'LiterateAgdaLexer', 'PostgresConsoleLexer', 'ElixirConsoleLexer', 'JuliaConsoleLexer', 'RobotFrameworkLexer', 'DylanConsoleLexer', 'ShellSessionLexer', 'LiterateIdrisLexer', 'LiterateCryptolLexer'): inst = cls(ensurenl=False) ensure(inst.get_tokens('a\nb'), 'a\nb') inst = cls(ensurenl=False, stripall=True) ensure(inst.get_tokens('a\nb\n\n'), 'a\nb') for lexer in lexers._iter_lexerclasses(): if lexer.__name__ == 'RawTokenLexer': # this one is special continue yield verify, lexer def test_get_lexers(): # test that the lexers functions work def verify(func, args): x = func(opt='val', *args) assert isinstance(x, lexers.PythonLexer) assert x.options["opt"] == "val" for func, args in [(lexers.get_lexer_by_name, ("python",)), (lexers.get_lexer_for_filename, ("test.py",)), (lexers.get_lexer_for_mimetype, ("text/x-python",)), (lexers.guess_lexer, ("#!/usr/bin/python -O\nprint",)), (lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>")) ]: yield verify, func, args for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items(): assert cls == lexers.find_lexer_class(lname).__name__ for alias in aliases: assert cls == lexers.get_lexer_by_name(alias).__class__.__name__ for mimetype in mimetypes: assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__ try: lexers.get_lexer_by_name(None) except ClassNotFound: pass else: raise Exception def test_formatter_public_api(): ts = list(lexers.PythonLexer().get_tokens("def f(): pass")) out = StringIO() # test that every formatter class has the correct public API def verify(formatter, info): assert len(info) == 4 assert info[0], "missing formatter name" assert info[1], "missing formatter aliases" assert info[3], "missing formatter docstring" if formatter.name == 'Raw tokens': # will not work with Unicode output file return try: inst = formatter(opt1="val1") except (ImportError, FontNotFound): return try: inst.get_style_defs() except NotImplementedError: # may be raised by formatters for which it doesn't make sense pass inst.format(ts, out) for formatter, info in formatters.FORMATTERS.items(): yield verify, formatter, info def test_formatter_encodings(): from pygments.formatters import HtmlFormatter # unicode output fmt = HtmlFormatter() tokens = [(Text, u"ä")] out = format(tokens, fmt) assert type(out) is text_type assert u"ä" in out # encoding option fmt = HtmlFormatter(encoding="latin1") tokens = [(Text, u"ä")] assert u"ä".encode("latin1") in format(tokens, fmt) # encoding and outencoding option fmt = HtmlFormatter(encoding="latin1", outencoding="utf8") tokens = [(Text, u"ä")] assert u"ä".encode("utf8") in format(tokens, fmt) def test_formatter_unicode_handling(): # test that the formatter supports encoding and Unicode tokens = list(lexers.PythonLexer(encoding='utf-8'). get_tokens("def f(): 'ä'")) def verify(formatter): try: inst = formatter(encoding=None) except (ImportError, FontNotFound): # some dependency or font not installed return if formatter.name != 'Raw tokens': out = format(tokens, inst) if formatter.unicodeoutput: assert type(out) is text_type inst = formatter(encoding='utf-8') out = format(tokens, inst) assert type(out) is bytes, '%s: %r' % (formatter, out) # Cannot test for encoding, since formatters may have to escape # non-ASCII characters. else: inst = formatter() out = format(tokens, inst) assert type(out) is bytes, '%s: %r' % (formatter, out) for formatter, info in formatters.FORMATTERS.items(): yield verify, formatter def test_get_formatters(): # test that the formatters functions work x = formatters.get_formatter_by_name("html", opt="val") assert isinstance(x, formatters.HtmlFormatter) assert x.options["opt"] == "val" x = formatters.get_formatter_for_filename("a.html", opt="val") assert isinstance(x, formatters.HtmlFormatter) assert x.options["opt"] == "val" def test_styles(): # minimal style test from pygments.formatters import HtmlFormatter fmt = HtmlFormatter(style="pastie") class FiltersTest(unittest.TestCase): def test_basic(self): filter_args = { 'whitespace': {'spaces': True, 'tabs': True, 'newlines': True}, 'highlight': {'names': ['isinstance', 'lexers', 'x']}, } for x in filters.FILTERS: lx = lexers.PythonLexer() lx.add_filter(x, **filter_args.get(x, {})) fp = open(TESTFILE, 'rb') try: text = fp.read().decode('utf-8') finally: fp.close() tokens = list(lx.get_tokens(text)) roundtext = ''.join([t[1] for t in tokens]) if x not in ('whitespace', 'keywordcase'): # these filters change the text self.assertEqual(roundtext, text, "lexer roundtrip with %s filter failed" % x) def test_raiseonerror(self): lx = lexers.PythonLexer() lx.add_filter('raiseonerror', excclass=RuntimeError) self.assertRaises(RuntimeError, list, lx.get_tokens('$')) def test_whitespace(self): lx = lexers.PythonLexer() lx.add_filter('whitespace', spaces='%') fp = open(TESTFILE, 'rb') try: text = fp.read().decode('utf-8') finally: fp.close() lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) self.assertFalse(' ' in lxtext) def test_keywordcase(self): lx = lexers.PythonLexer() lx.add_filter('keywordcase', case='capitalize') fp = open(TESTFILE, 'rb') try: text = fp.read().decode('utf-8') finally: fp.close() lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) self.assertTrue('Def' in lxtext and 'Class' in lxtext) def test_codetag(self): lx = lexers.PythonLexer() lx.add_filter('codetagify') text = u'# BUG: text' tokens = list(lx.get_tokens(text)) self.assertEqual('# ', tokens[0][1]) self.assertEqual('BUG', tokens[1][1]) def test_codetag_boundary(self): # ticket #368 lx = lexers.PythonLexer() lx.add_filter('codetagify') text = u'# DEBUG: text' tokens = list(lx.get_tokens(text)) self.assertEqual('# DEBUG: text', tokens[0][1]) pygments.rb-0.6.3/vendor/pygments-main/tests/test_cfm.py000066400000000000000000000026311250413007300233720ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Basic ColdfusionHtmlLexer Test ~~~~~~~~~~~~~~~~~ :copyright: Copyright 2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import unittest import os from pygments.token import Token from pygments.lexers import ColdfusionHtmlLexer class ColdfusionHtmlLexerTest(unittest.TestCase): def setUp(self): self.lexer = ColdfusionHtmlLexer() def testBasicComment(self): fragment = u'' expected = [ (Token.Text, u''), (Token.Comment.Multiline, u''), (Token.Text, u'\n'), ] self.assertEqual(expected, list(self.lexer.get_tokens(fragment))) def testNestedComment(self): fragment = u' --->' expected = [ (Token.Text, u''), (Token.Comment.Multiline, u''), (Token.Comment.Multiline, u' '), (Token.Comment.Multiline, u'--->'), (Token.Text, u'\n'), ] self.assertEqual(expected, list(self.lexer.get_tokens(fragment))) pygments.rb-0.6.3/vendor/pygments-main/tests/test_clexer.py000066400000000000000000000164271250413007300241170ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Basic CLexer Test ~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import unittest import os import textwrap from pygments.token import Text, Number, Token from pygments.lexers import CLexer class CLexerTest(unittest.TestCase): def setUp(self): self.lexer = CLexer() def testNumbers(self): code = '42 23.42 23. .42 023 0xdeadbeef 23e+42 42e-23' wanted = [] for item in zip([Number.Integer, Number.Float, Number.Float, Number.Float, Number.Oct, Number.Hex, Number.Float, Number.Float], code.split()): wanted.append(item) wanted.append((Text, ' ')) wanted = wanted[:-1] + [(Text, '\n')] self.assertEqual(list(self.lexer.get_tokens(code)), wanted) def testSwitch(self): fragment = u'''\ int main() { switch (0) { case 0: default: ; } } ''' tokens = [ (Token.Keyword.Type, u'int'), (Token.Text, u' '), (Token.Name.Function, u'main'), (Token.Punctuation, u'('), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'switch'), (Token.Text, u' '), (Token.Punctuation, u'('), (Token.Literal.Number.Integer, u'0'), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'case'), (Token.Text, u' '), (Token.Literal.Number.Integer, u'0'), (Token.Operator, u':'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'default'), (Token.Operator, u':'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Punctuation, u';'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Punctuation, u'}'), (Token.Text, u'\n'), (Token.Punctuation, u'}'), (Token.Text, u'\n'), ] self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) def testSwitchSpaceBeforeColon(self): fragment = u'''\ int main() { switch (0) { case 0 : default : ; } } ''' tokens = [ (Token.Keyword.Type, u'int'), (Token.Text, u' '), (Token.Name.Function, u'main'), (Token.Punctuation, u'('), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'switch'), (Token.Text, u' '), (Token.Punctuation, u'('), (Token.Literal.Number.Integer, u'0'), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'case'), (Token.Text, u' '), (Token.Literal.Number.Integer, u'0'), (Token.Text, u' '), (Token.Operator, u':'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'default'), (Token.Text, u' '), (Token.Operator, u':'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Punctuation, u';'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Punctuation, u'}'), (Token.Text, u'\n'), (Token.Punctuation, u'}'), (Token.Text, u'\n'), ] self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) def testLabel(self): fragment = u'''\ int main() { foo: goto foo; } ''' tokens = [ (Token.Keyword.Type, u'int'), (Token.Text, u' '), (Token.Name.Function, u'main'), (Token.Punctuation, u'('), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Name.Label, u'foo'), (Token.Punctuation, u':'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'goto'), (Token.Text, u' '), (Token.Name, u'foo'), (Token.Punctuation, u';'), (Token.Text, u'\n'), (Token.Punctuation, u'}'), (Token.Text, u'\n'), ] self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) def testLabelSpaceBeforeColon(self): fragment = u'''\ int main() { foo : goto foo; } ''' tokens = [ (Token.Keyword.Type, u'int'), (Token.Text, u' '), (Token.Name.Function, u'main'), (Token.Punctuation, u'('), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Name.Label, u'foo'), (Token.Text, u' '), (Token.Punctuation, u':'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'goto'), (Token.Text, u' '), (Token.Name, u'foo'), (Token.Punctuation, u';'), (Token.Text, u'\n'), (Token.Punctuation, u'}'), (Token.Text, u'\n'), ] self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) def testLabelFollowedByStatement(self): fragment = u'''\ int main() { foo:return 0; goto foo; } ''' tokens = [ (Token.Keyword.Type, u'int'), (Token.Text, u' '), (Token.Name.Function, u'main'), (Token.Punctuation, u'('), (Token.Punctuation, u')'), (Token.Text, u'\n'), (Token.Punctuation, u'{'), (Token.Text, u'\n'), (Token.Name.Label, u'foo'), (Token.Punctuation, u':'), (Token.Keyword, u'return'), (Token.Text, u' '), (Token.Literal.Number.Integer, u'0'), (Token.Punctuation, u';'), (Token.Text, u'\n'), (Token.Text, u' '), (Token.Keyword, u'goto'), (Token.Text, u' '), (Token.Name, u'foo'), (Token.Punctuation, u';'), (Token.Text, u'\n'), (Token.Punctuation, u'}'), (Token.Text, u'\n'), ] self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) pygments.rb-0.6.3/vendor/pygments-main/tests/test_cmdline.py000066400000000000000000000063151250413007300242430ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Command line test ~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ # Test the command line interface import io import sys import unittest from pygments import highlight from pygments.util import StringIO from pygments.cmdline import main as cmdline_main import support TESTFILE, TESTDIR = support.location(__file__) def run_cmdline(*args): saved_stdout = sys.stdout saved_stderr = sys.stderr new_stdout = sys.stdout = StringIO() new_stderr = sys.stderr = StringIO() try: ret = cmdline_main(["pygmentize"] + list(args)) finally: sys.stdout = saved_stdout sys.stderr = saved_stderr return (ret, new_stdout.getvalue(), new_stderr.getvalue()) class CmdLineTest(unittest.TestCase): def test_L_opt(self): c, o, e = run_cmdline("-L") self.assertEqual(c, 0) self.assertTrue("Lexers" in o and "Formatters" in o and "Filters" in o and "Styles" in o) c, o, e = run_cmdline("-L", "lexer") self.assertEqual(c, 0) self.assertTrue("Lexers" in o and "Formatters" not in o) c, o, e = run_cmdline("-L", "lexers") self.assertEqual(c, 0) def test_O_opt(self): filename = TESTFILE c, o, e = run_cmdline("-Ofull=1,linenos=true,foo=bar", "-fhtml", filename) self.assertEqual(c, 0) self.assertTrue("foo, bar=baz=," in o) def test_F_opt(self): filename = TESTFILE c, o, e = run_cmdline("-Fhighlight:tokentype=Name.Blubb," "names=TESTFILE filename", "-fhtml", filename) self.assertEqual(c, 0) self.assertTrue('_filename ' 'for overriding, thus no lexer found.' % fn) yield check_lexer, lx, absfn, outfn def check_lexer(lx, absfn, outfn): fp = open(absfn, 'rb') try: text = fp.read() finally: fp.close() text = text.replace(b'\r\n', b'\n') text = text.strip(b'\n') + b'\n' try: text = text.decode('utf-8') if text.startswith(u'\ufeff'): text = text[len(u'\ufeff'):] except UnicodeError: text = text.decode('latin1') ntext = [] tokens = [] for type, val in lx.get_tokens(text): ntext.append(val) assert type != Error, \ 'lexer %s generated error token for %s: %r at position %d' % \ (lx, absfn, val, len(u''.join(ntext))) tokens.append((type, val)) if u''.join(ntext) != text: print('\n'.join(difflib.unified_diff(u''.join(ntext).splitlines(), text.splitlines()))) raise AssertionError('round trip failed for ' + absfn) # check output against previous run if enabled if STORE_OUTPUT: # no previous output -- store it if not os.path.isfile(outfn): fp = open(outfn, 'wb') try: pickle.dump(tokens, fp) finally: fp.close() return # otherwise load it and compare fp = open(outfn, 'rb') try: stored_tokens = pickle.load(fp) finally: fp.close() if stored_tokens != tokens: f1 = pprint.pformat(stored_tokens) f2 = pprint.pformat(tokens) print('\n'.join(difflib.unified_diff(f1.splitlines(), f2.splitlines()))) assert False, absfn pygments.rb-0.6.3/vendor/pygments-main/tests/test_html_formatter.py000066400000000000000000000141601250413007300256540ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Pygments HTML formatter tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import print_function import io import os import re import unittest import tempfile from os.path import join, dirname, isfile from pygments.util import StringIO from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter, NullFormatter from pygments.formatters.html import escape_html import support TESTFILE, TESTDIR = support.location(__file__) fp = io.open(TESTFILE, encoding='utf-8') try: tokensource = list(PythonLexer().get_tokens(fp.read())) finally: fp.close() class HtmlFormatterTest(unittest.TestCase): def test_correct_output(self): hfmt = HtmlFormatter(nowrap=True) houtfile = StringIO() hfmt.format(tokensource, houtfile) nfmt = NullFormatter() noutfile = StringIO() nfmt.format(tokensource, noutfile) stripped_html = re.sub('<.*?>', '', houtfile.getvalue()) escaped_text = escape_html(noutfile.getvalue()) self.assertEqual(stripped_html, escaped_text) def test_external_css(self): # test correct behavior # CSS should be in /tmp directory fmt1 = HtmlFormatter(full=True, cssfile='fmt1.css', outencoding='utf-8') # CSS should be in TESTDIR (TESTDIR is absolute) fmt2 = HtmlFormatter(full=True, cssfile=join(TESTDIR, 'fmt2.css'), outencoding='utf-8') tfile = tempfile.NamedTemporaryFile(suffix='.html') fmt1.format(tokensource, tfile) try: fmt2.format(tokensource, tfile) self.assertTrue(isfile(join(TESTDIR, 'fmt2.css'))) except IOError: # test directory not writable pass tfile.close() self.assertTrue(isfile(join(dirname(tfile.name), 'fmt1.css'))) os.unlink(join(dirname(tfile.name), 'fmt1.css')) try: os.unlink(join(TESTDIR, 'fmt2.css')) except OSError: pass def test_all_options(self): for optdict in [dict(nowrap=True), dict(linenos=True), dict(linenos=True, full=True), dict(linenos=True, full=True, noclasses=True)]: outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) def test_linenos(self): optdict = dict(linenos=True) outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() self.assertTrue(re.search("
    \s+1\s+2\s+3", html))
    
        def test_linenos_with_startnum(self):
            optdict = dict(linenos=True, linenostart=5)
            outfile = StringIO()
            fmt = HtmlFormatter(**optdict)
            fmt.format(tokensource, outfile)
            html = outfile.getvalue()
            self.assertTrue(re.search("
    \s+5\s+6\s+7", html))
    
        def test_lineanchors(self):
            optdict = dict(lineanchors="foo")
            outfile = StringIO()
            fmt = HtmlFormatter(**optdict)
            fmt.format(tokensource, outfile)
            html = outfile.getvalue()
            self.assertTrue(re.search("
    ", html))
    
        def test_lineanchors_with_startnum(self):
            optdict = dict(lineanchors="foo", linenostart=5)
            outfile = StringIO()
            fmt = HtmlFormatter(**optdict)
            fmt.format(tokensource, outfile)
            html = outfile.getvalue()
            self.assertTrue(re.search("
    ", html))
    
        def test_valid_output(self):
            # test all available wrappers
            fmt = HtmlFormatter(full=True, linenos=True, noclasses=True,
                                outencoding='utf-8')
    
            handle, pathname = tempfile.mkstemp('.html')
            tfile = os.fdopen(handle, 'w+b')
            fmt.format(tokensource, tfile)
            tfile.close()
            catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc')
            try:
                import subprocess
                po = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname],
                                      stdout=subprocess.PIPE)
                ret = po.wait()
                output = po.stdout.read()
                po.stdout.close()
            except OSError:
                # nsgmls not available
                pass
            else:
                if ret:
                    print(output)
                self.assertFalse(ret, 'nsgmls run reported errors')
    
            os.unlink(pathname)
    
        def test_get_style_defs(self):
            fmt = HtmlFormatter()
            sd = fmt.get_style_defs()
            self.assertTrue(sd.startswith('.'))
    
            fmt = HtmlFormatter(cssclass='foo')
            sd = fmt.get_style_defs()
            self.assertTrue(sd.startswith('.foo'))
            sd = fmt.get_style_defs('.bar')
            self.assertTrue(sd.startswith('.bar'))
            sd = fmt.get_style_defs(['.bar', '.baz'])
            fl = sd.splitlines()[0]
            self.assertTrue('.bar' in fl and '.baz' in fl)
    
        def test_unicode_options(self):
            fmt = HtmlFormatter(title=u'Föö',
                                cssclass=u'bär',
                                cssstyles=u'div:before { content: \'bäz\' }',
                                encoding='utf-8')
            handle, pathname = tempfile.mkstemp('.html')
            tfile = os.fdopen(handle, 'w+b')
            fmt.format(tokensource, tfile)
            tfile.close()
    
        def test_ctags(self):
            try:
                import ctags
            except ImportError:
                # we can't check without the ctags module, but at least check the exception
                self.assertRaises(RuntimeError, HtmlFormatter, tagsfile='support/tags')
            else:
                # this tagfile says that test_ctags() is on line 165, even if it isn't
                # anymore in the actual source
                fmt = HtmlFormatter(tagsfile='support/tags', lineanchors='L',
                                    tagurlformat='%(fname)s%(fext)s')
                outfile = StringIO()
                fmt.format(tokensource, outfile)
                self.assertTrue('test_ctags'
                                in outfile.getvalue())
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_latex_formatter.py000066400000000000000000000030161250413007300260230ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Pygments LaTeX formatter tests
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    from __future__ import print_function
    
    import os
    import unittest
    import tempfile
    
    from pygments.formatters import LatexFormatter
    from pygments.lexers import PythonLexer
    
    import support
    
    TESTFILE, TESTDIR = support.location(__file__)
    
    
    class LatexFormatterTest(unittest.TestCase):
    
        def test_valid_output(self):
            fp = open(TESTFILE)
            try:
                tokensource = list(PythonLexer().get_tokens(fp.read()))
            finally:
                fp.close()
            fmt = LatexFormatter(full=True, encoding='latin1')
    
            handle, pathname = tempfile.mkstemp('.tex')
            # place all output files in /tmp too
            old_wd = os.getcwd()
            os.chdir(os.path.dirname(pathname))
            tfile = os.fdopen(handle, 'wb')
            fmt.format(tokensource, tfile)
            tfile.close()
            try:
                import subprocess
                po = subprocess.Popen(['latex', '-interaction=nonstopmode',
                                       pathname], stdout=subprocess.PIPE)
                ret = po.wait()
                output = po.stdout.read()
                po.stdout.close()
            except OSError:
                # latex not available
                pass
            else:
                if ret:
                    print(output)
                self.assertFalse(ret, 'latex run reported errors')
    
            os.unlink(pathname)
            os.chdir(old_wd)
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_lexers_other.py000066400000000000000000000044011250413007300253250ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Tests for other lexers
        ~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import glob
    import os
    import unittest
    
    from pygments.lexers import guess_lexer
    from pygments.lexers.other import RexxLexer
    
    
    def _exampleFilePath(filename):
        return os.path.join(os.path.dirname(__file__), 'examplefiles', filename)
    
    
    class AnalyseTextTest(unittest.TestCase):
        def _testCanRecognizeAndGuessExampleFiles(self, lexer):
            assert lexer is not None
    
            for pattern in lexer.filenames:
                exampleFilesPattern = _exampleFilePath(pattern)
                for exampleFilePath in glob.glob(exampleFilesPattern):
                    exampleFile = open(exampleFilePath, 'rb')
                    try:
                        text = exampleFile.read().decode('utf-8')
                        probability = lexer.analyse_text(text)
                        self.assertTrue(probability > 0,
                            '%s must recognize %r' % (
                            lexer.name, exampleFilePath))
                        guessedLexer = guess_lexer(text)
                        self.assertEqual(guessedLexer.name, lexer.name)
                    finally:
                        exampleFile.close()
    
        def testCanRecognizeAndGuessExampleFiles(self):
            self._testCanRecognizeAndGuessExampleFiles(RexxLexer)
    
    
    class RexxLexerTest(unittest.TestCase):
        def testCanGuessFromText(self):
            self.assertAlmostEqual(0.01,
                RexxLexer.analyse_text('/* */'))
            self.assertAlmostEqual(1.0,
                RexxLexer.analyse_text('''/* Rexx */
                    say "hello world"'''))
            val = RexxLexer.analyse_text('/* */\n'
                    'hello:pRoceduRe\n'
                    '  say "hello world"')
            self.assertTrue(val > 0.5, val)
            val = RexxLexer.analyse_text('''/* */
                    if 1 > 0 then do
                        say "ok"
                    end
                    else do
                        say "huh?"
                    end''')
            self.assertTrue(val > 0.2, val)
            val = RexxLexer.analyse_text('''/* */
                    greeting = "hello world!"
                    parse value greeting "hello" name "!"
                    say name''')
            self.assertTrue(val > 0.2, val)
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_objectiveclexer.py000066400000000000000000000047321250413007300260060ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Basic CLexer Test
        ~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import unittest
    import os
    
    from pygments.token import Token
    from pygments.lexers import ObjectiveCLexer
    
    
    class ObjectiveCLexerTest(unittest.TestCase):
    
        def setUp(self):
            self.lexer = ObjectiveCLexer()
    
        def testLiteralNumberInt(self):
            fragment = u'@(1);\n'
            expected = [
                (Token.Literal, u'@('),
                (Token.Literal.Number.Integer, u'1'),
                (Token.Literal, u')'),
                (Token.Punctuation, u';'),
                (Token.Text, u'\n'),
            ]
            self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    
        def testLiteralNumberExpression(self):
            fragment = u'@(1+2);\n'
            expected = [
                (Token.Literal, u'@('),
                (Token.Literal.Number.Integer, u'1'),
                (Token.Operator, u'+'),
                (Token.Literal.Number.Integer, u'2'),
                (Token.Literal, u')'),
                (Token.Punctuation, u';'),
                (Token.Text, u'\n'),
            ]
            self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    
        def testLiteralNumberNestedExpression(self):
            fragment = u'@(1+(2+3));\n'
            expected = [
                (Token.Literal, u'@('),
                (Token.Literal.Number.Integer, u'1'),
                (Token.Operator, u'+'),
                (Token.Punctuation, u'('),
                (Token.Literal.Number.Integer, u'2'),
                (Token.Operator, u'+'),
                (Token.Literal.Number.Integer, u'3'),
                (Token.Punctuation, u')'),
                (Token.Literal, u')'),
                (Token.Punctuation, u';'),
                (Token.Text, u'\n'),
            ]
            self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    
        def testLiteralNumberBool(self):
            fragment = u'@NO;\n'
            expected = [
                (Token.Literal.Number, u'@NO'),
                (Token.Punctuation, u';'),
                (Token.Text, u'\n'),
            ]
            self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    
        def testLieralNumberBoolExpression(self):
            fragment = u'@(YES);\n'
            expected = [
                (Token.Literal, u'@('),
                (Token.Name.Builtin, u'YES'),
                (Token.Literal, u')'),
                (Token.Punctuation, u';'),
                (Token.Text, u'\n'),
            ]
            self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_perllexer.py000066400000000000000000000123311250413007300246250ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Pygments regex lexer tests
        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import time
    import unittest
    
    from pygments.token import String
    from pygments.lexers.agile import PerlLexer
    
    
    class RunawayRegexTest(unittest.TestCase):
        # A previous version of the Perl lexer would spend a great deal of
        # time backtracking when given particular strings.  These tests show that
        # the runaway backtracking doesn't happen any more (at least for the given
        # cases).
    
        lexer = PerlLexer()
    
        ### Test helpers.
    
        def assert_single_token(self, s, token):
            """Show that a given string generates only one token."""
            tokens = list(self.lexer.get_tokens_unprocessed(s))
            self.assertEqual(len(tokens), 1, tokens)
            self.assertEqual(s, tokens[0][2])
            self.assertEqual(token, tokens[0][1])
    
        def assert_tokens(self, strings, expected_tokens):
            """Show that a given string generates the expected tokens."""
            tokens = list(self.lexer.get_tokens_unprocessed(''.join(strings)))
            self.assertEqual(len(tokens), len(expected_tokens), tokens)
            for index, s in enumerate(strings):
                self.assertEqual(s, tokens[index][2])
                self.assertEqual(expected_tokens[index], tokens[index][1])
    
        def assert_fast_tokenization(self, s):
            """Show that a given string is tokenized quickly."""
            start = time.time()
            tokens = list(self.lexer.get_tokens_unprocessed(s))
            end = time.time()
            # Isn't 10 seconds kind of a long time?  Yes, but we don't want false
            # positives when the tests are starved for CPU time.
            if end-start > 10:
                self.fail('tokenization took too long')
            return tokens
    
        ### Strings.
    
        def test_single_quote_strings(self):
            self.assert_single_token(r"'foo\tbar\\\'baz'", String)
            self.assert_fast_tokenization("'" + '\\'*999)
    
        def test_double_quote_strings(self):
            self.assert_single_token(r'"foo\tbar\\\"baz"', String)
            self.assert_fast_tokenization('"' + '\\'*999)
    
        def test_backtick_strings(self):
            self.assert_single_token(r'`foo\tbar\\\`baz`', String.Backtick)
            self.assert_fast_tokenization('`' + '\\'*999)
    
        ### Regex matches with various delimiters.
    
        def test_match(self):
            self.assert_single_token(r'/aa\tbb/', String.Regex)
            self.assert_fast_tokenization('/' + '\\'*999)
    
        def test_match_with_slash(self):
            self.assert_tokens(['m', '/\n\\t\\\\/'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m/xxx\n' + '\\'*999)
    
        def test_match_with_bang(self):
            self.assert_tokens(['m', r'!aa\t\!bb!'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m!' + '\\'*999)
    
        def test_match_with_brace(self):
            self.assert_tokens(['m', r'{aa\t\}bb}'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m{' + '\\'*999)
    
        def test_match_with_angle_brackets(self):
            self.assert_tokens(['m', r'bb>'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m<' + '\\'*999)
    
        def test_match_with_parenthesis(self):
            self.assert_tokens(['m', r'(aa\t\)bb)'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m(' + '\\'*999)
    
        def test_match_with_at_sign(self):
            self.assert_tokens(['m', r'@aa\t\@bb@'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m@' + '\\'*999)
    
        def test_match_with_percent_sign(self):
            self.assert_tokens(['m', r'%aa\t\%bb%'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m%' + '\\'*999)
    
        def test_match_with_dollar_sign(self):
            self.assert_tokens(['m', r'$aa\t\$bb$'], [String.Regex, String.Regex])
            self.assert_fast_tokenization('m$' + '\\'*999)
    
        ### Regex substitutions with various delimeters.
    
        def test_substitution_with_slash(self):
            self.assert_single_token('s/aaa/bbb/g', String.Regex)
            self.assert_fast_tokenization('s/foo/' + '\\'*999)
    
        def test_substitution_with_at_sign(self):
            self.assert_single_token(r's@aaa@bbb@g', String.Regex)
            self.assert_fast_tokenization('s@foo@' + '\\'*999)
    
        def test_substitution_with_percent_sign(self):
            self.assert_single_token(r's%aaa%bbb%g', String.Regex)
            self.assert_fast_tokenization('s%foo%' + '\\'*999)
    
        def test_substitution_with_brace(self):
            self.assert_single_token(r's{aaa}', String.Regex)
            self.assert_fast_tokenization('s{' + '\\'*999)
    
        def test_substitution_with_angle_bracket(self):
            self.assert_single_token(r's', String.Regex)
            self.assert_fast_tokenization('s<' + '\\'*999)
    
        def test_substitution_with_angle_bracket(self):
            self.assert_single_token(r's', String.Regex)
            self.assert_fast_tokenization('s<' + '\\'*999)
    
        def test_substitution_with_square_bracket(self):
            self.assert_single_token(r's[aaa]', String.Regex)
            self.assert_fast_tokenization('s[' + '\\'*999)
    
        def test_substitution_with_parenthesis(self):
            self.assert_single_token(r's(aaa)', String.Regex)
            self.assert_fast_tokenization('s(' + '\\'*999)
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_qbasiclexer.py000066400000000000000000000024521250413007300251300ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Tests for QBasic
        ~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import glob
    import os
    import unittest
    
    from pygments.token import Token
    from pygments.lexers.qbasic import QBasicLexer
    
    class QBasicTest(unittest.TestCase):
        def setUp(self):
            self.lexer = QBasicLexer()
            self.maxDiff = None
    
        def testKeywordsWithDollar(self):
            fragment = u'DIM x\nx = RIGHT$("abc", 1)\n'
            expected = [
                (Token.Keyword.Declaration, u'DIM'),
                (Token.Text.Whitespace, u' '),
                (Token.Name.Variable.Global, u'x'),
                (Token.Text, u'\n'),
                (Token.Name.Variable.Global, u'x'),
                (Token.Text.Whitespace, u' '),
                (Token.Operator, u'='),
                (Token.Text.Whitespace, u' '),
                (Token.Keyword.Reserved, u'RIGHT$'),
                (Token.Punctuation, u'('),
                (Token.Literal.String.Double, u'"abc"'),
                (Token.Punctuation, u','),
                (Token.Text.Whitespace, u' '),
                (Token.Literal.Number.Integer.Long, u'1'),
                (Token.Punctuation, u')'),
                (Token.Text, u'\n'),
            ]
            self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_regexlexer.py000066400000000000000000000027221250413007300250000ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Pygments regex lexer tests
        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import unittest
    
    from pygments.token import Text
    from pygments.lexer import RegexLexer
    from pygments.lexer import bygroups
    from pygments.lexer import default
    
    
    class TestLexer(RegexLexer):
        """Test tuple state transitions including #pop."""
        tokens = {
            'root': [
                ('a', Text.Root, 'rag'),
                ('e', Text.Root),
                default(('beer', 'beer'))
            ],
            'beer': [
                ('d', Text.Beer, ('#pop', '#pop')),
            ],
            'rag': [
                ('b', Text.Rag, '#push'),
                ('c', Text.Rag, ('#pop', 'beer')),
            ],
        }
    
    
    class TupleTransTest(unittest.TestCase):
        def test(self):
            lx = TestLexer()
            toks = list(lx.get_tokens_unprocessed('abcde'))
            self.assertEqual(toks,
               [(0, Text.Root, 'a'), (1, Text.Rag, 'b'), (2, Text.Rag, 'c'),
                (3, Text.Beer, 'd'), (4, Text.Root, 'e')])
    
        def test_multiline(self):
            lx = TestLexer()
            toks = list(lx.get_tokens_unprocessed('a\ne'))
            self.assertEqual(toks,
               [(0, Text.Root, 'a'), (1, Text, u'\n'),
                (2, Text.Root, 'e')])
    
        def test_default(self):
            lx = TestLexer()
            toks = list(lx.get_tokens_unprocessed('d'))
            self.assertEqual(toks, [(0, Text.Beer, 'd')])
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_rtf_formatter.py000066400000000000000000000100651250413007300255030ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Pygments RTF formatter tests
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import unittest
    from string_asserts import StringTests
    
    from pygments.util import StringIO
    from pygments.formatters import RtfFormatter
    from pygments.lexers.special import TextLexer
    
    class RtfFormatterTest(StringTests, unittest.TestCase):
        foot = (r'\par' '\n' r'}')
    
        def _escape(self, string):
            return(string.replace("\n", r"\n"))
    
        def _build_message(self, *args, **kwargs):
            string = kwargs.get('string', None)
            t = self._escape(kwargs.get('t', ''))
            expected = self._escape(kwargs.get('expected', ''))
            result = self._escape(kwargs.get('result', ''))
    
            if string is None:
                string = (u"The expected output of '{t}'\n"
                          u"\t\tShould be '{expected}'\n"
                          u"\t\tActually outputs '{result}'\n"
                          u"\t(WARNING: Partial Output of Result!)")
    
            end = -(len(self._escape(self.foot)))
            start = end-len(expected)
    
            return string.format(t=t,
                                 result = result[start:end],
                                 expected = expected)
    
        def format_rtf(self, t):
            tokensource = list(TextLexer().get_tokens(t))
            fmt = RtfFormatter()
            buf = StringIO()
            fmt.format(tokensource, buf)
            result = buf.getvalue()
            buf.close()
            return result
    
        def test_rtf_header(self):
            t = u''
            result = self.format_rtf(t)
            expected = r'{\rtf1\ansi\uc0'
            msg = (u"RTF documents are expected to start with '{expected}'\n"
                   u"\t\tStarts intead with '{result}'\n"
                   u"\t(WARNING: Partial Output of Result!)".format(
                       expected = expected,
                       result = result[:len(expected)]))
            self.assertStartsWith(result, expected, msg)
    
        def test_rtf_footer(self):
            t = u''
            result = self.format_rtf(t)
            expected = self.foot
            msg = (u"RTF documents are expected to end with '{expected}'\n"
                   u"\t\tEnds intead with '{result}'\n"
                   u"\t(WARNING: Partial Output of Result!)".format(
                       expected = self._escape(expected),
                       result = self._escape(result[-len(expected):])))
            self.assertEndsWith(result, expected, msg)
    
        def test_ascii_characters(self):
            t = u'a b c d ~'
            result = self.format_rtf(t)
            expected = (r'a b c d ~')
            if not result.endswith(self.foot):
                return(unittest.skip('RTF Footer incorrect'))
            msg = self._build_message(t=t, result=result, expected=expected)
            self.assertEndsWith(result, expected+self.foot, msg)
    
        def test_escape_characters(self):
            t = u'\ {{'
            result = self.format_rtf(t)
            expected = (r'\\ \{\{')
            if not result.endswith(self.foot):
                return(unittest.skip('RTF Footer incorrect'))
            msg = self._build_message(t=t, result=result, expected=expected)
            self.assertEndsWith(result, expected+self.foot, msg)
    
        def test_single_characters(self):
            t = u'â € ¤ каждой'
            result = self.format_rtf(t)
            expected = (r'{\u226} {\u8364} {\u164} '
                        r'{\u1082}{\u1072}{\u1078}{\u1076}{\u1086}{\u1081}')
            if not result.endswith(self.foot):
                return(unittest.skip('RTF Footer incorrect'))
            msg = self._build_message(t=t, result=result, expected=expected)
            self.assertEndsWith(result, expected+self.foot, msg)
    
        def test_double_characters(self):
            t = u'က 힣 ↕ ↕︎ 鼖'
            result = self.format_rtf(t)
            expected = (r'{\u4096} {\u55203} {\u8597} '
                        r'{\u8597}{\u65038} {\u55422}{\u56859}')
            if not result.endswith(self.foot):
                return(unittest.skip('RTF Footer incorrect'))
            msg = self._build_message(t=t, result=result, expected=expected)
            self.assertEndsWith(result, expected+self.foot, msg)
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_string_asserts.py000066400000000000000000000023261250413007300257000ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Pygments string assert utility tests
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import unittest
    from string_asserts import StringTests
    
    class TestStringTests(StringTests, unittest.TestCase):
    
        def test_startswith_correct(self):
            self.assertStartsWith("AAA", "A")
    
        # @unittest.expectedFailure not supported by nose
        def test_startswith_incorrect(self):
            with self.assertRaises(AssertionError):
                self.assertStartsWith("AAA", "B")
    
        # @unittest.expectedFailure not supported by nose
        def test_startswith_short(self):
            with self.assertRaises(AssertionError):
                self.assertStartsWith("A", "AA")
    
        def test_endswith_correct(self):
            self.assertEndsWith("AAA", "A")
    
        # @unittest.expectedFailure not supported by nose
        def test_endswith_incorrect(self):
            with self.assertRaises(AssertionError):
                self.assertEndsWith("AAA", "B")
    
        # @unittest.expectedFailure not supported by nose
        def test_endswith_short(self):
            with self.assertRaises(AssertionError):
                self.assertEndsWith("A", "AA")
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_token.py000066400000000000000000000026051250413007300237460ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Test suite for the token module
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import unittest
    
    from pygments import token
    
    
    class TokenTest(unittest.TestCase):
    
        def test_tokentype(self):
            e = self.assertEqual
    
            t = token.String
    
            e(t.split(), [token.Token, token.Literal, token.String])
    
            e(t.__class__, token._TokenType)
    
        def test_functions(self):
            self.assertTrue(token.is_token_subtype(token.String, token.String))
            self.assertTrue(token.is_token_subtype(token.String, token.Literal))
            self.assertFalse(token.is_token_subtype(token.Literal, token.String))
    
            self.assertTrue(token.string_to_tokentype(token.String) is token.String)
            self.assertTrue(token.string_to_tokentype('') is token.Token)
            self.assertTrue(token.string_to_tokentype('String') is token.String)
    
        def test_sanity_check(self):
            stp = token.STANDARD_TYPES.copy()
            stp[token.Token] = '---' # Token and Text do conflict, that is okay
            t = {}
            for k, v in stp.items():
                t.setdefault(v, []).append(k)
            if len(t) == len(stp):
                return # Okay
    
            for k, v in t.items():
                if len(v) > 1:
                    self.fail("%r has more than one key: %r" % (k, v))
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_using_api.py000066400000000000000000000021001250413007300245720ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Pygments tests for using()
        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import unittest
    
    from pygments.lexer import using, bygroups, this, RegexLexer
    from pygments.token import String, Text, Keyword
    
    class TestLexer(RegexLexer):
        tokens = {
            'root': [
                (r'#.*',
                 using(this, state='invalid')),
                (r'(")(.+?)(")',
                 bygroups(String, using(this, state='string'), String)),
                (r'[^"]+', Text),
            ],
            'string': [
                (r'.+', Keyword),
            ],
        }
    
    
    class UsingStateTest(unittest.TestCase):
        def test_basic(self):
            expected = [(Text, 'a'), (String, '"'), (Keyword, 'bcd'),
                        (String, '"'), (Text, 'e\n')]
            t = list(TestLexer().get_tokens('a"bcd"e'))
            self.assertEqual(t, expected)
    
        def test_error(self):
            def gen():
                return list(TestLexer().get_tokens('#a'))
            self.assertRaises(KeyError, gen)
    pygments.rb-0.6.3/vendor/pygments-main/tests/test_util.py000066400000000000000000000122671250413007300236100ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    """
        Test suite for the util module
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    
    import re
    import unittest
    
    from pygments import util
    
    
    class FakeLexer(object):
        def analyse(text):
            return float(text)
        analyse = util.make_analysator(analyse)
    
    
    class UtilTest(unittest.TestCase):
    
        def test_getoptions(self):
            raises = self.assertRaises
            equals = self.assertEqual
    
            equals(util.get_bool_opt({}, 'a', True), True)
            equals(util.get_bool_opt({}, 'a', 1), True)
            equals(util.get_bool_opt({}, 'a', 'true'), True)
            equals(util.get_bool_opt({}, 'a', 'no'), False)
            raises(util.OptionError, util.get_bool_opt, {}, 'a', [])
            raises(util.OptionError, util.get_bool_opt, {}, 'a', 'foo')
    
            equals(util.get_int_opt({}, 'a', 1), 1)
            raises(util.OptionError, util.get_int_opt, {}, 'a', [])
            raises(util.OptionError, util.get_int_opt, {}, 'a', 'bar')
    
            equals(util.get_list_opt({}, 'a', [1]), [1])
            equals(util.get_list_opt({}, 'a', '1 2'), ['1', '2'])
            raises(util.OptionError, util.get_list_opt, {}, 'a', 1)
    
    
        def test_docstring_headline(self):
            def f1():
                """
                docstring headline
    
                other text
                """
            def f2():
                """
                docstring
                headline
    
                other text
                """
    
            self.assertEqual(util.docstring_headline(f1), "docstring headline")
            self.assertEqual(util.docstring_headline(f2), "docstring headline")
    
        def test_analysator_returns_float(self):
            # If an analysator wrapped by make_analysator returns a floating point
            # number, then that number will be returned by the wrapper.
            self.assertEqual(FakeLexer.analyse('0.5'), 0.5)
    
        def test_analysator_returns_boolean(self):
            # If an analysator wrapped by make_analysator returns a boolean value,
            # then the wrapper will return 1.0 if the boolean was True or 0.0 if
            # it was False.
            self.assertEqual(FakeLexer.analyse(True), 1.0)
            self.assertEqual(FakeLexer.analyse(False), 0.0)
    
        def test_analysator_raises_exception(self):
            # If an analysator wrapped by make_analysator raises an exception,
            # then the wrapper will return 0.0.
            class ErrorLexer(object):
                def analyse(text):
                    raise RuntimeError('something bad happened')
                analyse = util.make_analysator(analyse)
            self.assertEqual(ErrorLexer.analyse(''), 0.0)
    
        def test_analysator_value_error(self):
            # When converting the analysator's return value to a float a
            # ValueError may occur.  If that happens 0.0 is returned instead.
            self.assertEqual(FakeLexer.analyse('bad input'), 0.0)
    
        def test_analysator_type_error(self):
            # When converting the analysator's return value to a float a
            # TypeError may occur.  If that happens 0.0 is returned instead.
            self.assertEqual(FakeLexer.analyse(None), 0.0)
    
        def test_shebang_matches(self):
            self.assertTrue(util.shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?'))
            self.assertTrue(util.shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?'))
            self.assertTrue(util.shebang_matches('#!/usr/bin/startsomethingwith python',
                                                 r'python(2\.\d)?'))
            self.assertTrue(util.shebang_matches('#!C:\\Python2.4\\Python.exe',
                                                 r'python(2\.\d)?'))
    
            self.assertFalse(util.shebang_matches('#!/usr/bin/python-ruby',
                                                  r'python(2\.\d)?'))
            self.assertFalse(util.shebang_matches('#!/usr/bin/python/ruby',
                                                  r'python(2\.\d)?'))
            self.assertFalse(util.shebang_matches('#!', r'python'))
    
        def test_doctype_matches(self):
            self.assertTrue(util.doctype_matches(
                ' ', 'html.*'))
            self.assertFalse(util.doctype_matches(
                '  ', 'html.*'))
            self.assertTrue(util.html_doctype_matches(
                ''))
    
        def test_xml(self):
            self.assertTrue(util.looks_like_xml(
                ''))
            self.assertTrue(util.looks_like_xml('abc'))
            self.assertFalse(util.looks_like_xml(''))
    
        def test_unirange(self):
            first_non_bmp = u'\U00010000'
            r = re.compile(util.unirange(0x10000, 0x20000))
            m = r.match(first_non_bmp)
            self.assertTrue(m)
            self.assertEquals(m.end(), len(first_non_bmp))
            self.assertFalse(r.match(u'\uffff'))
            self.assertFalse(r.match(u'xxx'))
            # Tests that end is inclusive
            r = re.compile(util.unirange(0x10000, 0x10000) + '+')
            # Tests that the plus works for the entire unicode point, if narrow
            # build
            m = r.match(first_non_bmp * 2)
            self.assertTrue(m)
            self.assertEquals(m.end(), len(first_non_bmp) * 2)
    pygments.rb-0.6.3/vendor/simplejson/000077500000000000000000000000001250413007300174435ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/simplejson/.gitignore000066400000000000000000000001221250413007300214260ustar00rootroot00000000000000*.egg-info
    *.egg
    *.pyc
    *.so
    /MANIFEST
    /.coverage
    /coverage.xml
    /build
    /dist
    /docs
    pygments.rb-0.6.3/vendor/simplejson/.travis.yml000066400000000000000000000001121250413007300215460ustar00rootroot00000000000000language: python
    python:
      - "2.6"
      - "2.7"
    script: python setup.py test
    pygments.rb-0.6.3/vendor/simplejson/CHANGES.txt000066400000000000000000000255051250413007300212630ustar00rootroot00000000000000Version 2.6.0 released 2012-06-26
    
    * Error messages changed to match proposal for Python 3.3.1
      http://bugs.python.org/issue5067
    
    Version 2.5.2 released 2012-05-10
    
    * Fix for regression introduced in 2.5.1
      https://github.com/simplejson/simplejson/issues/35
    
    Version 2.5.1 released 2012-05-10
    
    * Support for use_decimal=True in environments that use Python
      sub-interpreters such as uWSGI
      https://github.com/simplejson/simplejson/issues/34
    
    Version 2.5.0 released 2012-03-29
    
    * New item_sort_key option for encoder to allow fine grained control of sorted
      output
    
    Version 2.4.0 released 2012-03-06
    
    * New bigint_as_string option for encoder to trade JavaScript number precision
      issues for type issues.
      https://github.com/simplejson/simplejson/issues/31
    
    Version 2.3.3 released 2012-02-27
    
    * Allow unknown numerical types for indent parameter
      https://github.com/simplejson/simplejson/pull/29
    
    Version 2.3.2 released 2011-12-30
    
    * Fix crashing regression in speedups introduced in 2.3.1
    
    Version 2.3.1 released 2011-12-29
    
    * namedtuple_as_object now checks _asdict to ensure that it
      is callable.
      https://github.com/simplejson/simplejson/issues/26
    
    Version 2.3.0 released 2011-12-05
    
    * Any objects with _asdict() methods are now considered for
      namedtuple_as_object.
      https://github.com/simplejson/simplejson/pull/22
    
    Version 2.2.1 released 2011-09-06
    
    * Fix MANIFEST.in issue when building a sdist from a sdist.
      https://github.com/simplejson/simplejson/issues/16
    
    Version 2.2.0 released 2011-09-04
    
    * Remove setuptools requirement, reverted to pure distutils
    * use_decimal default for encoding (dump, dumps, JSONEncoder) is now True
    * tuple encoding as JSON objects can be turned off with new
      tuple_as_array=False option.
      https://github.com/simplejson/simplejson/pull/6
    * namedtuple (or other tuple subclasses with _asdict methods) are now
      encoded as JSON objects rather than arrays by default. Can be disabled
      and treated as a tuple with the new namedtuple_as_object=False option.
      https://github.com/simplejson/simplejson/pull/6
    * JSONDecodeError is now raised instead of ValueError when a document
      ends with an opening quote and the C speedups are in use.
      https://github.com/simplejson/simplejson/issues/15
    * Updated documentation with information about JSONDecodeError
    * Force unicode linebreak characters to be escaped (U+2028 and U+2029)
      http://timelessrepo.com/json-isnt-a-javascript-subset
    * Moved documentation from a git submodule to
      http://simplejson.readthedocs.org/
    
    Version 2.1.6 released 2011-05-08
    
    * Prevent segfaults with deeply nested JSON documents
      https://github.com/simplejson/simplejson/issues/11
    * Fix compatibility with Python 2.5
      https://github.com/simplejson/simplejson/issues/5
    
    Version 2.1.5 released 2011-04-17
    
    * Built sdist tarball with setuptools_git installed. Argh.
    
    Version 2.1.4 released 2011-04-17
    
    * Does not try to build the extension when using PyPy
    * Trailing whitespace after commas no longer emitted when indent is used
    * Migrated to github http://github.com/simplejson/simplejson
    
    Version 2.1.3 released 2011-01-17
    
    * Support the sort_keys option in C encoding speedups
      http://code.google.com/p/simplejson/issues/detail?id=86
    * Allow use_decimal to work with dump()
      http://code.google.com/p/simplejson/issues/detail?id=87
    
    Version 2.1.2 released 2010-11-01
    
    * Correct wrong end when object_pairs_hook is used
      http://code.google.com/p/simplejson/issues/detail?id=85
    * Correct output for indent=0
      http://bugs.python.org/issue10019
    * Correctly raise TypeError when non-string keys are used with speedups
      http://code.google.com/p/simplejson/issues/detail?id=82
    * Fix the endlineno, endcolno attributes of the JSONDecodeError exception.
      http://code.google.com/p/simplejson/issues/detail?id=81
    
    Version 2.1.1 released 2010-03-31
    
    * Change how setup.py imports ez_setup.py to try and workaround old versions
      of setuptools.
      http://code.google.com/p/simplejson/issues/detail?id=75
    * Fix compilation on Windows platform (and other platforms with very
      picky compilers)
    * Corrected simplejson.__version__ and other minor doc changes.
    * Do not fail speedups tests if speedups could not be built.
      http://code.google.com/p/simplejson/issues/detail?id=73
    
    Version 2.1.0 released 2010-03-10
    
    * Decimal serialization officially supported for encoding with
      use_decimal=True. For encoding this encodes Decimal objects and
      for decoding it implies parse_float=Decimal
    * Python 2.4 no longer supported (may still work, but no longer tested)
    * Decoding performance and memory utilization enhancements
      http://bugs.python.org/issue7451
    * JSONEncoderForHTML class for escaping &, <, >
      http://code.google.com/p/simplejson/issues/detail?id=66
    * Memoization of object keys during encoding (when using speedups)
    * Encoder changed to use PyIter_Next for list iteration to avoid
      potential threading issues
    * Encoder changed to use iteritems rather than PyDict_Next in order to
      support dict subclasses that have a well defined ordering
      http://bugs.python.org/issue6105
    * indent encoding parameter changed to be a string rather than an integer
      (integer use still supported for backwards compatibility)
      http://code.google.com/p/simplejson/issues/detail?id=56
    * Test suite (python setup.py test) now automatically runs with and without
      speedups
      http://code.google.com/p/simplejson/issues/detail?id=55
    * Fixed support for older versions of easy_install (e.g. stock Mac OS X config)
      http://code.google.com/p/simplejson/issues/detail?id=54
    * Fixed str/unicode mismatches when using ensure_ascii=False
      http://code.google.com/p/simplejson/issues/detail?id=48
    * Fixed error message when parsing an array with trailing comma with speedups
      http://code.google.com/p/simplejson/issues/detail?id=46
    * Refactor decoder errors to raise JSONDecodeError instead of ValueError
      http://code.google.com/p/simplejson/issues/detail?id=45
    * New ordered_pairs_hook feature in decoder which makes it possible to
      preserve key order. http://bugs.python.org/issue5381
    * Fixed containerless unicode float decoding (same bug as 2.0.4, oops!)
      http://code.google.com/p/simplejson/issues/detail?id=43
    * Share PosInf definition between encoder and decoder
    * Minor reformatting to make it easier to backport simplejson changes
      to Python 2.7/3.1 json module
    
    Version 2.0.9 released 2009-02-18
    
    * Adds cyclic GC to the Encoder and Scanner speedups, which could've
      caused uncollectible cycles in some cases when using custom parser
      or encoder functions
    
    Version 2.0.8 released 2009-02-15
    
    * Documentation fixes
    * Fixes encoding True and False as keys
    * Fixes checking for True and False by identity for several parameters
    
    Version 2.0.7 released 2009-01-04
    
    * Documentation fixes
    * C extension now always returns unicode strings when the input string is
      unicode, even for empty strings
    
    Version 2.0.6 released 2008-12-19
    
    * Windows build fixes
    
    Version 2.0.5 released 2008-11-23
    
    * Fixes a segfault in the C extension when using check_circular=False and
      encoding an invalid document
    
    Version 2.0.4 released 2008-10-24
    
    * Fixes a parsing error in the C extension when the JSON document is (only)
      a floating point number. It would consume one too few characters in that
      case, and claim the document invalid.
    
    Version 2.0.3 released 2008-10-11
    
    * Fixes reference leaks in the encoding speedups (sorry about that!)
    * Fixes doctest suite for Python 2.6
    * More optimizations for the decoder
    
    Version 2.0.2 released 2008-10-06
    
    * Fixes MSVC2003 build regression
    * Fixes Python 2.4 compatibility in _speedups.c
    
    Version 2.0.1 released 2008-09-29
    
    * Fixes long encoding regression introduced in 2.0.0
    * Fixes MinGW build regression introduced in 2.0.0
    
    Version 2.0.0 released 2008-09-27
    
    * optimized Python encoding path
    * optimized Python decoding path
    * optimized C encoding path
    * optimized C decoding path
    * switched to sphinx docs (nearly the same as the json module in python 2.6)
    
    Version 1.9.3 released 2008-09-23
    
    * Decoding is significantly faster (for our internal benchmarks)
    * Pretty-printing tool changed from simplejson to simplejson.tool for better
      Python 2.6 comaptibility
    * Misc. bug fixes
    
    Version 1.9 released 2008-05-03
    
    * Rewrote test suite with unittest and doctest (no more nosetest dependency)
    * Better PEP 7 and PEP 8 source compliance
    * Removed simplejson.jsonfilter demo module
    * simplejson.jsonfilter is no longer included
    
    Version 1.8.1 released 2008-03-24
    
    * Optional C extension for accelerating the decoding of JSON strings
    * Command line interface for pretty-printing JSON (via python -msimplejson)
    * Decoding of integers and floats is now extensible (e.g. to use Decimal) via
      parse_int, parse_float options.
    * Subversion and issue tracker moved to google code:
      http://code.google.com/p/simplejson/
    * "/" is no longer escaped, so if you're embedding JSON directly in HTML
      you'll want to use .replace("/", "\\/") to prevent a close-tag attack.
    
    Version 1.7 released 2007-03-18
    
    * Improves encoding performance with an optional C extension to speed up
      str/unicode encoding (by 10-150x or so), which yields an overall speed
      boost of 2x+ (JSON is string-heavy).
    * Support for encoding unicode code points outside the BMP to UTF-16
      surrogate code pairs (specified by the Strings section of RFC 4627).
    
    Version 1.6 released 2007-03-03
    
    * Improved str support for encoding. Previous versions of simplejson
      integrated strings directly into the output stream, this version ensures
      they're of a particular encoding (default is UTF-8) so that the output
      stream is valid.
    
    Version 1.5 released 2007-01-18
    
    * Better Python 2.5 compatibility
    * Better Windows compatibility
    * indent encoding parameter for pretty printing
    * separators encoding parameter for generating optimally compact JSON
    
    Version 1.3 released 2006-04-01
    
    * The optional object_hook function is called upon decoding of any JSON
      object literal, and its return value is used instead of the dict that
      would normally be used. This can be used to efficiently implement
      features such as JSON-RPC class hinting, or other custom decodings of
      JSON. See the documentation for more information.
    
    Version 1.1 released 2005-12-31
    
    * Renamed from simple_json to simplejson to comply with PEP 8 module naming
      guidelines
    * Full set of documentation
    * More tests
    * The encoder and decoder have been extended to understand NaN, Infinity, and
      -Infinity (but this can be turned off via allow_nan=False for strict JSON
      compliance)
    * The decoder's scanner has been fixed so that it no longer accepts invalid
      JSON documents
    * The decoder now reports line and column information as well as character
      numbers for easier debugging
    * The encoder now has a circular reference checker, which can be optionally
      disabled with check_circular=False
    * dump, dumps, load, loads now accept an optional cls kwarg to use an
      alternate JSONEncoder or JSONDecoder class for convenience.
    * The read/write compatibility shim for json-py now have deprecation warnings
    
    Version 1.0 released 2005-12-25
    
     * Initial release
    pygments.rb-0.6.3/vendor/simplejson/LICENSE.txt000066400000000000000000000020401250413007300212620ustar00rootroot00000000000000Copyright (c) 2006 Bob Ippolito
    
    Permission is hereby granted, free of charge, to any person obtaining a copy of
    this software and associated documentation files (the "Software"), to deal in
    the Software without restriction, including without limitation the rights to
    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
    of the Software, and to permit persons to whom the Software is furnished to do
    so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
    pygments.rb-0.6.3/vendor/simplejson/MANIFEST.in000066400000000000000000000001221250413007300211740ustar00rootroot00000000000000include *.py
    include *.txt
    include *.rst
    include scripts/*.py
    include MANIFEST.in
    pygments.rb-0.6.3/vendor/simplejson/README.rst000066400000000000000000000014021250413007300211270ustar00rootroot00000000000000simplejson is a simple, fast, complete, correct and extensible
    JSON  encoder and decoder for Python 2.5+.  It is
    pure Python code with no dependencies, but includes an optional C
    extension for a serious speed boost.
    
    The latest documentation for simplejson can be read online here:
    http://simplejson.readthedocs.org/
    
    simplejson is the externally maintained development version of the
    json library included with Python 2.6 and Python 3.0, but maintains
    backwards compatibility with Python 2.5.
    
    The encoder may be subclassed to provide serialization in any kind of
    situation, without any special support by the objects to be serialized
    (somewhat like pickle).
    
    The decoder can handle incoming JSON strings of any specified encoding
    (UTF-8 by default).
    
    pygments.rb-0.6.3/vendor/simplejson/conf.py000066400000000000000000000130611250413007300207430ustar00rootroot00000000000000# -*- coding: utf-8 -*-
    #
    # simplejson documentation build configuration file, created by
    # sphinx-quickstart on Fri Sep 26 18:58:30 2008.
    #
    # This file is execfile()d with the current directory set to its containing dir.
    #
    # The contents of this file are pickled, so don't put values in the namespace
    # that aren't pickleable (module imports are okay, they're removed automatically).
    #
    # All configuration values have a default value; values that are commented out
    # serve to show the default value.
    
    import sys, os
    
    # If your extensions are in another directory, add it here. If the directory
    # is relative to the documentation root, use os.path.abspath to make it
    # absolute, like shown here.
    #sys.path.append(os.path.abspath('some/directory'))
    
    # General configuration
    # ---------------------
    
    # Add any Sphinx extension module names here, as strings. They can be extensions
    # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
    extensions = []
    
    # Add any paths that contain templates here, relative to this directory.
    templates_path = ['_templates']
    
    # The suffix of source filenames.
    source_suffix = '.rst'
    
    # The master toctree document.
    master_doc = 'index'
    
    # General substitutions.
    project = 'simplejson'
    copyright = '2012, Bob Ippolito'
    
    # The default replacements for |version| and |release|, also used in various
    # other places throughout the built documents.
    #
    # The short X.Y version.
    version = '2.6'
    # The full version, including alpha/beta/rc tags.
    release = '2.6.0'
    
    # There are two options for replacing |today|: either, you set today to some
    # non-false value, then it is used:
    #today = ''
    # Else, today_fmt is used as the format for a strftime call.
    today_fmt = '%B %d, %Y'
    
    # List of documents that shouldn't be included in the build.
    #unused_docs = []
    
    # List of directories, relative to source directories, that shouldn't be searched
    # for source files.
    #exclude_dirs = []
    
    # The reST default role (used for this markup: `text`) to use for all documents.
    #default_role = None
    
    # If true, '()' will be appended to :func: etc. cross-reference text.
    #add_function_parentheses = True
    
    # If true, the current module name will be prepended to all description
    # unit titles (such as .. function::).
    #add_module_names = True
    
    # If true, sectionauthor and moduleauthor directives will be shown in the
    # output. They are ignored by default.
    #show_authors = False
    
    # The name of the Pygments (syntax highlighting) style to use.
    pygments_style = 'sphinx'
    
    
    # Options for HTML output
    # -----------------------
    
    # The style sheet to use for HTML and HTML Help pages. A file of that name
    # must exist either in Sphinx' static/ path, or in one of the custom paths
    # given in html_static_path.
    html_style = 'default.css'
    
    # The name for this set of Sphinx documents.  If None, it defaults to
    # " v documentation".
    #html_title = None
    
    # A shorter title for the navigation bar.  Default is the same as html_title.
    #html_short_title = None
    
    # The name of an image file (within the static path) to place at the top of
    # the sidebar.
    #html_logo = None
    
    # The name of an image file (within the static path) to use as favicon of the
    # docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
    # pixels large.
    #html_favicon = None
    
    # Add any paths that contain custom static files (such as style sheets) here,
    # relative to this directory. They are copied after the builtin static files,
    # so a file named "default.css" will overwrite the builtin "default.css".
    html_static_path = ['_static']
    
    # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
    # using the given strftime format.
    html_last_updated_fmt = '%b %d, %Y'
    
    # If true, SmartyPants will be used to convert quotes and dashes to
    # typographically correct entities.
    #html_use_smartypants = True
    
    # Custom sidebar templates, maps document names to template names.
    #html_sidebars = {}
    
    # Additional templates that should be rendered to pages, maps page names to
    # template names.
    #html_additional_pages = {}
    
    # If false, no module index is generated.
    html_use_modindex = False
    
    # If false, no index is generated.
    #html_use_index = True
    
    # If true, the index is split into individual pages for each letter.
    #html_split_index = False
    
    # If true, the reST sources are included in the HTML build as _sources/.
    #html_copy_source = True
    
    # If true, an OpenSearch description file will be output, and all pages will
    # contain a  tag referring to it.  The value of this option must be the
    # base URL from which the finished HTML is served.
    #html_use_opensearch = ''
    
    # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
    html_file_suffix = '.html'
    
    # Output file base name for HTML help builder.
    htmlhelp_basename = 'simplejsondoc'
    
    
    # Options for LaTeX output
    # ------------------------
    
    # The paper size ('letter' or 'a4').
    #latex_paper_size = 'letter'
    
    # The font size ('10pt', '11pt' or '12pt').
    #latex_font_size = '10pt'
    
    # Grouping the document tree into LaTeX files. List of tuples
    # (source start file, target name, title, author, document class [howto/manual]).
    latex_documents = [
      ('index', 'simplejson.tex', 'simplejson Documentation',
       'Bob Ippolito', 'manual'),
    ]
    
    # The name of an image file (relative to this directory) to place at the top of
    # the title page.
    #latex_logo = None
    
    # For "manual" documents, if this is true, then toplevel headings are parts,
    # not chapters.
    #latex_use_parts = False
    
    # Additional stuff for the LaTeX preamble.
    #latex_preamble = ''
    
    # Documents to append as an appendix to all manuals.
    #latex_appendices = []
    
    # If false, no module index is generated.
    #latex_use_modindex = True
    pygments.rb-0.6.3/vendor/simplejson/index.rst000066400000000000000000000615131250413007300213120ustar00rootroot00000000000000:mod:`simplejson` --- JSON encoder and decoder
    ==============================================
    
    .. module:: simplejson
       :synopsis: Encode and decode the JSON format.
    .. moduleauthor:: Bob Ippolito 
    .. sectionauthor:: Bob Ippolito 
    
    JSON (JavaScript Object Notation)  is a subset of JavaScript
    syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
    
    :mod:`simplejson` exposes an API familiar to users of the standard library
    :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
    version of the :mod:`json` library contained in Python 2.6, but maintains
    compatibility with Python 2.5 and (currently) has
    significant performance advantages, even without using the optional C
    extension for speedups.
    
    Development of simplejson happens on Github:
    http://github.com/simplejson/simplejson
    
    Encoding basic Python object hierarchies::
    
        >>> import simplejson as json
        >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
        '["foo", {"bar": ["baz", null, 1.0, 2]}]'
        >>> print json.dumps("\"foo\bar")
        "\"foo\bar"
        >>> print json.dumps(u'\u1234')
        "\u1234"
        >>> print json.dumps('\\')
        "\\"
        >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
        {"a": 0, "b": 0, "c": 0}
        >>> from StringIO import StringIO
        >>> io = StringIO()
        >>> json.dump(['streaming API'], io)
        >>> io.getvalue()
        '["streaming API"]'
    
    Compact encoding::
    
        >>> import simplejson as json
        >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':'))
        '[1,2,3,{"4":5,"6":7}]'
    
    Pretty printing::
    
        >>> import simplejson as json
        >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4 * ' ')
        >>> print '\n'.join([l.rstrip() for l in  s.splitlines()])
        {
            "4": 5,
            "6": 7
        }
    
    Decoding JSON::
    
        >>> import simplejson as json
        >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
        >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
        True
        >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
        True
        >>> from StringIO import StringIO
        >>> io = StringIO('["streaming API"]')
        >>> json.load(io)[0] == 'streaming API'
        True
    
    Using Decimal instead of float::
    
        >>> import simplejson as json
        >>> from decimal import Decimal
        >>> json.loads('1.1', use_decimal=True) == Decimal('1.1')
        True
        >>> json.dumps(Decimal('1.1'), use_decimal=True) == '1.1'
        True
    
    Specializing JSON object decoding::
    
        >>> import simplejson as json
        >>> def as_complex(dct):
        ...     if '__complex__' in dct:
        ...         return complex(dct['real'], dct['imag'])
        ...     return dct
        ...
        >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
        ...     object_hook=as_complex)
        (1+2j)
        >>> import decimal
        >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1')
        True
    
    Specializing JSON object encoding::
    
        >>> import simplejson as json
        >>> def encode_complex(obj):
        ...     if isinstance(obj, complex):
        ...         return [obj.real, obj.imag]
        ...     raise TypeError(repr(o) + " is not JSON serializable")
        ...
        >>> json.dumps(2 + 1j, default=encode_complex)
        '[2.0, 1.0]'
        >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
        '[2.0, 1.0]'
        >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
        '[2.0, 1.0]'
    
    
    .. highlight:: none
    
    Using :mod:`simplejson.tool` from the shell to validate and pretty-print::
    
        $ echo '{"json":"obj"}' | python -m simplejson.tool
        {
            "json": "obj"
        }
        $ echo '{ 1.2:3.4}' | python -m simplejson.tool
        Expecting property name enclosed in double quotes: line 1 column 2 (char 2)
    
    .. highlight:: python
    
    .. note::
    
       The JSON produced by this module's default settings is a subset of
       YAML, so it may be used as a serializer for that as well.
    
    
    Basic Usage
    -----------
    
    .. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, use_decimal[, namedtuple_as_object[, tuple_as_array[, bigint_as_string[, sort_keys[, item_sort_key[, **kw]]]]]]]]]]]]]]]])
    
       Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
       file-like object).
    
       If *skipkeys* is true (default: ``False``), then dict keys that are not
       of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`,
       :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
       :exc:`TypeError`.
    
       If *ensure_ascii* is false (default: ``True``), then some chunks written
       to *fp* may be :class:`unicode` instances, subject to normal Python
       :class:`str` to :class:`unicode` coercion rules.  Unless ``fp.write()``
       explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`) this
       is likely to cause an error. It's best to leave the default settings, because
       they are safe and it is highly optimized.
    
       If *check_circular* is false (default: ``True``), then the circular
       reference check for container types will be skipped and a circular reference
       will result in an :exc:`OverflowError` (or worse).
    
       If *allow_nan* is false (default: ``True``), then it will be a
       :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
       ``inf``, ``-inf``) in strict compliance of the JSON specification.
       If *allow_nan* is true, their JavaScript equivalents will be used
       (``NaN``, ``Infinity``, ``-Infinity``).
    
       If *indent* is a string, then JSON array elements and object members
       will be pretty-printed with a newline followed by that string repeated
       for each level of nesting. ``None`` (the default) selects the most compact
       representation without any newlines. For backwards compatibility with
       versions of simplejson earlier than 2.1.0, an integer is also accepted
       and is converted to a string with that many spaces.
    
       .. versionchanged:: 2.1.0
          Changed *indent* from an integer number of spaces to a string.
    
       If specified, *separators* should be an ``(item_separator, dict_separator)``
       tuple.  By default, ``(', ', ': ')`` are used.  To get the most compact JSON
       representation, you should specify ``(',', ':')`` to eliminate whitespace.
    
       *encoding* is the character encoding for str instances, default is
       ``'utf-8'``.
    
       *default(obj)* is a function that should return a serializable version of
       *obj* or raise :exc:`TypeError`.  The default simply raises :exc:`TypeError`.
    
       To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
       :meth:`default` method to serialize additional types), specify it with the
       *cls* kwarg.
    
       If *use_decimal* is true (default: ``True``) then :class:`decimal.Decimal`
       will be natively serialized to JSON with full precision.
    
       .. versionchanged:: 2.1.0
          *use_decimal* is new in 2.1.0.
    
       .. versionchanged:: 2.2.0
          The default of *use_decimal* changed to ``True`` in 2.2.0.
    
       If *namedtuple_as_object* is true (default: ``True``),
       objects with ``_asdict()`` methods will be encoded
       as JSON objects.
    
       .. versionchanged:: 2.2.0
         *namedtuple_as_object* is new in 2.2.0.
    
       .. versionchanged:: 2.3.0
         *namedtuple_as_object* no longer requires that these objects be
         subclasses of :class:`tuple`.
    
       If *tuple_as_array* is true (default: ``True``),
       :class:`tuple` (and subclasses) will be encoded as JSON arrays.
    
       .. versionchanged:: 2.2.0
         *tuple_as_array* is new in 2.2.0.
    
       If *bigint_as_string* is true (default: ``False``), :class:`int`` ``2**53``
       and higher or lower than ``-2**53`` will be encoded as strings. This is to
       avoid the rounding that happens in Javascript otherwise. Note that this
       option loses type information, so use with extreme caution.
    
       .. versionchanged:: 2.4.0
         *bigint_as_string* is new in 2.4.0.
    
       If *sort_keys* is true (not the default), then the output of dictionaries
       will be sorted by key; this is useful for regression tests to ensure that
       JSON serializations can be compared on a day-to-day basis.
    
       If *item_sort_key* is a callable (not the default), then the output of
       dictionaries will be sorted with it. The callable will be used like this:
       ``sorted(dct.items(), key=item_sort_key)``. This option takes precedence
       over *sort_keys*.
    
       .. versionchanged:: 2.5.0
          *item_sort_key* is new in 2.5.0.
    
        .. note::
    
            JSON is not a framed protocol so unlike :mod:`pickle` or :mod:`marshal` it
            does not make sense to serialize more than one JSON document without some
            container protocol to delimit them.
    
    
    .. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, use_decimal[, namedtuple_as_object[, tuple_as_array[, bigint_as_string[, sort_keys[, item_sort_key[, **kw]]]]]]]]]]]]]]]])
    
       Serialize *obj* to a JSON formatted :class:`str`.
    
       If *ensure_ascii* is false, then the return value will be a
       :class:`unicode` instance.  The other arguments have the same meaning as in
       :func:`dump`. Note that the default *ensure_ascii* setting has much
       better performance.
    
    
    .. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, use_decimal[, **kw]]]]]]]]])
    
       Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON
       document) to a Python object. :exc:`JSONDecodeError` will be
       raised if the given JSON document is not valid.
    
       If the contents of *fp* are encoded with an ASCII based encoding other than
       UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified.
       Encodings that are not ASCII based (such as UCS-2) are not allowed, and
       should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded
       to a :class:`unicode` object and passed to :func:`loads`. The default
       setting of ``'utf-8'`` is fastest and should be using whenever possible.
    
       If *fp.read()* returns :class:`str` then decoded JSON strings that contain
       only ASCII characters may be parsed as :class:`str` for performance and
       memory reasons. If your code expects only :class:`unicode` the appropriate
       solution is to wrap fp with a reader as demonstrated above.
    
       *object_hook* is an optional function that will be called with the result of
       any object literal decode (a :class:`dict`).  The return value of
       *object_hook* will be used instead of the :class:`dict`.  This feature can be used
       to implement custom decoders (e.g. JSON-RPC class hinting).
    
       *object_pairs_hook* is an optional function that will be called with the
       result of any object literal decode with an ordered list of pairs.  The
       return value of *object_pairs_hook* will be used instead of the
       :class:`dict`.  This feature can be used to implement custom decoders that
       rely on the order that the key and value pairs are decoded (for example,
       :class:`collections.OrderedDict` will remember the order of insertion). If
       *object_hook* is also defined, the *object_pairs_hook* takes priority.
    
       .. versionchanged:: 2.1.0
          Added support for *object_pairs_hook*.
    
       *parse_float*, if specified, will be called with the string of every JSON
       float to be decoded.  By default, this is equivalent to ``float(num_str)``.
       This can be used to use another datatype or parser for JSON floats
       (e.g. :class:`decimal.Decimal`).
    
       *parse_int*, if specified, will be called with the string of every JSON int
       to be decoded.  By default, this is equivalent to ``int(num_str)``.  This can
       be used to use another datatype or parser for JSON integers
       (e.g. :class:`float`).
    
       *parse_constant*, if specified, will be called with one of the following
       strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This can be used to
       raise an exception if invalid JSON numbers are encountered.
    
       If *use_decimal* is true (default: ``False``) then *parse_float* is set to
       :class:`decimal.Decimal`. This is a convenience for parity with the
       :func:`dump` parameter.
    
       .. versionchanged:: 2.1.0
          *use_decimal* is new in 2.1.0.
    
       To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
       kwarg.  Additional keyword arguments will be passed to the constructor of the
       class.
    
        .. note::
    
            :func:`load` will read the rest of the file-like object as a string and
            then call :func:`loads`. It does not stop at the end of the first valid
            JSON document it finds and it will raise an error if there is anything
            other than whitespace after the document. Except for files containing
            only one JSON document, it is recommended to use :func:`loads`.
    
    
    .. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, use_decimal[, **kw]]]]]]]]])
    
       Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
       document) to a Python object. :exc:`JSONDecodeError` will be
       raised if the given JSON document is not valid.
    
       If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
       other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
       specified.  Encodings that are not ASCII based (such as UCS-2) are not
       allowed and should be decoded to :class:`unicode` first.
    
       If *s* is a :class:`str` then decoded JSON strings that contain
       only ASCII characters may be parsed as :class:`str` for performance and
       memory reasons. If your code expects only :class:`unicode` the appropriate
       solution is decode *s* to :class:`unicode` prior to calling loads.
    
       The other arguments have the same meaning as in :func:`load`.
    
    
    Encoders and decoders
    ---------------------
    
    .. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, strict]]]]]]])
    
       Simple JSON decoder.
    
       Performs the following translations in decoding by default:
    
       +---------------+-------------------+
       | JSON          | Python            |
       +===============+===================+
       | object        | dict              |
       +---------------+-------------------+
       | array         | list              |
       +---------------+-------------------+
       | string        | unicode           |
       +---------------+-------------------+
       | number (int)  | int, long         |
       +---------------+-------------------+
       | number (real) | float             |
       +---------------+-------------------+
       | true          | True              |
       +---------------+-------------------+
       | false         | False             |
       +---------------+-------------------+
       | null          | None              |
       +---------------+-------------------+
    
       It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
       corresponding ``float`` values, which is outside the JSON spec.
    
       *encoding* determines the encoding used to interpret any :class:`str` objects
       decoded by this instance (``'utf-8'`` by default).  It has no effect when decoding
       :class:`unicode` objects.
    
       Note that currently only encodings that are a superset of ASCII work, strings
       of other encodings should be passed in as :class:`unicode`.
    
       *object_hook* is an optional function that will be called with the result of
       every JSON object decoded and its return value will be used in place of the
       given :class:`dict`.  This can be used to provide custom deserializations
       (e.g. to support JSON-RPC class hinting).
    
       *object_pairs_hook* is an optional function that will be called with the
       result of any object literal decode with an ordered list of pairs.  The
       return value of *object_pairs_hook* will be used instead of the
       :class:`dict`.  This feature can be used to implement custom decoders that
       rely on the order that the key and value pairs are decoded (for example,
       :class:`collections.OrderedDict` will remember the order of insertion). If
       *object_hook* is also defined, the *object_pairs_hook* takes priority.
    
       .. versionchanged:: 2.1.0
          Added support for *object_pairs_hook*.
    
       *parse_float*, if specified, will be called with the string of every JSON
       float to be decoded.  By default, this is equivalent to ``float(num_str)``.
       This can be used to use another datatype or parser for JSON floats
       (e.g. :class:`decimal.Decimal`).
    
       *parse_int*, if specified, will be called with the string of every JSON int
       to be decoded.  By default, this is equivalent to ``int(num_str)``.  This can
       be used to use another datatype or parser for JSON integers
       (e.g. :class:`float`).
    
       *parse_constant*, if specified, will be called with one of the following
       strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This can be used to
       raise an exception if invalid JSON numbers are encountered.
    
       *strict* controls the parser's behavior when it encounters an invalid
       control character in a string. The default setting of ``True`` means that
       unescaped control characters are parse errors, if ``False`` then control
       characters will be allowed in strings.
    
       .. method:: decode(s)
    
          Return the Python representation of *s* (a :class:`str` or
          :class:`unicode` instance containing a JSON document)
    
          If *s* is a :class:`str` then decoded JSON strings that contain
          only ASCII characters may be parsed as :class:`str` for performance and
          memory reasons. If your code expects only :class:`unicode` the
          appropriate solution is decode *s* to :class:`unicode` prior to calling
          decode.
    
          :exc:`JSONDecodeError` will be raised if the given JSON
          document is not valid.
    
       .. method:: raw_decode(s)
    
          Decode a JSON document from *s* (a :class:`str` or :class:`unicode`
          beginning with a JSON document) and return a 2-tuple of the Python
          representation and the index in *s* where the document ended.
    
          This can be used to decode a JSON document from a string that may have
          extraneous data at the end.
    
          :exc:`JSONDecodeError` will be raised if the given JSON
          document is not valid.
    
    .. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default[, use_decimal[, namedtuple_as_object[, tuple_as_array[, bigint_as_string[, item_sort_key]]]]]]]]]]]]])
    
       Extensible JSON encoder for Python data structures.
    
       Supports the following objects and types by default:
    
       +-------------------+---------------+
       | Python            | JSON          |
       +===================+===============+
       | dict, namedtuple  | object        |
       +-------------------+---------------+
       | list, tuple       | array         |
       +-------------------+---------------+
       | str, unicode      | string        |
       +-------------------+---------------+
       | int, long, float  | number        |
       +-------------------+---------------+
       | True              | true          |
       +-------------------+---------------+
       | False             | false         |
       +-------------------+---------------+
       | None              | null          |
       +-------------------+---------------+
    
       .. versionchanged:: 2.2.0
          Changed *namedtuple* encoding from JSON array to object.
    
       To extend this to recognize other objects, subclass and implement a
       :meth:`default` method with another method that returns a serializable object
       for ``o`` if possible, otherwise it should call the superclass implementation
       (to raise :exc:`TypeError`).
    
       If *skipkeys* is false (the default), then it is a :exc:`TypeError` to
       attempt encoding of keys that are not str, int, long, float or None.  If
       *skipkeys* is true, such items are simply skipped.
    
       If *ensure_ascii* is true (the default), the output is guaranteed to be
       :class:`str` objects with all incoming unicode characters escaped.  If
       *ensure_ascii* is false, the output will be a unicode object.
    
       If *check_circular* is false (the default), then lists, dicts, and custom
       encoded objects will be checked for circular references during encoding to
       prevent an infinite recursion (which would cause an :exc:`OverflowError`).
       Otherwise, no such check takes place.
    
       If *allow_nan* is true (the default), then ``NaN``, ``Infinity``, and
       ``-Infinity`` will be encoded as such.  This behavior is not JSON
       specification compliant, but is consistent with most JavaScript based
       encoders and decoders.  Otherwise, it will be a :exc:`ValueError` to encode
       such floats.
    
       If *sort_keys* is true (not the default), then the output of dictionaries
       will be sorted by key; this is useful for regression tests to ensure that
       JSON serializations can be compared on a day-to-day basis.
    
       If *item_sort_key* is a callable (not the default), then the output of
       dictionaries will be sorted with it. The callable will be used like this:
       ``sorted(dct.items(), key=item_sort_key)``. This option takes precedence
       over *sort_keys*.
    
       .. versionchanged:: 2.5.0
          *item_sort_key* is new in 2.5.0.
    
       If *indent* is a string, then JSON array elements and object members
       will be pretty-printed with a newline followed by that string repeated
       for each level of nesting. ``None`` (the default) selects the most compact
       representation without any newlines. For backwards compatibility with
       versions of simplejson earlier than 2.1.0, an integer is also accepted
       and is converted to a string with that many spaces.
    
       .. versionchanged:: 2.1.0
          Changed *indent* from an integer number of spaces to a string.
    
       If specified, *separators* should be an ``(item_separator, key_separator)``
       tuple.  By default, ``(', ', ': ')`` are used.  To get the most compact JSON
       representation, you should specify ``(',', ':')`` to eliminate whitespace.
    
       If specified, *default* should be a function that gets called for objects
       that can't otherwise be serialized.  It should return a JSON encodable
       version of the object or raise a :exc:`TypeError`.
    
       If *encoding* is not ``None``, then all input strings will be transformed
       into unicode using that encoding prior to JSON-encoding.  The default is
       ``'utf-8'``.
    
       If *namedtuple_as_object* is true (default: ``True``),
       objects with ``_asdict()`` methods will be encoded
       as JSON objects.
    
       .. versionchanged:: 2.2.0
         *namedtuple_as_object* is new in 2.2.0.
    
       .. versionchanged:: 2.3.0
         *namedtuple_as_object* no longer requires that these objects be
         subclasses of :class:`tuple`.
    
       If *tuple_as_array* is true (default: ``True``),
       :class:`tuple` (and subclasses) will be encoded as JSON arrays.
    
       .. versionchanged:: 2.2.0
         *tuple_as_array* is new in 2.2.0.
    
       If *bigint_as_string* is true (default: ``False``), :class:`int`` ``2**53``
       and higher or lower than ``-2**53`` will be encoded as strings. This is to
       avoid the rounding that happens in Javascript otherwise. Note that this
       option loses type information, so use with extreme caution.
    
       .. versionchanged:: 2.4.0
         *bigint_as_string* is new in 2.4.0.
    
    
       .. method:: default(o)
    
          Implement this method in a subclass such that it returns a serializable
          object for *o*, or calls the base implementation (to raise a
          :exc:`TypeError`).
    
          For example, to support arbitrary iterators, you could implement default
          like this::
    
             def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                return JSONEncoder.default(self, o)
    
    
       .. method:: encode(o)
    
          Return a JSON string representation of a Python data structure, *o*.  For
          example::
    
            >>> import simplejson as json
            >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
            '{"foo": ["bar", "baz"]}'
    
    
       .. method:: iterencode(o)
    
          Encode the given object, *o*, and yield each string representation as
          available.  For example::
    
                for chunk in JSONEncoder().iterencode(bigobject):
                    mysocket.write(chunk)
    
          Note that :meth:`encode` has much better performance than
          :meth:`iterencode`.
    
    .. class:: JSONEncoderForHTML([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default[, use_decimal[, namedtuple_as_object[, tuple_as_array[, bigint_as_string[, item_sort_key]]]]]]]]]]]]])
    
       Subclass of :class:`JSONEncoder` that escapes &, <, and > for embedding in HTML.
    
       .. versionchanged:: 2.1.0
          New in 2.1.0
    
    Exceptions
    ----------
    
    .. exception:: JSONDecodeError(msg, doc, pos[, end])
    
        Subclass of :exc:`ValueError` with the following additional attributes:
    
        .. attribute:: msg
    
            The unformatted error message
    
        .. attribute:: doc
    
            The JSON document being parsed
    
        .. attribute:: pos
    
            The start index of doc where parsing failed
    
        .. attribute:: end
    
            The end index of doc where parsing failed (may be ``None``)
    
        .. attribute:: lineno
    
            The line corresponding to pos
    
        .. attribute:: colno
    
            The column corresponding to pos
    
        .. attribute:: endlineno
    
            The line corresponding to end (may be ``None``)
    
        .. attribute:: endcolno
    
            The column corresponding to end (may be ``None``)
    pygments.rb-0.6.3/vendor/simplejson/scripts/000077500000000000000000000000001250413007300211325ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/simplejson/scripts/make_docs.py000077500000000000000000000006441250413007300234400ustar00rootroot00000000000000#!/usr/bin/env python
    import os
    import subprocess
    import shutil
    
    SPHINX_BUILD = 'sphinx-build'
    
    DOCTREES_DIR = 'build/doctrees'
    HTML_DIR = 'docs'
    for dirname in DOCTREES_DIR, HTML_DIR:
        if not os.path.exists(dirname):
            os.makedirs(dirname)
    
    open(os.path.join(HTML_DIR, '.nojekyll'), 'w').close()
    res = subprocess.call([
        SPHINX_BUILD, '-d', DOCTREES_DIR, '-b', 'html', '.', 'docs',
    ])
    raise SystemExit(res)
    pygments.rb-0.6.3/vendor/simplejson/setup.py000066400000000000000000000056171250413007300211660ustar00rootroot00000000000000#!/usr/bin/env python
    
    import sys
    from distutils.core import setup, Extension, Command
    from distutils.command.build_ext import build_ext
    from distutils.errors import CCompilerError, DistutilsExecError, \
        DistutilsPlatformError
    
    IS_PYPY = hasattr(sys, 'pypy_translation_info')
    VERSION = '2.6.0'
    DESCRIPTION = "Simple, fast, extensible JSON encoder/decoder for Python"
    LONG_DESCRIPTION = open('README.rst', 'r').read()
    
    CLASSIFIERS = filter(None, map(str.strip,
    """
    Intended Audience :: Developers
    License :: OSI Approved :: MIT License
    Programming Language :: Python
    Topic :: Software Development :: Libraries :: Python Modules
    """.splitlines()))
    
    if sys.platform == 'win32' and sys.version_info > (2, 6):
       # 2.6's distutils.msvc9compiler can raise an IOError when failing to
       # find the compiler
       ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError,
                     IOError)
    else:
       ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError)
    
    class BuildFailed(Exception):
        pass
    
    class ve_build_ext(build_ext):
        # This class allows C extension building to fail.
    
        def run(self):
            try:
                build_ext.run(self)
            except DistutilsPlatformError, x:
                raise BuildFailed()
    
        def build_extension(self, ext):
            try:
                build_ext.build_extension(self, ext)
            except ext_errors, x:
                raise BuildFailed()
    
    
    class TestCommand(Command):
        user_options = []
    
        def initialize_options(self):
            pass
    
        def finalize_options(self):
            pass
    
        def run(self):
            import sys, subprocess
            raise SystemExit(
                subprocess.call([sys.executable, 'simplejson/tests/__init__.py']))
    
    def run_setup(with_binary):
        cmdclass = dict(test=TestCommand)
        if with_binary:
            kw = dict(
                ext_modules = [
                    Extension("simplejson._speedups", ["simplejson/_speedups.c"]),
                ],
                cmdclass=dict(cmdclass, build_ext=ve_build_ext),
            )
        else:
            kw = dict(cmdclass=cmdclass)
    
        setup(
            name="simplejson",
            version=VERSION,
            description=DESCRIPTION,
            long_description=LONG_DESCRIPTION,
            classifiers=CLASSIFIERS,
            author="Bob Ippolito",
            author_email="bob@redivi.com",
            url="http://github.com/simplejson/simplejson",
            license="MIT License",
            packages=['simplejson', 'simplejson.tests'],
            platforms=['any'],
            **kw)
    
    try:
        run_setup(not IS_PYPY)
    except BuildFailed:
        BUILD_EXT_WARNING = "WARNING: The C extension could not be compiled, speedups are not enabled."
        print '*' * 75
        print BUILD_EXT_WARNING
        print "Failure information, if any, is above."
        print "I'm retrying the build without the C extension now."
        print '*' * 75
    
        run_setup(False)
    
        print '*' * 75
        print BUILD_EXT_WARNING
        print "Plain-Python installation succeeded."
        print '*' * 75
    pygments.rb-0.6.3/vendor/simplejson/simplejson/000077500000000000000000000000001250413007300216265ustar00rootroot00000000000000pygments.rb-0.6.3/vendor/simplejson/simplejson/__init__.py000066400000000000000000000501451250413007300237440ustar00rootroot00000000000000r"""JSON (JavaScript Object Notation)  is a subset of
    JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
    interchange format.
    
    :mod:`simplejson` exposes an API familiar to users of the standard library
    :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
    version of the :mod:`json` library contained in Python 2.6, but maintains
    compatibility with Python 2.4 and Python 2.5 and (currently) has
    significant performance advantages, even without using the optional C
    extension for speedups.
    
    Encoding basic Python object hierarchies::
    
        >>> import simplejson as json
        >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
        '["foo", {"bar": ["baz", null, 1.0, 2]}]'
        >>> print json.dumps("\"foo\bar")
        "\"foo\bar"
        >>> print json.dumps(u'\u1234')
        "\u1234"
        >>> print json.dumps('\\')
        "\\"
        >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
        {"a": 0, "b": 0, "c": 0}
        >>> from StringIO import StringIO
        >>> io = StringIO()
        >>> json.dump(['streaming API'], io)
        >>> io.getvalue()
        '["streaming API"]'
    
    Compact encoding::
    
        >>> import simplejson as json
        >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
        '[1,2,3,{"4":5,"6":7}]'
    
    Pretty printing::
    
        >>> import simplejson as json
        >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent='    ')
        >>> print '\n'.join([l.rstrip() for l in  s.splitlines()])
        {
            "4": 5,
            "6": 7
        }
    
    Decoding JSON::
    
        >>> import simplejson as json
        >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
        >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
        True
        >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
        True
        >>> from StringIO import StringIO
        >>> io = StringIO('["streaming API"]')
        >>> json.load(io)[0] == 'streaming API'
        True
    
    Specializing JSON object decoding::
    
        >>> import simplejson as json
        >>> def as_complex(dct):
        ...     if '__complex__' in dct:
        ...         return complex(dct['real'], dct['imag'])
        ...     return dct
        ...
        >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
        ...     object_hook=as_complex)
        (1+2j)
        >>> from decimal import Decimal
        >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
        True
    
    Specializing JSON object encoding::
    
        >>> import simplejson as json
        >>> def encode_complex(obj):
        ...     if isinstance(obj, complex):
        ...         return [obj.real, obj.imag]
        ...     raise TypeError(repr(o) + " is not JSON serializable")
        ...
        >>> json.dumps(2 + 1j, default=encode_complex)
        '[2.0, 1.0]'
        >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
        '[2.0, 1.0]'
        >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
        '[2.0, 1.0]'
    
    
    Using simplejson.tool from the shell to validate and pretty-print::
    
        $ echo '{"json":"obj"}' | python -m simplejson.tool
        {
            "json": "obj"
        }
        $ echo '{ 1.2:3.4}' | python -m simplejson.tool
        Expecting property name: line 1 column 2 (char 2)
    """
    __version__ = '2.6.0'
    __all__ = [
        'dump', 'dumps', 'load', 'loads',
        'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
        'OrderedDict', 'simple_first',
    ]
    
    __author__ = 'Bob Ippolito '
    
    from decimal import Decimal
    
    from decoder import JSONDecoder, JSONDecodeError
    from encoder import JSONEncoder
    def _import_OrderedDict():
        import collections
        try:
            return collections.OrderedDict
        except AttributeError:
            import ordered_dict
            return ordered_dict.OrderedDict
    OrderedDict = _import_OrderedDict()
    
    def _import_c_make_encoder():
        try:
            from simplejson._speedups import make_encoder
            return make_encoder
        except ImportError:
            return None
    
    _default_encoder = JSONEncoder(
        skipkeys=False,
        ensure_ascii=True,
        check_circular=True,
        allow_nan=True,
        indent=None,
        separators=None,
        encoding='utf-8',
        default=None,
        use_decimal=True,
        namedtuple_as_object=True,
        tuple_as_array=True,
        bigint_as_string=False,
        item_sort_key=None,
    )
    
    def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
            allow_nan=True, cls=None, indent=None, separators=None,
            encoding='utf-8', default=None, use_decimal=True,
            namedtuple_as_object=True, tuple_as_array=True,
            bigint_as_string=False, sort_keys=False, item_sort_key=None,
            **kw):
        """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
        ``.write()``-supporting file-like object).
    
        If ``skipkeys`` is true then ``dict`` keys that are not basic types
        (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
        will be skipped instead of raising a ``TypeError``.
    
        If ``ensure_ascii`` is false, then the some chunks written to ``fp``
        may be ``unicode`` instances, subject to normal Python ``str`` to
        ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
        understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
        to cause an error.
    
        If ``check_circular`` is false, then the circular reference check
        for container types will be skipped and a circular reference will
        result in an ``OverflowError`` (or worse).
    
        If ``allow_nan`` is false, then it will be a ``ValueError`` to
        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
        in strict compliance of the JSON specification, instead of using the
        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
    
        If *indent* is a string, then JSON array elements and object members
        will be pretty-printed with a newline followed by that string repeated
        for each level of nesting. ``None`` (the default) selects the most compact
        representation without any newlines. For backwards compatibility with
        versions of simplejson earlier than 2.1.0, an integer is also accepted
        and is converted to a string with that many spaces.
    
        If ``separators`` is an ``(item_separator, dict_separator)`` tuple
        then it will be used instead of the default ``(', ', ': ')`` separators.
        ``(',', ':')`` is the most compact JSON representation.
    
        ``encoding`` is the character encoding for str instances, default is UTF-8.
    
        ``default(obj)`` is a function that should return a serializable version
        of obj or raise TypeError. The default simply raises TypeError.
    
        If *use_decimal* is true (default: ``True``) then decimal.Decimal
        will be natively serialized to JSON with full precision.
    
        If *namedtuple_as_object* is true (default: ``True``),
        :class:`tuple` subclasses with ``_asdict()`` methods will be encoded
        as JSON objects.
    
        If *tuple_as_array* is true (default: ``True``),
        :class:`tuple` (and subclasses) will be encoded as JSON arrays.
    
        If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher
        or lower than -2**53 will be encoded as strings. This is to avoid the
        rounding that happens in Javascript otherwise. Note that this is still a
        lossy operation that will not round-trip correctly and should be used
        sparingly.
    
        If specified, *item_sort_key* is a callable used to sort the items in
        each dictionary. This is useful if you want to sort items other than
        in alphabetical order by key. This option takes precedence over
        *sort_keys*.
    
        If *sort_keys* is true (default: ``False``), the output of dictionaries
        will be sorted by item.
    
        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
        ``.default()`` method to serialize additional types), specify it with
        the ``cls`` kwarg.
    
        """
        # cached encoder
        if (not skipkeys and ensure_ascii and
            check_circular and allow_nan and
            cls is None and indent is None and separators is None and
            encoding == 'utf-8' and default is None and use_decimal
            and namedtuple_as_object and tuple_as_array
            and not bigint_as_string and not item_sort_key and not kw):
            iterable = _default_encoder.iterencode(obj)
        else:
            if cls is None:
                cls = JSONEncoder
            iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
                check_circular=check_circular, allow_nan=allow_nan, indent=indent,
                separators=separators, encoding=encoding,
                default=default, use_decimal=use_decimal,
                namedtuple_as_object=namedtuple_as_object,
                tuple_as_array=tuple_as_array,
                bigint_as_string=bigint_as_string,
                sort_keys=sort_keys,
                item_sort_key=item_sort_key,
                **kw).iterencode(obj)
        # could accelerate with writelines in some versions of Python, at
        # a debuggability cost
        for chunk in iterable:
            fp.write(chunk)
    
    
    def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
            allow_nan=True, cls=None, indent=None, separators=None,
            encoding='utf-8', default=None, use_decimal=True,
            namedtuple_as_object=True, tuple_as_array=True,
            bigint_as_string=False, sort_keys=False, item_sort_key=None,
            **kw):
        """Serialize ``obj`` to a JSON formatted ``str``.
    
        If ``skipkeys`` is false then ``dict`` keys that are not basic types
        (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
        will be skipped instead of raising a ``TypeError``.
    
        If ``ensure_ascii`` is false, then the return value will be a
        ``unicode`` instance subject to normal Python ``str`` to ``unicode``
        coercion rules instead of being escaped to an ASCII ``str``.
    
        If ``check_circular`` is false, then the circular reference check
        for container types will be skipped and a circular reference will
        result in an ``OverflowError`` (or worse).
    
        If ``allow_nan`` is false, then it will be a ``ValueError`` to
        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
        strict compliance of the JSON specification, instead of using the
        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
    
        If ``indent`` is a string, then JSON array elements and object members
        will be pretty-printed with a newline followed by that string repeated
        for each level of nesting. ``None`` (the default) selects the most compact
        representation without any newlines. For backwards compatibility with
        versions of simplejson earlier than 2.1.0, an integer is also accepted
        and is converted to a string with that many spaces.
    
        If ``separators`` is an ``(item_separator, dict_separator)`` tuple
        then it will be used instead of the default ``(', ', ': ')`` separators.
        ``(',', ':')`` is the most compact JSON representation.
    
        ``encoding`` is the character encoding for str instances, default is UTF-8.
    
        ``default(obj)`` is a function that should return a serializable version
        of obj or raise TypeError. The default simply raises TypeError.
    
        If *use_decimal* is true (default: ``True``) then decimal.Decimal
        will be natively serialized to JSON with full precision.
    
        If *namedtuple_as_object* is true (default: ``True``),
        :class:`tuple` subclasses with ``_asdict()`` methods will be encoded
        as JSON objects.
    
        If *tuple_as_array* is true (default: ``True``),
        :class:`tuple` (and subclasses) will be encoded as JSON arrays.
    
        If *bigint_as_string* is true (not the default), ints 2**53 and higher
        or lower than -2**53 will be encoded as strings. This is to avoid the
        rounding that happens in Javascript otherwise.
    
        If specified, *item_sort_key* is a callable used to sort the items in
        each dictionary. This is useful if you want to sort items other than
        in alphabetical order by key. This option takes precendence over
        *sort_keys*.
    
        If *sort_keys* is true (default: ``False``), the output of dictionaries
        will be sorted by item.
    
        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
        ``.default()`` method to serialize additional types), specify it with
        the ``cls`` kwarg.
    
        """
        # cached encoder
        if (not skipkeys and ensure_ascii and
            check_circular and allow_nan and
            cls is None and indent is None and separators is None and
            encoding == 'utf-8' and default is None and use_decimal
            and namedtuple_as_object and tuple_as_array
            and not bigint_as_string and not sort_keys
            and not item_sort_key and not kw):
            return _default_encoder.encode(obj)
        if cls is None:
            cls = JSONEncoder
        return cls(
            skipkeys=skipkeys, ensure_ascii=ensure_ascii,
            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
            separators=separators, encoding=encoding, default=default,
            use_decimal=use_decimal,
            namedtuple_as_object=namedtuple_as_object,
            tuple_as_array=tuple_as_array,
            bigint_as_string=bigint_as_string,
            sort_keys=sort_keys,
            item_sort_key=item_sort_key,
            **kw).encode(obj)
    
    
    _default_decoder = JSONDecoder(encoding=None, object_hook=None,
                                   object_pairs_hook=None)
    
    
    def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, object_pairs_hook=None,
            use_decimal=False, namedtuple_as_object=True, tuple_as_array=True,
            **kw):
        """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
        a JSON document) to a Python object.
    
        *encoding* determines the encoding used to interpret any
        :class:`str` objects decoded by this instance (``'utf-8'`` by
        default).  It has no effect when decoding :class:`unicode` objects.
    
        Note that currently only encodings that are a superset of ASCII work,
        strings of other encodings should be passed in as :class:`unicode`.
    
        *object_hook*, if specified, will be called with the result of every
        JSON object decoded and its return value will be used in place of the
        given :class:`dict`.  This can be used to provide custom
        deserializations (e.g. to support JSON-RPC class hinting).
    
        *object_pairs_hook* is an optional function that will be called with
        the result of any object literal decode with an ordered list of pairs.
        The return value of *object_pairs_hook* will be used instead of the
        :class:`dict`.  This feature can be used to implement custom decoders
        that rely on the order that the key and value pairs are decoded (for
        example, :func:`collections.OrderedDict` will remember the order of
        insertion). If *object_hook* is also defined, the *object_pairs_hook*
        takes priority.
    
        *parse_float*, if specified, will be called with the string of every
        JSON float to be decoded.  By default, this is equivalent to
        ``float(num_str)``. This can be used to use another datatype or parser
        for JSON floats (e.g. :class:`decimal.Decimal`).
    
        *parse_int*, if specified, will be called with the string of every
        JSON int to be decoded.  By default, this is equivalent to
        ``int(num_str)``.  This can be used to use another datatype or parser
        for JSON integers (e.g. :class:`float`).
    
        *parse_constant*, if specified, will be called with one of the
        following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This
        can be used to raise an exception if invalid JSON numbers are
        encountered.
    
        If *use_decimal* is true (default: ``False``) then it implies
        parse_float=decimal.Decimal for parity with ``dump``.
    
        To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
        kwarg.
    
        """
        return loads(fp.read(),
            encoding=encoding, cls=cls, object_hook=object_hook,
            parse_float=parse_float, parse_int=parse_int,
            parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
            use_decimal=use_decimal, **kw)
    
    
    def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, object_pairs_hook=None,
            use_decimal=False, **kw):
        """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
        document) to a Python object.
    
        *encoding* determines the encoding used to interpret any
        :class:`str` objects decoded by this instance (``'utf-8'`` by
        default).  It has no effect when decoding :class:`unicode` objects.
    
        Note that currently only encodings that are a superset of ASCII work,
        strings of other encodings should be passed in as :class:`unicode`.
    
        *object_hook*, if specified, will be called with the result of every
        JSON object decoded and its return value will be used in place of the
        given :class:`dict`.  This can be used to provide custom
        deserializations (e.g. to support JSON-RPC class hinting).
    
        *object_pairs_hook* is an optional function that will be called with
        the result of any object literal decode with an ordered list of pairs.
        The return value of *object_pairs_hook* will be used instead of the
        :class:`dict`.  This feature can be used to implement custom decoders
        that rely on the order that the key and value pairs are decoded (for
        example, :func:`collections.OrderedDict` will remember the order of
        insertion). If *object_hook* is also defined, the *object_pairs_hook*
        takes priority.
    
        *parse_float*, if specified, will be called with the string of every
        JSON float to be decoded.  By default, this is equivalent to
        ``float(num_str)``. This can be used to use another datatype or parser
        for JSON floats (e.g. :class:`decimal.Decimal`).
    
        *parse_int*, if specified, will be called with the string of every
        JSON int to be decoded.  By default, this is equivalent to
        ``int(num_str)``.  This can be used to use another datatype or parser
        for JSON integers (e.g. :class:`float`).
    
        *parse_constant*, if specified, will be called with one of the
        following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This
        can be used to raise an exception if invalid JSON numbers are
        encountered.
    
        If *use_decimal* is true (default: ``False``) then it implies
        parse_float=decimal.Decimal for parity with ``dump``.
    
        To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
        kwarg.
    
        """
        if (cls is None and encoding is None and object_hook is None and
                parse_int is None and parse_float is None and
                parse_constant is None and object_pairs_hook is None
                and not use_decimal and not kw):
            return _default_decoder.decode(s)
        if cls is None:
            cls = JSONDecoder
        if object_hook is not None:
            kw['object_hook'] = object_hook
        if object_pairs_hook is not None:
            kw['object_pairs_hook'] = object_pairs_hook
        if parse_float is not None:
            kw['parse_float'] = parse_float
        if parse_int is not None:
            kw['parse_int'] = parse_int
        if parse_constant is not None:
            kw['parse_constant'] = parse_constant
        if use_decimal:
            if parse_float is not None:
                raise TypeError("use_decimal=True implies parse_float=Decimal")
            kw['parse_float'] = Decimal
        return cls(encoding=encoding, **kw).decode(s)
    
    
    def _toggle_speedups(enabled):
        import simplejson.decoder as dec
        import simplejson.encoder as enc
        import simplejson.scanner as scan
        c_make_encoder = _import_c_make_encoder()
        if enabled:
            dec.scanstring = dec.c_scanstring or dec.py_scanstring
            enc.c_make_encoder = c_make_encoder
            enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or
                enc.py_encode_basestring_ascii)
            scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner
        else:
            dec.scanstring = dec.py_scanstring
            enc.c_make_encoder = None
            enc.encode_basestring_ascii = enc.py_encode_basestring_ascii
            scan.make_scanner = scan.py_make_scanner
        dec.make_scanner = scan.make_scanner
        global _default_decoder
        _default_decoder = JSONDecoder(
            encoding=None,
            object_hook=None,
            object_pairs_hook=None,
        )
        global _default_encoder
        _default_encoder = JSONEncoder(
           skipkeys=False,
           ensure_ascii=True,
           check_circular=True,
           allow_nan=True,
           indent=None,
           separators=None,
           encoding='utf-8',
           default=None,
       )
    
    def simple_first(kv):
        """Helper function to pass to item_sort_key to sort simple
        elements to the top, then container elements.
        """
        return (isinstance(kv[1], (list, dict, tuple)), kv[0])
    pygments.rb-0.6.3/vendor/simplejson/simplejson/_speedups.c000066400000000000000000002563101250413007300237700ustar00rootroot00000000000000#include "Python.h"
    #include "structmember.h"
    #if PY_VERSION_HEX < 0x02070000 && !defined(PyOS_string_to_double)
    #define PyOS_string_to_double json_PyOS_string_to_double
    static double
    json_PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception);
    static double
    json_PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) {
        double x;
        assert(endptr == NULL);
        assert(overflow_exception == NULL);
        PyFPE_START_PROTECT("json_PyOS_string_to_double", return -1.0;)
        x = PyOS_ascii_atof(s);
        PyFPE_END_PROTECT(x)
        return x;
    }
    #endif
    #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
    #define Py_TYPE(ob)     (((PyObject*)(ob))->ob_type)
    #endif
    #if PY_VERSION_HEX < 0x02060000 && !defined(Py_SIZE)
    #define Py_SIZE(ob)     (((PyVarObject*)(ob))->ob_size)
    #endif
    #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
    typedef int Py_ssize_t;
    #define PY_SSIZE_T_MAX INT_MAX
    #define PY_SSIZE_T_MIN INT_MIN
    #define PyInt_FromSsize_t PyInt_FromLong
    #define PyInt_AsSsize_t PyInt_AsLong
    #endif
    #ifndef Py_IS_FINITE
    #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
    #endif
    
    #ifdef __GNUC__
    #define UNUSED __attribute__((__unused__))
    #else
    #define UNUSED
    #endif
    
    #define DEFAULT_ENCODING "utf-8"
    
    #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
    #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
    #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
    #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
    
    static PyTypeObject PyScannerType;
    static PyTypeObject PyEncoderType;
    
    typedef struct _PyScannerObject {
        PyObject_HEAD
        PyObject *encoding;
        PyObject *strict;
        PyObject *object_hook;
        PyObject *pairs_hook;
        PyObject *parse_float;
        PyObject *parse_int;
        PyObject *parse_constant;
        PyObject *memo;
    } PyScannerObject;
    
    static PyMemberDef scanner_members[] = {
        {"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
        {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
        {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
        {"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, pairs_hook), READONLY, "object_pairs_hook"},
        {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
        {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
        {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
        {NULL}
    };
    
    typedef struct _PyEncoderObject {
        PyObject_HEAD
        PyObject *markers;
        PyObject *defaultfn;
        PyObject *encoder;
        PyObject *indent;
        PyObject *key_separator;
        PyObject *item_separator;
        PyObject *sort_keys;
        PyObject *skipkeys;
        PyObject *key_memo;
        PyObject *Decimal;
        int fast_encode;
        int allow_nan;
        int use_decimal;
        int namedtuple_as_object;
        int tuple_as_array;
        int bigint_as_string;
        PyObject *item_sort_key;
    } PyEncoderObject;
    
    static PyMemberDef encoder_members[] = {
        {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
        {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
        {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
        {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
        {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
        {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
        {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
        {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
        {"key_memo", T_OBJECT, offsetof(PyEncoderObject, key_memo), READONLY, "key_memo"},
        {"item_sort_key", T_OBJECT, offsetof(PyEncoderObject, item_sort_key), READONLY, "item_sort_key"},
        {NULL}
    };
    
    static PyObject *
    maybe_quote_bigint(PyObject *encoded, PyObject *obj);
    
    static Py_ssize_t
    ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
    static PyObject *
    ascii_escape_unicode(PyObject *pystr);
    static PyObject *
    ascii_escape_str(PyObject *pystr);
    static PyObject *
    py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
    void init_speedups(void);
    static PyObject *
    scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
    static PyObject *
    scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
    static PyObject *
    _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
    static PyObject *
    scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
    static int
    scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
    static void
    scanner_dealloc(PyObject *self);
    static int
    scanner_clear(PyObject *self);
    static PyObject *
    encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
    static int
    encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
    static void
    encoder_dealloc(PyObject *self);
    static int
    encoder_clear(PyObject *self);
    static int
    encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
    static int
    encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
    static int
    encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
    static PyObject *
    _encoded_const(PyObject *obj);
    static void
    raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
    static PyObject *
    encoder_encode_string(PyEncoderObject *s, PyObject *obj);
    static int
    _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
    static PyObject *
    _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
    static PyObject *
    encoder_encode_float(PyEncoderObject *s, PyObject *obj);
    static int
    _is_namedtuple(PyObject *obj);
    
    #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
    #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
    
    #define MIN_EXPANSION 6
    #ifdef Py_UNICODE_WIDE
    #define MAX_EXPANSION (2 * MIN_EXPANSION)
    #else
    #define MAX_EXPANSION MIN_EXPANSION
    #endif
    
    static PyObject *
    maybe_quote_bigint(PyObject *encoded, PyObject *obj)
    {
        static PyObject *big_long = NULL;
        static PyObject *small_long = NULL;
        if (big_long == NULL) {
            big_long = PyLong_FromLongLong(1LL << 53);
            if (big_long == NULL) {
                Py_DECREF(encoded);
                return NULL;
            }
        }
        if (small_long == NULL) {
            small_long = PyLong_FromLongLong(-1LL << 53);
            if (small_long == NULL) {
                Py_DECREF(encoded);
                return NULL;
            }
        }
        if (PyObject_RichCompareBool(obj, big_long, Py_GE) ||
            PyObject_RichCompareBool(obj, small_long, Py_LE)) {
            PyObject* quoted = PyString_FromFormat("\"%s\"",
                                                   PyString_AsString(encoded));
            Py_DECREF(encoded);
            encoded = quoted;
        }
        return encoded;
    }
    
    static int
    _is_namedtuple(PyObject *obj)
    {
        int rval = 0;
        PyObject *_asdict = PyObject_GetAttrString(obj, "_asdict");
        if (_asdict == NULL) {
            PyErr_Clear();
            return 0;
        }
        rval = PyCallable_Check(_asdict);
        Py_DECREF(_asdict);
        return rval;
    }
    
    static int
    _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
    {
        /* PyObject to Py_ssize_t converter */
        *size_ptr = PyInt_AsSsize_t(o);
        if (*size_ptr == -1 && PyErr_Occurred())
            return 0;
        return 1;
    }
    
    static PyObject *
    _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
    {
        /* Py_ssize_t to PyObject converter */
        return PyInt_FromSsize_t(*size_ptr);
    }
    
    static Py_ssize_t
    ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
    {
        /* Escape unicode code point c to ASCII escape sequences
        in char *output. output must have at least 12 bytes unused to
        accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
        output[chars++] = '\\';
        switch (c) {
            case '\\': output[chars++] = (char)c; break;
            case '"': output[chars++] = (char)c; break;
            case '\b': output[chars++] = 'b'; break;
            case '\f': output[chars++] = 'f'; break;
            case '\n': output[chars++] = 'n'; break;
            case '\r': output[chars++] = 'r'; break;
            case '\t': output[chars++] = 't'; break;
            default:
    #ifdef Py_UNICODE_WIDE
                if (c >= 0x10000) {
                    /* UTF-16 surrogate pair */
                    Py_UNICODE v = c - 0x10000;
                    c = 0xd800 | ((v >> 10) & 0x3ff);
                    output[chars++] = 'u';
                    output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
                    output[chars++] = "0123456789abcdef"[(c >>  8) & 0xf];
                    output[chars++] = "0123456789abcdef"[(c >>  4) & 0xf];
                    output[chars++] = "0123456789abcdef"[(c      ) & 0xf];
                    c = 0xdc00 | (v & 0x3ff);
                    output[chars++] = '\\';
                }
    #endif
                output[chars++] = 'u';
                output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
                output[chars++] = "0123456789abcdef"[(c >>  8) & 0xf];
                output[chars++] = "0123456789abcdef"[(c >>  4) & 0xf];
                output[chars++] = "0123456789abcdef"[(c      ) & 0xf];
        }
        return chars;
    }
    
    static PyObject *
    ascii_escape_unicode(PyObject *pystr)
    {
        /* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
        Py_ssize_t i;
        Py_ssize_t input_chars;
        Py_ssize_t output_size;
        Py_ssize_t max_output_size;
        Py_ssize_t chars;
        PyObject *rval;
        char *output;
        Py_UNICODE *input_unicode;
    
        input_chars = PyUnicode_GET_SIZE(pystr);
        input_unicode = PyUnicode_AS_UNICODE(pystr);
    
        /* One char input can be up to 6 chars output, estimate 4 of these */
        output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
        max_output_size = 2 + (input_chars * MAX_EXPANSION);
        rval = PyString_FromStringAndSize(NULL, output_size);
        if (rval == NULL) {
            return NULL;
        }
        output = PyString_AS_STRING(rval);
        chars = 0;
        output[chars++] = '"';
        for (i = 0; i < input_chars; i++) {
            Py_UNICODE c = input_unicode[i];
            if (S_CHAR(c)) {
                output[chars++] = (char)c;
            }
            else {
                chars = ascii_escape_char(c, output, chars);
            }
            if (output_size - chars < (1 + MAX_EXPANSION)) {
                /* There's more than four, so let's resize by a lot */
                Py_ssize_t new_output_size = output_size * 2;
                /* This is an upper bound */
                if (new_output_size > max_output_size) {
                    new_output_size = max_output_size;
                }
                /* Make sure that the output size changed before resizing */
                if (new_output_size != output_size) {
                    output_size = new_output_size;
                    if (_PyString_Resize(&rval, output_size) == -1) {
                        return NULL;
                    }
                    output = PyString_AS_STRING(rval);
                }
            }
        }
        output[chars++] = '"';
        if (_PyString_Resize(&rval, chars) == -1) {
            return NULL;
        }
        return rval;
    }
    
    static PyObject *
    ascii_escape_str(PyObject *pystr)
    {
        /* Take a PyString pystr and return a new ASCII-only escaped PyString */
        Py_ssize_t i;
        Py_ssize_t input_chars;
        Py_ssize_t output_size;
        Py_ssize_t chars;
        PyObject *rval;
        char *output;
        char *input_str;
    
        input_chars = PyString_GET_SIZE(pystr);
        input_str = PyString_AS_STRING(pystr);
    
        /* Fast path for a string that's already ASCII */
        for (i = 0; i < input_chars; i++) {
            Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
            if (!S_CHAR(c)) {
                /* If we have to escape something, scan the string for unicode */
                Py_ssize_t j;
                for (j = i; j < input_chars; j++) {
                    c = (Py_UNICODE)(unsigned char)input_str[j];
                    if (c > 0x7f) {
                        /* We hit a non-ASCII character, bail to unicode mode */
                        PyObject *uni;
                        uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
                        if (uni == NULL) {
                            return NULL;
                        }
                        rval = ascii_escape_unicode(uni);
                        Py_DECREF(uni);
                        return rval;
                    }
                }
                break;
            }
        }
    
        if (i == input_chars) {
            /* Input is already ASCII */
            output_size = 2 + input_chars;
        }
        else {
            /* One char input can be up to 6 chars output, estimate 4 of these */
            output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
        }
        rval = PyString_FromStringAndSize(NULL, output_size);
        if (rval == NULL) {
            return NULL;
        }
        output = PyString_AS_STRING(rval);
        output[0] = '"';
    
        /* We know that everything up to i is ASCII already */
        chars = i + 1;
        memcpy(&output[1], input_str, i);
    
        for (; i < input_chars; i++) {
            Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
            if (S_CHAR(c)) {
                output[chars++] = (char)c;
            }
            else {
                chars = ascii_escape_char(c, output, chars);
            }
            /* An ASCII char can't possibly expand to a surrogate! */
            if (output_size - chars < (1 + MIN_EXPANSION)) {
                /* There's more than four, so let's resize by a lot */
                output_size *= 2;
                if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
                    output_size = 2 + (input_chars * MIN_EXPANSION);
                }
                if (_PyString_Resize(&rval, output_size) == -1) {
                    return NULL;
                }
                output = PyString_AS_STRING(rval);
            }
        }
        output[chars++] = '"';
        if (_PyString_Resize(&rval, chars) == -1) {
            return NULL;
        }
        return rval;
    }
    
    static void
    raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
    {
        /* Use the Python function simplejson.decoder.errmsg to raise a nice
        looking ValueError exception */
        static PyObject *JSONDecodeError = NULL;
        PyObject *exc;
        if (JSONDecodeError == NULL) {
            PyObject *decoder = PyImport_ImportModule("simplejson.decoder");
            if (decoder == NULL)
                return;
            JSONDecodeError = PyObject_GetAttrString(decoder, "JSONDecodeError");
            Py_DECREF(decoder);
            if (JSONDecodeError == NULL)
                return;
        }
        exc = PyObject_CallFunction(JSONDecodeError, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
        if (exc) {
            PyErr_SetObject(JSONDecodeError, exc);
            Py_DECREF(exc);
        }
    }
    
    static PyObject *
    join_list_unicode(PyObject *lst)
    {
        /* return u''.join(lst) */
        static PyObject *joinfn = NULL;
        if (joinfn == NULL) {
            PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
            if (ustr == NULL)
                return NULL;
    
            joinfn = PyObject_GetAttrString(ustr, "join");
            Py_DECREF(ustr);
            if (joinfn == NULL)
                return NULL;
        }
        return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
    }
    
    static PyObject *
    join_list_string(PyObject *lst)
    {
        /* return ''.join(lst) */
        static PyObject *joinfn = NULL;
        if (joinfn == NULL) {
            PyObject *ustr = PyString_FromStringAndSize(NULL, 0);
            if (ustr == NULL)
                return NULL;
    
            joinfn = PyObject_GetAttrString(ustr, "join");
            Py_DECREF(ustr);
            if (joinfn == NULL)
                return NULL;
        }
        return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
    }
    
    static PyObject *
    _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
        /* return (rval, idx) tuple, stealing reference to rval */
        PyObject *tpl;
        PyObject *pyidx;
        /*
        steal a reference to rval, returns (rval, idx)
        */
        if (rval == NULL) {
            return NULL;
        }
        pyidx = PyInt_FromSsize_t(idx);
        if (pyidx == NULL) {
            Py_DECREF(rval);
            return NULL;
        }
        tpl = PyTuple_New(2);
        if (tpl == NULL) {
            Py_DECREF(pyidx);
            Py_DECREF(rval);
            return NULL;
        }
        PyTuple_SET_ITEM(tpl, 0, rval);
        PyTuple_SET_ITEM(tpl, 1, pyidx);
        return tpl;
    }
    
    #define APPEND_OLD_CHUNK \
        if (chunk != NULL) { \
            if (chunks == NULL) { \
                chunks = PyList_New(0); \
                if (chunks == NULL) { \
                    goto bail; \
                } \
            } \
            if (PyList_Append(chunks, chunk)) { \
                goto bail; \
            } \
            Py_CLEAR(chunk); \
        }
    
    static PyObject *
    scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
    {
        /* Read the JSON string from PyString pystr.
        end is the index of the first character after the quote.
        encoding is the encoding of pystr (must be an ASCII superset)
        if strict is zero then literal control characters are allowed
        *next_end_ptr is a return-by-reference index of the character
            after the end quote
    
        Return value is a new PyString (if ASCII-only) or PyUnicode
        */
        PyObject *rval;
        Py_ssize_t len = PyString_GET_SIZE(pystr);
        Py_ssize_t begin = end - 1;
        Py_ssize_t next = begin;
        int has_unicode = 0;
        char *buf = PyString_AS_STRING(pystr);
        PyObject *chunks = NULL;
        PyObject *chunk = NULL;
    
        if (len == end) {
            raise_errmsg("Unterminated string starting at", pystr, begin);
        }
        else if (end < 0 || len < end) {
            PyErr_SetString(PyExc_ValueError, "end is out of bounds");
            goto bail;
        }
        while (1) {
            /* Find the end of the string or the next escape */
            Py_UNICODE c = 0;
            for (next = end; next < len; next++) {
                c = (unsigned char)buf[next];
                if (c == '"' || c == '\\') {
                    break;
                }
                else if (strict && c <= 0x1f) {
                    raise_errmsg("Invalid control character at", pystr, next);
                    goto bail;
                }
                else if (c > 0x7f) {
                    has_unicode = 1;
                }
            }
            if (!(c == '"' || c == '\\')) {
                raise_errmsg("Unterminated string starting at", pystr, begin);
                goto bail;
            }
            /* Pick up this chunk if it's not zero length */
            if (next != end) {
                PyObject *strchunk;
                APPEND_OLD_CHUNK
                strchunk = PyString_FromStringAndSize(&buf[end], next - end);
                if (strchunk == NULL) {
                    goto bail;
                }
                if (has_unicode) {
                    chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
                    Py_DECREF(strchunk);
                    if (chunk == NULL) {
                        goto bail;
                    }
                }
                else {
                    chunk = strchunk;
                }
            }
            next++;
            if (c == '"') {
                end = next;
                break;
            }
            if (next == len) {
                raise_errmsg("Unterminated string starting at", pystr, begin);
                goto bail;
            }
            c = buf[next];
            if (c != 'u') {
                /* Non-unicode backslash escapes */
                end = next + 1;
                switch (c) {
                    case '"': break;
                    case '\\': break;
                    case '/': break;
                    case 'b': c = '\b'; break;
                    case 'f': c = '\f'; break;
                    case 'n': c = '\n'; break;
                    case 'r': c = '\r'; break;
                    case 't': c = '\t'; break;
                    default: c = 0;
                }
                if (c == 0) {
                    raise_errmsg("Invalid \\escape", pystr, end - 2);
                    goto bail;
                }
            }
            else {
                c = 0;
                next++;
                end = next + 4;
                if (end >= len) {
                    raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
                    goto bail;
                }
                /* Decode 4 hex digits */
                for (; next < end; next++) {
                    Py_UNICODE digit = buf[next];
                    c <<= 4;
                    switch (digit) {
                        case '0': case '1': case '2': case '3': case '4':
                        case '5': case '6': case '7': case '8': case '9':
                            c |= (digit - '0'); break;
                        case 'a': case 'b': case 'c': case 'd': case 'e':
                        case 'f':
                            c |= (digit - 'a' + 10); break;
                        case 'A': case 'B': case 'C': case 'D': case 'E':
                        case 'F':
                            c |= (digit - 'A' + 10); break;
                        default:
                            raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
                            goto bail;
                    }
                }
    #ifdef Py_UNICODE_WIDE
                /* Surrogate pair */
                if ((c & 0xfc00) == 0xd800) {
                    Py_UNICODE c2 = 0;
                    if (end + 6 >= len) {
                        raise_errmsg("Unpaired high surrogate", pystr, end - 5);
                        goto bail;
                    }
                    if (buf[next++] != '\\' || buf[next++] != 'u') {
                        raise_errmsg("Unpaired high surrogate", pystr, end - 5);
                        goto bail;
                    }
                    end += 6;
                    /* Decode 4 hex digits */
                    for (; next < end; next++) {
                        c2 <<= 4;
                        Py_UNICODE digit = buf[next];
                        switch (digit) {
                            case '0': case '1': case '2': case '3': case '4':
                            case '5': case '6': case '7': case '8': case '9':
                                c2 |= (digit - '0'); break;
                            case 'a': case 'b': case 'c': case 'd': case 'e':
                            case 'f':
                                c2 |= (digit - 'a' + 10); break;
                            case 'A': case 'B': case 'C': case 'D': case 'E':
                            case 'F':
                                c2 |= (digit - 'A' + 10); break;
                            default:
                                raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
                                goto bail;
                        }
                    }
                    if ((c2 & 0xfc00) != 0xdc00) {
                        raise_errmsg("Unpaired high surrogate", pystr, end - 5);
                        goto bail;
                    }
                    c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
                }
                else if ((c & 0xfc00) == 0xdc00) {
                    raise_errmsg("Unpaired low surrogate", pystr, end - 5);
                    goto bail;
                }
    #endif
            }
            if (c > 0x7f) {
                has_unicode = 1;
            }
            APPEND_OLD_CHUNK
            if (has_unicode) {
                chunk = PyUnicode_FromUnicode(&c, 1);
                if (chunk == NULL) {
                    goto bail;
                }
            }
            else {
                char c_char = Py_CHARMASK(c);
                chunk = PyString_FromStringAndSize(&c_char, 1);
                if (chunk == NULL) {
                    goto bail;
                }
            }
        }
    
        if (chunks == NULL) {
            if (chunk != NULL)
                rval = chunk;
            else
                rval = PyString_FromStringAndSize("", 0);
        }
        else {
            APPEND_OLD_CHUNK
            rval = join_list_string(chunks);
            if (rval == NULL) {
                goto bail;
            }
            Py_CLEAR(chunks);
        }
    
        *next_end_ptr = end;
        return rval;
    bail:
        *next_end_ptr = -1;
        Py_XDECREF(chunk);
        Py_XDECREF(chunks);
        return NULL;
    }
    
    
    static PyObject *
    scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
    {
        /* Read the JSON string from PyUnicode pystr.
        end is the index of the first character after the quote.
        if strict is zero then literal control characters are allowed
        *next_end_ptr is a return-by-reference index of the character
            after the end quote
    
        Return value is a new PyUnicode
        */
        PyObject *rval;
        Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
        Py_ssize_t begin = end - 1;
        Py_ssize_t next = begin;
        const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
        PyObject *chunks = NULL;
        PyObject *chunk = NULL;
    
        if (len == end) {
            raise_errmsg("Unterminated string starting at", pystr, begin);
        }
        else if (end < 0 || len < end) {
            PyErr_SetString(PyExc_ValueError, "end is out of bounds");
            goto bail;
        }
        while (1) {
            /* Find the end of the string or the next escape */
            Py_UNICODE c = 0;
            for (next = end; next < len; next++) {
                c = buf[next];
                if (c == '"' || c == '\\') {
                    break;
                }
                else if (strict && c <= 0x1f) {
                    raise_errmsg("Invalid control character at", pystr, next);
                    goto bail;
                }
            }
            if (!(c == '"' || c == '\\')) {
                raise_errmsg("Unterminated string starting at", pystr, begin);
                goto bail;
            }
            /* Pick up this chunk if it's not zero length */
            if (next != end) {
                APPEND_OLD_CHUNK
                chunk = PyUnicode_FromUnicode(&buf[end], next - end);
                if (chunk == NULL) {
                    goto bail;
                }
            }
            next++;
            if (c == '"') {
                end = next;
                break;
            }
            if (next == len) {
                raise_errmsg("Unterminated string starting at", pystr, begin);
                goto bail;
            }
            c = buf[next];
            if (c != 'u') {
                /* Non-unicode backslash escapes */
                end = next + 1;
                switch (c) {
                    case '"': break;
                    case '\\': break;
                    case '/': break;
                    case 'b': c = '\b'; break;
                    case 'f': c = '\f'; break;
                    case 'n': c = '\n'; break;
                    case 'r': c = '\r'; break;
                    case 't': c = '\t'; break;
                    default: c = 0;
                }
                if (c == 0) {
                    raise_errmsg("Invalid \\escape", pystr, end - 2);
                    goto bail;
                }
            }
            else {
                c = 0;
                next++;
                end = next + 4;
                if (end >= len) {
                    raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
                    goto bail;
                }
                /* Decode 4 hex digits */
                for (; next < end; next++) {
                    Py_UNICODE digit = buf[next];
                    c <<= 4;
                    switch (digit) {
                        case '0': case '1': case '2': case '3': case '4':
                        case '5': case '6': case '7': case '8': case '9':
                            c |= (digit - '0'); break;
                        case 'a': case 'b': case 'c': case 'd': case 'e':
                        case 'f':
                            c |= (digit - 'a' + 10); break;
                        case 'A': case 'B': case 'C': case 'D': case 'E':
                        case 'F':
                            c |= (digit - 'A' + 10); break;
                        default:
                            raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
                            goto bail;
                    }
                }
    #ifdef Py_UNICODE_WIDE
                /* Surrogate pair */
                if ((c & 0xfc00) == 0xd800) {
                    Py_UNICODE c2 = 0;
                    if (end + 6 >= len) {
                        raise_errmsg("Unpaired high surrogate", pystr, end - 5);
                        goto bail;
                    }
                    if (buf[next++] != '\\' || buf[next++] != 'u') {
                        raise_errmsg("Unpaired high surrogate", pystr, end - 5);
                        goto bail;
                    }
                    end += 6;
                    /* Decode 4 hex digits */
                    for (; next < end; next++) {
                        c2 <<= 4;
                        Py_UNICODE digit = buf[next];
                        switch (digit) {
                            case '0': case '1': case '2': case '3': case '4':
                            case '5': case '6': case '7': case '8': case '9':
                                c2 |= (digit - '0'); break;
                            case 'a': case 'b': case 'c': case 'd': case 'e':
                            case 'f':
                                c2 |= (digit - 'a' + 10); break;
                            case 'A': case 'B': case 'C': case 'D': case 'E':
                            case 'F':
                                c2 |= (digit - 'A' + 10); break;
                            default:
                                raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
                                goto bail;
                        }
                    }
                    if ((c2 & 0xfc00) != 0xdc00) {
                        raise_errmsg("Unpaired high surrogate", pystr, end - 5);
                        goto bail;
                    }
                    c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
                }
                else if ((c & 0xfc00) == 0xdc00) {
                    raise_errmsg("Unpaired low surrogate", pystr, end - 5);
                    goto bail;
                }
    #endif
            }
            APPEND_OLD_CHUNK
            chunk = PyUnicode_FromUnicode(&c, 1);
            if (chunk == NULL) {
                goto bail;
            }
        }
    
        if (chunks == NULL) {
            if (chunk != NULL)
                rval = chunk;
            else
                rval = PyUnicode_FromUnicode(NULL, 0);
        }
        else {
            APPEND_OLD_CHUNK
            rval = join_list_unicode(chunks);
            if (rval == NULL) {
                goto bail;
            }
            Py_CLEAR(chunks);
        }
        *next_end_ptr = end;
        return rval;
    bail:
        *next_end_ptr = -1;
        Py_XDECREF(chunk);
        Py_XDECREF(chunks);
        return NULL;
    }
    
    PyDoc_STRVAR(pydoc_scanstring,
        "scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
        "\n"
        "Scan the string s for a JSON string. End is the index of the\n"
        "character in s after the quote that started the JSON string.\n"
        "Unescapes all valid JSON string escape sequences and raises ValueError\n"
        "on attempt to decode an invalid string. If strict is False then literal\n"
        "control characters are allowed in the string.\n"
        "\n"
        "Returns a tuple of the decoded string and the index of the character in s\n"
        "after the end quote."
    );
    
    static PyObject *
    py_scanstring(PyObject* self UNUSED, PyObject *args)
    {
        PyObject *pystr;
        PyObject *rval;
        Py_ssize_t end;
        Py_ssize_t next_end = -1;
        char *encoding = NULL;
        int strict = 1;
        if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
            return NULL;
        }
        if (encoding == NULL) {
            encoding = DEFAULT_ENCODING;
        }
        if (PyString_Check(pystr)) {
            rval = scanstring_str(pystr, end, encoding, strict, &next_end);
        }
        else if (PyUnicode_Check(pystr)) {
            rval = scanstring_unicode(pystr, end, strict, &next_end);
        }
        else {
            PyErr_Format(PyExc_TypeError,
                         "first argument must be a string, not %.80s",
                         Py_TYPE(pystr)->tp_name);
            return NULL;
        }
        return _build_rval_index_tuple(rval, next_end);
    }
    
    PyDoc_STRVAR(pydoc_encode_basestring_ascii,
        "encode_basestring_ascii(basestring) -> str\n"
        "\n"
        "Return an ASCII-only JSON representation of a Python string"
    );
    
    static PyObject *
    py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
    {
        /* Return an ASCII-only JSON representation of a Python string */
        /* METH_O */
        if (PyString_Check(pystr)) {
            return ascii_escape_str(pystr);
        }
        else if (PyUnicode_Check(pystr)) {
            return ascii_escape_unicode(pystr);
        }
        else {
            PyErr_Format(PyExc_TypeError,
                         "first argument must be a string, not %.80s",
                         Py_TYPE(pystr)->tp_name);
            return NULL;
        }
    }
    
    static void
    scanner_dealloc(PyObject *self)
    {
        /* Deallocate scanner object */
        scanner_clear(self);
        Py_TYPE(self)->tp_free(self);
    }
    
    static int
    scanner_traverse(PyObject *self, visitproc visit, void *arg)
    {
        PyScannerObject *s;
        assert(PyScanner_Check(self));
        s = (PyScannerObject *)self;
        Py_VISIT(s->encoding);
        Py_VISIT(s->strict);
        Py_VISIT(s->object_hook);
        Py_VISIT(s->pairs_hook);
        Py_VISIT(s->parse_float);
        Py_VISIT(s->parse_int);
        Py_VISIT(s->parse_constant);
        Py_VISIT(s->memo);
        return 0;
    }
    
    static int
    scanner_clear(PyObject *self)
    {
        PyScannerObject *s;
        assert(PyScanner_Check(self));
        s = (PyScannerObject *)self;
        Py_CLEAR(s->encoding);
        Py_CLEAR(s->strict);
        Py_CLEAR(s->object_hook);
        Py_CLEAR(s->pairs_hook);
        Py_CLEAR(s->parse_float);
        Py_CLEAR(s->parse_int);
        Py_CLEAR(s->parse_constant);
        Py_CLEAR(s->memo);
        return 0;
    }
    
    static PyObject *
    _parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON object from PyString pystr.
        idx is the index of the first character after the opening curly brace.
        *next_idx_ptr is a return-by-reference index to the first character after
            the closing curly brace.
    
        Returns a new PyObject (usually a dict, but object_hook or
        object_pairs_hook can change that)
        */
        char *str = PyString_AS_STRING(pystr);
        Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
        PyObject *rval = NULL;
        PyObject *pairs = NULL;
        PyObject *item;
        PyObject *key = NULL;
        PyObject *val = NULL;
        char *encoding = PyString_AS_STRING(s->encoding);
        int strict = PyObject_IsTrue(s->strict);
        int has_pairs_hook = (s->pairs_hook != Py_None);
        Py_ssize_t next_idx;
        if (has_pairs_hook) {
            pairs = PyList_New(0);
            if (pairs == NULL)
                return NULL;
        }
        else {
            rval = PyDict_New();
            if (rval == NULL)
                return NULL;
        }
    
        /* skip whitespace after { */
        while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
        /* only loop if the object is non-empty */
        if (idx <= end_idx && str[idx] != '}') {
            while (idx <= end_idx) {
                PyObject *memokey;
    
                /* read key */
                if (str[idx] != '"') {
                    raise_errmsg(
                        "Expecting property name enclosed in double quotes",
                        pystr, idx);
                    goto bail;
                }
                key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
                if (key == NULL)
                    goto bail;
                memokey = PyDict_GetItem(s->memo, key);
                if (memokey != NULL) {
                    Py_INCREF(memokey);
                    Py_DECREF(key);
                    key = memokey;
                }
                else {
                    if (PyDict_SetItem(s->memo, key, key) < 0)
                        goto bail;
                }
                idx = next_idx;
    
                /* skip whitespace between key and : delimiter, read :, skip whitespace */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
                if (idx > end_idx || str[idx] != ':') {
                    raise_errmsg("Expecting ':' delimiter", pystr, idx);
                    goto bail;
                }
                idx++;
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
                /* read any JSON data type */
                val = scan_once_str(s, pystr, idx, &next_idx);
                if (val == NULL)
                    goto bail;
    
                if (has_pairs_hook) {
                    item = PyTuple_Pack(2, key, val);
                    if (item == NULL)
                        goto bail;
                    Py_CLEAR(key);
                    Py_CLEAR(val);
                    if (PyList_Append(pairs, item) == -1) {
                        Py_DECREF(item);
                        goto bail;
                    }
                    Py_DECREF(item);
                }
                else {
                    if (PyDict_SetItem(rval, key, val) < 0)
                        goto bail;
                    Py_CLEAR(key);
                    Py_CLEAR(val);
                }
                idx = next_idx;
    
                /* skip whitespace before } or , */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
                /* bail if the object is closed or we didn't get the , delimiter */
                if (idx > end_idx) break;
                if (str[idx] == '}') {
                    break;
                }
                else if (str[idx] != ',') {
                    raise_errmsg("Expecting ',' delimiter", pystr, idx);
                    goto bail;
                }
                idx++;
    
                /* skip whitespace after , delimiter */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
            }
        }
        /* verify that idx < end_idx, str[idx] should be '}' */
        if (idx > end_idx || str[idx] != '}') {
            raise_errmsg("Expecting object", pystr, end_idx);
            goto bail;
        }
    
        /* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
        if (s->pairs_hook != Py_None) {
            val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
            if (val == NULL)
                goto bail;
            Py_DECREF(pairs);
            *next_idx_ptr = idx + 1;
            return val;
        }
    
        /* if object_hook is not None: rval = object_hook(rval) */
        if (s->object_hook != Py_None) {
            val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
            if (val == NULL)
                goto bail;
            Py_DECREF(rval);
            rval = val;
            val = NULL;
        }
        *next_idx_ptr = idx + 1;
        return rval;
    bail:
        Py_XDECREF(rval);
        Py_XDECREF(key);
        Py_XDECREF(val);
        Py_XDECREF(pairs);
        return NULL;
    }
    
    static PyObject *
    _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON object from PyUnicode pystr.
        idx is the index of the first character after the opening curly brace.
        *next_idx_ptr is a return-by-reference index to the first character after
            the closing curly brace.
    
        Returns a new PyObject (usually a dict, but object_hook can change that)
        */
        Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
        Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
        PyObject *rval = NULL;
        PyObject *pairs = NULL;
        PyObject *item;
        PyObject *key = NULL;
        PyObject *val = NULL;
        int strict = PyObject_IsTrue(s->strict);
        int has_pairs_hook = (s->pairs_hook != Py_None);
        Py_ssize_t next_idx;
    
        if (has_pairs_hook) {
            pairs = PyList_New(0);
            if (pairs == NULL)
                return NULL;
        }
        else {
            rval = PyDict_New();
            if (rval == NULL)
                return NULL;
        }
    
        /* skip whitespace after { */
        while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
        /* only loop if the object is non-empty */
        if (idx <= end_idx && str[idx] != '}') {
            while (idx <= end_idx) {
                PyObject *memokey;
    
                /* read key */
                if (str[idx] != '"') {
                    raise_errmsg(
                        "Expecting property name enclosed in double quotes",
                        pystr, idx);
                    goto bail;
                }
                key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
                if (key == NULL)
                    goto bail;
                memokey = PyDict_GetItem(s->memo, key);
                if (memokey != NULL) {
                    Py_INCREF(memokey);
                    Py_DECREF(key);
                    key = memokey;
                }
                else {
                    if (PyDict_SetItem(s->memo, key, key) < 0)
                        goto bail;
                }
                idx = next_idx;
    
                /* skip whitespace between key and : delimiter, read :, skip
                   whitespace */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
                if (idx > end_idx || str[idx] != ':') {
                    raise_errmsg("Expecting ':' delimiter", pystr, idx);
                    goto bail;
                }
                idx++;
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
                /* read any JSON term */
                val = scan_once_unicode(s, pystr, idx, &next_idx);
                if (val == NULL)
                    goto bail;
    
                if (has_pairs_hook) {
                    item = PyTuple_Pack(2, key, val);
                    if (item == NULL)
                        goto bail;
                    Py_CLEAR(key);
                    Py_CLEAR(val);
                    if (PyList_Append(pairs, item) == -1) {
                        Py_DECREF(item);
                        goto bail;
                    }
                    Py_DECREF(item);
                }
                else {
                    if (PyDict_SetItem(rval, key, val) < 0)
                        goto bail;
                    Py_CLEAR(key);
                    Py_CLEAR(val);
                }
                idx = next_idx;
    
                /* skip whitespace before } or , */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
                /* bail if the object is closed or we didn't get the ,
                   delimiter */
                if (idx > end_idx) break;
                if (str[idx] == '}') {
                    break;
                }
                else if (str[idx] != ',') {
                    raise_errmsg("Expecting ',' delimiter", pystr, idx);
                    goto bail;
                }
                idx++;
    
                /* skip whitespace after , delimiter */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
            }
        }
    
        /* verify that idx < end_idx, str[idx] should be '}' */
        if (idx > end_idx || str[idx] != '}') {
            raise_errmsg("Expecting object", pystr, end_idx);
            goto bail;
        }
    
        /* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
        if (s->pairs_hook != Py_None) {
            val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
            if (val == NULL)
                goto bail;
            Py_DECREF(pairs);
            *next_idx_ptr = idx + 1;
            return val;
        }
    
        /* if object_hook is not None: rval = object_hook(rval) */
        if (s->object_hook != Py_None) {
            val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
            if (val == NULL)
                goto bail;
            Py_DECREF(rval);
            rval = val;
            val = NULL;
        }
        *next_idx_ptr = idx + 1;
        return rval;
    bail:
        Py_XDECREF(rval);
        Py_XDECREF(key);
        Py_XDECREF(val);
        Py_XDECREF(pairs);
        return NULL;
    }
    
    static PyObject *
    _parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON array from PyString pystr.
        idx is the index of the first character after the opening brace.
        *next_idx_ptr is a return-by-reference index to the first character after
            the closing brace.
    
        Returns a new PyList
        */
        char *str = PyString_AS_STRING(pystr);
        Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
        PyObject *val = NULL;
        PyObject *rval = PyList_New(0);
        Py_ssize_t next_idx;
        if (rval == NULL)
            return NULL;
    
        /* skip whitespace after [ */
        while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
        /* only loop if the array is non-empty */
        if (idx <= end_idx && str[idx] != ']') {
            while (idx <= end_idx) {
    
                /* read any JSON term and de-tuplefy the (rval, idx) */
                val = scan_once_str(s, pystr, idx, &next_idx);
                if (val == NULL) {
                    if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
                        PyErr_Clear();
                        raise_errmsg("Expecting object", pystr, idx);
                    }
                    goto bail;
                }
    
                if (PyList_Append(rval, val) == -1)
                    goto bail;
    
                Py_CLEAR(val);
                idx = next_idx;
    
                /* skip whitespace between term and , */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
                /* bail if the array is closed or we didn't get the , delimiter */
                if (idx > end_idx) break;
                if (str[idx] == ']') {
                    break;
                }
                else if (str[idx] != ',') {
                    raise_errmsg("Expecting ',' delimiter", pystr, idx);
                    goto bail;
                }
                idx++;
    
                /* skip whitespace after , */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
            }
        }
    
        /* verify that idx < end_idx, str[idx] should be ']' */
        if (idx > end_idx || str[idx] != ']') {
            raise_errmsg("Expecting object", pystr, end_idx);
            goto bail;
        }
        *next_idx_ptr = idx + 1;
        return rval;
    bail:
        Py_XDECREF(val);
        Py_DECREF(rval);
        return NULL;
    }
    
    static PyObject *
    _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON array from PyString pystr.
        idx is the index of the first character after the opening brace.
        *next_idx_ptr is a return-by-reference index to the first character after
            the closing brace.
    
        Returns a new PyList
        */
        Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
        Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
        PyObject *val = NULL;
        PyObject *rval = PyList_New(0);
        Py_ssize_t next_idx;
        if (rval == NULL)
            return NULL;
    
        /* skip whitespace after [ */
        while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
        /* only loop if the array is non-empty */
        if (idx <= end_idx && str[idx] != ']') {
            while (idx <= end_idx) {
    
                /* read any JSON term  */
                val = scan_once_unicode(s, pystr, idx, &next_idx);
                if (val == NULL) {
                    if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
                        PyErr_Clear();
                        raise_errmsg("Expecting object", pystr, idx);
                    }
                    goto bail;
                }
    
                if (PyList_Append(rval, val) == -1)
                    goto bail;
    
                Py_CLEAR(val);
                idx = next_idx;
    
                /* skip whitespace between term and , */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
    
                /* bail if the array is closed or we didn't get the , delimiter */
                if (idx > end_idx) break;
                if (str[idx] == ']') {
                    break;
                }
                else if (str[idx] != ',') {
                    raise_errmsg("Expecting ',' delimiter", pystr, idx);
                    goto bail;
                }
                idx++;
    
                /* skip whitespace after , */
                while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
            }
        }
    
        /* verify that idx < end_idx, str[idx] should be ']' */
        if (idx > end_idx || str[idx] != ']') {
            raise_errmsg("Expecting object", pystr, end_idx);
            goto bail;
        }
        *next_idx_ptr = idx + 1;
        return rval;
    bail:
        Py_XDECREF(val);
        Py_DECREF(rval);
        return NULL;
    }
    
    static PyObject *
    _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON constant from PyString pystr.
        constant is the constant string that was found
            ("NaN", "Infinity", "-Infinity").
        idx is the index of the first character of the constant
        *next_idx_ptr is a return-by-reference index to the first character after
            the constant.
    
        Returns the result of parse_constant
        */
        PyObject *cstr;
        PyObject *rval;
        /* constant is "NaN", "Infinity", or "-Infinity" */
        cstr = PyString_InternFromString(constant);
        if (cstr == NULL)
            return NULL;
    
        /* rval = parse_constant(constant) */
        rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
        idx += PyString_GET_SIZE(cstr);
        Py_DECREF(cstr);
        *next_idx_ptr = idx;
        return rval;
    }
    
    static PyObject *
    _match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON number from PyString pystr.
        idx is the index of the first character of the number
        *next_idx_ptr is a return-by-reference index to the first character after
            the number.
    
        Returns a new PyObject representation of that number:
            PyInt, PyLong, or PyFloat.
            May return other types if parse_int or parse_float are set
        */
        char *str = PyString_AS_STRING(pystr);
        Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
        Py_ssize_t idx = start;
        int is_float = 0;
        PyObject *rval;
        PyObject *numstr;
    
        /* read a sign if it's there, make sure it's not the end of the string */
        if (str[idx] == '-') {
            idx++;
            if (idx > end_idx) {
                PyErr_SetNone(PyExc_StopIteration);
                return NULL;
            }
        }
    
        /* read as many integer digits as we find as long as it doesn't start with 0 */
        if (str[idx] >= '1' && str[idx] <= '9') {
            idx++;
            while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
        }
        /* if it starts with 0 we only expect one integer digit */
        else if (str[idx] == '0') {
            idx++;
        }
        /* no integer digits, error */
        else {
            PyErr_SetNone(PyExc_StopIteration);
            return NULL;
        }
    
        /* if the next char is '.' followed by a digit then read all float digits */
        if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
            is_float = 1;
            idx += 2;
            while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
        }
    
        /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
        if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
    
            /* save the index of the 'e' or 'E' just in case we need to backtrack */
            Py_ssize_t e_start = idx;
            idx++;
    
            /* read an exponent sign if present */
            if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
    
            /* read all digits */
            while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
    
            /* if we got a digit, then parse as float. if not, backtrack */
            if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
                is_float = 1;
            }
            else {
                idx = e_start;
            }
        }
    
        /* copy the section we determined to be a number */
        numstr = PyString_FromStringAndSize(&str[start], idx - start);
        if (numstr == NULL)
            return NULL;
        if (is_float) {
            /* parse as a float using a fast path if available, otherwise call user defined method */
            if (s->parse_float != (PyObject *)&PyFloat_Type) {
                rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
            }
            else {
                /* rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr))); */
                double d = PyOS_string_to_double(PyString_AS_STRING(numstr),
                                                 NULL, NULL);
                if (d == -1.0 && PyErr_Occurred())
                    return NULL;
                rval = PyFloat_FromDouble(d);
            }
        }
        else {
            /* parse as an int using a fast path if available, otherwise call user defined method */
            if (s->parse_int != (PyObject *)&PyInt_Type) {
                rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
            }
            else {
                rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
            }
        }
        Py_DECREF(numstr);
        *next_idx_ptr = idx;
        return rval;
    }
    
    static PyObject *
    _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
        /* Read a JSON number from PyUnicode pystr.
        idx is the index of the first character of the number
        *next_idx_ptr is a return-by-reference index to the first character after
            the number.
    
        Returns a new PyObject representation of that number:
            PyInt, PyLong, or PyFloat.
            May return other types if parse_int or parse_float are set
        */
        Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
        Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
        Py_ssize_t idx = start;
        int is_float = 0;
        PyObject *rval;
        PyObject *numstr;
    
        /* read a sign if it's there, make sure it's not the end of the string */
        if (str[idx] == '-') {
            idx++;
            if (idx > end_idx) {
                PyErr_SetNone(PyExc_StopIteration);
                return NULL;
            }
        }
    
        /* read as many integer digits as we find as long as it doesn't start with 0 */
        if (str[idx] >= '1' && str[idx] <= '9') {
            idx++;
            while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
        }
        /* if it starts with 0 we only expect one integer digit */
        else if (str[idx] == '0') {
            idx++;
        }
        /* no integer digits, error */
        else {
            PyErr_SetNone(PyExc_StopIteration);
            return NULL;
        }
    
        /* if the next char is '.' followed by a digit then read all float digits */
        if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
            is_float = 1;
            idx += 2;
            while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
        }
    
        /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
        if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
            Py_ssize_t e_start = idx;
            idx++;
    
            /* read an exponent sign if present */
            if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
    
            /* read all digits */
            while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
    
            /* if we got a digit, then parse as float. if not, backtrack */
            if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
                is_float = 1;
            }
            else {
                idx = e_start;
            }
        }
    
        /* copy the section we determined to be a number */
        numstr = PyUnicode_FromUnicode(&str[start], idx - start);
        if (numstr == NULL)
            return NULL;
        if (is_float) {
            /* parse as a float using a fast path if available, otherwise call user defined method */
            if (s->parse_float != (PyObject *)&PyFloat_Type) {
                rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
            }
            else {
                rval = PyFloat_FromString(numstr, NULL);
            }
        }
        else {
            /* no fast path for unicode -> int, just call */
            rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
        }
        Py_DECREF(numstr);
        *next_idx_ptr = idx;
        return rval;
    }
    
    static PyObject *
    scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
    {
        /* Read one JSON term (of any kind) from PyString pystr.
        idx is the index of the first character of the term
        *next_idx_ptr is a return-by-reference index to the first character after
            the number.
    
        Returns a new PyObject representation of the term.
        */
        char *str = PyString_AS_STRING(pystr);
        Py_ssize_t length = PyString_GET_SIZE(pystr);
        PyObject *rval = NULL;
        int fallthrough = 0;
        if (idx >= length) {
            PyErr_SetNone(PyExc_StopIteration);
            return NULL;
        }
        if (Py_EnterRecursiveCall(" while decoding a JSON document"))
            return NULL;
        switch (str[idx]) {
            case '"':
                /* string */
                rval = scanstring_str(pystr, idx + 1,
                    PyString_AS_STRING(s->encoding),
                    PyObject_IsTrue(s->strict),
                    next_idx_ptr);
                break;
            case '{':
                /* object */
                rval = _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
                break;
            case '[':
                /* array */
                rval = _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
                break;
            case 'n':
                /* null */
                if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
                    Py_INCREF(Py_None);
                    *next_idx_ptr = idx + 4;
                    rval = Py_None;
                }
                else
                    fallthrough = 1;
                break;
            case 't':
                /* true */
                if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
                    Py_INCREF(Py_True);
                    *next_idx_ptr = idx + 4;
                    rval = Py_True;
                }
                else
                    fallthrough = 1;
                break;
            case 'f':
                /* false */
                if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
                    Py_INCREF(Py_False);
                    *next_idx_ptr = idx + 5;
                    rval = Py_False;
                }
                else
                    fallthrough = 1;
                break;
            case 'N':
                /* NaN */
                if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
                    rval = _parse_constant(s, "NaN", idx, next_idx_ptr);
                }
                else
                    fallthrough = 1;
                break;
            case 'I':
                /* Infinity */
                if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
                    rval = _parse_constant(s, "Infinity", idx, next_idx_ptr);
                }
                else
                    fallthrough = 1;
                break;
            case '-':
                /* -Infinity */
                if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
                    rval = _parse_constant(s, "-Infinity", idx, next_idx_ptr);
                }
                else
                    fallthrough = 1;
                break;
            default:
                fallthrough = 1;
        }
        /* Didn't find a string, object, array, or named constant. Look for a number. */
        if (fallthrough)
            rval = _match_number_str(s, pystr, idx, next_idx_ptr);
        Py_LeaveRecursiveCall();
        return rval;
    }
    
    static PyObject *
    scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
    {
        /* Read one JSON term (of any kind) from PyUnicode pystr.
        idx is the index of the first character of the term
        *next_idx_ptr is a return-by-reference index to the first character after
            the number.
    
        Returns a new PyObject representation of the term.
        */
        Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
        Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
        PyObject *rval = NULL;
        int fallthrough = 0;
        if (idx >= length) {
            PyErr_SetNone(PyExc_StopIteration);
            return NULL;
        }
        if (Py_EnterRecursiveCall(" while decoding a JSON document"))
            return NULL;
        switch (str[idx]) {
            case '"':
                /* string */
                rval = scanstring_unicode(pystr, idx + 1,
                    PyObject_IsTrue(s->strict),
                    next_idx_ptr);
                break;
            case '{':
                /* object */
                rval = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
                break;
            case '[':
                /* array */
                rval = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
                break;
            case 'n':
                /* null */
                if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
                    Py_INCREF(Py_None);
                    *next_idx_ptr = idx + 4;
                    rval = Py_None;
                }
                else
                    fallthrough = 1;
                break;
            case 't':
                /* true */
                if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
                    Py_INCREF(Py_True);
                    *next_idx_ptr = idx + 4;
                    rval = Py_True;
                }
                else
                    fallthrough = 1;
                break;
            case 'f':
                /* false */
                if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
                    Py_INCREF(Py_False);
                    *next_idx_ptr = idx + 5;
                    rval = Py_False;
                }
                else
                    fallthrough = 1;
                break;
            case 'N':
                /* NaN */
                if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
                    rval = _parse_constant(s, "NaN", idx, next_idx_ptr);
                }
                else
                    fallthrough = 1;
                break;
            case 'I':
                /* Infinity */
                if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
                    rval = _parse_constant(s, "Infinity", idx, next_idx_ptr);
                }
                else
                    fallthrough = 1;
                break;
            case '-':
                /* -Infinity */
                if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
                    rval = _parse_constant(s, "-Infinity", idx, next_idx_ptr);
                }
                else
                    fallthrough = 1;
                break;
            default:
                fallthrough = 1;
        }
        /* Didn't find a string, object, array, or named constant. Look for a number. */
        if (fallthrough)
            rval = _match_number_unicode(s, pystr, idx, next_idx_ptr);
        Py_LeaveRecursiveCall();
        return rval;
    }
    
    static PyObject *
    scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
    {
        /* Python callable interface to scan_once_{str,unicode} */
        PyObject *pystr;
        PyObject *rval;
        Py_ssize_t idx;
        Py_ssize_t next_idx = -1;
        static char *kwlist[] = {"string", "idx", NULL};
        PyScannerObject *s;
        assert(PyScanner_Check(self));
        s = (PyScannerObject *)self;
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
            return NULL;
    
        if (PyString_Check(pystr)) {
            rval = scan_once_str(s, pystr, idx, &next_idx);
        }
        else if (PyUnicode_Check(pystr)) {
            rval = scan_once_unicode(s, pystr, idx, &next_idx);
        }
        else {
            PyErr_Format(PyExc_TypeError,
                     "first argument must be a string, not %.80s",
                     Py_TYPE(pystr)->tp_name);
            return NULL;
        }
        PyDict_Clear(s->memo);
        return _build_rval_index_tuple(rval, next_idx);
    }
    
    static PyObject *
    scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    {
        PyScannerObject *s;
        s = (PyScannerObject *)type->tp_alloc(type, 0);
        if (s != NULL) {
            s->encoding = NULL;
            s->strict = NULL;
            s->object_hook = NULL;
            s->pairs_hook = NULL;
            s->parse_float = NULL;
            s->parse_int = NULL;
            s->parse_constant = NULL;
        }
        return (PyObject *)s;
    }
    
    static int
    scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
    {
        /* Initialize Scanner object */
        PyObject *ctx;
        static char *kwlist[] = {"context", NULL};
        PyScannerObject *s;
    
        assert(PyScanner_Check(self));
        s = (PyScannerObject *)self;
    
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
            return -1;
    
        if (s->memo == NULL) {
            s->memo = PyDict_New();
            if (s->memo == NULL)
                goto bail;
        }
    
        /* PyString_AS_STRING is used on encoding */
        s->encoding = PyObject_GetAttrString(ctx, "encoding");
        if (s->encoding == NULL)
            goto bail;
        if (s->encoding == Py_None) {
            Py_DECREF(Py_None);
            s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
        }
        else if (PyUnicode_Check(s->encoding)) {
            PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
            Py_DECREF(s->encoding);
            s->encoding = tmp;
        }
        if (s->encoding == NULL || !PyString_Check(s->encoding))
            goto bail;
    
        /* All of these will fail "gracefully" so we don't need to verify them */
        s->strict = PyObject_GetAttrString(ctx, "strict");
        if (s->strict == NULL)
            goto bail;
        s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
        if (s->object_hook == NULL)
            goto bail;
        s->pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook");
        if (s->pairs_hook == NULL)
            goto bail;
        s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
        if (s->parse_float == NULL)
            goto bail;
        s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
        if (s->parse_int == NULL)
            goto bail;
        s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
        if (s->parse_constant == NULL)
            goto bail;
    
        return 0;
    
    bail:
        Py_CLEAR(s->encoding);
        Py_CLEAR(s->strict);
        Py_CLEAR(s->object_hook);
        Py_CLEAR(s->pairs_hook);
        Py_CLEAR(s->parse_float);
        Py_CLEAR(s->parse_int);
        Py_CLEAR(s->parse_constant);
        return -1;
    }
    
    PyDoc_STRVAR(scanner_doc, "JSON scanner object");
    
    static
    PyTypeObject PyScannerType = {
        PyObject_HEAD_INIT(NULL)
        0,                    /* tp_internal */
        "simplejson._speedups.Scanner",       /* tp_name */
        sizeof(PyScannerObject), /* tp_basicsize */
        0,                    /* tp_itemsize */
        scanner_dealloc, /* tp_dealloc */
        0,                    /* tp_print */
        0,                    /* tp_getattr */
        0,                    /* tp_setattr */
        0,                    /* tp_compare */
        0,                    /* tp_repr */
        0,                    /* tp_as_number */
        0,                    /* tp_as_sequence */
        0,                    /* tp_as_mapping */
        0,                    /* tp_hash */
        scanner_call,         /* tp_call */
        0,                    /* tp_str */
        0,/* PyObject_GenericGetAttr, */                    /* tp_getattro */
        0,/* PyObject_GenericSetAttr, */                    /* tp_setattro */
        0,                    /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,   /* tp_flags */
        scanner_doc,          /* tp_doc */
        scanner_traverse,                    /* tp_traverse */
        scanner_clear,                    /* tp_clear */
        0,                    /* tp_richcompare */
        0,                    /* tp_weaklistoffset */
        0,                    /* tp_iter */
        0,                    /* tp_iternext */
        0,                    /* tp_methods */
        scanner_members,                    /* tp_members */
        0,                    /* tp_getset */
        0,                    /* tp_base */
        0,                    /* tp_dict */
        0,                    /* tp_descr_get */
        0,                    /* tp_descr_set */
        0,                    /* tp_dictoffset */
        scanner_init,                    /* tp_init */
        0,/* PyType_GenericAlloc, */        /* tp_alloc */
        scanner_new,          /* tp_new */
        0,/* PyObject_GC_Del, */              /* tp_free */
    };
    
    static PyObject *
    encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    {
        PyEncoderObject *s;
        s = (PyEncoderObject *)type->tp_alloc(type, 0);
        if (s != NULL) {
            s->markers = NULL;
            s->defaultfn = NULL;
            s->encoder = NULL;
            s->indent = NULL;
            s->key_separator = NULL;
            s->item_separator = NULL;
            s->sort_keys = NULL;
            s->skipkeys = NULL;
            s->key_memo = NULL;
            s->item_sort_key = NULL;
            s->Decimal = NULL;
        }
        return (PyObject *)s;
    }
    
    static int
    encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
    {
        /* initialize Encoder object */
        static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", "key_memo", "use_decimal", "namedtuple_as_object", "tuple_as_array", "bigint_as_string", "item_sort_key", "Decimal", NULL};
    
        PyEncoderObject *s;
        PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
        PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan, *key_memo;
        PyObject *use_decimal, *namedtuple_as_object, *tuple_as_array;
        PyObject *bigint_as_string, *item_sort_key, *Decimal;
    
        assert(PyEncoder_Check(self));
        s = (PyEncoderObject *)self;
    
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOOOOOOOO:make_encoder", kwlist,
            &markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator,
            &sort_keys, &skipkeys, &allow_nan, &key_memo, &use_decimal,
            &namedtuple_as_object, &tuple_as_array, &bigint_as_string,
            &item_sort_key, &Decimal))
            return -1;
    
        s->markers = markers;
        s->defaultfn = defaultfn;
        s->encoder = encoder;
        s->indent = indent;
        s->key_separator = key_separator;
        s->item_separator = item_separator;
        s->sort_keys = sort_keys;
        s->skipkeys = skipkeys;
        s->key_memo = key_memo;
        s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
        s->allow_nan = PyObject_IsTrue(allow_nan);
        s->use_decimal = PyObject_IsTrue(use_decimal);
        s->namedtuple_as_object = PyObject_IsTrue(namedtuple_as_object);
        s->tuple_as_array = PyObject_IsTrue(tuple_as_array);
        s->bigint_as_string = PyObject_IsTrue(bigint_as_string);
        s->item_sort_key = item_sort_key;
        s->Decimal = Decimal;
    
        Py_INCREF(s->markers);
        Py_INCREF(s->defaultfn);
        Py_INCREF(s->encoder);
        Py_INCREF(s->indent);
        Py_INCREF(s->key_separator);
        Py_INCREF(s->item_separator);
        Py_INCREF(s->sort_keys);
        Py_INCREF(s->skipkeys);
        Py_INCREF(s->key_memo);
        Py_INCREF(s->item_sort_key);
        Py_INCREF(s->Decimal);
        return 0;
    }
    
    static PyObject *
    encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
    {
        /* Python callable interface to encode_listencode_obj */
        static char *kwlist[] = {"obj", "_current_indent_level", NULL};
        PyObject *obj;
        PyObject *rval;
        Py_ssize_t indent_level;
        PyEncoderObject *s;
        assert(PyEncoder_Check(self));
        s = (PyEncoderObject *)self;
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
            &obj, _convertPyInt_AsSsize_t, &indent_level))
            return NULL;
        rval = PyList_New(0);
        if (rval == NULL)
            return NULL;
        if (encoder_listencode_obj(s, rval, obj, indent_level)) {
            Py_DECREF(rval);
            return NULL;
        }
        return rval;
    }
    
    static PyObject *
    _encoded_const(PyObject *obj)
    {
        /* Return the JSON string representation of None, True, False */
        if (obj == Py_None) {
            static PyObject *s_null = NULL;
            if (s_null == NULL) {
                s_null = PyString_InternFromString("null");
            }
            Py_INCREF(s_null);
            return s_null;
        }
        else if (obj == Py_True) {
            static PyObject *s_true = NULL;
            if (s_true == NULL) {
                s_true = PyString_InternFromString("true");
            }
            Py_INCREF(s_true);
            return s_true;
        }
        else if (obj == Py_False) {
            static PyObject *s_false = NULL;
            if (s_false == NULL) {
                s_false = PyString_InternFromString("false");
            }
            Py_INCREF(s_false);
            return s_false;
        }
        else {
            PyErr_SetString(PyExc_ValueError, "not a const");
            return NULL;
        }
    }
    
    static PyObject *
    encoder_encode_float(PyEncoderObject *s, PyObject *obj)
    {
        /* Return the JSON representation of a PyFloat */
        double i = PyFloat_AS_DOUBLE(obj);
        if (!Py_IS_FINITE(i)) {
            if (!s->allow_nan) {
                PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
                return NULL;
            }
            if (i > 0) {
                return PyString_FromString("Infinity");
            }
            else if (i < 0) {
                return PyString_FromString("-Infinity");
            }
            else {
                return PyString_FromString("NaN");
            }
        }
        /* Use a better float format here? */
        return PyObject_Repr(obj);
    }
    
    static PyObject *
    encoder_encode_string(PyEncoderObject *s, PyObject *obj)
    {
        /* Return the JSON representation of a string */
        if (s->fast_encode)
            return py_encode_basestring_ascii(NULL, obj);
        else
            return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
    }
    
    static int
    _steal_list_append(PyObject *lst, PyObject *stolen)
    {
        /* Append stolen and then decrement its reference count */
        int rval = PyList_Append(lst, stolen);
        Py_DECREF(stolen);
        return rval;
    }
    
    static int
    encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
    {
        /* Encode Python object obj to a JSON term, rval is a PyList */
        int rv = -1;
        if (Py_EnterRecursiveCall(" while encoding a JSON document"))
            return rv;
        do {
            if (obj == Py_None || obj == Py_True || obj == Py_False) {
                PyObject *cstr = _encoded_const(obj);
                if (cstr != NULL)
                    rv = _steal_list_append(rval, cstr);
            }
            else if (PyString_Check(obj) || PyUnicode_Check(obj))
            {
                PyObject *encoded = encoder_encode_string(s, obj);
                if (encoded != NULL)
                    rv = _steal_list_append(rval, encoded);
            }
            else if (PyInt_Check(obj) || PyLong_Check(obj)) {
                PyObject *encoded = PyObject_Str(obj);
                if (encoded != NULL) {
                    if (s->bigint_as_string) {
                        encoded = maybe_quote_bigint(encoded, obj);
                        if (encoded == NULL)
                            break;
                    }
                    rv = _steal_list_append(rval, encoded);
                }
            }
            else if (PyFloat_Check(obj)) {
                PyObject *encoded = encoder_encode_float(s, obj);
                if (encoded != NULL)
                    rv = _steal_list_append(rval, encoded);
            }
            else if (s->namedtuple_as_object && _is_namedtuple(obj)) {
                PyObject *newobj = PyObject_CallMethod(obj, "_asdict", NULL);
                if (newobj != NULL) {
                    rv = encoder_listencode_dict(s, rval, newobj, indent_level);
                    Py_DECREF(newobj);
                }
            }
            else if (PyList_Check(obj) || (s->tuple_as_array && PyTuple_Check(obj))) {
                rv = encoder_listencode_list(s, rval, obj, indent_level);
            }
            else if (PyDict_Check(obj)) {
                rv = encoder_listencode_dict(s, rval, obj, indent_level);
            }
            else if (s->use_decimal && PyObject_TypeCheck(obj, s->Decimal)) {
                PyObject *encoded = PyObject_Str(obj);
                if (encoded != NULL)
                    rv = _steal_list_append(rval, encoded);
            }
            else {
                PyObject *ident = NULL;
                PyObject *newobj;
                if (s->markers != Py_None) {
                    int has_key;
                    ident = PyLong_FromVoidPtr(obj);
                    if (ident == NULL)
                        break;
                    has_key = PyDict_Contains(s->markers, ident);
                    if (has_key) {
                        if (has_key != -1)
                            PyErr_SetString(PyExc_ValueError, "Circular reference detected");
                        Py_DECREF(ident);
                        break;
                    }
                    if (PyDict_SetItem(s->markers, ident, obj)) {
                        Py_DECREF(ident);
                        break;
                    }
                }
                newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
                if (newobj == NULL) {
                    Py_XDECREF(ident);
                    break;
                }
                rv = encoder_listencode_obj(s, rval, newobj, indent_level);
                Py_DECREF(newobj);
                if (rv) {
                    Py_XDECREF(ident);
                    rv = -1;
                }
                else if (ident != NULL) {
                    if (PyDict_DelItem(s->markers, ident)) {
                        Py_XDECREF(ident);
                        rv = -1;
                    }
                    Py_XDECREF(ident);
                }
            }
        } while (0);
        Py_LeaveRecursiveCall();
        return rv;
    }
    
    static int
    encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
    {
        /* Encode Python dict dct a JSON term, rval is a PyList */
        static PyObject *open_dict = NULL;
        static PyObject *close_dict = NULL;
        static PyObject *empty_dict = NULL;
        static PyObject *iteritems = NULL;
        PyObject *kstr = NULL;
        PyObject *ident = NULL;
        PyObject *iter = NULL;
        PyObject *item = NULL;
        PyObject *items = NULL;
        PyObject *encoded = NULL;
        int skipkeys;
        Py_ssize_t idx;
    
        if (open_dict == NULL || close_dict == NULL || empty_dict == NULL || iteritems == NULL) {
            open_dict = PyString_InternFromString("{");
            close_dict = PyString_InternFromString("}");
            empty_dict = PyString_InternFromString("{}");
            iteritems = PyString_InternFromString("iteritems");
            if (open_dict == NULL || close_dict == NULL || empty_dict == NULL || iteritems == NULL)
                return -1;
        }
        if (PyDict_Size(dct) == 0)
            return PyList_Append(rval, empty_dict);
    
        if (s->markers != Py_None) {
            int has_key;
            ident = PyLong_FromVoidPtr(dct);
            if (ident == NULL)
                goto bail;
            has_key = PyDict_Contains(s->markers, ident);
            if (has_key) {
                if (has_key != -1)
                    PyErr_SetString(PyExc_ValueError, "Circular reference detected");
                goto bail;
            }
            if (PyDict_SetItem(s->markers, ident, dct)) {
                goto bail;
            }
        }
    
        if (PyList_Append(rval, open_dict))
            goto bail;
    
        if (s->indent != Py_None) {
            /* TODO: DOES NOT RUN */
            indent_level += 1;
            /*
                newline_indent = '\n' + (_indent * _current_indent_level)
                separator = _item_separator + newline_indent
                buf += newline_indent
            */
        }
    
        if (PyCallable_Check(s->item_sort_key)) {
            if (PyDict_CheckExact(dct))
                items = PyDict_Items(dct);
            else
                items = PyMapping_Items(dct);
            PyObject_CallMethod(items, "sort", "OO", Py_None, s->item_sort_key);
        }
        else if (PyObject_IsTrue(s->sort_keys)) {
            /* First sort the keys then replace them with (key, value) tuples. */
            Py_ssize_t i, nitems;
            if (PyDict_CheckExact(dct))
                items = PyDict_Keys(dct);
            else
                items = PyMapping_Keys(dct);
            if (items == NULL)
                goto bail;
            if (!PyList_Check(items)) {
                PyErr_SetString(PyExc_ValueError, "keys must return list");
                goto bail;
            }
            if (PyList_Sort(items) < 0)
                goto bail;
            nitems = PyList_GET_SIZE(items);
            for (i = 0; i < nitems; i++) {
                PyObject *key, *value;
                key = PyList_GET_ITEM(items, i);
                value = PyDict_GetItem(dct, key);
                item = PyTuple_Pack(2, key, value);
                if (item == NULL)
                    goto bail;
                PyList_SET_ITEM(items, i, item);
                Py_DECREF(key);
            }
        }
        else {
            if (PyDict_CheckExact(dct))
                items = PyDict_Items(dct);
            else
                items = PyMapping_Items(dct);
        }
        if (items == NULL)
            goto bail;
        iter = PyObject_GetIter(items);
        Py_DECREF(items);
        if (iter == NULL)
            goto bail;
    
        skipkeys = PyObject_IsTrue(s->skipkeys);
        idx = 0;
        while ((item = PyIter_Next(iter))) {
            PyObject *encoded, *key, *value;
            if (!PyTuple_Check(item) || Py_SIZE(item) != 2) {
                PyErr_SetString(PyExc_ValueError, "items must return 2-tuples");
                goto bail;
            }
            key = PyTuple_GET_ITEM(item, 0);
            if (key == NULL)
                goto bail;
            value = PyTuple_GET_ITEM(item, 1);
            if (value == NULL)
                goto bail;
    
            encoded = PyDict_GetItem(s->key_memo, key);
            if (encoded != NULL) {
                Py_INCREF(encoded);
            }
            else if (PyString_Check(key) || PyUnicode_Check(key)) {
                Py_INCREF(key);
                kstr = key;
            }
            else if (PyFloat_Check(key)) {
                kstr = encoder_encode_float(s, key);
                if (kstr == NULL)
                    goto bail;
            }
            else if (key == Py_True || key == Py_False || key == Py_None) {
                /* This must come before the PyInt_Check because
                   True and False are also 1 and 0.*/
                kstr = _encoded_const(key);
                if (kstr == NULL)
                    goto bail;
            }
            else if (PyInt_Check(key) || PyLong_Check(key)) {
                kstr = PyObject_Str(key);
                if (kstr == NULL)
                    goto bail;
            }
            else if (skipkeys) {
                Py_DECREF(item);
                continue;
            }
            else {
                /* TODO: include repr of key */
                PyErr_SetString(PyExc_TypeError, "keys must be a string");
                goto bail;
            }
    
            if (idx) {
                if (PyList_Append(rval, s->item_separator))
                    goto bail;
            }
    
            if (encoded == NULL) {
                encoded = encoder_encode_string(s, kstr);
                Py_CLEAR(kstr);
                if (encoded == NULL)
                    goto bail;
                if (PyDict_SetItem(s->key_memo, key, encoded))
                    goto bail;
            }
            if (PyList_Append(rval, encoded)) {
                goto bail;
            }
            Py_CLEAR(encoded);
            if (PyList_Append(rval, s->key_separator))
                goto bail;
            if (encoder_listencode_obj(s, rval, value, indent_level))
                goto bail;
            Py_CLEAR(item);
            idx += 1;
        }
        Py_CLEAR(iter);
        if (PyErr_Occurred())
            goto bail;
        if (ident != NULL) {
            if (PyDict_DelItem(s->markers, ident))
                goto bail;
            Py_CLEAR(ident);
        }
        if (s->indent != Py_None) {
            /* TODO: DOES NOT RUN */
            indent_level -= 1;
            /*
                yield '\n' + (_indent * _current_indent_level)
            */
        }
        if (PyList_Append(rval, close_dict))
            goto bail;
        return 0;
    
    bail:
        Py_XDECREF(encoded);
        Py_XDECREF(items);
        Py_XDECREF(iter);
        Py_XDECREF(kstr);
        Py_XDECREF(ident);
        return -1;
    }
    
    
    static int
    encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
    {
        /* Encode Python list seq to a JSON term, rval is a PyList */
        static PyObject *open_array = NULL;
        static PyObject *close_array = NULL;
        static PyObject *empty_array = NULL;
        PyObject *ident = NULL;
        PyObject *iter = NULL;
        PyObject *obj = NULL;
        int is_true;
        int i = 0;
    
        if (open_array == NULL || close_array == NULL || empty_array == NULL) {
            open_array = PyString_InternFromString("[");
            close_array = PyString_InternFromString("]");
            empty_array = PyString_InternFromString("[]");
            if (open_array == NULL || close_array == NULL || empty_array == NULL)
                return -1;
        }
        ident = NULL;
        is_true = PyObject_IsTrue(seq);
        if (is_true == -1)
            return -1;
        else if (is_true == 0)
            return PyList_Append(rval, empty_array);
    
        if (s->markers != Py_None) {
            int has_key;
            ident = PyLong_FromVoidPtr(seq);
            if (ident == NULL)
                goto bail;
            has_key = PyDict_Contains(s->markers, ident);
            if (has_key) {
                if (has_key != -1)
                    PyErr_SetString(PyExc_ValueError, "Circular reference detected");
                goto bail;
            }
            if (PyDict_SetItem(s->markers, ident, seq)) {
                goto bail;
            }
        }
    
        iter = PyObject_GetIter(seq);
        if (iter == NULL)
            goto bail;
    
        if (PyList_Append(rval, open_array))
            goto bail;
        if (s->indent != Py_None) {
            /* TODO: DOES NOT RUN */
            indent_level += 1;
            /*
                newline_indent = '\n' + (_indent * _current_indent_level)
                separator = _item_separator + newline_indent
                buf += newline_indent
            */
        }
        while ((obj = PyIter_Next(iter))) {
            if (i) {
                if (PyList_Append(rval, s->item_separator))
                    goto bail;
            }
            if (encoder_listencode_obj(s, rval, obj, indent_level))
                goto bail;
            i++;
            Py_CLEAR(obj);
        }
        Py_CLEAR(iter);
        if (PyErr_Occurred())
            goto bail;
        if (ident != NULL) {
            if (PyDict_DelItem(s->markers, ident))
                goto bail;
            Py_CLEAR(ident);
        }
        if (s->indent != Py_None) {
            /* TODO: DOES NOT RUN */
            indent_level -= 1;
            /*
                yield '\n' + (_indent * _current_indent_level)
            */
        }
        if (PyList_Append(rval, close_array))
            goto bail;
        return 0;
    
    bail:
        Py_XDECREF(obj);
        Py_XDECREF(iter);
        Py_XDECREF(ident);
        return -1;
    }
    
    static void
    encoder_dealloc(PyObject *self)
    {
        /* Deallocate Encoder */
        encoder_clear(self);
        Py_TYPE(self)->tp_free(self);
    }
    
    static int
    encoder_traverse(PyObject *self, visitproc visit, void *arg)
    {
        PyEncoderObject *s;
        assert(PyEncoder_Check(self));
        s = (PyEncoderObject *)self;
        Py_VISIT(s->markers);
        Py_VISIT(s->defaultfn);
        Py_VISIT(s->encoder);
        Py_VISIT(s->indent);
        Py_VISIT(s->key_separator);
        Py_VISIT(s->item_separator);
        Py_VISIT(s->sort_keys);
        Py_VISIT(s->skipkeys);
        Py_VISIT(s->key_memo);
        Py_VISIT(s->item_sort_key);
        return 0;
    }
    
    static int
    encoder_clear(PyObject *self)
    {
        /* Deallocate Encoder */
        PyEncoderObject *s;
        assert(PyEncoder_Check(self));
        s = (PyEncoderObject *)self;
        Py_CLEAR(s->markers);
        Py_CLEAR(s->defaultfn);
        Py_CLEAR(s->encoder);
        Py_CLEAR(s->indent);
        Py_CLEAR(s->key_separator);
        Py_CLEAR(s->item_separator);
        Py_CLEAR(s->sort_keys);
        Py_CLEAR(s->skipkeys);
        Py_CLEAR(s->key_memo);
        Py_CLEAR(s->item_sort_key);
        Py_CLEAR(s->Decimal);
        return 0;
    }
    
    PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
    
    static
    PyTypeObject PyEncoderType = {
        PyObject_HEAD_INIT(NULL)
        0,                    /* tp_internal */
        "simplejson._speedups.Encoder",       /* tp_name */
        sizeof(PyEncoderObject), /* tp_basicsize */
        0,                    /* tp_itemsize */
        encoder_dealloc, /* tp_dealloc */
        0,                    /* tp_print */
        0,                    /* tp_getattr */
        0,                    /* tp_setattr */
        0,                    /* tp_compare */
        0,                    /* tp_repr */
        0,                    /* tp_as_number */
        0,                    /* tp_as_sequence */
        0,                    /* tp_as_mapping */
        0,                    /* tp_hash */
        encoder_call,         /* tp_call */
        0,                    /* tp_str */
        0,                    /* tp_getattro */
        0,                    /* tp_setattro */
        0,                    /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,   /* tp_flags */
        encoder_doc,          /* tp_doc */
        encoder_traverse,     /* tp_traverse */
        encoder_clear,        /* tp_clear */
        0,                    /* tp_richcompare */
        0,                    /* tp_weaklistoffset */
        0,                    /* tp_iter */
        0,                    /* tp_iternext */
        0,                    /* tp_methods */
        encoder_members,      /* tp_members */
        0,                    /* tp_getset */
        0,                    /* tp_base */
        0,                    /* tp_dict */
        0,                    /* tp_descr_get */
        0,                    /* tp_descr_set */
        0,                    /* tp_dictoffset */
        encoder_init,         /* tp_init */
        0,                    /* tp_alloc */
        encoder_new,          /* tp_new */
        0,                    /* tp_free */
    };
    
    static PyMethodDef speedups_methods[] = {
        {"encode_basestring_ascii",
            (PyCFunction)py_encode_basestring_ascii,
            METH_O,
            pydoc_encode_basestring_ascii},
        {"scanstring",
            (PyCFunction)py_scanstring,
            METH_VARARGS,
            pydoc_scanstring},
        {NULL, NULL, 0, NULL}
    };
    
    PyDoc_STRVAR(module_doc,
    "simplejson speedups\n");
    
    void
    init_speedups(void)
    {
        PyObject *m;
        PyScannerType.tp_new = PyType_GenericNew;
        if (PyType_Ready(&PyScannerType) < 0)
            return;
        PyEncoderType.tp_new = PyType_GenericNew;
        if (PyType_Ready(&PyEncoderType) < 0)
            return;
    
    
        m = Py_InitModule3("_speedups", speedups_methods, module_doc);
        Py_INCREF((PyObject*)&PyScannerType);
        PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
        Py_INCREF((PyObject*)&PyEncoderType);
        PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
    }
    pygments.rb-0.6.3/vendor/simplejson/simplejson/decoder.py000066400000000000000000000356501250413007300236160ustar00rootroot00000000000000"""Implementation of JSONDecoder
    """
    import re
    import sys
    import struct
    
    from simplejson.scanner import make_scanner
    def _import_c_scanstring():
        try:
            from simplejson._speedups import scanstring
            return scanstring
        except ImportError:
            return None
    c_scanstring = _import_c_scanstring()
    
    __all__ = ['JSONDecoder']
    
    FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
    
    def _floatconstants():
        _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
        # The struct module in Python 2.4 would get frexp() out of range here
        # when an endian is specified in the format string. Fixed in Python 2.5+
        if sys.byteorder != 'big':
            _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
        nan, inf = struct.unpack('dd', _BYTES)
        return nan, inf, -inf
    
    NaN, PosInf, NegInf = _floatconstants()
    
    
    class JSONDecodeError(ValueError):
        """Subclass of ValueError with the following additional properties:
    
        msg: The unformatted error message
        doc: The JSON document being parsed
        pos: The start index of doc where parsing failed
        end: The end index of doc where parsing failed (may be None)
        lineno: The line corresponding to pos
        colno: The column corresponding to pos
        endlineno: The line corresponding to end (may be None)
        endcolno: The column corresponding to end (may be None)
    
        """
        def __init__(self, msg, doc, pos, end=None):
            ValueError.__init__(self, errmsg(msg, doc, pos, end=end))
            self.msg = msg
            self.doc = doc
            self.pos = pos
            self.end = end
            self.lineno, self.colno = linecol(doc, pos)
            if end is not None:
                self.endlineno, self.endcolno = linecol(doc, end)
            else:
                self.endlineno, self.endcolno = None, None
    
    
    def linecol(doc, pos):
        lineno = doc.count('\n', 0, pos) + 1
        if lineno == 1:
            colno = pos
        else:
            colno = pos - doc.rindex('\n', 0, pos)
        return lineno, colno
    
    
    def errmsg(msg, doc, pos, end=None):
        # Note that this function is called from _speedups
        lineno, colno = linecol(doc, pos)
        if end is None:
            #fmt = '{0}: line {1} column {2} (char {3})'
            #return fmt.format(msg, lineno, colno, pos)
            fmt = '%s: line %d column %d (char %d)'
            return fmt % (msg, lineno, colno, pos)
        endlineno, endcolno = linecol(doc, end)
        #fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
        #return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
        fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
        return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
    
    
    _CONSTANTS = {
        '-Infinity': NegInf,
        'Infinity': PosInf,
        'NaN': NaN,
    }
    
    STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
    BACKSLASH = {
        '"': u'"', '\\': u'\\', '/': u'/',
        'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
    }
    
    DEFAULT_ENCODING = "utf-8"
    
    def py_scanstring(s, end, encoding=None, strict=True,
            _b=BACKSLASH, _m=STRINGCHUNK.match):
        """Scan the string s for a JSON string. End is the index of the
        character in s after the quote that started the JSON string.
        Unescapes all valid JSON string escape sequences and raises ValueError
        on attempt to decode an invalid string. If strict is False then literal
        control characters are allowed in the string.
    
        Returns a tuple of the decoded string and the index of the character in s
        after the end quote."""
        if encoding is None:
            encoding = DEFAULT_ENCODING
        chunks = []
        _append = chunks.append
        begin = end - 1
        while 1:
            chunk = _m(s, end)
            if chunk is None:
                raise JSONDecodeError(
                    "Unterminated string starting at", s, begin)
            end = chunk.end()
            content, terminator = chunk.groups()
            # Content is contains zero or more unescaped string characters
            if content:
                if not isinstance(content, unicode):
                    content = unicode(content, encoding)
                _append(content)
            # Terminator is the end of string, a literal control character,
            # or a backslash denoting that an escape sequence follows
            if terminator == '"':
                break
            elif terminator != '\\':
                if strict:
                    msg = "Invalid control character %r at" % (terminator,)
                    #msg = "Invalid control character {0!r} at".format(terminator)
                    raise JSONDecodeError(msg, s, end)
                else:
                    _append(terminator)
                    continue
            try:
                esc = s[end]
            except IndexError:
                raise JSONDecodeError(
                    "Unterminated string starting at", s, begin)
            # If not a unicode escape sequence, must be in the lookup table
            if esc != 'u':
                try:
                    char = _b[esc]
                except KeyError:
                    msg = "Invalid \\escape: " + repr(esc)
                    raise JSONDecodeError(msg, s, end)
                end += 1
            else:
                # Unicode escape sequence
                esc = s[end + 1:end + 5]
                next_end = end + 5
                if len(esc) != 4:
                    msg = "Invalid \\uXXXX escape"
                    raise JSONDecodeError(msg, s, end)
                uni = int(esc, 16)
                # Check for surrogate pair on UCS-4 systems
                if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
                    msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
                    if not s[end + 5:end + 7] == '\\u':
                        raise JSONDecodeError(msg, s, end)
                    esc2 = s[end + 7:end + 11]
                    if len(esc2) != 4:
                        raise JSONDecodeError(msg, s, end)
                    uni2 = int(esc2, 16)
                    uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
                    next_end += 6
                char = unichr(uni)
                end = next_end
            # Append the unescaped character
            _append(char)
        return u''.join(chunks), end
    
    
    # Use speedup if available
    scanstring = c_scanstring or py_scanstring
    
    WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
    WHITESPACE_STR = ' \t\n\r'
    
    def JSONObject((s, end), encoding, strict, scan_once, object_hook,
            object_pairs_hook, memo=None,
            _w=WHITESPACE.match, _ws=WHITESPACE_STR):
        # Backwards compatibility
        if memo is None:
            memo = {}
        memo_get = memo.setdefault
        pairs = []
        # Use a slice to prevent IndexError from being raised, the following
        # check will raise a more specific ValueError if the string is empty
        nextchar = s[end:end + 1]
        # Normally we expect nextchar == '"'
        if nextchar != '"':
            if nextchar in _ws:
                end = _w(s, end).end()
                nextchar = s[end:end + 1]
            # Trivial empty object
            if nextchar == '}':
                if object_pairs_hook is not None:
                    result = object_pairs_hook(pairs)
                    return result, end + 1
                pairs = {}
                if object_hook is not None:
                    pairs = object_hook(pairs)
                return pairs, end + 1
            elif nextchar != '"':
                raise JSONDecodeError(
                    "Expecting property name enclosed in double quotes",
                    s, end)
        end += 1
        while True:
            key, end = scanstring(s, end, encoding, strict)
            key = memo_get(key, key)
    
            # To skip some function call overhead we optimize the fast paths where
            # the JSON key separator is ": " or just ":".
            if s[end:end + 1] != ':':
                end = _w(s, end).end()
                if s[end:end + 1] != ':':
                    raise JSONDecodeError("Expecting ':' delimiter", s, end)
    
            end += 1
    
            try:
                if s[end] in _ws:
                    end += 1
                    if s[end] in _ws:
                        end = _w(s, end + 1).end()
            except IndexError:
                pass
    
            try:
                value, end = scan_once(s, end)
            except StopIteration:
                raise JSONDecodeError("Expecting object", s, end)
            pairs.append((key, value))
    
            try:
                nextchar = s[end]
                if nextchar in _ws:
                    end = _w(s, end + 1).end()
                    nextchar = s[end]
            except IndexError:
                nextchar = ''
            end += 1
    
            if nextchar == '}':
                break
            elif nextchar != ',':
                raise JSONDecodeError("Expecting ',' delimiter", s, end - 1)
    
            try:
                nextchar = s[end]
                if nextchar in _ws:
                    end += 1
                    nextchar = s[end]
                    if nextchar in _ws:
                        end = _w(s, end + 1).end()
                        nextchar = s[end]
            except IndexError:
                nextchar = ''
    
            end += 1
            if nextchar != '"':
                raise JSONDecodeError(
                    "Expecting property name enclosed in double quotes",
                    s, end - 1)
    
        if object_pairs_hook is not None:
            result = object_pairs_hook(pairs)
            return result, end
        pairs = dict(pairs)
        if object_hook is not None:
            pairs = object_hook(pairs)
        return pairs, end
    
    def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
        values = []
        nextchar = s[end:end + 1]
        if nextchar in _ws:
            end = _w(s, end + 1).end()
            nextchar = s[end:end + 1]
        # Look-ahead for trivial empty array
        if nextchar == ']':
            return values, end + 1
        _append = values.append
        while True:
            try:
                value, end = scan_once(s, end)
            except StopIteration:
                raise JSONDecodeError("Expecting object", s, end)
            _append(value)
            nextchar = s[end:end + 1]
            if nextchar in _ws:
                end = _w(s, end + 1).end()
                nextchar = s[end:end + 1]
            end += 1
            if nextchar == ']':
                break
            elif nextchar != ',':
                raise JSONDecodeError("Expecting ',' delimiter", s, end)
    
            try:
                if s[end] in _ws:
                    end += 1
                    if s[end] in _ws:
                        end = _w(s, end + 1).end()
            except IndexError:
                pass
    
        return values, end
    
    class JSONDecoder(object):
        """Simple JSON  decoder
    
        Performs the following translations in decoding by default:
    
        +---------------+-------------------+
        | JSON          | Python            |
        +===============+===================+
        | object        | dict              |
        +---------------+-------------------+
        | array         | list              |
        +---------------+-------------------+
        | string        | unicode           |
        +---------------+-------------------+
        | number (int)  | int, long         |
        +---------------+-------------------+
        | number (real) | float             |
        +---------------+-------------------+
        | true          | True              |
        +---------------+-------------------+
        | false         | False             |
        +---------------+-------------------+
        | null          | None              |
        +---------------+-------------------+
    
        It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
        their corresponding ``float`` values, which is outside the JSON spec.
    
        """
    
        def __init__(self, encoding=None, object_hook=None, parse_float=None,
                parse_int=None, parse_constant=None, strict=True,
                object_pairs_hook=None):
            """
            *encoding* determines the encoding used to interpret any
            :class:`str` objects decoded by this instance (``'utf-8'`` by
            default).  It has no effect when decoding :class:`unicode` objects.
    
            Note that currently only encodings that are a superset of ASCII work,
            strings of other encodings should be passed in as :class:`unicode`.
    
            *object_hook*, if specified, will be called with the result of every
            JSON object decoded and its return value will be used in place of the
            given :class:`dict`.  This can be used to provide custom
            deserializations (e.g. to support JSON-RPC class hinting).
    
            *object_pairs_hook* is an optional function that will be called with
            the result of any object literal decode with an ordered list of pairs.
            The return value of *object_pairs_hook* will be used instead of the
            :class:`dict`.  This feature can be used to implement custom decoders
            that rely on the order that the key and value pairs are decoded (for
            example, :func:`collections.OrderedDict` will remember the order of
            insertion). If *object_hook* is also defined, the *object_pairs_hook*
            takes priority.
    
            *parse_float*, if specified, will be called with the string of every
            JSON float to be decoded.  By default, this is equivalent to
            ``float(num_str)``. This can be used to use another datatype or parser
            for JSON floats (e.g. :class:`decimal.Decimal`).
    
            *parse_int*, if specified, will be called with the string of every
            JSON int to be decoded.  By default, this is equivalent to
            ``int(num_str)``.  This can be used to use another datatype or parser
            for JSON integers (e.g. :class:`float`).
    
            *parse_constant*, if specified, will be called with one of the
            following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This
            can be used to raise an exception if invalid JSON numbers are
            encountered.
    
            *strict* controls the parser's behavior when it encounters an
            invalid control character in a string. The default setting of
            ``True`` means that unescaped control characters are parse errors, if
            ``False`` then control characters will be allowed in strings.
    
            """
            self.encoding = encoding
            self.object_hook = object_hook
            self.object_pairs_hook = object_pairs_hook
            self.parse_float = parse_float or float
            self.parse_int = parse_int or int
            self.parse_constant = parse_constant or _CONSTANTS.__getitem__
            self.strict = strict
            self.parse_object = JSONObject
            self.parse_array = JSONArray
            self.parse_string = scanstring
            self.memo = {}
            self.scan_once = make_scanner(self)
    
        def decode(self, s, _w=WHITESPACE.match):
            """Return the Python representation of ``s`` (a ``str`` or ``unicode``
            instance containing a JSON document)
    
            """
            obj, end = self.raw_decode(s, idx=_w(s, 0).end())
            end = _w(s, end).end()
            if end != len(s):
                raise JSONDecodeError("Extra data", s, end, len(s))
            return obj
    
        def raw_decode(self, s, idx=0):
            """Decode a JSON document from ``s`` (a ``str`` or ``unicode``
            beginning with a JSON document) and return a 2-tuple of the Python
            representation and the index in ``s`` where the document ended.
    
            This can be used to decode a JSON document from a string that may
            have extraneous data at the end.
    
            """
            try:
                obj, end = self.scan_once(s, idx)
            except StopIteration:
                raise JSONDecodeError("No JSON object could be decoded", s, idx)
            return obj, end
    pygments.rb-0.6.3/vendor/simplejson/simplejson/encoder.py000066400000000000000000000524461250413007300236320ustar00rootroot00000000000000"""Implementation of JSONEncoder
    """
    import re
    from decimal import Decimal
    
    def _import_speedups():
        try:
            from simplejson import _speedups
            return _speedups.encode_basestring_ascii, _speedups.make_encoder
        except ImportError:
            return None, None
    c_encode_basestring_ascii, c_make_encoder = _import_speedups()
    
    from simplejson.decoder import PosInf
    
    ESCAPE = re.compile(ur'[\x00-\x1f\\"\b\f\n\r\t\u2028\u2029]')
    ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
    HAS_UTF8 = re.compile(r'[\x80-\xff]')
    ESCAPE_DCT = {
        '\\': '\\\\',
        '"': '\\"',
        '\b': '\\b',
        '\f': '\\f',
        '\n': '\\n',
        '\r': '\\r',
        '\t': '\\t',
        u'\u2028': '\\u2028',
        u'\u2029': '\\u2029',
    }
    for i in range(0x20):
        #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
        ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
    
    FLOAT_REPR = repr
    
    def encode_basestring(s):
        """Return a JSON representation of a Python string
    
        """
        if isinstance(s, str) and HAS_UTF8.search(s) is not None:
            s = s.decode('utf-8')
        def replace(match):
            return ESCAPE_DCT[match.group(0)]
        return u'"' + ESCAPE.sub(replace, s) + u'"'
    
    
    def py_encode_basestring_ascii(s):
        """Return an ASCII-only JSON representation of a Python string
    
        """
        if isinstance(s, str) and HAS_UTF8.search(s) is not None:
            s = s.decode('utf-8')
        def replace(match):
            s = match.group(0)
            try:
                return ESCAPE_DCT[s]
            except KeyError:
                n = ord(s)
                if n < 0x10000:
                    #return '\\u{0:04x}'.format(n)
                    return '\\u%04x' % (n,)
                else:
                    # surrogate pair
                    n -= 0x10000
                    s1 = 0xd800 | ((n >> 10) & 0x3ff)
                    s2 = 0xdc00 | (n & 0x3ff)
                    #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
                    return '\\u%04x\\u%04x' % (s1, s2)
        return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
    
    
    encode_basestring_ascii = (
        c_encode_basestring_ascii or py_encode_basestring_ascii)
    
    class JSONEncoder(object):
        """Extensible JSON  encoder for Python data structures.
    
        Supports the following objects and types by default:
    
        +-------------------+---------------+
        | Python            | JSON          |
        +===================+===============+
        | dict, namedtuple  | object        |
        +-------------------+---------------+
        | list, tuple       | array         |
        +-------------------+---------------+
        | str, unicode      | string        |
        +-------------------+---------------+
        | int, long, float  | number        |
        +-------------------+---------------+
        | True              | true          |
        +-------------------+---------------+
        | False             | false         |
        +-------------------+---------------+
        | None              | null          |
        +-------------------+---------------+
    
        To extend this to recognize other objects, subclass and implement a
        ``.default()`` method with another method that returns a serializable
        object for ``o`` if possible, otherwise it should call the superclass
        implementation (to raise ``TypeError``).
    
        """
        item_separator = ', '
        key_separator = ': '
        def __init__(self, skipkeys=False, ensure_ascii=True,
                check_circular=True, allow_nan=True, sort_keys=False,
                indent=None, separators=None, encoding='utf-8', default=None,
                use_decimal=True, namedtuple_as_object=True,
                tuple_as_array=True, bigint_as_string=False,
                item_sort_key=None):
            """Constructor for JSONEncoder, with sensible defaults.
    
            If skipkeys is false, then it is a TypeError to attempt
            encoding of keys that are not str, int, long, float or None.  If
            skipkeys is True, such items are simply skipped.
    
            If ensure_ascii is true, the output is guaranteed to be str
            objects with all incoming unicode characters escaped.  If
            ensure_ascii is false, the output will be unicode object.
    
            If check_circular is true, then lists, dicts, and custom encoded
            objects will be checked for circular references during encoding to
            prevent an infinite recursion (which would cause an OverflowError).
            Otherwise, no such check takes place.
    
            If allow_nan is true, then NaN, Infinity, and -Infinity will be
            encoded as such.  This behavior is not JSON specification compliant,
            but is consistent with most JavaScript based encoders and decoders.
            Otherwise, it will be a ValueError to encode such floats.
    
            If sort_keys is true, then the output of dictionaries will be
            sorted by key; this is useful for regression tests to ensure
            that JSON serializations can be compared on a day-to-day basis.
    
            If indent is a string, then JSON array elements and object members
            will be pretty-printed with a newline followed by that string repeated
            for each level of nesting. ``None`` (the default) selects the most compact
            representation without any newlines. For backwards compatibility with
            versions of simplejson earlier than 2.1.0, an integer is also accepted
            and is converted to a string with that many spaces.
    
            If specified, separators should be a (item_separator, key_separator)
            tuple.  The default is (', ', ': ').  To get the most compact JSON
            representation you should specify (',', ':') to eliminate whitespace.
    
            If specified, default is a function that gets called for objects
            that can't otherwise be serialized.  It should return a JSON encodable
            version of the object or raise a ``TypeError``.
    
            If encoding is not None, then all input strings will be
            transformed into unicode using that encoding prior to JSON-encoding.
            The default is UTF-8.
    
            If use_decimal is true (not the default), ``decimal.Decimal`` will
            be supported directly by the encoder. For the inverse, decode JSON
            with ``parse_float=decimal.Decimal``.
    
            If namedtuple_as_object is true (the default), objects with
            ``_asdict()`` methods will be encoded as JSON objects.
    
            If tuple_as_array is true (the default), tuple (and subclasses) will
            be encoded as JSON arrays.
    
            If bigint_as_string is true (not the default), ints 2**53 and higher
            or lower than -2**53 will be encoded as strings. This is to avoid the
            rounding that happens in Javascript otherwise.
    
            If specified, item_sort_key is a callable used to sort the items in
            each dictionary. This is useful if you want to sort items other than
            in alphabetical order by key.
            """
    
            self.skipkeys = skipkeys
            self.ensure_ascii = ensure_ascii
            self.check_circular = check_circular
            self.allow_nan = allow_nan
            self.sort_keys = sort_keys
            self.use_decimal = use_decimal
            self.namedtuple_as_object = namedtuple_as_object
            self.tuple_as_array = tuple_as_array
            self.bigint_as_string = bigint_as_string
            self.item_sort_key = item_sort_key
            if indent is not None and not isinstance(indent, basestring):
                indent = indent * ' '
            self.indent = indent
            if separators is not None:
                self.item_separator, self.key_separator = separators
            elif indent is not None:
                self.item_separator = ','
            if default is not None:
                self.default = default
            self.encoding = encoding
    
        def default(self, o):
            """Implement this method in a subclass such that it returns
            a serializable object for ``o``, or calls the base implementation
            (to raise a ``TypeError``).
    
            For example, to support arbitrary iterators, you could
            implement default like this::
    
                def default(self, o):
                    try:
                        iterable = iter(o)
                    except TypeError:
                        pass
                    else:
                        return list(iterable)
                    return JSONEncoder.default(self, o)
    
            """
            raise TypeError(repr(o) + " is not JSON serializable")
    
        def encode(self, o):
            """Return a JSON string representation of a Python data structure.
    
            >>> from simplejson import JSONEncoder
            >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
            '{"foo": ["bar", "baz"]}'
    
            """
            # This is for extremely simple cases and benchmarks.
            if isinstance(o, basestring):
                if isinstance(o, str):
                    _encoding = self.encoding
                    if (_encoding is not None
                            and not (_encoding == 'utf-8')):
                        o = o.decode(_encoding)
                if self.ensure_ascii:
                    return encode_basestring_ascii(o)
                else:
                    return encode_basestring(o)
            # This doesn't pass the iterator directly to ''.join() because the
            # exceptions aren't as detailed.  The list call should be roughly
            # equivalent to the PySequence_Fast that ''.join() would do.
            chunks = self.iterencode(o, _one_shot=True)
            if not isinstance(chunks, (list, tuple)):
                chunks = list(chunks)
            if self.ensure_ascii:
                return ''.join(chunks)
            else:
                return u''.join(chunks)
    
        def iterencode(self, o, _one_shot=False):
            """Encode the given object and yield each string
            representation as available.
    
            For example::
    
                for chunk in JSONEncoder().iterencode(bigobject):
                    mysocket.write(chunk)
    
            """
            if self.check_circular:
                markers = {}
            else:
                markers = None
            if self.ensure_ascii:
                _encoder = encode_basestring_ascii
            else:
                _encoder = encode_basestring
            if self.encoding != 'utf-8':
                def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
                    if isinstance(o, str):
                        o = o.decode(_encoding)
                    return _orig_encoder(o)
    
            def floatstr(o, allow_nan=self.allow_nan,
                    _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf):
                # Check for specials. Note that this type of test is processor
                # and/or platform-specific, so do tests which don't depend on
                # the internals.
    
                if o != o:
                    text = 'NaN'
                elif o == _inf:
                    text = 'Infinity'
                elif o == _neginf:
                    text = '-Infinity'
                else:
                    return _repr(o)
    
                if not allow_nan:
                    raise ValueError(
                        "Out of range float values are not JSON compliant: " +
                        repr(o))
    
                return text
    
    
            key_memo = {}
            if (_one_shot and c_make_encoder is not None
                    and self.indent is None):
                _iterencode = c_make_encoder(
                    markers, self.default, _encoder, self.indent,
                    self.key_separator, self.item_separator, self.sort_keys,
                    self.skipkeys, self.allow_nan, key_memo, self.use_decimal,
                    self.namedtuple_as_object, self.tuple_as_array,
                    self.bigint_as_string, self.item_sort_key,
                    Decimal)
            else:
                _iterencode = _make_iterencode(
                    markers, self.default, _encoder, self.indent, floatstr,
                    self.key_separator, self.item_separator, self.sort_keys,
                    self.skipkeys, _one_shot, self.use_decimal,
                    self.namedtuple_as_object, self.tuple_as_array,
                    self.bigint_as_string, self.item_sort_key,
                    Decimal=Decimal)
            try:
                return _iterencode(o, 0)
            finally:
                key_memo.clear()
    
    
    class JSONEncoderForHTML(JSONEncoder):
        """An encoder that produces JSON safe to embed in HTML.
    
        To embed JSON content in, say, a script tag on a web page, the
        characters &, < and > should be escaped. They cannot be escaped
        with the usual entities (e.g. &) because they are not expanded
        within '
            self.assertEqual(
                r'"\u003c/script\u003e\u003cscript\u003e'
                r'alert(\"gotcha\")\u003c/script\u003e"',
                self.encoder.encode(bad_string))
            self.assertEqual(
                bad_string, self.decoder.decode(
                    self.encoder.encode(bad_string)))
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_errors.py000066400000000000000000000020001250413007300257050ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    
    class TestErrors(TestCase):
        def test_string_keys_error(self):
            data = [{'a': 'A', 'b': (2, 4), 'c': 3.0, ('d',): 'D tuple'}]
            self.assertRaises(TypeError, json.dumps, data)
    
        def test_decode_error(self):
            err = None
            try:
                json.loads('{}\na\nb')
            except json.JSONDecodeError, e:
                err = e
            else:
                self.fail('Expected JSONDecodeError')
            self.assertEquals(err.lineno, 2)
            self.assertEquals(err.colno, 1)
            self.assertEquals(err.endlineno, 3)
            self.assertEquals(err.endcolno, 2)
    
        def test_scan_error(self):
            err = None
            for t in (str, unicode):
                try:
                    json.loads(t('{"asdf": "'))
                except json.JSONDecodeError, e:
                    err = e
                else:
                    self.fail('Expected JSONDecodeError')
                self.assertEquals(err.lineno, 1)
                self.assertEquals(err.colno, 9)
            pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_fail.py000066400000000000000000000067431250413007300253260ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    
    # Fri Dec 30 18:57:26 2005
    JSONDOCS = [
        # http://json.org/JSON_checker/test/fail1.json
        '"A JSON payload should be an object or array, not a string."',
        # http://json.org/JSON_checker/test/fail2.json
        '["Unclosed array"',
        # http://json.org/JSON_checker/test/fail3.json
        '{unquoted_key: "keys must be quoted}',
        # http://json.org/JSON_checker/test/fail4.json
        '["extra comma",]',
        # http://json.org/JSON_checker/test/fail5.json
        '["double extra comma",,]',
        # http://json.org/JSON_checker/test/fail6.json
        '[   , "<-- missing value"]',
        # http://json.org/JSON_checker/test/fail7.json
        '["Comma after the close"],',
        # http://json.org/JSON_checker/test/fail8.json
        '["Extra close"]]',
        # http://json.org/JSON_checker/test/fail9.json
        '{"Extra comma": true,}',
        # http://json.org/JSON_checker/test/fail10.json
        '{"Extra value after close": true} "misplaced quoted value"',
        # http://json.org/JSON_checker/test/fail11.json
        '{"Illegal expression": 1 + 2}',
        # http://json.org/JSON_checker/test/fail12.json
        '{"Illegal invocation": alert()}',
        # http://json.org/JSON_checker/test/fail13.json
        '{"Numbers cannot have leading zeroes": 013}',
        # http://json.org/JSON_checker/test/fail14.json
        '{"Numbers cannot be hex": 0x14}',
        # http://json.org/JSON_checker/test/fail15.json
        '["Illegal backslash escape: \\x15"]',
        # http://json.org/JSON_checker/test/fail16.json
        '["Illegal backslash escape: \\\'"]',
        # http://json.org/JSON_checker/test/fail17.json
        '["Illegal backslash escape: \\017"]',
        # http://json.org/JSON_checker/test/fail18.json
        '[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]',
        # http://json.org/JSON_checker/test/fail19.json
        '{"Missing colon" null}',
        # http://json.org/JSON_checker/test/fail20.json
        '{"Double colon":: null}',
        # http://json.org/JSON_checker/test/fail21.json
        '{"Comma instead of colon", null}',
        # http://json.org/JSON_checker/test/fail22.json
        '["Colon instead of comma": false]',
        # http://json.org/JSON_checker/test/fail23.json
        '["Bad value", truth]',
        # http://json.org/JSON_checker/test/fail24.json
        "['single quote']",
        # http://code.google.com/p/simplejson/issues/detail?id=3
        u'["A\u001FZ control characters in string"]',
    ]
    
    SKIPS = {
        1: "why not have a string payload?",
        18: "spec doesn't specify any nesting limitations",
    }
    
    class TestFail(TestCase):
        def test_failures(self):
            for idx, doc in enumerate(JSONDOCS):
                idx = idx + 1
                if idx in SKIPS:
                    json.loads(doc)
                    continue
                try:
                    json.loads(doc)
                except json.JSONDecodeError:
                    pass
                else:
                    #self.fail("Expected failure for fail{0}.json: {1!r}".format(idx, doc))
                    self.fail("Expected failure for fail%d.json: %r" % (idx, doc))
    
        def test_array_decoder_issue46(self):
            # http://code.google.com/p/simplejson/issues/detail?id=46
            for doc in [u'[,]', '[,]']:
                try:
                    json.loads(doc)
                except json.JSONDecodeError, e:
                    self.assertEquals(e.pos, 1)
                    self.assertEquals(e.lineno, 1)
                    self.assertEquals(e.colno, 1)
                except Exception, e:
                    self.fail("Unexpected exception raised %r %s" % (e, e))
                else:
                    self.fail("Unexpected success parsing '[,]'")pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_float.py000066400000000000000000000013471250413007300255130ustar00rootroot00000000000000import math
    from unittest import TestCase
    
    import simplejson as json
    
    class TestFloat(TestCase):
        def test_floats(self):
            for num in [1617161771.7650001, math.pi, math.pi**100,
                        math.pi**-100, 3.1]:
                self.assertEquals(float(json.dumps(num)), num)
                self.assertEquals(json.loads(json.dumps(num)), num)
                self.assertEquals(json.loads(unicode(json.dumps(num))), num)
    
        def test_ints(self):
            for num in [1, 1L, 1<<32, 1<<64]:
                self.assertEquals(json.dumps(num), str(num))
                self.assertEquals(int(json.dumps(num)), num)
                self.assertEquals(json.loads(json.dumps(num)), num)
                self.assertEquals(json.loads(unicode(json.dumps(num))), num)
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_indent.py000066400000000000000000000050121250413007300256600ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    import textwrap
    from StringIO import StringIO
    
    class TestIndent(TestCase):
        def test_indent(self):
            h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh',
                 'i-vhbjkhnth',
                 {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
    
            expect = textwrap.dedent("""\
            [
            \t[
            \t\t"blorpie"
            \t],
            \t[
            \t\t"whoops"
            \t],
            \t[],
            \t"d-shtaeou",
            \t"d-nthiouh",
            \t"i-vhbjkhnth",
            \t{
            \t\t"nifty": 87
            \t},
            \t{
            \t\t"field": "yes",
            \t\t"morefield": false
            \t}
            ]""")
    
    
            d1 = json.dumps(h)
            d2 = json.dumps(h, indent='\t', sort_keys=True, separators=(',', ': '))
            d3 = json.dumps(h, indent='  ', sort_keys=True, separators=(',', ': '))
            d4 = json.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
    
            h1 = json.loads(d1)
            h2 = json.loads(d2)
            h3 = json.loads(d3)
            h4 = json.loads(d4)
    
            self.assertEquals(h1, h)
            self.assertEquals(h2, h)
            self.assertEquals(h3, h)
            self.assertEquals(h4, h)
            self.assertEquals(d3, expect.replace('\t', '  '))
            self.assertEquals(d4, expect.replace('\t', '  '))
            # NOTE: Python 2.4 textwrap.dedent converts tabs to spaces,
            #       so the following is expected to fail. Python 2.4 is not a
            #       supported platform in simplejson 2.1.0+.
            self.assertEquals(d2, expect)
    
        def test_indent0(self):
            h = {3: 1}
            def check(indent, expected):
                d1 = json.dumps(h, indent=indent)
                self.assertEquals(d1, expected)
    
                sio = StringIO()
                json.dump(h, sio, indent=indent)
                self.assertEquals(sio.getvalue(), expected)
    
            # indent=0 should emit newlines
            check(0, '{\n"3": 1\n}')
            # indent=None is more compact
            check(None, '{"3": 1}')
    
        def test_separators(self):
            lst = [1,2,3,4]
            expect = '[\n1,\n2,\n3,\n4\n]'
            expect_spaces = '[\n1, \n2, \n3, \n4\n]'
            # Ensure that separators still works
            self.assertEquals(
                expect_spaces,
                json.dumps(lst, indent=0, separators=(', ', ': ')))
            # Force the new defaults
            self.assertEquals(
                expect,
                json.dumps(lst, indent=0, separators=(',', ': ')))
            # Added in 2.1.4
            self.assertEquals(
                expect,
                json.dumps(lst, indent=0))pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_item_sort_key.py000066400000000000000000000021521250413007300272560ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    from operator import itemgetter
    
    class TestItemSortKey(TestCase):
        def test_simple_first(self):
            a = {'a': 1, 'c': 5, 'jack': 'jill', 'pick': 'axe', 'array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'}
            self.assertEquals(
                '{"a": 1, "c": 5, "crate": "dog", "jack": "jill", "pick": "axe", "zeak": "oh", "array": [1, 5, 6, 9], "tuple": [83, 12, 3]}',
                json.dumps(a, item_sort_key=json.simple_first))
    
        def test_case(self):
            a = {'a': 1, 'c': 5, 'Jack': 'jill', 'pick': 'axe', 'Array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'}
            self.assertEquals(
                '{"Array": [1, 5, 6, 9], "Jack": "jill", "a": 1, "c": 5, "crate": "dog", "pick": "axe", "tuple": [83, 12, 3], "zeak": "oh"}',
                json.dumps(a, item_sort_key=itemgetter(0)))
            self.assertEquals(
                '{"a": 1, "Array": [1, 5, 6, 9], "c": 5, "crate": "dog", "Jack": "jill", "pick": "axe", "tuple": [83, 12, 3], "zeak": "oh"}',
                json.dumps(a, item_sort_key=lambda kv: kv[0].lower()))
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_namedtuple.py000066400000000000000000000075641250413007300265530ustar00rootroot00000000000000import unittest
    import simplejson as json
    from StringIO import StringIO
    
    try:
        from collections import namedtuple
    except ImportError:
        class Value(tuple):
            def __new__(cls, *args):
                return tuple.__new__(cls, args)
    
            def _asdict(self):
                return {'value': self[0]}
        class Point(tuple):
            def __new__(cls, *args):
                return tuple.__new__(cls, args)
    
            def _asdict(self):
                return {'x': self[0], 'y': self[1]}
    else:
        Value = namedtuple('Value', ['value'])
        Point = namedtuple('Point', ['x', 'y'])
    
    class DuckValue(object):
        def __init__(self, *args):
            self.value = Value(*args)
    
        def _asdict(self):
            return self.value._asdict()
    
    class DuckPoint(object):
        def __init__(self, *args):
            self.point = Point(*args)
    
        def _asdict(self):
            return self.point._asdict()
    
    class DeadDuck(object):
        _asdict = None
    
    class DeadDict(dict):
        _asdict = None
    
    CONSTRUCTORS = [
        lambda v: v,
        lambda v: [v],
        lambda v: [{'key': v}],
    ]
    
    class TestNamedTuple(unittest.TestCase):
        def test_namedtuple_dumps(self):
            for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:
                d = v._asdict()
                self.assertEqual(d, json.loads(json.dumps(v)))
                self.assertEqual(
                    d,
                    json.loads(json.dumps(v, namedtuple_as_object=True)))
                self.assertEqual(d, json.loads(json.dumps(v, tuple_as_array=False)))
                self.assertEqual(
                    d,
                    json.loads(json.dumps(v, namedtuple_as_object=True,
                                          tuple_as_array=False)))
    
        def test_namedtuple_dumps_false(self):
            for v in [Value(1), Point(1, 2)]:
                l = list(v)
                self.assertEqual(
                    l,
                    json.loads(json.dumps(v, namedtuple_as_object=False)))
                self.assertRaises(TypeError, json.dumps, v,
                    tuple_as_array=False, namedtuple_as_object=False)
    
        def test_namedtuple_dump(self):
            for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:
                d = v._asdict()
                sio = StringIO()
                json.dump(v, sio)
                self.assertEqual(d, json.loads(sio.getvalue()))
                sio = StringIO()
                json.dump(v, sio, namedtuple_as_object=True)
                self.assertEqual(
                    d,
                    json.loads(sio.getvalue()))
                sio = StringIO()
                json.dump(v, sio, tuple_as_array=False)
                self.assertEqual(d, json.loads(sio.getvalue()))
                sio = StringIO()
                json.dump(v, sio, namedtuple_as_object=True,
                          tuple_as_array=False)
                self.assertEqual(
                    d,
                    json.loads(sio.getvalue()))
    
        def test_namedtuple_dump_false(self):
            for v in [Value(1), Point(1, 2)]:
                l = list(v)
                sio = StringIO()
                json.dump(v, sio, namedtuple_as_object=False)
                self.assertEqual(
                    l,
                    json.loads(sio.getvalue()))
                self.assertRaises(TypeError, json.dump, v, StringIO(),
                    tuple_as_array=False, namedtuple_as_object=False)
    
        def test_asdict_not_callable_dump(self):
            for f in CONSTRUCTORS:
                self.assertRaises(TypeError,
                    json.dump, f(DeadDuck()), StringIO(), namedtuple_as_object=True)
                sio = StringIO()
                json.dump(f(DeadDict()), sio, namedtuple_as_object=True)
                self.assertEqual(
                    json.dumps(f({})),
                    sio.getvalue())
    
        def test_asdict_not_callable_dumps(self):
            for f in CONSTRUCTORS:
                self.assertRaises(TypeError,
                    json.dumps, f(DeadDuck()), namedtuple_as_object=True)
                self.assertEqual(
                    json.dumps(f({})),
                    json.dumps(f(DeadDict()), namedtuple_as_object=True))
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_pass1.py000066400000000000000000000035571250413007300254420ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    
    # from http://json.org/JSON_checker/test/pass1.json
    JSON = r'''
    [
        "JSON Test Pattern pass1",
        {"object with 1 member":["array with 1 element"]},
        {},
        [],
        -42,
        true,
        false,
        null,
        {
            "integer": 1234567890,
            "real": -9876.543210,
            "e": 0.123456789e-12,
            "E": 1.234567890E+34,
            "":  23456789012E666,
            "zero": 0,
            "one": 1,
            "space": " ",
            "quote": "\"",
            "backslash": "\\",
            "controls": "\b\f\n\r\t",
            "slash": "/ & \/",
            "alpha": "abcdefghijklmnopqrstuvwyz",
            "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
            "digit": "0123456789",
            "special": "`1~!@#$%^&*()_+-={':[,]}|;.?",
            "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
            "true": true,
            "false": false,
            "null": null,
            "array":[  ],
            "object":{  },
            "address": "50 St. James Street",
            "url": "http://www.JSON.org/",
            "comment": "// /*  */": " ",
            " s p a c e d " :[1,2 , 3
    
    ,
    
    4 , 5        ,          6           ,7        ],
            "compact": [1,2,3,4,5,6,7],
            "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
            "quotes": "" \u0022 %22 0x22 034 "",
            "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
    : "A key can be any string"
        },
        0.5 ,98.6
    ,
    99.44
    ,
    
    1066
    
    
    ,"rosebud"]
    '''
    
    class TestPass1(TestCase):
        def test_parse(self):
            # test in/out equivalence and parsing
            res = json.loads(JSON)
            out = json.dumps(res)
            self.assertEquals(res, json.loads(out))
            try:
                json.dumps(res, allow_nan=False)
            except ValueError:
                pass
            else:
                self.fail("23456789012E666 should be out of range")
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_pass2.py000066400000000000000000000006031250413007300254300ustar00rootroot00000000000000from unittest import TestCase
    import simplejson as json
    
    # from http://json.org/JSON_checker/test/pass2.json
    JSON = r'''
    [[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
    '''
    
    class TestPass2(TestCase):
        def test_parse(self):
            # test in/out equivalence and parsing
            res = json.loads(JSON)
            out = json.dumps(res)
            self.assertEquals(res, json.loads(out))
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_pass3.py000066400000000000000000000007431250413007300254360ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    
    # from http://json.org/JSON_checker/test/pass3.json
    JSON = r'''
    {
        "JSON Test Pattern pass3": {
            "The outermost value": "must be an object or array.",
            "In this test": "It is an object."
        }
    }
    '''
    
    class TestPass3(TestCase):
        def test_parse(self):
            # test in/out equivalence and parsing
            res = json.loads(JSON)
            out = json.dumps(res)
            self.assertEquals(res, json.loads(out))
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_recursion.py000066400000000000000000000032201250413007300264070ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    
    class JSONTestObject:
        pass
    
    
    class RecursiveJSONEncoder(json.JSONEncoder):
        recurse = False
        def default(self, o):
            if o is JSONTestObject:
                if self.recurse:
                    return [JSONTestObject]
                else:
                    return 'JSONTestObject'
            return json.JSONEncoder.default(o)
    
    
    class TestRecursion(TestCase):
        def test_listrecursion(self):
            x = []
            x.append(x)
            try:
                json.dumps(x)
            except ValueError:
                pass
            else:
                self.fail("didn't raise ValueError on list recursion")
            x = []
            y = [x]
            x.append(y)
            try:
                json.dumps(x)
            except ValueError:
                pass
            else:
                self.fail("didn't raise ValueError on alternating list recursion")
            y = []
            x = [y, y]
            # ensure that the marker is cleared
            json.dumps(x)
    
        def test_dictrecursion(self):
            x = {}
            x["test"] = x
            try:
                json.dumps(x)
            except ValueError:
                pass
            else:
                self.fail("didn't raise ValueError on dict recursion")
            x = {}
            y = {"a": x, "b": x}
            # ensure that the marker is cleared
            json.dumps(y)
    
        def test_defaultrecursion(self):
            enc = RecursiveJSONEncoder()
            self.assertEquals(enc.encode(JSONTestObject), '"JSONTestObject"')
            enc.recurse = True
            try:
                enc.encode(JSONTestObject)
            except ValueError:
                pass
            else:
                self.fail("didn't raise ValueError on default recursion")
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_scanstring.py000066400000000000000000000077341250413007300265670ustar00rootroot00000000000000import sys
    from unittest import TestCase
    
    import simplejson as json
    import simplejson.decoder
    
    class TestScanString(TestCase):
        def test_py_scanstring(self):
            self._test_scanstring(simplejson.decoder.py_scanstring)
    
        def test_c_scanstring(self):
            if not simplejson.decoder.c_scanstring:
                return
            self._test_scanstring(simplejson.decoder.c_scanstring)
    
        def _test_scanstring(self, scanstring):
            self.assertEquals(
                scanstring('"z\\ud834\\udd20x"', 1, None, True),
                (u'z\U0001d120x', 16))
    
            if sys.maxunicode == 65535:
                self.assertEquals(
                    scanstring(u'"z\U0001d120x"', 1, None, True),
                    (u'z\U0001d120x', 6))
            else:
                self.assertEquals(
                    scanstring(u'"z\U0001d120x"', 1, None, True),
                    (u'z\U0001d120x', 5))
    
            self.assertEquals(
                scanstring('"\\u007b"', 1, None, True),
                (u'{', 8))
    
            self.assertEquals(
                scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True),
                (u'A JSON payload should be an object or array, not a string.', 60))
    
            self.assertEquals(
                scanstring('["Unclosed array"', 2, None, True),
                (u'Unclosed array', 17))
    
            self.assertEquals(
                scanstring('["extra comma",]', 2, None, True),
                (u'extra comma', 14))
    
            self.assertEquals(
                scanstring('["double extra comma",,]', 2, None, True),
                (u'double extra comma', 21))
    
            self.assertEquals(
                scanstring('["Comma after the close"],', 2, None, True),
                (u'Comma after the close', 24))
    
            self.assertEquals(
                scanstring('["Extra close"]]', 2, None, True),
                (u'Extra close', 14))
    
            self.assertEquals(
                scanstring('{"Extra comma": true,}', 2, None, True),
                (u'Extra comma', 14))
    
            self.assertEquals(
                scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True),
                (u'Extra value after close', 26))
    
            self.assertEquals(
                scanstring('{"Illegal expression": 1 + 2}', 2, None, True),
                (u'Illegal expression', 21))
    
            self.assertEquals(
                scanstring('{"Illegal invocation": alert()}', 2, None, True),
                (u'Illegal invocation', 21))
    
            self.assertEquals(
                scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True),
                (u'Numbers cannot have leading zeroes', 37))
    
            self.assertEquals(
                scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True),
                (u'Numbers cannot be hex', 24))
    
            self.assertEquals(
                scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True),
                (u'Too deep', 30))
    
            self.assertEquals(
                scanstring('{"Missing colon" null}', 2, None, True),
                (u'Missing colon', 16))
    
            self.assertEquals(
                scanstring('{"Double colon":: null}', 2, None, True),
                (u'Double colon', 15))
    
            self.assertEquals(
                scanstring('{"Comma instead of colon", null}', 2, None, True),
                (u'Comma instead of colon', 25))
    
            self.assertEquals(
                scanstring('["Colon instead of comma": false]', 2, None, True),
                (u'Colon instead of comma', 25))
    
            self.assertEquals(
                scanstring('["Bad value", truth]', 2, None, True),
                (u'Bad value', 12))
    
        def test_issue3623(self):
            self.assertRaises(ValueError, json.decoder.scanstring, "xxx", 1,
                              "xxx")
            self.assertRaises(UnicodeDecodeError,
                              json.encoder.encode_basestring_ascii, "xx\xff")
    
        def test_overflow(self):
            # Python 2.5 does not have maxsize
            maxsize = getattr(sys, 'maxsize', sys.maxint)
            self.assertRaises(OverflowError, json.decoder.scanstring, "xxx",
                              maxsize + 1)
    
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_separators.py000066400000000000000000000016611250413007300265700ustar00rootroot00000000000000import textwrap
    from unittest import TestCase
    
    import simplejson as json
    
    
    class TestSeparators(TestCase):
        def test_separators(self):
            h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
                 {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
    
            expect = textwrap.dedent("""\
            [
              [
                "blorpie"
              ] ,
              [
                "whoops"
              ] ,
              [] ,
              "d-shtaeou" ,
              "d-nthiouh" ,
              "i-vhbjkhnth" ,
              {
                "nifty" : 87
              } ,
              {
                "field" : "yes" ,
                "morefield" : false
              }
            ]""")
    
    
            d1 = json.dumps(h)
            d2 = json.dumps(h, indent='  ', sort_keys=True, separators=(' ,', ' : '))
    
            h1 = json.loads(d1)
            h2 = json.loads(d2)
    
            self.assertEquals(h1, h)
            self.assertEquals(h2, h)
            self.assertEquals(d2, expect)
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_speedups.py000066400000000000000000000011201250413007300262230ustar00rootroot00000000000000from unittest import TestCase
    
    from simplejson import encoder, scanner
    
    def has_speedups():
        return encoder.c_make_encoder is not None
    
    class TestDecode(TestCase):
        def test_make_scanner(self):
            if not has_speedups():
                return
            self.assertRaises(AttributeError, scanner.c_make_scanner, 1)
    
        def test_make_encoder(self):
            if not has_speedups():
                return
            self.assertRaises(TypeError, encoder.c_make_encoder,
                None,
                "\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75",
                None)
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_tuple.py000066400000000000000000000034621250413007300255370ustar00rootroot00000000000000import unittest
    from StringIO import StringIO
    
    import simplejson as json
    
    class TestTuples(unittest.TestCase):
        def test_tuple_array_dumps(self):
            t = (1, 2, 3)
            expect = json.dumps(list(t))
            # Default is True
            self.assertEqual(expect, json.dumps(t))
            self.assertEqual(expect, json.dumps(t, tuple_as_array=True))
            self.assertRaises(TypeError, json.dumps, t, tuple_as_array=False)
            # Ensure that the "default" does not get called
            self.assertEqual(expect, json.dumps(t, default=repr))
            self.assertEqual(expect, json.dumps(t, tuple_as_array=True, default=repr))
            # Ensure that the "default" gets called
            self.assertEqual(
                json.dumps(repr(t)),
                json.dumps(t, tuple_as_array=False, default=repr))
    
        def test_tuple_array_dump(self):
            t = (1, 2, 3)
            expect = json.dumps(list(t))
            # Default is True
            sio = StringIO()
            json.dump(t, sio)
            self.assertEqual(expect, sio.getvalue())
            sio = StringIO()
            json.dump(t, sio, tuple_as_array=True)
            self.assertEqual(expect, sio.getvalue())
            self.assertRaises(TypeError, json.dump, t, StringIO(), tuple_as_array=False)
            # Ensure that the "default" does not get called
            sio = StringIO()
            json.dump(t, sio, default=repr)
            self.assertEqual(expect, sio.getvalue())
            sio = StringIO()
            json.dump(t, sio, tuple_as_array=True, default=repr)
            self.assertEqual(expect, sio.getvalue())
            # Ensure that the "default" gets called
            sio = StringIO()
            json.dump(t, sio, tuple_as_array=False, default=repr)
            self.assertEqual(
                json.dumps(repr(t)),
                sio.getvalue())
    
    class TestNamedTuple(unittest.TestCase):
        def test_namedtuple_dump(self):
            passpygments.rb-0.6.3/vendor/simplejson/simplejson/tests/test_unicode.py000066400000000000000000000111171250413007300260300ustar00rootroot00000000000000from unittest import TestCase
    
    import simplejson as json
    
    class TestUnicode(TestCase):
        def test_encoding1(self):
            encoder = json.JSONEncoder(encoding='utf-8')
            u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
            s = u.encode('utf-8')
            ju = encoder.encode(u)
            js = encoder.encode(s)
            self.assertEquals(ju, js)
    
        def test_encoding2(self):
            u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
            s = u.encode('utf-8')
            ju = json.dumps(u, encoding='utf-8')
            js = json.dumps(s, encoding='utf-8')
            self.assertEquals(ju, js)
    
        def test_encoding3(self):
            u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
            j = json.dumps(u)
            self.assertEquals(j, '"\\u03b1\\u03a9"')
    
        def test_encoding4(self):
            u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
            j = json.dumps([u])
            self.assertEquals(j, '["\\u03b1\\u03a9"]')
    
        def test_encoding5(self):
            u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
            j = json.dumps(u, ensure_ascii=False)
            self.assertEquals(j, u'"' + u + u'"')
    
        def test_encoding6(self):
            u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
            j = json.dumps([u], ensure_ascii=False)
            self.assertEquals(j, u'["' + u + u'"]')
    
        def test_big_unicode_encode(self):
            u = u'\U0001d120'
            self.assertEquals(json.dumps(u), '"\\ud834\\udd20"')
            self.assertEquals(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')
    
        def test_big_unicode_decode(self):
            u = u'z\U0001d120x'
            self.assertEquals(json.loads('"' + u + '"'), u)
            self.assertEquals(json.loads('"z\\ud834\\udd20x"'), u)
    
        def test_unicode_decode(self):
            for i in range(0, 0xd7ff):
                u = unichr(i)
                #s = '"\\u{0:04x}"'.format(i)
                s = '"\\u%04x"' % (i,)
                self.assertEquals(json.loads(s), u)
    
        def test_object_pairs_hook_with_unicode(self):
            s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
            p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4),
                 (u"qrt", 5), (u"pad", 6), (u"hoy", 7)]
            self.assertEqual(json.loads(s), eval(s))
            self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
            od = json.loads(s, object_pairs_hook=json.OrderedDict)
            self.assertEqual(od, json.OrderedDict(p))
            self.assertEqual(type(od), json.OrderedDict)
            # the object_pairs_hook takes priority over the object_hook
            self.assertEqual(json.loads(s,
                                        object_pairs_hook=json.OrderedDict,
                                        object_hook=lambda x: None),
                             json.OrderedDict(p))
    
    
        def test_default_encoding(self):
            self.assertEquals(json.loads(u'{"a": "\xe9"}'.encode('utf-8')),
                {'a': u'\xe9'})
    
        def test_unicode_preservation(self):
            self.assertEquals(type(json.loads(u'""')), unicode)
            self.assertEquals(type(json.loads(u'"a"')), unicode)
            self.assertEquals(type(json.loads(u'["a"]')[0]), unicode)
    
        def test_ensure_ascii_false_returns_unicode(self):
            # http://code.google.com/p/simplejson/issues/detail?id=48
            self.assertEquals(type(json.dumps([], ensure_ascii=False)), unicode)
            self.assertEquals(type(json.dumps(0, ensure_ascii=False)), unicode)
            self.assertEquals(type(json.dumps({}, ensure_ascii=False)), unicode)
            self.assertEquals(type(json.dumps("", ensure_ascii=False)), unicode)
    
        def test_ensure_ascii_false_bytestring_encoding(self):
            # http://code.google.com/p/simplejson/issues/detail?id=48
            doc1 = {u'quux': 'Arr\xc3\xaat sur images'}
            doc2 = {u'quux': u'Arr\xeat sur images'}
            doc_ascii = '{"quux": "Arr\\u00eat sur images"}'
            doc_unicode = u'{"quux": "Arr\xeat sur images"}'
            self.assertEquals(json.dumps(doc1), doc_ascii)
            self.assertEquals(json.dumps(doc2), doc_ascii)
            self.assertEquals(json.dumps(doc1, ensure_ascii=False), doc_unicode)
            self.assertEquals(json.dumps(doc2, ensure_ascii=False), doc_unicode)
    
        def test_ensure_ascii_linebreak_encoding(self):
            # http://timelessrepo.com/json-isnt-a-javascript-subset
            s1 = u'\u2029\u2028'
            s2 = s1.encode('utf8')
            expect = '"\\u2029\\u2028"'
            self.assertEquals(json.dumps(s1), expect)
            self.assertEquals(json.dumps(s2), expect)
            self.assertEquals(json.dumps(s1, ensure_ascii=False), expect)
            self.assertEquals(json.dumps(s2, ensure_ascii=False), expect)
    pygments.rb-0.6.3/vendor/simplejson/simplejson/tool.py000066400000000000000000000017751250413007300231670ustar00rootroot00000000000000r"""Command-line tool to validate and pretty-print JSON
    
    Usage::
    
        $ echo '{"json":"obj"}' | python -m simplejson.tool
        {
            "json": "obj"
        }
        $ echo '{ 1.2:3.4}' | python -m simplejson.tool
        Expecting property name: line 1 column 2 (char 2)
    
    """
    import sys
    import simplejson as json
    
    def main():
        if len(sys.argv) == 1:
            infile = sys.stdin
            outfile = sys.stdout
        elif len(sys.argv) == 2:
            infile = open(sys.argv[1], 'rb')
            outfile = sys.stdout
        elif len(sys.argv) == 3:
            infile = open(sys.argv[1], 'rb')
            outfile = open(sys.argv[2], 'wb')
        else:
            raise SystemExit(sys.argv[0] + " [infile [outfile]]")
        try:
            obj = json.load(infile,
                            object_pairs_hook=json.OrderedDict,
                            use_decimal=True)
        except ValueError, e:
            raise SystemExit(e)
        json.dump(obj, outfile, sort_keys=True, indent='    ', use_decimal=True)
        outfile.write('\n')
    
    
    if __name__ == '__main__':
        main()