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 fetcher.model;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Ryan Gilera
 */
public class UtilsTest {

    public UtilsTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of isValidURL method, of class Utils.
     */
    @Test
    public void testIsValidURLForValidURL() {
        // given:
        String URL_String = "http://google.com";

        // when:
        boolean result = Utils.isValidURL(URL_String);

        // then:
        assertTrue(result);
    }

    /**
     * Test of isValidURL method, of class Utils.
     */
    @Test
    public void testIsValidURLForInvalidURL() {
        // given:
        String URL_String = "dummy text";

        // when:
        boolean result = Utils.isValidURL(URL_String);

        // then:
        assertFalse(result);
    }

    /**
     * Test of exists method, of class Utils.
     */
    @Test
    public void testExistsValid() {
        // given:
        boolean expResult = true;
        Integer inputArgument = 1;
        List<Integer> testList = new ArrayList<Integer>();
        testList.add(1);

        // when:
        boolean result = Utils.exists(testList, inputArgument);

        // then:
        assertEquals(expResult, result);
    }

    /**
     * Test of exists method, of class Utils.
     */
    @Test
    public void testExistsInvalid() {
        // given:
        boolean expResult = false;
        Integer inputArgument = 2;
        List<Integer> testList = new ArrayList<Integer>();
        testList.add(1);

        // when:
        boolean result = Utils.exists(testList, inputArgument);

        // then:
        assertEquals(expResult, result);
    }

    /**
     * Test of convertToObservableList method, of class Utils.
     */
    @Test
    public void testConvertToObservableListValid() {
        // given:
        HashSet<Integer> aHashSetObj = new HashSet<Integer>();
        aHashSetObj.add(1);
        aHashSetObj.add(2);

        ObservableList expResult = FXCollections.observableArrayList();
        expResult.add(1);
        expResult.add(2);

        // when:
        ObservableList result = Utils.convertToObservableList(aHashSetObj);

        // then:
        assertEquals(expResult, result);
        assertEquals(expResult.size(), result.size());
        assertEquals(expResult.get(0), result.get(0));
        assertEquals(expResult.get(1), result.get(1));
    }

    /**
     * Test of convertToObservableList method, of class Utils.
     */
    @Test
    public void testConvertToObservableListEmpty() {
        // given:
        HashSet<Integer> aHashSetObj = new HashSet<Integer>();
        ObservableList expResult = FXCollections.observableArrayList();

        // when:
        ObservableList result = Utils.convertToObservableList(aHashSetObj);

        // then:
        assertEquals(expResult, result);
        assertEquals(expResult.size(), result.size());
    }

    /**
     * Test of FileExists method, of class Utils.
     */
    @Test
    public void testFileExistsInvalid() {
        // given:
        String file = "dummy";
        boolean expResult = false;

        // when:
        boolean result = Utils.FileExists(file);

        // then:
        assertEquals(expResult, result);
    }

    // TODO: testFileExistsValid()

    /**
     * Test of fileList method.
     *
     * @author Mike Caverly
     */
    @Test
    public void testFileList() {
        //given
        File file = new File("dummy");
        List<File> testList = new ArrayList<File>();
        testList.add(file);
        //when
        List result = Utils.filesList(file, file);
        //then
        assertEquals(testList, result);
    }

}


text:
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>dev-it-tests</groupId>
  <artifactId>dev-sample-proj</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <app.name>LibertyProject</app.name>
    <!-- tag::ports[] -->
    <testServerHttpPort>9080</testServerHttpPort>
    <testServerHttpsPort>9443</testServerHttpsPort>
    <!-- end::ports[] -->
    <packaging.type>usr</packaging.type>
  </properties>

  <dependencyManagement>
      <dependencies>
          <dependency>
              <groupId>io.openliberty.features</groupId>
              <artifactId>features-bom</artifactId>
              <version>RUNTIME_VERSION</version>
              <type>pom</type>
              <scope>import</scope>
          </dependency>
      </dependencies>
  </dependencyManagement>

  <dependencies>
    <!-- Open Liberty features -->
    <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>jaxrs-2.1</artifactId>
        <type>esa</type>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>jsonp-1.1</artifactId>
        <type>esa</type>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>cdi-2.0</artifactId>
        <type>esa</type>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>mpConfig-1.3</artifactId>
        <type>esa</type>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>mpRestClient-1.2</artifactId>
        <type>esa</type>
        <scope>provided</scope>
    </dependency>
    <!-- <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>mpHealth-1.0</artifactId>
        <type>esa</type>
        <scope>provided</scope>
    </dependency> -->
    <!-- <dependency>
        <groupId>io.openliberty.features</groupId>
        <artifactId>abcd</artifactId>
        <version>1.0</version>
    </dependency> -->
    <!-- For tests -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-client</artifactId>
      <version>3.2.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-extension-providers</artifactId>
      <version>3.2.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.glassfish</groupId>
      <artifactId>javax.json</artifactId>
      <version>1.0.4</version>
      <scope>test</scope>
    </dependency>
    <!-- Java utility classes -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
    </dependency>
    <!-- Support for JDK 9 and above-->
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.2</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <!-- Test runtime dependency for run goal -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
   <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.2</version>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
          <packagingExcludes>pom.xml</packagingExcludes>
        </configuration>
      </plugin>
      <!-- Plugin to run unit tests -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M1</version>
        <executions>
          <execution>
            <phase>test</phase>
            <id>default-test</id>
            <configuration>
              <excludes>
                <exclude>**/it/**</exclude>
              </excludes>
              <reportsDirectory>${project.build.directory}/test-reports/unit</reportsDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <!-- Enable liberty-maven plugin -->
      <plugin>
        <groupId>io.openliberty.tools</groupId>
        <artifactId>liberty-maven-plugin</artifactId>
        <version>SUB_VERSION</version>
        <configuration>
          <assemblyArtifact>
            <groupId>io.openliberty</groupId>
            <artifactId>openliberty-kernel</artifactId>
            <version>RUNTIME_VERSION</version>
            <type>zip</type>
          </assemblyArtifact>
          <packageName>${app.name}</packageName>
          <include>${packaging.type}</include>
          <bootstrapProperties>
            <default.http.port>${testServerHttpPort}</default.http.port>
            <default.https.port>${testServerHttpsPort}</default.https.port>
            <com.ibm.ws.logging.message.format>json</com.ibm.ws.logging.message.format>
          </bootstrapProperties>
        </configuration>
      </plugin>
      <!-- Plugin to run functional tests -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>3.0.0-M1</version>
        <executions>
          <execution>
            <phase>integration-test</phase>
            <id>integration-test</id>
            <goals>
              <goal>integration-test</goal>
            </goals>
            <configuration>
              <includes>
                <include>**/it/**/*.java</include>
              </includes>
              <!-- tag::system-props[] -->
              <systemPropertyVariables>
                <liberty.test.port>${testServerHttpPort}</liberty.test.port>
              </systemPropertyVariables>
              <!-- end::system-props[] -->
            </configuration>
          </execution>
          <execution>
            <id>verify-results</id>
            <goals>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <summaryFile>${project.build.directory}/test-reports/it/failsafe-summary.xml</summaryFile>
          <reportsDirectory>${project.build.directory}/test-reports/it</reportsDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
(function () {
  'use strict';

  angular
    .module('statuslist')
    .config(function ($stateProvider, $urlRouterProvider) {
      $stateProvider
        .state('home', {
          url: '/',
          templateUrl: 'app/main/main.html',
          controller: 'MainController',
          controllerAs: 'main'
        });

      $urlRouterProvider.otherwise('/');
    });

}());


text:
package com.util;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.util.Log;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by BinhTran on 3/13/17.
 */
public class TypefaceUtil {

    /**
     * Using reflection to override default typeface
     * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
     *
     * @param context                    to work with assets
     * @param defaultFontNameToOverride  for example "monospace"
     * @param customFontFileNameInAssets file name of the font from assets
     */
    public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

