text:
import unittest
import StringIO
import re
from resync.resource import Resource
from resync.resource_list import ResourceList, ResourceListDupeError
from resync.sitemap import SitemapParseError

class TestResourceList(unittest.TestCase):

    def test01_same(self):
        src = ResourceList()
        src.add( Resource('a',timestamp=1) )
        src.add( Resource('b',timestamp=2) )
        dst = ResourceList()
        dst.add( Resource('a',timestamp=1) )
        dst.add( Resource('b',timestamp=2) )
        ( same, changed, deleted, added ) = dst.compare(src)
        self.assertEqual( len(same), 2, "2 things unchanged" )
        i = iter(same)
        self.assertEqual( i.next().uri, 'a', "first was a" )
        self.assertEqual( i.next().uri, 'b', "second was b" )
        self.assertEqual( len(changed), 0, "nothing changed" )
        self.assertEqual( len(deleted), 0, "nothing deleted" )
        self.assertEqual( len(added), 0, "nothing added" )

    def test02_changed(self):
        src = ResourceList()
        src.add( Resource('a',timestamp=1) )
        src.add( Resource('b',timestamp=2) )
        dst = ResourceList()
        dst.add( Resource('a',timestamp=3) )
        dst.add( Resource('b',timestamp=4) )
        ( same, changed, deleted, added ) = dst.compare(src)
        self.assertEqual( len(same), 0, "0 things unchanged" )
        self.assertEqual( len(changed), 2, "2 things changed" )
        i = iter(changed)
        self.assertEqual( i.next().uri, 'a', "first was a" )
        self.assertEqual( i.next().uri, 'b', "second was b" )
        self.assertEqual( len(deleted), 0, "nothing deleted" )
        self.assertEqual( len(added), 0, "nothing added" )

    def test03_deleted(self):
        src = ResourceList()
        src.add( Resource('a',timestamp=1) )
        src.add( Resource('b',timestamp=2) )
        dst = ResourceList()
        dst.add( Resource('a',timestamp=1) )
        dst.add( Resource('b',timestamp=2) )
        dst.add( Resource('c',timestamp=3) )
        dst.add( Resource('d',timestamp=4) )
        ( same, changed, deleted, added ) = dst.compare(src)
        self.assertEqual( len(same), 2, "2 things unchanged" )
        self.assertEqual( len(changed), 0, "nothing changed" )
        self.assertEqual( len(deleted), 2, "c and d deleted" )
        i = iter(deleted)
        self.assertEqual( i.next().uri, 'c', "first was c" )
        self.assertEqual( i.next().uri, 'd', "second was d" )
        self.assertEqual( len(added), 0, "nothing added" )

    def test04_added(self):
        src = ResourceList()
        src.add( Resource('a',timestamp=1) )
        src.add( Resource('b',timestamp=2) )
        src.add( Resource('c',timestamp=3) )
        src.add( Resource('d',timestamp=4) )
        dst = ResourceList()
        dst.add( Resource('a',timestamp=1) )
        dst.add( Resource('c',timestamp=3) )
        ( same, changed, deleted, added ) = dst.compare(src)
        self.assertEqual( len(same), 2, "2 things unchanged" )
        self.assertEqual( len(changed), 0, "nothing changed" )
        self.assertEqual( len(deleted), 0, "nothing deleted" )
        self.assertEqual( len(added), 2, "b and d added" )
        i = iter(added)
        self.assertEqual( i.next().uri, 'b', "first was b" )
        self.assertEqual( i.next().uri, 'd', "second was d" )

    def test05_add(self):
        r1 = Resource(uri='a',length=1)
        r2 = Resource(uri='b',length=2)
        i = ResourceList()
        i.add(r1)
        self.assertRaises( ResourceListDupeError, i.add, r1)
        i.add(r2)
        self.assertRaises( ResourceListDupeError, i.add, r2)
        # allow dupes
        r1d = Resource(uri='a',length=10)
        i.add(r1d,replace=True)
        self.assertEqual( len(i), 2 )
        self.assertEqual( i.resources['a'].length, 10 )

    def test06_add_iterable(self):
        r1 = Resource(uri='a',length=1)
        r2 = Resource(uri='b',length=2)
        i = ResourceList()
        i.add( [r1,r2] )
        self.assertRaises( ResourceListDupeError, i.add, r1)
        self.assertRaises( ResourceListDupeError, i.add, r2)
        # allow dupes
        r1d = Resource(uri='a',length=10)
        i.add( [r1d] ,replace=True)
        self.assertEqual( len(i), 2 )
        self.assertEqual( i.resources['a'].length, 10 )

    def test07_has_md5(self):
        r1 = Resource(uri='a')
        r2 = Resource(uri='b')
        i = ResourceList()
        self.assertFalse( i.has_md5() )
        i.add(r1)
        i.add(r2)
        self.assertFalse( i.has_md5() )
        r1.md5="aabbcc"
        self.assertTrue( i.has_md5() )

    def test08_iter(self):
        i = ResourceList()
        i.add( Resource('a',timestamp=1) )
        i.add( Resource('b',timestamp=2) )
        i.add( Resource('c',timestamp=3) )
        i.add( Resource('d',timestamp=4) )
        resources=[]
        for r in i:
            resources.append(r)
        self.assertEqual(len(resources), 4)
        self.assertEqual( resources[0].uri, 'a')
        self.assertEqual( resources[3].uri, 'd')

    def test20_as_xml(self):
        rl = ResourceList()
        rl.add( Resource('a',timestamp=1) )
        rl.add( Resource('b',timestamp=2) )
        xml = rl.as_xml()
        print xml
        self.assertTrue( re.search(r'<rs:md .*capability="resourcelist"', xml), 'XML has capability' )
        self.assertTrue( re.search(r'<url><loc>a</loc><lastmod>1970-01-01T00:00:01Z</lastmod></url>', xml), 'XML has resource a' )

    def test30_parse(self):
        xml='<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n\
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:rs="http://www.openarchives.org/rs/terms/">\
<rs:md at="2013-08-07" capability="resourcelist" completed="2013-08-08" />\
<url><loc>/tmp/rs_test/src/file_a</loc><lastmod>2012-03-14T18:37:36Z</lastmod><rs:md change="updated" length="12" /></url>\
<url><loc>/tmp/rs_test/src/file_b</loc><lastmod>2012-03-14T18:37:36Z</lastmod><rs:md length="32" /></url>\
</urlset>'
        rl=ResourceList()
        rl.parse(fh=StringIO.StringIO(xml))
        self.assertEqual( len(rl.resources), 2, 'got 2 resources')
        self.assertEqual( rl.md['capability'], 'resourcelist', 'capability set' )
        self.assertEqual( rl.md_at, '2013-08-07' )
        self.assertEqual( rl.md_completed, '2013-08-08' )

    def test31_parse_no_capability(self):
        xml='<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n\
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\
<url><loc>http://example.com/res1</loc><lastmod>2012-03-14T18:37:36Z</lastmod></url>\
</urlset>'
        rl=ResourceList()
        rl.parse(fh=StringIO.StringIO(xml))
        self.assertEqual( len(rl.resources), 1, 'got 1 resource')
        self.assertEqual( rl.md['capability'], 'resourcelist', 'capability set by reading routine' )
        self.assertFalse( 'from' in rl.md )

    def test32_parse_bad_capability(self):
        # the <rs:md capability="bad_capability".. should give error
        xml='<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n\
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:rs="http://www.openarchives.org/rs/terms/">\
<rs:md capability="bad_capability" from="2013-01-01"/>\
<url><loc>http://example.com/bad_res_1</loc><lastmod>2012-03-14T18:37:36Z</lastmod></url>\
</urlset>'
        rl=ResourceList()
        self.assertRaises( SitemapParseError, rl.parse, fh=StringIO.StringIO(xml) )

if __name__ == '__main__':
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestResourceList)
    unittest.TextTestRunner().run(suite)


text:
FROM ubuntu:14.04
MAINTAINER Sascha Ishikawa <sascha@zooniverse.org>
WORKDIR /planetary-response-network
ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update && apt-get -y upgrade && \
    apt-get install --no-install-recommends -y ca-certificates sudo git curl bash-completion vim-tiny supervisor ghostscript imagemagick libgdal-dev libimage-exiftool-perl make g++ python
RUN curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
RUN apt-get install --no-install-recommends -y nodejs && apt-get clean

# Language setup
RUN locale-gen  fr_FR.UTF-8 en_US.UTF-8
RUN update-locale LANG=en_US.UTF-8

# Common alias
RUN alias ls='ls --color=auto'
RUN alias ll='ls -halF'

ADD supervisord.conf /etc/supervisor/supervisord.conf
ADD ./ /planetary-response-network

RUN npm install .

EXPOSE 3736
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
# CMD ["echo", "hello there!"]

# # Gdal binary crashes on mac VM, so build from scratch by running this on the instance:
# apt-get install --no-install-recommends -y libgdal-dev && \
#   npm install gdal --build-from-source --shared_gdal

redpajama_set_name: RedPajamaGithub


text:
namespace BlogEngine.Core.Web.HttpHandlers
{
    using System;
    using System.Net;
    using System.Web;

    /// <summary>
    /// Removes whitespace in all stylesheets added to the
    ///     header of the HTML document in site.master.
    /// </summary>
    /// <remarks>
    ///
    /// This handler uses an external library to perform minification of scripts.
    /// See the BlogEngine.Core.JavascriptMinifier class for more details.
    ///
    /// </remarks>
    public class JavaScriptHandler : IHttpHandler
    {
        #region Properties

        /// <summary>
        ///     Gets a value indicating whether another request can use the <see cref = "T:System.Web.IHttpHandler"></see> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref = "T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.</returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region IHttpHandler

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom
        ///     HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">
        /// An <see cref="T:System.Web.HttpContext"></see> object that provides
        ///     references to the intrinsic server objects
        ///     (for example, Request, Response, Session, and Server) used to service HTTP requests.
        /// </param>
        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            string fileName = request.FilePath;
            fileName = fileName.Substring(Utils.RelativeWebRoot.Length);

            string resKey = "";
            string script = "";

            if (fileName.StartsWith("res-"))
            {
                resKey = fileName.Substring(4);
                resKey = resKey.Substring(0, resKey.IndexOf("."));

                if (Blog.CurrentInstance.Cache[resKey] != null)
                {
                    script = (string)Blog.CurrentInstance.Cache[resKey];
                }
            }

            SetHeaders(script.GetHashCode(), context);
            context.Response.Write(script);
        }

        #endregion

        #region Methods

