text:
.. _example-13:

==================================================
Post-Processing and Pipelining (from the Tutorial)
==================================================

Here you find an example of post-processing.

It consists of a main script `main.py` for the three phases
*pre-processing*, *run phase* and *post-processing* of a single neuron
simulation and a `analysis.py` file
giving an example of a potential data analysis encompassing plotting the results.
Moreover, there exists a `pipeline.py` file to crunch all first three phases into
a single function.

A detail explanation of the example can be found in the :ref:`tutorial` section.

Download: :download:`main.py <../../../examples/example_13_post_processing/main.py>`

Download: :download:`analysis.py <../../../examples/example_13_post_processing/analysis.py>`

Download: :download:`pipeline.py <../../../examples/example_13_post_processing/pipeline.py>`

------------
Main
------------

.. literalinclude:: ../../../examples/example_13_post_processing/main.py

----------
Analysis
----------

.. literalinclude:: ../../../examples/example_13_post_processing/analysis.py

-----------
Pipelining
-----------

Additionally, you can use pipelining.

Since these three steps pre-processing, run-phase, post-processing define a common pipeline,
you can actually also make *pypet* supervise all three steps at once.

You can define a pipeline function, that does the pre-processing and returns
the job function plus some optional arguments and the post-processing function
with some other optional arguments.

So, you could define the following pipeline function.
The pipeline function has to only accept the trajectory as first argument and
has to return 2 tuples, one for the run function and one for the
post-processing. Since none of our functions takes any other arguments than the trajectory
(and the pos-processing function the result list) we simply return an empty
tuple ``()`` for no arguments and an empty dictionary ``{}`` for no keyword arguments.

And that's it, than everything including the pre-processing and addition of parameters
is supervised by *pypet*. Check out the source code below:

.. literalinclude:: ../../../examples/example_13_post_processing/pipeline.py


text:
// Copyright 2016 Google Inc. All rights reserved.
//
// 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.

using UnityEngine;

namespace GVR.Samples.DragonTeam {
  /// <summary>
  /// Basic Orient constraint system for synchronizing one or more local Euler Axis between two
  /// Transforms on late update.
  /// </summary>
  public class OrientConstraint : MonoBehaviour {
    [Tooltip("The Driving transform whose local Euler Angles will be applied to the " +
             "Driven Transform in late update.")]
    public Transform Driver;

    [Tooltip("The Driven transform whose local Euler angles will be overwritten on late update " +
             "by the Driving Transform's.")]
    public Transform Driven;

    [Tooltip("Synchronize the local Euler X axis.")]
    public bool OrientX = false;

    [Tooltip("Synchronize the local Euler Y axis.")]
    public bool OrientY = true;

    [Tooltip("Synchronize the local Euler Z axis.")]
    public bool OrientZ = false;

    void LateUpdate() {
      Vector3 newEuler = Driven.transform.localEulerAngles;
      if (OrientX) {
        newEuler.x = Driver.transform.localEulerAngles.x;
      }
      if (OrientY) {
        newEuler.y = Driver.transform.localEulerAngles.y;
      }
      if (OrientZ) {
        newEuler.z = Driver.transform.localEulerAngles.z;
      }
      Driven.transform.localEulerAngles = newEuler;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
.hero {
  background: url("../../images/bg-image.jpg");
  width: 100vw;
  height: 100vh;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column; }


text: These files are an extract from the Microchip TCPIP stack


text:
<?php

declare(strict_types=1);

namespace App\Presenters;

use App\Forms\SignInFormFactory;
use Nette\Application\UI\Form;

/**
 * Sign in/out presenter
 */
class SignPresenter extends BasePresenter {

	/**
	 * @var SignInFormFactory Sign in form factory
	 * @inject
	 */
	public $signInFactory;

	/**
	 * User sign in
	 */
	public function actionIn() {
		if ($this->user->isLoggedIn()) {
			$this->redirect('Homepage:');
		}
	}

	/**
	 * Create sign in form
	 * @return Form Sign in form
	 */
	protected function createComponentSignInForm() {
		return $this->signInFactory->create(function () {
					$this->redirect('Homepage:');
				});
	}

	/**
	 * User sign out
	 */
	public function actionOut() {
		if (!$this->user->isLoggedIn()) {
			$this->redirect('Sign:in');
		} else {
			$this->getUser()->logout();
		}
	}

}


text:
{{+bindTo:partials.standard_nacl_api}}

ppb_file_system.h File Reference

{{- dummy div to appease doxygen -}}

Include dependency graph for ppb_file_system.h:

<map name="ppb__file__system_8h" id="ppb__file__system_8h">
</map>

Data Structures

struct  	PPB_FileSystem

 	The PPB_FileSystem struct identifies the file system type associated with a file.  More...

Defines

#define 	PPB_FILESYSTEM_INTERFACE   "PPB_FileSystem;1.0"

#define 	PPB_FILESYSTEM_INTERFACE   PPB_FILESYSTEM_INTERFACE

Typedefs

typedef struct PPB_FileSystem 	PPB_FileSystem

Detailed Description

This file defines the API to create a file system associated with a file.

Define Documentation

#define PPB_FILESYSTEM_INTERFACE   PPB_FILESYSTEM_INTERFACE

#define PPB_FILESYSTEM_INTERFACE   "PPB_FileSystem;1.0"

{{/partials.standard_nacl_api}}


text:
<?php

namespace PiApp\AdminBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerInterface;

use PiApp\AdminBundle\Twig\TokenParser\StyleSheetsTokenParser;
use PiApp\AdminBundle\Twig\TokenParser\StyleSheetTokenParser;
use PiApp\AdminBundle\Twig\TokenParser\JavascriptsTokenParser;
use PiApp\AdminBundle\Twig\TokenParser\JavascriptTokenParser;

/**
 * stylesheet and javascript tags used in twig
 * This extension lets you save the CSS and JS files with tags.
 *
 * @category   Admin_Twig
 * @package    Extension_layoutHead
 *
 * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
 */
class PiLayoutHeadExtension extends \Twig_Extension
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;

    /**
     *  absolute path to YUI jar file.
     */
    private $JAR_PATH;
    private $TEMP_FILES_DIR;
    private $options = array('type' => 'js',
            'linebreak' => false,
            'verbose' => false,
            'nomunge' => false,
            'semi' => false,
            'nooptimize' => false);
    private $files = array();

    /**
     * Constructor.
     *
     * @param ContainerInterface $container The service container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container         = $container;
        $this->JAR_PATH         = realpath($container->getParameter("kernel.root_dir") . "/Resources/java/yuicompressor-2.4.7.jar");
        $this->TEMP_FILES_DIR     = $container->getParameter("kernel.root_dir") . "/../web/yui";
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function getName()
    {
        return 'pi_app_admin';
    }

    /**
     * Returns the token parsers
     *
     *
     *     {% stylesheet "/path/to/css/file" %} to add a css file
     *  {% CMFstylesheets 'file' %} to render all css files
     *     {% javascript "/path/to/css/file" %} to add a js file
     *  {% CMFjavascripts 'file' %} to render all js files
     *
     *
     * @return string The extension name
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function getTokenParsers()
    {
        return array(
            new StyleSheetTokenParser($this->getName()),
            new StyleSheetsTokenParser($this->getName()),
            new JavascriptTokenParser($this->getName()),
            new JavascriptsTokenParser($this->getName()),
        );
    }

    /**
     * Returns a list of functions to add to the existing list.
     *
     *
     *
     *
     * @return array An array of functions
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function getFunctions() {
        return array(
                'CMFstylesheetsFunc'        => new \Twig_Function_Method($this, 'renderLink'),
                'CMFjavascriptsFunc'        => new \Twig_Function_Method($this, 'renderScript'),
        );
    }

    /**
     * Callbacks
     */

    /**
     * Add CSS file in the contener.
     *
     * @param string $file
     * @param string $order        ['append', 'prepend']
     *
     * @return void
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function addCssFile($file, $order = "append")
    {
        $css_files = ($this->container->has('css_files')) ? $this->container->get('css_files') : array();
        $is_order  = explode(':', $file);

        if (isset($is_order[1]) && !empty($is_order[1])){
            if (in_array($is_order[1], array('append', 'prepend'))){
                $file  = $is_order[0];
                $order = $is_order[1];
            }
        }

        // Append to the beginning of an array
        if ($order == "append") {
            array_push($css_files, $file);
        } elseif ($order == "prepend"){
            // Prepend to the beginning of an array
            array_unshift($css_files, $file);
        }

        // Removes duplicate values from an array
        $css_files = array_unique($css_files);

        $this->container->set('css_files', $css_files);
    }

    /**
     * Add JS file in the contener.
     *
     * @param string $file
     * @param string $order        ['append', 'prepend']
     *
     * @return void
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function addJsFile($file, $order = "append")
    {
        $js_files = ($this->container->has('js_files')) ? $this->container->get('js_files') : array();
        $is_order  = explode(':', $file);

        if (isset($is_order[1]) && !empty($is_order[1])){
            if (in_array($is_order[1], array('append', 'prepend'))){
                $file  = $is_order[0];
                $order = $is_order[1];
            }
        }

        // Append to the beginning of an array
        if ($order == "append") {
            array_push($js_files, $file);
        } elseif ($order == "prepend"){
            // Prepend to the beginning of an array
            array_unshift($js_files, $file);
        }

        // Removes duplicate values from an array
        $js_files = array_unique($js_files);

        $this->container->set('js_files', $js_files);
    }

    /**
     * Return all CSS files in the container in links.
     *
     * @param string $compressor        ['php', 'yui', 'file', 'array', 'empty']
     *
     * @return string
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function renderLink($compressor = "yui")
    {
        if (!$this->container->has('css_files'))
            return ;
        elseif ($compressor == "empty"){
            $this->container->set('css_files', array());
            return '';
        }

        $links              = array();
        $linksPath          = array();
        $this->files     = array();

        $all_stylesheets = $this->container->get('css_files');
        foreach($all_stylesheets as $stylesheet)
        {
            $stylesheet = trim($stylesheet);

            if (empty($stylesheet))
                continue;

            str_replace('http://', 'http', $stylesheet, $nb_http);
            str_replace('https://', 'https', $stylesheet, $nb_https);

            //$links[] = '<link type="text/css" rel="stylesheet" href="' . $this->container->get('router')->generate('public_head_file', array('file' => $stylesheet, 'filetype' => 'css')) . '" />';
            if ($nb_http == 0){
                $links[] = '    <link type="text/css" rel="stylesheet" href="' . $this->container->get('Request')->getBasePath() . '/' . $stylesheet.'" />';
                $this->files[]     = $this->container->getParameter("kernel.root_dir") . '/../web/' . $stylesheet;
                $linksPath[]    = $this->container->get('Request')->getBasePath() . '/' . $stylesheet;
            } else {
                $links[] = '    <link type="text/css" rel="stylesheet" href="' . $stylesheet.'" />';
                $this->files[]    = $stylesheet;
                $linksPath[]    = $stylesheet;
            }
        }

        if ($compressor == 'file'){
            return implode("\n", $links);
        }elseif ($compressor == 'php'){
            $this->options['type'] = "css";
            //return '<link type="text/css" rel="stylesheet" href="/css/app_cache_yui_css_'.$this->compress("path", "php_css").'__css" />';
            return '<link type="text/css" rel="stylesheet" href="/yui/css' . $this->container->get('Request')->getBasePath() . '/' . $this->compress("path", "php_css").'.css'.'" />';
           }elseif ($compressor == 'yui'){
            $this->options['type'] = "css";
            //return '<link type="text/css" rel="stylesheet" href="/css/app_cache_yui_css_'.$this->compress("path", "yui").'__css" />';
            return '<link type="text/css" rel="stylesheet" href="/yui/css' . $this->container->get('Request')->getBasePath() . '/' . $this->compress("path", "yui").'.css'.'" />';
           }elseif ($compressor == 'array'){
            return $linksPath;
           }
    }

    /**
     * Return all JS files in the container in links.
     *
     * @param string $compressor        ['php', 'yui', 'file', 'array', 'empty']
     *
     * @return string
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    public function renderScript($compressor = 'yui')
    {
        if (!$this->container->has('js_files'))
            return ;
        elseif ($compressor == "empty"){
            $this->container->set('js_files', array());
            return '';
        }

        $scripts          = array();
        $linksPath          = array();
        $this->files     = array();

        $all_javascripts = $this->container->get('js_files');
        foreach($all_javascripts as $javascript)
           {
               $javascript = trim($javascript);

               if (empty($javascript))
                   continue;

               str_replace('http://', 'http', $javascript, $nb_http);
               str_replace('https://', 'https', $javascript, $nb_https);

               //$scripts[] = '';
               if ($nb_http == 0){
                $scripts[]  = '    ';
                $this->files[]    = $this->container->getParameter("kernel.root_dir") . '/../web/' . $javascript;
                $linksPath[]    = $this->container->get('Request')->getBasePath() . '/' . $javascript;
              } else {
                $scripts[]  = '    ';
                $this->files[]    = $javascript;
                $linksPath[]    = $javascript;
               }
           }

           if ($compressor == 'file'){
            return implode("\n", $scripts);
           }elseif ($compressor == 'php'){
               $this->options['type'] = "js";
               //return '';
               return '';
           }elseif ($compressor == 'yui'){
               $this->options['type'] = "js";
               //return '';
               return '';
           }elseif ($compressor == 'array'){
            return $linksPath;
           }
    }

    /**
     * Executes the compression command in shell
     *
     * @param string $result            ['path', 'content']
     * @param string $compressor        ['yui', 'php_js', 'php_css']
     *
     * @return string    file path result
     * @access public
     *
     * @author Etienne de Longeaux <etienne.delongeaux@gmail.com>
     */
    private function compress($result = "path", $compressor = "yui")
    {
        // create the input
        foreach ($this->files as $file) {
            $basePath        = str_replace($this->container->getParameter("kernel.root_dir"). '/../web/', '', dirname($file));

            if (strtolower($this->options['type']) == "css"){
                $content_file    = str_replace(array('url("', "url('", "')", '")'), array('url(', 'url(', ')', ')'), file_get_contents($file)) or die("Cannot read from uploaded file");
                $content_file   = str_replace(array('url('), array('url(../../'.$basePath.'/'), $content_file);

                $content_file   = str_replace('@import "', "   @import \"../../".$basePath."/", $content_file);
                $content_file   = str_replace('";', '";   ', $content_file);

                $this->string  .= $content_file;
            }else
                $this->string  .=  file_get_contents($file) or die("Cannot read from uploaded file");
        }

        if (preg_match_all('/@import "([^`]*?)";/i', $this->string, $allImports, PREG_SET_ORDER)){
            $this->string = preg_replace('/@import "([^`]*?)";/i', '', $this->string);
            foreach($allImports as $k => $import){
                $this->string = $import[0] . "  " . $this->string;
            }
        }

        // create single file from all input
        $input_hash = sha1($this->string);
        // create path file
        $nameFile    = strtolower($this->options['type']) . '/' . $input_hash . '.' . strtolower($this->options['type']);
        $file         = $this->TEMP_FILES_DIR . '/' . $nameFile;

        $is_refresh_css_js_cache_file = $this->container->getParameter("pi_app_admin.page.refresh_css_js_cache_file");

        // we compress the content
        if ( ($is_refresh_css_js_cache_file || !file_exists($file)) && $this->container->get('pi_app_admin.file_manager')->save($file, $this->string, 0777)){
            switch (true) {
                case ($compressor == "yui"):
                    // start with basic command
                    $cmd = "java -Xmx32m -jar " . escapeshellarg($this->JAR_PATH) . ' ' . escapeshellarg($file) . " --charset UTF-8";

                    // set the file type
                    $cmd .= " --type " . (strtolower($this->options['type']) == "css" ? "css" : "js");

                    // and add options as needed
                    if ($this->options['linebreak'] && intval($this->options['linebreak']) > 0) {
                        $cmd .= ' --line-break ' . intval($this->options['linebreak']);
                    }

                    if ($this->options['verbose']) {
                        $cmd .= " -v";
                    }

                    if ($this->options['nomunge']) {
                        $cmd .= ' --nomunge';
                    }

                    if ($this->options['semi']) {
                        $cmd .= ' --preserve-semi';
                    }

                    if ($this->options['nooptimize']) {
                        $cmd .= ' --disable-optimizations';
                    }

                    // execute the command
                    exec($cmd . ' 2>&1', $raw_output);

                    // add line breaks to show errors in an intelligible manner
                    $flattened_output = implode("\n", $raw_output);
                    // we put the compressor content in the file.
                    file_put_contents($file, $flattened_output);
                    break;
                case ($compressor == "php_js"):
                    $flattened_output = str_replace("/*\n", "\n\n /*\n", $this->string);
                    $flattened_output = str_replace("/*!\n", "\n\n /*!\n", $flattened_output);
                    // we put the compressor content in the file.
                    file_put_contents($file, $flattened_output);
                    break;
                case ($compressor == "php_css"):
                    // Remove comments
                    $flattened_output = $this->container->get('pi_app_admin.string_manager')->remove_comment_in_css_file($this->string);
                    // Remove space after colons
                    $flattened_output = str_replace(': ', ':', $flattened_output);
                    // Remove whitespace
                    $flattened_output = $this->container->get('pi_app_admin.string_manager')->cleanWhitespace($flattened_output);
                    // we put the compressor content in the file.
                    file_put_contents($file, $flattened_output);
                    break;
                default:
                    // use default
                    break;
            }
        }

        // we initialize the content.
        $this->string = "";

        switch (true) {
            case ($result == "content"):
                return $flattened_output;
            case ($result == "path"):
                return $input_hash;
            default:
                return "";
        }
    }

}


text:
/**
* Author: Bob Chen
*/

package com.jcommerce.core.service;

import java.util.List;

import com.jcommerce.core.model.Cart;
import com.jcommerce.core.service.Criteria;
import com.jcommerce.core.model.Session;

public interface CartManager extends Manager {
    public Cart initialize(Cart obj);

