text:
<?php

/**
 * Show an error message.....
 *
 * It is shown when an error occurs, and should show at least a back
 * button and $context['error_message'].
 */
function template_fatal_error()
{
	global $context, $txt;

	echo '

', $context['error_title'], '

', $context['error_message'], '

		', $txt['back'], '

';
}

/**
 * Shows the forum error log in all its detail
 * Supports filtering for viewing all errors of a 'type'
 */
function template_error_log()
{
	global $context, $settings, $scripturl, $txt;

	echo '
		<form class="generic_list_wrapper" action="', $scripturl, '?action=admin;area=logs;sa=errorlog', $context['sort_direction'] === 'down' ? ';desc' : '', ';start=', $context['start'], $context['has_filter'] ? $context['$page_filter'] : '', '" method="post" accept-charset="UTF-8">

				 ', $txt['errlog'], '

';

	template_pagesection();

	echo '

					<input type="submit" name="removeSelection" value="' . $txt['remove_selection'] . '" onclick="return confirm(\'' . $txt['remove_selection_confirm'] . '\');" />
					<input type="submit" name="delall" value="', $context['has_filter'] ? $txt['remove_filtered_results'] : $txt['remove_all'], '" onclick="return confirm(\'', $context['has_filter'] ? $txt['remove_filtered_results_confirm'] : $txt['sure_about_errorlog_remove'], '\');" />

';

	echo '

						  ', $txt['apply_filter_of_type'], ':';

	$error_types = array();
	foreach ($context['error_types'] as $type => $details)
	{
		$error_types[] = ($details['is_selected'] ? ' ' : '') . '' . $details['label'] . '';
	}

	echo '
						', implode(' | ', $error_types), '

';

	if ($context['has_filter'])
	{
		echo '

						  ', $txt['applying_filter'], ': ', $context['filter']['entity'], ' ', $context['filter']['value']['html'], '  [', $txt['clear_filter'], ']

';
	}

	echo '

						', $txt['check_all'], '
						<input type="checkbox" id="check_all1" onclick="invertAll(this, this.form, \'delete[]\'); this.form.check_all2.checked = this.checked;" />

';

	// No errors, then show a message
	if (count($context['errors']) == 0)
	{
		echo '

					', $txt['errlog_no_entries'], '

';
	}

	// We have some errors, show them...
	foreach ($context['errors'] as $error)
	{
		echo '

							', $txt['error_type'], ': ', $error['error_type']['name'], '

						', $error['message']['html'], '

							', $error['url']['html'], '

';

		if (!empty($error['file']))
		{
			echo '

							', $txt['file'], ': ', $error['file']['link'], '

							', $txt['line'], ': ', $error['file']['line'], '

';
		}

		echo '

							', $error['member']['link'], '

							', $error['time'], '

							', $error['member']['ip'], '

';

		if ($error['member']['session'] !== '')
		{
			echo '

							', $error['member']['session'], '

';
		}

		echo '

						<input type="checkbox" name="delete[]" value="', $error['id'], '" />

';
	}

	echo '

						', $txt['check_all'], '
						<input type="checkbox" id="check_all2" onclick="invertAll(this, this.form, \'delete[]\'); this.form.check_all1.checked = this.checked;" />

';

	template_pagesection();

	echo '

					<input type="submit" name="removeSelection" value="' . $txt['remove_selection'] . '" onclick="return confirm(\'' . $txt['remove_selection_confirm'] . '\');" />
					<input type="submit" name="delall" value="', $context['has_filter'] ? $txt['remove_filtered_results'] : $txt['remove_all'], '" onclick="return confirm(\'', $context['has_filter'] ? $txt['remove_filtered_results_confirm'] : $txt['sure_about_errorlog_remove'], '\');" />';

	if ($context['sort_direction'] === 'down')
	{
		echo '
					<input type="hidden" name="desc" value="1" />';
	}

	echo '
					<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
					<input type="hidden" name="', $context['admin-el_token_var'], '" value="', $context['admin-el_token'], '" />

		</form>';
}

/**
 * Shows the subsection of a file where an error occurred
 */
function template_show_file()
{
	global $context;

	echo '<!DOCTYPE html>

		<title>', $context['file_data']['file'], '</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

';

	foreach ($context['file_data']['contents'] as $line => $content)
	{
		printf(
			'%d: ',
			$line
		);

		echo $content, "\n";
	}

	echo '

';
}

/**
 * When an attachment fails to upload, this template will show
 * all the issues to the user
 */
function template_attachment_errors()
{
	global $context, $txt;

	echo '

', $txt['attach_error_title'], '

';

	foreach ($context['attachment_error_keys'] as $key)
	{
		template_show_error($key);
	}

	echo '

';
}


text:
require 'taiko'
require 'keyboard'
require 'view'
require 'scene'

rgss_main { Scene.run }

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Displays details about an order
 * @todo
 */

if( !Auth::isAuthenticated() ) {
    Util::getTemplate( 'login.php' );
    return;
}

//force a search query
if( !isset( $_REQUEST['q'] ) || empty( $_REQUEST['q'] ) ) {
    Util::getTemplate( 'index.php' );
    return;
}

//get order details
if( isset( $_REQUEST['entry'] ) )
    $entry = ApiLinks::decodeHateoasLink( $_REQUEST['entry'] );
else
    $entry = LSM_API_ENDPOINT . "order/" . $_REQUEST['q'] ;

$lsm = new LsmCurl;
$lsm->setEndpoint( $entry );
$lsm->useGet();
$lsm->sendRequest();

$order = $lsm->getResponseContent();
if( !$order || (int) $lsm->getResponseStatus() != 200 ) {
    Util::getTemplate( '500.php' );
    return;
}

//get product details
$productEntry = LSM_API_ENDPOINT . "product-by-id/" . $order->productID;

$productLsm = new LsmCurl;
$productLsm->setEndpoint( $productEntry );
$productLsm->useGet();
$productLsm->sendRequest();
$product = $productLsm->getResponseContent();

if( !$product || (int) $productLsm->getResponseStatus() != 200 ) {
    Util::getTemplate( '500.php' );
    return;
}

Util::getHeader();
if( DEBUG_API_CALLS ) {
    echo "
"; var_dump( $order ); echo"
";
    echo "
"; var_dump( $product ); echo"
";
}

//get the order status
switch( $order->orderStatusCode ) {
    case 0:
        $percent = 100;
        $statusClass = "warning";
        $orderStatus = "Cancelled";
        break;

    case 1:
    default:
        $percent = 40;
        $statusClass = "primary";
        $orderStatus = "In Progress";
        break;

    case 2:
        $percent = 80;
        $statusClass = "primary";
        $orderStatus = "Shipped";
        break;

    case 3:
        $percent = 100;
        $statusClass = "success";
        $orderStatus = "Delivered";
        break;
}

?>

Order Details Order Number <?=$order->orderID?>

            <div class="progress-bar progress-bar-<?=$statusClass?>" role="progressbar" style="width: <?=$percent?>%;">
                <?=$orderStatus?>

<a href="<?=SITE_URI?>product/detail/q/<?=$product->productID?>"><?=$product->productName?> $<?=money_format( '%i', $product->price );?>

<?=$product->description?>

Ordered: <?=date("Y/d/m H:i:s", $order->datePurchased);?>

        <?php
        if( $order->dateRefunded ):
            ?>

Refunded: <?=date("Y/d/m H:i:s", $order->dateRefunded);?>

            <?php
        endif;

        if( $orderStatus == "Shipped" ):
            ?>

Tracking Number: <?=$order->trackingNumber?>

            <?php
        endif;
        ?>

        <?php
        echo ApiLinks::linksToHtml( $order );
        ?>

<?php
Util::getFooter();


text:
'''This is a default configuration file, that should be imported in the
user's configuration.
'''

import os
import imp
import sys
from cytoplasm import controllers
from cytoplasm.temp import site

# Specify the build directory, where the built site will be copied to
build_dir = "_build"

from .interpreters import SaveReturned
# A dictionary where the key of a suffix is the function that should handle
# that file. The function is given two arguments, the filename and where that
# file should be put after it's finished.
interpreters = {}

# This is a decorator that can be prepended to an interpreter function, so
# that you don't need to have the manually add each to the interpreters
# dictionary.
def Interpreter(*keys):
    # You can have as many suffixes as you want.
    def Add(fn):
        for suffix in keys:
            interpreters[suffix] = fn
    return Add

# An interpreter for mako, which will be pretty essential both for "static"
# files and for controllers to use.
import mako.lookup
import mako.template
# Mako should look for templates to include in the current directory.
# This should let you include things like "_templates/site.mako"
mako_lookup = mako.lookup.TemplateLookup(directories=[site.source])

# Mako doesn't come with an easy built-in way to save the output to a
# certain file; this decorator does that.
@Interpreter("mako")
@SaveReturned
def mako_interpreter(file, **kwargs):
    # pass kwargs to the mako template
    page = mako.template.Template(file.read(), lookup=mako_lookup,
            input_encoding='utf-8')
    # this is dumb but it's the only way I can make it work.
    if sys.version_info.major == 2:
        # if it's python 2, use .encode('utf-8', 'replace')
        return page.render_unicode(**kwargs).encode('utf-8', 'replace')
    elif sys.version_info.major == 3:
        # otherwise, just render it...
        return page.render_unicode(**kwargs)

# This is a list of controllers to be used.
# Each item should be a 2-tuple containing:
# * The controller's module's name; i.e, the thing in _controllers
# * The list of arguments to use when instantiating the controller class;
#   usually at least the controller's source directory and where files
#   should be output to, in the build directory.
controllers = []

# This is a list of folders to be watched for file modifications to trigger
# a rebuild of the site when running cytoplasm serve -r
watch_dirs = []


text:
package io.flutter.sdk;

import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

@NonNls
public class FlutterSdkChannel {

  public enum ID {

    // Do not change this order. An unknown branch is assumed to be off master.
    STABLE("stable"), BETA("beta"), DEV("dev"), MASTER("master"), UNKNOWN("unknown");

    private final String name;

    ID(String name) {
      this.name = name;
    }

    public String toString() {
      return name;
    }

    @NotNull
    public static ID fromText(String name) {
      switch (name) {
        case "master":
          return MASTER;
        case "dev":
          return DEV;
        case "beta":
          return BETA;
        case "stable":
          return STABLE;
        default:
          return UNKNOWN;
      }
    }
  }

  @NotNull
  private final ID channel;

  @NotNull
  public static FlutterSdkChannel fromText(@NotNull String text) {
    return new FlutterSdkChannel(ID.fromText(text));
  }

  private FlutterSdkChannel(@NotNull ID channel) {
    this.channel = channel;
  }

  @NotNull
  public ID getID() {
    return channel;
  }

  public String toString() {
    return "channel " + channel.toString();
  }