        /// <summary>
        /// This will make the browser and server keep the output
        ///     in its cache and thereby improve performance.
        /// </summary>
        /// <param name="hash">
        /// The hash number.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        private static void SetHeaders(int hash, HttpContext context)
        {
            var response = context.Response;
            response.ContentType = "text/javascript";
            var cache = response.Cache;

            cache.VaryByHeaders["Accept-Encoding"] = true;
            cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(7));
            cache.SetMaxAge(new TimeSpan(30, 0, 0, 0));
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            var etag = string.Format("\"{0}\"", hash);
            var incomingEtag = context.Request.Headers["If-None-Match"];

            //cache.SetETag(etag);
            cache.SetCacheability(HttpCacheability.Public);

            if (String.Compare(incomingEtag, etag) != 0)
            {
                return;
            }

            response.Clear();
            response.StatusCode = (int)HttpStatusCode.NotModified;
            response.SuppressContent = true;
        }

        #endregion
    }
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] 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 EnsEMBL::Draw::Style::Graph;

=pod
Renders a track as a graph or continuous plot

This module expects data in the following format:

  $data = [
          {'metadata' => {},
           'features'  => [
              {
              'start'         => 123456,
              'end'           => 123789,
              'colour'        => 'red',                             # mandatory unless bordercolour set
              'bordercolour'  => 'black',                           # optional
              'label'         => 'Feature 1',                       # optional
              'label_colour'  => 'red',                             # optional
              'href'          => '/Location/View?r=123456-124789',  # optional
              'title'         => 'Some text goes here',             # optional
              },
            ],
          ];

Note that in order to support multiple subtracks within a glyphset (whether multi-wiggle or separate), we must pass an array of hashes with optional metadata for each subtrack

=cut

use strict;
use warnings;
no warnings 'uninitialized';

use List::Util qw(min max);

use parent qw(EnsEMBL::Draw::Style);

sub create_glyphs {
### Create all the glyphs required by this style
### @return ArrayRef of EnsEMBL::Web::Glyph objects
  my $self = shift;

  my $data            = $self->data;
  my $track_config    = $self->track_config;

  my $graph_conf    = {};
  my $multi_wiggle  = $track_config->get('multi');
  if ($multi_wiggle) {
    # Merge metadata of subtracks
    my $metadata = $data->[0]{'metadata'};
    $metadata->{'max_score'} =
      max(map { $_->{'metadata'}{'max_score'} } @$data);
    $metadata->{'min_score'} =
      min(map { $_->{'metadata'}{'min_score'} } @$data);

    ## Draw any axes, track labels, etc
    $graph_conf = $self->draw_graph_base($metadata);
  }

  my $height   = $track_config->get('height');

  foreach my $subtrack (@$data) {
    my $metadata = $subtrack->{'metadata'} || {};
    my $features = $subtrack->{'features'};

    unless ($multi_wiggle) {
      ## Draw any axes, track labels, etc
      $graph_conf = $self->draw_graph_base($metadata);
    }

    ## Set cutoff point for top of graph if we have one
    if (defined($self->{'cutoff'})) {
      $graph_conf->{'cutoff_max'} = $self->{'cutoff'};
    }
    elsif (defined($metadata->{'y_max'})) {
      $graph_conf->{'cutoff_max'} = $metadata->{'y_max'};
    }

    if (defined($metadata->{'y_min'})) {
      $graph_conf->{'cutoff_min'} = $metadata->{'y_min'};
    }

    ## Single line? Build into singleton set.
    $features = [ $features ] if ref $features ne 'ARRAY';

    ## Work out a default colour
    my $colour = $track_config->get('colour')
                  || $subtrack->{'metadata'}{'colour'}
                  || $subtrack->{'metadata'}{'color'}; ## default

    ## Select a colour to indicate truncated values
    my $truncate_colour = ($colour eq 'black' || $colour eq '0,0,0') ? 'red' : 'black';

    ## Draw them!
    my $plot_conf = {
      height          => $height,
      pix_per_score   => $track_config->get('pix_per_score'),
      default_strand  => $track_config->get('default_strand'),
      unit            => $subtrack->{'metadata'}{'unit'},
      graph_type      => $subtrack->{'metadata'}{'graphType'} || $track_config->get('graph_type'),
      colour          => $colour,
      truncate_colour => $truncate_colour,
      colours         => $subtrack->{'metadata'}{'gradient'},
      alt_colour      => $subtrack->{'metadata'}{'altColor'},
      %$graph_conf,
    };

    ## Determine absolute positioning for graph
    $plot_conf->{'absolute_xy'} = {'absolutey' => 1};
    ## Absolutex is weird and finicky - some graphs won't show if it's even defined
    if ($track_config->get('absolutex')) {
      $plot_conf->{'absolute_xy'}{'absolutex'} = 1;
    }

    $self->draw_wiggle($plot_conf, $features);
    $self->draw_hidden_bgd($height);
  }
  ## Only add height once, as we superimpose subtracks on a graph
  my $total_height = $track_config->get('total_height') || 0;
  $track_config->set('total_height', $total_height + $height);

  return @{$self->glyphs||[]};
}

########## DRAW INDIVIDUAL GLYPHS ###################

####### FEATURES ##################

sub draw_wiggle {
  my ($self, $c, $features) = @_;

  return unless $features && @$features;

  my $slice_length  = $self->image_config->container_width;
  if(ref($features->[0]) eq 'HASH') {
    $features = [ sort { $a->{'start'} <=> $b->{'start'} } @$features ];
  }
  my ($previous_x,$previous_y);
  my $plain_x = 0;

  for (my $i = 0; $i < @$features; $i++) {
    my $f = $features->[$i];
    unless(ref($f) eq 'HASH') {
      # Plain old value
      $f = {
        start => $plain_x,
        end => $plain_x+$c->{'unit'},
        score => $f,
      };
      $plain_x += $c->{'unit'};
    }
    my ($current_x,$current_score);
    $current_x     = ($f->{'end'} + $f->{'start'}) / 2;
    next unless $current_x <= $slice_length;

    $current_score = $f->{'score'};
    my ($colour, $ok_score);
    if ($current_score =~ /INF/) {
      $colour   = 'black';
      $ok_score = $current_score eq '-INF' ? $c->{'min_score'} : $c->{'max_score'};
    }
    elsif (defined($c->{'cutoff_min'}) && $c->{'cutoff_min'} ne '' && $current_score < $c->{'cutoff_min'}) {
      $ok_score = $c->{'cutoff_min'};
    }
    elsif (defined($c->{'cutoff_max'})  && $c->{'cutoff_max'} ne '' && $current_score > $c->{'cutoff_max'}) {
      $ok_score = $c->{'cutoff_max'};
    }
    else {
      $colour   = $self->set_colour($c, $f);
      $ok_score = $current_score;
    }
    my $current_y = $c->{'line_px'} - ($ok_score - $c->{'line_score'}) * $c->{'pix_per_score'};

    if(defined $previous_x) {
      push @{$self->glyphs}, $self->Line({
                                            x         => $current_x,
                                            y         => $current_y,
                                            width     => $previous_x - $current_x,
                                            height    => $previous_y - $current_y,
                                            colour    => $colour,
                                            absolutey => 1,
                                        });
    }

    $previous_x = $current_x;
    $previous_y = $current_y;
  }
}

####### AXES AND LABELS ###########

sub draw_axes {
### Axes for the graph
  my ($self, $top, $zero, $bottom, $slice_length) = @_;

  ## horizontal line
  my $params = {
                x         => 0,
                y         => $zero,
                width     => $slice_length,
                height    => 0,
                absolutey => 1,
                colour    => $self->track_config->get('axis_colour') || 'red',
                dotted    => $self->track_config->get('graph_type') eq 'line' ? 0 : 1,
  };
  push @{$self->glyphs}, $self->Line($params);

  ## vertical line
  $params->{'y'}          = $top;
  $params->{'width'}      = 0;
  $params->{'height'}     = $bottom - $top;
  $params->{'absolutex'}  = 1;
  push @{$self->glyphs}, $self->Line($params);
}

sub set_colour {
### Make final decision on feature colour before drawing it
### @param c Hashref - track configuration
### @param f Hashref - feature
### @return String - colour of feature
  my ($self, $c, $f) = @_;
  my $cutoff = $c->{'alt_colour_cutoff'} || 0;
  my $colour = ($c->{'alt_colour'} && $f->{'score'} < $cutoff)
                  ? $c->{'alt_colour'} : $f->{'colour'};
  $colour ||= $c->{'colour'};
  $colour ||= 'black';
  return $colour;
}

sub draw_score {
### Max and min scores on axes
  my ($self, $y, $value) = @_;

  my $text      = $self->track_config->get('integer_score') ? int($value) : sprintf('%.2f',$value);
  my $text_info = $self->get_text_info($text);
  my $width     = $text_info->{'width'};
  my $height    = $text_info->{'height'};
  my $colour    = 'black';

  my %params = (
    absolutey     => 1,
    absolutex     => 1,
    absolutewidth => 1,
    colour        => $colour,
  );

  ## Score label - make it slightly smaller than other labels
  push @{$self->glyphs}, $self->Text({
                                      text        => $text,
                                      height      => $height,
                                      width       => $width,
                                      x           => -8 - $width,
                                      y           => $y - $height * 0.75,
                                      textwidth   => $width * 0.9,
                                      halign      => 'right',
                                      font        => $self->{'font_name'},
                                      ptsize      => $self->{'font_size'} * 0.9,
                                      %params
                                    });

  ## 'Tick' on y-axis
  push @{$self->glyphs}, $self->Rect({
                                      height        => 0,
                                      width         => 5,
                                      y             => $y,
                                      x             => -8,
                                      %params
                                    });
}

sub draw_guideline {
  my ($self, $width, $y, $type) = @_;

  $type ||= '1';
  push @{$self->glyphs}, $self->Line({
                                        x         => 0,
                                        y         => $y,
                                        width     => $width,
                                        height    => 1,
                                        colour    => 'grey90',
                                        absolutey => 1,
                                        dotted => $type,
                                      });
}

sub add_minilabel {}

1;


text:
package xyz.nabijaczleweli.scala_game_of_life.util

import scala.swing.{Point, Color}
import java.awt.image._
import java.awt.{PaintContext, RenderingHints, Rectangle}
import java.awt.geom.{AffineTransform, Rectangle2D}
import scala.util.Random

/** @author Jędrzej
  * @since  15.05.14
  */
class ColorRainbow(val maxR: Int = 256, val maxG: Int = 256, val maxB: Int = 256, val alpha: Int = 255) extends Color(0) {
	private val rand = new Random

	override def createContext(cm: ColorModel, r: Rectangle, r2d: Rectangle2D, xform: AffineTransform, hints: RenderingHints) =
		new PaintContext {
			override def getRaster(x: Int, y: Int, w: Int, h: Int): Raster = {
				val arr = Array.fill(w * h)(getRGB)
				Raster.createRaster(new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, w, h, arr), new DataBufferInt(arr, arr.length), new Point(x, y))
			}

			override def getColorModel =
				ColorModel.getRGBdefault

			override def dispose() {}
		}

	override def getRed =
		rand nextInt maxR

	override def getGreen =
		rand nextInt maxG

	override def getBlue =
		rand nextInt maxB

	override def getAlpha =
		alpha

	// aaaaaaaarrrrrrrrggggggggbbbbbbbb
	override def getRGB =
		(getAlpha << 24) | (getRed <<  16) | (getGreen << 8) | getBlue
}