        final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Map<String, Typeface> newMap = new HashMap<String, Typeface>();
            newMap.put("serif", customFontTypeface);
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField("sSystemFontMap");
                staticField.setAccessible(true);
                staticField.set(null, newMap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
                defaultFontTypefaceField.setAccessible(true);
                defaultFontTypefaceField.set(null, customFontTypeface);
            } catch (Exception e) {
                Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ja">
<context>
    <name>LFileDialog</name>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="14"/>
        <source>Open With...</source>
        <translation>アプリケーションで開く...</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="68"/>
        <source>Preferred</source>
        <translation>推奨</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="75"/>
        <source>Available</source>
        <translation>利用可能</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="82"/>
        <source>Custom</source>
        <translation>カスタム</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="131"/>
        <source>Binary Location</source>
        <translation>バイナリーの場所</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="138"/>
        <source>Find</source>
        <translation>検索</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="199"/>
        <source>Set this application as the default </source>
        <translation>このアプリケーションをいつも使用する </translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="221"/>
        <source>OK</source>
        <translation>OK</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.ui" line="235"/>
        <source>Cancel</source>
        <translation>キャンセル</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="40"/>
        <source>(Email Link)</source>
        <translation>(電子メールリンク)</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="41"/>
        <source>(Internet URL - %1)</source>
        <translation>(インターネット URL - %1)</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="114"/>
        <source>Audio</source>
        <translation>オーディオ</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="115"/>
        <source>Video</source>
        <translation>動画</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="116"/>
        <source>Multimedia</source>
        <translation>マルチメディア</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="117"/>
        <source>Development</source>
        <translation>開発</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="118"/>
        <source>Education</source>
        <translation>教育</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="119"/>
        <source>Game</source>
        <translation>ゲーム</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="120"/>
        <source>Graphics</source>
        <translation>グラフィックス</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="121"/>
        <source>Network</source>
        <translation>ネットワーク</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="122"/>
        <source>Office</source>
        <translation>オフィス</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="123"/>
        <source>Science</source>
        <translation>科学</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="124"/>
        <source>Settings</source>
        <translation>設定</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="125"/>
        <source>System</source>
        <translation>システム</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="126"/>
        <source>Utilities</source>
        <translation>ユーティリティー</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="127"/>
        <source>Other</source>
        <translation>その他</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/LFileDialog.cpp" line="271"/>
        <source>Find Application Binary</source>
        <translatorcomment>"Find"とあるが、ファイル指定ダイアログのタイトル</translatorcomment>
        <translation>アプリケーションのバイナリーを指定</translation>
    </message>
</context>
<context>
    <name>QObject</name>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="51"/>
        <source>File Error</source>
        <translation>ファイルエラー</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="187"/>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="193"/>
        <source>Audio Volume %1%</source>
        <translation>音声ボリューム %1%</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="201"/>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="210"/>
        <source>Screen Brightness %1%</source>
        <translation>画面の明るさ %1%</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="242"/>
        <source>Invalid file or URL: %1</source>
        <translation>無効なファイルまたはURL: %1</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="264"/>
        <source>File could not be opened: %1</source>
        <translation>ファイルを開けません: %1</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="273"/>
        <source>Application shortcut is missing the launching information (malformed shortcut): %1</source>
        <translation>アプリケーションショートカットの起動情報が失われています(無効なショートカット): %1</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="284"/>
        <source>URL shortcut is missing the URL: %1</source>
        <translation>URL ショートカットの URL が失われています: %1</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="295"/>
        <source>Directory shortcut is missing the path to the directory: %1</source>
        <translation>ディレクトリーショートカットのパス情報が失われています: %1</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="300"/>
        <source>Unknown type of shortcut : %1</source>
        <translation>種類が不明なショートカットです: %1</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="362"/>
        <source>Binary Missing</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="362"/>
        <source>Could not find "%1". Please ensure it is installed first.</source>
        <translation>"%1" が見つかりませんでした。まずそれがインストールされている事を確認してください。</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="412"/>
        <source>Application Error</source>
        <translation>アプリケーションエラー</translation>
    </message>
    <message>
        <location filename="../../lumina-git/src-qt5/core/lumina-open/main.cpp" line="412"/>
        <source>The following application experienced an error and needed to close:</source>
        <translation>このアプリケーションでエラーが発生したため、閉じる必要があります:</translation>
    </message>
</context>
</TS>


text:
@interface GTTransferManager : NSObject

+ (void)uploadLogFile;
+ (void)uploadLogFile:(uint64_t)startTime endTime:(uint64_t)endTime;

+ (void)uploadCrashReport;

+ (void)uploadAttachment;

@end


text:
from __future__ import absolute_import

from django.db import IntegrityError, transaction
from rest_framework import serializers
from rest_framework.response import Response

from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import SavedSearch, SavedSearchUserDefault

class SavedSearchSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=128, required=True)
    query = serializers.CharField(required=True)
    isDefault = serializers.BooleanField(required=False)
    isUserDefault = serializers.BooleanField(required=False)

class ProjectSearchesEndpoint(ProjectEndpoint):
    def get(self, request, project):
        """
        List a project's saved searches

        Retrieve a list of saved searches for a given project.

            {method} {path}

        """
        results = list(SavedSearch.objects.filter(
            project=project,
        ).order_by('name'))

        return Response(serialize(results, request.user))

    def post(self, request, project):
        """
        Create a new saved search

        Create a new saved search for the given project.

            {method} {path}
            {{
                "name": "Latest Release",
                "query": "release:[latest]"
            }}

        """
        serializer = SavedSearchSerializer(data=request.DATA)

        if serializer.is_valid():
            result = serializer.object

            with transaction.atomic():
                try:
                    search = SavedSearch.objects.create(
                        project=project,
                        name=result['name'],
                        query=result['query'],
                        is_default=result.get('isDefault', False),
                    )
                except IntegrityError:
                    return Response({
                        'detail': 'Search with same name already exists.'
                    }, status=400)

                if search.is_default:
                    SavedSearch.objects.filter(
                        project=project,
                    ).exclude(
                        id=search.id,
                    ).update(
                        is_default=False,
                    )

                if result.get('isUserDefault'):
                    SavedSearchUserDefault.objects.create_or_update(
                        savedsearch=search,
                        user=request.user,
                        project=project,
                    )

            return Response(serialize(search, request.user), status=201)
        return Response(serializer.errors, status=400)


text:
<?php

/**
 *	@author Félix Girault <felix.girault@gmail.com>
 *	@license FreeBSD License (http://opensource.org/licenses/BSD-2-Clause)
 */

/**
 *	Library path.
 */

define(
	'MULTIPLAYER_LIB',
	dirname( dirname( __FILE__ )) . DIRECTORY_SEPARATOR . 'lib'
);

/**
 *	Autoloads lib files.
 */

spl_autoload_register( function( $className ) {
	$path = MULTIPLAYER_LIB
		. DIRECTORY_SEPARATOR
		. str_replace( '\\', DIRECTORY_SEPARATOR, $className )
		. '.php';

	if ( file_exists( $path )) {
		require_once $path;
	}
});


text:
from __future__ import unicode_literals
from pybooru import Pybooru

client = Pybooru('Konachan')

tags = client.tags_list(None, None, 100, 0, 'date')

for tag in tags:
    print("Nombre: {0} ----- {1}".format(tag['name'], tag['type']))


text:
"""Miscellaneous network utility code."""

from __future__ import absolute_import, division, with_statement

import errno
import logging
import os
import socket
import stat

from tornado import process
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream, SSLIOStream
from tornado.platform.auto import set_close_exec

try:
    import ssl  # Python 2.6+
except ImportError:
    ssl = None

class TCPServer(object):
    r"""A non-blocking, single-threaded TCP server.

    To use `TCPServer`, define a subclass which overrides the `handle_stream`
    method.

    `TCPServer` can serve SSL traffic with Python 2.6+ and OpenSSL.
    To make this server serve SSL traffic, send the ssl_options dictionary
    argument with the arguments required for the `ssl.wrap_socket` method,
    including "certfile" and "keyfile"::

       TCPServer(ssl_options={
           "certfile": os.path.join(data_dir, "mydomain.crt"),
           "keyfile": os.path.join(data_dir, "mydomain.key"),
       })

    `TCPServer` initialization follows one of three patterns:

    1. `listen`: simple single-process::

            server = TCPServer()
            server.listen(8888)
            IOLoop.instance().start()

    2. `bind`/`start`: simple multi-process::

            server = TCPServer()
            server.bind(8888)
            server.start(0)  # Forks multiple sub-processes
            IOLoop.instance().start()

       When using this interface, an `IOLoop` must *not* be passed
       to the `TCPServer` constructor.  `start` will always start
       the server on the default singleton `IOLoop`.

    3. `add_sockets`: advanced multi-process::

            sockets = bind_sockets(8888)
            tornado.process.fork_processes(0)
            server = TCPServer()
            server.add_sockets(sockets)
            IOLoop.instance().start()

       The `add_sockets` interface is more complicated, but it can be
       used with `tornado.process.fork_processes` to give you more
       flexibility in when the fork happens.  `add_sockets` can
       also be used in single-process servers if you want to create
       your listening sockets in some way other than
       `bind_sockets`.
    """
    def __init__(self, io_loop=None, ssl_options=None):
        self.io_loop = io_loop
        self.ssl_options = ssl_options
        self._sockets = {}  # fd -> socket object
        self._pending_sockets = []
        self._started = False

    def listen(self, port, address=""):
        """Starts accepting connections on the given port.

        This method may be called more than once to listen on multiple ports.
        `listen` takes effect immediately; it is not necessary to call
        `TCPServer.start` afterwards.  It is, however, necessary to start
        the `IOLoop`.
        """
        sockets = bind_sockets(port, address=address)
        self.add_sockets(sockets)