    public List<Cart> getCartList(int firstRow, int maxRow);

    public int getCartCount(Criteria criteria);

    public List<Cart> getCartList(Criteria criteria);

    public List<Cart> getCartList(int firstRow, int maxRow, Criteria criteria);

    public List<Cart> getCartList();

    public Cart getCart(Long id);

    public void saveCart(Cart obj);

    public void removeCart(Long id);

    public List<Cart> getCartList(Session session);

    public void removeCarts(Session session);

    public void removeCarts(List<Cart> carts);
}


text:
package org.wso2.developerstudio.datamapper.diagram.providers.assistants;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.wso2.developerstudio.datamapper.diagram.providers.DataMapperElementTypes;
import org.wso2.developerstudio.datamapper.diagram.providers.DataMapperModelingAssistantProvider;

/**
 * @generated
 */
public class DataMapperModelingAssistantProviderOfAttributeEditPart extends
		DataMapperModelingAssistantProvider {

	/**
	 * @generated
	 */
	@Override
	public List<IElementType> getTypesForPopupBar(IAdaptable host) {
		List<IElementType> types = new ArrayList<IElementType>(2);
		types.add(DataMapperElementTypes.InNode_3008);
		types.add(DataMapperElementTypes.OutNode_3009);
		return types;
	}

}


text:
package com.kendelong.hellomodule.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kendelong.hellomodule.service.MyService;

@Controller
public class MyController
{
	@Autowired
	private MyService myService;

	@Autowired
	@Qualifier("rootMessage")
	private String rootMessage;

