text:
<?php
namespace Plugin\GiftWrapping;

use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class GiftWrappingEvent
{

    /** @var  \Eccube\Application $app */
    private $app;

    public function __construct($app)
    {
        $this->app = $app;
    }

    /**
     * 購入画面にラッピング項目を表示
     *
     * @param FilterResponseEvent $event
     */
    public function onRenderGiftWrappingShoppingBefore(FilterResponseEvent $event)
    {

        $request = $event->getRequest();
        $response = $event->getResponse();

        $Wrapping = $this->app['eccube.plugin.repository.wrapping']->find(1);

        if ($Wrapping->getIsWrapping()) {
            $html = $this->getHtmlWrapping($request, $response);
            $response->setContent($html);
        }

        $event->setResponse($response);
    }

    /**
     *
     * @param Request $request
     * @param Response $response
     * @return string
     */
    private function getHtmlWrapping(Request $request, Response $response)
    {

        $crawler = new Crawler($response->getContent());

        $html = $this->getHtml($crawler);

        $form = $this->app['form.factory']->createBuilder('shopping')->getForm();

        $form->handleRequest($request);

        $parts = $this->app->renderView('GiftWrapping/Resource/template/wrapping_parts.twig', array(
            'form' => $form->createView()
        ));

        try {
            $oldHtml = $crawler->filter('#confirm_main')->last()->html();
            $newHtml = $oldHtml . $parts;
            $html = str_replace($oldHtml, $newHtml, $html);

        } catch (\InvalidArgumentException $e) {
        }

        return html_entity_decode($html, ENT_NOQUOTES, 'UTF-8');

    }

    /**
     * 解析用HTMLを取得
     *
     * @param Crawler $crawler
     * @return string
     */
    private function getHtml(Crawler $crawler)
    {
        $html = '';
        foreach ($crawler as $domElement) {
            $domElement->ownerDocument->formatOutput = true;
            $html .= $domElement->ownerDocument->saveHTML();
        }
        return html_entity_decode($html, ENT_NOQUOTES, 'UTF-8');
    }

}


text:
import os
import unirest
import time
import json
import pprint
import logging
import argparse

unirest.timeout(120)

IODAPIKEY = os.environ.get('IODAPIKEY')

parser = argparse.ArgumentParser(description='Delete an IOD web connector and its associated text index')
parser.add_argument('--apikey', default=IODAPIKEY)
parser.add_argument('--name', default='')
args = parser.parse_args()

apikey = args.apikey
if apikey:
    logging.info("Using apikey: %s" % apikey)
else:
    logging.critical("No apikey supplied. Exiting.")
    exit(1)

name = args.name
if name:
    logging.info("Deleting index/connector: %s" % name)
else:
    logging.critical("No name supplied. Exiting.")
    exit(1)

# Now delete the index.  Call first to get the confirmation token
response = unirest.get("https://api.idolondemand.com/1/api/sync/deletetextindex/v1", headers={"Accept": "application/json"}, params={"index": name, "apikey": apikey})
reply = json.loads(response.raw_body)
pprint.pprint(reply)
confirm = reply['confirm']

print "DELETING INDEX - CONFIRM"
# Now delete the index.  Second call with the "confirm" token
response = unirest.get("https://api.idolondemand.com/1/api/sync/deletetextindex/v1", headers={"Accept": "application/json"}, params={"index": name, "apikey": apikey, "confirm": confirm})
reply = json.loads(response.raw_body)
pprint.pprint(reply)

print "DELETING CONNECTOR"
response = unirest.get("https://api.idolondemand.com/1/api/sync/deleteconnector/v1", headers={"Accept": "application/json"}, params={"connector": name, "apikey": apikey})
reply = json.loads(response.raw_body)
pprint.pprint(reply)

redpajama_set_name: RedPajamaGithub


text:
#ifndef INCLUDE_git_merge_h__
#define INCLUDE_git_merge_h__

#include "common.h"
#include "types.h"
#include "oid.h"

/**
 * @file git2/merge.h
 * @brief Git merge-base routines
 * @defgroup git_revwalk Git merge-base routines
 * @ingroup Git
 * @{
 */
GIT_BEGIN_DECL

/**
 * Find a merge base between two commits
 *
 * @param out the OID of a merge base between 'one' and 'two'
 * @param repo the repository where the commits exist
 * @param one one of the commits
 * @param two the other commit
 */
GIT_EXTERN(int) git_merge_base(git_oid *out, git_repository *repo, const git_oid *one, const git_oid *two);

/**
 * Find a merge base given a list of commits
 *
 * @param out the OID of a merge base considering all the commits
 * @param repo the repository where the commits exist
 * @param input_array oids of the commits
 * @param length The number of commits in the provided `input_array`
 */
GIT_EXTERN(int) git_merge_base_many(git_oid *out, git_repository *repo, const git_oid input_array[], size_t length);

/** @} */
GIT_END_DECL
#endif


text:
package cn.moo.trainingcollege.controller;

import cn.moo.trainingcollege.entity.ManagerEntity;
import cn.moo.trainingcollege.entity.OrganizationEntity;
import cn.moo.trainingcollege.entity.StudentEntity;
import cn.moo.trainingcollege.service.ManagerService;
import cn.moo.trainingcollege.service.OrganService;
import cn.moo.trainingcollege.service.StudentService;
import org.codehaus.jackson.map.deser.ValueInstantiators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created by chenmuen on 2017/2/27.
 */
@Controller
@RequestMapping("/")
public class MainController extends BaseController {
    @Autowired
    StudentService studentService;

    @Autowired
    OrganService organService;

    @Autowired
    ManagerService managerService;

    @RequestMapping("")
    public String indexPage(HttpSession session) {
        int userType = (int)session.getAttribute("userType");

        switch (userType) {
            case 0:
                return "redirect:/course/all";
            case 1:
                return "redirect:/course/manage";
            case 2:
                return "redirect:/course/approve";
            default:
                return "redirect:/login";
        }

    }

    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam String id,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes redirectAttributes) {
        if(id==null||id.isEmpty()) {
            redirectAttributes.addFlashAttribute("errorMessage","账号为空");
            return "redirect:login";
        }

        StudentEntity studentEntity;
        char type = id.charAt(0);
        switch (type) {
            case 'S':
                if((studentEntity=studentService.getStudent(id))==null){
                    redirectAttributes.addFlashAttribute("message", "查无此ID");
                } else if(studentEntity.getState()==3){
                    redirectAttributes.addFlashAttribute("errorMessage", "该账号已注销,请重新注册");
                    return "redirect:/login";
                } else if(studentService.checkLogin(id, password)) {
                    session.setAttribute("user", id);
                    if(studentEntity.getState()==2) {
                        session.setAttribute("userType", 3);
                        redirectAttributes.addFlashAttribute("errorMessage", "账户被暂停,请充值激活");
                        return "redirect:/user/topup";
                    } else {
                        session.setAttribute("userType", 0);
                        redirectAttributes.addFlashAttribute("message", "登录成功");
                        return "redirect:/course/all";
                    }

                } else {
                    redirectAttributes.addFlashAttribute("errorMessage", "密码错误");
                }
                break;
            case 'O':
                if(organService.getOrgan(id)==null){
                    redirectAttributes.addFlashAttribute("errorMessage", "查无此ID");
                } else if(organService.checkLogin(id, password)) {
                    session.setAttribute("user", id);
                    session.setAttribute("userType", 1);
                    redirectAttributes.addFlashAttribute("message", "登录成功");
                    return "redirect:/course/manage";
                } else {
                    redirectAttributes.addFlashAttribute("errorMessage", "密码错误");
                }
                break;
            case 'M':
                if(managerService.getManager(id)==null){
                    redirectAttributes.addFlashAttribute("errorMessage", "查无此ID");
                } else if(managerService.checkLogin(id, password)) {
                    session.setAttribute("user", id);
                    session.setAttribute("userType", 2);
                    redirectAttributes.addFlashAttribute("message", "登录成功");
                    return "redirect:/course/approve";
                } else {
                    redirectAttributes.addFlashAttribute("errorMessage", "密码错误");
                }
                break;
            default:
                redirectAttributes.addFlashAttribute("errorMessage", "查无此ID");
                break;

        }

        return "redirect:/login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerPage() {
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam String name,
                           @RequestParam String password,
                           @RequestParam int type,
                           @RequestParam(required = false) String account,
                           RedirectAttributes redirectAttributes) {
        String id = null;

        switch (type) {
            case 0:
                StudentEntity studentEntity = new StudentEntity();
                studentEntity.setName(name);
                studentEntity.setPassword(password);
                studentEntity.setAccount(account);
                studentEntity.setState(0);
                id = studentService.addStudent(studentEntity);
                redirectAttributes.addFlashAttribute("id", id);
                redirectAttributes.addFlashAttribute("message", "注册成功,请记住账号");
                break;
            case 1:
                OrganizationEntity organizationEntity = new OrganizationEntity();
                organizationEntity.setName(name);
                organizationEntity.setPassword(password);
                organizationEntity.setLocation("");
                organizationEntity.setDescription("");
                id = organService.addOrgan(organizationEntity);
                redirectAttributes.addFlashAttribute("id", id);
                redirectAttributes.addFlashAttribute("message", "注册成功,请记住账号");
                break;
            case 2:
                ManagerEntity managerEntity = new ManagerEntity();
                managerEntity.setName(name);
                managerEntity.setPassword(password);
                id = managerService.addManager(managerEntity);
                redirectAttributes.addFlashAttribute("id", id);
                redirectAttributes.addFlashAttribute("message", "注册成功,请记住账号");
                break;
        }

        return "redirect:/login";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public String logout(HttpSession session){
        session.invalidate();

        return "redirect:/login";
    }

}


text:
package v1beta1

const (
	// Healthy means that the device is healty
	Healthy = "Healthy"
	// UnHealthy means that the device is unhealthy
	Unhealthy = "Unhealthy"

	// Current version of the API supported by kubelet
	Version = "v1beta1"
	// DevicePluginPath is the folder the Device Plugin is expecting sockets to be on
	// Only privileged pods have access to this path
	// Note: Placeholder until we find a "standard path"
	DevicePluginPath = "/var/lib/kubelet/device-plugins/"
	// KubeletSocket is the path of the Kubelet registry socket
	KubeletSocket = DevicePluginPath + "kubelet.sock"
	// Timeout duration in secs for PreStartContainer RPC
	KubeletPreStartContainerRPCTimeoutInSecs = 30
)