    def add_sockets(self, sockets):
        """Makes this server start accepting connections on the given sockets.

        The ``sockets`` parameter is a list of socket objects such as
        those returned by `bind_sockets`.
        `add_sockets` is typically used in combination with that
        method and `tornado.process.fork_processes` to provide greater
        control over the initialization of a multi-process server.
        """
        if self.io_loop is None:
            self.io_loop = IOLoop.instance()

        for sock in sockets:
            self._sockets[sock.fileno()] = sock
            add_accept_handler(sock, self._handle_connection,
                               io_loop=self.io_loop)

    def add_socket(self, socket):
        """Singular version of `add_sockets`.  Takes a single socket object."""
        self.add_sockets([socket])

    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128):
        """Binds this server to the given port on the given address.

        To start the server, call `start`. If you want to run this server
        in a single process, you can call `listen` as a shortcut to the
        sequence of `bind` and `start` calls.

        Address may be either an IP address or hostname.  If it's a hostname,
        the server will listen on all IP addresses associated with the
        name.  Address may be an empty string or None to listen on all
        available interfaces.  Family may be set to either ``socket.AF_INET``
        or ``socket.AF_INET6`` to restrict to ipv4 or ipv6 addresses, otherwise
        both will be used if available.

        The ``backlog`` argument has the same meaning as for
        `socket.listen`.

        This method may be called multiple times prior to `start` to listen
        on multiple ports or interfaces.
        """
        sockets = bind_sockets(port, address=address, family=family,
                               backlog=backlog)
        if self._started:
            self.add_sockets(sockets)
        else:
            self._pending_sockets.extend(sockets)

    def start(self, num_processes=1):
        """Starts this server in the IOLoop.

        By default, we run the server in this process and do not fork any
        additional child process.

        If num_processes is ``None`` or <= 0, we detect the number of cores
        available on this machine and fork that number of child
        processes. If num_processes is given and > 1, we fork that
        specific number of sub-processes.

        Since we use processes and not threads, there is no shared memory
        between any server code.

        Note that multiple processes are not compatible with the autoreload
        module (or the ``debug=True`` option to `tornado.web.Application`).
        When using multiple processes, no IOLoops can be created or
        referenced until after the call to ``TCPServer.start(n)``.
        """
        assert not self._started
        self._started = True
        if num_processes != 1:
            process.fork_processes(num_processes)
        sockets = self._pending_sockets
        self._pending_sockets = []
        self.add_sockets(sockets)

    def stop(self):
        """Stops listening for new connections.

        Requests currently in progress may still continue after the
        server is stopped.
        """
        for fd, sock in self._sockets.iteritems():
            self.io_loop.remove_handler(fd)
            sock.close()

    def handle_stream(self, stream, address):
        """Override to handle a new `IOStream` from an incoming connection."""
        raise NotImplementedError()

    def _handle_connection(self, connection, address):
        if self.ssl_options is not None:
            assert ssl, "Python 2.6+ and OpenSSL required for SSL"
            try:
                connection = ssl.wrap_socket(connection,
                                             server_side=True,
                                             do_handshake_on_connect=False,
                                             **self.ssl_options)
            except ssl.SSLError, err:
                if err.args[0] == ssl.SSL_ERROR_EOF:
                    return connection.close()
                else:
                    raise
            except socket.error, err:
                if err.args[0] == errno.ECONNABORTED:
                    return connection.close()
                else:
                    raise
        try:
            if self.ssl_options is not None:
                stream = SSLIOStream(connection, io_loop=self.io_loop)
            else:
                stream = IOStream(connection, io_loop=self.io_loop)
            self.handle_stream(stream, address)
        except Exception:
            logging.error("Error in connection callback", exc_info=True)

def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128):
    """Creates listening sockets bound to the given port and address.

    Returns a list of socket objects (multiple sockets are returned if
    the given address maps to multiple IP addresses, which is most common
    for mixed IPv4 and IPv6 use).

    Address may be either an IP address or hostname.  If it's a hostname,
    the server will listen on all IP addresses associated with the
    name.  Address may be an empty string or None to listen on all
    available interfaces.  Family may be set to either socket.AF_INET
    or socket.AF_INET6 to restrict to ipv4 or ipv6 addresses, otherwise
    both will be used if available.

    The ``backlog`` argument has the same meaning as for
    ``socket.listen()``.
    """
    sockets = []
    if address == "":
        address = None
    flags = socket.AI_PASSIVE
    if hasattr(socket, "AI_ADDRCONFIG"):
        # AI_ADDRCONFIG ensures that we only try to bind on ipv6
        # if the system is configured for it, but the flag doesn't
        # exist on some platforms (specifically WinXP, although
        # newer versions of windows have it)
        flags |= socket.AI_ADDRCONFIG
    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,
                                  0, flags)):
        af, socktype, proto, canonname, sockaddr = res
        sock = socket.socket(af, socktype, proto)
        set_close_exec(sock.fileno())
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if af == socket.AF_INET6:
            # On linux, ipv6 sockets accept ipv4 too by default,
            # but this makes it impossible to bind to both
            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,
            # separate sockets *must* be used to listen for both ipv4
            # and ipv6.  For consistency, always disable ipv4 on our
            # ipv6 sockets and use a separate ipv4 socket when needed.
            #
            # Python 2.x on windows doesn't have IPPROTO_IPV6.
            if hasattr(socket, "IPPROTO_IPV6"):
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
        sock.setblocking(0)
        sock.bind(sockaddr)
        sock.listen(backlog)
        sockets.append(sock)
    return sockets

if hasattr(socket, 'AF_UNIX'):
    def bind_unix_socket(file, mode=0600, backlog=128):
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        try:
            st = os.stat(file)
        except OSError, err:
            if err.errno != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock

def add_accept_handler(sock, callback, io_loop=None):
    """Adds an ``IOLoop`` event handler to accept new connections on ``sock``.

    When a connection is accepted, ``callback(connection, address)`` will
    be run (``connection`` is a socket object, and ``address`` is the
    address of the other end of the connection).  Note that this signature
    is different from the ``callback(fd, events)`` signature used for
    ``IOLoop`` handlers.
    """
    if io_loop is None:
        io_loop = IOLoop.instance()

    def accept_handler(fd, events):
        while True:
            try:
                connection, address = sock.accept()
            except socket.error, e:
                if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN):
                    return
                raise
            callback(connection, address)
    io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ)


text:
package org.apache.druid.server;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.smile.SmileMediaTypes;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.guava.LazySequence;
import org.apache.druid.java.util.common.guava.Sequences;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.query.DefaultGenericQueryMetricsFactory;
import org.apache.druid.query.MapQueryToolChestWarehouse;
import org.apache.druid.query.Query;
import org.apache.druid.query.QueryInterruptedException;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QuerySegmentWalker;
import org.apache.druid.query.QueryToolChestWarehouse;
import org.apache.druid.query.QueryUnsupportedException;
import org.apache.druid.query.Result;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.TruncatedResponseContextException;
import org.apache.druid.query.timeboundary.TimeBoundaryResultValue;
import org.apache.druid.server.initialization.ServerConfig;
import org.apache.druid.server.log.TestRequestLogger;
import org.apache.druid.server.metrics.NoopServiceEmitter;
import org.apache.druid.server.scheduling.HiLoQueryLaningStrategy;
import org.apache.druid.server.scheduling.ManualQueryPrioritizationStrategy;
import org.apache.druid.server.scheduling.NoQueryLaningStrategy;
import org.apache.druid.server.scheduling.ThresholdBasedQueryPrioritizationStrategy;
import org.apache.druid.server.security.Access;
import org.apache.druid.server.security.Action;
import org.apache.druid.server.security.AuthConfig;
import org.apache.druid.server.security.AuthTestUtils;
import org.apache.druid.server.security.AuthenticationResult;
import org.apache.druid.server.security.Authorizer;
import org.apache.druid.server.security.AuthorizerMapper;
import org.apache.druid.server.security.ForbiddenException;
import org.apache.druid.server.security.Resource;
import org.apache.http.HttpStatus;
import org.easymock.EasyMock;
import org.joda.time.Interval;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

public class QueryResourceTest
{
  private static final QueryToolChestWarehouse WAREHOUSE = new MapQueryToolChestWarehouse(ImmutableMap.of());
  private static final ObjectMapper JSON_MAPPER = new DefaultObjectMapper();
  private static final AuthenticationResult AUTHENTICATION_RESULT =
      new AuthenticationResult("druid", "druid", null, null);

  private final HttpServletRequest testServletRequest = EasyMock.createMock(HttpServletRequest.class);

  private static final QuerySegmentWalker TEST_SEGMENT_WALKER = new QuerySegmentWalker()
  {
    @Override
    public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals)
    {
      return (queryPlus, responseContext) -> Sequences.empty();
    }

