text:
/**
 * \file
 *
 * Interface for Quad Serial Peripheral Interface (QSPI) controller.
 *
 */

#ifndef _QSPI_H_
#define _QSPI_H_

/*----------------------------------------------------------------------------
 *        Types
 *----------------------------------------------------------------------------*/

/** QSPI Command structure */
struct _qspi_cmd {
	/** Data Transfer Type (QSPI_IFR_TFRTYP_TRSFR_xxx) */
	uint32_t ifr_type;

	/** Width of Instruction Code, Address, Option Code and Data
	 * (QSPI_IFR_WIDTH_xxx) */
	uint32_t ifr_width;

	/** Flags to select which information is included in the command */
	struct {
		/** 0: don't send instruction code, 1: send instuction code */
		uint32_t instruction:1;
		/** 0: don't send address, 3: send 3-byte address, 4: send
		 * 4-byte address */
		uint32_t address:3;
		/** 0: don't send mode bits, 1: send mode bits */
		uint32_t mode:1;
		/** 0: don't send dummy bits, 1: send dummy bits */
		uint32_t dummy:1;
		/** 0: don't send/recieve data, 1: send/recieve data */
		uint32_t data:1;
		/** reserved, not used */
		uint32_t reserved:25;
	} enable;

	/** Instruction code */
	uint8_t instruction;

	/** Mode bits */
	uint8_t mode;

	/** Number of mode cycles */
	uint8_t num_mode_cycles;

	/** Number of dummy cycles */
	uint8_t num_dummy_cycles;

	/** QSPI address */
	uint32_t address;

	/** Address of the TX buffer */
	const void *tx_buffer;

	/** Address of the RX buffer */
	void *rx_buffer;

	/** Size of the RX/TX buffer */
	uint32_t buffer_len;

	/** Timeout for the command execution, in timer ticks */
	uint32_t timeout;
};

/*----------------------------------------------------------------------------
 *        Exported functions
 *----------------------------------------------------------------------------*/

#ifdef __cplusplus
 extern "C" {
#endif

/**
 * \brief Reset and initialize a QSPI instance.
 *
 * \param qspi the QSPI instance
 */
void qspi_initialize(Qspi *qspi);

/**
 * \brief Configure the baudrate for a QSPI instance.
 *
 * \param qspi the QSPI instance
 * \param baudrate the requested baudrate
 * \return the actual baudrate configured (can be lower than requested)
 */
uint32_t qspi_set_baudrate(Qspi *qspi, uint32_t baudrate);

/**
 * \brief Perform a QSPI command.
 *
 * Note that if enable.data is set in the command, data will be sent/recieved:
 * - if tx_buffer is not NULL, data will be sent
 * - if rx_buffer is not NULL, data will be recieved
 * - if both tx_buffer and rx_buffer are NULL, QSPI will be configured in
 * "Continuous Read" mode and random read access can be done at the address
 * returned by get_qspi_mem_from_addr
 *
 * \param qspi the QSPI instance
 * \param cmd the QSPI command to perform
 * \return true if the command was succesfully issued, false otherwise
 */
bool qspi_perform_command(Qspi *qspi, const struct _qspi_cmd *cmd);

#ifdef __cplusplus
}
#endif

#endif /* _QSPI_H_ */


text:
package org.dcm4chee.usr.war;

import java.security.Principal;
import java.security.acl.Group;
import java.util.Enumeration;

import javax.security.auth.Subject;

import org.apache.wicket.Page;
import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.markup.html.WebPage;
import org.dcm4chee.usr.war.common.AccessDeniedPage;
import org.dcm4chee.usr.war.common.InternalErrorPage;
import org.dcm4chee.usr.war.common.PageExpiredErrorPage;
import org.dcm4chee.usr.war.pages.LoginPage;
import org.dcm4chee.usr.war.pages.UserManagementMainPage;
import org.dcm4chee.usr.war.session.JaasWicketSession;

public class WicketApplication extends AuthenticatedWebApplication {

    private String securityDomainName;
    private String rolesGroupName;
    private String userRoleName;
    private String adminRoleName;

    private String hashEncoding;
    private String hashCharset;
    private String hashAlgorithm;

    public static WicketApplication get() {
        return (WicketApplication) AuthenticatedWebApplication.get();
    }

    public String getSecurityDomainName() {
        return securityDomainName;
    }

    public String getRolesGroupName() {
        return rolesGroupName;
    }

    public String getUserRoleName() {
        return userRoleName;
    }

    public String getAdminRoleName() {
        return adminRoleName;
    }

    public void setHashEncoding(String hashEncoding) {
        this.hashEncoding = hashEncoding;
    }

    public String getHashEncoding() {
        return hashEncoding;
    }

    public void setHashCharset(String hashCharset) {
        this.hashCharset = hashCharset;
    }

    public String getHashCharset() {
        return hashCharset;
    }

    public void setHashAlgorithm(String hashAlgorithm) {
        this.hashAlgorithm = hashAlgorithm;
    }

    public String getHashAlgorithm() {
        return hashAlgorithm;
    }

    @Override
    protected void init() {
        super.init();

        getApplicationSettings().setAccessDeniedPage(AccessDeniedPage.class);
        getApplicationSettings().setInternalErrorPage(InternalErrorPage.class);
        getApplicationSettings().setPageExpiredErrorPage(PageExpiredErrorPage.class);

        mountBookmarkablePage("/login", LoginPage.class);

        this.securityDomainName = getInitParameter("securityDomainName");
        this.rolesGroupName = getInitParameter("rolesGroupName");
        this.userRoleName = getInitParameter("userRoleName");
        this.adminRoleName = getInitParameter("adminRoleName");
    }

    public Roles getRoles(Subject subject) {
        Roles roles = new Roles();
        for (Principal p : subject.getPrincipals()) {
            if ((p instanceof Group) && (rolesGroupName.equals(p.getName()))) {
                Group g = (Group) p;
                Enumeration<? extends Principal> members = g.members();
                while (members.hasMoreElements()) {
                    Principal member = members.nextElement();
                    String name = member.getName();
                    if (userRoleName.equals(name))
                        roles.add(Roles.USER);
                    if (adminRoleName.equals(name))
                        roles.add(Roles.ADMIN);
                }
            }
        }
        return roles;
    }

    public boolean isUserOrAdminRole(String role) {
        return userRoleName.equals(role) || adminRoleName.equals(role);
    }