text:
BEGIN_REPLICANT_NAMESPACE

class pending_defended_call : public pending_robust
{
    public:
        pending_defended_call(int64_t id,
                              const char* object,
                              const char* enter_func,
                              const char* enter_input, size_t enter_input_sz,
                              const char* exit_func,
                              const char* exit_input, size_t exit_input_sz,
                              replicant_returncode* status);
        virtual ~pending_defended_call() throw ();

    public:
        virtual std::auto_ptr<e::buffer> request(uint64_t nonce);
        virtual bool resend_on_failure();
        virtual void handle_response(client* cl,
                                     std::auto_ptr<e::buffer> msg,
                                     e::unpacker up);

    private:
        const std::string m_object;
        const std::string m_enter_func;
        const std::string m_enter_input;
        const std::string m_exit_func;
        const std::string m_exit_input;

    private:
        pending_defended_call(const pending_defended_call&);
        pending_defended_call& operator = (const pending_defended_call&);
};

END_REPLICANT_NAMESPACE

#endif // replicant_client_pending_defended_call_h_


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

namespace Utilities.Extensions
{
    public static class EnumerableExtension
    {
        public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> list)
        {
            if (list == null)
                return null;
            return list.Where(x => !EqualityComparer<T>.Default.Equals(x, default (T)));
        }

        public static List<T> InList<T>(this T item)
        {
            return new List<T> {item};
        }

        public static List<T> WithItems<T>(this List<T> list, params T[] items)
        {
            list.AddRange(items);
            return list;
        }

        public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T toReplace, T replaceWith)
        {
            return source.Select(item => Equals(item, toReplace) ? replaceWith : item);
        }

        public static IEnumerable<TResult> SelectManySafe<TSource, TResult>(this IEnumerable<TSource> source,
            Func<TSource, IEnumerable<TResult>> selector)
        {
            Contract.Requires(source != null);
            Contract.Requires(selector != null);

            return source.Select(selector).WhereNotNull().SelectMany(x => x);
        }

        public static ICollection<T> Takes<T>(this ICollection<T> source, Func<IEnumerable<T>, IEnumerable<T>> filter)
        {
            Contract.Requires(source != null);
            Contract.Requires(filter != null);

            List<T> result = filter(source).ToList();
            source = source.Except(result).ToList();
            return result;
        }

        public static IEnumerable<T> Aggregate<T>(this IEnumerable<T> source, int following,
            Func<IEnumerable<T>, T> aggregate)
        {
            Contract.Requires(source != null);
            Contract.Requires(aggregate != null);

            IEnumerable<T> enumerable = source as IList<T> ?? source.ToList();
            for (int cpt = 0; enumerable.Count() > cpt; cpt += following)
                yield return aggregate(enumerable.Skip(cpt).Take(following));
        }

        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
        {
            return new HashSet<T>(source);
        }

        public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
        {
            if (items == null) throw new ArgumentNullException("items");
            if (predicate == null) throw new ArgumentNullException("predicate");

            int retVal = 0;

            foreach (T item in items)
            {
                if (predicate(item)) return retVal;
                retVal++;
            }

            return -1;
        }

        public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            return source.MaxBy(selector, Comparer<TKey>.Default);
        }

        public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector,
            IComparer<TKey> comparer)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (selector == null) throw new ArgumentNullException("selector");
            if (comparer == null) throw new ArgumentNullException("comparer");

            using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
            {
                if (!sourceIterator.MoveNext()) throw new InvalidOperationException("Sequence contains no elements");
                TSource max = sourceIterator.Current;
                TKey maxKey = selector(max);
                while (sourceIterator.MoveNext())
                {
                    TSource candidate = sourceIterator.Current;
                    TKey candidateProjected = selector(candidate);

                    if (comparer.Compare(candidateProjected, maxKey) <= 0) continue;
                    max = candidate;
                    maxKey = candidateProjected;
                }

                return max;
            }
        }

        //public static IDictionary<TKey, TElement> ToMyDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
        //{
        //    IEqualityComparer<TKey> comparer = EqualityComparer<TKey>.Default;
        //    ICollection<TSource> list = source as ICollection<TSource>;
        //    var ret = list == null ? new Dictionary<TKey, TElement>(comparer)
        //                           : new Dictionary<TKey, TElement>(list.Count, comparer);
        //    foreach (TSource item in source)
        //        ret.Add(keySelector(item), elementSelector(item));
        //    return ret;
        //}

        //public static IDictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
        //{
        //    comparer = comparer ?? EqualityComparer<TKey>.Default;
        //    ICollection<TSource> list = source as ICollection<TSource>;
        //    var ret = list == null ? new Dictionary<TKey, TElement>(comparer)
        //                           : new Dictionary<TKey, TElement>(list.Count, comparer);
        //    foreach (TSource item in source)
        //        ret.Add(keySelector(item), elementSelector(item));
        //    return ret;
        //}
    }

    //public class SourceWoResultAndResult<T>
    //{
    //    public IList<T> SourceWithoutResult { get; set; }
    //    public IList<T> Result { get; set; }
    //}
}


text:
drop sequence KREN_CHNL_S;
drop sequence KREN_CHNL_SUBSCRP_S;
drop sequence KREN_CNTNT_TYP_S;
drop sequence KREN_MSG_DELIV_S;
drop sequence KREN_MSG_S;
drop sequence KREN_NTFCTN_MSG_DELIV_S;
drop sequence KREN_NTFCTN_S;
drop sequence KREN_PRIO_S;
drop sequence KREN_PRODCR_S;
drop sequence KREN_RECIP_DELIV_S;
drop sequence KREN_RECIP_LIST_S;
drop sequence KREN_RECIP_PREF_S;
drop sequence KREN_RECIP_S;
drop sequence KREN_RVWER_S;
drop sequence KREN_SNDR_S;
drop sequence KREW_ACTN_ITM_S;
drop sequence KREW_ACTN_LIST_OPTN_S;
drop sequence KREW_ACTN_RQST_S;
drop sequence KREW_ACTN_TKN_S;
drop sequence KREW_DOC_HDR_S;
drop sequence KREW_DOC_LNK_S;
drop sequence KREW_DOC_NTE_S;
drop sequence KREW_DOC_TYP_ATTR_S;
drop sequence KREW_EDL_FLD_DMP_S;
drop sequence KREW_EDL_S;
drop sequence KREW_HLP_S;
drop sequence KREW_OUT_BOX_ITM_S;
drop sequence KREW_RSP_S;
drop sequence KREW_RTE_NODE_CFG_PARM_S;
drop sequence KREW_RTE_NODE_S;
drop sequence KREW_RTE_TMPL_S;
drop sequence KREW_RULE_EXPR_S;
drop sequence KREW_RULE_TMPL_OPTN_S;
drop sequence KREW_SRCH_ATTR_S;
drop sequence KREW_USR_S;
drop sequence KRIM_ATTR_DATA_ID_S;
drop sequence KRIM_ATTR_DEFN_ID_S;
drop sequence KRIM_DLGN_ID_S;
drop sequence KRIM_DLGN_MBR_ID_S;
drop sequence KRIM_ENTITY_ADDR_ID_S;
drop sequence KRIM_ENTITY_AFLTN_ID_S;
drop sequence KRIM_ENTITY_CTZNSHP_ID_S;
drop sequence KRIM_ENTITY_EMAIL_ID_S;
drop sequence KRIM_ENTITY_EMP_ID_S;
drop sequence KRIM_ENTITY_ETHNIC_ID_S;
drop sequence KRIM_ENTITY_EXT_ID_ID_S;
drop sequence KRIM_ENTITY_ID_S;
drop sequence KRIM_ENTITY_NM_ID_S;
drop sequence KRIM_ENTITY_PHONE_ID_S;
drop sequence KRIM_ENTITY_RESIDENCY_ID_S;
drop sequence KRIM_ENTITY_VISA_ID_S;
drop sequence KRIM_GRP_ATTR_DATA_ID_S;
drop sequence KRIM_GRP_ID_S;
drop sequence KRIM_GRP_MBR_ID_S;
drop sequence KRIM_PERM_ID_S;
drop sequence KRIM_PERM_RQRD_ATTR_ID_S;
drop sequence KRIM_PERM_TMPL_ID_S;
drop sequence KRIM_PRNCPL_ID_S;
drop sequence KRIM_ROLE_ID_S;
drop sequence KRIM_ROLE_MBR_ID_S;
drop sequence KRIM_ROLE_PERM_ID_S;
drop sequence KRIM_ROLE_RSP_ACTN_ID_S;
drop sequence KRIM_ROLE_RSP_ID_S;
drop sequence KRIM_RSP_ID_S;
drop sequence KRIM_RSP_RQRD_ATTR_ID_S;
drop sequence KRIM_RSP_TMPL_ID_S;
drop sequence KRIM_TYP_ATTR_ID_S;
drop sequence KRIM_TYP_ID_S;


text:
Lists present multiple line items in a vertical arrangement as a single continuous element.

A list consists of a single continuous column of tessellated sub-divisions of equal width called rows that function as containers for tiles.

    <md-tabs class="example-tabs margin-bottom-40" md-dynamic-height md-border-bottom>
        <md-tab label="example">
            <md-content class="padding-40">
                <md-card>
                    <md-card-content layout="row" layout-padding layout-align="space-around start" ng-include="'app/elements/examples/lists-1.tmpl.html'"></md-card-content>
                </md-card>
            </md-content>
        </md-tab>
        <md-tab label="HTML">
            <md-content>

            </md-content>
        </md-tab>
    </md-tabs>

List Controls

    <md-tabs class="example-tabs margin-bottom-40" md-dynamic-height md-border-bottom>
        <md-tab label="example">
            <md-content class="padding-40">
                <md-card>
                    <md-card-content layout="row" layout-padding layout-align="space-around center" ng-include="'app/elements/examples/lists-2.tmpl.html'"></md-card-content>
                </md-card>
            </md-content>
        </md-tab>
        <md-tab label="HTML">
            <md-content>

            </md-content>
        </md-tab>
    </md-tabs>


text:
package org.robolectric.shadows;

import android.os.Build.VERSION_CODES;
import android.util.EventLog;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.shadow.api.Shadow;

@Implements(EventLog.class)
public class ShadowEventLog {