  @NotNull
  public static String parseChannel(@NotNull String text) {
    String[] lines = text.split("\n"); // TODO(messick) check windows
    for (String line : lines) {
      if (line.startsWith("*")) {
        return line.substring(2);
      }
    }
    return "unknown";
  }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42.c
Label Definition File: CWE675_Duplicate_Operations_on_Resource__w32CreateFile.label.xml
Template File: sources-sinks-42.tmpl.c
*/
/*
 * @description
 * CWE: 675 Duplicate Operations on Resource
 * BadSource:  Open and close a file using CreateFile() and CloseHandle()
 * GoodSource: Open a file using CreateFile()
 * Sinks:
 *    GoodSink: Do nothing
 *    BadSink : Close the file
 * Flow Variant: 42 Data flow: data returned from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

#include <windows.h>

#ifndef OMITBAD

static HANDLE badSource(HANDLE data)
{
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    /* POTENTIAL FLAW: Close the file in the source */
    CloseHandle(data);
    return data;
}

void CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad()
{
    HANDLE data;
    data = INVALID_HANDLE_VALUE; /* Initialize data */
    data = badSource(data);
    /* POTENTIAL FLAW: Close the file in the sink (it may have been closed in the Source) */
    CloseHandle(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static HANDLE goodG2BSource(HANDLE data)
{
    /* FIX: Open, but do not close the file in the source */
    data = CreateFile("GoodSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    return data;
}

static void goodG2B()
{
    HANDLE data;
    data = INVALID_HANDLE_VALUE; /* Initialize data */
    data = goodG2BSource(data);
    /* POTENTIAL FLAW: Close the file in the sink (it may have been closed in the Source) */
    CloseHandle(data);
}

/* goodB2G uses the BadSource with the GoodSink */
static HANDLE goodB2GSource(HANDLE data)
{
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    /* POTENTIAL FLAW: Close the file in the source */
    CloseHandle(data);
    return data;
}

static void goodB2G()
{
    HANDLE data;
    data = INVALID_HANDLE_VALUE; /* Initialize data */
    data = goodB2GSource(data);
    /* Do nothing */
    /* FIX: Don't close the file in the sink */
    ; /* empty statement needed for some flow variants */
}

void CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good()
{
    goodB2G();
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package XrefMapper::CoordinateMapper;

# $Id$

# This is a set of subroutines used for creating Xrefs based on
# coordinate overlaps.

use strict;
use warnings;

use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Mapper::RangeRegistry;

use DBI qw( :sql_types );

use Carp;
use IO::File;
use File::Spec::Functions;

use base qw( Exporter XrefMapper::BasicMapper);

our @EXPORT = qw( run_coordinatemapping );

our $coding_weight = 2;
our $ens_weight    = 3;

our $transcript_score_threshold = 0.75;

my $verbose = 0;

sub new {
  my($class, $mapper) = @_;

  my $self ={};
  bless $self,$class;
  $self->core($mapper->core);
  $self->xref($mapper->xref);
  $self->mapper($mapper);
  $verbose = $mapper->verbose();
  return $self;
}

sub mapper{
  my ($self, $arg) = @_;

  (defined $arg) &&
    ($self->{_mapper} = $arg );
  return $self->{_mapper};
}

sub run_coordinatemapping {
  my ( $self, $do_upload, $species_id) = @_;

  my $sth_stat = $self->xref->dbc->prepare(
                           "INSERT INTO process_status (status, date) "
                         . "VALUES('coordinate_xrefs_started',now())" );
  $sth_stat->execute();
  $sth_stat->finish();

  my $xref_db = $self->xref();
  my $core_db = $self->core();

  my $species = $core_db->species();
#  my $species_id = $self->mapper->core->species;
  $species_id = XrefMapper::BasicMapper::get_species_id_from_species_name( $xref_db, $species ) unless defined $species_id;
  if (!defined $species_id) { return; }

  # We only do coordinate mapping for mouse and human for now.
  if ( !( $species eq 'mus_musculus' || $species eq 'homo_sapiens' ) ) {
    #  if ( !( $species eq 'mus_musculus') ) {
    my $sth_stat = $self->xref->dbc->prepare(
                          "INSERT INTO process_status (status, date) "
                        . "VALUES ('coordinate_xref_finished',now())" );
    $sth_stat->execute();
    $sth_stat->finish();
    return;
  }
  print "species = $species ($species_id))\n";

  my $output_dir = $core_db->dir();

  my $xref_filename = catfile( $output_dir, 'xref_coord.txt' );
  my $object_xref_filename =
    catfile( $output_dir, 'object_xref_coord.txt' );
  my $unmapped_reason_filename =
    catfile( $output_dir, 'unmapped_reason_coord.txt' );
  my $unmapped_object_filename =
    catfile( $output_dir, 'unmapped_object_coord.txt' );

  my $xref_dbh = $xref_db->dbc()->db_handle();
  my $core_dbh = $core_db->dbc()->db_handle();

  ######################################################################
  # Figure out the last used 'xref_id', 'object_xref_id',              #
  # 'unmapped_object_id', and 'unmapped_reason_id' from the Core       #
  # database.                                                          #
  ######################################################################

  my $xref_id =
    $core_dbh->selectall_arrayref('SELECT MAX(xref_id) FROM xref')
    ->[0][0];
  my $object_xref_id = $core_dbh->selectall_arrayref(
                 'SELECT MAX(object_xref_id) FROM object_xref')->[0][0];
  my $unmapped_object_id = $core_dbh->selectall_arrayref(
         'SELECT MAX(unmapped_object_id) FROM unmapped_object')->[0][0];
  my $unmapped_reason_id = $core_dbh->selectall_arrayref(
         'SELECT MAX(unmapped_reason_id) FROM unmapped_reason')->[0][0];

  log_progress( "Last used xref_id            is %d\n", $xref_id );
  log_progress( "Last used object_xref_id     is %d\n",
                $object_xref_id );
  log_progress( "Last used unmapped_object_id is %d\n",
                $unmapped_object_id );
  log_progress( "Last used unmapped_reason_id is %d\n",
                $unmapped_reason_id );

  ######################################################################
  # Get an 'analysis_id', or discover that we need to add our analysis #
  # to the 'analyis' table later.                                      #
  ######################################################################

  my $analysis_params =
    sprintf( "weights(coding,ensembl)="
               . "%.2f,%.2f;"
               . "transcript_score_threshold=" . "%.2f",
             $coding_weight, $ens_weight, $transcript_score_threshold );

  my $analysis_sql = qq(
    SELECT  analysis_id
    FROM    analysis
    WHERE   logic_name = 'xrefcoordinatemapping'
    AND     parameters = ?
  );

  my $analysis_sth = $core_dbh->prepare($analysis_sql);
  $analysis_sth->bind_param( 1, $analysis_params, SQL_VARCHAR );

  $analysis_sth->execute();

  my $analysis_id = $analysis_sth->fetchall_arrayref()->[0][0];
  if ( !defined($analysis_id) ) {
    $analysis_id =
      $core_dbh->selectall_arrayref( "SELECT analysis_id FROM analysis "
               . "WHERE logic_name = 'xrefcoordinatemapping'" )->[0][0];

    if ( defined($analysis_id) && $do_upload ) {
      log_progress(   "Will update 'analysis' table "
                    . "with new parameter settings\n" );

      #-----------------------------------------------------------------
      # Update an existing analysis.
      #-----------------------------------------------------------------

      my $sql = qq(
        UPDATE  analysis
        SET     created = now(), parameters = ?
        WHERE   analysis_id = ?
      );

      $core_dbh->do( $sql, undef, $analysis_params, $analysis_id );

    } else {
      log_progress("Can not find analysis ID for this analysis:\n");
      log_progress("  logic_name = 'xrefcoordinatemapping'\n");
      log_progress( "  parameters = '%s'\n", $analysis_params );

      if ($do_upload) {

        #---------------------------------------------------------------
        # Store a new analysis.
        #---------------------------------------------------------------

        log_progress("A new analysis will be added\n");

        $analysis_id = $core_dbh->selectall_arrayref(
                       'SELECT MAX(analysis_id) FROM analysis')->[0][0];
        log_progress( "Last used analysis_id is %d\n", $analysis_id );

        my $sql =
            'INSERT INTO analysis '
          . 'VALUES(?, now(), ?, \N, \N, \N, ?, '
          . '\N, \N, ?, ?, \N, \N, \N)';
        my $sth = $core_dbh->prepare($sql);

        $sth->bind_param( 1, ++$analysis_id,          SQL_INTEGER );
        $sth->bind_param( 2, 'xrefcoordinatemapping', SQL_VARCHAR );
        $sth->bind_param( 3, 'xref_mapper.pl',        SQL_VARCHAR );
        $sth->bind_param( 4, $analysis_params,        SQL_VARCHAR );
        $sth->bind_param( 5, 'CoordinateMapper.pm',   SQL_VARCHAR );

        $sth->execute();
      }
    } ## end else [ if ( defined($analysis_id...
  } ## end if ( !defined($analysis_id...

  if ( defined($analysis_id) ) {
    log_progress( "Analysis ID                  is %d\n",
                  $analysis_id );
  }

  ######################################################################
  # Read and store available Xrefs from the Xref database.             #
  ######################################################################

  my %unmapped;
  my %mapped;

  my $xref_sql = qq(
    SELECT  coord_xref_id, source_id, accession
    FROM    coordinate_xref
    WHERE   species_id = ?
  );

  my $xref_sth = $xref_dbh->prepare($xref_sql);
  $xref_sth->bind_param( 1, $species_id, SQL_INTEGER );

  $xref_sth->execute();

  my $external_db_id;

  while ( my $xref = $xref_sth->fetchrow_hashref() ) {
    $external_db_id ||=
      $XrefMapper::BasicMapper::source_to_external_db{ $xref->{
        'source_id'} };
    $external_db_id ||= 11000;    # FIXME (11000 is 'UCSC')

    $unmapped{ $xref->{'coord_xref_id'} } = {
                   'external_db_id' => $external_db_id,
                   'accession'      => $xref->{'accession'},
                   'reason'         => 'No overlap',
                   'reason_full' =>
                     'No coordinate overlap with any Ensembl transcript'
    };
  }
  $xref_sth->finish();

  if(!defined($external_db_id)){
    die "External_db_id is undefined  species_id = $species_id\n";
  }

  ######################################################################
  # Do coordinate matching.                                            #
  ######################################################################

  my $core_db_adaptor =
    Bio::EnsEMBL::DBSQL::DBAdaptor->new(
                                   -host => $core_db->dbc()->host(),
                                   -port => $core_db->dbc()->port(),
                                   -user => $core_db->dbc()->username(),
                                   -pass => $core_db->dbc()->password(),
                                   -dbname => $core_db->dbc()->dbname(),
    );

  my $slice_adaptor = $core_db_adaptor->get_SliceAdaptor();
  my @chromosomes   = @{ $slice_adaptor->fetch_all('Chromosome') };

  my $sql = qq(
    SELECT    coord_xref_id, accession,
              txStart, txEnd,
              cdsStart, cdsEnd,
              exonStarts, exonEnds
    FROM      coordinate_xref
    WHERE     species_id = ?
    AND       chromosome = ? AND strand   = ?
    AND       ((txStart BETWEEN ? AND ?)        -- txStart in region
    OR         (txEnd   BETWEEN ? AND ?)        -- txEnd in region
    OR         (txStart <= ? AND txEnd >= ?))   -- region is fully contained
    ORDER BY  accession
  );

  foreach my $chromosome (@chromosomes) {
    my $chr_name = $chromosome->seq_region_name();

    log_progress( "Processing chromsome '%s'\n", $chr_name );

    my @genes = @{ $chromosome->get_all_Genes( undef, undef, 1 ) };

    log_progress( "There are %4d genes on chromosome '%s'\n",
                  scalar(@genes), $chr_name );

    while ( my $gene = shift(@genes) ) {
      my @transcripts = @{ $gene->get_all_Transcripts() };

      my %gene_result;

      foreach my $transcript ( sort { $a->start() <=> $b->start() }
                               @transcripts )
      {

        ################################################################
        # For each Ensembl transcript:                                 #
        #   1. Register all Ensembl exons in a RangeRegistry.          #
        #                                                              #
        #   2. Find all transcripts in the external database that are  #
        #      within the range of this Ensembl transcript.            #
        #                                                              #
        # For each of those external transcripts:                      #
        #   3. Calculate the overlap of the exons of the external      #
        #      transcript with the Ensembl exons using the             #
        #      overlap_size() method in the RangeRegistry.             #
        #                                                              #
        #   4. Register the external exons in their own RangeRegistry. #
        #                                                              #
        #   5. Calculate the overlap of the Ensembl exons with the     #
        #      external exons as in step 3.                            #
        #                                                              #
        #   6. Calculate the match score.                              #
        #                                                              #
        #   7. Decide whether or not to keep the match.                #
        ################################################################

        my @exons = @{ $transcript->get_all_Exons() };

        my %transcript_result;

        # '$rr1' is the RangeRegistry holding Ensembl exons for one
        # transcript at a time.
        my $rr1 = Bio::EnsEMBL::Mapper::RangeRegistry->new();

        my $coding_transcript;
        if ( defined( $transcript->translation() ) ) {
          $coding_transcript = 1;
        } else {
          $coding_transcript = 0;
        }

        foreach my $exon (@exons) {

          #-------------------------------------------------------------
          # Register each exon in the RangeRegistry.  Register both the
          # total length of the exon and the coding range of the exon.
          #-------------------------------------------------------------

          $rr1->check_and_register( 'exon', $exon->start(),
                                    $exon->end() );

          if (    $coding_transcript
               && defined( $exon->coding_region_start($transcript) )
               && defined( $exon->coding_region_end($transcript) ) )
          {
            $rr1->check_and_register(
                                'coding',
                                $exon->coding_region_start($transcript),
                                $exon->coding_region_end($transcript) );
          }
        }

        #---------------------------------------------------------------
        # Get hold of all transcripts from the external database that
        # overlaps with this Ensembl transcript.
        #---------------------------------------------------------------

        my $sth = $xref_dbh->prepare_cached($sql);
        $sth->bind_param( 1, $species_id,          SQL_INTEGER );
        $sth->bind_param( 2, $chr_name,            SQL_VARCHAR );
        $sth->bind_param( 3, $gene->strand(),      SQL_INTEGER );
        $sth->bind_param( 4, $transcript->start(), SQL_INTEGER );
        $sth->bind_param( 5, $transcript->end(),   SQL_INTEGER );
        $sth->bind_param( 6, $transcript->start(), SQL_INTEGER );
        $sth->bind_param( 7, $transcript->end(),   SQL_INTEGER );
        $sth->bind_param( 8, $transcript->start(), SQL_INTEGER );
        $sth->bind_param( 9, $transcript->end(),   SQL_INTEGER );

        $sth->execute();

        my ( $coord_xref_id, $accession, $txStart, $txEnd, $cdsStart,
             $cdsEnd, $exonStarts, $exonEnds );

        $sth->bind_columns(
                        \( $coord_xref_id, $accession, $txStart, $txEnd,
                           $cdsStart, $cdsEnd, $exonStarts, $exonEnds
                        ) );

        while ( $sth->fetch() ) {
          my @exonStarts = split( /,\s*/, $exonStarts );
          my @exonEnds   = split( /,\s*/, $exonEnds );
          my $exonCount = scalar(@exonStarts);

          # '$rr2' is the RangeRegistry holding exons from the external
          # transcript, for one transcript at a time.
          my $rr2 = Bio::EnsEMBL::Mapper::RangeRegistry->new();

          my $exon_match   = 0;
          my $coding_match = 0;

          my $coding_count = 0;

          for ( my $i = 0 ; $i < $exonCount ; ++$i ) {

            #-----------------------------------------------------------
            # Register the exons from the external database in the same
            # was as with the Ensembl exons, and calculate the overlap
            # of the external exons with the previously registered
            # Ensembl exons.
            #-----------------------------------------------------------

            my $overlap =
              $rr1->overlap_size( 'exon', $exonStarts[$i],
                                  $exonEnds[$i] );

            $exon_match +=
              $overlap/( $exonEnds[$i] - $exonStarts[$i] + 1 );

            $rr2->check_and_register( 'exon', $exonStarts[$i],
                                      $exonEnds[$i] );

            if ( !defined($cdsStart) || !defined($cdsEnd) ) {
              # Non-coding transcript.
            } else {
              my $codingStart = (   $exonStarts[$i] > $cdsStart
                                  ? $exonStarts[$i]
                                  : $cdsStart );
              my $codingEnd =
                ( $exonEnds[$i] < $cdsEnd ? $exonEnds[$i] : $cdsEnd );

              if ( $codingStart < $codingEnd ) {
                my $coding_overlap =
                  $rr1->overlap_size( 'coding', $codingStart,
                                      $codingEnd );

                $coding_match +=
                  $coding_overlap/( $codingEnd - $codingStart + 1 );

                $rr2->check_and_register( 'coding', $codingStart,
                                          $codingEnd );

                ++$coding_count;
              }
            }
          } ## end for ( my $i = 0 ; $i < ...

          my $rexon_match   = 0;
          my $rcoding_match = 0;

          my $rcoding_count = 0;

          foreach my $exon (@exons) {

            #-----------------------------------------------------------
            # Calculate the overlap of the Ensembl exons with the
            # external exons.
            #-----------------------------------------------------------

            my $overlap =
              $rr2->overlap_size( 'exon', $exon->start(),
                                  $exon->end() );

            $rexon_match +=
              $overlap/( $exon->end() - $exon->start() + 1 );

            if (    $coding_transcript
                 && defined( $exon->coding_region_start($transcript) )
                 && defined( $exon->coding_region_end($transcript) ) )
            {
              my $coding_overlap =
                $rr2->overlap_size( 'coding',
                                    $exon->coding_region_start(
                                                           $transcript),
                                    $exon->coding_region_end(
                                                            $transcript)
                );

              $rcoding_match +=
                $coding_overlap/
                ( $exon->coding_region_end($transcript) -
                  $exon->coding_region_start($transcript) +
                  1 );

              ++$rcoding_count;
            }
          } ## end foreach my $exon (@exons)

          #-------------------------------------------------------------
          # Calculate the match score.
          #-------------------------------------------------------------

          my $score = ( ( $exon_match + $ens_weight*$rexon_match ) +
                          $coding_weight*(
                              $coding_match + $ens_weight*$rcoding_match
                          )
            )/( ( $exonCount + $ens_weight*scalar(@exons) ) +
                  $coding_weight*(
                              $coding_count + $ens_weight*$rcoding_count
                  ) );

          if ( !defined( $transcript_result{$coord_xref_id} )
               || $transcript_result{$coord_xref_id} < $score )
          {
            $transcript_result{$coord_xref_id} = $score;
          }

        } ## end while ( $sth->fetch() )
        $sth->finish();

        #---------------------------------------------------------------
        # Apply transcript threshold and pick the best match(es) for
        # this transcript.
        #---------------------------------------------------------------

        my $best_score;
        foreach my $coord_xref_id (
             sort( { $transcript_result{$b} <=> $transcript_result{$a} }
                   keys(%transcript_result) ) )
        {
          my $score = $transcript_result{$coord_xref_id};

          if ( $score > $transcript_score_threshold ) {
            $best_score ||= $score;

            if ( sprintf( "%.3f", $score ) eq
                 sprintf( "%.3f", $best_score ) )
            {
              if ( exists( $unmapped{$coord_xref_id} ) ) {
                $mapped{$coord_xref_id} = $unmapped{$coord_xref_id};
                delete( $unmapped{$coord_xref_id} );
                $mapped{$coord_xref_id}{'reason'}      = undef;
                $mapped{$coord_xref_id}{'reason_full'} = undef;
              }

              push( @{ $mapped{$coord_xref_id}{'mapped_to'} }, {
                      'ensembl_id'          => $transcript->dbID(),
                      'ensembl_object_type' => 'Transcript'
                    } );

              # This is now a candidate Xref for the gene.
              if ( !defined( $gene_result{$coord_xref_id} )
                   || $gene_result{$coord_xref_id} < $score )
              {
                $gene_result{$coord_xref_id} = $score;
              }

            } elsif ( exists( $unmapped{$coord_xref_id} ) ) {
              $unmapped{$coord_xref_id}{'reason'} =
                'Was not best match';
              $unmapped{$coord_xref_id}{'reason_full'} =
                sprintf(
                       "Did not top best transcript match score (%.2f)",
                       $best_score );
              if ( !defined( $unmapped{$coord_xref_id}{'score'} )
                   || $score > $unmapped{$coord_xref_id}{'score'} )
              {
                $unmapped{$coord_xref_id}{'score'} = $score;
                $unmapped{$coord_xref_id}{'ensembl_id'} =
                  $transcript->dbID();
              }
            }

          } elsif ( exists( $unmapped{$coord_xref_id} )
                    && $unmapped{$coord_xref_id}{'reason'} ne
                    'Was not best match' )
          {
            $unmapped{$coord_xref_id}{'reason'} =
              'Did not meet threshold';
            $unmapped{$coord_xref_id}{'reason_full'} =
              sprintf( "Match score for transcript "
                         . "lower than threshold (%.2f)",
                       $transcript_score_threshold );
            if ( !defined( $unmapped{$coord_xref_id}{'score'} )
                 || $score > $unmapped{$coord_xref_id}{'score'} )
            {
              $unmapped{$coord_xref_id}{'score'} = $score;
              $unmapped{$coord_xref_id}{'ensembl_id'} =
                $transcript->dbID();
            }
          }
        } ## end foreach my $coord_xref_id (...

      } ## end foreach my $transcript ( sort...

      #-----------------------------------------------------------------
      # Pick the best match(es) for this gene.
      #-----------------------------------------------------------------

      # Do not want them on both Transcripts and Genes. For Biomart purposes. (Ianl)
      # So no need to find the best one for the gene.

#      my $best_score;
#      foreach my $coord_xref_id (
#                         sort( { $gene_result{$b} <=> $gene_result{$a} }
#                               keys(%gene_result) ) )
#      {
#        my $score = $gene_result{$coord_xref_id};
#
#        $best_score ||= $score;
#
#        if (
#           sprintf( "%.3f", $score ) eq sprintf( "%.3f", $best_score ) )
#        {
#          push( @{ $mapped{$coord_xref_id}{'mapped_to'} }, {
#                  'ensembl_id'          => $gene->dbID(),
#                  'ensembl_object_type' => 'Gene'
#                } );
#        }
#      }

    } ## end while ( my $gene = shift(...
  } ## end foreach my $chromosome (@chromosomes)

  # Make all dumps.  Order is important.
  dump_xref( $xref_filename, $xref_id, \%mapped, \%unmapped );
  dump_object_xref( $object_xref_filename, $object_xref_id, $analysis_id, \%mapped );
  dump_unmapped_reason( $unmapped_reason_filename, $unmapped_reason_id,
                        \%unmapped, $core_dbh );
  dump_unmapped_object( $unmapped_object_filename, $unmapped_object_id,
                        $analysis_id, \%unmapped );

  if ($do_upload) {
    # Order is important!
    upload_data( 'unmapped_reason', $unmapped_reason_filename,
                 $external_db_id, $core_dbh );
    upload_data( 'unmapped_object', $unmapped_object_filename,
                 $external_db_id, $core_dbh );
    upload_data( 'object_xref', $object_xref_filename, $external_db_id,
                 $core_dbh );
    upload_data( 'xref', $xref_filename, $external_db_id, $core_dbh );
  }

  $sth_stat = $self->xref->dbc->prepare(
                          "INSERT INTO process_status (status, date) "
                        . "VALUES ('coordinate_xref_finished',now())" );
  $sth_stat->execute();
  $sth_stat->finish();

  $self->biomart_fix("UCSC","Translation","Gene");
  $self->biomart_fix("UCSC","Transcript","Gene");

} ## end sub run_coordinatemapping

#-----------------------------------------------------------------------

sub dump_xref {
  my ( $filename, $xref_id, $mapped, $unmapped ) = @_;

  ######################################################################
  # Dump for 'xref'.                                                   #
  ######################################################################

  my $fh = IO::File->new( '>' . $filename )
    or croak( sprintf( "Can not open '%s' for writing", $filename ) );

  log_progress( "Dumping for 'xref' to '%s'\n", $filename );

  foreach my $xref ( values( %{$unmapped} ), values( %{$mapped} ) ) {
    # Assign 'xref_id' to this Xref.
    $xref->{'xref_id'} = ++$xref_id;

    my $accession = $xref->{'accession'};

    my ($version) = ( $accession =~ /\.(\d+)$/ );
    $version ||= 0;

    $fh->printf("%d\t%d\t%s\t%s\t%d\t%s\t%s\t%s\n",
                $xref->{'xref_id'},
                $xref->{'external_db_id'},
                $accession,
                $accession,
                $version,
                '\N',
                'COORDINATE_OVERLAP',
                ''                                  # FIXME (possibly)
    );
  }
  $fh->close();

  log_progress("Dumping for 'xref' done\n");

} ## end sub dump_xref

#-----------------------------------------------------------------------

sub dump_object_xref {
  my ( $filename, $object_xref_id, $analysis_id, $mapped ) = @_;

  ######################################################################
  # Dump for 'object_xref'.                                            #
  ######################################################################

  my $fh = IO::File->new( '>' . $filename )
    or croak( sprintf( "Can not open '%s' for writing", $filename ) );

  log_progress( "Dumping for 'object_xref' to '%s'\n", $filename );

  foreach my $xref ( values( %{$mapped} ) ) {
    foreach my $object_xref ( @{ $xref->{'mapped_to'} } ) {
      # Assign 'object_xref_id' to this Object Xref.
      $object_xref->{'object_xref_id'} = ++$object_xref_id;

      $fh->printf( "%d\t%d\t%s\t%d\t%s\t%s\n",
                   $object_xref->{'object_xref_id'},
                   $object_xref->{'ensembl_id'},
                   $object_xref->{'ensembl_object_type'},
                   $xref->{'xref_id'},
                   '\N',
                   $analysis_id );
    }
  }
  $fh->close();

  log_progress("Dumping for 'object_xref' done\n");

} ## end sub dump_objexref

#-----------------------------------------------------------------------

sub dump_unmapped_reason {
  my ( $filename, $unmapped_reason_id, $unmapped, $core_dbh ) = @_;

  ######################################################################
  # Dump for 'unmapped_reason'.                                        #
  ######################################################################

  # Create a list of the unique reasons.
  my %reasons;

  foreach my $xref ( values( %{$unmapped} ) ) {
    if ( !exists( $reasons{ $xref->{'reason_full'} } ) ) {
      $reasons{ $xref->{'reason_full'} } = {
                                        'summary' => $xref->{'reason'},
                                        'full' => $xref->{'reason_full'}
      };
    }
  }

  my $fh = IO::File->new( '>' . $filename )
    or croak( sprintf( "Can not open '%s' for writing", $filename ) );

  log_progress( "Dumping for 'unmapped_reason' to '%s'\n", $filename );

  my $sth =
    $core_dbh->prepare(   'SELECT unmapped_reason_id '
                        . 'FROM unmapped_reason '
                        . 'WHERE full_description = ?' );

  foreach my $reason (
            sort( { $a->{'full'} cmp $b->{'full'} } values(%reasons) ) )
  {
    # Figure out 'unmapped_reason_id' from the core database.
    $sth->bind_param( 1, $reason->{'full'}, SQL_VARCHAR );

    $sth->execute();

    my $id;
    $sth->bind_col( 1, \$id );
    $sth->fetch();

    if ( defined($id) ) {
      $reason->{'unmapped_reason_id'} = $id;
    } else {
      $reason->{'unmapped_reason_id'} = ++$unmapped_reason_id;
    }

    $sth->finish();

    $fh->printf( "%d\t%s\t%s\n", $reason->{'unmapped_reason_id'},
                 $reason->{'summary'}, $reason->{'full'} );

  }
  $fh->close();

  log_progress("Dumping for 'unmapped_reason' done\n");

  # Assign reasons to the unmapped Xrefs from %reasons.
  foreach my $xref ( values( %{$unmapped} ) ) {
    $xref->{'reason'}      = $reasons{ $xref->{'reason_full'} };
    $xref->{'reason_full'} = undef;
  }

} ## end sub dump_unmapped_reason

#-----------------------------------------------------------------------

sub dump_unmapped_object {
  my ( $filename, $unmapped_object_id, $analysis_id, $unmapped ) = @_;

  ######################################################################
  # Dump for 'unmapped_object'.                                        #
  ######################################################################

  my $fh = IO::File->new( '>' . $filename )
    or croak( sprintf( "Can not open '%s' for writing", $filename ) );

  log_progress( "Dumping for 'unmapped_object' to '%s'\n", $filename );

  foreach my $xref ( values( %{$unmapped} ) ) {
    # Assign 'unmapped_object_id' to this Xref.
    $xref->{'unmapped_object_id'} = ++$unmapped_object_id;

    $fh->printf(
      "%d\t%s\t%s\t%d\t%s\t%d\t%s\t%s\t%s\t%s\t%s\n",
      $xref->{'unmapped_object_id'},
      'xref',
      $analysis_id || '\N',    # '\N' (NULL) means no analysis exists
                               # and uploading this table will fail.
      $xref->{'external_db_id'},
      $xref->{'accession'},
      $xref->{'reason'}->{'unmapped_reason_id'}, (
        defined( $xref->{'score'} )
        ? sprintf( "%.3f", $xref->{'score'} )
        : '\N'
      ),
      '\N',
      $xref->{'ensembl_id'} || '\N',
      ( defined( $xref->{'ensembl_id'} ) ? 'Transcript' : '\N' ),
      '\N' );
  }
  $fh->close();

  log_progress("Dumping for 'unmapped_object' done\n");

} ## end sub dump_unmapped_object

#-----------------------------------------------------------------------

sub upload_data {
  my ( $table_name, $filename, $external_db_id, $dbh ) = @_;

  ######################################################################
  # Upload data from a file to a table.                                #
  ######################################################################

  if ( !-r $filename ) {
    croak( sprintf( "Can not open '%s' for reading", $filename ) );
  }

  my $cleanup_sql = '';
  if ( $table_name eq 'unmapped_reason' ) {
    $cleanup_sql = qq(
    DELETE  ur
    FROM    unmapped_object uo,
            unmapped_reason ur
    WHERE   uo.external_db_id       = ?
    AND     ur.unmapped_reason_id   = uo.unmapped_reason_id);
  } elsif ( $table_name eq 'unmapped_object' ) {
    $cleanup_sql = qq(
    DELETE  uo
    FROM    unmapped_object uo
    WHERE   uo.external_db_id = ?);
  } elsif ( $table_name eq 'object_xref' ) {
    $cleanup_sql = qq(
    DELETE  ox
    FROM    xref x,
            object_xref ox
    WHERE   x.external_db_id    = ?
    AND     ox.xref_id          = x.xref_id);
  } elsif ( $table_name eq 'xref' ) {
    $cleanup_sql = qq(
    DELETE  x
    FROM    xref x
    WHERE   x.external_db_id    = ?);
  } else {
    croak( sprintf( "Table '%s' is unknown\n", $table_name ) );
  }

  my $load_sql =
    sprintf( "LOAD DATA LOCAL INFILE ? REPLACE INTO TABLE %s",
             $table_name );

  log_progress(
          "Removing old data (external_db_id = '%d') from table '%s'\n",
          $external_db_id, $table_name );

  my $rows = $dbh->do( $cleanup_sql, undef, $external_db_id )
    or croak( $dbh->strerr() );

  log_progress( "Removed %d rows\n", $rows );

  log_progress( "Uploading for '%s' from '%s'\n",
                $table_name, $filename );

  $rows = $dbh->do( $load_sql, undef, $filename )
    or croak( $dbh->errstr() );

  $dbh->do("OPTIMIZE TABLE $table_name") or croak( $dbh->errstr() );

  log_progress( "Uploading for '%s' done (%d rows)\n",
                $table_name, $rows );

} ## end sub upload_data

#-----------------------------------------------------------------------

sub log_progress {
  my ( $fmt, @params ) = @_;

  return if (!$verbose);
  printf( STDERR "COORD==> %s", sprintf( $fmt, @params ) );
}

1;


text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "portaudio.h"
#include "ringbuffer.h"
#include "pablio.h"
#include <string.h>

/************************************************************************/
/******** Constants *****************************************************/
/************************************************************************/

#define FRAMES_PER_BUFFER    (256)

/************************************************************************/
/******** Prototypes ****************************************************/
/************************************************************************/

static int blockingIOCallback( void *inputBuffer, void *outputBuffer,
                               unsigned long framesPerBuffer,
                               PaTimestamp outTime, void *userData );
static PaError PABLIO_InitFIFO( RingBuffer *rbuf, long numFrames, long bytesPerFrame );
static PaError PABLIO_TermFIFO( RingBuffer *rbuf );

/************************************************************************/
/******** Functions *****************************************************/
/************************************************************************/

/* Called from PortAudio.
 * Read and write data only if there is room in FIFOs.
 */
static int blockingIOCallback( void *inputBuffer, void *outputBuffer,
                               unsigned long framesPerBuffer,
                               PaTimestamp outTime, void *userData )
{
    PABLIO_Stream *data = (PABLIO_Stream*)userData;
    long numBytes = data->bytesPerFrame * framesPerBuffer;
    (void) outTime;

    /* This may get called with NULL inputBuffer during initial setup. */
    if( inputBuffer != NULL )
    {
        RingBuffer_Write( &data->inFIFO, inputBuffer, numBytes );
    }
    if( outputBuffer != NULL )
    {
        int i;
        int numRead = RingBuffer_Read( &data->outFIFO, outputBuffer, numBytes );
        /* Zero out remainder of buffer if we run out of data. */
        for( i=numRead; i<numBytes; i++ )
        {
            ((char *)outputBuffer)[i] = 0;
        }
    }

    return 0;
}

/* Allocate buffer. */
static PaError PABLIO_InitFIFO( RingBuffer *rbuf, long numFrames, long bytesPerFrame )
{
    long numBytes = numFrames * bytesPerFrame;
    char *buffer = (char *) malloc( numBytes );
    if( buffer == NULL ) return paInsufficientMemory;
    memset( buffer, 0, numBytes );
    return (PaError) RingBuffer_Init( rbuf, numBytes, buffer );
}

/* Free buffer. */
static PaError PABLIO_TermFIFO( RingBuffer *rbuf )
{
    if( rbuf->buffer ) free( rbuf->buffer );
    rbuf->buffer = NULL;
    return paNoError;
}

/************************************************************
 * Write data to ring buffer.
 * Will not return until all the data has been written.
 */
long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )
{
    long bytesWritten;
    char *p = (char *) data;
    long numBytes = aStream->bytesPerFrame * numFrames;
    while( numBytes > 0)
    {
        bytesWritten = RingBuffer_Write( &aStream->outFIFO, p, numBytes );
        numBytes -= bytesWritten;
        p += bytesWritten;
        if( numBytes > 0) Pa_Sleep(10);
    }
    return numFrames;
}

/************************************************************
 * Read data from ring buffer.
 * Will not return until all the data has been read.
 */
long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )
{
    long bytesRead;
    char *p = (char *) data;
    long numBytes = aStream->bytesPerFrame * numFrames;
    while( numBytes > 0)
    {
        bytesRead = RingBuffer_Read( &aStream->inFIFO, p, numBytes );
        numBytes -= bytesRead;
        p += bytesRead;
        if( numBytes > 0) Pa_Sleep(10);
    }
    return numFrames;
}

/************************************************************
 * Return the number of frames that could be written to the stream without
 * having to wait.
 */
long GetAudioStreamWriteable( PABLIO_Stream *aStream )
{
    int bytesEmpty = RingBuffer_GetWriteAvailable( &aStream->outFIFO );
    return bytesEmpty / aStream->bytesPerFrame;
}

/************************************************************
 * Return the number of frames that are available to be read from the
 * stream without having to wait.
 */
long GetAudioStreamReadable( PABLIO_Stream *aStream )
{
    int bytesFull = RingBuffer_GetReadAvailable( &aStream->inFIFO );
    return bytesFull / aStream->bytesPerFrame;
}

/************************************************************/
static unsigned long RoundUpToNextPowerOf2( unsigned long n )
{
    long numBits = 0;
    if( ((n-1) & n) == 0) return n; /* Already Power of two. */
    while( n > 0 )
    {
        n= n>>1;
        numBits++;
    }
    return (1<<numBits);
}

/************************************************************
 * Opens a PortAudio stream with default characteristics.
 * Allocates PABLIO_Stream structure.
 *
 * flags parameter can be an ORed combination of:
 *    PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE,
 *    and either PABLIO_MONO or PABLIO_STEREO
 */
PaError OpenAudioStream( PABLIO_Stream **rwblPtr, double sampleRate,
                         PaSampleFormat format, long flags )
{
    long   bytesPerSample;
    long   doRead = 0;
    long   doWrite = 0;
    PaError err;
    PABLIO_Stream *aStream;
    long   minNumBuffers;
    long   numFrames;

    /* Allocate PABLIO_Stream structure for caller. */
    aStream = (PABLIO_Stream *) malloc( sizeof(PABLIO_Stream) );
    if( aStream == NULL ) return paInsufficientMemory;
    memset( aStream, 0, sizeof(PABLIO_Stream) );

    /* Determine size of a sample. */
    bytesPerSample = Pa_GetSampleSize( format );
    if( bytesPerSample < 0 )
    {
        err = (PaError) bytesPerSample;
        goto error;
    }
    aStream->samplesPerFrame = ((flags&PABLIO_MONO) != 0) ? 1 : 2;
    aStream->bytesPerFrame = bytesPerSample * aStream->samplesPerFrame;

    /* Initialize PortAudio  */
    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    /* Warning: numFrames must be larger than amount of data processed per interrupt
     *    inside PA to prevent glitches. Just to be safe, adjust size upwards.
     */
    minNumBuffers = 2 * Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate );
    numFrames = minNumBuffers * FRAMES_PER_BUFFER;
    numFrames = RoundUpToNextPowerOf2( numFrames );

    /* Initialize Ring Buffers */
    doRead = ((flags & PABLIO_READ) != 0);
    doWrite = ((flags & PABLIO_WRITE) != 0);
    if(doRead)
    {
        err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames, aStream->bytesPerFrame );
        if( err != paNoError ) goto error;
    }
    if(doWrite)
    {
        long numBytes;
        err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->bytesPerFrame );
        if( err != paNoError ) goto error;
        /* Make Write FIFO appear full initially. */
        numBytes = RingBuffer_GetWriteAvailable( &aStream->outFIFO );
        RingBuffer_AdvanceWriteIndex( &aStream->outFIFO, numBytes );
    }

    /* Open a PortAudio stream that we will use to communicate with the underlying
     * audio drivers. */
    err = Pa_OpenStream(
              &aStream->stream,
              (doRead ? Pa_GetDefaultInputDeviceID() : paNoDevice),
              (doRead ? aStream->samplesPerFrame : 0 ),
              format,
              NULL,
              (doWrite ? Pa_GetDefaultOutputDeviceID() : paNoDevice),
              (doWrite ? aStream->samplesPerFrame : 0 ),
              format,
              NULL,
              sampleRate,
              FRAMES_PER_BUFFER,
              minNumBuffers,
              paClipOff,       /* we won't output out of range samples so don't bother clipping them */
              blockingIOCallback,
              aStream );
    if( err != paNoError ) goto error;

    err = Pa_StartStream( aStream->stream );
    if( err != paNoError ) goto error;

    *rwblPtr = aStream;
    return paNoError;