    @Override
    public Class<? extends Page> getHomePage() {
        return UserManagementMainPage.class;
    }

    @Override
    protected Class<? extends WebPage> getSignInPageClass() {
        return LoginPage.class;
    }

    @Override
    protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
        return JaasWicketSession.class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.cuberite.android.helpers;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.File;

import static android.content.Context.MODE_PRIVATE;

public class StateHelper {
    public enum State {
        NEED_DOWNLOAD_SERVER,
        NEED_DOWNLOAD_BINARY,
        NEED_DOWNLOAD_BOTH,
        PICK_FILE_BINARY,
        PICK_FILE_SERVER,
        RUNNING,
        READY
    }

    public static boolean isCuberiteInstalled(Context context) {
        State state = getState(context);
        return (
                state != State.NEED_DOWNLOAD_BINARY
                && state != State.NEED_DOWNLOAD_SERVER
                && state != State.NEED_DOWNLOAD_BOTH
        );
    }

    public static State getState(Context context) {
        // Logging tag
        String LOG = "Cuberite/State";

        final SharedPreferences preferences = context.getSharedPreferences(context.getPackageName(), MODE_PRIVATE);
        boolean hasBinary = false;
        boolean hasServer = false;

        if (new File(context.getFilesDir().getAbsolutePath() + "/" + CuberiteHelper.getExecutableName()).exists()) {
            hasBinary = true;
        }

        if (new File(preferences.getString("cuberiteLocation", "")).exists()) {
            hasServer = true;
        }

        // Update state
        State state = State.READY;

        if (CuberiteHelper.isCuberiteRunning(context)) {
            state = State.RUNNING;
        } else if (!hasBinary && !hasServer) {
            state = State.NEED_DOWNLOAD_BOTH;
        } else if (!hasBinary) {
            state = State.NEED_DOWNLOAD_BINARY;
        } else if (!hasServer) {
            state = State.NEED_DOWNLOAD_SERVER;
        }

        Log.d(LOG, "Getting State: " + state);
        return state;
    }
}


text:
package com.haulmont.cuba.core.entity;

/**
 * DEPRECATED. Use {@link Entity}.
 */
@Deprecated
public interface BaseEntity<T> extends Entity<T> {
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="PAMI Plataforma de Administracion de Medios Inteligentes">
    <meta name="author" content="Vi Electronic Entertainment">
    <link rel="icon" href="public/favicon.ico">
    <title>PAMI Project</title>
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
    <link href="public/css/bootstrap.min.css" rel="stylesheet" />
    <link href="public/css/now-ui-kit.css?v=1.1.0" rel="stylesheet" />
    <link href="public/css/demo.css" rel="stylesheet" />

                    PAMI

                <button class="navbar-toggler navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        Que Queremos Hacer?

                        Quienes Somos?

                        Trabaja Con Nosotros

Twitter

Facebook

GitHub

Plataforma Administracion de Medios Inteligentes

-PAMI-

Que Queremos Hacer?

Usar elementos de juegos para optimizar el trabajo y la productividad en empresas, organizaciones y academias. Mediante una plataforma web que permita el desarrollo de redes y grupos de trabajo, que aprenda de sus usuarios implementando inteligencia artificial y brinde datos valiosos para emprendedores y empresarios.

"Somos testigos del gran poder que tienen los juegos en la vida, estos se enseñan se motivan y se evaluan a si mismos."

                                    -Sergio Veloza

Elementos de los juegos incluidos en PAMI

De Tareas a Misiones!

Puede parecer un cambio de apariencia pero realmente es un cambio de fondo, el proponer las cosas como un reto a superar, estimula la competitivad.

Puntos de Experiencia

En la medida que desarrollas actividades, interactuas con la plataforma y resuelves problemas, tendras puntos de experiencia que aumentaran tu nivel y brindaran un prestigio.

Hoja de Atributos

Inspirado en los juegos de Rol tendras una hoja de habilidades que iran progresando en la medida que se desarrollen las diferentes actividades que propone la plataforma y sus proponentes.

Y mucho mas!

Tenemos muchas mas caracteristicas pensadas para PAMI que iremos implementando en la medida que la plataforma evolucione, sobre todo en elementos de cooperacion y productividad.

Quienes Somos?

Sergio Veloza

CEO

Fundador y visionario. Soy una persona emprendedora y creativa, he trabajado en el desarrollo de experiencias con juegos desde toda mi vida, mis pasatiempos son dominar el mundo y aprender :)

Andres Gonzalez

COO

Cofundador e inversionista. Soy una persona emprendedora e innovadora que le gusta viajar y conocer, me gustan los videojuegos en especial a los shooter, aunque me gustan un poco mas los frijoles.

Maira Benedetti

CFO

Soy la persona encargada de aterrizar a estos dos locos, me considero una persona inteligente y creativa que le gustan los numeros, "si... Si es posible". No muestro mi cara porque soy el genio malvado detras de esto... Ahh y me gustan los gatos.

Deseas trabajar con nosotros?

Un gran trabajo requiere grandes personas, estas preparado?

                    <form class="col-lg-6 text-center col-md-8 ml-auto mr-auto" action="mailto:blinteruniverse@gmail.com" method="post" enctype="text/plain">

                            <input type="text" class="form-control" name="name" placeholder="Nombre...">

                            <input type="text" class="form-control" placeholder="Email...">

 En que area Deseas trabajar:

                        <select name="area: ">
                            <option value="Desarrollo"> Desarrollo Web </option>
                            <option value="Marketing"> Marketing </option>
                            <option value="Negocixos"> Negocios </option>
                            <option value="Inteligencia Artifical"> Inteligencia Artifical </option>
                            <option value="Diseño"> Diseño </option>
                            <option value="UX"> Experiencia de Usuario </option>
                            <option value="Otro"> Otro </option>
                        </select>

                            <textarea class="form-control" name="mi razon" rows="4" cols="80" placeholder="Porque quieres trabajar con nosotros?"></textarea>

                            <input class="btn btn-primary btn-round btn-block btn-lg" type="submit" value="Enviar formulario">

                    </form>

                                Blinter Universe

                                Acceso a Alpha