  /**
   * Constant written to the log if the parameter is null.
   *
   * <p>This matches how the real android code handles nulls.
   */
  static final String NULL_PLACE_HOLDER = "NULL";

  @Implements(EventLog.Event.class)
  public static class ShadowEvent {

    private Object data;
    private int tag;
    private int processId;
    private long timeNanos;

    @Implementation
    protected Object getData() {
      return data;
    }

    @Implementation
    protected int getTag() {
      return tag;
    }

    @Implementation
    protected int getProcessId() {
      return processId;
    }

    @Implementation
    protected long getTimeNanos() {
      return timeNanos;
    }
  }

  private static final List<EventLog.Event> events = new ArrayList<>();

  /** Class to build {@link EventLog.Event} */
  public static class EventBuilder {

    private final Object data;
    private final int tag;
    private int processId = ShadowProcess.myPid();
    private long timeNanos = System.nanoTime();

    public EventBuilder(int tag, Object data) {
      this.tag = tag;
      this.data = data;
    }

    public EventBuilder setProcessId(int processId) {
      this.processId = processId;
      return this;
    }

    public EventBuilder setTimeNanos(long timeNanos) {
      this.timeNanos = timeNanos;
      return this;
    }

    public EventLog.Event build() {
      EventLog.Event event = Shadow.newInstanceOf(EventLog.Event.class);
      ShadowEvent shadowEvent = Shadow.extract(event);
      shadowEvent.data = data;
      shadowEvent.tag = tag;
      shadowEvent.processId = processId;
      shadowEvent.timeNanos = timeNanos;
      return event;
    }
  }

  /** Add event to {@link EventLog}. */
  public static void addEvent(EventLog.Event event) {
    events.add(event);
  }

  @Resetter
  public static void clearAll() {
    events.clear();
  }

  /** Writes an event log message, returning an approximation of the bytes written. */
  @Implementation
  protected static int writeEvent(int tag, String str) {
    if (str == null) {
      str = NULL_PLACE_HOLDER;
    }
    addEvent(new EventBuilder(tag, str).build());
    return Integer.BYTES + str.length();
  }

  /** Writes an event log message, returning an approximation of the bytes written. */
  @Implementation
  protected static int writeEvent(int tag, Object... list) {
    if (list == null) {
      // This matches how the real android code handles nulls
      return writeEvent(tag, (String) null);
    }
    addEvent(new EventBuilder(tag, list).build());
    return Integer.BYTES + list.length * Integer.BYTES;
  }

  /** Writes an event log message, returning an approximation of the bytes written. */
  @Implementation
  protected static int writeEvent(int tag, int value) {
    addEvent(new EventBuilder(tag, value).build());
    return Integer.BYTES + Integer.BYTES;
  }

  /** Writes an event log message, returning an approximation of the bytes written. */
  @Implementation(minSdk = VERSION_CODES.M)
  protected static int writeEvent(int tag, float value) {
    addEvent(new EventBuilder(tag, value).build());
    return Integer.BYTES + Float.BYTES;
  }

  /** Writes an event log message, returning an approximation of the bytes written. */
  @Implementation
  protected static int writeEvent(int tag, long value) {
    addEvent(new EventBuilder(tag, value).build());
    return Integer.BYTES + Long.BYTES;
  }

  @Implementation
  protected static void readEvents(int[] tags, Collection<EventLog.Event> output) {
    for (EventLog.Event event : events) {
      for (int tag : tags) {
        if (tag == event.getTag()) {
          output.add(event);
          break;
        }
      }
    }
  }
}


text:
package com.google.dataflow.sample.retail.businesslogic.core.utils.test.clickstream;

import com.google.dataflow.sample.retail.businesslogic.core.transforms.clickstream.CountViewsPerProduct;
import com.google.dataflow.sample.retail.dataobjects.ClickStream.ClickStreamEvent;
import com.google.dataflow.sample.retail.dataobjects.ClickStream.PageViewAggregator;
import org.apache.beam.sdk.schemas.transforms.Convert;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
/** Unit tests for {@link ClickstreamProcessing}. */
public class CountViewsPerProductTest {

  private static final Long TIME = Instant.parse("2000-01-01T00:00:00").getMillis();

  private static final ClickStreamEvent EVENT =
      ClickStreamEvent.builder()
          .setUid(1L)
          .setClientId("1")
          .setPage("pageRef")
          .setPagePrevious("pageTarget")
          .setEvent("browse")
          .setTimestamp(TIME)
          .build();

  private static final TimestampedValue<ClickStreamEvent> CLICK_STREAM_EVENT_0_MINS =
      TimestampedValue.of(EVENT, Instant.ofEpochMilli(TIME));

  private static final TimestampedValue<ClickStreamEvent> CLICK_STREAM_EVENT_1_MINS =
      TimestampedValue.of(
          EVENT
              .toBuilder()
              .setTimestamp(
                  Instant.ofEpochMilli(TIME).plus(Duration.standardMinutes(1)).getMillis())
              .build(),
          Instant.ofEpochMilli(TIME).plus(Duration.standardMinutes(1)));

  @Rule public transient TestPipeline pipeline = TestPipeline.create();

  @Test
  public void testCountViews() {

    Duration windowDuration = Duration.standardMinutes(5);

    PCollection<PageViewAggregator> countPageViews =
        pipeline
            .apply(Create.timestamped(CLICK_STREAM_EVENT_0_MINS, CLICK_STREAM_EVENT_1_MINS))
            .apply(Convert.toRows())
            .apply(new CountViewsPerProduct(windowDuration));

    PageViewAggregator pageViewAggregator =
        PageViewAggregator.builder()
            .setCount(2L)
            .setPage("pageRef")
            .setDurationMS(windowDuration.getMillis())
            .setStartTime(TIME)
            .build();

    PAssert.that(countPageViews).containsInAnyOrder(pageViewAggregator);

    pipeline.run();
  }
}


text:
import numpy as np
import operator

def add_intercept(X, val):
    b = np.zeros([X.shape[0], 1])
    b[:] = val
    return np.concatenate([b, X], axis=1)

def get_split_mask(X, column, value, relation):
    left_mask = relation(X[:, column], value)
    right_mask = ~relation(X[:, column], value)
    return left_mask, right_mask

def get_split_mask_by_eq(X, column, value):
    return get_split_mask(X, column, value, operator.eq)

def split_dataset(X, column, value, relation):
    less_mask, greater_mask = get_split_mask(
            X, column, value, relation)
    return X[less_mask], X[greater_mask]

def squared_error(actual, pred):
    return (actual - pred) ** 2

def mean_squared_error(actual):
    mean = np.mean(actual)
    return squared_error(actual, mean)

def pGini(y, lables):
    n_samples = np.shape(y)[0]
    gini = 1.0
    for lable in lables:
        n_lable = np.sum(y == lable)
        gini -= (n_lable / n_samples) ** 2
    return gini

def accuracy(actual, pred):
    return np.mean(actual == pred)

def normal_feature(X):
    mu = np.mean(X, 0)
    sigma = np.std(X, 0, ddof=1)
    return (X - mu) / sigma

def reshape_1d_to_2d(X):
    X = np.array(X)
    if X.ndim == 1:
        X = np.reshape(X, (X.shape[0], 1))
    return X


text:
title: DbpediaLiteSearch::__construct — Core Library
package: lib
packageTitle: Core Library
layout: default
className: DbpediaLiteSearch
type: method
---

# DbpediaLiteSearch::__construct

## Synopsis

public function DbpediaLiteSearch::__construct($uri)

## Parameters

      Name
      Direction
      Type
      Description

      $uri


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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>ir.co.dpq.jpluf</groupId>
    <artifactId>jpluf</artifactId>
    <version>0.3.0</version>
  </parent>
  <artifactId>jpluf-hibernate</artifactId>
</project>


text:
static int ip_layer_init(void);
static void ip_handler(void* user_ctx, NetworkBuffer* incomingPacket);
static bool ip_is_valid(iphdr_t* iphdr);
static void ip_hint_arp_cache(const NetworkBuffer *packet);
static uint16_t nextId(void);

class RawIpFileDescriptor;

static std::atomic<uint16_t> gId(0);
std::vector<RawIpFileDescriptor*> gRawSockets;

DECLARE_DRIVER(ip_layer, ip_layer_init, STAGE_SECOND + 1);

int ip_input(NetworkBuffer *incomingPacket)
{
    int ret = 0;
    const interface_t* interface = nullptr;
    iphdr_t* iphdr = ip_hdr(incomingPacket);

    if (nbuf_size_from(incomingPacket, iphdr) < sizeof(iphdr_t)) {
        kprintf("ip: packet is too small, dropping. (buf %d ip %d)\n", nbuf_size_from(incomingPacket, iphdr), sizeof(iphdr_t));
        goto error;
    }

    if (4 != iphdr->version) {
        goto error;
    }

    iphdr->len = ntohs(iphdr->len);
    iphdr->id = ntohs(iphdr->id);
    iphdr->frag_offset = ntohs(iphdr->frag_offset);
    iphdr->csum = ntohs(iphdr->csum);
    iphdr->saddr = ntohl(iphdr->saddr);
    iphdr->daddr = ntohl(iphdr->daddr);

    if (!ip_is_valid(iphdr)) {
        goto error;
    }

    nbuf_set_l4(incomingPacket, iphdr->data, iphdr->proto);
    ip_hint_arp_cache(incomingPacket);

//    kprintf("ip: received an IP datagram %08x --> %08x (%d)\n", iphdr->saddr, iphdr->daddr, iphdr->proto);

    // duplicate the packet and push it to each waiting raw ip socket
    {
        InterruptsMutex mutex;
        mutex.lock();
        if (!gRawSockets.empty()) {
            for (auto& sock : gRawSockets) {
                auto* clone = nbuf_clone(incomingPacket);
                if (clone) {
                    sock->rxQueue.push(clone);
                }
            }
        }
        mutex.unlock();
    }

    // now, let this packet flow only if its for us...
    // drop it otherwise as we do not support acting as a router just yet..
    interface = interface_get(nbuf_device(incomingPacket));
    if (!interface || !is_ip_on_same_network(iphdr->saddr, interface->ipv4.address, interface->ipv4.netmask)) {
        goto error;
    }

    // TODO: implement register_protocol() interface
    switch (iphdr->proto)
    {
        case IPPROTO_ICMP:
            icmp_input(incomingPacket);
            break;

        case IPPROTO_TCP:
            tcp_input(incomingPacket);
            break;

        case IPPROTO_UDP:
            udp_input(incomingPacket);
            break;

        default:
            goto error;
    }

    goto exit;

error:
    ret = -1;
    nbuf_free(incomingPacket);

exit:
    return ret;
}