error:
    CloseAudioStream( aStream );
    *rwblPtr = NULL;
    return err;
}

/************************************************************/
PaError CloseAudioStream( PABLIO_Stream *aStream )
{
    PaError err;
    int bytesEmpty;
    int byteSize = aStream->outFIFO.bufferSize;

    /* If we are writing data, make sure we play everything written. */
    if( byteSize > 0 )
    {
        bytesEmpty = RingBuffer_GetWriteAvailable( &aStream->outFIFO );
        while( bytesEmpty < byteSize )
        {
            Pa_Sleep( 10 );
            bytesEmpty = RingBuffer_GetWriteAvailable( &aStream->outFIFO );
        }
    }

    err = Pa_StopStream( aStream->stream );
    if( err != paNoError ) goto error;
    err = Pa_CloseStream( aStream->stream );
    if( err != paNoError ) goto error;
    Pa_Terminate();

error:
    PABLIO_TermFIFO( &aStream->inFIFO );
    PABLIO_TermFIFO( &aStream->outFIFO );
    free( aStream );
    return err;
}


text:
<?php
namespace Light\ObjectAccess\Resource\Addressing;

use Light\ObjectAccess\Resource\ResolvedResource;

/**
 * Provides a path from a source resource to a destination resource.
 */
interface RelativeAddress extends Address
{
	/**
	 * Returns the source resource.
	 * @return ResolvedResource
	 */
	public function getSourceResource();