                    ©
                    , Diseñado por
                    BlinterUniverse. Todos los derechos son reservados.


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Error;

use PhpCsFixer\Error\Error;
use PhpCsFixer\Error\ErrorsManager;

/**
 * @internal
 */
final class ErrorsManagerTest extends \PHPUnit_Framework_TestCase
{
    public function testDefaults()
    {
        $errorsManager = new ErrorsManager();

        $this->assertTrue($errorsManager->isEmpty());
        $this->assertEmpty($errorsManager->getInvalidErrors());
        $this->assertEmpty($errorsManager->getExceptionErrors());
        $this->assertEmpty($errorsManager->getLintErrors());
    }

    public function testThatCanReportAndRetrieveInvalidErrors()
    {
        $error = new Error(
            Error::TYPE_INVALID,
            'foo.php'
        );

        $errorsManager = new ErrorsManager();

        $errorsManager->report($error);

        $this->assertFalse($errorsManager->isEmpty());

        $errors = $errorsManager->getInvalidErrors();

        $this->assertInternalType('array', $errors);
        $this->assertCount(1, $errors);
        $this->assertSame($error, array_shift($errors));

        $this->assertCount(0, $errorsManager->getExceptionErrors());
        $this->assertCount(0, $errorsManager->getLintErrors());
    }

    public function testThatCanReportAndRetrieveExceptionErrors()
    {
        $error = new Error(
            Error::TYPE_EXCEPTION,
            'foo.php'
        );

        $errorsManager = new ErrorsManager();

        $errorsManager->report($error);

        $this->assertFalse($errorsManager->isEmpty());

        $errors = $errorsManager->getExceptionErrors();

        $this->assertInternalType('array', $errors);
        $this->assertCount(1, $errors);
        $this->assertSame($error, array_shift($errors));

        $this->assertCount(0, $errorsManager->getInvalidErrors());
        $this->assertCount(0, $errorsManager->getLintErrors());
    }

    public function testThatCanReportAndRetrieveInvalidFileErrors()
    {
        $error = new Error(
            Error::TYPE_LINT,
            'foo.php'
        );

        $errorsManager = new ErrorsManager();

        $errorsManager->report($error);

        $this->assertFalse($errorsManager->isEmpty());

        $errors = $errorsManager->getLintErrors();

        $this->assertInternalType('array', $errors);
        $this->assertCount(1, $errors);
        $this->assertSame($error, array_shift($errors));

        $this->assertCount(0, $errorsManager->getInvalidErrors());
        $this->assertCount(0, $errorsManager->getExceptionErrors());
    }
}


text:
<?php

namespace Joomla\Registry\Format;

use Joomla\Registry\AbstractRegistryFormat;
use Joomla\String\String;

/**
 * JSON format handler for Registry.
 *
 * @since  1.0
 */
class Json extends AbstractRegistryFormat
{
	/**
	 * Converts an object into a JSON formatted string.
	 *
	 * @param   object  $object   Data source object.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  string  JSON formatted string.
	 *
	 * @since   1.0
	 */
	public function objectToString($object, $options = array())
	{
		return String::unicode_to_utf8(json_encode($object));
	}

	/**
	 * Parse a JSON formatted string and convert it into an object.
	 *
	 * If the string is not in JSON format, this method will attempt to parse it as INI format.
	 *
	 * @param   string  $data     JSON formatted string to convert.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  object   Data object.
	 *
	 * @since   1.0
	 */
	public function stringToObject($data, array $options = array('processSections' => false))
	{
		$data = trim($data);

		if ((substr($data, 0, 1) != '{') && (substr($data, -1, 1) != '}'))
		{
			$ini = AbstractRegistryFormat::getInstance('Ini');
			$obj = $ini->stringToObject($data, $options);
		}
		else
		{
			$obj = json_decode($data);
		}

		return $obj;
	}
}


text:
var Language = require ( "../../lib/language/language" )
  , Parser   = require ( "../../lib/parser/parser"     )
  , Lexer    = require ( "../../lib/lexer/lexer"       )
  , should   = require ( "should"                      )
  ;

describe ("Language", function () {
  var language, helper;
  beforeEach(function () {
    language = Language.clone();
    helper = function () { return "helper"; };
  });

  describe ("init", function () {
    it ("assigns a parser instance", function () {
      language.parser.parent.should.eql(Parser);
    });

    it ("assigns a lexer instance", function () {
      language.lexer.parent.should.eql(Lexer);
    });
  });

  describe('rule', function () {
    it("delegates to the lexer", function () {
      language.rule("operator", /[a-zA-Z]+/, helper, "(operator)");
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['operator', "/^([a-zA-Z]+)/", helper]);
    });
  });

  describe('name', function () {
    it("delegates to the lexer", function () {
      language.name(/[a-zA-Z]+/, helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(name)', "/^([a-zA-Z]+)/", helper]);
    });
  });

  describe('number', function () {
    it("delegates to the lexer", function () {
      language.number(/[0-9]+/, helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(number)', "/^([0-9]+)/", helper]);
    });
  });

  describe('string', function () {
    it("delegates to the lexer", function () {
      language.string(/\".+\"/, helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(string)', '/^(\\".+\\")/', helper]);
    });
  });

  describe('regex', function () {
    it("delegates to the lexer", function () {
      language.regex(/\/.+\//, helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(regex)', "/^(\\/.+\\/)/", helper]);
    });
  });

  describe('operator', function () {
    it("delegates to the lexer", function () {
      language.operator(/\+/, helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(operator)', '/^(\\+)/', helper]);
    });
  });

  describe('eol', function () {
    it("delegates to the lexer", function () {
      language.eol(/\;/, helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(eol)', '/^(\\;)/', helper]);
    });
  });

  describe('skip', function () {
    it("delegates to the lexer", function () {
      language.skip(/\s+/);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString(), r.action] })[0].
        should.eql(['(skip)', '/^(\\s+)/', language.lexer.helpers.skip]);
    });
  });

  describe ("prefix", function () {
    it ("delegates to the lexer", function () {
      language.prefix("+");
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] })[0].
        should.eql(['(operator)', '+']);
    });

    it ("accepts variadic number of ids", function () {
      language.prefix("+", "-")
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([['(operator)', '+'], ['(operator)', '-']]);
      language.parser.symbol_table.symbols["+"].id.should.eql("+");
      language.parser.symbol_table.symbols["-"].id.should.eql("-");
    })

    it ("delegates to the parser", function () {
      language.prefix("+", helper);

      language.parser.symbol_table.symbols["+"].id.should.eql("+");
      language.parser.symbol_table.symbols["+"].nud({}).should.eql("helper");
    });
  });

  describe ("infix", function () {
    it ("delegates to the lexer", function () {
      language.infix("+", 10);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] })[0].
        should.eql(['(operator)', '+']);
    });