    @Override
    public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs)
    {
      return getQueryRunnerForIntervals(null, null);
    }
  };

  private static final String SIMPLE_TIMESERIES_QUERY =
      "{\n"
      + "    \"queryType\": \"timeseries\",\n"
      + "    \"dataSource\": \"mmx_metrics\",\n"
      + "    \"granularity\": \"hour\",\n"
      + "    \"intervals\": [\n"
      + "      \"2014-12-17/2015-12-30\"\n"
      + "    ],\n"
      + "    \"aggregations\": [\n"
      + "      {\n"
      + "        \"type\": \"count\",\n"
      + "        \"name\": \"rows\"\n"
      + "      }\n"
      + "    ]\n"
      + "}";

  private static final String SIMPLE_TIMESERIES_QUERY_SMALLISH_INTERVAL =
      "{\n"
      + "    \"queryType\": \"timeseries\",\n"
      + "    \"dataSource\": \"mmx_metrics\",\n"
      + "    \"granularity\": \"hour\",\n"
      + "    \"intervals\": [\n"
      + "      \"2014-12-17/2014-12-30\"\n"
      + "    ],\n"
      + "    \"aggregations\": [\n"
      + "      {\n"
      + "        \"type\": \"count\",\n"
      + "        \"name\": \"rows\"\n"
      + "      }\n"
      + "    ]\n"
      + "}";

  private static final String SIMPLE_TIMESERIES_QUERY_LOW_PRIORITY =
      "{\n"
      + "    \"queryType\": \"timeseries\",\n"
      + "    \"dataSource\": \"mmx_metrics\",\n"
      + "    \"granularity\": \"hour\",\n"
      + "    \"intervals\": [\n"
      + "      \"2014-12-17/2015-12-30\"\n"
      + "    ],\n"
      + "    \"aggregations\": [\n"
      + "      {\n"
      + "        \"type\": \"count\",\n"
      + "        \"name\": \"rows\"\n"
      + "      }\n"
      + "    ],\n"
      + "    \"context\": { \"priority\": -1 }"
      + "}";

  private static final ServiceEmitter NOOP_SERVICE_EMITTER = new NoopServiceEmitter();
  private static final DruidNode DRUID_NODE = new DruidNode(
      "broker",
      "localhost",
      true,
      8082,
      null,
      true,
      false
  );

  private QueryResource queryResource;
  private QueryScheduler queryScheduler;
  private TestRequestLogger testRequestLogger;

  @BeforeClass
  public static void staticSetup()
  {
    EmittingLogger.registerEmitter(NOOP_SERVICE_EMITTER);
  }

  @Before
  public void setup()
  {
    EasyMock.expect(testServletRequest.getContentType()).andReturn(MediaType.APPLICATION_JSON).anyTimes();
    EasyMock.expect(testServletRequest.getHeader("Accept")).andReturn(MediaType.APPLICATION_JSON).anyTimes();
    EasyMock.expect(testServletRequest.getHeader(QueryResource.HEADER_IF_NONE_MATCH)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getRemoteAddr()).andReturn("localhost").anyTimes();
    queryScheduler = QueryStackTests.DEFAULT_NOOP_SCHEDULER;
    testRequestLogger = new TestRequestLogger();
    queryResource = createQueryResource(ResponseContextConfig.newConfig(true));
  }

  private QueryResource createQueryResource(ResponseContextConfig responseContextConfig)
  {
    return new QueryResource(
        new QueryLifecycleFactory(
            WAREHOUSE,
            TEST_SEGMENT_WALKER,
            new DefaultGenericQueryMetricsFactory(),
            new NoopServiceEmitter(),
            testRequestLogger,
            new AuthConfig(),
            AuthTestUtils.TEST_AUTHORIZER_MAPPER
        ),
        JSON_MAPPER,
        JSON_MAPPER,
        queryScheduler,
        new AuthConfig(),
        null,
        responseContextConfig,
        DRUID_NODE
    );
  }

  @After
  public void tearDown()
  {
    EasyMock.verify(testServletRequest);
  }

  @Test
  public void testGoodQuery() throws IOException
  {
    expectPermissiveHappyPathAuth();

    Response response = queryResource.doPost(
        new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertNotNull(response);
  }

  @Test
  public void testTruncatedResponseContextShouldFail() throws IOException
  {
    expectPermissiveHappyPathAuth();
    final QueryResource queryResource = createQueryResource(ResponseContextConfig.forTest(true, 0));

    Response response = queryResource.doPost(
        new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertEquals(1, queryResource.getInterruptedQueryCount());
    Assert.assertNotNull(response);
    Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus());
    final String expectedException = new QueryInterruptedException(
        new TruncatedResponseContextException("Serialized response context exceeds the max size[0]"),
        DRUID_NODE.getHostAndPortToUse()
    ).toString();
    Assert.assertEquals(
        expectedException,
        JSON_MAPPER.readValue((byte[]) response.getEntity(), QueryInterruptedException.class).toString()
    );
  }

  @Test
  public void testTruncatedResponseContextShouldSucceed() throws IOException
  {
    expectPermissiveHappyPathAuth();
    final QueryResource queryResource = createQueryResource(ResponseContextConfig.forTest(false, 0));

    Response response = queryResource.doPost(
        new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertNotNull(response);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
  }

  @Test
  public void testGoodQueryWithNullAcceptHeader() throws IOException
  {
    final String acceptHeader = null;
    final String contentTypeHeader = MediaType.APPLICATION_JSON;
    EasyMock.reset(testServletRequest);

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
        .andReturn(null)
        .anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
        .andReturn(AUTHENTICATION_RESULT)
        .anyTimes();

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);

    EasyMock.expect(testServletRequest.getHeader("Accept")).andReturn(acceptHeader).anyTimes();
    EasyMock.expect(testServletRequest.getContentType()).andReturn(contentTypeHeader).anyTimes();
    EasyMock.expect(testServletRequest.getHeader(QueryResource.HEADER_IF_NONE_MATCH)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getRemoteAddr()).andReturn("localhost").anyTimes();

    EasyMock.replay(testServletRequest);
    Response response = queryResource.doPost(
        new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    //since accept header is null, the response content type should be same as the value of 'Content-Type' header
    Assert.assertEquals(contentTypeHeader, (response.getMetadata().get("Content-Type").get(0)).toString());
    Assert.assertNotNull(response);
  }

  @Test
  public void testGoodQueryWithEmptyAcceptHeader() throws IOException
  {
    final String acceptHeader = "";
    final String contentTypeHeader = MediaType.APPLICATION_JSON;
    EasyMock.reset(testServletRequest);

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
        .andReturn(null)
        .anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
        .andReturn(AUTHENTICATION_RESULT)
        .anyTimes();

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);

    EasyMock.expect(testServletRequest.getHeader("Accept")).andReturn(acceptHeader).anyTimes();
    EasyMock.expect(testServletRequest.getContentType()).andReturn(contentTypeHeader).anyTimes();
    EasyMock.expect(testServletRequest.getHeader(QueryResource.HEADER_IF_NONE_MATCH)).andReturn(null).anyTimes();
    EasyMock.expect(testServletRequest.getRemoteAddr()).andReturn("localhost").anyTimes();

    EasyMock.replay(testServletRequest);
    Response response = queryResource.doPost(
        new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    //since accept header is empty, the response content type should be same as the value of 'Content-Type' header
    Assert.assertEquals(contentTypeHeader, (response.getMetadata().get("Content-Type").get(0)).toString());
    Assert.assertNotNull(response);
  }

  @Test
  public void testGoodQueryWithSmileAcceptHeader() throws IOException
  {
    //Doing a replay of testServletRequest for teardown to succeed.
    //We dont use testServletRequest in this testcase
    EasyMock.replay(testServletRequest);

    //Creating our own Smile Servlet request, as to not disturb the remaining tests.
    // else refactoring required for this class. i know this kinda makes the class somewhat Dirty.
    final HttpServletRequest smileRequest = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(smileRequest.getContentType()).andReturn(MediaType.APPLICATION_JSON).anyTimes();

    EasyMock.expect(smileRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
        .andReturn(null)
        .anyTimes();
    EasyMock.expect(smileRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(smileRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
        .andReturn(AUTHENTICATION_RESULT)
        .anyTimes();

    smileRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);

    EasyMock.expect(smileRequest.getHeader("Accept")).andReturn(SmileMediaTypes.APPLICATION_JACKSON_SMILE).anyTimes();
    EasyMock.expect(smileRequest.getHeader(QueryResource.HEADER_IF_NONE_MATCH)).andReturn(null).anyTimes();
    EasyMock.expect(smileRequest.getRemoteAddr()).andReturn("localhost").anyTimes();

    EasyMock.replay(smileRequest);
    Response response = queryResource.doPost(
        new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        smileRequest
    );
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    Assert.assertEquals(SmileMediaTypes.APPLICATION_JACKSON_SMILE, (response.getMetadata().get("Content-Type").get(0)).toString());
    Assert.assertNotNull(response);
    EasyMock.verify(smileRequest);
  }

  @Test
  public void testBadQuery() throws IOException
  {
    EasyMock.replay(testServletRequest);
    Response response = queryResource.doPost(
        new ByteArrayInputStream("Meka Leka Hi Meka Hiney Ho".getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertNotNull(response);
    Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
  }

  @Test
  public void testUnsupportedQueryThrowsException() throws IOException
  {
    String errorMessage = "This will be support in Druid 9999";
    ByteArrayInputStream badQuery = EasyMock.createMock(ByteArrayInputStream.class);
    EasyMock.expect(badQuery.read(EasyMock.anyObject(), EasyMock.anyInt(), EasyMock.anyInt())).andThrow(
        new QueryUnsupportedException(errorMessage));
    EasyMock.replay(badQuery);
    EasyMock.replay(testServletRequest);
    Response response = queryResource.doPost(
        badQuery,
        null /*pretty*/,
        testServletRequest
    );
    Assert.assertNotNull(response);
    Assert.assertEquals(QueryUnsupportedException.STATUS_CODE, response.getStatus());
    QueryUnsupportedException ex;
    try {
      ex = JSON_MAPPER.readValue((byte[]) response.getEntity(), QueryUnsupportedException.class);
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
    Assert.assertEquals(errorMessage, ex.getMessage());
    Assert.assertEquals(QueryUnsupportedException.ERROR_CODE, ex.getErrorCode());
  }

  @Test
  public void testSecuredQuery() throws Exception
  {
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
            .andReturn(null)
            .anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
            .andReturn(AUTHENTICATION_RESULT)
            .anyTimes();

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, false);
    EasyMock.expectLastCall().times(1);

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);

    EasyMock.replay(testServletRequest);

    AuthorizerMapper authMapper = new AuthorizerMapper(null)
    {
      @Override
      public Authorizer getAuthorizer(String name)
      {
        return new Authorizer()
        {
          @Override
          public Access authorize(AuthenticationResult authenticationResult, Resource resource, Action action)
          {
            if (resource.getName().equals("allow")) {
              return new Access(true);
            } else {
              return new Access(false);
            }
          }

        };
      }
    };

    queryResource = new QueryResource(
        new QueryLifecycleFactory(
            WAREHOUSE,
            TEST_SEGMENT_WALKER,
            new DefaultGenericQueryMetricsFactory(),
            new NoopServiceEmitter(),
            testRequestLogger,
            new AuthConfig(),
            authMapper
        ),
        JSON_MAPPER,
        JSON_MAPPER,
        queryScheduler,
        new AuthConfig(),
        authMapper,
        ResponseContextConfig.newConfig(true),
        DRUID_NODE
    );

    try {
      queryResource.doPost(
          new ByteArrayInputStream(SIMPLE_TIMESERIES_QUERY.getBytes(StandardCharsets.UTF_8)),
          null /*pretty*/,
          testServletRequest
      );
      Assert.fail("doPost did not throw ForbiddenException for an unauthorized query");
    }
    catch (ForbiddenException e) {
    }

    Response response = queryResource.doPost(
        new ByteArrayInputStream("{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"}".getBytes(StandardCharsets.UTF_8)),
        null /*pretty*/,
        testServletRequest
    );

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ((StreamingOutput) response.getEntity()).write(baos);
    final List<Result<TimeBoundaryResultValue>> responses = JSON_MAPPER.readValue(
        baos.toByteArray(),
        new TypeReference<List<Result<TimeBoundaryResultValue>>>() {}
    );

    Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    Assert.assertEquals(0, responses.size());
    Assert.assertEquals(1, testRequestLogger.getNativeQuerylogs().size());
    Assert.assertEquals(
        true,
        testRequestLogger.getNativeQuerylogs().get(0).getQueryStats().getStats().get("success")
    );
    Assert.assertEquals(
        "druid",
        testRequestLogger.getNativeQuerylogs().get(0).getQueryStats().getStats().get("identity")
    );
  }

  @Test(timeout = 60_000L)
  public void testSecuredCancelQuery() throws Exception
  {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    final CountDownLatch cancelledCountDownLatch = new CountDownLatch(1);

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
            .andReturn(null)
            .anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
            .andReturn(AUTHENTICATION_RESULT)
            .anyTimes();

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);

    EasyMock.replay(testServletRequest);

    AuthorizerMapper authMapper = new AuthorizerMapper(null)
    {
      @Override
      public Authorizer getAuthorizer(String name)
      {
        return new Authorizer()
        {
          @Override
          public Access authorize(AuthenticationResult authenticationResult, Resource resource, Action action)
          {
            // READ action corresponds to the query
            // WRITE corresponds to cancellation of query
            if (action.equals(Action.READ)) {
              try {
                // Countdown startAwaitLatch as we want query cancellation to happen
                // after we enter isAuthorized method so that we can handle the
                // InterruptedException here because of query cancellation
                startAwaitLatch.countDown();
                waitForCancellationLatch.await();
              }
              catch (InterruptedException e) {
                // When the query is cancelled the control will reach here,
                // countdown the latch and rethrow the exception so that error response is returned for the query
                cancelledCountDownLatch.countDown();
                throw new RuntimeException(e);
              }
              return new Access(true);
            } else {
              return new Access(true);
            }
          }

        };
      }
    };

    queryResource = new QueryResource(
        new QueryLifecycleFactory(
            WAREHOUSE,
            TEST_SEGMENT_WALKER,
            new DefaultGenericQueryMetricsFactory(),
            new NoopServiceEmitter(),
            testRequestLogger,
            new AuthConfig(),
            authMapper
        ),
        JSON_MAPPER,
        JSON_MAPPER,
        queryScheduler,
        new AuthConfig(),
        authMapper,
        ResponseContextConfig.newConfig(true),
        DRUID_NODE
    );

    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\","
                               + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query query = mapper.readValue(queryString, Query.class);

    ListenableFuture future = MoreExecutors.listeningDecorator(
        Execs.singleThreaded("test_query_resource_%s")
    ).submit(
        new Runnable()
        {
          @Override
          public void run()
          {
            try {
              Response response = queryResource.doPost(
                  new ByteArrayInputStream(queryString.getBytes(StandardCharsets.UTF_8)),
                  null,
                  testServletRequest
              );

              Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
            }
            catch (IOException e) {
              throw new RuntimeException(e);
            }
            waitFinishLatch.countDown();
          }
        }
    );

    queryScheduler.registerQueryFuture(query, future);
    startAwaitLatch.await();

    Executors.newSingleThreadExecutor().submit(
        new Runnable() {
          @Override
          public void run()
          {
            Response response = queryResource.cancelQuery("id_1", testServletRequest);
            Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
            waitForCancellationLatch.countDown();
            waitFinishLatch.countDown();
          }
        }
    );
    waitFinishLatch.await();
    cancelledCountDownLatch.await();
  }

  @Test(timeout = 60_000L)
  public void testDenySecuredCancelQuery() throws Exception
  {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
            .andReturn(null)
            .anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
        .andReturn(AUTHENTICATION_RESULT)
            .anyTimes();

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().times(1);

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, false);
    EasyMock.expectLastCall().times(1);

    EasyMock.replay(testServletRequest);

    AuthorizerMapper authMapper = new AuthorizerMapper(null)
    {
      @Override
      public Authorizer getAuthorizer(String name)
      {
        return new Authorizer()
        {
          @Override
          public Access authorize(AuthenticationResult authenticationResult, Resource resource, Action action)
          {
            // READ action corresponds to the query
            // WRITE corresponds to cancellation of query
            if (action.equals(Action.READ)) {
              try {
                waitForCancellationLatch.await();
              }
              catch (InterruptedException e) {
                throw new RuntimeException(e);
              }
              return new Access(true);
            } else {
              // Deny access to cancel the query
              return new Access(false);
            }
          }

        };
      }
    };

    queryResource = new QueryResource(
        new QueryLifecycleFactory(
            WAREHOUSE,
            TEST_SEGMENT_WALKER,
            new DefaultGenericQueryMetricsFactory(),
            new NoopServiceEmitter(),
            testRequestLogger,
            new AuthConfig(),
            authMapper
        ),
        JSON_MAPPER,
        JSON_MAPPER,
        queryScheduler,
        new AuthConfig(),
        authMapper,
        ResponseContextConfig.newConfig(true),
        DRUID_NODE
    );

    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\","
                               + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query query = mapper.readValue(queryString, Query.class);

    ListenableFuture future = MoreExecutors.listeningDecorator(
        Execs.singleThreaded("test_query_resource_%s")
    ).submit(
        new Runnable()
        {
          @Override
          public void run()
          {
            try {
              startAwaitLatch.countDown();
              Response response = queryResource.doPost(
                  new ByteArrayInputStream(queryString.getBytes(StandardCharsets.UTF_8)),
                  null,
                  testServletRequest
              );
              Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
            }
            catch (IOException e) {
              throw new RuntimeException(e);
            }
            waitFinishLatch.countDown();
          }
        }
    );

    queryScheduler.registerQueryFuture(query, future);
    startAwaitLatch.await();

    Executors.newSingleThreadExecutor().submit(
        new Runnable()
        {
          @Override
          public void run()
          {
            try {
              queryResource.cancelQuery("id_1", testServletRequest);
            }
            catch (ForbiddenException e) {
              waitForCancellationLatch.countDown();
              waitFinishLatch.countDown();
            }
          }
        }
    );
    waitFinishLatch.await();
  }

  @Test(timeout = 10_000L)
  public void testTooManyQuery() throws InterruptedException
  {
    expectPermissiveHappyPathAuth();

    final CountDownLatch waitTwoScheduled = new CountDownLatch(2);
    final CountDownLatch waitAllFinished = new CountDownLatch(3);
    final QueryScheduler laningScheduler = new QueryScheduler(
        2,
        ManualQueryPrioritizationStrategy.INSTANCE,
        NoQueryLaningStrategy.INSTANCE,
        new ServerConfig()
    );

    createScheduledQueryResource(laningScheduler, Collections.emptyList(), ImmutableList.of(waitTwoScheduled));
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY,
        waitAllFinished,
        response -> Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus())
    );
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY,
        waitAllFinished,
        response -> Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus())
    );
    waitTwoScheduled.await();
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY,
        waitAllFinished,
        response -> {
          Assert.assertEquals(QueryCapacityExceededException.STATUS_CODE, response.getStatus());
          QueryCapacityExceededException ex;
          try {
            ex = JSON_MAPPER.readValue((byte[]) response.getEntity(), QueryCapacityExceededException.class);
          }
          catch (IOException e) {
            throw new RuntimeException(e);
          }
          Assert.assertEquals(QueryCapacityExceededException.makeTotalErrorMessage(2), ex.getMessage());
          Assert.assertEquals(QueryCapacityExceededException.ERROR_CODE, ex.getErrorCode());
        }
    );
    waitAllFinished.await();
  }

  @Test(timeout = 10_000L)
  public void testTooManyQueryInLane() throws InterruptedException
  {
    expectPermissiveHappyPathAuth();
    final CountDownLatch waitTwoStarted = new CountDownLatch(2);
    final CountDownLatch waitOneScheduled = new CountDownLatch(1);
    final CountDownLatch waitAllFinished = new CountDownLatch(3);
    final QueryScheduler scheduler = new QueryScheduler(
        40,
        ManualQueryPrioritizationStrategy.INSTANCE,
        new HiLoQueryLaningStrategy(2),
        new ServerConfig()
    );

    createScheduledQueryResource(scheduler, ImmutableList.of(waitTwoStarted), ImmutableList.of(waitOneScheduled));

    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY_LOW_PRIORITY,
        waitAllFinished,
        response -> Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus())
    );
    waitOneScheduled.await();
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY_LOW_PRIORITY,
        waitAllFinished,
        response -> {
          Assert.assertEquals(QueryCapacityExceededException.STATUS_CODE, response.getStatus());
          QueryCapacityExceededException ex;
          try {
            ex = JSON_MAPPER.readValue((byte[]) response.getEntity(), QueryCapacityExceededException.class);
          }
          catch (IOException e) {
            throw new RuntimeException(e);
          }
          Assert.assertEquals(
              QueryCapacityExceededException.makeLaneErrorMessage(HiLoQueryLaningStrategy.LOW, 1),
              ex.getMessage()
          );
          Assert.assertEquals(QueryCapacityExceededException.ERROR_CODE, ex.getErrorCode());

        }
    );
    waitTwoStarted.await();
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY,
        waitAllFinished,
        response -> Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus())
    );

    waitAllFinished.await();
  }

  @Test(timeout = 10_000L)
  public void testTooManyQueryInLaneImplicitFromDurationThreshold() throws InterruptedException
  {
    expectPermissiveHappyPathAuth();
    final CountDownLatch waitTwoStarted = new CountDownLatch(2);
    final CountDownLatch waitOneScheduled = new CountDownLatch(1);
    final CountDownLatch waitAllFinished = new CountDownLatch(3);
    final QueryScheduler scheduler = new QueryScheduler(
        40,
        new ThresholdBasedQueryPrioritizationStrategy(null, "P90D", null, null),
        new HiLoQueryLaningStrategy(1),
        new ServerConfig()
    );

    createScheduledQueryResource(scheduler, ImmutableList.of(waitTwoStarted), ImmutableList.of(waitOneScheduled));

    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY,
        waitAllFinished,
        response -> Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus())
    );
    waitOneScheduled.await();
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY,
        waitAllFinished,
        response -> {
          Assert.assertEquals(QueryCapacityExceededException.STATUS_CODE, response.getStatus());
          QueryCapacityExceededException ex;
          try {
            ex = JSON_MAPPER.readValue((byte[]) response.getEntity(), QueryCapacityExceededException.class);
          }
          catch (IOException e) {
            throw new RuntimeException(e);
          }
          Assert.assertEquals(
              QueryCapacityExceededException.makeLaneErrorMessage(HiLoQueryLaningStrategy.LOW, 1),
              ex.getMessage()
          );
          Assert.assertEquals(QueryCapacityExceededException.ERROR_CODE, ex.getErrorCode());
        }
    );
    waitTwoStarted.await();
    assertResponseAndCountdownOrBlockForever(
        SIMPLE_TIMESERIES_QUERY_SMALLISH_INTERVAL,
        waitAllFinished,
        response -> Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus())
    );

    waitAllFinished.await();
  }

  private void createScheduledQueryResource(
      QueryScheduler scheduler,
      Collection<CountDownLatch> beforeScheduler,
      Collection<CountDownLatch> inScheduler
  )
  {

    QuerySegmentWalker texasRanger = new QuerySegmentWalker()
    {
      @Override
      public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals)
      {
        return (queryPlus, responseContext) -> {
          beforeScheduler.forEach(CountDownLatch::countDown);

          return scheduler.run(
              scheduler.prioritizeAndLaneQuery(queryPlus, ImmutableSet.of()),
              new LazySequence<T>(() -> {
                inScheduler.forEach(CountDownLatch::countDown);
                try {
                  // pretend to be a query that is waiting on results
                  Thread.sleep(500);
                }
                catch (InterruptedException ignored) {
                }
                // all that waiting for nothing :(
                return Sequences.empty();
              })
          );
        };
      }

      @Override
      public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs)
      {
        return getQueryRunnerForIntervals(null, null);
      }
    };

    queryResource = new QueryResource(
        new QueryLifecycleFactory(
            WAREHOUSE,
            texasRanger,
            new DefaultGenericQueryMetricsFactory(),
            new NoopServiceEmitter(),
            testRequestLogger,
            new AuthConfig(),
            AuthTestUtils.TEST_AUTHORIZER_MAPPER
        ),
        JSON_MAPPER,
        JSON_MAPPER,
        scheduler,
        new AuthConfig(),
        null,
        ResponseContextConfig.newConfig(true),
        DRUID_NODE
    );
  }

  private void assertResponseAndCountdownOrBlockForever(String query, CountDownLatch done, Consumer<Response> asserts)
  {
    Executors.newSingleThreadExecutor().submit(() -> {
      try {
        Response response = queryResource.doPost(
            new ByteArrayInputStream(query.getBytes(StandardCharsets.UTF_8)),
            null,
            testServletRequest
        );
        asserts.accept(response);
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
      done.countDown();
    });
  }

  private void expectPermissiveHappyPathAuth()
  {
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED))
            .andReturn(null)
            .anyTimes();
    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH)).andReturn(null).anyTimes();

    EasyMock.expect(testServletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT))
            .andReturn(AUTHENTICATION_RESULT)
            .anyTimes();

    testServletRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
    EasyMock.expectLastCall().anyTimes();

    EasyMock.replay(testServletRequest);
  }
}


