text:
require 'helper'

class TestImage < Test::Unit::TestCase

  test "create an image given the proper coordinates" do
    image = Wireframe::Image.new("50+10").draw
    assert_not_nil image
  end

  test "should draw an image of the proper width" do
    image = Wireframe::Image.new("50+10").draw
    assert_equal 50, image_from_string(image).columns
  end

  test "should draw an image of the proper height" do
    image = Wireframe::Image.new("50+10").draw
    assert_equal 10, image_from_string(image).rows
  end

  private

  def image_from_string(string)
    Magick::Image.from_blob(string)[0]
  end

end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DocumentDiscussionsWeb.Pages
{
    public partial class PostDocumentStory : System.Web.UI.Page
    {

    }
}


text:
This library provides a nice pizza graph view. it was made for developers who wants a better UI for their apps!

# Installation

## From CocoaPods
RSPizzaGraphView is available through [CocoaPods](https://cocoapods.org/). To install
it, simply add the following line to your Podfile:

    pod "RSPizzaGraphView"

## Manually
Copy the source file RSPizzaGraphView into your project.

# Usage

RSPizzaGraphView is a UIView. So, you can create a UIView in the InterfaceBuilder and use it as an @IBOutlet,
or you can create it manually. If you wanna use as an @IBOutlet, does not forget to set RSPizzaGraphView as the Custom Class
of your UIView in the Interface Builder.

You need to have some values and colors in order to configure your graph. You will use the RSPizzaGraph class.
You can configure the values of graph like this code, for example:

```swift
     let graphs = [RSPizzaGraph(value: 50, color: UIColor.red),
                  RSPizzaGraph(value: 15, color: UIColor.blue),
                  RSPizzaGraph(value: 23, color: UIColor.yellow),
                  RSPizzaGraph(value: 30, color: UIColor.black),
                  RSPizzaGraph(value: 20, color: UIColor.darkGray)]
```

The size of each slice will be calculated according the value. You can choose any color you want. Choose the nice ones! :)

You just need to call one function to configure the RSPizzaGraphView. This function have three required parameters.
The others are optionals. Assuming you already have a initialized RSPizzaGraphView,
you can call the function like this code below:

```swift
    pizzaGraphView.configureGraph(borderWidth: 150,
    graphs: graphs,
    animation: .circular,
    shouldShowText: true,
    font: UIFont.systemFont(ofSize: 15),
    textColor: UIColor.white,
    unityText: "pt")
```

* **borderWidth**: While the width of the view is the width of all RSPizzaGraphView,
the border width is the width of the colored border.
* **graphs**: The array of RSPizzaGraph, like explained above.
* **animation**: The type of the animation. It is a enum called RSPizzaGraphAnimation. Can be *.circular* or *.sliceFading*.
* **shouldShowText**: It is a boolean that defines if the pizza graph should show the number values over the graph.
The default value is *false*.
* **font**: The font used in the texts. If shouldShowText is false, it will be useless.
The default value is *UIFont.systemFont(ofSize: 12)*
* **textColor**: The text color of texts. If shouldShowText is false, it will be useless.
The default value is *UIColor.black*.
* **unityText**: This text will be showed together the values, in order to define its unity, if necessary.
The default is *""*.

The parameters **borderWidth**, **graphs** and **animation** are *required*. The other ones are *optionals*.

# Screenshots

Circular animation | SliceFading animation
:-------------------------:|:-------------------------:
 |


text:
//server.js

//set up
var express         = require('express');           //express framework
var app             = express();                    //app with express
var http            = require('http').Server(app);
var io              = require('socket.io')(http);   // socket.io
var nodemailer      = require('nodemailer');        // Node Mail module
var mongoose		= require('mongoose');			// mongoose for mongodb
//var morgan			= require('morgan');			// log requests to the console (express4)
var bodyParser		= require('body-parser');		// pull information from HTML POST (express4)
var methodOverride	= require('method-override');	// simulate DELETE and PUT (express4)
var favicon         = require('serve-favicon');     //favicon

//mongo configuration
mongoose.set('debug', false);                           // mongoose debug mode
mongoose.connect('mongodb://localhost:27017/notes');	// connect to mongoDB database

//app settings
app.use(express.static('public'));           			// set the static files location
//app.use(morgan('debug'));                                // log every request to the console
app.use(bodyParser.json());                             // parse application/json
app.use(methodOverride());                              // delete & put requests
app.use(favicon(__dirname + '/public/img/favicon.ico'));

//define mongoose models
var UserSchema = new mongoose.Schema({
    socketId: {
        type: String,
        unique: true
    }
});
var User = mongoose.model('User', UserSchema);

var NoteSchema = new mongoose.Schema({
    _creator: {type: String, ref: 'User'},
    text: String
});
var Note = mongoose.model('Note', NoteSchema);

//Socket IO
io.on('connection', function(socket){

    User.create({ socketId: socket.id}, function(err) {
        if (err) return console.error(err);
    });

    socket.on('disconnect', function(){
        Note.remove({ _creator: socket.id}, function(err) {
            if (err) return console.error(err);
        });

        User.remove({ socketId: socket.id}, function(err) {
            if (err) return console.error(err);
        });
    });
});

//API Routes

//update
app.put('/api/notes', function(req, res) {
    Note.update({ _id : req.body.dbId }, { text: req.body.msg }, function(err) {
        if (err) res.send(err);
        res.send().end();
    });
});
//get all *NOT USED*
app.get('/api/notes', function(req, res) {
    res.send().end();
});

//create
app.post('/api/notes', function(req, res) {
    Note.create({
        text: req.body.text,
        _creator: req.body.client
    }, function(err) {
        if (err) res.send(err);

        Note.find({_creator: req.body.client}, function(err, notes) {
            if (err) res.send(err);
            res.json(notes);
        });
    });
});
//delete
app.delete('/api/notes/:noteId/:clientId', function(req, res) {
    Note.remove({
        _id : req.params.noteId
    }, function(err) {
        if (err) res.send(err);

        Note.find({_creator: req.params.clientId}, function(err, notes) {
            if (err) res.send(err);
            res.json(notes);
        });
    });
});

//Route SendMail
app.post('/send/msg', function(req, res) {
    /*TEMPORARY DISABLED*/
    /*
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'xxxx@xxx.com',
            pass: 'xxxxxx'
        }
    });

    var mailOptions = {
        from: 'Test MSG',
        to: 'xxxx@xxx.com, xxxx@xxx.by',
        subject: '',
        text: '',
        html: ''
    };

    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            return console.log(error);
        }
        console.log('Message sent: ' + info.response);
    });
    */
    res.send().end();
});

//Routes
app.get('/notes', function(req, res) {
    res.sendFile('notes.html', {root: __dirname + '/public'}, function(err) {
        res.status(404).end();
    });
});

app.get('*', function(req, res) {
    res.status(404).end();
});

//Listen port
http.listen(80, function() {
    console.log("App listening on port 80");
});


text:
package lirc

import (
	gopi "github.com/djthorpe/gopi/v3"
)

////////////////////////////////////////////////////////////////////////////////
// TYPES

type lirc struct {
	gopi.Unit
}

////////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS

func (this *lirc) RecvMode() gopi.LIRCMode {
	return gopi.LIRC_MODE_NONE
}

func (this *lirc) SendMode() gopi.LIRCMode {
	return gopi.LIRC_MODE_NONE
}

func (this *lirc) SetRecvMode(gopi.LIRCMode) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) SetSendMode(gopi.LIRCMode) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) RecvDutyCycle() uint32 {
	return 0
}

func (this *lirc) RecvResolutionMicros() uint32 {
	return 0
}

func (this *lirc) SetRecvTimeoutMs(uint32) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) SetRecvTimeoutReports(bool) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) SetRecvCarrierHz(uint32) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) SetRecvCarrierRangeHz(min, max uint32) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) SendDutyCycle() uint32 {
	return 0
}
func (this *lirc) SetSendCarrierHz(uint32) error {
	return gopi.ErrNotImplemented

}
func (this *lirc) SetSendDutyCycle(uint32) error {
	return gopi.ErrNotImplemented
}

func (this *lirc) PulseSend([]uint32) error {
	return gopi.ErrNotImplemented
}

////////////////////////////////////////////////////////////////////////////////
// STRINGIFY

func (this *lirc) String() string {
	str := "<lirc"
	return str + ">"
}