	@RequestMapping("/go")
	public String hello(Model model)
	{
		String message = myService.munge("hello");
		model.addAttribute("message", message + rootMessage);
		System.out.println("Dispatched to hello");
		return "hello";
	}
}


text:
require 'rails_helper'

RSpec.describe StaticPagesController,:type => :controller do
  describe "GET home" do
   it "should have index " do
      get :home
      expect(response).to have_http_status(:success)
   end
  end
end


text:
<title>Defining Predicates - GNU Compiler Collection (GCC) Internals</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="GNU Compiler Collection (GCC) Internals">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Predicates.html#Predicates" title="Predicates">
<link rel="prev" href="Machine_002dIndependent-Predicates.html#Machine_002dIndependent-Predicates" title="Machine-Independent Predicates">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Previous: Machine-Independent Predicates,
Up: Predicates

16.7.2 Defining Machine-Specific Predicates

Many machines have requirements for their operands that cannot be
expressed precisely using the generic predicates.  You can define
additional predicates using define_predicate and
define_special_predicate expressions.  These expressions have
three operands:

The name of the predicate, as it will be referred to in
match_operand or match_operator expressions.

An RTL expression which evaluates to true if the predicate allows the
operand <var>op</var>, false if it does not.  This expression can only use
the following RTL codes:

MATCH_OPERAND
When written inside a predicate expression, a MATCH_OPERAND
expression evaluates to true if the predicate it names would allow
<var>op</var>.  The operand number and constraint are ignored.  Due to
limitations in <samp>genrecog</samp>, you can only refer to generic
predicates and predicates that have already been defined.

MATCH_CODE
This expression evaluates to true if <var>op</var> or a specified
subexpression of <var>op</var> has one of a given list of RTX codes.

The first operand of this expression is a string constant containing a
comma-separated list of RTX code names (in lower case).  These are the
codes for which the MATCH_CODE will be true.

The second operand is a string constant which indicates what
subexpression of <var>op</var> to examine.  If it is absent or the empty
string, <var>op</var> itself is examined.  Otherwise, the string constant
must be a sequence of digits and/or lowercase letters.  Each character
indicates a subexpression to extract from the current expression; for
the first character this is <var>op</var>, for the second and subsequent
characters it is the result of the previous character.  A digit
<var>n</var> extracts ‘<samp>XEXP (<var>e</var>, <var>n</var>)</samp>’; a letter <var>l</var>
extracts ‘<samp>XVECEXP (<var>e</var>, 0, <var>n</var>)</samp>’ where <var>n</var> is the
alphabetic ordinal of <var>l</var> (0 for `a', 1 for 'b', and so on).  The
MATCH_CODE then examines the RTX code of the subexpression
extracted by the complete string.  It is not possible to extract
components of an rtvec that is not at position 0 within its RTX
object.

MATCH_TEST
This expression has one operand, a string constant containing a C
expression.  The predicate's arguments, <var>op</var> and <var>mode</var>, are
available with those names in the C expression.  The MATCH_TEST
evaluates to true if the C expression evaluates to a nonzero value.
MATCH_TEST expressions must not have side effects.

AND
IOR
NOT
IF_THEN_ELSE
The basic ‘<samp>MATCH_</samp>’ expressions can be combined using these
logical operators, which have the semantics of the C operators
‘<samp>&&</samp>’, ‘<samp>||</samp>’, ‘<samp>!</samp>’, and ‘<samp>? :</samp>’ respectively.  As
in Common Lisp, you may give an AND or IOR expression an
arbitrary number of arguments; this has exactly the same effect as
writing a chain of two-argument AND or IOR expressions.

An optional block of C code, which should execute
‘<samp>return true</samp>’ if the predicate is found to match and
‘<samp>return false</samp>’ if it does not.  It must not have any side
effects.  The predicate arguments, <var>op</var> and <var>mode</var>, are
available with those names.

If a code block is present in a predicate definition, then the RTL
expression must evaluate to true and the code block must
execute ‘<samp>return true</samp>’ for the predicate to allow the operand.
The RTL expression is evaluated first; do not re-check anything in the
code block that was checked in the RTL expression.

The program <samp>genrecog</samp> scans define_predicate and
define_special_predicate expressions to determine which RTX
codes are possibly allowed.  You should always make this explicit in
the RTL predicate expression, using MATCH_OPERAND and
MATCH_CODE.

Here is an example of a simple predicate definition, from the IA64
machine description:

     ;; True if <var>op</var> is a SYMBOL_REF which refers to the sdata section.
     (define_predicate "small_addr_symbolic_operand"
       (and (match_code "symbol_ref")
            (match_test "SYMBOL_REF_SMALL_ADDR_P (op)")))

And here is another, showing the use of the C block.

     ;; True if <var>op</var> is a register operand that is (or could be) a GR reg.
     (define_predicate "gr_register_operand"
       (match_operand 0 "register_operand")
     {
       unsigned int regno;
       if (GET_CODE (op) == SUBREG)
         op = SUBREG_REG (op);

       regno = REGNO (op);
       return (regno >= FIRST_PSEUDO_REGISTER || GENERAL_REGNO_P (regno));
     })

Predicates written with define_predicate automatically include
a test that <var>mode</var> is VOIDmode, or <var>op</var> has the same
mode as <var>mode</var>, or <var>op</var> is a CONST_INT or
CONST_DOUBLE.  They do not check specifically for
integer CONST_DOUBLE, nor do they test that the value of either
kind of constant fits in the requested mode.  This is because
target-specific predicates that take constants usually have to do more
stringent value checks anyway.  If you need the exact same treatment
of CONST_INT or CONST_DOUBLE that the generic predicates
provide, use a MATCH_OPERAND subexpression to call
const_int_operand, const_double_operand, or
immediate_operand.

Predicates written with define_special_predicate do not get any
automatic mode checks, and are treated as having special mode handling
by <samp>genrecog</samp>.

The program <samp>genpreds</samp> is responsible for generating code to
test predicates.  It also writes a header file containing function
declarations for all machine-specific predicates.  It is not necessary
to declare these predicates in <samp><var>cpu</var>-protos.h</samp>.


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./baPictureUploader.component'));
//# sourceMappingURL=index.js.map


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Communications;

import java.util.ArrayList;

/**
 *
 * @author jtroxel
 */
public class ReplayStreamer {

    private final MessagePipeline pipe;
    private final DataRelay relay;
    private ArrayList<String> msgs;

    public ReplayStreamer()
    {
        pipe = MessagePipeline.getInstance();
        relay = MessagePipeline.getDataRelay();
        msgs = new ArrayList<>();
    }

    public void loadStream(int timeStamp)
    {
        //SELECT * FROM PREVIOUS_LAUNCHES WHERE FLIGHT_ID = ID??
    }

    public int startStream(int startTime)
    {
        int curTime = startTime;
        int curIndex = 0;
        while(curIndex < msgs.size())
        {
            relay.forwardMessage(msgs.get(curIndex));
            //wait for some time???
            curIndex++;
        }

        return curTime;
    }
}


text:
var f = require("fcombine");

var error = {
	/*
		return a new function which is the old function wrapped
			with error handling logic. The error handling logic
			will pass the error to the errorHandler if the error
			exists

		@param Function errorHandler - handles error
		@param Function cb - function to wrap

		@return Function
	*/
	passTo: function passTo(errorHandler, cb) {
		return proxy;

		function proxy(err) {
			if (err) {
				if (typeof errorHandler === "string") {
					return this[errorHandler].apply(this, arguments);
				}
				return errorHandler.apply(this, arguments);
			} else {
				return cb.apply(this, arguments);
			}
		}
	},
	/*
		return a new function which is the old function wrapped
			with error handling logic, to throw the error
			if it exists

		@param Function cb - function to wrap

		@return Function
	*/
	throw: function _throw(cb) {
		return f.pre(error.thrower, cb);
	},
	/*
		error throwing function. Takes one argument and if it exists
		it will throw it

		@param Object err - error to throw
	*/
	thrower: function (err) {
		if (err) {
			throw err;
		}
	},
	/*
		return a new function which will pass the arguments to the cb
		if the error is whitelisted and pass it to the errorHandler if
		the error is not whitelisted

		@param Function whitelist - A function to be called with the error
			if it returns true then the error is whitelisted and the cb
			is invoked. If it returns false then the errorHandler is invoked
			if it returns anything else then neither get invoked
		@param Function cb - invoked if the error is whitelisted
		@param Function [optional] errorHandler. errorHandler to be invoked
			the default value is error.thrower

		@return Function
	*/
	whitelist: function (whitelist, cb, errorHandler) {
		errorHandler = errorHandler || error.thrower;

		return function _handleError(err) {
			var ret = (err === null ? true : whitelist(err));
			if (ret === true) {
				return cb.apply(this, arguments);
			} else if (ret === false) {
				return errorHandler.apply(this, arguments);
			}
		}
	}
}

module.exports = error;


text:
module ShibuyaRecord
  module QueryGenerators
    class Limit
      def self.limit(value, offset: nil)
        if offset
          "LIMIT ?, ?", [offset, value]
        else
          "LIMIT ?", [value]
        end
      end
    end
  end
end


text:
import _ from 'lodash'
import SoundEffectManager from 'sound-effect-manager'
const SEM = new SoundEffectManager()

const utils = {
  loadSound: (path, name) => SEM.loadFile(path, name),
  toKeys: (v,k) => k
}

/* -----------------------------
  Simon game sounds
----------------------------- */
const _SimonSounds = {
  error: '/apps/simon/error.mp3',
  success: '/apps/simon/success.mp3',
  levelComplete: '/apps/simon/nextLevel.mp3'
}
export const SimonSounds = _.mapValues(_SimonSounds, utils.toKeys)

/* -----------------------------
  Load all sounds
----------------------------- */
_.forEach(_SimonSounds, utils.loadSound)

export default SEM


text:
package org.apache.solr.handler;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.core.PluginInfo;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.FieldType;
import org.apache.solr.search.QParser;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.CommitUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
import org.apache.solr.update.processor.UpdateRequestProcessorChain;
import org.apache.solr.util.SimplePostTool;
import org.apache.solr.util.plugin.PluginInfoInitialized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.util.Collections.singletonMap;
import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;

public class BlobHandler extends RequestHandlerBase  implements PluginInfoInitialized{
  protected static final Logger log = LoggerFactory.getLogger(BlobHandler.class);

  private static final long MAX_SZ = 5*1024*1024;//2MB
  private long maxSize = MAX_SZ;

  @Override
  public void handleRequestBody(final SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    String httpMethod = (String) req.getContext().get("httpMethod");
    String path = (String) req.getContext().get("path");
    SolrConfigHandler.setWt(req,"json");

    List<String> pieces = StrUtils.splitSmart(path, '/');
    String blobName = null;
    if(pieces.size()>=3) blobName = pieces.get(2);

    if("POST".equals(httpMethod)) {
      if (blobName == null || blobName.isEmpty()) {
        rsp.add("error","Name not found");
        return;
      }
      String err = SolrConfigHandler.validateName(blobName);
      if(err!=null){
        log.warn("no blob name");
        rsp.add("error", err);
        return;
      }
      if(req.getContentStreams() == null )  {
        log.warn("no content stream");
        rsp.add("error","No stream");
        return;
      }

      for (ContentStream stream : req.getContentStreams()) {
        ByteBuffer payload = SimplePostTool.inputStreamToByteArray(stream.getStream(), maxSize);
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(payload.array(),payload.position(),payload.limit());
        String md5 = new BigInteger(1,m.digest()).toString(16);

        TopDocs duplicate = req.getSearcher().search(new TermQuery(new Term("md5", md5)), 1);
        if(duplicate.totalHits >0){
          rsp.add("error", "duplicate entry");
          req.forward(null,
              new MapSolrParams((Map) makeMap(
              "q", "md5:" + md5,
              "fl", "id,size,version,timestamp,blobName")),
              rsp);
          log.warn("duplicate entry for blob :"+blobName);
          return;
        }

        TopFieldDocs docs = req.getSearcher().search(new TermQuery(new Term("blobName", blobName)),
            null, 1, new Sort(new SortField("version", SortField.Type.LONG, true)));

        long version = 0;
        if(docs.totalHits >0){
          Document doc = req.getSearcher().doc(docs.scoreDocs[0].doc);
          Number n = doc.getField("version").numericValue();
          version = n.longValue();
        }
        version++;
        String id = blobName+"/"+version;
        Map<String, Object> doc = makeMap(
            "id", id,
            "md5", md5,
            "blobName", blobName,
            "version", version,
            "timestamp", new Date(),
            "size", payload.limit(),
            "blob", payload);
        verifyWithRealtimeGet(blobName, version, req, doc);
        log.info(MessageFormat.format("New blob inserting {0} ,size {1}, md5 {2}",doc.get("id"), payload.limit(),md5));
        indexMap(req, rsp, doc);
        log.info(" Successfully Added and committed a blob with id {} and size {} ",id, payload.limit());

        break;
      }

    } else {
      int version =-1;
      if(pieces.size()>3){
        try {
          version = Integer.parseInt(pieces.get(3));
        } catch (NumberFormatException e) {
          rsp.add("error", "Invalid version" + pieces.get(3));
          return;
        }

      }
      if(ReplicationHandler.FILE_STREAM.equals(req.getParams().get(CommonParams.WT))){
        if(blobName == null ){
          throw new SolrException(SolrException.ErrorCode.NOT_FOUND, "Please send the request in the format /blob/<blobName>/<version>");
        } else {
          String q = "blobName:{0}";
          if(version != -1) q = "id:{0}/{1}";
          QParser qparser =  QParser.getParser(MessageFormat.format(q,blobName,version) , "lucene", req);
          final TopDocs docs = req.getSearcher().search(qparser.parse(), 1, new Sort( new SortField("version", SortField.Type.LONG, true)));
          if(docs.totalHits>0){
            rsp.add(ReplicationHandler.FILE_STREAM, new SolrCore.RawWriter(){

              @Override
              public void write(OutputStream os) throws IOException {
                Document doc = req.getSearcher().doc(docs.scoreDocs[0].doc);
                IndexableField sf = doc.getField("blob");
                FieldType fieldType = req.getSchema().getField("blob").getType();
                ByteBuffer buf = (ByteBuffer) fieldType.toObject(sf);
                if(buf == null){
                  //should never happen unless a user wrote this document directly
                  throw new SolrException(SolrException.ErrorCode.NOT_FOUND, "Invalid document . No field called blob");
                } else {
                  os.write(buf.array(),0,buf.limit());
                }
              }
            });

          } else {
            throw new SolrException(SolrException.ErrorCode.NOT_FOUND,
                MessageFormat.format("Invalid combination of blobName {0} and version {1}", blobName,version));
          }

        }
      } else {
        String q = "*:*";
        if(blobName != null){
          q = "blobName:{0}";
          if(version != -1){
            q = "id:{0}/{1}";
          }
        }

        req.forward(null,
            new MapSolrParams((Map) makeMap(
                "q", MessageFormat.format(q, blobName, version),
                "fl", "id,size,version,timestamp,blobName,md5",
                "sort", "version desc"))
            , rsp);
      }
    }
  }

  private void verifyWithRealtimeGet(String blobName, long version, SolrQueryRequest req, Map<String, Object> doc) {
    for(;;) {
      SolrQueryResponse response = new SolrQueryResponse();
      String id = blobName + "/" + version;
      req.forward("/get", new MapSolrParams(singletonMap("id", id)), response);
      if(response.getValues().get("doc") == null) {
        //ensure that the version does not exist
        return;
      } else {
        log.info("id {} already exists trying next ",id);
        version++;
        doc.put("version", version);
        id = blobName + "/" + version;
        doc.put("id", id);
      }
   }

  }

  public static void indexMap(SolrQueryRequest req, SolrQueryResponse rsp, Map<String, Object> doc) throws IOException {
    SolrInputDocument solrDoc = new SolrInputDocument();
    for (Map.Entry<String, Object> e : doc.entrySet()) solrDoc.addField(e.getKey(),e.getValue());
    UpdateRequestProcessorChain processorChain = req.getCore().getUpdateProcessingChain(req.getParams().get(UpdateParams.UPDATE_CHAIN));
    UpdateRequestProcessor processor = processorChain.createProcessor(req, rsp);
    AddUpdateCommand cmd = new AddUpdateCommand(req);
    cmd.solrDoc = solrDoc;
    log.info("Adding doc "+doc);
    processor.processAdd(cmd);
    log.info("committing doc"+doc);
    processor.processCommit(new CommitUpdateCommand(req, false));
  }

  @Override
  public SolrRequestHandler getSubHandler(String subPath) {
    if(StrUtils.splitSmart(subPath,'/').size()>4)  return null;
    return this;
  }

//////////////////////// SolrInfoMBeans methods //////////////////////

  @Override
  public String getDescription() {
    return "Load Jars into a system index";
  }

  public static final String SCHEMA = "<?xml version='1.0' ?>\n" +
      "<schema name='_system collection or core' version='1.1'>\n" +
      "  <fieldtype name='string'  class='solr.StrField' sortMissingLast='true' omitNorms='true'/>\n" +
      "  <fieldType name='long' class='solr.TrieLongField' precisionStep='0' positionIncrementGap='0'/>\n" +
      "  <fieldType name='bytes' class='solr.BinaryField'/>\n" +
      "  <fieldType name='date' class='solr.TrieDateField'/>\n" +
      "  <field name='id'   type='string'   indexed='true'  stored='true'  multiValued='false' required='true'/>\n" +
      "  <field name='md5'   type='string'   indexed='true'  stored='true'  multiValued='false' required='true'/>\n" +
      "  <field name='blob'      type='bytes'   indexed='false' stored='true'  multiValued='false' />\n" +
      "  <field name='size'      type='long'   indexed='true' stored='true'  multiValued='false' />\n" +
      "  <field name='version'   type='long'     indexed='true'  stored='true'  multiValued='false' />\n" +
      "  <field name='timestamp'   type='date'   indexed='true'  stored='true'  multiValued='false' />\n" +
      "  <field name='blobName'      type='string'   indexed='true'  stored='true'  multiValued='false' />\n" +
      "  <field name='_version_' type='long'     indexed='true'  stored='true'/>\n" +
      "  <uniqueKey>id</uniqueKey>\n" +
      "</schema>" ;

  public static final String CONF = "<?xml version='1.0' ?>\n" +
      "<config>\n" +
      "<luceneMatchVersion>LATEST</luceneMatchVersion>\n" +
      "<directoryFactory name='DirectoryFactory' class='${solr.directoryFactory:solr.StandardDirectoryFactory}'/>\n" +
      "<updateHandler class='solr.DirectUpdateHandler2'>\n" +
      "  <updateLog>\n" +
      "    <str name='dir'>${solr.ulog.dir:}</str>\n" +
      "  </updateLog>\n     " +
      "  <autoCommit> \n" +
      "       <maxDocs>1</maxDocs> \n" +
      "       <openSearcher>true</openSearcher> \n" +
      "  </autoCommit>" +
      "</updateHandler>\n" +
      "<requestHandler name='standard' class='solr.StandardRequestHandler' default='true' />\n" +
      "<requestHandler name='/analysis/field' startup='lazy' class='solr.FieldAnalysisRequestHandler' />\n" +
      "<requestHandler name='/blob' class='solr.BlobHandler'>\n" +
      "  <lst name='invariants'>\n"+
           "<str name='maxSize'>${blob.max.size.mb:5}</str>\n"+
         "</lst>\n"+
      "</requestHandler>\n" +
      "</config>" ;

  @Override
  public void init(PluginInfo info) {
    super.init(info.initArgs);
    if(info.initArgs != null ){
      NamedList invariants = (NamedList) info.initArgs.get(PluginInfo.INVARIANTS);
      if(invariants != null){
        Object o = invariants.get("maxSize");
        if(o != null){
          maxSize = Long.parseLong(String.valueOf(o));
          maxSize = maxSize*1024*1024;
        }
      }

    }
  }
}


text:
package main

import (
	"fmt"
	"os"

	"github.com/Symantec/Dominator/imagepublishers/amipublisher"
	libjson "github.com/Symantec/Dominator/lib/json"
	"github.com/Symantec/Dominator/lib/log"
)

func deleteTagsSubcommand(args []string, logger log.DebugLogger) {
	err := deleteTags(args[0], args[1:], logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error deleting tags for resources: %s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}

func deleteTags(tagKey string, resultsFiles []string,
	logger log.DebugLogger) error {
	results := make([]amipublisher.Resource, 0)
	for _, resultsFile := range resultsFiles {
		fileResults := make([]amipublisher.Resource, 0)
		if err := libjson.ReadFromFile(resultsFile, &fileResults); err != nil {
			return err
		}
		results = append(results, fileResults...)
	}
	tagKeys := make([]string, 1)
	tagKeys[0] = tagKey
	return amipublisher.DeleteTags(results, tagKeys, logger)
}

func deleteTagsOnUnpackersSubcommand(args []string, logger log.DebugLogger) {
	err := deleteTagsOnUnpackers(args[0], logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error deleting tags on unpackers: %s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}

func deleteTagsOnUnpackers(tagKey string, logger log.DebugLogger) error {
	tagKeys := []string{tagKey}
	return amipublisher.DeleteTagsOnUnpackers(targets, skipTargets,
		*instanceName, tagKeys, logger)
}


text:
*****************************
Mode d'emploi du contributeur
*****************************

Philosophie
===========

Le travail dans Dezède se veut le plus scientifique possible.  Ainsi, toute
donnée ne pourra être considérée comme fiable si aucune source ne peut la
soutenir.  Toute contribution devra donc être réalisée avec comme point de
départ la source.  Le travail du musicologue s'en trouve donc facilité, car
la mécanique rigoureuse de Dezède lui impose de faire les choses proprement.

Débuter
=======

Pour commencer, munissez-vous d'une source historique.  Comme nous travaillons
sur l'histoire du spectacle, la source souvent privilégiée est le périodique
contemporain de l'événement.  Le plus souvent il s'agit de l'annonce du
spectacle le jour même ou quelques jours avant dans le journal du coin.  On
trouve presque aussi souvent des comptes rendus du spectacle le lendemain ou
quelques jours après dans le même journal.

Saisie de la source
-------------------

Rendez-vous sur `<https://dezede.org/admin/libretto/source/add/>`_.
Remplissez les différents champs courants (sauf ``Événements``) tout en tenant
compte des :ref:`typo`.

Une fois la saisie terminée, cliquez sur
``Sauvegarder et continuer l'édition``.

Votre source est sauvegardée et vous pouvez désormais y ajouter des événements.

Saisie des événements
---------------------


text:
import * as React from 'react';
import * as Swipeable from 'react-swipeable';

class SampleComponent extends React.PureComponent<Swipeable.SwipeableProps> {
  private handleSwiped: Swipeable.OnSwipedCallback = () => {};
  private handleSwiping: Swipeable.OnSwipingCallback = () => {};
  private handleSwipingUp: Swipeable.OnSwipingDirectionCallback = () => {};
  private handleSwipingRight: Swipeable.OnSwipingDirectionCallback = () => {};
  private handleSwipingDown: Swipeable.OnSwipingDirectionCallback = () => {};
  private handleSwipingLeft: Swipeable.OnSwipingDirectionCallback = () => {};
  private handleSwipedUp: Swipeable.OnSwipedDirectionCallback = () => {};
  private handleSwipedRight: Swipeable.OnSwipedDirectionCallback = () => {};
  private handleSwipedDown: Swipeable.OnSwipedDirectionCallback = () => {};
  private handleSwipedLeft: Swipeable.OnSwipedDirectionCallback = () => {};
  private handleTap: Swipeable.OnTapCallback = () => {};
  private handleClick = () => {};

  render() {
    return (
      <Swipeable
        onSwiped={this.handleSwiped}
        onSwiping={this.handleSwiping}
        onSwipingUp={this.handleSwipingUp}
        onSwipingRight={this.handleSwipingRight}
        onSwipingDown={this.handleSwipingDown}
        onSwipingLeft={this.handleSwipingLeft}
        onSwipedUp={this.handleSwipedUp}
        onSwipedRight={this.handleSwipedRight}
        onSwipedDown={this.handleSwipedDown}
        onSwipedLeft={this.handleSwipedLeft}
        onTap={this.handleTap}
        flickThreshold={10}
        delta={10}
        preventDefaultTouchmoveEvent
        stopPropagation
        nodeName="swipe"
        trackMouse
        onClick={this.handleClick}
      >
        <div>
          This element can be swiped
        </div>
      </Swipeable>
    );
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright 2013 Christian Grach

     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.
-->

<resources>

    <declare-styleable name="FlowLayout">
        <attr name="horizontalSpacing" format="dimension" />
        <attr name="verticalSpacing" format="dimension" />
        <attr name="android:orientation" />
    </declare-styleable>
    <declare-styleable name="FlowLayout_Layout">
        <attr name="layout_newLine" format="boolean" />
        <attr name="layout_horizontalSpacing" format="dimension" />
        <attr name="layout_verticalSpacing" format="dimension" />
    </declare-styleable>
    <declare-styleable name="RelativeSquareLayout">
        <attr name="constraint">
            <enum name="width" value="0" />
            <enum name="height" value="1" />
        </attr>
    </declare-styleable>

</resources>


text:
require('es6-promise').polyfill()

import Conversation from '../general/conversation-framework/conversation'
import BaseHandler from './base.handler'
import Memory from '../services/food-order-processing/capabilities/memory'
import Waiter from '../services/food-order-processing/workers/waiter'
import cache from '../caching'
import disambiguator from '../services/food-order-processing/capabilities/message-disambiguation/deterministic-disambiguator'

class MessageHandler extends BaseHandler {
  constructor() {
    super()
    this.processMessage = this
      .processMessage
      .bind(this)
  }

  processMessage(req, res) {
    const message = req.body.Body
    const senderId = req.body.senderId
    const sender = {
      id : senderId
    }

    // Setup memory
    let memory = new Memory(cache)

    // Setup Brain
    let brain = {
      disambiguator: disambiguator,
      memory: memory
    }

    // Setup waiter worker
    let waiter = new Waiter(brain)
    let convo = null

    // See if waiter remembers sender
    if (waiter.brain.memory.recalls(sender)){
      convo = waiter.brain.memory.recallConversationWith(sender)
    } else {
      convo = new Conversation(['me',sender.id])
      waiter.brain.memory.memorize(sender)
    }

    console.log(convo)

    waiter.brain.memory.add(convo, message)

    // Map to action based on input and current conversation context
    let outcome = waiter.actOnMessage(message, convo)

    // Let app output response
    res.json({response: outcome})
  }
}

export default new MessageHandler()


text:
package com.revlo.requests;

import lombok.Builder;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Builder
@Data
public class BonusPointsRequest implements Request {
    private String username;
    private Integer amount;

    @Override
    public Map<String, String> params() {
        return new HashMap<>();
    }

    @Override
    public String payload() {
        if (getAmount() != null) {
            return "{\"amount\":" + getAmount() + "}";
        }
        return "{}";
    }
}


text:
package org.projectfloodlight.openflow.protocol.ver13;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.hamcrest.CoreMatchers;

public class OFOxmBsnGlobalVrfAllowedVer13Test {
    OFOxms factory;

    final static byte[] OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED =
        new byte[] { 0x0, 0x3, 0x6, 0x1, 0x1 };

    @Before
    public void setup() {
        factory = OFOxmsVer13.INSTANCE;
    }

    @Test
    public void testWrite() {
        OFOxmBsnGlobalVrfAllowed.Builder builder = factory.buildBsnGlobalVrfAllowed();
        builder.setValue(OFBooleanValue.TRUE);
        OFOxmBsnGlobalVrfAllowed oxmBsnGlobalVrfAllowed = builder.build();
        ByteBuf bb = Unpooled.buffer();
        oxmBsnGlobalVrfAllowed.writeTo(bb);
        byte[] written = new byte[bb.readableBytes()];
        bb.readBytes(written);

        assertThat(written, CoreMatchers.equalTo(OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED));
    }

    @Test
    public void testRead() throws Exception {
        OFOxmBsnGlobalVrfAllowed.Builder builder = factory.buildBsnGlobalVrfAllowed();
        builder.setValue(OFBooleanValue.TRUE);
        OFOxmBsnGlobalVrfAllowed oxmBsnGlobalVrfAllowedBuilt = builder.build();

        ByteBuf input = Unpooled.copiedBuffer(OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED);

        // FIXME should invoke the overall reader once implemented
        OFOxmBsnGlobalVrfAllowed oxmBsnGlobalVrfAllowedRead = OFOxmBsnGlobalVrfAllowedVer13.READER.readFrom(input);
        assertEquals(OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED.length, input.readerIndex());

        assertEquals(oxmBsnGlobalVrfAllowedBuilt, oxmBsnGlobalVrfAllowedRead);
   }

   @Test
   public void testReadWrite() throws Exception {
       ByteBuf input = Unpooled.copiedBuffer(OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED);

       // FIXME should invoke the overall reader once implemented
       OFOxmBsnGlobalVrfAllowed oxmBsnGlobalVrfAllowed = OFOxmBsnGlobalVrfAllowedVer13.READER.readFrom(input);
       assertEquals(OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED.length, input.readerIndex());

       // write message again
       ByteBuf bb = Unpooled.buffer();
       oxmBsnGlobalVrfAllowed.writeTo(bb);
       byte[] written = new byte[bb.readableBytes()];
       bb.readBytes(written);

       assertThat(written, CoreMatchers.equalTo(OXM_BSN_GLOBAL_VRF_ALLOWED_SERIALIZED));
   }

}


text:
using ::testing::_;
using ::testing::DeleteArg;
using ::testing::DoAll;
using ::testing::Eq;
using ::testing::IsNull;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::NotNull;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::SetArgumentPointee;
using ::testing::StrictMock;
using content::BrowserThread;
using content::RenderViewHostTester;
using content::WebContents;

namespace {
const bool kFalse = false;
const bool kTrue = true;
}

namespace safe_browsing {
namespace {
// This matcher verifies that the client computed verdict
// (ClientPhishingRequest) which is passed to SendClientReportPhishingRequest
// has the expected fields set.  Note: we can't simply compare the protocol
// buffer strings because the BrowserFeatureExtractor might add features to the
// verdict object before calling SendClientReportPhishingRequest.
MATCHER_P(PartiallyEqualVerdict, other, "") {
  return (other.url() == arg.url() &&
          other.client_score() == arg.client_score() &&
          other.is_phishing() == arg.is_phishing());
}

MATCHER_P(PartiallyEqualMalwareVerdict, other, "") {
  return (other.url() == arg.url() &&
          other.feature_map_size() == arg.feature_map_size());
}

// Test that the callback is NULL when the verdict is not phishing.
MATCHER(CallbackIsNull, "") {
  return arg.is_null();
}

ACTION(QuitUIMessageLoop) {
  EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI));
  MessageLoopForUI::current()->Quit();
}

// It's kind of insane that InvokeArgument doesn't work with callbacks, but it
// doesn't seem like it.
ACTION_TEMPLATE(InvokeCallbackArgument,
                HAS_1_TEMPLATE_PARAMS(int, k),
                AND_2_VALUE_PARAMS(p0, p1)) {
  ::std::tr1::get<k>(args).Run(p0, p1);
}

void EmptyUrlCheckCallback(bool processed) {
}

class MockClientSideDetectionService : public ClientSideDetectionService {
 public:
  MockClientSideDetectionService() : ClientSideDetectionService(NULL) {}
  virtual ~MockClientSideDetectionService() {};

  MOCK_METHOD2(SendClientReportPhishingRequest,
               void(ClientPhishingRequest*,
                    const ClientReportPhishingRequestCallback&));
  MOCK_METHOD2(SendClientReportMalwareRequest,
               void(ClientMalwareRequest*,
                    const ClientReportMalwareRequestCallback&));
  MOCK_CONST_METHOD1(IsPrivateIPAddress, bool(const std::string&));
  MOCK_METHOD2(GetValidCachedResult, bool(const GURL&, bool*));
  MOCK_METHOD1(IsInCache, bool(const GURL&));
  MOCK_METHOD0(OverPhishingReportLimit, bool());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockClientSideDetectionService);
};

class MockSafeBrowsingUIManager : public SafeBrowsingUIManager {
 public:
  explicit MockSafeBrowsingUIManager(SafeBrowsingService* service)
      : SafeBrowsingUIManager(service) { }

  MOCK_METHOD1(DoDisplayBlockingPage, void(const UnsafeResource& resource));

  // Helper function which calls OnBlockingPageComplete for this client
  // object.
  void InvokeOnBlockingPageComplete(const UrlCheckCallback& callback) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    DCHECK(!callback.is_null());
    // Note: this will delete the client object in the case of the CsdClient
    // implementation.
    callback.Run(false);
  }

 protected:
  virtual ~MockSafeBrowsingUIManager() { }

 private:
  DISALLOW_COPY_AND_ASSIGN(MockSafeBrowsingUIManager);
};

class MockSafeBrowsingDatabaseManager : public SafeBrowsingDatabaseManager {
 public:
  explicit MockSafeBrowsingDatabaseManager(SafeBrowsingService* service)
      : SafeBrowsingDatabaseManager(service) { }

  MOCK_METHOD1(MatchCsdWhitelistUrl, bool(const GURL&));

 protected:
  virtual ~MockSafeBrowsingDatabaseManager() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(MockSafeBrowsingDatabaseManager);
};

class MockTestingProfile : public TestingProfile {
 public:
  MockTestingProfile() {}
  virtual ~MockTestingProfile() {}

  MOCK_CONST_METHOD0(IsOffTheRecord, bool());
};

class MockBrowserFeatureExtractor : public BrowserFeatureExtractor {
 public:
  explicit MockBrowserFeatureExtractor(
      WebContents* tab,
      ClientSideDetectionService* service)
      : BrowserFeatureExtractor(tab, service) {}
  virtual ~MockBrowserFeatureExtractor() {}

  MOCK_METHOD3(ExtractFeatures,
               void(const BrowseInfo* info,
                    ClientPhishingRequest*,
                    const BrowserFeatureExtractor::DoneCallback&));

  MOCK_METHOD2(ExtractMalwareFeatures,
               void(const BrowseInfo* info,
                    ClientMalwareRequest*));
};

// Helper function which quits the UI message loop from the IO message loop.
void QuitUIMessageLoopFromIO() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  BrowserThread::PostTask(BrowserThread::UI,
                          FROM_HERE,
                          MessageLoop::QuitClosure());
}
}  // namespace

class ClientSideDetectionHostTest : public ChromeRenderViewHostTestHarness {
 public:
  typedef SafeBrowsingUIManager::UnsafeResource UnsafeResource;