    it ("accepts variadic number of ids", function () {
      language.infix("+", "-", 10)
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([['(operator)', '+'], ['(operator)', '-']]);
      language.parser.symbol_table.symbols["+"].id.should.eql("+");
      language.parser.symbol_table.symbols["-"].id.should.eql("-");
    });

    it ("delegates to the parser", function () {
      language.infix("+", 10, helper);

      language.parser.symbol_table.symbols["+"].id.should.eql("+");
      language.parser.symbol_table.symbols["+"].lbp.should.eql(10);
      language.parser.symbol_table.symbols["+"].led({}).should.eql("helper");
    });
  });

  describe ("infixr", function () {
    it ("delegates to the lexer", function () {
      language.infixr("=", 10);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] })[0].
        should.eql(['(operator)', '=']);
    });

    it ("accepts variadic number of ids", function () {
      language.infixr("+", "-", 10)
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([['(operator)', '+'], ['(operator)', '-']]);
      language.parser.symbol_table.symbols["+"].id.should.eql("+");
      language.parser.symbol_table.symbols["-"].id.should.eql("-");
    });

    it ("delegates to the parser", function () {
      language.infixr("=", 10, helper);

      language.parser.symbol_table.symbols["="].id.should.eql("=");
      language.parser.symbol_table.symbols["="].lbp.should.eql(10);
      language.parser.symbol_table.symbols["="].led({}).should.eql("helper");
    });
  });

  describe ("stmt", function () {
    it ("delegates to the lexer", function () {
      language.stmt("if", helper);
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] })[0].
        should.eql(['(operator)', 'if']);
    });

    it ("accepts variadic number of ids", function () {
      language.stmt("print", "return")
      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([['(operator)', 'print'], ['(operator)', 'return']]);
      language.parser.symbol_table.symbols["print"].id.should.eql("print");
      language.parser.symbol_table.symbols["return"].id.should.eql("return");
    })

    it ("delegates to the parser", function () {
      language.stmt("if", helper);

      language.parser.symbol_table.symbols["if"].id.should.eql("if");
      language.parser.symbol_table.symbols["if"].lbp.should.eql(0);
      language.parser.symbol_table.symbols["if"].std({}).should.eql("helper");
    });
  });

  describe ("borrow", function () {
    it ("copies specific parser rules from another language", function () {
      var otherLang = Language.clone(function () { this.infix("+", 10); this.infix("-", 10); this.infix("*", 10) });
      language.borrow(otherLang, "+", "-")

      should.exist(language.parser.symbol_table.symbols["+"])
      should.exist(language.parser.symbol_table.symbols["-"])
      should.not.exist(language.parser.symbol_table.symbols["*"])
    });

    it ("copies specific lexer rules from another language", function () {
      var otherLang = Language.clone(function () { this.infix("+", 10); this.infix("-", 10); this.infix("*", 10) });
      language.borrow(otherLang, "+", "-")

      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([["(operator)", "+"], ["(operator)", "-"]]);
    });
  });

  describe ("extend", function () {
    it ("copies all parser rules from another language", function () {
      var otherLang = Language.clone(function () { this.infix("+", 10); this.infix("-", 10); this.infix("*", 10) });
      language.extend(otherLang);

      should.exist(language.parser.symbol_table.symbols["+"]);
      should.exist(language.parser.symbol_table.symbols["-"]);
      should.exist(language.parser.symbol_table.symbols["*"]);
    });

    it ("copies all parser rules from multiple languages", function () {
      var otherLang1 = Language.clone(function () { this.infix("+", 10); this.infix("-", 10); });
      var otherLang2 = Language.clone(function () { this.infix("*", 10)                       });
      language.extend(otherLang1);
      language.extend(otherLang2);

      should.exist(language.parser.symbol_table.symbols["+"]);
      should.exist(language.parser.symbol_table.symbols["-"]);
      should.exist(language.parser.symbol_table.symbols["*"]);
    });

    it ("copies all lexer rules from another language", function () {
      var otherLang = Language.clone(function () { this.infix("+", 10); this.infix("-", 10); this.infix("*", 10) });
      language.extend(otherLang);

      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([["(operator)", "+"], ["(operator)", "-"], ["(operator)", "*"]]);
    });

    it ("copies all lexer rules from multiple languages", function () {
      var otherLang1 = Language.clone(function () { this.infix("+", 10); this.infix("-", 10); });
      var otherLang2 = Language.clone(function () { this.infix("*", 10);                      });
      language.extend(otherLang1);
      language.extend(otherLang2);

      language.lexer.rules.map(function (r) { return [r.name, r.regex.toString()] }).
        should.eql([["(operator)", "+"], ["(operator)", "-"], ["(operator)", "*"]]);
    });
  });

  describe("advance", function () {
    beforeEach(function () {
      language.parser.token  = {match : function () { return true; }}
      language.parser.tokens = {next  : function () { return { extend: function () {}, value: "+"};  }}
    })
    describe("with id", function () {
      it ("should add a lexer rule", function () {
        language.parser.advance("+")
        language.lexer.rules[0].name.should.eql("(operator)");
        language.lexer.rules[0].regex.should.eql("+")
      });
    });

    describe("without id", function () {
      it ("should not add a lexer rule", function () {
        language.parser.advance()
        language.lexer.rules.should.eql([])
      });
    });
  });

  describe("parseUntil", function () {

    it ("should add a lexer rule for the value", function () {
      var lang = Language.clone()
      lang.name(/[a-z]+/)
      lang.infix("(", 80, function (node, left) {
        node.first  = left;
        node.second = this.parseUntil(")");
        return node;
      });

      lang.parse("foo(abc)");
      var rule = lang.lexer.rules[2];
      rule.name.should.eql("(operator)");
      rule.regex.should.eql(")");
    });

    it ("should add lexer rule for the step argument", function () {
      var lang = Language.clone(function () {
        this.name(/[a-zA-Z]+/)
        this.infix("(", 80, function (node, left) {
          node.first  = left;
          node.second = this.parseUntil(")", {step: ","});
          return node;
        });
      })

      lang.parse("foo(abc,efg)");
      var rule = lang.lexer.rules[3];
      rule.name.should.eql("(operator)");
      rule.regex.should.eql(",");
    })
  })

  describe ("parse", function () {
    it ("accepts a program string as input and produces an ast as output", function () {
      language.lexer.number(/[0-9]+/);
      language.lexer.operator("+");
      language.lexer.skip(/\s+/);
      language.parser.infix("+", 10);

      language.parse("1 + 1").toSexp().should.eql("(+ 1 1)");
    });
  });
})