static void ip_hint_arp_cache(const NetworkBuffer *packet) {
    const char* device = nbuf_device(packet);
    ethernet_t* eth = ethernet_hdr(packet);
    iphdr_t* ip = ip_hdr(packet);

    arp_set_entry(device, eth->src, ip->saddr);
}

NetworkBuffer* ip_alloc_nbuf(IpAddress dst, uint8_t ttl, uint8_t proto, uint16_t size) {
    route_t route;
    if (0 != ip_route_lookup(dst, &route)) {
        return NULL;
    }

    NetworkBuffer *nbuf = ethernet_alloc_nbuf(route.iface->device, ETH_P_IPv4, sizeof(iphdr_t) + size);
    if (!nbuf) {
        return nbuf;
    }

    iphdr_t* iphdr = ip_hdr(nbuf);
    memset(iphdr, 0, sizeof(*iphdr));
    iphdr->version = 4;
    iphdr->ihl = 5;
    iphdr->id = htons(nextId());
    iphdr->ttl = ttl;
    iphdr->len = htons(sizeof(iphdr_t) + size);
    iphdr->saddr = htonl(route.iface->ipv4.address);
    iphdr->daddr = htonl(dst);
    iphdr->proto = proto;
    nbuf_set_l4(nbuf, iphdr->data, proto);

    return nbuf;
}

struct ArpResolveContext {
    NetworkBuffer* ipPacket;
};

static void arp_resolve_cb(NetworkBuffer* arpContext, int result)
{
    MacAddress mac{};
    ArpResolveContext* ctx = (ArpResolveContext *) nbuf_data(arpContext);
    iphdr_t* iphdr = ip_hdr(ctx->ipPacket);

    if (0 == result) {
        goto error;
    }

    if (0 != arp_get_hwaddr(ntohl(iphdr->daddr), mac)) {
        goto error;
    }

    ethernet_send_packet(ctx->ipPacket, mac);
    goto exit;

error:
    nbuf_free(ctx->ipPacket);

exit:
    nbuf_free(arpContext);
}

// no ip options for now..
int ip_output(NetworkBuffer* packet)
{
    iphdr_t* iphdr = ip_hdr(packet);
    iphdr->csum = 0;
    iphdr->csum = checksum(iphdr, iphdr->ihl * 4, 0);

    NetworkBuffer* arpContextNbuf = nbuf_alloc(sizeof(ArpResolveContext));
    if (!arpContextNbuf) {
        nbuf_free(packet);
        return -1;
    }

    ArpResolveContext* arpContext = (ArpResolveContext *) nbuf_data(arpContextNbuf);
    arpContext->ipPacket = packet;

    if (0 != arp_resolve(ntohl(iphdr->daddr), (arp_resolve_cb_t)arp_resolve_cb, arpContextNbuf)) {
        nbuf_free(packet);
        nbuf_free(arpContextNbuf);
        return -1;
    }

    return 0;
}

static uint16_t nextId(void) {
    return gId.fetch_add(1, std::memory_order::memory_order_relaxed);
}

static int ip_layer_init(void)
{
    ethernet_register_handler(ETH_P_IPv4, ip_handler, NULL);
    socket_register_triple({AF_INET, SOCK_RAW, IPPROTO_RAW}, []() {
        return std::unique_ptr<SocketFileDescriptor>(new RawIpFileDescriptor());
    });
    return 0;
}

static void ip_handler(void* user_ctx, NetworkBuffer* incomingPacket)
{
    (void)user_ctx;

    ip_input(incomingPacket);
}

static bool ip_is_valid(iphdr_t* iphdr) {
    if (5 > iphdr->ihl) {
        kprintf("ip: IPv4 header length must be at least 5\n");
        return false;
    }

    if (IP_FLAGS(iphdr) & IP_FLAGS_MORE_FRAGMENTS) {
        kprintf("ip: Fragments are not supported yet..\n");
        return false;
    }

    uint16_t orig_csum = iphdr->csum;
    iphdr->csum = 0;

    uint16_t new_csum = checksum(iphdr, iphdr->ihl * 4, 0);
    iphdr->csum = orig_csum;

    if (orig_csum != new_csum) {
        kprintf("ip: checksum mismatch (got %04x expected %04x)\n", orig_csum, new_csum);
        return false;
    }

    return true;
}


text:
<?php namespace Gears;
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

use RuntimeException;
use Gears\Di\Container;
use Illuminate\Database\Capsule\Manager as LaravelDb;
use Illuminate\Session\Store;
use Illuminate\Session\DatabaseSessionHandler;

class Session extends Container
{
	/**
	 * Property: name
	 * =========================================================================
	 * Used to identify the session, the name of the actual session cookie.
	 */
	protected $injectName;

	/**
	 * Property: lifetime
	 * =========================================================================
	 * The time in seconds before garbage collection is run on the server.
	 */
	protected $injectLifetime;

	/**
	 * Property: path
	 * =========================================================================
	 * This is passed directly to setcookie.
	 * See: http://php.net/manual/en/function.setcookie.php
	 */
	protected $injectPath;

	/**
	 * Property: domain
	 * =========================================================================
	 * This is passed directly to setcookie.
	 * See: http://php.net/manual/en/function.setcookie.php
	 */
	protected $injectDomain;

	/**
	 * Property: secure
	 * =========================================================================
	 * This is passed directly to setcookie.
	 * See: http://php.net/manual/en/function.setcookie.php
	 */
	protected $injectSecure;

	/**
	 * Property: dbConfig
	 * =========================================================================
	 * This is an array of configuration data that can be used to create the
	 * dbConnection. This **must** be injected, if you do not inject your very
	 * own dbConnection.
	 */
	protected $injectDbConfig;

	/**
	 * Property: table
	 * =========================================================================
	 * The name of the database table to use for session storage.
	 */
	protected $injectTable;

	/**
	 * Property: dbConnection
	 * =========================================================================
	 * An instance of ```\Illuminate\Database\Connection```.
	 */
	protected $injectDbConnection;

	/**
	 * Property: databaseSessionHandler
	 * =========================================================================
	 * An instance of ```Illuminate\Session\DatabaseSessionHandler```.
	 */
	protected $injectDatabaseSessionHandler;

	/**
	 * Property: sessionStore
	 * =========================================================================
	 * An instance of ```Illuminate\Session\Store```.
	 */
	protected $injectSessionStore;

	/**
	 * Property: expired
	 * =========================================================================
	 * We have added in some extra functionality. We can now easily check to
	 * see if the session has expired. If it has we reset the cookie with a
	 * new id, etc.
	 */
	private $expired = false;

	/**
	 * Property: instance
	 * =========================================================================
	 * This is used as part of the globalise functionality.
	 */
	private static $instance;

	/**
	 * Method: setDefaults
	 * =========================================================================
	 * This is where we set all our defaults. If you need to customise this
	 * container this is a good place to look to see what can be configured
	 * and how to configure it.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * n/a
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * void
	 */
	protected function setDefaults()
	{
		$this->name = 'gears-session';

		$this->table = 'sessions';

		$this->lifetime = 120;

		$this->path = '/';

		$this->dbConnection = function()
		{
			if (!is_array($this->dbConfig))
			{
				throw new RuntimeException
				(
					'Invalid Database Connection Provided'
				);
			}

			$capsule = new LaravelDb;
			$capsule->addConnection($this->dbConfig);
			return $capsule->getConnection('default');
		};

		$this->databaseSessionHandler = function()
		{
			return new DatabaseSessionHandler
			(
				$this->dbConnection,
				$this->table
			);
		};

		$this->sessionStore = function()
		{
			return new Store
			(
				$this->name,
				$this->databaseSessionHandler
			);
		};
	}

	/**
	 * Method: install
	 * =========================================================================
	 * Once the container has been configured. Please call this method to
	 * install the session api into your application.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * - $global: If set to true we will also run globalise after setup.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * void
	 */
	public function install($global = false)
	{
		// Make sure we have a sessions table
		$schema = $this->dbConnection->getSchemaBuilder();
		if (!$schema->hasTable($this->table))
		{
			$schema->create($this->table, function($t)
			{
				$t->string('id')->unique();
				$t->text('payload');
				$t->integer('last_activity');
			});
		}

		// Run the garbage collection
		$this->sessionStore->getHandler()->gc($this->lifetime);

		// Check for our session cookie
		if (isset($_COOKIE[$this->name]))
		{
			// Grab the session id from the cookie
			$cookie_id = $_COOKIE[$this->name];

			// Does the session exist in the db?
			$session = (object) $this->dbConnection
				->table($this->table)
				->find($cookie_id)
			;

			if (isset($session->payload))
			{
				// Set the id of the session
				$this->sessionStore->setId($cookie_id);
			}
			else
			{
				// Set the expired flag
				$this->expired = true;

				// NOTE: We do not need to set the id here.
				// As it has already been set by the constructor of the Store.
			}
		}

		// Set / reset the session cookie
		if (!isset($_COOKIE[$this->name]) || $this->expired)
		{
			setcookie
			(
				$this->name,
				$this->sessionStore->getId(),
				0,
				$this->path,
				$this->domain,
				$this->secure,
				true
			);
		}

		// Start the session
		$this->sessionStore->start();

		// Save the session on shutdown
		register_shutdown_function([$this->sessionStore, 'save']);

		// Run globalise
		if ($global) $this->globalise();
	}

	/**
	 * Method: hasExpired
	 * =========================================================================
	 * Pretty simple, if the session has previously been set and now has been
	 * expired by means of garbage collection on the server, this will return
	 * true, otherwise false.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * n/a
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * boolean
	 */
	public function hasExpired()
	{
		return $this->expired;
	}