  virtual void SetUp() {
    // Set custom profile object so that we can mock calls to IsOffTheRecord.
    // This needs to happen before we call the parent SetUp() function.  We use
    // a nice mock because other parts of the code are calling IsOffTheRecord.
    mock_profile_ = new NiceMock<MockTestingProfile>();
    browser_context_.reset(mock_profile_);

    ui_thread_.reset(new content::TestBrowserThread(BrowserThread::UI,
                                                    &message_loop_));
    file_user_blocking_thread_.reset(
        new content::TestBrowserThread(BrowserThread::FILE_USER_BLOCKING,
        &message_loop_));
    // Note: we're starting a real IO thread to make sure our DCHECKs that
    // verify which thread is running are actually tested.
    io_thread_.reset(new content::TestBrowserThread(BrowserThread::IO));
    ASSERT_TRUE(io_thread_->Start());

    ChromeRenderViewHostTestHarness::SetUp();

    // Inject service classes.
    csd_service_.reset(new StrictMock<MockClientSideDetectionService>());
    // Only used for initializing mock objects.
    SafeBrowsingService* sb_service =
        SafeBrowsingService::CreateSafeBrowsingService();
    database_manager_ =
        new StrictMock<MockSafeBrowsingDatabaseManager>(sb_service);
    ui_manager_ = new StrictMock<MockSafeBrowsingUIManager>(sb_service);
    csd_host_.reset(safe_browsing::ClientSideDetectionHost::Create(
        web_contents()));
    csd_host_->set_client_side_detection_service(csd_service_.get());
    csd_host_->set_safe_browsing_managers(ui_manager_, database_manager_);
    // We need to create this here since we don't call
    // DidNavigateMainFramePostCommit in this test.
    csd_host_->browse_info_.reset(new BrowseInfo);
  }