	/**
	 * Returns a list of path elements to traverse for reaching the target resource.
	 * @return mixed[]
	 */
	public function getPathElements();
}


text:
package ar.com.javacuriosities.nio.server.message.processor;

import ar.com.javacuriosities.nio.server.message.Message;
import ar.com.javacuriosities.nio.server.message.writer.WriteProxy;

/*
 * La implementación esta encargada de leer el mensaje y responder en consecuencia
 */
public interface IMessageProcessor {

    void process(Message message, WriteProxy writeProxy);
}


text:
package com.vk.api.sdk.objects.media;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.objects.Validable;
import com.vk.api.sdk.objects.annotations.Required;
import com.vk.api.sdk.objects.base.BoolInt;
import com.vk.api.sdk.objects.base.Image;
import com.vk.api.sdk.objects.video.RestrictionButton;
import java.util.List;
import java.util.Objects;

/**
 * Media restrictions
 */
public class Restriction implements Validable {
    @SerializedName("text")
    private String text;

    @SerializedName("title")
    @Required
    private String title;

    @SerializedName("button")
    private RestrictionButton button;

    /**
     * Need show restriction always or not
     */
    @SerializedName("always_shown")
    private BoolInt alwaysShown;

    /**
     * Need blur current video or not
     */
    @SerializedName("blur")
    private BoolInt blur;