text:
from unittest.mock import Mock

import pytest

from streamlink import Streamlink
from streamlink.stream.dash import DASHStream
from streamlink.stream.file import FileStream
from streamlink.stream.hls import HLSStream
from streamlink.stream.http import HTTPStream
from streamlink.stream.stream import Stream

@pytest.fixture(scope="module")
def session():
    return Streamlink()

@pytest.fixture(scope="module")
def common_args():
    return dict(
        params={"queryparamkey": "queryparamval"},
        unknown="invalid",
    )

def test_base_stream(session):
    stream = Stream(session)
    with pytest.raises(TypeError) as cm:
        stream.to_url()
    assert str(cm.value) == "<Stream [stream]> cannot be translated to a URL"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<Stream [stream]> cannot be translated to a manifest URL"

def test_file_stream_handle(session):
    stream = FileStream(session, None, Mock())
    with pytest.raises(TypeError) as cm:
        stream.to_url()
    assert str(cm.value) == "<FileStream [file]> cannot be translated to a URL"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<FileStream [file]> cannot be translated to a manifest URL"

def test_file_stream_path(session):
    stream = FileStream(session, "/path/to/file")
    assert stream.to_url() == "/path/to/file"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<FileStream [file]> cannot be translated to a manifest URL"

def test_http_stream(session, common_args):
    stream = HTTPStream(session, "http://host/stream?foo=bar", **common_args)
    assert stream.to_url() == "http://host/stream?foo=bar&queryparamkey=queryparamval"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<HTTPStream [http]> cannot be translated to a manifest URL"

def test_hls_stream(session, common_args):
    stream = HLSStream(session, "http://host/stream.m3u8?foo=bar", **common_args)
    assert stream.to_url() == "http://host/stream.m3u8?foo=bar&queryparamkey=queryparamval"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<HLSStream [hls]> cannot be translated to a manifest URL"

def test_hls_stream_master(session, common_args):
    stream = HLSStream(session, "http://host/stream.m3u8?foo=bar", "http://host/master.m3u8?foo=bar", **common_args)
    assert stream.to_url() == "http://host/stream.m3u8?foo=bar&queryparamkey=queryparamval"
    assert stream.to_manifest_url() == "http://host/master.m3u8?foo=bar&queryparamkey=queryparamval"

def test_dash_stream(session):
    mpd = Mock(url=None)
    stream = DASHStream(session, mpd)
    with pytest.raises(TypeError) as cm:
        stream.to_url()
    assert str(cm.value) == "<DASHStream [dash]> cannot be translated to a URL"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<DASHStream [dash]> cannot be translated to a manifest URL"

def test_dash_stream_url(session, common_args):
    # DASHStream requires an MPD instance as input:
    # The URL of the MPD instance was already prepared by DASHStream.parse_manifest, so copy this behavior here.
    # This test verifies that session params are added to the URL, without duplicates.
    args = common_args.copy()
    args.update(url="http://host/stream.mpd?foo=bar")
    url = session.http.prepare_new_request(**args).url
    mpd = Mock(url=url)
    stream = DASHStream(session, mpd, **common_args)
    assert stream.to_url() == "http://host/stream.mpd?foo=bar&queryparamkey=queryparamval"
    with pytest.raises(TypeError) as cm:
        stream.to_manifest_url()
    assert str(cm.value) == "<DASHStream [dash]> cannot be translated to a manifest URL"


text:
//
//  Copyright (c) 2014 VK.com
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//  the Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

package com.vk.sdk.api.model;

import android.os.Parcel;

import org.json.JSONObject;

/**
 * This class represents owner of some VK object.
 */
@SuppressWarnings("unused")
public class VKApiOwner extends VKApiModel implements Identifiable, android.os.Parcelable {

    /**
     * User or group ID.
     * If ID is positive, owner is user.
     * If ID is negative, owner is community.
     */
    public int id;

    /**
     * Creates an owner with empty ID.
     */
    public VKApiOwner() {

    }

    /**
     * Fills an owner from JSONObject
     */
    public VKApiOwner parse(JSONObject from) {
        id = from.optInt("id");
        return this;
    }

    /**
     * Creates according with given ID.
     */
    public VKApiOwner(int id) {
        this.id = id;
    }

    /**
     * Creates an owner from Parcel.
     */
    public VKApiOwner(Parcel in) {
        this.id = in.readInt();
    }

    @Override
    public int getId() {
        return id;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
    }

    public static Creator<VKApiOwner> CREATOR = new Creator<VKApiOwner>() {
        public VKApiOwner createFromParcel(Parcel source) {
            return new VKApiOwner(source);
        }

        public VKApiOwner[] newArray(int size) {
            return new VKApiOwner[size];
        }
    };
}


text:
<?php

namespace RedisClient\Exception;

class ErrorException extends RedisException {

}


text:
// Copyright (C) Pash Contributors. License GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;

namespace System.Management.Automation
{
    public class PSDataCollection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable, IDisposable
    {
        private bool isopen;
        private bool isenumerated;
        private IList<T> data;