text:
using System.Threading.Tasks;
using Autofac;
using Slalom.Stacks.Services.Messaging;
using Slalom.Stacks.Services.Validation;
using Slalom.Stacks.Validation;

namespace Slalom.Stacks.Services.Pipeline
{
    /// <summary>
    /// The validate message step of the usecase execution pipeline.
    /// </summary>
    /// <seealso cref="Slalom.Stacks.Services.Pipeline.IMessageExecutionStep" />
    internal class ValidateMessage : IMessageExecutionStep
    {
        private readonly IComponentContext _components;

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateMessage" /> class.
        /// </summary>
        /// <param name="components">The context.</param>
        public ValidateMessage(IComponentContext components)
        {
            Argument.NotNull(components, nameof(components));

            _components = components;
        }

        /// <inheritdoc />
        public async Task Execute(ExecutionContext context)
        {
            var message = context.Request.Message;

            if (message.Body != null)
            {
                var validator = (IMessageValidator) _components.Resolve(typeof(MessageValidator<>).MakeGenericType(context.EndPoint.RequestType));
                var results = await validator.Validate(message.Body, context);
                context.AddValidationErrors(results);
            }
        }
    }
}


text:
namespace juce
{

AudioIODeviceType::AudioIODeviceType (const String& name)
    : typeName (name)
{
}

AudioIODeviceType::~AudioIODeviceType()
{
}

//==============================================================================
void AudioIODeviceType::addListener (Listener* l)      { listeners.add (l); }
void AudioIODeviceType::removeListener (Listener* l)   { listeners.remove (l); }

void AudioIODeviceType::callDeviceChangeListeners()
{
    listeners.call ([] (Listener& l) { l.audioDeviceListChanged(); });
}

//==============================================================================
#if ! JUCE_MAC
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio()       { return nullptr; }
#endif

#if ! JUCE_IOS
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()        { return nullptr; }
#endif

#if ! (JUCE_WINDOWS && JUCE_WASAPI)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI (bool)     { return nullptr; }
#endif

#if ! (JUCE_WINDOWS && JUCE_DIRECTSOUND)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound()     { return nullptr; }
#endif

#if ! (JUCE_WINDOWS && JUCE_ASIO)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()            { return nullptr; }
#endif

#if ! (JUCE_LINUX && JUCE_ALSA)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()            { return nullptr; }
#endif

#if ! (JUCE_LINUX && JUCE_JACK)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()            { return nullptr; }
#endif

#if ! (JUCE_LINUX && JUCE_BELA)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Bela()            { return nullptr; }
#endif

#if ! JUCE_ANDROID
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android()         { return nullptr; }
#endif

#if ! (JUCE_ANDROID && JUCE_USE_ANDROID_OPENSLES)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES()        { return nullptr; }
#endif

#if ! (JUCE_ANDROID && JUCE_USE_ANDROID_OBOE)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Oboe()            { return nullptr; }
#endif

} // namespace juce