    /**
     * Can play video or not
     */
    @SerializedName("can_play")
    private BoolInt canPlay;

    /**
     * Can preview video or not
     */
    @SerializedName("can_preview")
    private BoolInt canPreview;

    @SerializedName("card_icon")
    private List<Image> cardIcon;

    @SerializedName("list_icon")
    private List<Image> listIcon;

    public String getText() {
        return text;
    }

    public Restriction setText(String text) {
        this.text = text;
        return this;
    }

    public String getTitle() {
        return title;
    }

    public Restriction setTitle(String title) {
        this.title = title;
        return this;
    }

    public RestrictionButton getButton() {
        return button;
    }

    public Restriction setButton(RestrictionButton button) {
        this.button = button;
        return this;
    }

    public boolean isAlwaysShown() {
        return alwaysShown == BoolInt.YES;
    }

    public BoolInt getAlwaysShown() {
        return alwaysShown;
    }

    public boolean isBlur() {
        return blur == BoolInt.YES;
    }

    public BoolInt getBlur() {
        return blur;
    }

    public boolean canPlay() {
        return canPlay == BoolInt.YES;
    }

    public BoolInt getCanPlay() {
        return canPlay;
    }

    public boolean canPreview() {
        return canPreview == BoolInt.YES;
    }

    public BoolInt getCanPreview() {
        return canPreview;
    }

    public List<Image> getCardIcon() {
        return cardIcon;
    }

    public Restriction setCardIcon(List<Image> cardIcon) {
        this.cardIcon = cardIcon;
        return this;
    }

    public List<Image> getListIcon() {
        return listIcon;
    }

    public Restriction setListIcon(List<Image> listIcon) {
        this.listIcon = listIcon;
        return this;
    }

    @Override
    public int hashCode() {
        return Objects.hash(button, cardIcon, alwaysShown, canPlay, listIcon, blur, text, title, canPreview);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Restriction restriction = (Restriction) o;
        return Objects.equals(button, restriction.button) &&
                Objects.equals(canPlay, restriction.canPlay) &&
                Objects.equals(cardIcon, restriction.cardIcon) &&
                Objects.equals(alwaysShown, restriction.alwaysShown) &&
                Objects.equals(blur, restriction.blur) &&
                Objects.equals(text, restriction.text) &&
                Objects.equals(title, restriction.title) &&
                Objects.equals(canPreview, restriction.canPreview) &&
                Objects.equals(listIcon, restriction.listIcon);
    }