text:
class RubyBuild < Formula
  desc "Install various Ruby versions and implementations"
  homepage "https://github.com/rbenv/ruby-build"
  url "https://github.com/rbenv/ruby-build/archive/v20200819.tar.gz"
  sha256 "4f2e76f0ebb169dc0760b7cc0ddf863277a7dd56399d390367c285c2eb5a9f9b"
  license "MIT"
  head "https://github.com/rbenv/ruby-build.git"

  bottle :unneeded

  depends_on "autoconf"
  depends_on "pkg-config"
  depends_on "readline"

  def install
    ENV["PREFIX"] = prefix
    system "./install.sh"
  end

  def caveats
    <<~EOS
      ruby-build installs a non-Homebrew OpenSSL for each Ruby version installed and these are never upgraded.

      To link Rubies to Homebrew's OpenSSL 1.1 (which is upgraded) add the following
      to your #{shell_profile}:
        export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix openssl@1.1)"

      Note: this may interfere with building old versions of Ruby (e.g <2.4) that use
      OpenSSL <1.1.
    EOS
  end

  test do
    assert_match "2.0.0", shell_output("#{bin}/ruby-build --definitions")
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<widget id="com.github.vasudeva-chaynes.svadhyaya" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>Svadhyaya</name>
  <description>    SGS Datta Deepam flash card application; under development.  </description>
  <author email="svadhyaya.app@gmail.com"	  href="https://github.com/vasudeva-chaynes/Svadhyaya">Vasudeva (Chris Haynes</author>
  <content src="index.html"/>
  <access origin="*"/>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="true"/>
  <preference name="BackupWebStorage" value="none"/>
  <feature name="StatusBar">
    <param name="ios-package" value="CDVStatusBar" onload="true"/>
  </feature>
</widget>


text:
package org.basex.build;

import static org.basex.core.Text.*;

import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;

import org.basex.core.*;
import org.basex.core.MainOptions.MainParser;
import org.basex.core.cmd.*;
import org.basex.io.*;
import org.basex.io.in.*;
import org.basex.util.*;
import org.basex.util.list.*;

/**
 * This class recursively scans files and directories and parses all
 * relevant files.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Christian Gruen
 */
public final class DirParser extends Parser {
  /** Number of skipped files to log. */
  private static final int SKIPLOG = 10;
  /** Skipped files. */
  private final StringList skipped = new StringList();
  /** File pattern. */
  private final Pattern filter;
  /** Initial file path. */
  private final String root;

  /** Parse archives in directories. */
  private final boolean archives;
  /** Skip corrupt files in directories. */
  private final boolean skipCorrupt;
  /** Add ignored files as raw files. */
  private final boolean addRaw;
  /** DTD parsing. */
  private final boolean dtd;
  /** Raw parsing. */
  private final boolean rawParser;
  /** Archive name. */
  private final boolean archiveName;
  /** Database path for storing binary files. */
  private IOFile rawPath;

  /** Last source. */
  private IO lastSrc;
  /** Parser reference. */
  private Parser parser;
  /** Element counter. */
  private int c;

  /**
   * Constructor.
   * @param source source path
   * @param options main options
   */
  public DirParser(final IO source, final MainOptions options) {
    super(source, options);

    final String dir = source.dir();
    root = dir.endsWith("/") ? dir : dir + '/';
    skipCorrupt = options.get(MainOptions.SKIPCORRUPT);
    archives = options.get(MainOptions.ADDARCHIVES);
    archiveName = options.get(MainOptions.ARCHIVENAME);
    addRaw = options.get(MainOptions.ADDRAW);
    dtd = options.get(MainOptions.DTD);
    rawParser = options.get(MainOptions.PARSER) == MainParser.RAW;
    filter = !source.isDir() && !source.isArchive() ? null :
      Pattern.compile(IOFile.regex(options.get(MainOptions.CREATEFILTER)));
  }

  /**
   * Constructor.
   * @param source source path
   * @param options main options
   * @param dbpath future database path (required for binary resources)
   */
  public DirParser(final IO source, final MainOptions options, final IOFile dbpath) {
    this(source, options);
    if(dbpath != null && (addRaw || rawParser)) rawPath = new IOFile(dbpath, IO.RAW);
  }

  @Override
  public void parse(final Builder build) throws IOException {
    build.meta.filesize = 0;
    build.meta.original = source.path();
    parse(build, source);
  }

  /**
   * Parses the specified file or its children.
   * @param builder builder
   * @param input current input
   * @throws IOException I/O exception
   */
  private void parse(final Builder builder, final IO input) throws IOException {
    if(input instanceof IOFile && input.isDir()) {
      for(final IO f : ((IOFile) input).children()) parse(builder, f);
    } else if(archives && input.isArchive()) {
      final String name = input.name().toLowerCase(Locale.ENGLISH);
      InputStream in = input.inputStream();
      if(name.endsWith(IO.TARSUFFIX) || name.endsWith(IO.TGZSUFFIX) ||
          name.endsWith(IO.TARGZSUFFIX)) {
        // process TAR files
        if(!name.endsWith(IO.TARSUFFIX)) in = new GZIPInputStream(in);
        try(final TarInputStream is = new TarInputStream(in)) {
          for(TarEntry ze; (ze = is.getNextEntry()) != null;) {
            if(ze.isDirectory()) continue;
            source = newStream(is, ze.getName(), input);
            source.length(ze.getSize());
            parseResource(builder);
          }
        }
      } else if(name.endsWith(IO.GZSUFFIX)) {
        // process GZIP archive
        try(final GZIPInputStream is = new GZIPInputStream(in)) {
          source = newStream(is, input.name().replaceAll("\\..*", IO.XMLSUFFIX), input);
          parseResource(builder);
        }
      } else {
        // process ZIP archive
        try(final ZipInputStream is = new ZipInputStream(in)) {
          for(ZipEntry ze; (ze = is.getNextEntry()) != null;) {
            if(ze.isDirectory()) continue;
            source = newStream(is, ze.getName(), input);
            source.length(ze.getSize());
            parseResource(builder);
          }
        }
      }
    } else {
      // process regular file
      source = input;
      parseResource(builder);
    }
  }

  /**
   * Creates a new stream.
   * @param is input stream
   * @param path path inside archive
   * @param input input
   * @return stream
   */
  private IOStream newStream(final InputStream is, final String path, final IO input) {
    return new IOStream(is, archiveName ? (input.path() + '/' + path) : path);
  }

  /**
   * Parses the current source.
   * @param builder builder instance
   * @throws IOException I/O exception
   */
  private void parseResource(final Builder builder) throws IOException {
    builder.checkStop();

    // add file size for database meta information
    final long l = source.length();
    if(l != -1) builder.meta.filesize += l;

    // use global target as path prefix
    final String name = source.name();
    String targ = target;

    // add relative path without root (prefix) and file name (suffix)
    String path = source.path();
    if(path.endsWith('/' + name)) {
      path = path.substring(0, path.length() - name.length());
      if(path.startsWith(root)) path = path.substring(root.length());
      targ = (targ + path).replace("//", "/");
    }

    // check if file passes the name filter pattern
    boolean exclude = false;
    if(filter != null) {
      final String nm = Prop.CASE ? name : name.toLowerCase(Locale.ENGLISH);
      exclude = !filter.matcher(nm).matches();
    }

    if(exclude) {
      // exclude file: check if will be added as raw file
      if(addRaw && rawPath != null) {
        Store.store(source.inputSource(), new IOFile(rawPath, targ + name));
      }
    } else {
      if(rawParser) {
        // store input in raw format if database path is known
        if(rawPath != null) {
          Store.store(source.inputSource(), new IOFile(rawPath, targ + name));
        }
      } else {
        // store input as XML
        boolean ok = true;
        IO in = source;
        if(skipCorrupt) {
          // parse file twice to ensure that it is well-formed
          try {
            // cache file contents to allow or speed up a second run
            if(!(source instanceof IOContent || dtd)) {
              in = new IOContent(source.read());
              in.name(name);
            }
            parser = Parser.singleParser(in, options, targ);
            MemBuilder.build("", parser);
          } catch(final IOException ex) {
            Util.debug(ex);
            skipped.add(source.path());
            ok = false;
          }
        }

        // parse file
        if(ok) {
          parser = Parser.singleParser(in, options, targ);
          parser.parse(builder);
        }
        parser = null;
        // dump debug data
        if(Prop.debug && (++c & 0x3FF) == 0) Util.err(";");
      }
    }
  }

  @Override
  public String info() {
    final TokenBuilder tb = new TokenBuilder();
    if(!skipped.isEmpty()) {
      tb.add(SKIPPED).add(COL).add(NL);
      final int s = skipped.size();
      for(int i = 0; i < s && i < SKIPLOG; i++) {
        tb.add(LI).add(skipped.get(i)).add(NL);
      }
      if(s > SKIPLOG) {
        tb.add(LI).addExt(MORE_SKIPPED_X, s - SKIPLOG).add(NL);
      }
    }
    return tb.toString();
  }

  @Override
  public String det() {
    return parser != null ? parser.detail() : source.path();
  }

  @Override
  public double prog() {
    if(parser != null) return parser.progress();
    if(lastSrc == source) return 1;
    lastSrc = source;
    return Math.random();
  }

  @Override
  public void close() throws IOException {
    if(parser != null) parser.close();
  }
}


text:
<?php

namespace Laminas\View\Helper\Escaper;

use Laminas\Escaper;
use Laminas\View\Exception;
use Laminas\View\Helper;

/**
 * Helper for escaping values
 */
abstract class AbstractHelper extends Helper\AbstractHelper
{
    /**
     * @const Recursion constants
     */
    const RECURSE_NONE   = 0x00;
    const RECURSE_ARRAY  = 0x01;
    const RECURSE_OBJECT = 0x02;

    /**
     * @var string Encoding
     */
    protected $encoding = 'UTF-8';

    /**
     * @var Escaper\Escaper
     */
    protected $escaper = null;

    /**
     * Invoke this helper: escape a value
     *
     * @param  mixed $value
     * @param  int   $recurse Expects one of the recursion constants;
     *                        used to decide whether or not to recurse the given value when escaping
     * @throws Exception\InvalidArgumentException
     * @return mixed Given a scalar, a scalar value is returned. Given an object, with the $recurse flag not
     *               allowing object recursion, returns a string. Otherwise, returns an array.
     */
    public function __invoke($value, $recurse = self::RECURSE_NONE)
    {
        if (is_string($value)) {
            return $this->escape($value);
        }

        if (is_array($value)) {
            if (! (self::RECURSE_ARRAY & $recurse)) {
                throw new Exception\InvalidArgumentException(
                    'Array provided to Escape helper, but flags do not allow recursion'
                );
            }
            foreach ($value as $k => $v) {
                $value[$k] = $this->__invoke($v, $recurse);
            }
            return $value;
        }

        if (is_object($value)) {
            if (! (self::RECURSE_OBJECT & $recurse)) {
                // Attempt to cast it to a string
                if (method_exists($value, '__toString')) {
                    return $this->escape((string) $value);
                }
                throw new Exception\InvalidArgumentException(
                    'Object provided to Escape helper, but flags do not allow recursion'
                );
            }
            if (method_exists($value, 'toArray')) {
                return $this->__invoke($value->toArray(), $recurse | self::RECURSE_ARRAY);
            }
            return $this->__invoke((array) $value, $recurse | self::RECURSE_ARRAY);
        }

        return $value;
    }

    /**
     * Escape a value for current escaping strategy
     *
     * @param  string $value
     * @return string
     */
    abstract protected function escape($value);

    /**
     * Set the encoding to use for escape operations
     *
     * @param  string $encoding
     * @throws Exception\InvalidArgumentException
     * @return AbstractHelper
     */
    public function setEncoding($encoding)
    {
        if (null !== $this->escaper) {
            throw new Exception\InvalidArgumentException(
                'Character encoding settings cannot be changed once the Helper has been used or '
                . ' if a Laminas\Escaper\Escaper object (with preset encoding option) is set.'
            );
        }

        $this->encoding = $encoding;

        return $this;
    }

    /**
     * Get the encoding to use for escape operations
     *
     * @return string
     */
    public function getEncoding()
    {
        return $this->encoding;
    }

    /**
     * Set instance of Escaper
     *
     * @param  Escaper\Escaper $escaper
     * @return AbstractHelper
     */
    public function setEscaper(Escaper\Escaper $escaper)
    {
        $this->escaper  = $escaper;
        $this->encoding = $escaper->getEncoding();

        return $this;
    }

    /**
     * Get instance of Escaper
     *
     * @return null|Escaper\Escaper
     */
    public function getEscaper()
    {
        if (null === $this->escaper) {
            $this->setEscaper(new Escaper\Escaper($this->getEncoding()));
        }

        return $this->escaper;
    }
}


text:
<?php

namespace Zend\Mvc\Router\Http;

use Zend\Mvc\Router\RouteMatch as BaseRouteMatch;

/**
 * Part route match.
 */
class RouteMatch extends BaseRouteMatch
{
    /**
     * Length of the matched path.
     *
     * @var integer
     */
    protected $length;

    /**
     * Create a part RouteMatch with given parameters and length.
     *
     * @param  array   $params
     * @param  integer $length
     */
    public function __construct(array $params, $length = 0)
    {
        parent::__construct($params);

        $this->length = $length;
    }

    /**
     * setMatchedRouteName(): defined by BaseRouteMatch.
     *
     * @see    BaseRouteMatch::setMatchedRouteName()
     * @param  string $name
     * @return RouteMatch
     */
    public function setMatchedRouteName($name)
    {
        if ($this->matchedRouteName === null) {
            $this->matchedRouteName = $name;
        } else {
            $this->matchedRouteName = $name . '/' . $this->matchedRouteName;
        }

        return $this;
    }

    /**
     * Merge parameters from another match.
     *
     * @param  RouteMatch $match
     * @return RouteMatch
     */
    public function merge(RouteMatch $match)
    {
        $this->params  = array_merge($this->params, $match->getParams());
        $this->length += $match->getLength();

        $this->matchedRouteName = $match->getMatchedRouteName();

        return $this;
    }

    /**
     * Get the matched path length.
     *
     * @return integer
     */
    public function getLength()
    {
        return $this->length;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Observatory - University of Toronto at Scarborough</title>

The Astronomical Observatory at the University of Toronto Scarborough has ceased operations.

Unfortunately, due to new university priorities and recent construction work related to a new animal testing lab, it is no longer feasible to keep the observatory open.

Until March 2019, the observatory was maintained by Hanno Rein (hanno.rein@utoronto.ca).


text:
use strict;
die "
************************************************************
                      pwm_from_fasta.pl
                      Stewart MacArthur
                        January 2007
                  Updated March 200 for GALAXY
************************************************************
Generates a horizontal counts matrix from a fasta file

USAGE: INFILE OUTFILE

************************************************************
\n" unless @ARGV ==2;

open (INFILE,shift) || die "Can not open INPUT file\n";
my %seqs;
my $counter=0;
while (<INFILE>){
    chomp;
    if (m/^>/){
	$counter++;
    }else {
	tr/a-z/A-Z/;
	$seqs{$counter}.=$_;
    }
}
die "NOT A VALID FASTA FILE\nPlease check the format\n" unless scalar keys %seqs >0;
my %matrix;
my %all_bases;
my $length;
my %lens;
foreach my $seq(keys %seqs) {
    for my $pos (0..length($seqs{$seq})-1) {
	$matrix{substr($seqs{$seq},$pos,1)}{$pos}++;
	$all_bases{substr($seqs{$seq},$pos,1)}++;
    }
$length+=$seqs{$seq}=~tr/ATGC/ATGC/;
    $lens{length($seqs{$seq})}++;
}
die "SEQUENCES ARE NOT OF EQUAL LENGTH\nA counts matrix requires sequences of the same length\n" unless scalar keys %lens ==1;
$length/=scalar keys %seqs;

my @bases= qw(A C G T);

open (OUTFILE,">",shift) || die "Can not create output file\n";

foreach my $base(@bases) {
print OUTFILE "$base| ";
    for my $pos(0..$length-1) {
	if (defined $matrix{$base}{$pos}) {
	    print OUTFILE "$matrix{$base}{$pos}\t";}else {print OUTFILE "0\t";}
    }
print OUTFILE "\n";
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AWSample.EF.Database.DbMappers;

namespace AWSample.EF.Person
{
    public class PersonStore : IPersonStore
    {
        public IList<AWSample.EF.POCO.Person.Person> Get(Expression<Func<AWSample.EF.POCO.Person.Person, bool>> filter = null, Func<IQueryable<AWSample.EF.POCO.Person.Person>, IQueryable<AWSample.EF.POCO.Person.Person>> orderBy = null, ICollection<Expression<Func<AWSample.EF.POCO.Person.Person, object>>> includeProperties = null)
        {
            IList<AWSample.EF.POCO.Person.Person> list = null;
            using (IPersonUnitOfWork unitOfWork = new PersonUnitOfWork())
            {
                list = new PersonDbMapper(unitOfWork).Get(filter, orderBy, includeProperties);
            }

            return list;
        }

        public int Count(Expression<Func<AWSample.EF.POCO.Person.Person, bool>> filter = null)
        {
            int count = 0;
            using (IPersonUnitOfWork unitOfWork = new PersonUnitOfWork())
            {
                count = unitOfWork.PersonRepository.Count(filter);
            }

            return count;
        }

        public void Save(ICollection<AWSample.EF.POCO.Person.Person> entities)
        {
            using (IPersonUnitOfWork unitOfWork = new PersonUnitOfWork())
            {
                new PersonDbMapper(unitOfWork).Save(entities);
                unitOfWork.Save();
            }
        }

        public void SaveGraphs(ICollection<AWSample.EF.POCO.Person.Person> entities)
        {
            using (IPersonUnitOfWork unitOfWork = new PersonUnitOfWork())
            {
                new PersonDbMapper(unitOfWork).SaveGraphs(entities);
                unitOfWork.Save();
            }
        }

        public void Delete(ICollection<AWSample.EF.POCO.Person.Person> entities)
        {
            using (IPersonUnitOfWork unitOfWork = new PersonUnitOfWork())
            {
                new PersonDbMapper(unitOfWork).Delete(entities);
                unitOfWork.Save();
            }
        }
    }
}


text:
package com.trivago.jcha.apps;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import javafx.util.converter.TimeStringConverter;

import com.trivago.jcha.core.DataPointType;
import com.trivago.jcha.core.HistogramAverager;
import com.trivago.jcha.core.JchaUtil;
import com.trivago.jcha.correlation.BaseCorrelator;
import com.trivago.jcha.stats.ClassHistogram;
import com.trivago.jcha.stats.ClassHistogramEntry;
import com.trivago.jcha.stats.ClassHistogramStats;
import com.trivago.jcha.stats.ClassHistogramStatsEntry;

public class App extends Application
{
	com.trivago.jcha.core.Parameters param = new com.trivago.jcha.core.Parameters();
	static String[] args;

	@Override
	public void start(Stage stage)
	{
		if (param.getLimit() <= 0 || param.getLimit() == Integer.MAX_VALUE)
		{
			// Limit 9 is useful, as more typically obscures the graphs.
			// Also more than 9 currently make the legend disappear. Possibly have to add (re)sizing code to fix that.
			param.setLimit(9);
		}
		param.parseArgs(App.args, "jcha-gui", 1); // -<- This is likely not the endorsed way. Can I pick up the args from launch()?
		SortedSet<ClassHistogram> histograms = loadHistograms();
		int count = histograms.size();

		param.overrideClassFilter(calculateClassFilter(histograms));

		Scene scene = new Scene(new Group());
		stage.setWidth(800);
		stage.setHeight(600);
		stage.setTitle("Java Class Histogram Analyzer");

		if (count == 0)
		{
			stage.setTitle("No Histograms given on command line");
		}
		else
		{
	        final LineChart<Number, Number> chart = createChart(histograms, count, param.getDataPointType());

			((Group) scene.getRoot()).getChildren().add(chart);
		}

		stage.setScene(scene);
		stage.show();
	}

	class TimestampToStringConverter extends StringConverter<Number>
	{
		final TimeStringConverter tsc;

		/**
		 * Creates a converter, that uses the default timezone to convert the timestamp into a String.
		 */
		TimestampToStringConverter()
		{
			this(TimeZone.getDefault());
		}

		/**
		 * Creates a converter, that uses the given timezone to convert the timestamp into a String.
		 */
		TimestampToStringConverter(TimeZone tz)
		{
			DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");
			df.setTimeZone(tz);
			tsc = new TimeStringConverter(df);
		}

		@Override
		public String toString(Number t)
		{
			return tsc.toString(new Date(t.longValue()));
		}

		@Override
		public Number fromString(String string)
		{
			return 1;
		}

	}

	private LineChart<Number, Number> createChart(Collection<ClassHistogram> histograms, int count, DataPointType dataPointType)
	{
		boolean useDateAxis = false;
		boolean useSizeYAxis = true;

		final NumberAxis xAxis = new NumberAxis();
		final NumberAxis yAxis = new NumberAxis();
		xAxis.setLabel("Time");
		if (useDateAxis)
		{
			xAxis.setTickLabelFormatter(new TimestampToStringConverter());
		}

		if (useSizeYAxis)
		{
			yAxis.setLabel("Object size"); // or size
		}
		else
		{
			yAxis.setLabel("Object count"); // or size
		}
		//creating the chart
		final LineChart<Number,Number> chart =
		        new LineChart<Number,Number>(xAxis,yAxis);

		String limitText = "";
		if (!param.classFilter().isEmpty())
		{
			limitText = " (filtering for " + param.classFilter().size() + " classes)";
		}
		else if (param.getLimit() != 0)
		{
			limitText = " (class limit " + param.getLimit() + ")";
		}

		String orderText = ""; //" orderBy ignored (impl. pending)";

		if (count == 1)
			chart.setTitle("Analyzed 1 histogram" + orderText);
		else
			chart.setTitle("Analyzed " + count + " histograms" + limitText + orderText);

		Map<String, XYChart.Series<Number,Number>> chartMap = new HashMap<>();
		Map<String, Long> lastInstances = new HashMap<>();

		int x = 1;
		for (ClassHistogram histogram : histograms )
		{
			int limit = param.getLimit();

			for (ClassHistogramEntry entry : histogram.values())
			{
				if (!param.isClassAcceptable(entry.className))
				{
					continue;
				}
				XYChart.Series<Number,Number> series = resolveSeries(chartMap, entry.className);

				final long chartValue ;
				long value = useSizeYAxis ? entry.bytes : entry.instances;

				if (dataPointType == DataPointType.FirstDerivation)
				{
					Long lastInstanceCount = lastInstances.get(entry.className);
					if (lastInstanceCount == null)
						chartValue = 0;
					else
						chartValue = value - lastInstanceCount;
				}
				else
				{
					chartValue = value;
				}

				long xValue;
				if (useDateAxis)
				{
					xValue = histogram.getSnapshotTimeMillisTo();
//					if (xValue < 1344813629000L)
//						continue;
				}
				else
				{
					xValue = x;
				}

				lastInstances.put(entry.className, value);

		        //populating the series with data
		        series.getData().add(new XYChart.Data<Number,Number>(xValue, chartValue));

		        if (limit-- == 0)
		        {
		        	break; // enough
		        }
			}

			x++; // Advance in x-Axis
		}

		ObservableList<Series<Number, Number>> data = chart.getData();
		for (Series<Number,Number> series : chartMap.values())
		{
			data.add(series);
		}
//		data.addListener(arg0);
		return chart;
	}

	/**
	 * Returns a class filter that is most appropriate for the given histograms and the Parameters
	 * field from this object.
	 * If the user has explicitly specified a filter, no calculation is done - the user filter is returned as-is.
	 *
	 * @param histograms
	 * @param classFilter
	 * @param limit
	 * @return
	 */
	private Set<String> calculateClassFilter(SortedSet<ClassHistogram> histograms)
	{
		if (!param.classFilter().isEmpty())
			return param.classFilter();

		Set<String> classFilter = new HashSet<>();
		ClassHistogramStats statsFiltered = HistogramAverager.compareFirstWithSecondHalf(histograms, param);
		BaseCorrelator correlator = JchaUtil.correlate(statsFiltered, param);

		int pos = 0;
outer:	for (Entry<String, ArrayList<ClassHistogramStatsEntry>> groupEntry : correlator.getGroups().entrySet())
		{
			ArrayList<ClassHistogramStatsEntry> group = groupEntry.getValue();
			for (ClassHistogramStatsEntry entry : group)
			{
				classFilter.add(entry.id());
				if (++pos == param.getLimit())
				{
					break outer;
				}
			}
		}

		return classFilter;
	}

	/**
	 * Returns the Series for the given className. It is taken from the given Map.
	 *
	 * @param chartMap
	 * @param className
	 * @return
	 */
	private Series<Number,Number> resolveSeries(Map<String, Series<Number,Number>> chartMap, String className)
	{
		Series<Number,Number> series2 = chartMap.get(className);
		if (series2 != null)
		{
			return series2; // Already exists. Fine. Use it
		}

		series2 = new XYChart.Series<Number,Number>();
        series2.setName(className);
        chartMap.put(className, series2);

		return series2;
	}

	SortedSet<ClassHistogram> loadHistograms()
	{
		List<String> files = param.getFiles();
		int histCountFiles = files.size();
		SortedSet<ClassHistogram> histograms = new TreeSet<>();
		for (int i=0; i< histCountFiles; i++)
		{
			try
			{
				histograms.add(new ClassHistogram(files.get(i), param.ignoreKnownDuplicates(), param.classFilter()));
			}
			catch (Exception exc)
			{
				warn("Ignoring histogram: " + exc.getMessage());
			}
		}

		return histograms;
	}

	private void warn(String string)
	{
		System.err.println("WARN " + string);
		// TODO Move to logger

	}

	public static void main(String[] args)
	{
		App.args = args;
		launch(args);
	}
}


text:
<?php

namespace Slim\Exception;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class MethodNotAllowedException extends SlimException
{
    /**
     * HTTP methods allowed
     *
     * @var string[]
     */
    protected $allowedMethods;

    /**
     * Create new exception
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param string[] $allowedMethods
     */
    public function __construct(ServerRequestInterface $request, ResponseInterface $response, array $allowedMethods)
    {
        parent::__construct($request, $response);
        $this->allowedMethods = $allowedMethods;
    }

    /**
     * Get allowed methods
     *
     * @return string[]
     */
    public function getAllowedMethods()
    {
        return $this->allowedMethods;
    }
}


text:
<#
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
#>

<#
.SYNOPSIS
    A plan represents a package of quotas and capabilities that are offered tenants. A tenant can acquire this plan through an offer to upgrade his access to underlying cloud services.

.DESCRIPTION
    A plan represents a package of quotas and capabilities that are offered tenants. A tenant can acquire this plan through an offer to upgrade his access to underlying cloud services.

.PARAMETER Description
    Description of the plan.

.PARAMETER Id
    URI of the resource.

.PARAMETER Type
    Type of resource.

.PARAMETER SkuIds
    SKU identifiers.

.PARAMETER Tags
    List of key-value pairs.

.PARAMETER ExternalReferenceId
    External reference identifier.

.PARAMETER Name
    Name of the resource.

.PARAMETER DisplayName
    Display name.

.PARAMETER Location
    Location where resource is location.

.PARAMETER QuotaIds
    Quota identifiers under the plan.

.PARAMETER SubscriptionCount
    Subscription count.

#>
function New-PlanObject
{
    param(
        [Parameter(Mandatory = $false)]
        [string]
        $Description,

        [Parameter(Mandatory = $false)]
        [string]
        $Id,

        [Parameter(Mandatory = $false)]
        [string]
        $Type,

        [Parameter(Mandatory = $false)]
        [string[]]
        $SkuIds,

        [Parameter(Mandatory = $false)]
        [System.Collections.Generic.Dictionary[[string],[string]]]
        $Tags,

        [Parameter(Mandatory = $false)]
        [string]
        $ExternalReferenceId,

        [Parameter(Mandatory = $false)]
        [string]
        $Name,

        [Parameter(Mandatory = $false)]
        [string]
        $DisplayName,

        [Parameter(Mandatory = $false)]
        [string]
        $Location,

        [Parameter(Mandatory = $false)]
        [string[]]
        $QuotaIds,

        [Parameter(Mandatory = $false)]
        [System.Nullable`1[long]]
        $SubscriptionCount
    )

    $Object = New-Object -TypeName Microsoft.AzureStack.Management.Subscriptions.Admin.Models.Plan -ArgumentList @($id,$name,$type,$location,$tags,$description,$displayName,$externalReferenceId,$quotaIds,$name,$subscriptionCount,$skuIds)

    if(Get-Member -InputObject $Object -Name Validate -MemberType Method)
    {
        $Object.Validate()
    }

    return $Object
}


text:
> delete software

    apt-get remove libreoffice-common
    apt-get remove unity-webapps-common
    apt-get remove thunderbird totem rhythmbox empathy brasero simple-scan gnome-mahjongg aisleriot gnome-mines cheese transmission-common gnome-orca webbrowser-app gnome-sudoku  landscape-client-ui-install
    apt-get remove onboard deja-dup

> install sunpinyin

    sudo add-apt-repository ppa:ibus-dev/ibus-1.3-lucid
    sudo apt-get update
    sudo apt-get install ibus
    sudo apt-get install ibus-sunpinyin
    rm /etc/apt/sources.list.d/ibus-dev-ubuntu-ibus-1_3-lucid-xenial.list

> install lamp

    apt-get install tasksel
    reboot(重新启动)
    tasksel (选择安装 lamp)
    apt-get update
    apt-get upgrade
    reboot(重新启动)
    apt-get install phpmyadmin
    apt-get install php-gd
    apt-get install git

> config composer

    apt-get install composer
    composer config -g repo.packagist composer http://packagist.phpcomposer.com

/root/.composer/config.json add code

    "secure-http": "false"

    composer global require "fxp/composer-asset-plugin:~1.1.2"

> config apache2 vhosts

    git clone https://github.com/wangjulong/pls2.git
    git clone https://github.com/wangjulong/plsdev.git
    a2enmod rewrite

pls2.conf copy to /etc/apache2/sites-enable/pls2.conf

    cp /var/www/plsdev/pls2.conf /etc/apache2/sites-enabled/

    <VirtualHost *:80>
        ServerName frontend.dev
        DocumentRoot /var/www/pls2/frontend/web
        <Directory /var/www/pls2/frontend/web>

            # use mod_rewrite for pretty URL support
            RewriteEngine on
            # If a directory or a file exists, use the request directly
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            # Otherwise forward the request to index.php
            RewriteRule . index.php

            Options -Indexes +FollowSymLinks +MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    <VirtualHost *:80>
        ServerName backend.dev
        DocumentRoot /var/www/pls2/backend/web
        <Directory /var/www/pls2/backend/web>

            # use mod_rewrite for pretty URL support
            RewriteEngine on
            # If a directory or a file exists, use the request directly
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            # Otherwise forward the request to index.php
            RewriteRule . index.php

            Options -Indexes +FollowSymLinks +MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    <VirtualHost *:80>
        ServerName vagrant.dev
        DocumentRoot /var/www
        <Directory /var/www>
            Options +Indexes +FollowSymLinks +MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    <VirtualHost *:80>
        ServerName plsdev.dev
        DocumentRoot /var/www/plsdev/frontend/web
        <Directory /var/www/plsdev/frontend/web>

            # use mod_rewrite for pretty URL support
            RewriteEngine on
            # If a directory or a file exists, use the request directly
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            # Otherwise forward the request to index.php
            RewriteRule . index.php

            Options -Indexes +FollowSymLinks +MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    <VirtualHost *:80>
        ServerName plsdevback.dev
        DocumentRoot /var/www/plsdev/backend/web
        <Directory /var/www/plsdev/backend/web>

            # use mod_rewrite for pretty URL support
            RewriteEngine on
            # If a directory or a file exists, use the request directly
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            # Otherwise forward the request to index.php
            RewriteRule . index.php

            Options -Indexes +FollowSymLinks +MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>

> config php-xdebug

    sudo apt install php-xdebug

    修改文件 /etc/php/7.0/apache2/php.ini
    参考官网https://www.jetbrains.com/phpstorm/help/configuring-xdebug.html

    [Xdebug]
    zend_extension="xdebug.so"
    xdebug.remote_enable=1
    xdebug.remote_port="9000"
    xdebug.profiler_enable=1
    xdebug.profiler_output_dir="tmp"

> config databases using phpmyadmin

> config /etc/hosts file

    vim /etc/hosts
    127.0.0.1       localhost
    127.0.1.1       wjl-OEM
    127.0.0.1       frontend.dev
    127.0.0.1       backend.dev
    127.0.0.1       vagrant.dev
    127.0.0.1       plsdev.dev
    127.0.0.1       plsdevback.dev

> config fonts

    apt-get install ttf-wqy-microhei  #文泉驿-微米黑
    apt-get install ttf-wqy-zenhei  #文泉驿-正黑
    apt-get install xfonts-wqy #文泉驿-点阵宋体

> software center Synaptic

    apt-get install synaptic gdebi

> system setting tools

    apt-get install unity-tweak-tool gnome-tweak-tool

> clean

    apt-get -y autoremove
    apt-get -y autoclean
    apt-get -y clean


text:
.. taskthread documentation master file, created by
   sphinx-quickstart on Wed Dec  4 15:35:14 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to taskthread's documentation!
======================================

*taskthread* provides a thread implementation that executes a repetitive
task several times without the need to start up a new thread.

Installation
------------

*taskthread* can be installed with pip, via ``pip install taskthread``.

Usage
-----

TaskThread
~~~~~~~~~~
.. autoclass:: taskthread.TaskThread
    :members:

TaskInProcessException
~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: taskthread.TaskInProcessException
    :members:

TimerThread
~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: taskthread.TimerTask
    :members:


text:
package cli

import (
	"os"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"

	exutil "github.com/openshift/origin/test/extended/util"
)

const (
	podLabelTemplate = `{{index .metadata.labels "new-label"}}`
)

var _ = g.Describe("[sig-cli] oc label", func() {
	defer g.GinkgoRecover()

	var oc = exutil.NewCLI("oc-label")

	g.It("pod", func() {
		g.By("creating hello-openshift pod")
		helloPodFile, err := writeObjectToFile(newHelloPod())
		o.Expect(err).NotTo(o.HaveOccurred())
		defer os.Remove(helloPodFile)

		err = oc.Run("create").Args("-f", helloPodFile).Execute()
		o.Expect(err).NotTo(o.HaveOccurred())

		g.By("setting a new label")
		out, err := oc.Run("label").Args("pod", "hello-openshift", "new-label=hello").Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		o.Expect(out).To(o.ContainSubstring("pod/hello-openshift labeled"))

		g.By("validating new label")
		out, err = oc.Run("get").Args("pod", "hello-openshift", "--template", podLabelTemplate).Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		o.Expect(out).To(o.Equal("hello"))

		g.By("removing the label")
		out, err = oc.Run("label").Args("pod", "hello-openshift", "new-label-").Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		o.Expect(out).To(o.Or(o.ContainSubstring("pod/hello-openshift labeled"), o.ContainSubstring("pod/hello-openshift unlabeled")))

		g.By("validating missing label")
		out, err = oc.Run("get").Args("pod", "hello-openshift", "--template", podLabelTemplate).Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		o.Expect(out).To(o.Equal("<no value>"))

		g.By("setting empty label")
		out, err = oc.Run("label").Args("pod", "hello-openshift", `new-label=`).Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		o.Expect(out).To(o.ContainSubstring("pod/hello-openshift labeled"))

		g.By("validating empty label")
		out, err = oc.Run("get").Args("pod", "hello-openshift", "--template", podLabelTemplate).Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		o.Expect(out).To(o.BeEmpty())
	})
})


text:
// $Id: TSS_T.cpp 91693 2010-09-09 12:57:54Z johnnyw $

#ifndef ACE_TSS_T_CPP
#define ACE_TSS_T_CPP

#include "ace/TSS_T.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if !defined (__ACE_INLINE__)
#include "ace/TSS_T.inl"
#endif /* __ACE_INLINE__ */

#include "ace/Thread.h"
#include "ace/Log_Msg.h"
#include "ace/Guard_T.h"
#include "ace/OS_NS_stdio.h"

#if defined (ACE_HAS_THR_C_DEST)
#  include "ace/TSS_Adapter.h"
#endif /* ACE_HAS_THR_C_DEST */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_ALLOC_HOOK_DEFINE(ACE_TSS)

#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))
# if defined (ACE_HAS_THR_C_DEST)
extern "C" void ACE_TSS_C_cleanup (void *);
# endif /* ACE_HAS_THR_C_DEST */
#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */

template <class TYPE>
ACE_TSS<TYPE>::~ACE_TSS (void)
{
#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))
  if (this->once_)
  {
# if defined (ACE_HAS_THR_C_DEST)
    ACE_TSS_Adapter *tss_adapter = this->ts_value ();
    this->ts_value (0);
    ACE_TSS_C_cleanup (tss_adapter);
# else
    TYPE *ts_obj = this->ts_value ();
    this->ts_value (0);
    ACE_TSS<TYPE>::cleanup (ts_obj);
# endif /* ACE_HAS_THR_C_DEST */

    ACE_OS::thr_key_detach (this->key_);
    ACE_OS::thr_keyfree (this->key_);
  }
#else // defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))
  // We own it, we need to delete it.
  delete type_;
#endif // defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))
}

template <class TYPE> TYPE *
ACE_TSS<TYPE>::operator-> () const
{
  return this->ts_get ();
}

template <class TYPE>
ACE_TSS<TYPE>::operator TYPE *(void) const
{
  return this->ts_get ();
}

template <class TYPE> TYPE *
ACE_TSS<TYPE>::make_TSS_TYPE (void) const
{
  TYPE *temp = 0;
  ACE_NEW_RETURN (temp,
                  TYPE,
                  0);
  return temp;
}

template <class TYPE> void
ACE_TSS<TYPE>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))
  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
  this->keylock_.dump ();
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %d\n"), this->key_));
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nonce_ = %d\n"), this->once_));
  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */
#endif /* ACE_HAS_DUMP */
}

#if defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION))

template <class TYPE> void
ACE_TSS<TYPE>::cleanup (void *ptr)
{
  // Cast this to the concrete TYPE * so the destructor gets called.
  delete (TYPE *) ptr;
}

template <class TYPE> int
ACE_TSS<TYPE>::ts_init (void)
{
  // Ensure that we are serialized!
  ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->keylock_, 0);

  // Use the Double-Check pattern to make sure we only create the key
  // once!
  if (!this->once_)
    {
      if (ACE_Thread::keycreate (&this->key_,
#if defined (ACE_HAS_THR_C_DEST)
                                 &ACE_TSS_C_cleanup
#else
                                 &ACE_TSS<TYPE>::cleanup
#endif /* ACE_HAS_THR_C_DEST */
                                 ) != 0)
        return -1; // Major problems, this should *never* happen!
      else
        {
          // This *must* come last to avoid race conditions!
          this->once_ = true;
          return 0;
        }
    }

  return 0;
}

template <class TYPE>
ACE_TSS<TYPE>::ACE_TSS (TYPE *ts_obj)
  : once_ (false),
    key_ (ACE_OS::NULL_key)
{
  // If caller has passed us a non-NULL TYPE *, then we'll just use
  // this to initialize the thread-specific value.  Thus, subsequent
  // calls to operator->() will return this value.  This is useful
  // since it enables us to assign objects to thread-specific data
  // that have arbitrarily complex constructors!

  if (ts_obj != 0)
    {
      if (this->ts_init () == -1)
        {
          // Save/restore errno.
          ACE_Errno_Guard error (errno);
          // What should we do if this call fails?!
#if defined (ACE_HAS_WINCE)
          ::MessageBox (0,
                        ACE_TEXT ("ACE_Thread::keycreate() failed!"),
                        ACE_TEXT ("ACE_TSS::ACE_TSS"),
                        MB_OK);
#else
          ACE_OS::fprintf (stderr,
                           "ACE_Thread::keycreate() failed!");
#endif /* ACE_HAS_WINCE */
          return;
        }

#if defined (ACE_HAS_THR_C_DEST)
      // Encapsulate a ts_obj and it's destructor in an
      // ACE_TSS_Adapter.
      ACE_TSS_Adapter *tss_adapter = 0;
      ACE_NEW (tss_adapter,
               ACE_TSS_Adapter ((void *) ts_obj,
                                ACE_TSS<TYPE>::cleanup));

      // Put the adapter in thread specific storage
      if (this->ts_value (tss_adapter) == -1)
        {
          delete tss_adapter;
        }
#else
      this->ts_value (ts_obj);
#endif /* ACE_HAS_THR_C_DEST */
    }
}

template <class TYPE> TYPE *
ACE_TSS<TYPE>::ts_get (void) const
{
  if (!this->once_)
    {
      // Create and initialize thread-specific ts_obj.
      if (const_cast< ACE_TSS < TYPE > * >(this)->ts_init () == -1)
        // Seriously wrong..
        return 0;
    }

  TYPE *ts_obj = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = this->ts_value ();
  ACE_TSS_Adapter *fake_tss_adapter = 0;

  // If tss_adapter is not 0 but its ts_obj_ is 0 then we still need to create
  // a proper ts_obj. That's the intent of this member function.
  if (tss_adapter != 0 && tss_adapter->ts_obj_ == 0)
    {
      fake_tss_adapter = tss_adapter;
      tss_adapter = 0;
    }

  // Check to see if this is the first time in for this thread.
  if (tss_adapter == 0)
#else
  ts_obj = this->ts_value ();

  // Check to see if this is the first time in for this thread.
  if (ts_obj == 0)
#endif /* ACE_HAS_THR_C_DEST */
    {
      // Allocate memory off the heap and store it in a pointer in
      // thread-specific storage (on the stack...).

      ts_obj = this->make_TSS_TYPE ();

      if (ts_obj == 0)
        return 0;

#if defined (ACE_HAS_THR_C_DEST)
      // Encapsulate a ts_obj and it's destructor in an
      // ACE_TSS_Adapter.
      ACE_NEW_RETURN (tss_adapter,
                      ACE_TSS_Adapter (ts_obj,
                                       ACE_TSS<TYPE>::cleanup), 0);

      // Put the adapter in thread specific storage
      if (this->ts_value (tss_adapter) == -1)
        {
          delete tss_adapter;
          delete ts_obj;
          return 0; // Major problems, this should *never* happen!
        }
#else
      // Store the dynamically allocated pointer in thread-specific
      // storage.
      if (this->ts_value (ts_obj) == -1)
        {
          delete ts_obj;
          return 0; // Major problems, this should *never* happen!
        }
#endif /* ACE_HAS_THR_C_DEST */
    }

#if defined (ACE_HAS_THR_C_DEST)
  // Delete the adapter that didn't actually have a real ts_obj.
  delete fake_tss_adapter;
  // Return the underlying ts object.
  return static_cast <TYPE *> (tss_adapter->ts_obj_);
#else
  return ts_obj;
#endif /* ACE_HAS_THR_C_DEST */
}

// Get the thread-specific object for the key associated with this
// object.  Returns 0 if the ts_obj has never been initialized,
// otherwise returns a pointer to the ts_obj.

template <class TYPE> TYPE *
ACE_TSS<TYPE>::ts_object (void) const
{
  if (!this->once_) // Return 0 if we've never been initialized.
    return 0;

  TYPE *ts_obj = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = this->ts_value ();

  if (tss_adapter != 0)
    {
      // Extract the real TS object.
      ts_obj = static_cast <TYPE *> (tss_adapter->ts_obj_);
    }
#else
  ts_obj = this->ts_value ();
#endif /* ACE_HAS_THR_C_DEST */

  return ts_obj;
}

template <class TYPE> TYPE *
ACE_TSS<TYPE>::ts_object (TYPE *new_ts_obj)
{
  // Note, we shouldn't hold the keylock at this point because
  // <ts_init> does it for us and we'll end up with deadlock
  // otherwise...
  if (!this->once_)
    {
      // Create and initialize thread-specific ts_obj.
      if (this->ts_init () == -1)
        return 0;
    }

  TYPE *ts_obj = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = this->ts_value ();

  if (tss_adapter != 0)
    {
      ts_obj = static_cast <TYPE *> (tss_adapter->ts_obj_);
      // Don't delete tss_adapter yet. It can be double-deleted
      // in case setspecific below fails.
    }

  ACE_TSS_Adapter *new_tss_adapter = 0;
  ACE_NEW_RETURN (new_tss_adapter,
                  ACE_TSS_Adapter ((void *) new_ts_obj,
                                   ACE_TSS<TYPE>::cleanup),
                  0);

  if (this->ts_value (new_tss_adapter) == -1)
    {
      delete new_tss_adapter;
    }
  else
    {
      // Now it's fine to delete the old tss_adapter.
      delete tss_adapter;
    }
#else
  ts_obj = this->ts_value ();
  this->ts_value (new_ts_obj);
#endif /* ACE_HAS_THR_C_DEST */

  return ts_obj;
}

ACE_ALLOC_HOOK_DEFINE(ACE_TSS_Guard)

template <class ACE_LOCK> void
ACE_TSS_Guard<ACE_LOCK>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %d\n"), this->key_));
  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}

template <class ACE_LOCK> void
ACE_TSS_Guard<ACE_LOCK>::init_key (void)
{
  this->key_ = ACE_OS::NULL_key;
  ACE_Thread::keycreate (&this->key_,
#if defined (ACE_HAS_THR_C_DEST)
                         &ACE_TSS_C_cleanup,
#else
                         &ACE_TSS_Guard<ACE_LOCK>::cleanup,
#endif /* ACE_HAS_THR_C_DEST */
                         (void *) this);
}

template <class ACE_LOCK>
ACE_TSS_Guard<ACE_LOCK>::ACE_TSS_Guard (void)
{
  this->init_key ();
}

template <class ACE_LOCK> int
ACE_TSS_Guard<ACE_LOCK>::release (void)
{
  Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->release ();
}

template <class ACE_LOCK> int
ACE_TSS_Guard<ACE_LOCK>::remove (void)
{
  Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->remove ();
}

template <class ACE_LOCK>
ACE_TSS_Guard<ACE_LOCK>::~ACE_TSS_Guard (void)
{
  Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  // Make sure that this pointer is NULL when we shut down...
  ACE_Thread::setspecific (this->key_, 0);
  ACE_Thread::keyfree (this->key_);
  // Destructor releases lock.
  delete guard;
}

template <class ACE_LOCK> void
ACE_TSS_Guard<ACE_LOCK>::cleanup (void *ptr)
{
  // Destructor releases lock.
  delete (Guard_Type *) ptr;
}

template <class ACE_LOCK>
ACE_TSS_Guard<ACE_LOCK>::ACE_TSS_Guard (ACE_LOCK &lock, bool block)
{
  this->init_key ();
  Guard_Type *guard = 0;
  ACE_NEW (guard,
           Guard_Type (lock, block));

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  ACE_NEW (tss_adapter,
           ACE_TSS_Adapter ((void *) guard,
                            ACE_TSS_Guard<ACE_LOCK>::cleanup));
  ACE_Thread::setspecific (this->key_,
                           (void *) tss_adapter);
#else
  ACE_Thread::setspecific (this->key_,
                           (void *) guard);
#endif /* ACE_HAS_THR_C_DEST */
}

template <class ACE_LOCK> int
ACE_TSS_Guard<ACE_LOCK>::acquire (void)
{
  Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->acquire ();
}

template <class ACE_LOCK> int
ACE_TSS_Guard<ACE_LOCK>::tryacquire (void)
{
  Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->tryacquire ();
}

template <class ACE_LOCK>
ACE_TSS_Write_Guard<ACE_LOCK>::ACE_TSS_Write_Guard (ACE_LOCK &lock,
                                                    bool block)
{
  this->init_key ();
  Guard_Type *guard = 0;
  ACE_NEW (guard,
           Write_Guard_Type (lock, block));

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  ACE_NEW (tss_adapter,
           ACE_TSS_Adapter ((void *) guard,
                            ACE_TSS_Guard<ACE_LOCK>::cleanup));
  ACE_Thread::setspecific (this->key_, (void *) tss_adapter);
#else
  ACE_Thread::setspecific (this->key_, (void *) guard);
#endif /* ACE_HAS_THR_C_DEST */
}

template <class ACE_LOCK> int
ACE_TSS_Write_Guard<ACE_LOCK>::acquire (void)
{
  Write_Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Write_Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Write_Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->acquire_write ();
}

template <class ACE_LOCK> int
ACE_TSS_Write_Guard<ACE_LOCK>::tryacquire (void)
{
  Write_Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Write_Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Write_Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->tryacquire_write ();
}

template <class ACE_LOCK> int
ACE_TSS_Write_Guard<ACE_LOCK>::acquire_write (void)
{
  return this->acquire ();
}

template <class ACE_LOCK> int
ACE_TSS_Write_Guard<ACE_LOCK>::tryacquire_write (void)
{
  return this->tryacquire ();
}

template <class ACE_LOCK> void
ACE_TSS_Write_Guard<ACE_LOCK>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
  ACE_TSS_Guard<ACE_LOCK>::dump ();
#endif /* ACE_HAS_DUMP */
}

template <class ACE_LOCK>
ACE_TSS_Read_Guard<ACE_LOCK>::ACE_TSS_Read_Guard (ACE_LOCK &lock, bool block)
{
  this->init_key ();
  Guard_Type *guard = 0;
  ACE_NEW (guard,
           Read_Guard_Type (lock, block));
#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter;
  ACE_NEW (tss_adapter,
           ACE_TSS_Adapter ((void *)guard,
                            ACE_TSS_Guard<ACE_LOCK>::cleanup));
  ACE_Thread::setspecific (this->key_,
                           (void *) tss_adapter);
#else
  ACE_Thread::setspecific (this->key_,
                           (void *) guard);
#endif /* ACE_HAS_THR_C_DEST */
}

template <class ACE_LOCK> int
ACE_TSS_Read_Guard<ACE_LOCK>::acquire (void)
{
  Read_Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Read_Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Read_Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->acquire_read ();
}

template <class ACE_LOCK> int
ACE_TSS_Read_Guard<ACE_LOCK>::tryacquire (void)
{
  Read_Guard_Type *guard = 0;

#if defined (ACE_HAS_THR_C_DEST)
  ACE_TSS_Adapter *tss_adapter = 0;
  void *temp = tss_adapter; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  tss_adapter = static_cast <ACE_TSS_Adapter *> (temp);
  guard = static_cast <Read_Guard_Type *> (tss_adapter->ts_obj_);
#else
  void *temp = guard; // Need this temp to keep G++ from complaining.
  ACE_Thread::getspecific (this->key_, &temp);
  guard = static_cast <Read_Guard_Type *> (temp);
#endif /* ACE_HAS_THR_C_DEST */

  return guard->tryacquire_read ();
}

template <class ACE_LOCK> int
ACE_TSS_Read_Guard<ACE_LOCK>::acquire_read (void)
{
  return this->acquire ();
}

template <class ACE_LOCK> int
ACE_TSS_Read_Guard<ACE_LOCK>::tryacquire_read (void)
{
  return this->tryacquire ();
}

template <class ACE_LOCK> void
ACE_TSS_Read_Guard<ACE_LOCK>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
  ACE_TSS_Guard<ACE_LOCK>::dump ();
#endif /* ACE_HAS_DUMP */
}

#endif /* defined (ACE_HAS_THREADS) && (defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) || defined (ACE_HAS_TSS_EMULATION)) */

ACE_END_VERSIONED_NAMESPACE_DECL

#endif /* ACE_TSS_T_CPP */


text:
<!-- .slide: data-background="img/background.svg" -->
# Getting Git

Homebrew:

``` bash
$ brew update
$ brew install git
```

Debian-based:

``` bash
$ sudo apt-get install git
```

Otherwise: http://git-scm.com/download/


text:
package fi.seco.rdfio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.jena.iri.IRI;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.RiotReader;
import org.apache.jena.riot.lang.LabelToNode;
import org.apache.jena.riot.lang.LangNTuple;
import org.apache.jena.riot.lang.LangRIOT;
import org.apache.jena.riot.system.ErrorHandlerFactory;
import org.apache.jena.riot.system.ParserProfileBase;
import org.apache.jena.riot.system.PrefixMap;
import org.apache.jena.riot.system.PrefixMapStd;
import org.apache.jena.riot.system.StreamRDFBase;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.RDFParser.DatatypeHandling;
import org.openrdf.rio.RDFParserRegistry;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.RDFHandlerBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.hpl.jena.graph.Triple;

import fi.seco.openrdf.IllegalURICorrectingValueFactory;
import fi.seco.openrdf.RDFFormats;
import fi.seco.rdfobject.IQuad;
import fi.seco.rdfobject.IQuadVisitor;
import fi.seco.rdfobject.IRDFObject;
import fi.seco.rdfobject.ITriple;
import fi.seco.rdfobject.ITripleVisitor;
import fi.seco.rdfobject.URIResourceRDFObject;
import fi.seco.rdfobject.jena.JenaRDFObjectUtil;
import fi.seco.rdfobject.model.IRDFObjectQuadModel;
import fi.seco.rdfobject.model.IRDFObjectTripleModel;
import fi.seco.rdfobject.openrdf.OpenRDFRDFObjectUtil;

/**
 * An utility class for reading RDF. Uses efficient streaming parsers where
 * possible. Combines readers from Sesame and Jena with custom readers for the
 * Freebase dump format and Sindice DE tar format. Can read at least RDF/XML,
 * turtle, N3, n-triples, n-quads, trix, trig, rdf-json, binary, Freebase dump
 * and Sindice DE tar. Also supports gzip and bzip2 compressed sources.
 *
 * @author jiemakel
 *
 */
public class RDFReader {

	private static final Logger log = LoggerFactory.getLogger(RDFReader.class);

	static {
		RDFParserRegistry.getInstance(); // for initialization of formats;
	}

	/**
	 * A handler for streaming RDF quads and metadata
	 *
	 * @author jiemakel
	 *
	 */
	public interface IRDFHandler extends IQuadVisitor {
		/**
		 * A namespace definition encountered while processing RDF
		 *
		 * @param prefix
		 *            the prefix for the namespace
		 * @param ns
		 *            the namespace for the prefix
		 */
		public void setNameSpace(String prefix, String ns);

		public void setBaseIRI(String baseIRI);

		/**
		 * A comment encountered while processing RDF
		 *
		 * @param comment
		 *            the comment
		 */
		public void comment(String comment);

	}

	static RDFFormat getFormat(String url) {
		return RDFFormat.forFileName(url);
	}

	static Lang getLang(String url) {
		return RDFLanguages.filenameToLang(url);
	}

	static InputStream getInputStreamFromURL(String s) {
		try {
			if (s.endsWith(".xz")) return new XZCompressorInputStream(new URL(s).openStream());
			if (s.endsWith(".gz")) return new GZIPInputStream(new URL(s).openStream());
			if (s.endsWith(".bz2"))
				return new BZip2CompressorInputStream(new URL(s).openStream());
			else return new URL(s).openStream();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Check whether the format of the source url is a quad format, as
	 * determined by the extension
	 *
	 * @param url
	 *            the file to check
	 * @return true if the url's extension indicates a quad format
	 */
	public static boolean isQuads(String url) {
		RDFFormat f = getFormat(url);
		if (f != null) return f.supportsContexts();
		return false;
	}

	/**
	 * Check whether the format of the source url is something that this reader
	 * can parse, as determined by the extension.
	 *
	 * @param url
	 *            the file to check
	 * @return true if this reader can parse the file format
	 */
	public static boolean canRead(String url) {
		if (getFormat(url) != null) return true;
		return false;
	}

	/**
	 * Parse a file, streaming quads and metadata to an RDF handler
	 *
	 * @param url
	 *            the location of the file to read
	 * @param handler
	 *            the RDF handler to pass quads and metadata to
	 * @throws IOException
	 * @throws RDFHandlerException
	 * @throws RDFParseException
	 */
	public static void read(String url, final IRDFHandler handler) throws IOException, RDFParseException, RDFHandlerException {
		read(getInputStreamFromURL(url), getFormat(url), new URIResourceRDFObject(url), url, handler);
	}

	public static void read(InputStream is, RDFFormat type, final IRDFObject dg, String baseURI,
			final IRDFHandler handler) throws IOException, RDFParseException, RDFHandlerException {
		Lang lang = RDFLanguages.nameToLang(type.getName());
		if (lang != null && !RDFLanguages.RDFXML.equals(lang)) {// openrdf parsers throw a fit if ttl lname starts with a number. RIOT seems faster also on at least NTRIPLES. But RIOT's RDF/XML parser is too strict
			LangRIOT parser = RiotReader.createParser(is, lang, baseURI, new StreamRDFBase() {

				@Override
				public void triple(Triple t) {
					handler.visit(new fi.seco.rdfobject.Quad(JenaRDFObjectUtil.getRDFObjectForNode(t.getSubject()), JenaRDFObjectUtil.getRDFObjectForNode(t.getPredicate()), JenaRDFObjectUtil.getRDFObjectForNode(t.getObject()), dg));
				}

				@Override
				public void prefix(String prefix, String iri) {
					handler.setNameSpace(prefix, iri);
				}

				@Override
				public void base(String iri) {
					handler.setBaseIRI(iri);
				}

			});
			if (parser instanceof LangNTuple<?>) ((LangNTuple<?>) parser).setSkipOnBadTerm(true);
			parser.setProfile(new ParserProfileBase(parser.getProfile().getPrologue(), ErrorHandlerFactory.errorHandlerWarn, LabelToNode.createUseLabelAsGiven()));
			parser.getProfile().getPrologue().setPrefixMapping(new PrefixMapStd(parser.getProfile().getPrologue().getPrefixMap()) {
				@Override
				public void add(String prefix, String iriString) {
					super.add(prefix, iriString);
					handler.setNameSpace(prefix, iriString);
				}

				@Override
				public void add(String prefix, IRI iri) {
					super.add(prefix, iri);
					handler.setNameSpace(prefix, iri.toString());
				}

				@Override
				public void putAll(PrefixMap pmap) {
					super.putAll(pmap);
					for (Map.Entry<String, IRI> e : pmap.getMapping().entrySet())
						handler.setNameSpace(e.getKey(), e.getValue().toString());
				}
			});
			parser.parse();
		} else if (RDFFormats.SINDICE_DE_TAR.equals(type))
			SindiceDETarParser.parse(is, handler);
		else if (RDFFormats.FREEBASE_QUADS.equals(type))
			FreebaseParser.transformData(new BufferedReader(new InputStreamReader(is)), new ITripleVisitor() {

				@Override
				public void visit(ITriple t) {
					handler.visit(new fi.seco.rdfobject.Quad(t.getSubject(), t.getProperty(), t.getObject(), dg));
				}

			});
		else {
			RDFParser p = Rio.createParser(type);
			p.setStopAtFirstError(false);
			p.setVerifyData(false);
			p.setValueFactory(IllegalURICorrectingValueFactory.instance);
			p.setDatatypeHandling(DatatypeHandling.IGNORE);
			if (type.supportsContexts())
				p.setRDFHandler(new RDFHandlerBase() {
					@Override
					public void handleNamespace(String prefix, String uri) {
						if ("".equals(prefix))
							handler.setBaseIRI(uri);
						else handler.setNameSpace(prefix, uri);
					}

					@Override
					public void handleStatement(Statement st) {
						handler.visit(OpenRDFRDFObjectUtil.getQuadForStatement(st));
					}

					@Override
					public void handleComment(String comment) {
						handler.comment(comment);
					}
				});
			else p.setRDFHandler(new RDFHandlerBase() {
				@Override
				public void handleNamespace(String prefix, String uri) {
					if ("".equals(prefix))
						handler.setBaseIRI(uri);
					else handler.setNameSpace(prefix, uri);
				}

				@Override
				public void handleStatement(Statement st) {
					handler.visit(new fi.seco.rdfobject.Quad(OpenRDFRDFObjectUtil.getRDFObjectForValue(st.getSubject()), OpenRDFRDFObjectUtil.getRDFObjectForValue(st.getPredicate()), OpenRDFRDFObjectUtil.getRDFObjectForValue(st.getObject()), dg));
				}

				@Override
				public void handleComment(String comment) {
					handler.comment(comment);
				}
			});
			p.parse(new InputStreamReader(is, "UTF-8"), baseURI);
		}
	}

	public static IRDFHandler getInserter(final IRDFObjectQuadModel m) {
		return new IRDFHandler() {

			@Override
			public void visit(IQuad q) {
				m.addQuad(q);
			}

			@Override
			public void setNameSpace(String prefix, String ns) {
				m.getPrefixMap().put(prefix, ns);
			}

			@Override
			public void comment(String comment) {

			}

			@Override
			public void setBaseIRI(String baseIRI) {}

		};
	}

	public static IRDFHandler getInserter(final IRDFObjectTripleModel m) {
		return new IRDFHandler() {

			@Override
			public void visit(IQuad q) {
				m.addTriple(q);
			}

			@Override
			public void setNameSpace(String prefix, String ns) {
				m.getPrefixMap().put(prefix, ns);
			}

			@Override
			public void comment(String comment) {

			}

			@Override
			public void setBaseIRI(String baseIRI) {}

		};
	}

}


text: {{ uld.uld_compatibility_group }}


text:
* Loosen dependencies

# 0.0.5

* Use `broccoli-filter` instead of `broccoli.Filter`

# 0.0.4

* Do not require dependency-injecting broccoli

# 0.0.3

* Expose new functional syntax

# 0.0.2

* Use new `Filter` architecture

# 0.0.1

* Initial release


text:
package org.apache.camel.component.hazelcast.map;

import com.hazelcast.core.HazelcastInstance;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.hazelcast.HazelcastComponent;
import org.apache.camel.component.hazelcast.HazelcastDefaultEndpoint;

public class HazelcastMapEndpoint extends HazelcastDefaultEndpoint {

    public HazelcastMapEndpoint(HazelcastInstance hazelcastInstance, String uri, String cacheName, HazelcastComponent component) {
        super(hazelcastInstance, uri, component, cacheName);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        HazelcastMapConsumer answer = new HazelcastMapConsumer(hazelcastInstance, this, processor, cacheName);
        configureConsumer(answer);
        return answer;
    }

    public Producer createProducer() throws Exception {
        return new HazelcastMapProducer(hazelcastInstance, this, cacheName);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>protobuf</groupId>
  <artifactId>protobuf-codec-core</artifactId>
  <versioning>
    <release>1.2</release>
    <versions>
      <version>1.1</version>
      <version>1.0</version>
      <version>1.2</version>
    </versions>
    <lastUpdated>20110820142213</lastUpdated>
  </versioning>
</metadata>


text:
<?php

namespace yii\jui\datepicker\tests;

use yii\jui\datepicker\FormatConverter;
use yii\phpunit\TestCase;

class FormatConverterTest extends TestCase
{

    /**
     * @return array
     */
    public function formatsDataProvider()
    {
        return [
            ['php:Y-m-d', 'yyyy-MM-dd', 'yy-mm-dd'], // 1952-12-13
            ['php:m/d/y', 'MM/dd/yy', 'mm/dd/y'], // 12/13/52
            ['php:M. d, Y', 'MMM. dd, yyyy', 'M. dd, yy'], // Jan. 12, 1952
            ['php:F d, Y', 'MMMM dd, yyyy', 'MM dd, yy'] // January 12, 1952
        ];
    }

    /**
     * @param string $phpFormat
     * @param string $icuFormat
     * @param string $juiFormat
     * @dataProvider formatsDataProvider
     */
    public function testConvertDatePhpOrIcuToJui($phpFormat, $icuFormat, $juiFormat)
    {
        $this->assertEquals($juiFormat, FormatConverter::convertDatePhpOrIcuToJui($phpFormat));
        $this->assertEquals($juiFormat, FormatConverter::convertDatePhpOrIcuToJui($icuFormat));
    }
}


text:
require "rails_helper"

RSpec.feature "Custody Suite Officers viewing defence request" do
  specify "shows all required fields" do
    cso_user = create :cso_user
    defence_request = create(
      :defence_request,
      :accepted,
      :appropriate_adult,
      :interview_start_time,
      :unfit_for_interview,
      :with_detainee_address,
      :with_dscc_number,
      :with_interpreter_required,
      :with_investigating_officer,
      custody_suite_uid: cso_user.organisation["uid"]
    )

    login_with cso_user
    within "tr#defence_request_#{defence_request.id} td.actions" do
      find("a").click
    end

    expect(page).to have_content defence_request.dscc_number
  end

  specify "can follow a link back to the dashboard" do
    cso_user = create :cso_user
    defence_request = create :defence_request, :queued, custody_suite_uid: cso_user.organisation["uid"]

    login_with cso_user
    within "tr#defence_request_#{defence_request.id} td.actions" do
      find("a").click
    end

    click_link "< Back to requests"
    expect(current_path).to eq("/custody_suite/dashboard")
  end

  specify "It sets the first tab as active", js: true do
    cso_user = create :cso_user
    defence_request = create :defence_request, :queued, custody_suite_uid: cso_user.organisation["uid"]

    login_with cso_user
    within "tr#defence_request_#{defence_request.id} td.actions" do
      find("a").click
    end

    visit custody_suite_defence_request_path(defence_request, tab: "googly woogly wooo")
    expect(find(:css, ".tabs").first("li")["class"]).to include "is-active"
  end
end


text:
<!--?xml version="1.0" encoding="utf-8"?-->
<request method="estimate.get">
  <estimate_id>21</estimate_id>
</request>


text:
import { Server, ServerOptionsCache } from "hapi";
import * as catbox from "catbox";

const server = new Server({
    port: 8000,
});

const catboxOptions: ServerOptionsCache = {
    segment: 'countries',
    expiresIn: 60 * 60 * 1000
};
const cache: catbox.Policy = server.cache(catboxOptions);
cache.set('norway', 'oslo', 10 * 1000, () => {});

const value = cache.get('norway', () => {});
console.log("Value: " + value);

server.start();

server.events.on('start', () => {
    console.log('Server started at: ' + server.info.uri);
});


text:
#include <xboot.h>
#include <command/command.h>

static void usage(void)
{
	printf("usage:\r\n");
	printf("    delay [millisecond]\r\n");
}

static int do_delay(int argc, char ** argv)
{
	u32_t ms = 1000;

	if(argc > 1)
		ms = strtoul(argv[1], NULL, 0);
	mdelay(ms);

	return 0;
}

static struct command_t cmd_delay = {
	.name	= "delay",
	.desc	= "delay for a specified time",
	.usage	= usage,
	.exec	= do_delay,
};

static __init void delay_cmd_init(void)
{
	register_command(&cmd_delay);
}

static __exit void delay_cmd_exit(void)
{
	unregister_command(&cmd_delay);
}

command_initcall(delay_cmd_init);
command_exitcall(delay_cmd_exit);


text:
Main module, it creates the `VgAPI` and contains some required components and directives like `VgPlayer` and `VgMedia`.

Import definition:

```typescript
...
import { VgCoreModule } from 'videogular2/core';

@NgModule({
    ...
    imports: [
        ...
        VgCoreModule
    ],
    ...
})
export class AppModule {
}
```


text:
self.addEventListener('message',function(e){
  if (e.data === "ping"){
    self.postMessage("pong");
  }
});


text:
================================================================================
OvfParseDescriptorParams
================================================================================

.. describe:: Parameter to

    :py:meth:`~pyvisdk.do.parse_descriptor.ParseDescriptor`

.. describe:: Since

    vSphere API 4.0

.. describe:: Extends

    :py:class:`~pyvisdk.mo.ovf_manager_common_params.OvfManagerCommonParams`

.. class:: pyvisdk.do.ovf_parse_descriptor_params.OvfParseDescriptorParams


text:
package org.carrot2.source.etools;

@SuppressWarnings("serial")
public class IpBannedException extends Exception
{
    public IpBannedException(Exception cause)
    {
        super(cause);
    }
}


text:
var ModalDispacher = require('../sqlite3/ModalDispacher.js'),
    ResponseBuilder = require('../util/ResponseBuilder.js');

var RouterPost = {
    recive: function(req, res) {
        var url = req.url.toLowerCase().split('?')[0];
        switch (url) {
            case '/unlockdb':
                this.unlockDb(req, res);
                break;
            case '/getdatabaseinfo':
                this.getDatabaseInfo(req, res);
                break;
            case '/createtable':
                this.createTable(req, res);
                break;
            case '/droptable':
                this.dropTable(req, res);
                break;
            case '/uploadimage':
                this.uploadImage(req, res);
                break;
            default:
                break;
        }
    },

    unlockDb: function(req, res) {
        var TableLol = ModalDispacher.TableLol;
        TableLol.findAll().then(function(result) {
            if(result && result.length > 0) {
                if(result[0].lolname == req.body.secretWord) {
                    ResponseBuilder.status(200).entity('SUCCESS').end(res);
                } else {
                    res.sendStatus(400);
                }
            }
        }, function(err) {
            console.log(err);
            res.sendStatus(500);
        });
    },

    getDatabaseInfo: function(req, res) {
        var DatabaseBuilder = ModalDispacher.DatabaseBuilder;
        var type = req.body.postType;
        if(type == 1) {
            DatabaseBuilder.showTables().then(function(result) {
                ResponseBuilder.status(200).entity(result).end(res);
            }, function(err) {
                console.log(err);
                res.sendStatus(500);
            });
        }
        if(type == 2) {
            DatabaseBuilder.showTableSchemas(req.body.tableName).then(function(result) {
                ResponseBuilder.status(200).entity(result).end(res);
            }, function(err) {
                console.log(err);
                res.sendStatus(500);
            });
        }
    },

    createTable: function(req, res) {
        var DatabaseBuilder = ModalDispacher.DatabaseBuilder;
        var tableName = req.query.tableName;
        var params = {
            tableName: tableName,
            colums: req.body
        }
        DatabaseBuilder.createTable(params).then(function(result) {
            ResponseBuilder.status(200).entity({msg: 'Build Success'}).end(res);
        }, function(err) {
            if(err.errno == 1) {
                res.sendStatus(501);
            }
        });
    },

    dropTable: function(req, res) {
        var DatabaseBuilder = ModalDispacher.DatabaseBuilder;
        var tableName = req.query.tableName;
        DatabaseBuilder.dropTable(tableName).then(function(result) {
            ResponseBuilder.status(200).entity({msg: 'Drop Success'}).end(res);
        }, function(err) {
            res.sendStatus(500);
        });
    },

    uploadImage: function(req, res) {
        var TableImageOrigin = ModalDispacher.TableImageOrigin;
        var imageFile = req.body;
        TableImageOrigin.insert(imageFile).then(function(result) {
            ResponseBuilder.status(200).entity({msg: 'Upload Success'}).end(res);
        }, function(err) {
            res.sendStatus(500);
        });
    }
}

module.exports = RouterPost;


text:
// Setting Panel Helper
//
// Douglas Thrift
//
// SettingPanelHelper.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Windows.Controls;

public static class SettingPanelHelper
{
    public static void DoExecutableBrowseClick(AutoCompleteBox executableBox)
    {
        var dialog = new System.Windows.Forms.OpenFileDialog();

        dialog.AutoUpgradeEnabled = true;

        string pathext = Environment.GetEnvironmentVariable("PathExt");

        if (pathext == null)
            pathext = ".com;.exe;.bat;.cmd";

        pathext = string.Join(";", pathext.Split(';').Select(extension => "*" + extension.ToLowerInvariant()));

        dialog.Filter = string.Format("Executable files ({0})|{0}|All files (*.*)|*.*", pathext);
        dialog.FilterIndex = 1;
        dialog.RestoreDirectory = true;

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            executableBox.Text = dialog.FileName;
    }

    public static void DoExecutableBoxPopulating(AutoCompleteBox executableBox)
    {
        try
        {
            string directoryName = Path.GetDirectoryName(executableBox.Text);
            if (directoryName == null)
                directoryName = Path.GetPathRoot(executableBox.Text);

            if (Directory.Exists(directoryName))
            {
                var directoryInfo = new DirectoryInfo(directoryName.EndsWith(":") ? directoryName + @"\" : directoryName);
                executableBox.ItemsSource = directoryInfo.EnumerateFileSystemInfos().Where(info => !info.Attributes.HasFlag(FileAttributes.Hidden)).Select(info => info.FullName);
                executableBox.PopulateComplete();
            }
        }
        catch (ArgumentException exception)
        {
            Debug.WriteLine("{0}: {1}", exception, exception.Message);
        }
        catch (PathTooLongException exception)
        {
            Debug.WriteLine("{0}: {1}", exception, exception.Message);
        }
        catch (SecurityException exception)
        {
            Debug.WriteLine("{0}: {1}", exception, exception.Message);
        }
    }

    public static void DoDirectoryBrowseClick(AutoCompleteBox directoryBox)
    {
        var dialog = new System.Windows.Forms.FolderBrowserDialog();

        dialog.ShowNewFolderButton = false;

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            directoryBox.Text = dialog.SelectedPath;
    }

    public static void DoDirectoryBoxPopulating(AutoCompleteBox directoryBox)
    {
        try
        {
            string directoryName = Path.GetDirectoryName(directoryBox.Text);
            if (directoryName == null)
                directoryName = Path.GetPathRoot(directoryBox.Text);

            if (Directory.Exists(directoryName))
            {
                var directoryInfo = new DirectoryInfo(directoryName.EndsWith(":") ? directoryName + @"\" : directoryName);
                directoryBox.ItemsSource = directoryInfo.EnumerateDirectories().Where(info => !info.Attributes.HasFlag(FileAttributes.Hidden)).Select(info => info.FullName);
                directoryBox.PopulateComplete();
            }
        }
        catch (ArgumentException exception)
        {
            Debug.WriteLine("{0}: {1}", exception, exception.Message);
        }
        catch (PathTooLongException exception)
        {
            Debug.WriteLine("{0}: {1}", exception, exception.Message);
        }
        catch (SecurityException exception)
        {
            Debug.WriteLine("{0}: {1}", exception, exception.Message);
        }
    }
}