  static void RunAllPendingOnIO(base::WaitableEvent* event) {
    MessageLoop::current()->RunUntilIdle();
    event->Signal();
  }

  virtual void TearDown() {
    // Delete the host object on the UI thread and release the
    // SafeBrowsingService.
    BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE,
                              csd_host_.release());
    database_manager_ = NULL;
    ui_manager_ = NULL;
    message_loop_.RunUntilIdle();
    ChromeRenderViewHostTestHarness::TearDown();

    // Let the tasks on the IO thread run to avoid memory leaks.
    base::WaitableEvent done(false, false);
    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
        base::Bind(RunAllPendingOnIO, &done));
    done.Wait();
    io_thread_.reset();
    message_loop_.RunUntilIdle();
    file_user_blocking_thread_.reset();
    ui_thread_.reset();
  }

  void OnPhishingDetectionDone(const std::string& verdict_str) {
    csd_host_->OnPhishingDetectionDone(verdict_str);
  }

  void UpdateIPHostMap(const std::string& ip, const std::string& host) {
    csd_host_->UpdateIPHostMap(ip, host);
  }

  BrowseInfo* GetBrowseInfo() {
    return csd_host_->browse_info_.get();
  }

  void FlushIOMessageLoop() {
    // If there was a message posted on the IO thread to display the
    // interstitial page we know that it would have been posted before
    // we put the quit message there.
    BrowserThread::PostTask(BrowserThread::IO,
                            FROM_HERE,
                            base::Bind(&QuitUIMessageLoopFromIO));
    MessageLoop::current()->Run();
  }

  void ExpectPreClassificationChecks(const GURL& url,
                                     const bool* is_private,
                                     const bool* is_incognito,
                                     const bool* match_csd_whitelist,
                                     const bool* get_valid_cached_result,
                                     const bool* is_in_cache,
                                     const bool* over_report_limit) {
    if (is_private) {
      EXPECT_CALL(*csd_service_, IsPrivateIPAddress(_))
          .WillOnce(Return(*is_private));
    }
    if (is_incognito) {
      EXPECT_CALL(*mock_profile_, IsOffTheRecord())
          .WillRepeatedly(Return(*is_incognito));
    }
    if (match_csd_whitelist) {
      EXPECT_CALL(*database_manager_, MatchCsdWhitelistUrl(url))
          .WillOnce(Return(*match_csd_whitelist));
    }
    if (get_valid_cached_result) {
      EXPECT_CALL(*csd_service_, GetValidCachedResult(url, NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(true),
                          Return(*get_valid_cached_result)));
    }
    if (is_in_cache) {
      EXPECT_CALL(*csd_service_, IsInCache(url)).WillOnce(Return(*is_in_cache));
    }
    if (over_report_limit) {
      EXPECT_CALL(*csd_service_, OverPhishingReportLimit())
          .WillOnce(Return(*over_report_limit));
    }
  }

  void WaitAndCheckPreClassificationChecks() {
    // Wait for CheckCsdWhitelist to be called if at all.
    FlushIOMessageLoop();
    // Checks for CheckCache() to be called if at all.
    MessageLoop::current()->RunUntilIdle();
    EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
    EXPECT_TRUE(Mock::VerifyAndClear(ui_manager_.get()));
    EXPECT_TRUE(Mock::VerifyAndClear(database_manager_.get()));
    EXPECT_TRUE(Mock::VerifyAndClear(mock_profile_));
  }

  void SetFeatureExtractor(BrowserFeatureExtractor* extractor) {
    csd_host_->feature_extractor_.reset(extractor);
  }

  void SetRedirectChain(const std::vector<GURL>& redirect_chain) {
    csd_host_->browse_info_->url_redirects = redirect_chain;
  }

  void SetUnsafeResourceToCurrent() {
    UnsafeResource resource;
    resource.url = GURL("http://www.malware.com/");
    resource.original_url = web_contents()->GetURL();
    resource.is_subresource = true;
    resource.threat_type = SB_THREAT_TYPE_URL_MALWARE;
    resource.callback = base::Bind(&EmptyUrlCheckCallback);
    resource.render_process_host_id = web_contents()->GetRenderProcessHost()->
        GetID();
    resource.render_view_id =
        web_contents()->GetRenderViewHost()->GetRoutingID();
    csd_host_->OnSafeBrowsingHit(resource);
    resource.callback.Reset();
    ASSERT_TRUE(csd_host_->DidShowSBInterstitial());
    ASSERT_TRUE(csd_host_->unsafe_resource_.get());
    // Test that the resource above was copied.
    EXPECT_EQ(resource.url, csd_host_->unsafe_resource_->url);
    EXPECT_EQ(resource.original_url, csd_host_->unsafe_resource_->original_url);
    EXPECT_EQ(resource.is_subresource,
              csd_host_->unsafe_resource_->is_subresource);
    EXPECT_EQ(resource.threat_type, csd_host_->unsafe_resource_->threat_type);
    EXPECT_TRUE(csd_host_->unsafe_resource_->callback.is_null());
    EXPECT_EQ(resource.render_process_host_id,
              csd_host_->unsafe_resource_->render_process_host_id);
    EXPECT_EQ(resource.render_view_id,
              csd_host_->unsafe_resource_->render_view_id);
  }

 protected:
  scoped_ptr<ClientSideDetectionHost> csd_host_;
  scoped_ptr<StrictMock<MockClientSideDetectionService> > csd_service_;
  scoped_refptr<StrictMock<MockSafeBrowsingUIManager> > ui_manager_;
  scoped_refptr<StrictMock<MockSafeBrowsingDatabaseManager> > database_manager_;
  MockTestingProfile* mock_profile_;  // We don't own this object

 private:
  scoped_ptr<content::TestBrowserThread> ui_thread_;
  scoped_ptr<content::TestBrowserThread> file_user_blocking_thread_;
  scoped_ptr<content::TestBrowserThread> io_thread_;
};