    @Override
    public String toString() {
        final Gson gson = new Gson();
        return gson.toJson(this);
    }

    public String toPrettyString() {
        final StringBuilder sb = new StringBuilder("Restriction{");
        sb.append("button=").append(button);
        sb.append(", canPlay=").append(canPlay);
        sb.append(", cardIcon=").append(cardIcon);
        sb.append(", alwaysShown=").append(alwaysShown);
        sb.append(", blur=").append(blur);
        sb.append(", text='").append(text).append("'");
        sb.append(", title='").append(title).append("'");
        sb.append(", canPreview=").append(canPreview);
        sb.append(", listIcon=").append(listIcon);
        sb.append('}');
        return sb.toString();
    }
}


text:
IndicatorPlatform::IndicatorPlatform() {
}

void IndicatorPlatform::set(IndicatorIntent intent, bool value) {
  switch(intent) {
    case HEARTBEAT:
      palWritePad(GPIOB, 2, value);
      break;
    case VEHICLE_ARMED:
      palWritePad(GPIOA, 15, value);
      break;
  }
}


text:
/*
 * EProtocolCodecFilter.cpp
 *
 *  Created on: 2016-5-20
 *      Author: cxxjava@163.com
 */

#include "../inc/EProtocolCodecFilter.hh"
#include "../inc/EFileRegion.hh"
#include "../inc/EProtocolEncoderException.hh"
#include "../inc/EProtocolDecoderException.hh"
#include "../inc/ERecoverableProtocolDecoderException.hh"

namespace efc {
namespace eio {

sp<ELogger> EProtocolCodecFilter::LOGGER = ELoggerManager::getLogger("EProtocolCodecFilter");
sp<EAttributeKey> EProtocolCodecFilter::ENCODER = new EAttributeKey(typeid(EProtocolCodecFilter).name(), "encoder");
sp<EAttributeKey> EProtocolCodecFilter::DECODER = new EAttributeKey(typeid(EProtocolCodecFilter).name(), "decoder");
sp<EAttributeKey> EProtocolCodecFilter::DECODER_OUT = new EAttributeKey(typeid(EProtocolCodecFilter).name(), "decoderOut");
sp<EAttributeKey> EProtocolCodecFilter::ENCODER_OUT = new EAttributeKey(typeid(EProtocolCodecFilter).name(), "encoderOut");
static const char* emptyBuffer = "";
EIoBuffer* EProtocolCodecFilter::EMPTY_BUFFER = EIoBuffer::wrap(&emptyBuffer, 0, 0); //!

EProtocolCodecFilter::~EProtocolCodecFilter() {
	if (factoryOwner && factory) {
		delete factory;
	}
}

EProtocolCodecFilter::EProtocolCodecFilter(EProtocolCodecFactory* factory) {
	if (factory == null) {
		throw EIllegalArgumentException(__FILE__, __LINE__, "factory");
	}

	this->factory = factory;
	this->factoryOwner = false;
}

EProtocolCodecFilter::EProtocolCodecFilter(EProtocolEncoder* encoder,
		EProtocolDecoder* decoder) {
	if (encoder == null) {
		throw EIllegalArgumentException(__FILE__, __LINE__, "encoder");
	}
	if (decoder == null) {
		throw EIllegalArgumentException(__FILE__, __LINE__, "decoder");
	}

	class ProtocolCodecFactory: public EProtocolCodecFactory {
	private:
		EProtocolEncoder* encoder;
		EProtocolDecoder* decoder;
	public:
		ProtocolCodecFactory(EProtocolEncoder* e, EProtocolDecoder* d) {
			encoder = e;
			decoder = d;
		}
		virtual EProtocolEncoder* getEncoder(sp<EIoSession>& session) {
			return encoder;
		}

		virtual EProtocolDecoder* getDecoder(sp<EIoSession>& session) {
			return decoder;
		}
	};
	// Create the inner Factory based on the two parameters
	this->factory = new ProtocolCodecFactory(encoder, decoder);
}

//EProtocolEncoder* EProtocolCodecFilter::getEncoder(sp<EIoSession>& session) {
//	return (EProtocolEncoder*) session->getAttribute(ENCODER);
//}

void EProtocolCodecFilter::onPreAdd(EIoFilterChain* parent, const char* name,
		EIoFilter::NextFilter* nextFilter) {
	if (parent->contains(this)) {
		throw EIllegalArgumentException(__FILE__, __LINE__,
			"You can't add the same filter instance more than once.  Create another instance and add it.");
	}
}

void EProtocolCodecFilter::onPostRemove(EIoFilterChain* parent,
		const char* name, EIoFilter::NextFilter* nextFilter) {
	// Clean everything
	sp<EIoSession> session = parent->getSession();
	disposeCodec(session);
}

void EProtocolCodecFilter::messageReceived(EIoFilter::NextFilter* nextFilter,
		sp<EIoSession>& session, sp<EObject>& message) {
	LOGGER->debug__(__FILE__, __LINE__, "Processing a MESSAGE_RECEIVED for session %ld", session->getId());

	EIoBuffer* in = dynamic_cast<EIoBuffer*>(message.get());
	if (!in) {
		nextFilter->messageReceived(session, message);
		return;
	}

	EProtocolDecoder* decoder = factory->getDecoder(session);
	sp<EProtocolDecoderOutput> decoderOut = getDecoderOut(session, nextFilter);

	// Loop until we don't have anymore byte in the buffer,
	// or until the decoder throws an unrecoverable exception or
	// can't decoder a message, because there are not enough
	// data in the buffer
	while (in->hasRemaining()) {
		int oldPos = in->position();
		try {
//			ELock* lock = session->getLock();
//			ES_ASSERT(lock);
//			SYNCBLOCK(lock) { // here need lock ? cxxjava@163.com
				// Call the decoder with the read bytes
				decoder->decode(session, in, decoderOut);
//			}}
			// Finish decoding if no exception was thrown.
			decoderOut->flush(nextFilter, session);
		} catch (EException& e) {
			EProtocolDecoderException pde(e);
			if (pde.getHexdump() == null) {
				// Generate a message hex dump
				int curPos = in->position();
				in->position(oldPos);
				pde.setHexdump(in->getHexdump().c_str());
				in->position(curPos);
			}
			// Fire the exceptionCaught event.
			decoderOut->flush(nextFilter, session);
			sp<EThrowableType> tt(new EThrowableObject<EProtocolDecoderException>(pde));
			nextFilter->exceptionCaught(session, tt);
			// Retry only if the type of the caught exception is
			// recoverable and the buffer position has changed.
			// We check buffer position additionally to prevent an
			// infinite loop.
			//@see: if (!(e instanceof RecoverableProtocolDecoderException) || (in.position() == oldPos)) {
			if (instanceof<ERecoverableProtocolDecoderException>(e) || (in->position() == oldPos)) {
				break;
			}
		}
	}
}

void EProtocolCodecFilter::messageSent(EIoFilter::NextFilter* nextFilter,
		sp<EIoSession>& session, sp<EWriteRequest>& writeRequest) {
	if (instanceof<EncodedWriteRequest>(writeRequest.get())) {
		return;
	}

	sp<MessageWriteRequest> wrappedRequest = dynamic_pointer_cast<MessageWriteRequest>(writeRequest);
	if (wrappedRequest != null) {
		sp<EWriteRequest> wr = wrappedRequest->getParentRequest();
		nextFilter->messageSent(session, wr);
	} else {
		nextFilter->messageSent(session, writeRequest);
	}
}

void EProtocolCodecFilter::filterWrite(EIoFilter::NextFilter* nextFilter,
		sp<EIoSession>& session, sp<EWriteRequest>& writeRequest) {
	sp<EObject> message = writeRequest->getMessage();

	// Bypass the encoding if the message is contained in a IoBuffer,
	// as it has already been encoded before
	if (instanceof<EIoBuffer>(message.get()) || instanceof<EFileRegion>(message.get())) {
		nextFilter->filterWrite(session, writeRequest);
		return;
	}

	// Get the encoder in the session
	EProtocolEncoder* encoder = factory->getEncoder(session);

	sp<EProtocolEncoderOutput> encoderOut = getEncoderOut(session, nextFilter, writeRequest);

	if (encoder == null) {
		throw EProtocolEncoderException(__FILE__, __LINE__,
				EString::formatOf("The encoder is null for the session %s", session->toString().c_str()).c_str());
	}

	try {
		// Now we can try to encode the response
		encoder->encode(session, message, encoderOut);

		/* @see:
		// Send it directly
		Queue<Object> bufferQueue = ((AbstractProtocolEncoderOutput) encoderOut).getMessageQueue();

		// Write all the encoded messages now
		while (!bufferQueue.isEmpty()) {
			Object encodedMessage = bufferQueue.poll();

			if (encodedMessage == null) {
				break;
			}

			// Flush only when the buffer has remaining.
			if (!(encodedMessage instanceof IoBuffer) || ((IoBuffer) encodedMessage).hasRemaining()) {
				SocketAddress destination = writeRequest.getDestination();
				WriteRequest encodedWriteRequest = new EncodedWriteRequest(encodedMessage, null, destination);

				nextFilter.filterWrite(session, encodedWriteRequest);
			}
		}
		*/
		// Write all the encoded messages now
		EAbstractProtocolEncoderOutput* peo = dynamic_cast<EAbstractProtocolEncoderOutput*>(encoderOut.get());
		sp<EObject>  encodedMessage;
		while ((encodedMessage = peo->poll()) != null) {
			// Flush only when the buffer has remaining.
			sp<EIoBuffer> buf = dynamic_pointer_cast<EIoBuffer>(encodedMessage);
			if (buf == null || buf->hasRemaining()) {
				EInetSocketAddress* destination = writeRequest->getDestination();
				sp<EWriteRequest> encodedWriteRequest = new EncodedWriteRequest(encodedMessage, null, destination);

				nextFilter->filterWrite(session, encodedWriteRequest);
			}
		}

		// Call the next filter
		sp<EWriteRequest> wr = new MessageWriteRequest(writeRequest);
		nextFilter->filterWrite(session, wr);
	} catch (EException& e) {
		throw EProtocolEncoderException(e.getSourceFile(), e.getSourceLine(), e.getMessage(), e.getErrno());
	}
}

void EProtocolCodecFilter::sessionClosed(EIoFilter::NextFilter* nextFilter,
		sp<EIoSession>& session) {
	// Call finishDecode() first when a connection is closed.
	EProtocolDecoder* decoder = factory->getDecoder(session);
	sp<EProtocolDecoderOutput> decoderOut = getDecoderOut(session, nextFilter);

	ON_FINALLY_NOTHROW(
		// Dispose everything
		disposeCodec(session);
		decoderOut->flush(nextFilter, session);
	) {
		try {
			decoder->finishDecode(session, decoderOut);
		} catch (EException& e) {
			EProtocolDecoderException pde(e);
			throw pde;
		}
    }}