	/**
	 * Method: regenerate
	 * =========================================================================
	 * When the session id is regenerated we need to reset the cookie.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * - $destroy: If set to true the previous session will be deleted.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * boolean
	 */
	public function regenerate($destroy = false)
	{
		if ($this->sessionStore->regenerate($destroy))
		{
			setcookie
			(
				$this->sessionStore->getName(),
				$this->sessionStore->getId(),
				0,
				$this->path,
				$this->domain,
				$this->secure,
				true
			);

			return  true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * Method: globalise
	 * =========================================================================
	 * Now in a normal laravel application you can call the session api like so:
	 *
	 * ```php
	 * Session::push('key', 'value');
	 * ```
	 *
	 * This is because laravel has the IoC container with Service Providers and
	 * Facades and other intresting things that work some magic to set this up
	 * for you. Have a look in you main app.php config file and checkout the
	 * aliases section.
	 *
	 * If you want to be able to do the same in your
	 * application you need to call this method.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * - $alias: This is the name of the alias to create. Defaults to Session.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * void
	 *
	 * Throws:
	 * -------------------------------------------------------------------------
	 * - RuntimeException: When a class of the same name as the alias
	 *   already exists.
	 */
	public function globalise($alias = 'Session')
	{
		// Create the alias name
		if (substr($alias, 0, 1) != '\\')
		{
			// This ensures the alias is created in the global namespace.
			$alias = '\\'.$alias;
		}

		// Check if a class already exists
		if (class_exists($alias))
		{
			// Bail out, a class already exists with the same name.
			throw new RuntimeException('Class already exists!');
		}

		// Create the alias
		class_alias('\Gears\Session', $alias);

		// Save our instance
		self::$instance = $this;
	}

	/**
	 * Method: __call
	 * =========================================================================
	 * This will pass any unresolved method calls
	 * through to the main session store object.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * - $name: The name of the method to call.
	 * - $args: The argumnent array that is given to us.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * mixed
	 */
	public function __call($name, $args)
	{
		return call_user_func_array([$this->sessionStore, $name], $args);
	}

	/**
	 * Method: __callStatic
	 * =========================================================================
	 * This will pass any unresolved static method calls
	 * through to the saved instance.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * - $name: The name of the method to call.
	 * - $args: The argumnent array that is given to us.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * mixed
	 *
	 * Throws:
	 * -------------------------------------------------------------------------
	 * - RuntimeException: When we have not been globalised.
	 */
	public static function __callStatic($name, $args)
	{
		if (empty(self::$instance))
		{
			throw new RuntimeException('You need to run globalise first!');
		}

		return call_user_func_array([self::$instance, $name], $args);
	}
}


text:
import { AbstractPokerCommand } from "../../core/commands/AbstractPokerCommand";
import { SrvTourPlayerPositionData } from "../data/SrvTourPlayerPositionData";

export class SrvTourPlayerPositionCommand extends AbstractPokerCommand {
	public static NAME = "SrvTourPlayerPosition";
	public static UID = 12525;

		public data: SrvTourPlayerPositionData;

	constructor() {
		super();
		this.init(3, 237, SrvTourPlayerPositionCommand.NAME);
	}
}


text:
package org.elasticsearch.painless;

import org.elasticsearch.painless.spi.Whitelist;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptFactory;
import org.elasticsearch.script.TemplateScript;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class FactoryTests extends ScriptTestCase {

    @Override
    protected Map<ScriptContext<?>, List<Whitelist>> scriptContexts() {
        Map<ScriptContext<?>, List<Whitelist>> contexts = super.scriptContexts();
        contexts.put(StatefulFactoryTestScript.CONTEXT, Whitelist.BASE_WHITELISTS);
        contexts.put(FactoryTestScript.CONTEXT, Whitelist.BASE_WHITELISTS);
        contexts.put(DeterministicFactoryTestScript.CONTEXT, Whitelist.BASE_WHITELISTS);
        contexts.put(EmptyTestScript.CONTEXT, Whitelist.BASE_WHITELISTS);
        contexts.put(TemplateScript.CONTEXT, Whitelist.BASE_WHITELISTS);
        contexts.put(VoidReturnTestScript.CONTEXT, Whitelist.BASE_WHITELISTS);

        return contexts;
    }

    public abstract static class StatefulFactoryTestScript {
        private final int x;
        private final int y;

        public StatefulFactoryTestScript(int x, int y, int a, int b) {
            this.x = x*a;
            this.y = y*b;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y*2;
        }

        public int getC() {
            return -1;
        }

        public int getD() {
            return 2;
        }

        public static final String[] PARAMETERS = new String[] {"test"};
        public abstract Object execute(int test);

        public abstract boolean needsTest();
        public abstract boolean needsNothing();
        public abstract boolean needsX();
        public abstract boolean needsC();
        public abstract boolean needsD();

        public interface StatefulFactory {
            StatefulFactoryTestScript newInstance(int a, int b);

            boolean needsTest();
            boolean needsNothing();
            boolean needsX();
            boolean needsC();
            boolean needsD();
        }

        public interface Factory {
            StatefulFactory newFactory(int x, int y);

            boolean needsTest();
            boolean needsNothing();
            boolean needsX();
            boolean needsC();
            boolean needsD();
        }

        public static final ScriptContext<StatefulFactoryTestScript.Factory> CONTEXT =
            new ScriptContext<>("test", StatefulFactoryTestScript.Factory.class);
    }

    public void testStatefulFactory() {
        StatefulFactoryTestScript.Factory factory = scriptEngine.compile(
            "stateful_factory_test", "test + x + y + d", StatefulFactoryTestScript.CONTEXT, Collections.emptyMap());
        StatefulFactoryTestScript.StatefulFactory statefulFactory = factory.newFactory(1, 2);
        StatefulFactoryTestScript script = statefulFactory.newInstance(3, 4);
        assertEquals(24, script.execute(3));
        statefulFactory.newInstance(5, 6);
        assertEquals(28, script.execute(7));
        assertEquals(true, script.needsTest());
        assertEquals(false, script.needsNothing());
        assertEquals(true, script.needsX());
        assertEquals(false, script.needsC());
        assertEquals(true, script.needsD());
        assertEquals(true, statefulFactory.needsTest());
        assertEquals(false, statefulFactory.needsNothing());
        assertEquals(true, statefulFactory.needsX());
        assertEquals(false, statefulFactory.needsC());
        assertEquals(true, statefulFactory.needsD());
        assertEquals(true, factory.needsTest());
        assertEquals(false, factory.needsNothing());
        assertEquals(true, factory.needsX());
        assertEquals(false, factory.needsC());
        assertEquals(true, factory.needsD());
    }

    public abstract static class FactoryTestScript {
        private final Map<String, Object> params;

        public FactoryTestScript(Map<String, Object> params) {
            this.params = params;
        }

        public Map<String, Object> getParams() {
            return params;
        }

        public static final String[] PARAMETERS = new String[] {"test"};
        public abstract Object execute(int test);

        public interface Factory {
            FactoryTestScript newInstance(Map<String, Object> params);

            boolean needsTest();
            boolean needsNothing();
        }

        public static final ScriptContext<FactoryTestScript.Factory> CONTEXT =
            new ScriptContext<>("test", FactoryTestScript.Factory.class);
    }

    public abstract static class DeterministicFactoryTestScript {
        private final Map<String, Object> params;

        public DeterministicFactoryTestScript(Map<String, Object> params) {
            this.params = params;
        }

        public Map<String, Object> getParams() {
            return params;
        }

        public static final String[] PARAMETERS = new String[] {"test"};
        public abstract Object execute(int test);

        public interface Factory extends ScriptFactory{
            FactoryTestScript newInstance(Map<String, Object> params);

            boolean needsTest();
            boolean needsNothing();
        }

        public static final ScriptContext<DeterministicFactoryTestScript.Factory> CONTEXT =
            new ScriptContext<>("test", DeterministicFactoryTestScript.Factory.class);
    }

    public void testFactory() {
        FactoryTestScript.Factory factory =
            scriptEngine.compile("factory_test", "test + params.get('test')", FactoryTestScript.CONTEXT, Collections.emptyMap());
        FactoryTestScript script = factory.newInstance(Collections.singletonMap("test", 2));
        assertEquals(4, script.execute(2));
        assertEquals(5, script.execute(3));
        script = factory.newInstance(Collections.singletonMap("test", 3));
        assertEquals(5, script.execute(2));
        assertEquals(2, script.execute(-1));
        assertEquals(true, factory.needsTest());
        assertEquals(false, factory.needsNothing());
    }

    public void testDeterministic() {
        DeterministicFactoryTestScript.Factory factory =
            scriptEngine.compile("deterministic_test", "Integer.parseInt('123')",
                DeterministicFactoryTestScript.CONTEXT, Collections.emptyMap());
        assertTrue(factory.isResultDeterministic());
        assertEquals(123, factory.newInstance(Collections.emptyMap()).execute(0));
    }

    public void testNotDeterministic() {
        DeterministicFactoryTestScript.Factory factory =
            scriptEngine.compile("not_deterministic_test", "Math.random()",
                DeterministicFactoryTestScript.CONTEXT, Collections.emptyMap());
        assertFalse(factory.isResultDeterministic());
        Double d = (Double)factory.newInstance(Collections.emptyMap()).execute(0);
        assertTrue(d >= 0.0 && d <= 1.0);
    }

    public void testMixedDeterministicIsNotDeterministic() {
        DeterministicFactoryTestScript.Factory factory =
            scriptEngine.compile("not_deterministic_test", "Integer.parseInt('123') + Math.random()",
                DeterministicFactoryTestScript.CONTEXT, Collections.emptyMap());
        assertFalse(factory.isResultDeterministic());
        Double d = (Double)factory.newInstance(Collections.emptyMap()).execute(0);
        assertTrue(d >= 123.0 && d <= 124.0);
    }

    public abstract static class EmptyTestScript {
        public static final String[] PARAMETERS = {};
        public abstract Object execute();

        public interface Factory {
            EmptyTestScript newInstance();
        }

        public static final ScriptContext<EmptyTestScript.Factory> CONTEXT =
            new ScriptContext<>("test", EmptyTestScript.Factory.class);
    }

    public void testEmpty() {
        EmptyTestScript.Factory factory = scriptEngine.compile("empty_test", "1", EmptyTestScript.CONTEXT, Collections.emptyMap());
        EmptyTestScript script = factory.newInstance();
        assertEquals(1, script.execute());
        assertEquals(1, script.execute());
        script = factory.newInstance();
        assertEquals(1, script.execute());
        assertEquals(1, script.execute());
    }

    public void testTemplate() {
        TemplateScript.Factory factory =
            scriptEngine.compile("template_test", "params['test']", TemplateScript.CONTEXT, Collections.emptyMap());
        TemplateScript script = factory.newInstance(Collections.singletonMap("test", "abc"));
        assertEquals("abc", script.execute());
        assertEquals("abc", script.execute());
        script = factory.newInstance(Collections.singletonMap("test", "def"));
        assertEquals("def", script.execute());
        assertEquals("def", script.execute());
    }

    public void testGetterInLambda() {
        FactoryTestScript.Factory factory =
            scriptEngine.compile("template_test",
                "IntSupplier createLambda(IntSupplier s) { return s; } createLambda(() -> params['x'] + test).getAsInt()",
                FactoryTestScript.CONTEXT, Collections.emptyMap());
        FactoryTestScript script = factory.newInstance(Collections.singletonMap("x", 1));
        assertEquals(2, script.execute(1));
    }

    public abstract static class VoidReturnTestScript {
        public static final String[] PARAMETERS = {"map"};
        public abstract void execute(Map<Object, Object> map);

        public interface Factory {
            VoidReturnTestScript newInstance();
        }

        public static final ScriptContext<VoidReturnTestScript.Factory> CONTEXT =
                new ScriptContext<>("test", VoidReturnTestScript.Factory.class);
    }

    public void testVoidReturn() {
        scriptEngine.compile("void_return_test", "int x = 1 + 1; return;", VoidReturnTestScript.CONTEXT, Collections.emptyMap());
        IllegalArgumentException iae = expectScriptThrows(IllegalArgumentException.class, () ->
                scriptEngine.compile("void_return_test", "1 + 1", VoidReturnTestScript.CONTEXT, Collections.emptyMap()));
        assertEquals(iae.getMessage(), "not a statement: result not used from addition operation [+]");
    }
}


text:
**Core Features, World Class Technology**

SFM3000 is a cost effective fingerprint identification module
equipped with essential part for fingerprint identification
and template storage. SFM3000 is suitable for most of the
applications where it processes fingerprint recognition and
host controller is used to handle other operations. The
communication between SFM3000 and host controller is
done by packet protocol through CMOS level serial interface.

## Features
- High Performance 400MHz DSP
- Fast Power-on Time
- Suprema, ISO19794-2 and ANSI 378 Template Options
- 8 Configurable Digital I/O Ports
- Low Power Consumption
- 256-bit AES Fingerprint Data Encryption

!!! info
	Click here to get detailed information of SFM3000 series.

## Standard pin assignment

![](/images/product/SFM3000.png)

## Related links
##### Datasheets
- [SFM3050-TC1]()
- [SFM3050-TC2]()
- [SFM3050-TC2S]()

##### Documents
- [UF Protocol Manual](../documents/UF_Protocol_Manual/)

##### Software
- [UnifingerUI](https://github.com/supremainc/sfm-unifingerui/releases)


text: NHS prototyping kit


text:
<!-- Licensed under a BSD license. See license.html for license -->
(function($){
$(document).ready(function($){
  // are there more languages for this article?
  var pathname = window.location.pathname;
  var lastSlash = pathname.lastIndexOf("/");
  var filename = pathname.substr(lastSlash + 1);

  Object.keys(window.langDB.langs).forEach(function(lang) {
      $("#language")
          .append($("<option></option>")
              .attr("value", lang)
              .text(window.langDB.langs[lang].language));
  });

  var m = /webgl\/lessons\/(.*?)\//.exec(window.location.pathname);
  var lang = "en";
  if (m) {
    lang = m[1];
  }

  $('#language').val(lang);
  $('#language').on('change', function() {
    var lang = this.value;
    var path = "/webgl/lessons";
    var article = window.langDB.articles[filename];
    if (!article || !article[lang]) {
      filename = "index.html";
    }
    if (filename === "index.html") {
      if (lang === "en") {
        path = "";
      }
    }
    lang = lang === "en" ? "" : ("/" + lang);
    var url = path + lang + "/" + filename + window.location.search + window.location.hash;
    window.location.href = url;
  });
});
}(jQuery));


text:
<?php
/**
 * A simple class comment.
 */
class MyPropertyClass
{
    /**
     * This is one comment.
     */
    private $property_with_comment;

    // Wrong comment type
    public $property_without_doc_comment;

    protected $property_without_comment = null;

    /**
     * This is a second comment.
     */
    protected $another_property_with_comment;
}


text:
<?php

declare(strict_types=1);

namespace Gears\Framework\Application\ResourceHandler;

use Gears\Framework\Application\ServiceAware;
use Gears\Db\Table\TableAbstract;
use Symfony\Component\HttpFoundation\JsonResponse;

class DbTableHandler implements ResourceHandlerInterface
{
    use ServiceAware;

    public function list(string $resource): JsonResponse
    {
        /** @var TableAbstract $table */
        $table = $this->get($resource);

        return new JsonResponse($table->fetchAll());
    }

    public function one(string $resource, string $id): JsonResponse
    {
        /** @var TableAbstract $table */
        $table = $this->get($resource);

        if (!$row = $table->fetchRow($id)) {
            throw new ResourceNotFoundException($resource . "[$id]");
        }

        return new JsonResponse($row);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ptr_pull_to_refresh">Pull to refresh</string>
    <string name="ptr_release_to_refresh">Release to refresh</string>
    <string name="ptr_refreshing">Refreshing…</string>
    <string name="ptr_last_updated">Updated: %1$s</string>
</resources>


text: module.exports = require("./lib/MPEG2TS");


text:
// Copyright 2017 Mike Fricker. All Rights Reserved.

#include "StreetMapImporting.h"
#include "OSMFile.h"

FOSMFile::FOSMFile()
	: ParsingState( ParsingState::Root )
{
}

FOSMFile::~FOSMFile()
{
	// Clean up time
	{
		for( auto* Way : Ways )
		{
			delete Way;
		}
		Ways.Empty();

		for( auto HashPair : NodeMap )
		{
			FOSMNodeInfo* NodeInfo = HashPair.Value;
			delete NodeInfo;
		}
		NodeMap.Empty();
	}
}

bool FOSMFile::LoadOpenStreetMapFile( FString& OSMFilePath, const bool bIsFilePathActuallyTextBuffer, FFeedbackContext* FeedbackContext )
{
	const bool bShowSlowTaskDialog = true;
	const bool bShowCancelButton = true;

	FText ErrorMessage;
	int32 ErrorLineNumber;
	if( FFastXml::ParseXmlFile(
		this,
		bIsFilePathActuallyTextBuffer ? nullptr : *OSMFilePath,
		bIsFilePathActuallyTextBuffer ? OSMFilePath.GetCharArray().GetData() : nullptr,
		FeedbackContext,
		bShowSlowTaskDialog,
		bShowCancelButton,
		/* Out */ ErrorMessage,
		/* Out */ ErrorLineNumber ) )
	{
		if( NodeMap.Num() > 0 )
		{
			AverageLatitude /= NodeMap.Num();
			AverageLongitude /= NodeMap.Num();
		}

		return true;
	}

	if( FeedbackContext != nullptr )
	{
		FeedbackContext->Logf(
			ELogVerbosity::Error,
			TEXT( "Failed to load OpenStreetMap XML file ('%s', Line %i)" ),
			*ErrorMessage.ToString(),
			ErrorLineNumber );
	}

	return false;
}

bool FOSMFile::ProcessXmlDeclaration( const TCHAR* ElementData, int32 XmlFileLineNumber )
{
	// Don't care about XML declaration
	return true;
}

bool FOSMFile::ProcessComment( const TCHAR* Comment )
{
	// Don't care about comments
	return true;
}

bool FOSMFile::ProcessElement( const TCHAR* ElementName, const TCHAR* ElementData, int32 XmlFileLineNumber )
{
	if( ParsingState == ParsingState::Root )
	{
		if( !FCString::Stricmp( ElementName, TEXT( "node" ) ) )
		{
			ParsingState = ParsingState::Node;
			CurrentNodeInfo = new FOSMNodeInfo();
			CurrentNodeInfo->Latitude = 0.0;
			CurrentNodeInfo->Longitude = 0.0;
		}
		else if( !FCString::Stricmp( ElementName, TEXT( "way" ) ) )
		{
			ParsingState = ParsingState::Way;
			CurrentWayInfo = new FOSMWayInfo();
			CurrentWayInfo->Name.Empty();
			CurrentWayInfo->Ref.Empty();
			CurrentWayInfo->WayType = EOSMWayType::Other;
			CurrentWayInfo->Height = 0.0;
			CurrentWayInfo->bIsOneWay = false;

			// @todo: We're currently ignoring the "visible" tag on ways, which means that roads will always
			//        be included in our data set.  It might be nice to make this an import option.
		}
	}
	else if( ParsingState == ParsingState::Way )
	{
		if( !FCString::Stricmp( ElementName, TEXT( "nd" ) ) )
		{
			ParsingState = ParsingState::Way_NodeRef;
		}
		else if( !FCString::Stricmp( ElementName, TEXT( "tag" ) ) )
		{
			ParsingState = ParsingState::Way_Tag;
		}
	}

	return true;
}

bool FOSMFile::ProcessAttribute( const TCHAR* AttributeName, const TCHAR* AttributeValue )
{
	if( ParsingState == ParsingState::Node )
	{
		if( !FCString::Stricmp( AttributeName, TEXT( "id" ) ) )
		{
			CurrentNodeID = FPlatformString::Atoi64( AttributeValue );
		}
		else if( !FCString::Stricmp( AttributeName, TEXT( "lat" ) ) )
		{
			CurrentNodeInfo->Latitude = FPlatformString::Atod( AttributeValue );

			AverageLatitude += CurrentNodeInfo->Latitude;

			// Update minimum and maximum latitude
			// @todo: Performance: Instead of computing our own bounding box, we could parse the "minlat" and
			//        "minlon" tags from the OSM file
			if( CurrentNodeInfo->Latitude < MinLatitude )
			{
				MinLatitude = CurrentNodeInfo->Latitude;
			}
			if( CurrentNodeInfo->Latitude > MaxLatitude )
			{
				MaxLatitude = CurrentNodeInfo->Latitude;
			}
		}
		else if( !FCString::Stricmp( AttributeName, TEXT( "lon" ) ) )
		{
			CurrentNodeInfo->Longitude = FPlatformString::Atod( AttributeValue );

			AverageLongitude += CurrentNodeInfo->Longitude;

			// Update minimum and maximum longitude
			if( CurrentNodeInfo->Longitude < MinLongitude )
			{
				MinLongitude = CurrentNodeInfo->Longitude;
			}
			if( CurrentNodeInfo->Longitude > MaxLongitude )
			{
				MaxLongitude = CurrentNodeInfo->Longitude;
			}
		}
	}
	else if( ParsingState == ParsingState::Way )
	{
		// ...
	}
	else if( ParsingState == ParsingState::Way_NodeRef )
	{
		if( !FCString::Stricmp( AttributeName, TEXT( "ref" ) ) )
		{
			FOSMNodeInfo* ReferencedNode = NodeMap.FindRef( FPlatformString::Atoi64( AttributeValue ) );
			const int NewNodeIndex = CurrentWayInfo->Nodes.Num();
			CurrentWayInfo->Nodes.Add( ReferencedNode );

			// Update the node with information about the way that is referencing it
			{
				FOSMWayRef NewWayRef;
				NewWayRef.Way = CurrentWayInfo;
				NewWayRef.NodeIndex = NewNodeIndex;
				ReferencedNode->WayRefs.Add( NewWayRef );
			}
		}
	}
	else if( ParsingState == ParsingState::Way_Tag )
	{
		if( !FCString::Stricmp( AttributeName, TEXT( "k" ) ) )
		{
			CurrentWayTagKey = AttributeValue;
		}
		else if( !FCString::Stricmp( AttributeName, TEXT( "v" ) ) )
		{
			if( !FCString::Stricmp( CurrentWayTagKey, TEXT( "name" ) ) )
			{
				CurrentWayInfo->Name = AttributeValue;
			}
			else if( !FCString::Stricmp( CurrentWayTagKey, TEXT( "ref" ) ) )
			{
				CurrentWayInfo->Ref = AttributeValue;
			}
			else if( !FCString::Stricmp( CurrentWayTagKey, TEXT( "highway" ) ) )
			{
				EOSMWayType WayType = EOSMWayType::Other;

				if( !FCString::Stricmp( AttributeValue, TEXT( "motorway" ) ) )
				{
					WayType = EOSMWayType::Motorway;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "motorway_link" ) ) )
				{
					WayType = EOSMWayType::Motorway_Link;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "trunk" ) ) )
				{
					WayType = EOSMWayType::Trunk;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "trunk_link" ) ) )
				{
					WayType = EOSMWayType::Trunk_Link;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "primary" ) ) )
				{
					WayType = EOSMWayType::Primary;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "primary_link" ) ) )
				{
					WayType = EOSMWayType::Primary_Link;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "secondary" ) ) )
				{
					WayType = EOSMWayType::Secondary;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "secondary_link" ) ) )
				{
					WayType = EOSMWayType::Secondary_Link;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "tertiary" ) ) )
				{
					WayType = EOSMWayType::Tertiary;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "tertiary_link" ) ) )
				{
					WayType = EOSMWayType::Tertiary_Link;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "residential" ) ) )
				{
					WayType = EOSMWayType::Residential;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "service" ) ) )
				{
					WayType = EOSMWayType::Service;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "unclassified" ) ) )
				{
					WayType = EOSMWayType::Unclassified;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "living_street" ) ) )
				{
					WayType = EOSMWayType::Living_Street;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "pedestrian" ) ) )
				{
					WayType = EOSMWayType::Pedestrian;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "track" ) ) )
				{
					WayType = EOSMWayType::Track;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "bus_guideway" ) ) )
				{
					WayType = EOSMWayType::Bus_Guideway;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "raceway" ) ) )
				{
					WayType = EOSMWayType::Raceway;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "road" ) ) )
				{
					WayType = EOSMWayType::Road;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "footway" ) ) )
				{
					WayType = EOSMWayType::Footway;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "cycleway" ) ) )
				{
					WayType = EOSMWayType::Cycleway;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "bridleway" ) ) )
				{
					WayType = EOSMWayType::Bridleway;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "steps" ) ) )
				{
					WayType = EOSMWayType::Steps;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "path" ) ) )
				{
					WayType = EOSMWayType::Path;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "proposed" ) ) )
				{
					WayType = EOSMWayType::Proposed;
				}
				else if( !FCString::Stricmp( AttributeValue, TEXT( "construction" ) ) )
				{
					WayType = EOSMWayType::Construction;
				}
				else
				{
					// Other type that we don't recognize yet.  See http://wiki.openstreetmap.org/wiki/Key:highway
				}

				CurrentWayInfo->WayType = WayType;
			}
			else if( !FCString::Stricmp( CurrentWayTagKey, TEXT( "building" ) ) )
			{
				CurrentWayInfo->WayType = EOSMWayType::Building;

				if( !FCString::Stricmp( AttributeValue, TEXT( "yes" ) ) )
				{
					CurrentWayInfo->WayType = EOSMWayType::Building;
				}
				else
				{
					// Other type that we don't recognize yet.  See http://wiki.openstreetmap.org/wiki/Key:building
				}
			}
			else if( !FCString::Stricmp( CurrentWayTagKey, TEXT( "height" ) ) )
			{
				// Check to see if there is a space character in the height value.  For now, we're looking
				// for straight-up floating point values.
				if( !FString( AttributeValue ).Contains( TEXT( " " ) ) )
				{
					// Okay, no space character.  So this has got to be a floating point number.  The OSM
					// spec says that the height values are in meters.
					CurrentWayInfo->Height = FPlatformString::Atod( AttributeValue );
				}
				else
				{
					// Looks like the height value contains units of some sort.
					// @todo: Add support for interpreting unit strings and converting the values
				}
			}
			else if (!FCString::Stricmp(CurrentWayTagKey, TEXT("building:levels")))
			{
				CurrentWayInfo->BuildingLevels = FPlatformString::Atoi(AttributeValue);
			}
			else if( !FCString::Stricmp( CurrentWayTagKey, TEXT( "oneway" ) ) )
			{
				if( !FCString::Stricmp( AttributeValue, TEXT( "yes" ) ) )
				{
					CurrentWayInfo->bIsOneWay = true;
				}
				else
				{
					CurrentWayInfo->bIsOneWay = false;
				}
			}
		}
	}

	return true;
}