text:
'use strict';

let React = require('react/addons');
let d3 = require('d3')
let Utils = require('./utils.js')
let ChartInfo = require('./ChartInfo.js')

let Save = require('save-svg-as-png')

require('styles/Chart.sass');

let Chart = React.createClass({

  getInitialState: () => Object({
      infoDisplay: "none"
  }),

  render: function() {

    return (

          <ChartInfo
            source={this.props.data.source} display={this.state.infoDisplay}
            close={this.hideInfo}/>

      );
  },

  showInfo: function(){
    this.setState({
      infoDisplay: "block"
    })
  },

  hideInfo: function(){
    this.setState({
      infoDisplay: "none"
    })
  },

  componentDidMount: function(){
    this.draw()
    let comp = this
    window.addEventListener("resize", Utils.debounce(function() {
      comp.draw()
    }, 150))

  },

  draw: function(){

    //DATA
    let {history, objectives, source} = this.props.data
    let icon = require("../images/quote-icons/" + this.props.icon)

    //compute objective if they are operations
    Object.keys(objectives).forEach(k => {
      if (typeof objectives[k] === "number") {return}
      let matches = objectives[k].match(/(\d+)\s?%\s?\[(\d{4})\]/) // e.g 20 % [1990] for 20 percent of the value in 1990
      if (matches && matches.length > 0 ){
        let [, percent, year] = matches
        objectives[k] = history[year] * (+percent) / 100
      }
    })

    //get a list of points from these objects
    let historyPoints = Utils.yearSeriesArray(history),
    lastHistoryPoint = historyPoints.reduce((mem, next) => next.year > mem.year ? next : mem),
    objectivePoints = [lastHistoryPoint, ...Utils.yearSeriesArray(objectives, "objective")],
    points = historyPoints.concat(objectivePoints);

    //DRAWING SIZES
    let [ww, _] = this.getWindowDimensions(),
    factor = ww < 600 ? 0.9 : ( ww < 900 ? 0.8 : (ww < 1390 ? 0.6 : 0.55)),
    [w, h] = [ww * factor, ww * factor * 0.375],
    margin = {top: 20, right: 20, bottom: 30, left: 50},
    drawingWidth = w - margin.left - margin.right,
    drawingHeight = h - margin.top - margin.bottom;

    let leChart = this.refs["le-chart"].getDOMNode()
    leChart.innerHTML = ""
    let svg = d3.select(leChart).append("svg")
    let defs = svg.append("defs");
    let playground = svg
    .attr("width", w)
    .attr("height", h)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    //SCALES & AXES
    let x = d3.time.scale()
    .range([0, drawingWidth])
    .domain(d3.extent(points, p => p.year))

    let y = d3.scale.linear()
    .range([drawingHeight, 0])
    .domain([0, d3.max(points, p => p.val)])

    let xAxis = d3.svg.axis().scale(x)
    .orient("bottom").outerTickSize(0).ticks(d3.time.years, 10)

    let yAxis = d3.svg.axis().scale(y)
    .orient("left").outerTickSize(0).ticks(6)

    let filter = defs.append("filter").attr("id", "teinte")
    filter.append("feColorMatrix")
    .attr("in", "SourceGraphic")
    .attr("type", "matrix")
    .attr("values",  `0 0 0 0 0.08
                      0 0 0 0 0.62
                      0 0 0 0 0.52
                      0 0 0 1 0`)

    playground.append("image")
    .attr(
      { "class": "icon",
        "xlink:xlink:href": icon.substring(1),
        "x": drawingWidth / 4 + "px",
        "y": 0,
        "height": drawingHeight + "px",
        "width": drawingWidth / 2 + "px",
        "filter": "url(#teinte)"
      })
    .attr("opacity", "0.15")

    playground.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    // making the horizontal ticks chart-wide
    .selectAll(".tick line")
    .attr("x1", 0)
    .attr("x2", drawingWidth)

    playground.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + drawingHeight + ")")
    .call(xAxis)
    .selectAll(".tick line")
    .attr("y1", 1)
    .attr("y2", 6)

    d3.selectAll(".x.axis .tick text")
    .attr("class", p => objectivePoints.some(o => o.year.getTime() === p.getTime()) ? "objective" : "")

    // Draw the LINE(s)
    let line = d3.svg.line()
    .x(p => x(p.year))
    .y(p => y(p.val))
    .interpolate("basis")

    function drawPartialLine(points){
      playground.append("path")
      .datum(points)
      .attr("class", `line ${points.slice(-1)[0].marker || ""}`)
      .attr("d", line)
    }

    [historyPoints,objectivePoints].map(drawPartialLine)

    // POINT CIRCLES
    playground.append("g").attr("class", "circles")
    .selectAll("circle")
    .data(objectivePoints)
    .enter()
    .append("circle")
    .attr("r", 3.5)
    .attr("cx", p => x(p.year))
    .attr("cy", p => y(p.val))

    //FOCUS CIRCLE
    //http://www.d3noob.org/2014/07/my-favourite-tooltip-method-for-line.html

    let focus = playground.append("g")
    .style("display", "none");
    focus.append("circle")
        .attr("class", "focus")
        .attr("r", 3.5);

    let focusValue = playground.append("text").attr("class", "focus-value")
    .attr("x", drawingWidth / 2)
    .attr("y", drawingHeight - 10)

    playground.append("rect").attr("class", "mouse-capture") //serves to capture the mouse
        .attr("width", drawingWidth)
        .attr("height", drawingHeight)
        .on("mouseover", function() { focus.style("display", null); focusValue.text("")})
        .on("mouseout", function() { focus.style("display", "none"); focusValue.text("")})
        .on("mousemove", function() {
            let d = x.invert(d3.mouse(this)[0]),
            year = d.getMonth() > 5 ? d.getFullYear() + 1 : d.getFullYear(),
            allYears = [].concat(...[history, objectives].map(Object.keys)), //yay flatmap
            closestYear = allYears.reduce((memo, y) => Math.abs(year - y) < Math.abs(memo - year) ? y : memo),
            val = history[closestYear + ""] || objectives[closestYear + ""]

            focus.select("circle.focus")
            .attr("transform",
                  "translate(" + x(d3.time.format("%Y").parse(closestYear + "")) + "," +
                                 y(val) + ")")

            let focusValueText =
            Math.abs(year - closestYear) < 3 ?
              `${Math.round(val * 10) / 10} ${source["unit-tip"] || ""} en ${year}`
              : ""
            focusValue.text(focusValueText)
        });

    //SOURCE BUTTON
    playground.append("text").attr("class", "info-button")
    .text("source")
    .attr("x", drawingWidth - 45)
    .attr("y", drawingHeight - 5)
    .on("click", this.showInfo)

    //Save.saveSvgAsPng(document.querySelector(".chart svg"), "diagram.png");

  },

  getWindowDimensions: function(){
      var d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0];

      var x = window.innerWidth || e.clientWidth || g.clientWidth;
      var y = window.innerHeight|| e.clientHeight|| g.clientHeight;

      return [x, y]
    },

})