        public event EventHandler<DataAddedEventArgs> DataAdded
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            add
            {
                throw new NotImplementedException();
            }
            [MethodImpl(MethodImplOptions.Synchronized)]
            remove
            {
                throw new NotImplementedException();
            }
        }
        public event EventHandler Completed
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            add
            {
                throw new NotImplementedException();
            }
            [MethodImpl(MethodImplOptions.Synchronized)]
            remove
            {
                throw new NotImplementedException();
            }
        }
        public bool IsOpen
        {
            get
            {
                return this.isopen;
            }
        }
        internal bool ReleaseOnEnumeration
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        internal bool IsEnumerated
        {
            get
            {
                return isenumerated;
            }
            set
            {
                isenumerated = value;
            }
        }
        public T this[int index]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public int Count
        {
            get
            {
                int cnt = 0;

                if (data != null)
                    cnt = data.Count;

                return cnt;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        bool IList.IsFixedSize
        {
            get
            {
                throw new NotImplementedException();
            }
        }
        bool IList.IsReadOnly
        {
            get
            {
                throw new NotImplementedException();
            }
        }
        object IList.this[int index]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        bool ICollection.IsSynchronized
        {
            get
            {
                throw new NotImplementedException();
            }
        }
        object ICollection.SyncRoot
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public PSDataCollection()
            : this(new List<T>())
        {

        }
        public PSDataCollection(IEnumerable<T> items)
            : this(new List<T>(items))
        {

        }
        public PSDataCollection(int capacity)
            : this(new List<T>(capacity))
        {

        }

        /// <summary>
        /// TODO: .
        /// </summary>
        internal PSDataCollection(IList<T> listToUse)
        {
            isopen = false;
            isenumerated = false;
            data = listToUse;
        }

        public void Complete()
        {
            throw new NotImplementedException();
        }

        public int IndexOf(T item)
        {
            throw new NotImplementedException();
        }

        public void Insert(int index, T item)
        {
            throw new NotImplementedException();
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException();
        }

        public void Add(T item)
        {
            throw new NotImplementedException();
        }

        public void Clear()
        {
            throw new NotImplementedException();
        }

        public bool Contains(T item)
        {
            throw new NotImplementedException();
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        public bool Remove(T item)
        {
            throw new NotImplementedException();
        }

        public IEnumerator<T> GetEnumerator()
        {
            return new PSDataCollectionEnumerator<T>(this);
        }

        int IList.Add(object value)
        {
            throw new NotImplementedException();
        }

        bool IList.Contains(object value)
        {
            throw new NotImplementedException();
        }

        int IList.IndexOf(object value)
        {
            throw new NotImplementedException();
        }

        void IList.Insert(int index, object value)
        {
            throw new NotImplementedException();
        }

        void IList.Remove(object value)
        {
            throw new NotImplementedException();
        }

        void ICollection.CopyTo(Array array, int index)
        {
            throw new NotImplementedException();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new PSDataCollectionEnumerator<T>(this);
        }

        public Collection<T> ReadAll()
        {
            throw new NotImplementedException();
        }

        protected virtual void InsertItem(Guid psInstanceId, int index, T item)
        {
            throw new NotImplementedException();
        }

        protected virtual void RemoveItem(int index)
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {

            GC.SuppressFinalize(this);
        }

    }
}


text:
using Robotlegs.Bender.Extensions.ContextViews.API;
using SwiftSuspenders;
using SwiftSuspenders.DependencyProviders;
using System;
using System.Collections.Generic;
using UnityEngine;
using SwiftSuspenders.Errors;

namespace Robotlegs.Bender.DependencyProviders
{
	public class UnitySingletonComponentProvider : AbstractUnityComponentProvider, DependencyProvider
	{
		public UnitySingletonComponentProvider(Type componentType) : base(componentType) { }

		public UnitySingletonComponentProvider(Type componentType, GameObject parentObject) : base(componentType, parentObject) { }

		public UnitySingletonComponentProvider(Type componentType, Transform parentObject) : base(componentType, parentObject) { }

		private bool _destroyed = false;

		public object Apply(Type targetType, Injector activeInjector, Dictionary<string, object> injectParameters)
		{
			if (_destroyed)
				throw new InjectorException("Forbidden usage of unmapped singleton provider for type "
					+ targetType.ToString());

			if (component == null)
			{
				AddComponent(activeInjector, componentType);

				activeInjector.InjectInto(component);
			}

			if (_postApply != null)
			{
				_postApply(this, component);
			}
			return component;
		}

		public void Destroy()
		{
			if (_preDestroy != null)
			{
				_preDestroy(this, component);
			}
			_destroyed = true;
			RemoveComponent();
		}
	}
}


text:
import React, {Component, PropTypes} from 'react';
import {dateTimeFormat, formatIso, isEqualDate} from './dateUtils';
import DatePickerDialog from './DatePickerDialog';
import TextField from '../TextField';

class DatePicker extends Component {
  static propTypes = {
    /**
     * Constructor for date formatting for the specified `locale`.
     * The constructor must follow this specification: ECMAScript Internationalization API 1.0 (ECMA-402).
     * `Intl.DateTimeFormat` is supported by most modern browsers, see http://caniuse.com/#search=intl,
     * otherwise https://github.com/andyearnshaw/Intl.js is a good polyfill.
     *
     * By default, a built-in `DateTimeFormat` is used which supports the 'en-US' `locale`.
     */
    DateTimeFormat: PropTypes.func,
    /**
     * If true, automatically accept and close the picker on select a date.
     */
    autoOk: PropTypes.bool,
    /**
     * Override the default text of the 'Cancel' button.
     */
    cancelLabel: PropTypes.node,
    /**
     * The css class name of the root element.
     */
    className: PropTypes.string,
    /**
     * Used to control how the Date Picker will be displayed when the input field is focused.
     * `dialog` (default) displays the DatePicker as a dialog with a modal.
     * `inline` displays the DatePicker below the input field (similar to auto complete).
     */
    container: PropTypes.oneOf(['dialog', 'inline']),
    /**
     * This is the initial date value of the component.
     * If either `value` or `valueLink` is provided they will override this
     * prop with `value` taking precedence.
     */
    defaultDate: PropTypes.object,
    /**
     * Override the inline-styles of DatePickerDialog's Container element.
     */
    dialogContainerStyle: PropTypes.object,
    /**
     * Disables the year selection in the date picker.
     */
    disableYearSelection: PropTypes.bool,
    /**
     * Disables the DatePicker.
     */
    disabled: PropTypes.bool,
    /**
     * Used to change the first day of week. It varies from
     * Saturday to Monday between different locales.
     * The allowed range is 0 (Sunday) to 6 (Saturday).
     * The default is `1`, Monday, as per ISO 8601.
     */
    firstDayOfWeek: PropTypes.number,
    /**
     * This function is called to format the date displayed in the input field, and should return a string.
     * By default if no `locale` and `DateTimeFormat` is provided date objects are formatted to ISO 8601 YYYY-MM-DD.
     *
     * @param {object} date Date object to be formatted.
     * @returns {any} The formatted date.
     */
    formatDate: PropTypes.func,
    /**
     * Hide date display
     */
    hideCalendarDate: PropTypes.bool,
    /**
     * Locale used for formatting the `DatePicker` date strings. Other than for 'en-US', you
     * must provide a `DateTimeFormat` that supports the chosen `locale`.
     */
    locale: PropTypes.string,
    /**
     * The ending of a range of valid dates. The range includes the endDate.
     * The default value is current date + 100 years.
     */
    maxDate: PropTypes.object,
    /**
     * The beginning of a range of valid dates. The range includes the startDate.
     * The default value is current date - 100 years.
     */
    minDate: PropTypes.object,
    /**
     * Tells the component to display the picker in portrait or landscape mode.
     */
    mode: PropTypes.oneOf(['portrait', 'landscape']),
    /**
     * Override the default text of the 'OK' button.
     */
    okLabel: PropTypes.node,
    /**
     * Callback function that is fired when the date value changes.
     *
     * @param {null} null Since there is no particular event associated with the change,
     * the first argument will always be null.
     * @param {object} date The new date.
     */
    onChange: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's dialog is dismissed.
     */
    onDismiss: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's `TextField` gains focus.
     */
    onFocus: PropTypes.func,
    /**
     * Callback function that is fired when the Date Picker's dialog is shown.
     */
    onShow: PropTypes.func,
    /**
     * Callback function that is fired when a touch tap event occurs on the Date Picker's `TextField`.
     *
     * @param {object} event TouchTap event targeting the `TextField`.
     */
    onTouchTap: PropTypes.func,
    /**
     * Callback function used to determine if a day's entry should be disabled on the calendar.
     *
     * @param {object} day Date object of a day.
     * @returns {boolean} Indicates whether the day should be disabled.
     */
    shouldDisableDate: PropTypes.func,
    /**
     * Override the inline-styles of the root element.
     */
    style: PropTypes.object,
    /**
     * Override the inline-styles of DatePicker's TextField element.
     */
    textFieldStyle: PropTypes.object,
    /**
     * Sets the date for the Date Picker programmatically.
     */
    value: PropTypes.object,
  };

  static defaultProps = {
    autoOk: false,
    container: 'dialog',
    disabled: false,
    disableYearSelection: false,
    firstDayOfWeek: 1,
    hideCalendarDate: false,
    style: {},
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  state = {
    date: undefined,
  };

  componentWillMount() {
    this.setState({
      date: this.isControlled() ? this.getControlledDate() : this.props.defaultDate,
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.isControlled()) {
      const newDate = this.getControlledDate(nextProps);
      if (!isEqualDate(this.state.date, newDate)) {
        this.setState({
          date: newDate,
        });
      }
    }
  }

  getDate() {
    return this.state.date;
  }

  /**
   * Open the date-picker dialog programmatically from a parent.
   */
  openDialog() {
    /**
     * if the date is not selected then set it to new date
     * (get the current system date while doing so)
     * else set it to the currently selected date
     */
    if (this.state.date !== undefined) {
      this.setState({
        dialogDate: this.getDate(),
      }, this.refs.dialogWindow.show);
    } else {
      this.setState({
        dialogDate: new Date(),
      }, this.refs.dialogWindow.show);
    }
  }

  /**
   * Alias for `openDialog()` for an api consistent with TextField.
   */
  focus() {
    this.openDialog();
  }

  handleAccept = (date) => {
    if (!this.isControlled()) {
      this.setState({
        date: date,
      });
    }
    if (this.props.onChange) {
      this.props.onChange(null, date);
    }
  };

  handleFocus = (event) => {
    event.target.blur();
    if (this.props.onFocus) {
      this.props.onFocus(event);
    }
  };

  handleTouchTap = (event) => {
    if (this.props.onTouchTap) {
      this.props.onTouchTap(event);
    }

    if (!this.props.disabled) {
      setTimeout(() => {
        this.openDialog();
      }, 0);
    }
  };

  isControlled() {
    return this.props.hasOwnProperty('value');
  }

  getControlledDate(props = this.props) {
    if (props.value instanceof Date) {
      return props.value;
    }
  }

  formatDate = (date) => {
    if (this.props.locale) {
      const DateTimeFormat = this.props.DateTimeFormat || dateTimeFormat;
      return new DateTimeFormat(this.props.locale, {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric',
      }).format(date);
    } else {
      return formatIso(date);
    }
  };

  render() {
    const {
      DateTimeFormat,
      autoOk,
      cancelLabel,
      className,
      container,
      defaultDate, // eslint-disable-line no-unused-vars
      dialogContainerStyle,
      disableYearSelection,
      firstDayOfWeek,
      formatDate: formatDateProp,
      locale,
      maxDate,
      minDate,
      mode,
      okLabel,
      onDismiss,
      onFocus, // eslint-disable-line no-unused-vars
      onShow,
      onTouchTap, // eslint-disable-line no-unused-vars
      shouldDisableDate,
      hideCalendarDate,
      style,
      textFieldStyle,
      ...other
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const formatDate = formatDateProp || this.formatDate;

    return (
      <div className={className} style={prepareStyles(Object.assign({}, style))}>
        <TextField
          {...other}
          onFocus={this.handleFocus}
          onTouchTap={this.handleTouchTap}
          ref="input"
          style={textFieldStyle}
          value={this.state.date ? formatDate(this.state.date) : ''}
        />
        <DatePickerDialog
          DateTimeFormat={DateTimeFormat}
          autoOk={autoOk}
          cancelLabel={cancelLabel}
          container={container}
          containerStyle={dialogContainerStyle}
          disableYearSelection={disableYearSelection}
          firstDayOfWeek={firstDayOfWeek}
          initialDate={this.state.dialogDate}
          locale={locale}
          maxDate={maxDate}
          minDate={minDate}
          mode={mode}
          okLabel={okLabel}
          onAccept={this.handleAccept}
          onShow={onShow}
          onDismiss={onDismiss}
          ref="dialogWindow"
          shouldDisableDate={shouldDisableDate}
          hideCalendarDate={hideCalendarDate}
        />
      </div>
    );
  }
}

export default DatePicker;


text:
<?php

namespace Caesar\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class UserRepository extends EntityRepository implements UserProviderInterface {

    public function loadUserByUsername($username) {
        $q = $this->createQueryBuilder('u')
                ->where('u.username = :username')
                ->setParameter('username', $username)
                ->orWhere('u.codeBu = :codeBu')
                ->setParameter('codeBu', $username)
                ->getQuery();
        $user = $q->getOneOrNullResult();
        if ($user == null) {
            throw new UsernameNotFoundException(sprintf('Unable to find an active admin CaesarUserBundle:User object identified by "%s".', $username), null, 0);
        }
        return $user;
    }

    public function authenticate($username, $password) {
        $q = $this->createQueryBuilder('u')
                ->where('u.username = :username')
                ->setParameter('username', $username)
                ->orWhere('u.codeBu = :codeBu')
                ->setParameter('codeBu', $username)
                ->andWhere('u.password = :password')
                ->setParameter('password', $password)
                ->getQuery();
        $user = $q->getOneOrNullResult();
        return $user;
    }

    public function refreshUser(UserInterface $user) {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
        }

        return $this->find($user->getId());
    }

    public function supportsClass($class) {
        return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
    }

    public function getUserFromToSortBy($page, $sort, $direction, $keywords = array()) {
        $nb_per_page = 10;
        $min = ($page - 1) * $nb_per_page;
        $qb = $this->createQueryBuilder('u');
        $qb->where("u.role = 'ROLE_USER'")
                ->orderBy('u.' . $sort, $direction)
                ->setFirstResult($min)
                ->setMaxResults($nb_per_page);
        if (!empty($keywords)) {
            $iteration = 0;
            foreach ($keywords as $string) {
                if ($iteration > 0) {
                    $qb->andWhere("u.username like :user" . $iteration . " OR u.name like :name" . $iteration . " OR u.firstname like :first" . $iteration);
                } else {
                    $qb->andWhere("u.username like :user" . $iteration . " OR u.name like :name" . $iteration . " OR u.firstname like :first" . $iteration);
                }
                $qb->setParameter('user' . $iteration, '%' . $string . '%');
                $qb->setParameter('name' . $iteration, '%' . $string . '%');
                $qb->setParameter('first' . $iteration, '%' . $string . '%');
                ++$iteration;
            }
        }

        return $qb->getQuery()->getResult();
    }

    public function count($keywords = array()) {
        $qb = $this->createQueryBuilder('u');
        $qb->select('count(u.id)')
                ->where("u.role = 'ROLE_USER'");
        if (!empty($keywords)) {
            $iteration = 0;
            foreach ($keywords as $string) {
                if ($iteration > 0) {
                    $qb->andWhere("u.username like :user" . $iteration . " OR u.name like :name" . $iteration . " OR u.firstname like :first" . $iteration);
                } else {
                    $qb->andWhere("u.username like :user" . $iteration . " OR u.name like :name" . $iteration . " OR u.firstname like :first" . $iteration);
                }
                $qb->setParameter('user' . $iteration, '%' . $string . '%');
                $qb->setParameter('name' . $iteration, '%' . $string . '%');
                $qb->setParameter('first' . $iteration, '%' . $string . '%');
                ++$iteration;
            }
        }
        return $qb->getQuery()->getSingleScalarResult();
    }

    public function findAllInArray() {
        $qb = $this->createQueryBuilder('u');
        $qb->select();
        return $qb->getQuery()->getArrayResult();
    }

}


text:
import React from "react";
import TestRenderer from "react-test-renderer";
import { iterator } from "@times-components/test-utils";
import { ApolloError } from "apollo-client";
import "./mocks";
import Topic from "../src/topic";

// eslint-disable-next-line global-require
jest.mock("@times-components/provider", () => require("./mock-provider"));
jest.mock("@times-components/tracking", () => {
  const id = x => x;

  return {
    withTrackEvents: id,
    withTrackingContext: id
  };
});

export default props => {
  const tests = [
    {
      name: "an error page",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} error={new ApolloError("Some Error")} />
        );

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "a loading state",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} isLoading page={1} />
        );

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "uses general description when there is no description",
      test() {
        const testInstance = TestRenderer.create(
          <Topic
            {...{ ...props, topic: { name: "London", description: null } }}
            isLoading={false}
            page={1}
          />
        );

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "render description when there is description",
      test() {
        const testInstance = TestRenderer.create(
          <Topic
            {...{
              ...props,
              topic: {
                name: "London",
                description: [
                  {
                    attributes: {
                      value: "Sample "
                    },
                    children: [],
                    name: "text"
                  },
                  {
                    attributes: {},
                    children: [
                      {
                        attributes: {
                          value: "Description."
                        },
                        children: [],
                        name: "text"
                      }
                    ],
                    name: "italic"
                  }
                ]
              }
            }}
            isLoading={false}
            page={1}
          />
        );

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "an article list",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} isLoading={false} page={2} />
        );

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "fetches more articles",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} isLoading={false} page={2} />
        );

        const articleList = testInstance.root.find(
          node => node.type === "ArticleList"
        );

        articleList.props.fetchMore(2);

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "fetches more articles and falls back to previous data if no more",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} isLoading={false} page={2} />
        );

        const articleList = testInstance.root.find(
          node => node.type === "ArticleList"
        );

        articleList.props.fetchMore(3);

        expect(testInstance).toMatchSnapshot();
      }
    },
    {
      name: "an article list header",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} isLoading={false} page={2} />
        );

        const articleList = testInstance.root.find(
          node => node.type === "ArticleList"
        );

        const articleListHeader = TestRenderer.create(
          articleList.props.articleListHeader
        );

        expect(articleListHeader).toMatchSnapshot();
      }
    },
    {
      name: "a topic header with no description",
      test() {
        const testInstance = TestRenderer.create(
          <Topic
            {...props}
            isLoading={false}
            page={2}
            topic={{
              name: "No Desc"
            }}
          />
        );

        const articleList = testInstance.root.find(
          node => node.type === "ArticleList"
        );

        const articleListHeader = TestRenderer.create(
          articleList.props.articleListHeader
        );

        expect(articleListHeader).toMatchSnapshot();
      }
    },
    {
      name: "an article list header loading",
      test() {
        const testInstance = TestRenderer.create(
          <Topic {...props} isLoading />
        );

        const articleList = testInstance.root.find(
          node => node.type === "ArticleList"
        );

        const articleListHeader = TestRenderer.create(
          articleList.props.articleListHeader
        );

        expect(articleListHeader).toMatchSnapshot();
      }
    }
  ];

  jest.useFakeTimers();

  iterator(tests);
};


text:
import cockatrice from "./cockatrice";
import mtgo from "./mtgo";
import mtga from "./mtga";
import text from "./text";

const toJSON = (filename, deck) => JSON.stringify(deck, null, 2);
const json = {
  name: "JSON",
  download: toJSON,
  downloadExtension: ".json",
  copy: toJSON
};

export default {
  cockatrice,
  mtga,
  mtgo,
  text,
  json
};