	// Call the next filter
	nextFilter->sessionClosed(session);
}

void EProtocolCodecFilter::disposeCodec(sp<EIoSession>& session) {
	// We just remove the two instances of encoder/decoder to release resources
	// from the session
	disposeEncoder(session);
	disposeDecoder(session);

	// We also remove the callback
	disposeDecoderOut(session);
}

void EProtocolCodecFilter::disposeEncoder(sp<EIoSession>& session) {
	sp<EProtocolEncoder> encoder = dynamic_pointer_cast<EProtocolEncoder>(session->removeAttribute(ENCODER.get())); //sp?
	if (encoder == null) {
		return;
	}

	try {
		encoder->dispose(session);
	} catch (EException& e) {
		LOGGER->warn__(__FILE__, __LINE__,
				EString::formatOf("Failed to dispose: %s (%s)", typeid(encoder).name(), encoder->toString().c_str()).c_str());
	}
}

void EProtocolCodecFilter::disposeDecoder(sp<EIoSession>& session) {
	sp<EProtocolDecoder> decoder = dynamic_pointer_cast<EProtocolDecoder>(session->removeAttribute(DECODER.get())); //sp?
	if (decoder == null) {
		return;
	}

	try {
		decoder->dispose(session);
	} catch (EException& e) {
		LOGGER->warn__(__FILE__, __LINE__,
				EString::formatOf("Failed to dispose: %s (%s)", typeid(decoder).name(), decoder->toString().c_str()).c_str());
	}
}

sp<EProtocolDecoderOutput> EProtocolCodecFilter::getDecoderOut(sp<EIoSession>& session, EIoFilter::NextFilter* nextFilter) {
	sp<EProtocolDecoderOutput> out = dynamic_pointer_cast<EProtocolDecoderOutput>(session->getAttribute(DECODER_OUT.get()));

	if (out == null) {
		// Create a new instance, and stores it into the session
		out = new ProtocolDecoderOutputImpl();
		session->setAttribute(DECODER_OUT, out);
	}

	return out;
}

sp<EProtocolEncoderOutput> EProtocolCodecFilter::getEncoderOut(sp<EIoSession>& session, EIoFilter::NextFilter* nextFilter, sp<EWriteRequest>& writeRequest) {
	sp<EProtocolEncoderOutput> out = dynamic_pointer_cast<EProtocolEncoderOutput>(session->getAttribute(ENCODER_OUT.get()));

	if (out == null) {
		// Create a new instance, and stores it into the session
		out = new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest);
		session->setAttribute(ENCODER_OUT, out);
	}

	return out;
}

void EProtocolCodecFilter::disposeDecoderOut(sp<EIoSession>& session) {
	session->removeAttribute(DECODER_OUT.get());
}

} /* namespace eio */
} /* namespace efc */


text:
<?php

namespace App\Action;

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Views\Twig;
use Psr\Log\LoggerInterface;
use RKA\Session;
use Slim\Flash\Messages;

final class AuthAction
{
    private $view;
    private $logger;
    private $session;
    private $flash;

    public function __construct(Twig $view, LoggerInterface $logger, Session $session, Messages $flash)
    {
        $this->view    = $view;
        $this->logger  = $logger;
        $this->session = $session;
        $this->flash   = $flash;
    }

    public function dispatch(Request $request, Response $response)
    {
        $this->logger->info("Auth");

        return $this->renderAuth($request, $response);
    }

    // ログアウト処理
    public function logout(Request $request, Response $response)
    {
        $this->session->destroy();
        return $response->withRedirect('/');
    }

    // ログイン画面
    private function renderAuth(Request $request, Response $response)
    {
        $csrf_name = $request->getAttribute('csrf_name');
        $csrf_value = $request->getAttribute('csrf_value');
        $error = $this->flash->getMessage('errorMessage');

        $this->view->render(
            $response,
            'auth.twig',
            [
                'csrf_name'  => $csrf_name,
                'csrf_value' => $csrf_value,
                'error'      => $error[0]
            ]
        );

        return $response;
    }
}


text:
When(/I have an authorized Controller defined as/) do |controller_code|
  require 'action_controller'
  require 'eaco/controller'

  @controller_class = Class.new(ActionController::Base)
  @controller_class.send(:attr_accessor, :current_user)
  @controller_class.instance_eval { include Eaco::Controller }
  @controller_class.class_eval controller_code
end

When(/I invoke the Controller "(.+?)" action with query string "(.+?)"$/) do |action_name, query|
  @controller  = @controller_class.new
  @action_name = action_name

  @controller.current_user = @current_user

  #:nocov:
  if Rails::VERSION::MAJOR < 5
    @controller.request = ActionDispatch::TestRequest.new('QUERY_STRING' => query).tap do |request|
      request.params.update('action' => @action_name)
    end
  else
    @controller.request = ActionDispatch::TestRequest.create('QUERY_STRING' => query).tap do |request|
      request.action = @action_name
    end
  end
  #:nocov:

  @controller.response = ActionDispatch::TestResponse.new
end

Then(/the Controller should not raise an error/) do
  expect { @controller.process @action_name }.to_not raise_error
end