TEST_F(ClientSideDetectionHostTest, OnPhishingDetectionDoneInvalidVerdict) {
  // Case 0: renderer sends an invalid verdict string that we're unable to
  // parse.
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.
  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _)).Times(0);
  OnPhishingDetectionDone("Invalid Protocol Buffer");
  EXPECT_TRUE(Mock::VerifyAndClear(mock_extractor));
}

TEST_F(ClientSideDetectionHostTest, OnPhishingDetectionDoneNotPhishing) {
  // Case 1: client thinks the page is phishing.  The server does not agree.
  // No interstitial is shown.
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientSideDetectionService::ClientReportPhishingRequestCallback cb;
  ClientPhishingRequest verdict;
  verdict.set_url("http://phishingurl.com/");
  verdict.set_client_score(1.0f);
  verdict.set_is_phishing(true);

  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _))
      .WillOnce(DoAll(DeleteArg<1>(),
                      InvokeCallbackArgument<2>(true, &verdict)));
  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), _))
      .WillOnce(SaveArg<1>(&cb));
  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  ASSERT_FALSE(cb.is_null());

  // Make sure DoDisplayBlockingPage is not going to be called.
  EXPECT_CALL(*ui_manager_, DoDisplayBlockingPage(_)).Times(0);
  cb.Run(GURL(verdict.url()), false);
  MessageLoop::current()->RunUntilIdle();
  EXPECT_TRUE(Mock::VerifyAndClear(ui_manager_.get()));
}