module.exports = Chart;


text:
module LanceTrack {
    export module Authorization {
        export function authorizationServiceFactory($q: ng.IQService, $http: ng.IHttpService) {
            return new AuthorizationService($q, $http);
        }

        export class AuthorizationService {
            constructor(
                private $q: ng.IQService,
                private $http: ng.IHttpService) {

            }

            login(loginData: Api.LoginModel): ng.IPromise<any> {
                var deferred = this.$q.defer();

                this.$http.post(urls.data.login, loginData)
                    .success(r => deferred.resolve(r))
                    .error(err => deferred.reject(err));

                return deferred.promise;
            }

            logout(): ng.IPromise<any> {
                var deferred = this.$q.defer();

                this.$http.post(urls.data.logout, {})
                    .success(r => deferred.resolve(r))
                    .error(err => deferred.reject(err));

                return deferred.promise;
            }

            currentUser(): ng.IPromise<Api.UserAccount> {
                var deferred = this.$q.defer();

                this.$http.get(urls.data.currentUser)
                    .success(r => deferred.resolve(r))
                    .error(err => deferred.reject(err));

                return deferred.promise;
            }
        }
    }
}
LanceTrack.Authorization.authorizationServiceFactory.$inject = ["$q", "$http"];


text:
package com.riversoft.weixin.mp.menu.bean;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.riversoft.weixin.common.menu.MenuType;