bool FOSMFile::ProcessClose( const TCHAR* Element )
{
	if( ParsingState == ParsingState::Node )
	{
		NodeMap.Add( CurrentNodeID, CurrentNodeInfo );
		CurrentNodeID = 0;
		CurrentNodeInfo = nullptr;

		ParsingState = ParsingState::Root;
	}
	else if( ParsingState == ParsingState::Way )
	{
		Ways.Add( CurrentWayInfo );
		CurrentWayInfo = nullptr;

		ParsingState = ParsingState::Root;
	}
	else if( ParsingState == ParsingState::Way_NodeRef )
	{
		ParsingState = ParsingState::Way;
	}
	else if( ParsingState == ParsingState::Way_Tag )
	{
		CurrentWayTagKey = TEXT( "" );
		ParsingState = ParsingState::Way;
	}

	return true;
}


text:
"""\
This is a python port of "Goose" orignialy licensed to Gravity.com
under one or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.

Python port was written by Xavier Grangier for Recrutae

Gravity.com licenses this file
to you 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.
"""
import os
import json
import urllib2
import unittest
import socket
import mimetools

from StringIO import StringIO

from goose import Goose
from goose.utils import FileHelper
from goose.configuration import Configuration

CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))

# Response
class MockResponse():
    """\
    Base mock response class
    """
    code = 200
    msg = "OK"

    def __init__(self, cls):
        self.cls = cls

    def content(self):
        return "response"

    def response(self, req):
        data = self.content(req)
        url = req.get_full_url()
        headers = mimetools.Message(StringIO(''))
        resp = urllib2.addinfourl(StringIO(data), headers, url)
        resp.code = self.code
        resp.msg = self.msg
        return resp