TEST_F(ClientSideDetectionHostTest, OnPhishingDetectionDoneDisabled) {
  // Case 2: client thinks the page is phishing and so does the server but
  // showing the interstitial is disabled => no interstitial is shown.
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientSideDetectionService::ClientReportPhishingRequestCallback cb;
  ClientPhishingRequest verdict;
  verdict.set_url("http://phishingurl.com/");
  verdict.set_client_score(1.0f);
  verdict.set_is_phishing(true);

  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _))
      .WillOnce(DoAll(DeleteArg<1>(),
                      InvokeCallbackArgument<2>(true, &verdict)));
  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), _))
      .WillOnce(SaveArg<1>(&cb));
  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  ASSERT_FALSE(cb.is_null());

  // Make sure DoDisplayBlockingPage is not going to be called.
  EXPECT_CALL(*ui_manager_, DoDisplayBlockingPage(_)).Times(0);
  cb.Run(GURL(verdict.url()), false);
  MessageLoop::current()->RunUntilIdle();
  EXPECT_TRUE(Mock::VerifyAndClear(ui_manager_.get()));
}

TEST_F(ClientSideDetectionHostTest, OnPhishingDetectionDoneShowInterstitial) {
  // Case 3: client thinks the page is phishing and so does the server.
  // We show an interstitial.
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientSideDetectionService::ClientReportPhishingRequestCallback cb;
  GURL phishing_url("http://phishingurl.com/");
  ClientPhishingRequest verdict;
  verdict.set_url(phishing_url.spec());
  verdict.set_client_score(1.0f);
  verdict.set_is_phishing(true);

  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _))
      .WillOnce(DoAll(DeleteArg<1>(),
                      InvokeCallbackArgument<2>(true, &verdict)));
  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), _))
      .WillOnce(SaveArg<1>(&cb));
  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  ASSERT_FALSE(cb.is_null());

  UnsafeResource resource;
  EXPECT_CALL(*ui_manager_, DoDisplayBlockingPage(_))
      .WillOnce(SaveArg<0>(&resource));
  cb.Run(phishing_url, true);

  MessageLoop::current()->RunUntilIdle();
  EXPECT_TRUE(Mock::VerifyAndClear(ui_manager_.get()));
  EXPECT_EQ(phishing_url, resource.url);
  EXPECT_EQ(phishing_url, resource.original_url);
  EXPECT_FALSE(resource.is_subresource);
  EXPECT_EQ(SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL, resource.threat_type);
  EXPECT_EQ(web_contents()->GetRenderProcessHost()->GetID(),
            resource.render_process_host_id);
  EXPECT_EQ(web_contents()->GetRenderViewHost()->GetRoutingID(),
            resource.render_view_id);

  // Make sure the client object will be deleted.
  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&MockSafeBrowsingUIManager::InvokeOnBlockingPageComplete,
                 ui_manager_, resource.callback));
  // Since the CsdClient object will be deleted on the UI thread I need
  // to run the UI message loop.  Post a task to stop the UI message loop
  // after the client object destructor is called.
  FlushIOMessageLoop();
}

TEST_F(ClientSideDetectionHostTest, OnPhishingDetectionDoneMultiplePings) {
  // Case 4 & 5: client thinks a page is phishing then navigates to
  // another page which is also considered phishing by the client
  // before the server responds with a verdict.  After a while the
  // server responds for both requests with a phishing verdict.  Only
  // a single interstitial is shown for the second URL.
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientSideDetectionService::ClientReportPhishingRequestCallback cb;
  GURL phishing_url("http://phishingurl.com/");
  ClientPhishingRequest verdict;
  verdict.set_url(phishing_url.spec());
  verdict.set_client_score(1.0f);
  verdict.set_is_phishing(true);

  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _))
      .WillOnce(DoAll(DeleteArg<1>(),
                      InvokeCallbackArgument<2>(true, &verdict)));
  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), _))
      .WillOnce(SaveArg<1>(&cb));
  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  ASSERT_FALSE(cb.is_null());

  // Set this back to a normal browser feature extractor since we're using
  // NavigateAndCommit() and it's easier to use the real thing than setting up
  // mock expectations.
  SetFeatureExtractor(new BrowserFeatureExtractor(web_contents(),
                                                  csd_service_.get()));
  GURL other_phishing_url("http://other_phishing_url.com/bla");
  ExpectPreClassificationChecks(other_phishing_url, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kFalse, &kFalse);
  // We navigate away.  The callback cb should be revoked.
  NavigateAndCommit(other_phishing_url);
  // Wait for the pre-classification checks to finish for other_phishing_url.
  WaitAndCheckPreClassificationChecks();

  ClientSideDetectionService::ClientReportPhishingRequestCallback cb_other;
  verdict.set_url(other_phishing_url.spec());
  verdict.set_client_score(0.8f);
  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), _))
      .WillOnce(DoAll(DeleteArg<0>(),
                      SaveArg<1>(&cb_other),
                      QuitUIMessageLoop()));
  std::vector<GURL> redirect_chain;
  redirect_chain.push_back(other_phishing_url);
  SetRedirectChain(redirect_chain);
  OnPhishingDetectionDone(verdict.SerializeAsString());
  MessageLoop::current()->Run();
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  ASSERT_FALSE(cb_other.is_null());

  // We expect that the interstitial is shown for the second phishing URL and
  // not for the first phishing URL.
  UnsafeResource resource;
  EXPECT_CALL(*ui_manager_, DoDisplayBlockingPage(_))
      .WillOnce(SaveArg<0>(&resource));

  cb.Run(phishing_url, true);  // Should have no effect.
  cb_other.Run(other_phishing_url, true);  // Should show interstitial.

  MessageLoop::current()->RunUntilIdle();
  EXPECT_TRUE(Mock::VerifyAndClear(ui_manager_.get()));
  EXPECT_EQ(other_phishing_url, resource.url);
  EXPECT_EQ(other_phishing_url, resource.original_url);
  EXPECT_FALSE(resource.is_subresource);
  EXPECT_EQ(SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL, resource.threat_type);
  EXPECT_EQ(web_contents()->GetRenderProcessHost()->GetID(),
            resource.render_process_host_id);
  EXPECT_EQ(web_contents()->GetRenderViewHost()->GetRoutingID(),
            resource.render_view_id);

  // Make sure the client object will be deleted.
  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&MockSafeBrowsingUIManager::InvokeOnBlockingPageComplete,
                 ui_manager_, resource.callback));
  // Since the CsdClient object will be deleted on the UI thread I need
  // to run the UI message loop.  Post a task to stop the UI message loop
  // after the client object destructor is called.
  FlushIOMessageLoop();
}

TEST_F(ClientSideDetectionHostTest,
       OnPhishingDetectionDoneVerdictNotPhishing) {
  // Case 6: renderer sends a verdict string that isn't phishing.
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientPhishingRequest verdict;
  verdict.set_url("http://not-phishing.com/");
  verdict.set_client_score(0.1f);
  verdict.set_is_phishing(false);

  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _)).Times(0);
  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(mock_extractor));
}

TEST_F(ClientSideDetectionHostTest,
       OnPhishingDetectionDoneVerdictNotPhishingButSBMatch) {
  // Case 7: renderer sends a verdict string that isn't phishing but the URL
  // was on the regular phishing or malware lists.
  GURL url("http://not-phishing.com/");
  ClientPhishingRequest verdict;
  verdict.set_url(url.spec());
  verdict.set_client_score(0.1f);
  verdict.set_is_phishing(false);

  // First we have to navigate to the URL to set the unique page ID.
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kFalse);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  SetUnsafeResourceToCurrent();

  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), CallbackIsNull()))
      .WillOnce(DoAll(DeleteArg<0>(), QuitUIMessageLoop()));
  std::vector<GURL> redirect_chain;
  redirect_chain.push_back(url);
  SetRedirectChain(redirect_chain);
  OnPhishingDetectionDone(verdict.SerializeAsString());
  MessageLoop::current()->Run();
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
}

TEST_F(ClientSideDetectionHostTest, UpdateIPHostMap) {
  BrowseInfo* browse_info = GetBrowseInfo();

  // Empty IP or host are skipped
  UpdateIPHostMap("250.10.10.10", std::string());
  ASSERT_EQ(0U, browse_info->ips.size());
  UpdateIPHostMap(std::string(), "google.com/");
  ASSERT_EQ(0U, browse_info->ips.size());
  UpdateIPHostMap(std::string(), std::string());
  ASSERT_EQ(0U, browse_info->ips.size());

  std::set<std::string> expected_hosts;
  for (int i = 0; i < 20; i++) {
    std::string host = base::StringPrintf("%d.com/", i);
    expected_hosts.insert(host);
    UpdateIPHostMap("250.10.10.10", host);
  }
  ASSERT_EQ(1U, browse_info->ips.size());
  ASSERT_EQ(20U, browse_info->ips["250.10.10.10"].size());
  EXPECT_EQ(expected_hosts, browse_info->ips["250.10.10.10"]);

  // Add more hosts for this ip, it exceeds max limit and won't be added
  UpdateIPHostMap("250.10.10.10", "21.com/");
  ASSERT_EQ(1U, browse_info->ips.size());
  ASSERT_EQ(20U, browse_info->ips["250.10.10.10"].size());
  EXPECT_EQ(expected_hosts, browse_info->ips["250.10.10.10"]);

  // Add 199 more IPs
  for (int i = 0; i < 199; i++) {
    std::string ip = base::StringPrintf("%d.%d.%d.256", i, i, i);
    expected_hosts.clear();
    expected_hosts.insert("test.com/");
    UpdateIPHostMap(ip, "test.com/");
    ASSERT_EQ(1U, browse_info->ips[ip].size());
    EXPECT_EQ(expected_hosts, browse_info->ips[ip]);
  }
  ASSERT_EQ(200U, browse_info->ips.size());

  // Exceeding max ip limit 200, these won't be added
  UpdateIPHostMap("250.250.250.250", "goo.com/");
  UpdateIPHostMap("250.250.250.250", "bar.com/");
  UpdateIPHostMap("250.250.0.250", "foo.com/");
  ASSERT_EQ(200U, browse_info->ips.size());

  // Add host to existing IPs succeed
  UpdateIPHostMap("100.100.100.256", "more.com/");
  ASSERT_EQ(2U, browse_info->ips["100.100.100.256"].size());
  expected_hosts.clear();
  expected_hosts.insert("test.com/");
  expected_hosts.insert("more.com/");
  EXPECT_EQ(expected_hosts, browse_info->ips["100.100.100.256"]);
}