/**
 * 获取自定义菜单配置接口使用
 * 操蛋的微信,JSON的协议就不能统一一下?
 * @borball on 5/26/2016.
 */
public class MenuButton {

    private MenuType type;
    private String name;
    private String key;
    private String url;

    @JsonProperty("sub_button")
    private MenuButtonList subItems;

    public MenuType getType() {
        return type;
    }

    public void setType(MenuType type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public MenuButtonList getSubItems() {
        return subItems;
    }

    public void setSubItems(MenuButtonList subItems) {
        this.subItems = subItems;
    }
}


text:
import {createFeature}  from 'feature-u';
import _discovery       from './featureName';
import _discoveryAct    from './actions'; // TODO: QUIRKINESS of IFormMeta (aggravated by feature-u) ... actions MUST be expanded BEFORE IFormMeta instance (eateryFilterFormMeta)
import reducer          from './state';
import logic            from './logic';
import route            from './route';
import DiscoveryLeftNavItem  from './comp/DiscoveryLeftNavItem';

// feature: discovery
//          manage and promotes the discovery view (a list of
//          "discoveries" from GooglePlaces).  Eateries can be
//          added/removed within the pool by simply
//          checking/unchecking the discoveries (full details in README)
export default createFeature({
  name: _discovery,

  // our public face ...
  fassets: {
    defineUse: {
      'leftNavItem.DiscoveryItem': DiscoveryLeftNavItem, // inject our entry into the leftNav
    }
  },

  reducer,
  logic,
  route,
});


text:
<!DOCTYPE html>
<meta charset="UTF-8">
<title>CSS Highlight API Test: Painting</title>
<link rel="help" href="https://drafts.csswg.org/css-highlight-api-1/">
<link rel="match" href="custom-highlight-painting-001-ref.html">
<meta name="assert" value="Highlighted elements must be correctly painted and there should be no caching that doesn't take highlight names into account">

One two three…


text:
import rankEncodings from './rankEncodings';

export const encoding = rankEncodings;


text:
#!/usr/bin/env node
/**
 * Author: yhtml5
 *
 */

'use strict';

const spawn = require('cross-spawn');
const { clearConsole } = require('yhtml5-dev-utils')
const args = process.argv.slice(2);
const paths = require('../utils/paths');

clearConsole()

const scriptIndex = args.findIndex(x =>
  x === 'build' || x === 'eject' || x === 'start' || x === 'test');
const script = scriptIndex === -1 ? args[0] : args[scriptIndex];
const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];

const result = spawn.sync(
  'node',
  nodeArgs
    .concat(require.resolve('../scripts/test'))
    .concat(args.slice(scriptIndex + 1)),
  { stdio: 'inherit' }
);

paths.isBeforePublish && console.log('\nyhtml5-test.js', {
  args: args,
  scriptIndex: scriptIndex,
  script: script,
  nodeArgs: nodeArgs
    .concat(require.resolve('../scripts/test'))
    .concat(args.slice(scriptIndex + 1)),
  result: result.signal
})

if (result.signal) {
  if (result.signal === 'SIGKILL') {
    console.log(
      'The build failed because the process exited too early. ' +
      'This probably means the system ran out of memory or someone called ' +
      '`kill -9` on the process.'
    );
  } else if (result.signal === 'SIGTERM') {
    console.log(
      'The build failed because the process exited too early. ' +
      'Someone might have called `kill` or `killall`, or the system could ' +
      'be shutting down.'
    );
  }
  process.exit(1);
}
process.exit(result.status);

// switch (script) {
//   case 'test': {
//     const result = spawn.sync(
//       'node',
//       nodeArgs
//         .concat(require.resolve('../scripts/' + script))
//         .concat(args.slice(scriptIndex + 1)),
//       { stdio: 'inherit' }
//     );
//     if (result.signal) {
//       if (result.signal === 'SIGKILL') {
//         console.log(
//           'The build failed because the process exited too early. ' +
//           'This probably means the system ran out of memory or someone called ' +
//           '`kill -9` on the process.'
//         );
//       } else if (result.signal === 'SIGTERM') {
//         console.log(
//           'The build failed because the process exited too early. ' +
//           'Someone might have called `kill` or `killall`, or the system could ' +
//           'be shutting down.'
//         );
//       }
//       process.exit(1);
//     }
//     process.exit(result.status);
//     break;
//   }
//   default:
//     console.log('Unknown script "' + script + '".');
//     console.log('Perhaps you need to update react-scripts?');
//     console.log(
//       'See: https://github.com/yhtml5/YHTML5-CLI'
//     );
//     break;
// }


text: """Templatetags for Zinnia"""


text:
#include <iostream>

#include "nlohmann/json.hpp"

#include "custom_interpreter.hpp"

namespace nl = nlohmann;

namespace custom
{

    nl::json custom_interpreter::execute_request_impl(int execution_counter, // Typically the cell number
                                                      const std::string& /*code*/, // Code to execute
                                                      bool /*silent*/,
                                                      bool /*store_history*/,
                                                      nl::json /*user_expressions*/,
                                                      bool /*allow_stdin*/)
    {
        // You can use the C-API of your target language for executing the code,
        // e.g. `PyRun_String` for the Python C-API
        //      `luaL_dostring` for the Lua C-API

        // Use this method for publishing the execution result to the client,
        // this method takes the ``execution_counter`` as first argument,
        // the data to publish (mime type data) as second argument and metadata
        // as third argument.
        // Replace "Hello World !!" by what you want to be displayed under the execution cell
        nl::json pub_data;
        pub_data["text/plain"] = "Hello World !!";
        publish_execution_result(execution_counter, std::move(pub_data), nl::json::object());

        // You can also use this method for publishing errors to the client, if the code
        // failed to execute
        // publish_execution_error(error_name, error_value, error_traceback);
        publish_execution_error("TypeError", "123", {"!@#$", "*(*"});

        nl::json result;
        result["status"] = "ok";
        return result;
    }

    void custom_interpreter::configure_impl()
    {
        // Perform some operations
    }

    nl::json custom_interpreter::complete_request_impl(const std::string& code,
                                                       int cursor_pos)
    {
        nl::json result;

        // Code starts with 'H', it could be the following completion
        if (code[0] == 'H')
        {
            result["status"] = "ok";
            result["matches"] = {"Hello", "Hey", "Howdy"};
            result["cursor_start"] = 5;
            result["cursor_end"] = cursor_pos;
        }
        // No completion result
        else
        {
            result["status"] = "ok";
            result["matches"] = nl::json::array();
            result["cursor_start"] = cursor_pos;
            result["cursor_end"] = cursor_pos;
        }

        return result;
    }

    nl::json custom_interpreter::inspect_request_impl(const std::string& code,
                                                      int /*cursor_pos*/,
                                                      int /*detail_level*/)
    {
        nl::json result;

        if (code.compare("print") == 0)
        {
            result["found"] = true;
            result["text/plain"] = "Print objects to the text stream file, [...]";
        }
        else
        {
            result["found"] = false;
        }

        result["status"] = "ok";
        return result;
    }

    nl::json custom_interpreter::is_complete_request_impl(const std::string& /*code*/)
    {
        nl::json result;

        // if (is_complete(code))
        // {
            result["status"] = "complete";
        // }
        // else
        // {
        //    result["status"] = "incomplete";
        //    result["indent"] = 4;
        //}

        return result;
    }

    nl::json custom_interpreter::kernel_info_request_impl()
    {
        nl::json result;
        result["implementation"] = "my_kernel";
        result["implementation_version"] = "0.1.0";
        result["language_info"]["name"] = "python";
        result["language_info"]["version"] = "3.7";
        result["language_info"]["mimetype"] = "text/x-python";
        result["language_info"]["file_extension"] = ".py";
        return result;
    }

    void custom_interpreter::shutdown_request_impl() {
        std::cout << "Bye!!" << std::endl;
    }

}