class MockHTTPHandler(urllib2.HTTPHandler, urllib2.HTTPSHandler):
    """\
    Mocked HTTPHandler in order to query APIs locally
    """
    cls = None

    def https_open(self, req):
        return self.http_open(req)

    def http_open(self, req):
        r = self.cls.callback(self.cls)
        return r.response(req)

    @staticmethod
    def patch(cls):
        opener = urllib2.build_opener(MockHTTPHandler)
        urllib2.install_opener(opener)
        # dirty !
        for h in opener.handlers:
            if isinstance(h, MockHTTPHandler):
                h.cls = cls
        return [h for h in opener.handlers if isinstance(h, MockHTTPHandler)][0]

    @staticmethod
    def unpatch():
        # urllib2
        urllib2._opener = None

class BaseMockTests(unittest.TestCase):
    """\
    Base Mock test case
    """
    callback = MockResponse

    def setUp(self):
        # patch DNS
        self.original_getaddrinfo = socket.getaddrinfo
        socket.getaddrinfo = self.new_getaddrinfo
        MockHTTPHandler.patch(self)

    def tearDown(self):
        MockHTTPHandler.unpatch()
        # DNS
        socket.getaddrinfo = self.original_getaddrinfo

    def new_getaddrinfo(self, *args):
        return [(2, 1, 6, '', ('127.0.0.1', 0))]

    def _get_current_testname(self):
        return self.id().split('.')[-1:][0]

class MockResponseExtractors(MockResponse):
    def content(self, req):
        test, suite, module, cls, func = self.cls.id().split('.')
        path = os.path.join(
                os.path.dirname(CURRENT_PATH),
                "data",
                suite,
                module,
                "%s.html" % func)
        path = os.path.abspath(path)
        content = FileHelper.loadResourceFile(path)
        return content

class TestExtractionBase(BaseMockTests):
    """\
    Extraction test case
    """
    callback = MockResponseExtractors

    def getRawHtml(self):
        test, suite, module, cls, func = self.id().split('.')
        path = os.path.join(
                os.path.dirname(CURRENT_PATH),
                "data",
                suite,
                module,
                "%s.html" % func)
        path = os.path.abspath(path)
        content = FileHelper.loadResourceFile(path)
        return content

    def loadData(self):
        """\

        """
        test, suite, module, cls, func = self.id().split('.')
        path = os.path.join(
                os.path.dirname(CURRENT_PATH),
                "data",
                suite,
                module,
                "%s.json" % func)
        path = os.path.abspath(path)
        content = FileHelper.loadResourceFile(path)
        self.data = json.loads(content)

    def assert_cleaned_text(self, field, expected_value, result_value):
        """\

        """
        # # TODO : handle verbose level in tests
        # print "\n=======================::. ARTICLE REPORT %s .::======================\n" % self.id()
        # print 'expected_value (%s) \n' % len(expected_value)
        # print expected_value
        # print "-------"
        # print 'result_value (%s) \n' % len(result_value)
        # print result_value

        # cleaned_text is Null
        msg = u"Resulting article text was NULL!"
        self.assertNotEqual(result_value, None, msg=msg)

        # cleaned_text length
        msg = u"Article text was not as long as expected beginning!"
        self.assertTrue(len(expected_value) <= len(result_value), msg=msg)

        # clean_text value
        result_value = result_value[0:len(expected_value)]
        msg = u"The beginning of the article text was not as expected!"
        self.assertEqual(expected_value, result_value, msg=msg)

    def runArticleAssertions(self, article, fields):
        """\

        """
        for field in fields:
            expected_value = self.data['expected'][field]
            result_value = getattr(article, field, None)

            # custom assertion for a given field
            assertion = 'assert_%s' % field
            if hasattr(self, assertion):
                getattr(self, assertion)(field, expected_value, result_value)
                continue

            # default assertion
            msg = u"Error %s \nexpected: %s\nresult: %s" % (field, expected_value, result_value)
            self.assertEqual(expected_value, result_value, msg=msg)

    def extract(self, instance):
        article = instance.extract(url=self.data['url'])
        return article

    def getConfig(self):
        config = Configuration()
        config.enable_image_fetching = False
        return config

    def getArticle(self):
        """\

        """
        # load test case data
        self.loadData()

        # basic configuration
        # no image fetching
        config = self.getConfig()
        self.parser = config.get_parser()

        # target language
        # needed for non english language most of the time
        target_language = self.data.get('target_language')
        if target_language:
            config.target_language = target_language
            config.use_meta_language = False

        # run goose
        g = Goose(config=config)
        return self.extract(g)


text:
package mind;

public class Driver {
	public static void main(String[] args) {
		/*Brain brain =*/ new Brain();
	}
}