var SupportedVersions = [...]string{"v1beta1"}


text:
#include <zephyr/irq.h>

/*
 * In RISC-V there is no conventional way to handle CPU power save.
 * Each RISC-V SOC handles it in its own way.
 * Hence, by default, arch_cpu_idle and arch_cpu_atomic_idle functions just
 * unlock interrupts and return to the caller, without issuing any CPU power
 * saving instruction.
 *
 * Nonetheless, define the default arch_cpu_idle and arch_cpu_atomic_idle
 * functions as weak functions, so that they can be replaced at the SOC-level.
 */

void __weak arch_cpu_idle(void)
{
	irq_unlock(MSTATUS_IEN);
}

void __weak arch_cpu_atomic_idle(unsigned int key)
{
	irq_unlock(key);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 OpenCB
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.opencb.opencga</groupId>
        <artifactId>opencga-storage</artifactId>
        <version>0.7-dev</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>opencga-storage-app</artifactId>
    <version>${opencga.version}</version>
    <packaging>jar</packaging>

    <properties>
        <build.dir>build</build.dir>
        <app.name>opencga-storage</app.name>
        <service.name>opencga-storage-server</service.name>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-storage-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.beust</groupId>
            <artifactId>jcommander</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.16</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>opencga-app</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <targetPath>${basedir}/build/conf</targetPath>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.9</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <repositoryName>libs</repositoryName>
                    <repositoryLayout>flat</repositoryLayout>
                    <useWildcardClassPath>true</useWildcardClassPath>
                    <assembleDirectory>${build.dir}</assembleDirectory>
                    <programs>
                        <program>
                            <mainClass>org.opencb.opencga.storage.app.cli.OpenCGAStorageMain</mainClass>
                            <name>${app.name}-old.sh</name>
                            <platforms>
                                <platform>unix</platform>
                            </platforms>
                        </program>
                        <program>
                            <mainClass>org.opencb.opencga.storage.app.StorageMain</mainClass>
                            <name>${app.name}.sh</name>
                            <platforms>
                                <platform>unix</platform>
                            </platforms>
                        </program>
                        <program>
                            <mainClass>org.opencb.opencga.storage.app.service.OpenCGAStorageServiceMain</mainClass>
                            <name>${service.name}.sh</name>
                            <platforms>
                                <platform>unix</platform>
                            </platforms>
                        </program>
                    </programs>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <id>clean-libs</id>
                        <phase>clean</phase>
                        <configuration>
                            <target>
                                <echo>Cleaning libs folder at ${build.dir}</echo>
                                <exec executable="rm">
                                    <arg value="-rf"/>
                                    <arg value="${build.dir}/libs"/>
                                    <arg value="${build.dir}/bin"/>
                                    <arg value="${build.dir}/conf"/>
                                </exec>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>install-app</id>
                        <phase>install</phase>
                        <configuration>
                            <target>
                                <echo>Adding execution permission</echo>
                                <exec executable="chmod">
                                    <arg value="+x"/>
                                    <arg value="${build.dir}/bin/${app.name}.sh"/>
                                    <arg value="${build.dir}/bin/${service.name}.sh"/>
                                </exec>
                                <echo>Coping configuration file</echo>
                                <exec executable="cp">
                                    <arg value="${pom.basedir}/../opencga-storage-core/target/classes/${storage.configuration.file}"/>
                                    <arg value="${build.dir}/conf/"/>
                                </exec>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>STORAGE-MONGODB1</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>../opencga-storage-mongodb/src/main/resources</directory>
                        <filtering>true</filtering>
                        <targetPath>${basedir}/build/conf</targetPath>
                    </resource>
                </resources>
            </build>
            <dependencies>
                <dependency>
                    <groupId>org.opencb.opencga</groupId>
                    <artifactId>opencga-storage-mongodb</artifactId>
                    <version>${opencga.version}</version>
                </dependency>
            </dependencies>
            <properties>
                <!--<app.name>opencga-mongo.sh</app.name>-->
            </properties>
        </profile>
        <profile>
            <id>STORAGE-HBASE1</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>../opencga-storage-hbase/src/main/resources</directory>
                        <filtering>true</filtering>
                        <targetPath>${basedir}/build/conf</targetPath>
                    </resource>
                </resources>
            </build>
            <dependencies>
                <dependency>
                    <groupId>org.opencb.opencga</groupId>
                    <artifactId>opencga-storage-hbase</artifactId>
                    <version>${opencga.version}</version>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

</project>


text:
<?php

/**
 * Tests for the WP_Site_Icon class.
 *
 * @group site_icon
 */
class Tests_WP_Site_Icon extends WP_UnitTestCase {
	public $wp_site_icon;
	public $attachment_id = 0;

	function setUp() {
		parent::setUp();

		require_once ABSPATH . 'wp-admin/includes/class-wp-site-icon.php';
		$this->wp_site_icon = $GLOBALS['wp_site_icon'];
	}

	function tearDown() {
		$this->site_icon = null;
		$this->remove_added_uploads();
		parent::tearDown();
	}

	function test_intermediate_image_sizes() {
		$image_sizes = $this->wp_site_icon->intermediate_image_sizes( array() );

		$sizes = array();
		foreach ( $this->wp_site_icon->site_icon_sizes as $size ) {
			$sizes[] = 'site_icon-' . $size;
		}

		$this->assertEquals( $sizes, $image_sizes );
	}

	function test_intermediate_image_sizes_with_filter() {
		add_filter( 'site_icon_image_sizes', array( $this, '_custom_test_sizes' ) );
		$image_sizes = $this->wp_site_icon->intermediate_image_sizes( array() );

		$sizes = array();
		foreach ( $this->wp_site_icon->site_icon_sizes as $size ) {
			$sizes[] = 'site_icon-' . $size;
		}

		// Is our custom icon size there?
		$this->assertContains( 'site_icon-321', $image_sizes );

		// All icon sizes should be part of the array, including sizes added through the filter.
		$this->assertEquals( $sizes, $image_sizes );

		// Remove custom size.
		unset( $this->wp_site_icon->site_icon_sizes[ array_search( 321, $this->wp_site_icon->site_icon_sizes ) ] );
		// Remove the filter we added
		remove_filter( 'site_icon_image_sizes', array( $this, '_custom_test_sizes' ) );
	}

	function test_additional_sizes() {
		$image_sizes = $this->wp_site_icon->additional_sizes( array() );

		$sizes = array();
		foreach ( $this->wp_site_icon->site_icon_sizes as $size ) {
			$sizes[ 'site_icon-' . $size ] = array(
				'width ' => $size,
				'height' => $size,
				'crop'   => true,
			);
		}

		$this->assertEquals( $sizes, $image_sizes );
	}

	function test_additional_sizes_with_filter() {
		add_filter( 'site_icon_image_sizes', array( $this, '_custom_test_sizes' ) );
		$image_sizes = $this->wp_site_icon->additional_sizes( array() );

		$sizes = array();
		foreach ( $this->wp_site_icon->site_icon_sizes as $size ) {
			$sizes[ 'site_icon-' . $size ] = array(
				'width ' => $size,
				'height' => $size,
				'crop'   => true,
			);
		}

		// Is our custom icon size there?
		$this->assertArrayHasKey( 'site_icon-321', $image_sizes );

		// All icon sizes should be part of the array, including sizes added through the filter.
		$this->assertEquals( $sizes, $image_sizes );

		// Remove custom size.
		unset( $this->wp_site_icon->site_icon_sizes[ array_search( 321, $this->wp_site_icon->site_icon_sizes ) ] );
	}

	function test_create_attachment_object() {
		$attachment_id = $this->_insert_attachment();
		$parent_url    = get_post( $attachment_id )->guid;
		$cropped       = str_replace( basename( $parent_url ), 'cropped-test-image.jpg', $parent_url );

		$object = $this->wp_site_icon->create_attachment_object( $cropped, $attachment_id );

		$this->assertEquals( $object['post_title'],     'cropped-test-image.jpg' );
		$this->assertEquals( $object['context'],        'site-icon' );
		$this->assertEquals( $object['post_mime_type'], 'image/jpeg' );
		$this->assertEquals( $object['post_content'],   $cropped );
		$this->assertEquals( $object['guid'],           $cropped );
	}

	function test_insert_cropped_attachment() {
		$attachment_id = $this->_insert_attachment();
		$parent_url    = get_post( $attachment_id )->guid;
		$cropped       = str_replace( basename( $parent_url ), 'cropped-test-image.jpg', $parent_url );

		$object     = $this->wp_site_icon->create_attachment_object( $cropped, $attachment_id );
		$cropped_id = $this->wp_site_icon->insert_attachment( $object, $cropped );

		$this->assertInternalType( 'int', $cropped_id );
		$this->assertGreaterThan( 0, $cropped_id );
	}

	function test_delete_attachment_data() {
		$attachment_id = $this->_insert_attachment();
		update_option( 'site_icon', $attachment_id );

		wp_delete_attachment( $attachment_id, true );

		$this->assertFalse( get_option( 'site_icon', false ) );
	}

	function _custom_test_sizes( $sizes ) {
		$sizes[] = 321;

		return $sizes;
	}

	function _insert_attachment() {
		if ( $this->attachment_id ) {
			return $this->attachment_id;
		}

		$filename = DIR_TESTDATA . '/images/test-image.jpg';
		$contents = file_get_contents( $filename );

		$upload = wp_upload_bits( basename( $filename ), null, $contents );
		$type   = '';
		if ( ! empty( $upload['type'] ) ) {
			$type = $upload['type'];
		} else {
			$mime = wp_check_filetype( $upload['file'] );
			if ( $mime ) {
				$type = $mime['type'];
			}
		}

		$attachment = array(
			'post_title'     => basename( $upload['file'] ),
			'post_content'   => $upload['url'],
			'post_type'      => 'attachment',
			'post_mime_type' => $type,
			'guid'           => $upload['url'],
		);

		// Save the data
		$this->attachment_id  = wp_insert_attachment( $attachment, $upload['file'] );
		wp_update_attachment_metadata( $this->attachment_id, wp_generate_attachment_metadata( $this->attachment_id, $upload['file'] ) );

		return $this->attachment_id;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlResults PUBLIC "-//GemStone Systems, Inc.//GemFireXD Test Results 1.0//EN"
          "sqlResults1_0.dtd">
<sqlResults>
	<!-- The empty result set -->
	<resultSet id="empty" />
	<!--
		Result set expected when no server group has been given in CREATE
		SCHEMA EMP.
	-->
	<resultSet id="emp_nosg">
		<row>
			<field name="SCHEMANAME">EMP</field>
			<field name="DEFAULTSERVERGROUPS"></field>
			<field name="AUTHORIZATIONID">APP</field>
		</row>
	</resultSet>
	<!--
		Result set expected when server group has been given in CREATE SCHEMA
		EMP. Deliberately changed the order of fields to check that the
		code for unordered checking in XML comparison works correctly.
	-->
	<resultSet id="emp_sg">
		<row>
			<field name="DEFAULTSERVERGROUPS">SG1</field>
			<field name="SCHEMANAME">EMP</field>
		</row>
	</resultSet>
	<!--
		Result set expected when selecting a single test row from a table in
		the EMP schema.
	-->
	<resultSet id="emp_tab_sel">
		<row>
			<field name="ID">1</field>
			<field name="DESCRIPTION">First</field>
		</row>
	</resultSet>
</sqlResults>


text:
module Azure::Network::Mgmt::V2016_09_01
  module Models
    #
    # Information on the configuration of flow log.
    #
    class FlowLogInformation

      include MsRestAzure

      # @return [String] The ID of the resource to configure for flow logging.
      attr_accessor :target_resource_id

      # @return [String] ID of the storage account which is used to store the
      # flow log.
      attr_accessor :storage_id

      # @return [Boolean] Flag to enable/disable flow logging.
      attr_accessor :enabled

      # @return [RetentionPolicyParameters]
      attr_accessor :retention_policy

      #
      # Mapper for FlowLogInformation class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'FlowLogInformation',
          type: {
            name: 'Composite',
            class_name: 'FlowLogInformation',
            model_properties: {
              target_resource_id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'targetResourceId',
                type: {
                  name: 'String'
                }
              },
              storage_id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'properties.storageId',
                type: {
                  name: 'String'
                }
              },
              enabled: {
                client_side_validation: true,
                required: true,
                serialized_name: 'properties.enabled',
                type: {
                  name: 'Boolean'
                }
              },
              retention_policy: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.retentionPolicy',
                type: {
                  name: 'Composite',
                  class_name: 'RetentionPolicyParameters'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
from impact.tests.api_test_case import APITestCase
from impact.tests.factories import PartnerFactory

class TestPartner(APITestCase):

    def test_str(self):
        partner = PartnerFactory()
        assert str(partner) == partner.name

    def test_partner_twitter_handle_is_from_organization(self):
        partner = PartnerFactory()
        partner.twitter_handle = 'partner'
        self.assertEqual(
            partner.twitter_handle,
            partner.organization.twitter_handle)

    def test_partner_website_url_is_from_organization(self):
        partner = PartnerFactory()
        partner.website_url = 'http://test.com'
        self.assertEqual(
            partner.website_url,
            partner.organization.website_url)


text:
<?php

namespace MadMind\StateMachineVisualizationBundle\Exception;

use RuntimeException;

class DotException extends RuntimeException
{
}


text:
<?php

namespace CpdnAPI\Controllers;

use CpdnAPI\Utils\Common;
use CpdnAPI\Models\Editor\Notification;
use CpdnAPI\Models\IdentityProvider\Profile;
use CpdnAPI\Utils\CollectionGenerator as CG;
use CpdnAPI\Utils\ItemGenerator as IG;
use CpdnAPI\Utils\MetaGenerator as MG;
use CpdnAPI\Utils\ResponseGenerator as RG;
use CpdnAPI\Utils\Searchable;
use CpdnAPI\Utils\Sortable;
use CpdnAPI\Utils\Expandable;
use CpdnAPI\Utils\Paginator;
use Phalcon\Paginator\Adapter\QueryBuilder as PQB;

class NotificationsController extends ControllerBase {
	private $validFields = array (
			"id" => Common::PATTERN_UNSIGNED_INTEGER_WITHOUT_ZERO,
			"tsCreate" => Common::PATTERN_TIMESTAMP,
			"tsUpdate" => Common::PATTERN_TIMESTAMP,
			"tsRead" => Common::PATTERN_TIMESTAMP,
			"profileId" => Common::PATTERN_UNSIGNED_INTEGER_WITHOUT_ZERO,
			"title" => "/^[\s\S]+$/",
			"content" => Common::PATTERN_TEXT_OPTIONAL
	);

	public function initialize() {
		$this->view->disable ();
		$this->response->setContentType ( 'application/json', 'UTF-8' );
		$this->response->setStatusCode ( 404, "Not Found" );
	}
	public function readCollectionAction() {
		$page_size = ( int ) $this->request->get ( Paginator::URL_QUERY_PARAM_PAGE_SIZE, "int", Paginator::DEFAULT_PAGE_SIZE );
		$page_number = ( int ) $this->request->get ( Paginator::URL_QUERY_PARAM_PAGE_NUMBER, "int", Paginator::DEFAULT_PAGE );

		switch ($this->dispatcher->getParam ( "version" )) {
			case Common::API_VERSION_V1 :
				// create builder
				$builder = $this->modelsManager->createBuilder ()->columns ( array_keys ( $this->validFields ) )->from ( 'CpdnAPI\Models\Editor\Notification' );

				// append WHERE conditions
				$where = Searchable::buildQueryBuilderWhereParams ( $this->request->get ( Searchable::URL_QUERY_PARAM ), $this->validFields, array("profileId") );
				if (is_array ( $where ) && ! empty ( $where ) && $where !== false && $where !== null) {
					$builder->where ( $where ["conditions"], $where ["bindParams"] );
				}
				if ($where === false) {
					$this->response->setStatusCode ( 400, "Bad Request" );
					$this->response->setJsonContent(RG::generateContent($this->request->getURI (), RG::S400_MISSING_FIELD));
					return $this->response;
				}

				// append ORDER BY string
				if (($order = Sortable::buildQueryBuilderOrderByParams ( $this->request->get ( Sortable::URL_QUERY_PARAM ), array_keys ( $this->validFields ) )) !== false) {
					$builder->orderBy ( $order );
				}

				// paginate builder
				$paginator = new PQB ( array (
						"builder" => $builder,
						"limit" => $page_size,
						"page" => $page_number
				) );
				$page = $paginator->getPaginate ();

				// expand & select result set
				$items = array ();
				$expandable = Expandable::buildExpandableFields ( $this->request->get ( Expandable::URL_QUERY_PARAM ), array (
						"notification", "notification.user"
				) );
				foreach ( $page->items as $item ) {
					if (in_array ( "notification", $expandable )) {
						// expanded notification

						$i = Notification::findFirst ( array (
								"id = :id:",
								"bind" => array (
										"id" => $item->id
								)
						) );
						$t = Notification::getNotification($i);

						if (in_array ( "notification.user", $expandable )) {
							$t ["user"] = IG::generate ( sprintf ( "/%s/users/%s/", Common::API_VERSION_V1, $i->profile->id ), array (
									MG::KEY_ID => $i->profile->id,
									"tsCreate" => $i->profile->tsCreate,
									"tsUpdate" => $i->profile->tsUpdate
							), Profile::getProfile ( $i->profile ) );
						}

						$items [] = IG::generate ( sprintf ( "/%s/notifications/%s/", Common::API_VERSION_V1, $i->id ), array (
								MG::KEY_ID => $i->id,
								"tsCreate" => $i->tsCreate,
								"tsUpdate" => $i->tsUpdate
						), $t );
					} else {
						// meta link to the notification
						$items [] = array (
								MG::KEY_META => MG::generate ( sprintf ( "/%s/notifications/%s/", Common::API_VERSION_V1, $item->id ), array (
										MG::KEY_ID => $item->id
								) )
						);
					}
				}

				if (! empty ( $items )) {
					$this->response->setStatusCode ( 200, "OK" );
					$this->response->setJsonContent ( CG::generate ( $items, $this->request->getURI (), $page->total_items, $page->total_pages, $page->current, $page_size, array (
							"first" => Paginator::DEFAULT_PAGE,
							"previous" => $page->before,
							"next" => $page->next,
							"last" => $page->last
					) ) );
				} else {
					$this->response->setStatusCode ( 204, "No Content" );
					$this->response->setJsonContent(RG::generateContent($this->request->getURI (), RG::S204));
				}
				return $this->response;
				break;
		}
	}
	public function readItemAction() {
		switch ($this->dispatcher->getParam ( "version" )) {
			case Common::API_VERSION_V1 :
				$id = $this->dispatcher->getParam ( "id" );

				$notification = Notification::findFirst ( array (
						"id = :id:",
						"bind" => array (
								"id" => $id
						)
				) );

				if ($notification) {
					$expandable = Expandable::buildExpandableFields ( $this->request->get ( Expandable::URL_QUERY_PARAM ), array (
							"user"
					) );

					$t = Notification::getNotification($notification);

					if (in_array ( "user", $expandable )) {
						$t ["user"] = IG::generate ( sprintf ( "/%s/users/%s/", Common::API_VERSION_V1, $notification->profile->id ), array (
								MG::KEY_ID => $notification->profile->id,
								"tsCreate" => $notification->profile->tsCreate,
								"tsUpdate" => $notification->profile->tsUpdate
						), Profile::getProfile ( $notification->profile ) );
					}

					$r = IG::generate ( sprintf ( "/%s/notifications/%s/", Common::API_VERSION_V1, $notification->id ), array (
							MG::KEY_ID => $notification->id,
							"tsCreate" => $notification->tsCreate,
							"tsUpdate" => $notification->tsUpdate
					), $t );

					$this->response->setStatusCode ( 200, "OK" );
					$this->response->setJsonContent ( $r );
				} else {
					$this->response->setStatusCode ( 404, "Not Found" );
					$this->response->setJsonContent ( RG::generateContent ( $this->request->getURI (), RG::S404 ) );
				}
				return $this->response;
				break;
		}
	}
	public function updateItemAction() {
		switch ($this->dispatcher->getParam ( "version" )) {
			case Common::API_VERSION_V1 :
				$body = $this->request->getJsonRawBody();
				$id = $this->dispatcher->getParam ( "id" );
				if(	preg_match ( $this->validFields ["tsRead"], $body->tsRead ) === 1){
							$notification = Notification::findFirst ( array (
									"id = :id:",
									"bind" => array (
											"id" => $id
									)
							) );

							// required notification
							if($notification){
								$notification->tsRead = $body->tsRead;

								if($notification->save()){
									$this->response->setStatusCode ( 200, "OK" );
									$this->response->setJsonContent(RG::generateContent($this->request->getURI (), RG::S200, "", array("id" => $notification->id)));
								} else{
									$this->response->setStatusCode ( 500, "Internal Server Error" );
									$this->response->setJsonContent(RG::generateContent($this->request->getURI (), RG::S500_CRUD_ERROR));
								}
							} else{
								$this->response->setStatusCode ( 404, "Not Found" );
								$this->response->setJsonContent ( RG::generateContent ( $this->request->getURI (), RG::S404, "Notification was not found by posted id.") );
							}
				} else{
					$this->response->setStatusCode ( 400, "Bad Request" );
					$this->response->setJsonContent(RG::generateContent($this->request->getURI (), RG::S400_VALIDATION_FAILED, "Regex validation of posted fields failed."));
				}

				return $this->response;
				break;
		}
	}
}


text:
import uuid
from filestore.api import db_connect, db_disconnect
import filestore.conf as fconf

conn = None
db_name = "fs_testing_disposable_{}".format(str(uuid.uuid4()))
old_conf = dict(fconf.connection_config)

def fs_setup():
    "Create a fresh database with unique (random) name."
    global conn
    db_disconnect()
    test_conf = dict(database=db_name, host='localhost',
                     port=27017)
    conn = db_connect(**test_conf)
    old_conf.clear()
    old_conf.update(fconf.connection_config)
    fconf.connection_config.clear()
    fconf.connection_config.update(test_conf)

def fs_teardown():
    "Drop the fresh database and disconnect."
    conn.drop_database(db_name)
    db_disconnect()
    fconf.connection_config.clear()
    fconf.connection_config.update(old_conf)


text:
export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-animator-css')
    .plugin('aurelia-bs-modal');

  aurelia.start().then(a => a.setRoot());
}


text:
package exec

import (
	"fmt"
	"path/filepath"
	"strings"

	"github.com/concourse/concourse/atc"
	"github.com/concourse/concourse/atc/exec/build"
	"github.com/concourse/concourse/atc/resource"
	"github.com/concourse/concourse/atc/runtime"
)

type PutInputNotFoundError struct {
	Input string
}

func (e PutInputNotFoundError) Error() string {
	return fmt.Sprintf("input not found: %s", e.Input)
}

type PutInputs interface {
	FindAll(*build.Repository) ([]runtime.Input, error)
}

type allInputs struct{}

func NewAllInputs() PutInputs {
	return &allInputs{}
}

func (i allInputs) FindAll(artifacts *build.Repository) ([]runtime.Input, error) {
	artifactsMap := artifacts.AsMap()

	inputs := make([]runtime.Input, 0, len(artifactsMap))
	for name, artifact := range artifactsMap {
		inputs = append(inputs, putInput(name, artifact))
	}

	return inputs, nil
}

type specificInputs struct {
	inputs []string
}

func NewSpecificInputs(inputs []string) PutInputs {
	return &specificInputs{
		inputs: inputs,
	}
}

func (i specificInputs) FindAll(artifacts *build.Repository) ([]runtime.Input, error) {
	artifactsMap := artifacts.AsMap()

	inputs := make([]runtime.Input, len(i.inputs))
	for i, name := range i.inputs {
		vol, found := artifactsMap[build.ArtifactName(name)]
		if !found {
			return nil, PutInputNotFoundError{Input: name}
		}
		inputs[i] = putInput(build.ArtifactName(name), vol)
	}

	return inputs, nil
}

type detectInputs struct {
	guessedNames []build.ArtifactName
}

func detectInputsFromParam(value interface{}) []build.ArtifactName {
	switch actual := value.(type) {
	case string:
		input := actual
		if parts := strings.Split(actual, "/"); len(parts) > 1 {
			for _, part := range parts {
				if part == "." || part == ".." {
					continue
				}
				input = part
				break
			}
		}
		return []build.ArtifactName{build.ArtifactName(input)}
	case map[string]interface{}:
		var inputs []build.ArtifactName
		for _, value := range actual {
			inputs = append(inputs, detectInputsFromParam(value)...)
		}
		return inputs
	case []interface{}:
		var inputs []build.ArtifactName
		for _, value := range actual {
			inputs = append(inputs, detectInputsFromParam(value)...)
		}
		return inputs
	default:
		return []build.ArtifactName{}
	}
}

func NewDetectInputs(params atc.Params) PutInputs {
	return &detectInputs{
		guessedNames: detectInputsFromParam(map[string]interface{}(params)),
	}
}

func (i detectInputs) FindAll(artifacts *build.Repository) ([]runtime.Input, error) {
	artifactsMap := artifacts.AsMap()

	inputs := []runtime.Input{}
	for _, name := range i.guessedNames {
		artifactEntry, found := artifactsMap[name]
		if !found {
			// false positive; not an artifact
			continue
		}
		inputs = append(inputs, putInput(name, artifactEntry))
	}

	return inputs, nil
}

func putInput(name build.ArtifactName, artifactEntry build.ArtifactEntry) runtime.Input {
	return runtime.Input{
		Artifact:        artifactEntry.Artifact,
		DestinationPath: filepath.Join(resource.ResourcesDir("put"), string(name)),
		FromCache:       artifactEntry.FromCache,
	}
}


text:
<%
    from pylons.i18n.translation import _
%>
<%inherit file="/base/admin.html"/>
<%namespace file="fields.html" name="fields" import="*"/>
<%namespace file="/component/admin.html" name="admin" import="*"/>
<%namespace file="/component/editor.html" name="editor" import="*"/>

<%def name="title()">
    ${_('Create a New Page')}
</%def>

<%def name="js()">
    ${editor.admin_editor()}
    ${admin.tooltip()}
</%def>

    ${h.link_to(
        h.literal(''),
        h.url_for(controller='page', action='list'),
        class_='ui-state-default ui-corner-all',
        title=_('Cancel')
    )}

${h.form(h.url_for(action='create', controller='page'), method='post')}
    ${fields.body()}
    ${h.submit('create', _('Create Page'))} ${_('or')}
    ${h.link_to(_('Cancel'), h.url_for(controller='page', action='list'))}
${h.end_form()}


text:
    {% if 1 > 2 %}

        Pepperoni pizzas are the best thing ever invented
    {% endif %}


text:
package util;

import hydra.FileUtil;
import hydra.HydraRuntimeException;
import hydra.Log;
import hydra.MasterProxyIF;
import hydra.ProcessMgr;
import hydra.RmiRegistryHelper;

import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.cache.Declarable;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.util.CacheListenerAdapter;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.control.InternalResourceManager;
import com.gemstone.gemfire.internal.cache.control.InternalResourceManager.ResourceObserverAdapter;

/**
 * CacheServer SilenceListener
 * Same as util.SilenceListener, but establishes the LogWriter in a static block
 *
 * @author lhughes
 * @since 7.0
 */
public class CSSilenceListener extends util.SilenceListener implements Declarable {

/**  Stub reference to a remote master controller */
public static MasterProxyIF Master = null;
protected static LogWriter log = null;

  static {

    // initialization in CacheServer VM
    // Open a LogWriter
    try {
       Log.getLogWriter();
    } catch (HydraRuntimeException e) {
       // create the task log
       String logName = "cacheserver_" + ProcessMgr.getProcessId();
       log = Log.createLogWriter( logName, "info" );
     }

     // We need to set user.dir (for access to TestConfig)
     // RMI lookup of Master (for Blackboard access), relies on TestConfig
     String cacheServerDir = System.getProperty("user.dir");
     String testDir = FileUtil.pathFor(cacheServerDir);
     System.setProperty("test.dir", testDir);

     if ( Master == null ) {
        Master = RmiRegistryHelper.lookupMaster();
     }
   }
}


text:
package lila.insight

case class Question[X](
    dimension: Dimension[X],
    metric: Metric,
    filters: List[Filter[_]]
)

case class Filter[A](
    dimension: Dimension[A],
    selected: List[A]
) {

  def isEmpty = selected.isEmpty || selected.sizeIs == Dimension.valuesOf(dimension).size

  import reactivemongo.api.bson._

  def matcher: BSONDocument = Dimension.filtersOf(dimension, selected)
}


text:
import time

from absl import app, flags
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from pywinauto.application import Application
from pywinauto.findwindows import ElementNotFoundError

from test_util import create_chrome_webdriver

FLAGS = flags.FLAGS

flags.DEFINE_string('url', None, 'The url to open in Chrome.')
flags.mark_flag_as_required('url')

def main(argv):
  chrome_options = webdriver.ChromeOptions()
  chrome_options.add_argument("--force-renderer-accessibility")
  #Always set useAutomationExtension as false to avoid failing launch Chrome
  #https://bugs.chromium.org/p/chromedriver/issues/detail?id=2930
  chrome_options.add_experimental_option("useAutomationExtension", False)
  driver = create_chrome_webdriver(chrome_options=chrome_options)
  app = Application(backend="uia")
  app.connect(title_re='.*Chrome|.*Chromium')
  driver.get(FLAGS.url)
  time.sleep(5)

  try:
    driver.find_element_by_xpath(
        "//div[@aria-label='Blocked by admin']").click()
    app.top_window() \
       .child_window(title_re='.*Your admin has blocked', control_type="TitleBar") \
       .print_control_identifiers()
  except NoSuchElementException:
    print("Not blocked")
  except ElementNotFoundError:
    print("Not blocked")
  finally:
    driver.quit()

if __name__ == '__main__':
  app.run(main)


text:
require "spec_helper"

describe Rack::Test::Session do
  describe "initialization" do
    it "supports being initialized with a Rack::MockSession app" do
      session = Rack::Test::Session.new(Rack::MockSession.new(app))
      session.request("/").should be_ok
    end

    it "supports being initialized with an app" do
      session = Rack::Test::Session.new(app)
      session.request("/").should be_ok
    end
  end

  describe "#request" do
    it "requests the URI using GET by default" do
      request "/"
      last_request.should be_get
      last_response.should be_ok
    end

    it "returns a response" do
      request("/").should be_ok
    end

    it "uses the provided env" do
      request "/", "X-Foo" => "bar"
      last_request.env["X-Foo"].should == "bar"
    end

    it "allows HTTP_HOST to be set" do
      request "/", "HTTP_HOST" => "www.example.ua"
      last_request.env['HTTP_HOST'].should == "www.example.ua"
    end

    it "sets HTTP_HOST with port for non-default ports" do
      request "http://foo.com:8080"
      last_request.env["HTTP_HOST"].should == "foo.com:8080"
      request "https://foo.com:8443"
      last_request.env["HTTP_HOST"].should == "foo.com:8443"
    end

    it "sets HTTP_HOST without port for default ports" do
      request "http://foo.com"
      last_request.env["HTTP_HOST"].should == "foo.com"
      request "http://foo.com:80"
      last_request.env["HTTP_HOST"].should == "foo.com"
      request "https://foo.com:443"
      last_request.env["HTTP_HOST"].should == "foo.com"
    end

    it "defaults to GET" do
      request "/"
      last_request.env["REQUEST_METHOD"].should == "GET"
    end

    it "defaults the REMOTE_ADDR to 127.0.0.1" do
      request "/"
      last_request.env["REMOTE_ADDR"].should == "127.0.0.1"
    end

    it "sets rack.test to true in the env" do
      request "/"
      last_request.env["rack.test"].should == true
    end

    it "defaults to port 80" do
      request "/"
      last_request.env["SERVER_PORT"].should == "80"
    end

    it "defaults to example.org" do
      request "/"
      last_request.env["SERVER_NAME"].should == "example.org"
    end

    it "yields the response to a given block" do
      request "/" do |response|
        response.should be_ok
      end
    end

    it "supports sending :params" do
      request "/", :params => { "foo" => "bar" }
      last_request.GET["foo"].should == "bar"
    end

    it "doesn't follow redirects by default" do
      request "/redirect"
      last_response.should be_redirect
      last_response.body.should be_empty
    end

    it "allows passing :input in for POSTs" do
      request "/", :method => :post, :input => "foo"
      last_request.env["rack.input"].read.should == "foo"
    end

    it "converts method names to a uppercase strings" do
      request "/", :method => :put
      last_request.env["REQUEST_METHOD"].should == "PUT"
    end

    it "prepends a slash to the URI path" do
      request "foo"
      last_request.env["PATH_INFO"].should == "/foo"
    end

    it "accepts params and builds query strings for GET requests" do
      request "/foo?baz=2", :params => {:foo => {:bar => "1"}}
      last_request.GET.should == { "baz" => "2", "foo" => { "bar" => "1" }}
    end

    it "parses query strings with repeated variable names correctly" do
      request "/foo?bar=2&bar=3"
      last_request.GET.should == { "bar" => "3" }
    end

    it "accepts raw input in params for GET requests" do
      request "/foo?baz=2", :params => "foo[bar]=1"
      last_request.GET.should == { "baz" => "2", "foo" => { "bar" => "1" }}
    end

    it "does not rewrite a GET query string when :params is not supplied" do
      request "/foo?a=1&b=2&c=3&e=4&d=5+%20"
      last_request.query_string.should == "a=1&b=2&c=3&e=4&d=5+%20"
    end

    it "does not overwrite multiple query string keys" do
      request "/foo?a=1&a=2", :params => { :bar => 1 }
      last_request.query_string.should == "a=1&a=2&bar=1"
    end

    it "accepts params and builds url encoded params for POST requests" do
      request "/foo", :method => :post, :params => {:foo => {:bar => "1"}}
      last_request.env["rack.input"].read.should == "foo[bar]=1"
    end

    it "accepts raw input in params for POST requests" do
      request "/foo", :method => :post, :params => "foo[bar]=1"
      last_request.env["rack.input"].read.should == "foo[bar]=1"
    end

    context "when the response body responds_to?(:close)" do
      class CloseableBody
        def initialize
          @closed = false
        end

        def each
          return if @closed
          yield "Hello, World!"
        end

        def close
          @closed = true
        end
      end

      it "closes response's body" do
        body = CloseableBody.new
        body.should_receive(:close)

        app = lambda do |env|
          [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, body]
        end

        session = Rack::Test::Session.new(Rack::MockSession.new(app))
        session.request("/")
      end

      it "closes response's body after iteration" do
        app = lambda do |env|
          [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, CloseableBody.new]
        end

        session = Rack::Test::Session.new(Rack::MockSession.new(app))
        session.request("/")
        session.last_response.body.should == "Hello, World!"
      end
    end

    context "when input is given" do
      it "sends the input" do
        request "/", :method => "POST", :input => "foo"
        last_request.env["rack.input"].read.should == "foo"
      end

      it "does not send a multipart request" do
        request "/", :method => "POST", :input => "foo"
        last_request.env["CONTENT_TYPE"].should_not == "application/x-www-form-urlencoded"
      end
    end

    context "for a POST specified with :method" do
      it "uses application/x-www-form-urlencoded as the CONTENT_TYPE" do
        request "/", :method => "POST"
        last_request.env["CONTENT_TYPE"].should == "application/x-www-form-urlencoded"
      end
    end

    context "for a POST specified with REQUEST_METHOD" do
      it "uses application/x-www-form-urlencoded as the CONTENT_TYPE" do
        request "/", "REQUEST_METHOD" => "POST"
        last_request.env["CONTENT_TYPE"].should == "application/x-www-form-urlencoded"
      end
    end

    context "when CONTENT_TYPE is specified in the env" do
      it "does not overwrite the CONTENT_TYPE" do
        request "/", "CONTENT_TYPE" => "application/xml"
        last_request.env["CONTENT_TYPE"].should == "application/xml"
      end
    end

    context "when the URL is https://" do
      it "sets rack.url_scheme to https" do
        get "https://example.org/"
        last_request.env["rack.url_scheme"].should == "https"
      end

      it "sets SERVER_PORT to 443" do
        get "https://example.org/"
        last_request.env["SERVER_PORT"].should == "443"
      end

      it "sets HTTPS to on" do
        get "https://example.org/"
        last_request.env["HTTPS"].should == "on"
      end
    end

    context "for a XHR" do
      it "sends XMLHttpRequest for the X-Requested-With header" do
        request "/", :xhr => true
        last_request.env["HTTP_X_REQUESTED_WITH"].should == "XMLHttpRequest"
        last_request.should be_xhr
      end
    end
  end

  describe "#header" do
    it "sets a header to be sent with requests" do
      header "User-Agent", "Firefox"
      request "/"

      last_request.env["HTTP_USER_AGENT"].should == "Firefox"
    end

    it "sets a Content-Type to be sent with requests" do
      header "Content-Type", "application/json"
      request "/"

      last_request.env["CONTENT_TYPE"].should == "application/json"
    end

    it "sets a Host to be sent with requests" do
      header "Host", "www.example.ua"
      request "/"

      last_request.env["HTTP_HOST"].should == "www.example.ua"
    end

    it "persists across multiple requests" do
      header "User-Agent", "Firefox"
      request "/"
      request "/"

      last_request.env["HTTP_USER_AGENT"].should == "Firefox"
    end

    it "overwrites previously set headers" do
      header "User-Agent", "Firefox"
      header "User-Agent", "Safari"
      request "/"

      last_request.env["HTTP_USER_AGENT"].should == "Safari"
    end

    it "can be used to clear a header" do
      header "User-Agent", "Firefox"
      header "User-Agent", nil
      request "/"

      last_request.env.should_not have_key("HTTP_USER_AGENT")
    end

    it "is overridden by headers sent during the request" do
      header "User-Agent", "Firefox"
      request "/", "HTTP_USER_AGENT" => "Safari"

      last_request.env["HTTP_USER_AGENT"].should == "Safari"
    end
  end

  describe "#env" do
    it "sets the env to be sent with requests" do
      env "rack.session", {:csrf => 'token'}
      request "/"

      last_request.env["rack.session"].should == {:csrf => 'token'}
    end

    it "persists across multiple requests" do
      env "rack.session", {:csrf => 'token'}
      request "/"
      request "/"

      last_request.env["rack.session"].should == {:csrf => 'token'}
    end

    it "overwrites previously set envs" do
      env "rack.session", {:csrf => 'token'}
      env "rack.session", {:some => :thing}
      request "/"

      last_request.env["rack.session"].should == {:some => :thing}
    end

    it "can be used to clear a env" do
      env "rack.session", {:csrf => 'token'}
      env "rack.session", nil
      request "/"

      last_request.env.should_not have_key("X_CSRF_TOKEN")
    end

    it "is overridden by envs sent during the request" do
      env "rack.session", {:csrf => 'token'}
      request "/", "rack.session" => {:some => :thing}

      last_request.env["rack.session"].should == {:some => :thing}
    end
  end

  describe "#authorize" do
    it "sets the HTTP_AUTHORIZATION header" do
      authorize "bryan", "secret"
      request "/"

      last_request.env["HTTP_AUTHORIZATION"].should == "Basic YnJ5YW46c2VjcmV0\n"
    end

    it "includes the header for subsequent requests" do
      basic_authorize "bryan", "secret"
      request "/"
      request "/"

      last_request.env["HTTP_AUTHORIZATION"].should == "Basic YnJ5YW46c2VjcmV0\n"
    end
  end

  describe "follow_redirect!" do
    it "follows redirects" do
      get "/redirect"
      follow_redirect!

      last_response.should_not be_redirect
      last_response.body.should == "You've been redirected"
      last_request.env["HTTP_REFERER"].should eql("http://example.org/redirect")
    end

    it "does not include params when following the redirect" do
      get "/redirect", { "foo" => "bar" }
      follow_redirect!

      last_request.GET.should == {}
    end

    it "raises an error if the last_response is not set" do
      lambda {
        follow_redirect!
      }.should raise_error(Rack::Test::Error)
    end

    it "raises an error if the last_response is not a redirect" do
      get "/"

      lambda {
        follow_redirect!
      }.should raise_error(Rack::Test::Error)
    end
  end

  describe "#last_request" do
    it "returns the most recent request" do
      request "/"
      last_request.env["PATH_INFO"].should == "/"
    end

    it "raises an error if no requests have been issued" do
      lambda {
        last_request
      }.should raise_error(Rack::Test::Error)
    end
  end

  describe "#last_response" do
    it "returns the most recent response" do
      request "/"
      last_response["Content-Type"].should == "text/html;charset=utf-8"
    end

    it "raises an error if no requests have been issued" do
      lambda {
        last_response
      }.should raise_error
    end
  end

  describe "after_request" do
    it "runs callbacks after each request" do
      ran = false

      rack_mock_session.after_request do
        ran = true
      end

      get "/"
      ran.should == true
    end

    it "runs multiple callbacks" do
      count = 0

      2.times do
        rack_mock_session.after_request do
          count += 1
        end
      end

      get "/"
      count.should == 2
    end
  end

  describe "#get" do
    it_should_behave_like "any #verb methods"

    def verb
      "get"
    end

    it "uses the provided params hash" do
      get "/", :foo => "bar"
      last_request.GET.should == { "foo" => "bar" }
    end

    it "sends params with parens in names" do
      get "/", "foo(1i)" => "bar"
      last_request.GET["foo(1i)"].should == "bar"
    end

    it "supports params with encoding sensitive names" do
      get "/", "foo bar" => "baz"
      last_request.GET["foo bar"].should == "baz"
    end

    it "supports params with nested encoding sensitive names" do
      get "/", "boo" => {"foo bar" => "baz"}
      last_request.GET.should == {"boo" => {"foo bar" => "baz"}}
    end

    it "accepts params in the path" do
      get "/?foo=bar"
      last_request.GET.should == { "foo" => "bar" }
    end
  end

  describe "#head" do
    it_should_behave_like "any #verb methods"

    def verb
      "head"
    end
  end

  describe "#post" do
    it_should_behave_like "any #verb methods"

    def verb
      "post"
    end

    it "uses the provided params hash" do
      post "/", :foo => "bar"
      last_request.POST.should == { "foo" => "bar" }
    end

    it "supports params with encoding sensitive names" do
      post "/", "foo bar" => "baz"
      last_request.POST["foo bar"].should == "baz"
    end

    it "uses application/x-www-form-urlencoded as the CONTENT_TYPE" do
      post "/"
      last_request.env["CONTENT_TYPE"].should == "application/x-www-form-urlencoded"
    end

    it "accepts a body" do
      post "/", "Lobsterlicious!"
      last_request.body.read.should == "Lobsterlicious!"
    end

    context "when CONTENT_TYPE is specified in the env" do
      it "does not overwrite the CONTENT_TYPE" do
        post "/", {}, { "CONTENT_TYPE" => "application/xml" }
        last_request.env["CONTENT_TYPE"].should == "application/xml"
      end
    end
  end

  describe "#put" do
    it_should_behave_like "any #verb methods"

    def verb
      "put"
    end

    it "accepts a body" do
      put "/", "Lobsterlicious!"
      last_request.body.read.should == "Lobsterlicious!"
    end
  end

  describe "#patch" do
    it_should_behave_like "any #verb methods"

    def verb
      "patch"
    end

    it "accepts a body" do
      patch "/", "Lobsterlicious!"
      last_request.body.read.should == "Lobsterlicious!"
    end
  end

  describe "#delete" do
    it_should_behave_like "any #verb methods"

    def verb
      "delete"
    end
  end

  describe "#options" do
    it_should_behave_like "any #verb methods"

    def verb
      "options"
    end
  end
end


text:
package com.github.tsavo.apiomatic.documentation;

public class JavaClassDescription {

	String name;
	String contents;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getContents() {
		return contents;
	}
	public void setContents(String contents) {
		this.contents = contents;
	}
}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class HostNoAvailableNetworksEvent extends HostDasEvent {
  public String ips;

  public String getIps() {
    return this.ips;
  }

  public void setIps(String ips) {
    this.ips=ips;
  }
}


text:
require 'spec_helper'

describe Mygegegems::Stat do
  before(:all) do
    Mygegegems::DATA_PATH = File.join(source_root, 'mygegegems.yaml')
  end

  describe ".latest" do
    it "returns latest data" do
      date, gems = described_class.latest
      expect(date.to_s).to eq '2014-07-11'
      expect(gems['emot']).to eq 762
    end
  end

  describe ".last" do
    it "returns last data(one before latest)" do
      date, gems = described_class.last
      expect(date.to_s).to eq '2014-07-10'
      expect(gems['emot']).to eq 760
    end
  end

  describe ".last_month" do
    it "returns last month's data" do
      date, gems = described_class.last_month
      expect(date.to_s).to eq '2014-06-30'
      expect(gems['emot']).to eq 600
    end
  end

  describe ".last_year" do
    it "returns last year's data" do
      date, gems = described_class.last_year
      expect(date).to be_nil
    end
  end

  describe ".diff" do
    it "raises an error with a wrong argument" do
      expect { described_class.diff(:newest) }.to raise_error(ArgumentError)
    end

    it "returns differences between last and latest" do
      (date1, date2), gems = described_class.diff(:last)
      expect(date1.to_s).to eq '2014-07-11'
      expect(date2.to_s).to eq '2014-07-10'
      expect(gems['emot']).to eq 2
      expect(gems['tildoc']).to eq 30
    end

    it "returns differences between last month and latest" do
      (date1, date2), gems = described_class.diff(:last_mon)
      expect(date1.to_s).to eq '2014-07-11'
      expect(date2.to_s).to eq '2014-06-30'
      expect(gems['emot']).to eq 162
      expect(gems['tildoc']).to be_nil
    end
  end

  describe ".total" do
    it "returns total stats" do
      total, diff_total, gems = described_class.total(:last)
      expect(total).to eq 7282
      expect(diff_total).to eq 164
      expect(gems).to eq 6
    end
  end
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CommonLanguageServerProtocol.Framework;
using Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;

/// <summary>
/// Request handler type exposed to typescript.
/// </summary>
internal abstract class AbstractVSTypeScriptRequestHandler<TRequestType, TResponseType> : ILspServiceRequestHandler<TRequestType, TResponseType>, IVSTypeScriptRequestHandler, ITextDocumentIdentifierHandler<TRequestType, TextDocumentIdentifier?>
{
    bool IMethodHandler.MutatesSolutionState => MutatesSolutionState;

    bool ISolutionRequiredHandler.RequiresLSPSolution => RequiresLSPSolution;

    public TextDocumentIdentifier? GetTextDocumentIdentifier(TRequestType request)
    {
        var typeScriptIdentifier = GetTypeSciptTextDocumentIdentifier(request);
        if (typeScriptIdentifier == null)
        {
            return null;
        }

        var textDocumentIdentifier = new VSTextDocumentIdentifier
        {
            Uri = typeScriptIdentifier.Value.Uri,
        };

        if (typeScriptIdentifier.Value.ProjectId != null)
        {
            textDocumentIdentifier.ProjectContext = new VSProjectContext
            {
                Id = typeScriptIdentifier.Value.ProjectId
            };
        }

        return textDocumentIdentifier;
    }

    public Task<TResponseType> HandleRequestAsync(TRequestType request, RequestContext context, CancellationToken cancellationToken)
    {
        return HandleRequestAsync(request, new TypeScriptRequestContext(context.Solution, context.Document), cancellationToken);
    }

    protected abstract bool MutatesSolutionState { get; }

    protected abstract bool RequiresLSPSolution { get; }

    protected abstract Task<TResponseType> HandleRequestAsync(TRequestType request, TypeScriptRequestContext context, CancellationToken cancellationToken);

    protected abstract TypeScriptTextDocumentIdentifier? GetTypeSciptTextDocumentIdentifier(TRequestType request);
}

internal record struct TypeScriptRequestContext(Solution? Solution, Document? Document);

/// <summary>
/// Custom type containing information in a <see cref="VSProjectContext"/> to avoid coupling LSP protocol versions.
/// </summary>
internal record struct TypeScriptTextDocumentIdentifier(Uri Uri, string? ProjectId);

internal interface IVSTypeScriptRequestHandler : ILspService
{
}


text:
import { extractRoute } from './ArrivalTimes';

describe(extractRoute, () => {
  test('should find route code', () => {
    expect(extractRoute('A1')).toEqual('A1');
    expect(extractRoute('C')).toEqual('C');
    expect(extractRoute('BTC1')).toEqual('BTC1');
  });

  test('should find route in string starting with route', () => {
    expect(extractRoute('D2(to UTown)')).toEqual('D2');
    expect(extractRoute('C(to FoS)')).toEqual('C');
  });

  test('should return null if no route code is found', () => {
    expect(extractRoute('Kent Ridge MRT')).toEqual(null);
    expect(extractRoute('')).toEqual(null);
  });
});


text:
package anuled.dynamicstore.backend;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import ch.systemsx.cisd.hdf5.IHDF5DoubleReader;
import ch.systemsx.cisd.hdf5.IHDF5Reader;
import ncsa.hdf.hdf5lib.exceptions.HDF5AttributeException;
import ncsa.hdf.hdf5lib.exceptions.HDF5SymbolTableException;

/**
 * Class representing a single DGGS cell, and its associated observations
 */
public class Cell {
	private String path, dggsIdent;
	private double[] centre;
	private List<List<Double>> bounds;
	private double latMin, latMax, longMin, longMax;
	private double degreesSpanned;
	HDF5Dataset owner;
	private Map<Product, Set<ZonedDateTime>> availableProducts;

	/**
	 * Thrown by the constructor when the given cell is not in the dataset
	 */
	protected class NotACell extends Exception {
		private static final long serialVersionUID = 1L;
	}

	protected Cell(String path, HDF5Dataset owner) throws NotACell {
		this.owner = owner;
		this.path = path;

		IHDF5Reader fp = owner.getReader();
		// centre is (lon, lat)
		IHDF5DoubleReader doubleReader = fp.float64();

		try {
			centre = doubleReader.getArrayAttr(path, "centre");
		} catch (HDF5AttributeException|HDF5SymbolTableException e) {
			throw new NotACell();
		}
		// bounds are list of (lon, lat), IIRC
		double[][] allBounds = doubleReader.getMatrixAttr(path, "bounds");
		// We need at least four coordinates to make a non-degenerate shape
		assert allBounds.length >= 4;
		bounds = new ArrayList<List<Double>>();
		latMin = longMin = Double.POSITIVE_INFINITY;
		latMax = longMax = Double.NEGATIVE_INFINITY;
		for (int row = 0; row < allBounds.length; row++) {
			List<Double> pair = new ArrayList<Double>(2);
			double[] thisRow = allBounds[row];
			assert thisRow.length == 2;
			double lon = thisRow[0];
			double lat = thisRow[1];
			pair.add(lon);
			pair.add(lat);
			bounds.add(pair);

			latMin = Math.min(latMin, lat);
			latMax = Math.max(latMax, lat);
			longMin = Math.min(longMin, lon);
			longMax = Math.max(longMax, lon);
		}

		// This will be used for resolution calculation
		degreesSpanned = (latMax - latMin + longMax - longMin) / 2;

		availableProducts = new HashMap<>();
		dggsIdent = path.replace("/", "");
		for (Product prod : owner.getProducts()) {
			String groupPath = path + "/" + prod.getName();
			if (fp.isGroup(groupPath)) {
				for (String member : fp.getGroupMembers(groupPath)) {
					if (member.startsWith("pixel@")) {
						// we expect format "pixel@<ISO 8601 date>"
						String[] timeStrings = member.split("@", 2);
						availableProducts
								.computeIfAbsent(prod,
										k -> new HashSet<ZonedDateTime>())
								.add(ZonedDateTime.parse(timeStrings[1]));
					}
				}
			}
		}
	}

	protected IHDF5Reader getReader() {
		return owner.getReader();
	}

	protected String getPath() {
		return path;
	}

	/**
	 * Approximate number of degrees (of latitude or longitude) spanned by the
	 * cell
	 */
	public double getDegreesSpanned() {
		return degreesSpanned;
	}

	/**
	 * Does this cell fall entirely within the rectangle defined by the given
	 * latitude and longitude bounds?
	 */
	public boolean inRect(Double lonMin, Double lonMax, Double latMin,
			Double latMax) {
		return (lonMin == null || this.longMin >= lonMin)
				&& (lonMax == null || this.longMax <= lonMax)
				&& (latMin == null || this.latMin >= latMin)
				&& (latMax == null || this.latMax <= latMax);
	}

	/** Return the parent dataset containing this cell */
	public HDF5Dataset getDataset() {
		return owner;
	}

	/**
	 * Get a PixelObservation for a single pixel covering this
	 * cell.
	 */
	public PixelObservation pixelObservation(Product product,
			ZonedDateTime timestamp, int band) {
		return new PixelObservation(this, product, timestamp, band);
	}

	/**
	 * Get a TileObservation for the data tile associated with this
	 * cell.
	 */
	public TileObservation tileObservation(Product product,
			ZonedDateTime timestamp, int band) {
		return new TileObservation(this, product, timestamp, band);
	}

	// used in method below
	private Stream<Integer> makeBandRange(Product prod, Integer band) {
		Supplier<IntStream> mkRange;
		if (band == null) {
			mkRange = () -> {
				return IntStream.range(0, prod.getNumBands());
			};
		} else if (band < 0 || band >= prod.getNumBands()) {
			// can only get valid bands
			return Stream.of();
		} else {
			mkRange = () -> {
				return IntStream.of(band);
			};
		}

		return mkRange.get().boxed();
	}

	/**
	 * Yield a stream of pixel and tile observations across all bands of the
	 * dataset
	 *
	 * @param band
	 *            sensor band for all observations, or null if all bands are
	 *            desired.
	 * @param expectedType
	 *            {@link TileObservation}, {@link PixelObservation} or null,
	 *            depending on which type of observation (if any particular
	 *            type) is desired.
	 */
	public Stream<Observation> observations(Integer band,
			Class<?> expectedType) {
		Stream<Boolean> isPixelStream;
		if (expectedType == null) {
			isPixelStream = Stream.of(true, false);
		} else if (expectedType.equals(PixelObservation.class)) {
			isPixelStream = Stream.of(true);
		} else if (expectedType.equals(TileObservation.class)) {
			isPixelStream = Stream.of(false);
		} else {
			throw new RuntimeException("Expected type must be "
					+ "PixelObservation or TileObservation");
		}

		// This is hideous, unfortunately. I'm trying to compute the following
		// cross product:
		//
		// (whether observation should be a pixel) x (products)
		// x (times for product) x (bands for product)
		//
		// The last two sets (times and bands for product) depend on the second
		// one. Further, the first and last sets depend on the argument. That's
		// why there are so many levels of flatMap here.
		return isPixelStream.flatMap(isPixel -> {
			return availableProducts.entrySet().stream().flatMap(entry -> {
				// we want to produce a stream which yields tuples of (product,
				// time, band, isPixel)
				Product prod = entry.getKey();

				return makeBandRange(prod, band).flatMap(bandNum -> {
					return entry.getValue().stream().map(time -> {
						if (isPixel) {
							return pixelObservation(prod, time, bandNum);
						} else {
							return tileObservation(prod, time, bandNum);
						}
					});
				});
			});
		});
	}

	/**
	 * Fetch the rHEALPix identifier (e.g. R7852) for this cell
	 */
	public String getDGGSIdent() {
		return dggsIdent;
	}

	/** Get the latitude of the centre of the cell */
	public double getLat() {
		return centre[1];
	}

	/** Get the longitude of the centre of the cell */
	public double getLon() {
		return centre[0];
	}

	public double getLatMin() {
		return latMin;
	}

	public double getLatMax() {
		return latMax;
	}

	public double getLongMin() {
		return longMin;
	}

	public double getLongMax() {
		return longMax;
	}

	@Override
	public String toString() {
		return "Cell " + getDGGSIdent();
	}

	public List<List<Double>> getBounds() {
		return bounds;
	}

	@Override
	public int hashCode() {
		return dggsIdent.hashCode();
	}

	@Override
	public boolean equals(Object other) {
		if (other instanceof Cell) {
			return ((Cell) other).getDGGSIdent().equals(getDGGSIdent());
		}
		return false;
	}
}


text:
(function ( Popcorn ) {

  var allWikiLangLinks, allWikiLangNames,
      cachedArticles = [];

  // shortcut
  function create( type ) {
    return document.createElement( type );
  }

  function getFragment( inputString ) {
    //grabbed from butter util methods
    var range = document.createRange(),
        // For particularly speedy loads, 'body' might not exist yet, so try to use 'head'
        container = document.body || document.head,
        fragment;

    range.selectNode( container );
    fragment = range.createContextualFragment( inputString );

    if( fragment.childNodes.length === 1 ){
      var child = fragment.firstChild;
      fragment.removeChild( child );
      return child;
    }

    return fragment;
  }

  function validateDimension( value, fallback ) {
    if ( typeof value === "number" ) {
      return value;
    }
    return fallback;
  }

  function sanitize( text ) {
    return text.replace( /\(/g, "(" )
               .replace( /\)/g, ")" )
               .replace( /-/g, "‐" )
               .replace( /\s/g, " " )
               .replace( /,/g, "," )
               .replace( /'/g, "&apos" );
  }

  function areValidElements( element ) {
    while( element && !element.textContent ){
      element = element.nextElementSibling;
      if ( !element || element.nodeName !== "P" ) {
        return false;
      }
    }
    return true;
  }

  function setupWiki( options, instance ) {
    // declare needed variables
    // get a guid to use for the global wikicallback function
    var _title,
        _titleDiv,
        _titleTextArea,
        _mainContentDiv,
        _contentArea,
        _toWikipedia,
        _inner,
        _href,
        _query,
        _guid = Popcorn.guid( "wikiCallback" ),
        _this = instance;

    if ( options._container && options._inner ) {
      options._container.removeChild( options._inner );
    }

    options._inner = _inner = create( "div" );
    _inner.classList.add( "wikipedia-inner-container" );

    _titleDiv = create( "div" );
    _titleDiv.classList.add( "wikipedia-title" );

    _titleTextArea = create( "div" );
    _titleTextArea.classList.add( "wikipedia-title-text" );
    _titleTextArea.classList.add( "wikipedia-ellipsis" );

    _titleDiv.appendChild( _titleTextArea );

    _mainContentDiv = create( "div" );
    _mainContentDiv.classList.add( "wikipedia-main-content" );

    _contentArea = create( "div" );
    _contentArea.classList.add( "wikipedia-content" );

    _mainContentDiv.appendChild( _contentArea );

    _toWikipedia = create( "a" );
    _toWikipedia.classList.add( "wikipedia-to-wiki" );

    _inner.appendChild( _titleDiv );
    _inner.appendChild( _mainContentDiv );
    _inner.appendChild( _toWikipedia );

    options._container.appendChild( _inner );
    options._target.appendChild( options._container );

    if ( !options.lang ) {
      options.lang = "en";
    }

    function buildArticle( data ) {
      var childIndex = 1,
          responseFragment = getFragment( "
" + data.parse.text + "
" ),
          element = responseFragment.querySelector( "div > p:nth-of-type(" + childIndex + ")" ),
          mainText = "";

      _titleTextArea.appendChild( getFragment( "" + sanitize( data.parse.title ) + "" ) );
      _toWikipedia.href = options._link;
      _toWikipedia.onclick = function() {
        _this.media.pause();
      };
      _toWikipedia.setAttribute( "target", "_blank" );

      while ( !areValidElements( element ) ) {
        element = responseFragment.querySelector( "div > p:nth-of-type(" + ( ++childIndex ) + ")" );
      }

      while ( element && element.nodeName === "P" ) {
        mainText += element.textContent + "
";
        element = element.nextElementSibling;
      }

      _contentArea.innerHTML = mainText;
    }

    window[ _guid ] = function ( data ) {

      cachedArticles[ _query ] = data;

      if ( data.error ) {
        _titleTextArea.innerHTML = "Article Not Found";
        _contentArea.innerHTML = data.error.info;
        return;
      }

      buildArticle( data );
    };

    if ( options.src ) {

      _query = options.src + options.lang;
      _href = "https://" + options.lang + ".wikipedia.org/w/";
      _title = options.src.slice( options.src.lastIndexOf( "/" ) + 1 );
      options._link = "https://" + options.lang + ".wikipedia.org/wiki/" + encodeURIComponent( _title );

      if ( !cachedArticles[ _query ] ) {
        // gets the mobile format, so that we don't load unwanted images when the respose is turned into a documentFragment
        Popcorn.getScript( _href + "api.php?action=parse&prop=text&redirects&page=" +
          encodeURIComponent( _title ) + "&noimages=1&mobileformat=html&format=json&callback=" + _guid );
      } else {
        buildArticle( cachedArticles[ _query ] );
      }
    }
  }

  var WikipediaDefinition = {

    _setup : function( options ) {
      var _outer;

      options._target = Popcorn.dom.find( options.target );

      if ( !options._target ) {
        return;
      }

      options._container = _outer = create( "div" );
      _outer.classList.add( "wikipedia-outer-container" );
      _outer.classList.add( options.transition );
      _outer.classList.add( "off" );

      _outer.style.width = validateDimension( options.width, "100" ) + "%";
      _outer.style.height = validateDimension( options.height, "100" ) + "%";
      _outer.style.top = validateDimension( options.top, "0" ) + "%";
      _outer.style.left = validateDimension( options.left, "0" ) + "%";
      _outer.style.zIndex = +options.zindex;

      setupWiki( options, this );

      options.toString = function() {
        return options.src || options._natives.manifest.options.src[ "default" ];
      };
    },

    start: function( event, options ){
      var container = options._container,
          redrawBug;

      if ( container ) {
        container.classList.add( "on" );
        container.classList.remove( "off" );

        // Safari Redraw hack - #3066
        container.style.display = "none";
        redrawBug = container.offsetHeight;
        container.style.display = "";
      }
    },

    end: function( event, options ){
      if ( options._container ) {
        options._container.classList.add( "off" );
        options._container.classList.remove( "on" );
      }
    },

    _teardown: function( options ){
      if ( options._target && options._container ) {
        options._target.removeChild( options._container );
      }
    },

    _update: function( trackEvent, options ) {

      if ( options.transition && options.transition !== trackEvent.transition ) {
        trackEvent._container.classList.remove( trackEvent.transition );
        trackEvent.transition = options.transition;
        trackEvent._container.classList.add( trackEvent.transition );
      }

      if ( options.src && options.src !== trackEvent.src ) {
        trackEvent.src = options.src;
        setupWiki( trackEvent, this );
      }

      if ( options.lang && options.lang !== trackEvent.lang ) {
        trackEvent.lang = options.lang;
        setupWiki( trackEvent, this );
      }

      if ( options.top && options.top !== trackEvent.top ) {
        trackEvent.top = options.top;
        trackEvent._container.style.top = trackEvent.top + "%";
      }

      if ( options.left && options.left !== trackEvent.left ) {
        trackEvent.left = options.left;
        trackEvent._container.style.left = trackEvent.left + "%";
      }

      if ( options.width && options.width !== trackEvent.width ) {
        trackEvent.width = options.width;
        trackEvent._container.style.width = trackEvent.width + "%";
      }

      if ( options.height && options.height !== trackEvent.height ) {
        trackEvent.height = options.height;
        trackEvent._container.style.height = trackEvent.height + "%";
      }

      if ( options.hasOwnProperty( "zindex" ) ) {
        trackEvent._container.style.zIndex = trackEvent.zindex = +options.zindex;
      }

    }
  };

  // Language codes: http://stats.wikimedia.org/EN/TablesDatabaseWikiLinks.htm

  allWikiLangLinks = ( "en,ja,es,de,ru,fr,it,pt,pl,zh,nl,tr,ar,sv,id,cs,fi,ko,th,fa,hu,he,no,vi,uk,da,ro" +
                         ",bg,hr,ca,el,sk,ms,sr,lt,sl,simple,eo,tl,et,hi,kk,sh,nn,ta,az,bs,af,eu,ka,lv,gl" +
                         ",zh_yue,tpi,mk,mr,la,ml,sq,be,cy,br,is,an,bn,war,oc,hy,arz,te,jv,ceb,sw" +
                         ",lb,als,ur,vo,fy,kn,gan,mg,ang,vec,gd,gu,ast,io,uz,qu,wuu,su,ku,yo,ga" +
                         ",tt,scn,bar,nds,se,ht,ne,ia,sco,lmo,mn,cv,ckb,diq,my,pnb,new,pms,zh-min-nan,yi,am" +
                         ",bpy,li,si,os,mt,nah,ps,fo,hsb,ilo,nap,wa,gv,ky,pam,sah,co,tg,ba,bcl" +
                         ",hif,km,sa,vls,or,mzn,ig,so,bo,kl,ksh,as,mi,szl,mwl,nrm,dsb,fiu-vro,dv,stq" +
                         ",tk,roa-rup,bug,mhr,kw,fur,sc,lad,csb,pa,rue,frr,gn,rm,ace,nv,bjn,arc,krc,ext,ug,nov" +
                         ",frp,crh,ab,lij,jbo,kv,ay,ce,ln,pdc,udm,eml,ie,mrj,xal,bh,hak,lo,wo" +
                         ",glk,myv,sn,chr,pag,rw,pcd,pap,zea,lbe,vep,koi,na,haw,cu,to,pi,av,zu,lez,kab,mdf," +
                         "tet,kaa,za,bm,rmy,kbd,iu,bi,kg,pih,ss,chy,ee,om,cr,cdo,srn,got,ha,bxr,ch,ty,sm,ltg," +
                         "pnt,ak,dz,st,sd,ik,ts,nso,y,tn,ki,ff,rn,xh,sg,ve,tw,ks,tum,fj,ti,lg" ).split( "," );

  allWikiLangNames = ( "English,Japanese,Spanish,German,Russian,French,Italian,Portuguese,Polish," +
                           "Chinese,Dutch,Turkish,Arabic,Swedish,Indonesian,Czech,Finnish,Korean,Thai," +
                           "Persian,Hungarian,Hebrew,Norwegian,Vietnamese,Ukrainian,Danish,Romanian," +
                           "Bulgarian,Croatian,Catalan,Greek,Slovak,Malay,Serbian,Lithuanian,Slovene," +
                           "Simple English,Esperanto,Tagalog,Estonian,Hindi,Kazakh,Serbo-Croatian,Nynorsk," +
                           "Tamil,Azeri,Bosnian,Afrikaans,Basque,Georgian,Latvian,Galician,Cantonese," +
                           "Tok Pisin,Macedonian,Marathi,Latin,Malayalam,Albanian,Welsh,Breton," +
                           "Icelandic,Aragonese,Bengali,Waray-Waray,Occitan,Armenian,Egyptian Arabic," +
                           "Belarusian,Telugu,Javanese,Cebuano,Swahili,Luxembourgish,Alemannic,Urdu," +
                           "Volapuk,Frisian,Kannada,Gan,Malagasy,Anglo Saxon,Venetian," +
                           "Scots Gaelic,Gujarati,Asturian,Ido,Uzbek,Quechua,Wu,Sundanese,Kurdish,Yoruba," +
                           "Irish,Tatar,Sicilian,Bavarian,Low Saxon,Northern Sami,Haitian,Nepali," +
                           "Interlingua,Scots,Lombard,Mongolian,Chuvash,Sorani,Zazaki,Burmese,Western Panjabi" +
                           ",Nepal Bhasa,Piedmontese,Min Nan,Yiddish,Amharic,Bishnupriya Manipuri,Limburgish," +
                           "Sinhala,Ossetic,Maltese,Nahuatl,Pashto,Faroese,Upper Sorbian,Ilokano,Neapolitan," +
                           "Walloon,Manx,Kirghiz,Kapampangan,Sakha,Corsican,Tajik,Bashkir," +
                           "Central Bicolano,Fiji Hindi,Khmer,Sanskrit,West Flemish,Oriya,Mazandarani," +
                           "Igbo,Somali,Tibetan,Greenlandic,Ripuarian,Assamese,Maori,Silesian," +
                           "Mirandese,Norman,Lower Sorbian,Voro,Divehi,Saterland Frisian,Turkmen,Aromanian," +
                           "Buginese,Eastern Mari,Cornish,Friulian,Sardinian,Ladino,Cassubian,Punjabi,Rusyn," +
                           "North Frisian,Guarani,Romansh,Acehnese,Navajo,Banjar,Aramaic,Karachay-Balkar," +
                           "Extremaduran,Uyghur,Novial,Arpitan,Crimean Tatar,Abkhazian,Ligurian," +
                           "Lojban,Komi,Aymara,Chechen,Lingala,Pennsylvania German,Udmurt,Emilian-Romagnol," +
                           "Interlingue,Western Mari,Kalmyk,Bihari,Hakka,Laotian,Wolof,Gilaki," +
                           "Erzya,Shona,Cherokee,Pangasinan,Kinyarwanda,Picard,Papiamentu,Zealandic,Lak," +
                           "Vepsian,Komi Permyak,Nauruan,Hawai'ian,Old Church Slavonic,Tongan,Pali,Avar," +
                           "Zulu,Lezgian,Kabyle,Moksha,Tetum,Karakalpak,Zhuang,Bambara,Romani,Karbadian," +
                           "Inuktitut,Bislama,Kongo,Norfolk,Siswati,Cheyenne,Ewe,Oromo,Cree,Min Dong," +
                           "Sranan,Gothic,Hausa,Buryat,Chamorro,Tahitian,Samoan,Latgalian,Pontic,Akan," +
                           "Dzongkha,Sesotho,Sindhi,Inupiak,Tsonga,Northern Sotho,Chichewa,Setswana,Kikuyu," +
                           "Fulfulde,Kirundi,Xhosa,Sangro,Venda,Twi,Kashmiri,Tumbuka,Fijian,Tigrinya,Ganda" ).split( "," );

  Popcorn.plugin( "wikipedia", WikipediaDefinition, {
    about:{
      name: "Popcorn Wikipedia Plugin",
      version: "0.1",
      author: "@ChrisDeCairos",
      website: "https://chrisdecairos.ca/"
    },
    options:{
      start: {
        elem: "input",
        type: "text",
        label: "Start",
        "units": "seconds"
      },
      end: {
        elem: "input",
        type: "text",
        label: "End",
        "units": "seconds"
      },
      lang: {
        elem: "select",
        options: allWikiLangNames,
        values: allWikiLangLinks,
        label: "Language",
        "default": "en"
      },
      src: {
        elem: "input",
        type: "text",
        label: "Article Link/Title",
        "default": "Popcorn"
      },
      width: {
        elem: "input",
        type: "number",
        label: "Width",
        "default": 30,
        "units": "%",
        "hidden": true
      },
      height: {
        elem: "input",
        type: "number",
        label: "Height",
        "default": 30,
        "units": "%",
        "hidden": true
      },
      top: {
        elem: "input",
        type: "number",
        label: "Top",
        "default": 25,
        "units": "%",
        "hidden": true
      },
      left: {
        elem: "input",
        type: "number",
        label: "Left",
        "default": 30,
        "units": "%",
        "hidden": true
      },
      target: {
        hidden: true
      },
      transition: {
        elem: "select",
        options: [ "None", "Pop", "Fade", "Slide Up", "Slide Down" ],
        values: [ "popcorn-none", "popcorn-pop", "popcorn-fade", "popcorn-slide-up", "popcorn-slide-down" ],
        label: "Transition",
        "default": "popcorn-fade"
      },
      zindex: {
        hidden: true
      }
    }
  });

}( Popcorn ));