TEST_F(ClientSideDetectionHostTest,
       OnPhishingDetectionDoneVerdictNotPhishingNotMalwareIP) {
  // Case 7: renderer sends a verdict string that isn't phishing and not matches
  // malware bad IP list
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientPhishingRequest verdict;
  verdict.set_url("http://not-phishing.com/");
  verdict.set_client_score(0.1f);
  verdict.set_is_phishing(false);

  ClientMalwareRequest malware_verdict;
  malware_verdict.set_url("http://not-phishing.com/");

  EXPECT_CALL(*mock_extractor, ExtractMalwareFeatures(_, _))
      .WillOnce(SetArgumentPointee<1>(malware_verdict));
  EXPECT_CALL(*csd_service_,
              SendClientReportMalwareRequest(_, _)).Times(0);
  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _)).Times(0);

  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(mock_extractor));
}

TEST_F(ClientSideDetectionHostTest,
       OnPhishingDetectionDoneVerdictNotPhishingButMalwareIP) {
  // Case 8: renderer sends a verdict string that isn't phishing but matches
  // malware bad IP list
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientPhishingRequest verdict;
  verdict.set_url("http://not-phishing.com/");
  verdict.set_client_score(0.1f);
  verdict.set_is_phishing(false);

  ClientMalwareRequest malware_verdict;
  malware_verdict.set_url("http://not-phishing.com/");
  ClientMalwareRequest::Feature* feature = malware_verdict.add_feature_map();
  feature->set_name("malwareip1.2.3.4");
  feature->set_value(1.0);
  feature->add_metainfo("badip.com");

  EXPECT_CALL(*mock_extractor, ExtractMalwareFeatures(_, _))
      .WillOnce(SetArgumentPointee<1>(malware_verdict));
  EXPECT_CALL(*csd_service_,
              SendClientReportMalwareRequest(
                  Pointee(PartiallyEqualMalwareVerdict(malware_verdict)), _))
      .WillOnce(DeleteArg<0>());
  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _)).Times(0);

  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(mock_extractor));
}

TEST_F(ClientSideDetectionHostTest,
       OnPhishingDetectionDoneVerdictPhishingAndMalwareIP) {
  // Case 9: renderer sends a verdict string that is phishing and matches
  // malware bad IP list
  MockBrowserFeatureExtractor* mock_extractor = new MockBrowserFeatureExtractor(
      web_contents(),
      csd_service_.get());
  SetFeatureExtractor(mock_extractor);  // The host class takes ownership.

  ClientSideDetectionService::ClientReportPhishingRequestCallback cb;
  ClientPhishingRequest verdict;
  verdict.set_url("http://not-phishing.com/");
  verdict.set_client_score(0.1f);
  verdict.set_is_phishing(true);

  ClientMalwareRequest malware_verdict;
  malware_verdict.set_url("http://not-phishing.com/");
  ClientMalwareRequest::Feature* feature = malware_verdict.add_feature_map();
  feature->set_name("malwareip1.2.3.4");
  feature->set_value(1.0);
  feature->add_metainfo("badip.com");

  EXPECT_CALL(*mock_extractor, ExtractMalwareFeatures(_, _))
      .WillOnce(SetArgumentPointee<1>(malware_verdict));
  EXPECT_CALL(*csd_service_,
              SendClientReportMalwareRequest(
                  Pointee(PartiallyEqualMalwareVerdict(malware_verdict)), _))
      .WillOnce(DeleteArg<0>());

  EXPECT_CALL(*mock_extractor, ExtractFeatures(_, _, _))
      .WillOnce(DoAll(DeleteArg<1>(),
                      InvokeCallbackArgument<2>(true, &verdict)));

  EXPECT_CALL(*csd_service_,
              SendClientReportPhishingRequest(
                  Pointee(PartiallyEqualVerdict(verdict)), _))
      .WillOnce(SaveArg<1>(&cb));
  OnPhishingDetectionDone(verdict.SerializeAsString());
  EXPECT_TRUE(Mock::VerifyAndClear(mock_extractor));
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  ASSERT_FALSE(cb.is_null());
}

TEST_F(ClientSideDetectionHostTest, NavigationCancelsShouldClassifyUrl) {
  // Test that canceling pending should classify requests works as expected.

  GURL first_url("http://first.phishy.url.com");
  GURL second_url("http://second.url.com/");
  // The first few checks are done synchronously so check that they have been
  // done for the first URL, while the second URL has all the checks done.  We
  // need to manually set up the IsPrivateIPAddress mock since if the same mock
  // expectation is specified twice, gmock will only use the last instance of
  // it, meaning the first will never be matched.
  EXPECT_CALL(*csd_service_, IsPrivateIPAddress(_))
      .WillOnce(Return(false))
      .WillOnce(Return(false));
  ExpectPreClassificationChecks(first_url, NULL, &kFalse, &kFalse, NULL,
                                NULL, NULL);
  ExpectPreClassificationChecks(second_url, NULL, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kFalse);

  NavigateAndCommit(first_url);
  // Don't flush the message loop, as we want to navigate to a different
  // url before the final pre-classification checks are run.
  NavigateAndCommit(second_url);
  WaitAndCheckPreClassificationChecks();
}

TEST_F(ClientSideDetectionHostTest, ShouldClassifyUrl) {
  // Navigate the tab to a page.  We should see a StartPhishingDetection IPC.
  GURL url("http://host.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kFalse);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();

  const IPC::Message* msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_TRUE(msg);
  Tuple1<GURL> actual_url;
  SafeBrowsingMsg_StartPhishingDetection::Read(msg, &actual_url);
  EXPECT_EQ(url, actual_url.a);
  EXPECT_EQ(rvh()->GetRoutingID(), msg->routing_id());
  process()->sink().ClearMessages();

  // Now try an in-page navigation.  This should not trigger an IPC.
  EXPECT_CALL(*csd_service_, IsPrivateIPAddress(_)).Times(0);
  url = GURL("http://host.com/#foo");
  ExpectPreClassificationChecks(url, NULL, NULL, NULL, NULL, NULL, NULL);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();

  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);

  // Check that XHTML is supported, in addition to the default HTML type.
  // Note: for this test to work correctly, the new URL must be on the
  // same domain as the previous URL, otherwise it will create a new
  // RenderViewHost that won't have the mime type set.
  url = GURL("http://host.com/xhtml");
  rvh_tester()->SetContentsMimeType("application/xhtml+xml");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kFalse);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_TRUE(msg);
  SafeBrowsingMsg_StartPhishingDetection::Read(msg, &actual_url);
  EXPECT_EQ(url, actual_url.a);
  EXPECT_EQ(rvh()->GetRoutingID(), msg->routing_id());
  process()->sink().ClearMessages();

  // Navigate to a new host, which should cause another IPC.
  url = GURL("http://host2.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kFalse);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_TRUE(msg);
  SafeBrowsingMsg_StartPhishingDetection::Read(msg, &actual_url);
  EXPECT_EQ(url, actual_url.a);
  EXPECT_EQ(rvh()->GetRoutingID(), msg->routing_id());
  process()->sink().ClearMessages();

  // If the mime type is not one that we support, no IPC should be triggered.
  // Note: for this test to work correctly, the new URL must be on the
  // same domain as the previous URL, otherwise it will create a new
  // RenderViewHost that won't have the mime type set.
  url = GURL("http://host2.com/image.jpg");
  rvh_tester()->SetContentsMimeType("image/jpeg");
  ExpectPreClassificationChecks(url, NULL, NULL, NULL, NULL, NULL, NULL);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);

  // If IsPrivateIPAddress returns true, no IPC should be triggered.
  url = GURL("http://host3.com/");
  ExpectPreClassificationChecks(url, &kTrue, NULL, NULL, NULL, NULL, NULL);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);

  // If the tab is incognito there should be no IPC.  Also, we shouldn't
  // even check the csd-whitelist.
  url = GURL("http://host4.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kTrue, NULL, NULL, NULL, NULL);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);

  // If the URL is on the csd whitelist, no IPC should be triggered.
  url = GURL("http://host5.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kTrue, NULL, NULL,
                                NULL);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);

  // If item is in the cache but it isn't valid, we will classify regardless
  // of whether we are over the reporting limit.
  url = GURL("http://host6.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kFalse, &kTrue,
                                NULL);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_TRUE(msg);
  SafeBrowsingMsg_StartPhishingDetection::Read(msg, &actual_url);
  EXPECT_EQ(url, actual_url.a);
  EXPECT_EQ(rvh()->GetRoutingID(), msg->routing_id());
  process()->sink().ClearMessages();

  // If the url isn't in the cache and we are over the reporting limit, we
  // don't do classification.
  url = GURL("http://host7.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kFalse,
                                &kFalse, &kTrue);
  NavigateAndCommit(url);
  WaitAndCheckPreClassificationChecks();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);

  // If result is cached, we will try and display the blocking page directly
  // with no start classification message.
  url = GURL("http://host8.com/");
  ExpectPreClassificationChecks(url, &kFalse, &kFalse, &kFalse, &kTrue, NULL,
                                NULL);

  UnsafeResource resource;
  EXPECT_CALL(*ui_manager_, DoDisplayBlockingPage(_))
      .WillOnce(SaveArg<0>(&resource));

  NavigateAndCommit(url);
  // Wait for CheckCsdWhitelist to be called on the IO thread.
  FlushIOMessageLoop();
  // Wait for CheckCache() to be called on the UI thread.
  MessageLoop::current()->RunUntilIdle();
  // Now we check that all expected functions were indeed called on the two
  // service objects.
  EXPECT_TRUE(Mock::VerifyAndClear(csd_service_.get()));
  EXPECT_TRUE(Mock::VerifyAndClear(ui_manager_.get()));
  EXPECT_EQ(url, resource.url);
  EXPECT_EQ(url, resource.original_url);
  resource.callback.Reset();
  msg = process()->sink().GetFirstMessageMatching(
      SafeBrowsingMsg_StartPhishingDetection::ID);
  ASSERT_FALSE(msg);
}

}  // namespace safe_browsing


text:
<?php

namespace Igniter\Flame\Translation;

use Illuminate\Support\Str;
use Illuminate\Translation\Translator as BaseTranslator;

class Translator extends BaseTranslator
{
    public function get($key, array $replace = [], $locale = null, $fallback = true)
    {
        if (Str::startsWith($key, 'lang:'))
            $key = substr($key, 5);

        if ($line = $this->getValidationKey($key, $replace, $locale))
            return $line;

        return parent::get($key, $replace, $locale, $fallback);
    }

    /**
     * Get the validation translation.
     *
     * @param  string $key
     * @param  array $replace
     * @param  string $locale
     * @return string
     */
    protected function getValidationKey($key, $replace, $locale)
    {
        if (
            starts_with($key, 'validation.')
            && !starts_with($key, 'validation.custom.')
            && !starts_with($key, 'validation.attributes.')
        ) {
            $systemKey = 'system::'.$key;
            $line = $this->get($systemKey, $replace, $locale);
            if ($line !== $systemKey) {
                return $line;
            }
        }
    }
}