Then(/the Controller should raise an (.+?) error saying/) do |error_class, error_contents|
  error_class = error_class.constantize

  expect { @controller.process @action_name }.to \
    raise_error(error_class).
    with_message(/#{error_contents}/)
end


text:
title: Blackbeard
subtitle: Movie database with torrents
layout: default
modal-id: 5
date: 2014-07-20
img: Blackbeard-full.jpg
thumbnail: Blackbeard-pre.jpg
alt: image-alt

project-date: April 2014
client: Start Bootstrap
category: Web Development

description: Final project, it is a movies database website, where an user can search for a movies and also find torrents    related to them, the user can start the download using magnet links.
Tech: Node Js, Angular Js, getstrike api, themoviedb api, JQuery, mongodb.
link: https://blackbeard-mdb.herokuapp.com

---


text:
<?php

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Validate;

/**
 * This link defines a reference from an entry or feed to a Web resource.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: @package_version@
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class AtomLink extends AtomBase
{
    /**
     * The undefined content.
     *
     * @var string
     */
    protected $undefinedContent;

    /**
     * The HREF of the link.
     *
     * @var string
     */
    protected $href;

    /**
     * The rel attribute of the link.
     *
     * @var string
     */
    protected $rel;

    /**
     * The media type of the link.
     *
     * @var string
     */
    protected $type;

    /**
     * The language of HREF.
     *
     * @var string
     */
    protected $hreflang;

    /**
     * The titile of the link.
     *
     * @var string
     */
    protected $title;

    /**
     * The length of the link.
     *
     * @var integer
     */
    protected $length;

    /**
     * Creates a AtomLink instance with specified text.
     */
    public function __construct()
    {
    }

    /**
     * Parse an ATOM Link xml.
     *
     * @param string $xmlString an XML based string of ATOM Link.
     *
     * @return none
     */
    public function parseXml($xmlString)
    {
        Validate::notNull($xmlString, 'xmlString');
        Validate::isString($xmlString, 'xmlString');
        $atomLinkXml = simplexml_load_string($xmlString);
        $attributes  = $atomLinkXml->attributes();

        if (!empty($attributes['href'])) {
            $this->href = (string)$attributes['href'];
        }

        if (!empty($attributes['rel'])) {
            $this->rel = (string)$attributes['rel'];
        }

        if (!empty($attributes['type'])) {
            $this->type = (string)$attributes['type'];
        }

        if (!empty($attributes['hreflang'])) {
            $this->hreflang = (string)$attributes['hreflang'];
        }

        if (!empty($attributes['title'])) {
            $this->title = (string)$attributes['title'];
        }

        if (!empty($attributes['length'])) {
            $this->length = (integer)$attributes['length'];
        }

        $undefinedContent = (string)$atomLinkXml;
        if (empty($undefinedContent)) {
            $this->undefinedContent = null;
        } else {
            $this->undefinedContent = (string)$atomLinkXml;
        }
    }

    /**
     * Gets the href of the link.
     *
     * @return string
     */
    public function getHref()
    {
        return $this->href;
    }

    /**
     * Sets the href of the link.
     *
     * @param string $href The href of the link.
     *
     * @return none
     */
    public function setHref($href)
    {
        $this->href = $href;
    }

    /**
     * Gets the rel of the atomLink.
     *
     * @return string
     */
    public function getRel()
    {
        return $this->rel;
    }

    /**
     * Sets the rel of the link.
     *
     * @param string $rel The rel of the atomLink.
     *
     * @return none
     */
    public function setRel($rel)
    {
        $this->rel = $rel;
    }

    /**
     * Gets the type of the link.
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Sets the type of the link.
     *
     * @param string $type The type of the link.
     *
     * @return none
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Gets the language of the href.
     *
     * @return string
     */
    public function getHrefLang()
    {
        return $this->hrefLang;
    }

    /**
     * Sets the language of the href.
     *
     * @param string $hrefLang The language of the href.
     *
     * @return none
     */
    public function setHrefLang($hrefLang)
    {
        $this->hrefLang = $hrefLang;
    }

    /**
     * Gets the title of the link.
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Sets the title of the link.
     *
     * @param string $title The title of the link.
     *
     * @return none
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Gets the length of the link.
     *
     * @return string
     */
    public function getLength()
    {
        return $this->length;
    }

    /**
     * Sets the length of the link.
     *
     * @param string $length The length of the link.
     *
     * @return none
     */
    public function setLength($length)
    {
        $this->length = $length;
    }

    /**
     * Gets the undefined content.
     *
     * @return string
     */
    public function getUndefinedContent()
    {
        return $this->undefinedContent;
    }

    /**
     * Sets the undefined content.
     *
     * @param string $undefinedContent The undefined content.
     *
     * @return none
     */
    public function setUndefinedContent($undefinedContent)
    {
        $this->undefinedContent = $undefinedContent;
    }

    /**
     * Writes an XML representing the ATOM link item.
     *
     * @param \XMLWriter $xmlWriter The xml writer.
     *
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom',
            Resources::LINK,
            Resources::ATOM_NAMESPACE
        );
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /**
     * Writes the inner XML representing the ATOM link item.
     *
     * @param \XMLWriter $xmlWriter The xml writer.
     *
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');

        $this->writeOptionalAttribute($xmlWriter, 'href', $this->href);
        $this->writeOptionalAttribute($xmlWriter, 'rel', $this->rel);
        $this->writeOptionalAttribute($xmlWriter, 'type', $this->type);
        $this->writeOptionalAttribute($xmlWriter, 'hreflang', $this->hreflang);
        $this->writeOptionalAttribute($xmlWriter, 'title', $this->title);
        $this->writeOptionalAttribute($xmlWriter, 'length', $this->length);

        if (!empty($this->undefinedContent)) {
            $xmlWriter->writeRaw($this->undefinedContent);
        }

    }
}


text:
package cn.felord.wepay.ali.sdk.api.domain;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;

/**
 * 教育缴费账单状态同步接口
 *
 * @author auto create
 * @version $Id: $Id
 */
public class AlipayEcoEduKtBillingModifyModel extends AlipayObject {

	private static final long serialVersionUID = 2322985251743655438L;

	/**
	 * 退款时,支付宝返回的用户的登录id
	 */
	@ApiField("buyer_logon_id")
	private String buyerLogonId;

	/**
	 * 支付宝返回的买家支付宝用户id
	 */
	@ApiField("buyer_user_id")
	private String buyerUserId;

	/**
	 * 本次退款是否发生了资金变化
	 */
	@ApiField("fund_change")
	private String fundChange;

	/**
	 * 支付宝返回的退款时间,而不是商户退款申请的时间
	 */
	@ApiField("gmt_refund")
	private String gmtRefund;

	/**
	 * 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
	 */
	@ApiField("out_request_no")
	private String outRequestNo;

	/**
	 * isv系统的订单号
	 */
	@ApiField("out_trade_no")
	private String outTradeNo;

	/**
	 * 需要退款的金额,该金额不能大于订单金额,单位为元,支持两位小数
	 */
	@ApiField("refund_amount")
	private String refundAmount;

	/**
	 * 支付宝返回的退款资金渠道,json格式字符串
	 */
	@ApiField("refund_detail_item_list")
	private String refundDetailItemList;

	/**
	 * 退款原因,商家根据客户实际退款原因填写
	 */
	@ApiField("refund_reason")
	private String refundReason;

	/**
	 * 状态:1:缴费成功,2:关闭账单,3、退费
如果为退款状态,需要填写以下字段,字段都是支付宝退款返回的必填参数
	 */
	@ApiField("status")
	private String status;

	/**
	 * 支付宝返回的交易号
	 */
	@ApiField("trade_no")
	private String tradeNo;

	/**
	 *
Getter for the field buyerLogonId.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getBuyerLogonId() {
		return this.buyerLogonId;
	}
	/**
	 *
Setter for the field buyerLogonId.

	 *
	 * @param buyerLogonId a {@link java.lang.String} object.
	 */
	public void setBuyerLogonId(String buyerLogonId) {
		this.buyerLogonId = buyerLogonId;
	}

	/**
	 *
Getter for the field buyerUserId.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getBuyerUserId() {
		return this.buyerUserId;
	}
	/**
	 *
Setter for the field buyerUserId.

	 *
	 * @param buyerUserId a {@link java.lang.String} object.
	 */
	public void setBuyerUserId(String buyerUserId) {
		this.buyerUserId = buyerUserId;
	}

	/**
	 *
Getter for the field fundChange.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getFundChange() {
		return this.fundChange;
	}
	/**
	 *
Setter for the field fundChange.

	 *
	 * @param fundChange a {@link java.lang.String} object.
	 */
	public void setFundChange(String fundChange) {
		this.fundChange = fundChange;
	}

	/**
	 *
Getter for the field gmtRefund.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getGmtRefund() {
		return this.gmtRefund;
	}
	/**
	 *
Setter for the field gmtRefund.

	 *
	 * @param gmtRefund a {@link java.lang.String} object.
	 */
	public void setGmtRefund(String gmtRefund) {
		this.gmtRefund = gmtRefund;
	}

	/**
	 *
Getter for the field outRequestNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOutRequestNo() {
		return this.outRequestNo;
	}
	/**
	 *
Setter for the field outRequestNo.

	 *
	 * @param outRequestNo a {@link java.lang.String} object.
	 */
	public void setOutRequestNo(String outRequestNo) {
		this.outRequestNo = outRequestNo;
	}

	/**
	 *
Getter for the field outTradeNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOutTradeNo() {
		return this.outTradeNo;
	}
	/**
	 *
Setter for the field outTradeNo.

	 *
	 * @param outTradeNo a {@link java.lang.String} object.
	 */
	public void setOutTradeNo(String outTradeNo) {
		this.outTradeNo = outTradeNo;
	}

	/**
	 *
Getter for the field refundAmount.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getRefundAmount() {
		return this.refundAmount;
	}
	/**
	 *
Setter for the field refundAmount.

	 *
	 * @param refundAmount a {@link java.lang.String} object.
	 */
	public void setRefundAmount(String refundAmount) {
		this.refundAmount = refundAmount;
	}

	/**
	 *
Getter for the field refundDetailItemList.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getRefundDetailItemList() {
		return this.refundDetailItemList;
	}
	/**
	 *
Setter for the field refundDetailItemList.

	 *
	 * @param refundDetailItemList a {@link java.lang.String} object.
	 */
	public void setRefundDetailItemList(String refundDetailItemList) {
		this.refundDetailItemList = refundDetailItemList;
	}

	/**
	 *
Getter for the field refundReason.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getRefundReason() {
		return this.refundReason;
	}
	/**
	 *
Setter for the field refundReason.

	 *
	 * @param refundReason a {@link java.lang.String} object.
	 */
	public void setRefundReason(String refundReason) {
		this.refundReason = refundReason;
	}

	/**
	 *
Getter for the field status.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getStatus() {
		return this.status;
	}
	/**
	 *
Setter for the field status.

	 *
	 * @param status a {@link java.lang.String} object.
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 *
Getter for the field tradeNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTradeNo() {
		return this.tradeNo;
	}
	/**
	 *
Setter for the field tradeNo.

	 *
	 * @param tradeNo a {@link java.lang.String} object.
	 */
	public void setTradeNo(String tradeNo) {
		this.tradeNo = tradeNo;
	}

}


text:
s = 'this string is %d characters long'

## We can apply values to a string with an expression that goes:
## string % value(s)
## if there's more than one, put them in ()'s with commas between!

## Go ahead and compute the length of s and substitute it into the string:

print 'Use the operator luke!'

# conversion
## Adding a string and a number together doesn't make sense... for example,
## what's the right thing to do for '1.0' + 2? Let's explore both ways that
## could go. First, we need to do the conversion ourselves. Remember, you can
## use the type functions to do that, in this case, str() and float() - int()
## would lose the decimal point that is clearly there for a reason!

print 'as "added" strings'

print 'as added numbers'


text:
package log

import (
	"io"
	"log"
)

// Log levels
const (
	TRACE = iota // 0
	DEBUG = iota // 1
	INFO  = iota // 2
	WARN  = iota // 3
	ERROR = iota // 4
)

// Level set for logs
var Level = TRACE

// SetLevel sets the log level
// given a string
func SetLevel(level string) {
	switch level {
	case "TRACE":
		Level = TRACE
	case "DEBUG":
		Level = DEBUG
	case "INFO":
		Level = INFO
	case "WARN":
		Level = WARN
	case "ERROR":
		Level = ERROR
	default:
		Level = TRACE
	}
}

// SetOutput set the output destination
// of logs
func SetOutput(w io.Writer) {
	log.SetOutput(w)
}

// Tracef writes a formatted log on TRACE level
func Tracef(format string, v ...interface{}) {
	if Level <= TRACE {
		log.Printf("[TRACE] "+format, v...)
	}
}

// Trace writes a log on TRACE level
func Trace(s string) {
	Tracef(s)
}

// Debugf writes a formatted log on DEBUG level
func Debugf(format string, v ...interface{}) {
	if Level <= DEBUG {
		log.Printf("[DEBUG] "+format, v...)
	}
}

// Debug writes a log on DEBUG level
func Debug(s string) {
	Debugf(s)
}

// Infof writes a formatted log on INFO level
func Infof(format string, v ...interface{}) {
	if Level <= INFO {
		log.Printf("[INFO ] "+format, v...)
	}
}

// Info write a log on INFO level
func Info(s string) {
	Infof(s)
}

// Warnf writes a formatted log on WARN level
func Warnf(format string, v ...interface{}) {
	if Level <= WARN {
		log.Printf("[WARN ] "+format, v...)
	}
}

// Warn write a log on WARN level
func Warn(s string) {
	Warnf(s)
}

// Errorf writes a formatted log on ERROR level
func Errorf(format string, v ...interface{}) {
	if Level <= ERROR {
		log.Printf("[ERROR] "+format, v...)
	}
}

// Error write a log on ERROR level
func Error(s string) {
	Errorf(s)
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.nanocontainer</groupId>
        <artifactId>nanocontainer-parent</artifactId>
        <version>1.2-SNAPSHOT</version>
    </parent>
    <artifactId>nanocontainer-jruby</artifactId>
    <name>NanoContainer JRuby</name>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>${pom.groupId}</groupId>
            <artifactId>nanocontainer</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- test scoped dependencies -->
        <dependency>
            <groupId>${pom.groupId}</groupId>
            <artifactId>nanocontainer-tck</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>${pom.groupId}</groupId>
            <artifactId>nanocontainer-testmodel</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
package org.eclipse.moquette.interception;

import org.eclipse.moquette.proto.messages.ConnectMessage;
import org.eclipse.moquette.proto.messages.PublishMessage;
import org.eclipse.moquette.spi.impl.subscriptions.Subscription;

/**
 * This interface is to be used internally by the broker components.
 *

 * An interface is used instead of a class to allow more flexibility in changing
 * an implementation.
 *

 * Interceptor implementations forward notifications to a InterceptHandler,
 * that is normally a field. So, the implementations should act as a proxy to a custom
 * intercept handler.
 *
 * @see InterceptHandler
 * @author Wagner Macedo
 */
public interface Interceptor {

    void notifyClientConnected(ConnectMessage msg);

    void notifyClientDisconnected(String clientID);

    void notifyTopicPublished(PublishMessage msg, String clientID);

    void notifyTopicSubscribed(Subscription sub);

    void notifyTopicUnsubscribed(String topic, String clientID);

}


text:
class GameMessage {
	std::string m_RequestType;
	std::map<std::string, std::string> m_RequestData;
public:
	const std::string & GetType() const;

	void Serialize(std::ostream & os);

	void SetType(const std::string &type);

	void Add(const std::string & key, const std::string & value);

	void Deserialize(std::istream & is);

	std::string Get(const std::string &key);
};


text:
package gov.nih.nci.clinicalconnector.service;

import java.rmi.RemoteException;

import javax.xml.namespace.QName;

import org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse;
import org.oasis.wsrf.properties.GetMultipleResourceProperties_Element;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.oasis.wsrf.properties.QueryResourcePropertiesResponse;
import org.oasis.wsrf.properties.QueryResourceProperties_Element;

import gov.nih.nci.cabig.ccts.domain.Registration;
import gov.nih.nci.clinicalconnector.common.ClinicalConnectorI;
//gov.nih.nci.ccts.grid.common.RegistrationConsumerI;
import gov.nih.nci.ccts.grid.stubs.types.InvalidRegistrationException;
import gov.nih.nci.ccts.grid.stubs.types.RegistrationConsumptionException;

public abstract class AbstractRegistrationConsumerImpl implements ClinicalConnectorI{

	public void commit(Registration registration) throws RemoteException,
			InvalidRegistrationException {
		// TODO Auto-generated method stub

	}

	public GetMultipleResourcePropertiesResponse getMultipleResourceProperties(
			GetMultipleResourceProperties_Element params)
			throws RemoteException {
		// TODO Auto-generated method stub
		return null;
	}

	public GetResourcePropertyResponse getResourceProperty(QName arg0)
			throws RemoteException {
		// TODO Auto-generated method stub
		return null;
	}

	public QueryResourcePropertiesResponse queryResourceProperties(
			QueryResourceProperties_Element arg0) throws RemoteException {
		// TODO Auto-generated method stub
		return null;
	}

	public abstract Registration register(Registration registration)
			throws RemoteException, InvalidRegistrationException,
			RegistrationConsumptionException ;

	public void rollback(Registration registration) throws RemoteException,
			InvalidRegistrationException {
		// TODO Auto-generated method stub

	}

}