text:
<!DOCTYPE html>

    <meta 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="">
    <meta name="author" content="">

    <title>Theory</title>

    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="../css/grayscale.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                    Menu
                </button>
                Back

                        History of Computing

Chapter 1 - Computational Thinking

                        Decomposition

                        OOP

                        Abstraction

History of Computing

One of the earliest and most simple creations for computing was the abacus. It dates back to 2400 BC and is the first known calculator.
				Its original style of usage was by lines drawn in sand with pebbles. Abaci, of a more modern design, are still used as calculation tools today.
				This was the first known computer and most advanced system of calculation known to date - preceding Greek methods by 2,000 years. The abacus was
				likely invented by the Babylonians and would have been used simply as an aid to simple arithmetic problems. In 1110 BC, the south-pointing chariot
				was invented in ancient China. It was the first known geared mechanism to use a differential gear, which was later used in analog computers.
				The Chinese also invented a more sophisticated abacus from around the 2nd century BC known as the Chinese abacus. In the 3rd century BC, Archimedes
				used the mechanical principle of balance to calculate mathematical problems, such as the number of grains of sand in the universe, which also
				required a recursive notation for numbers. The binary number system which is used today in all electronic computers was first described by Pingala,
				an Indian mathematician in 300 BC. The earliest known analog computer has been dated to 125 BC and is called the Antikythera mechanism after the
				Greek island it was found near. The computer was used to predict astronomical positions and eclipses as well as the olympiads which is the cycle
				of the ancient olympic games. During the Middle Ages, several European philosophers made attempts to produce analog computer devices. Influenced
				by the Arabs and Scholasticism, Majorcan philosopher Ramon Llull devoted a great part of his life to defining and designing several logical machines
				that, by combining simple and undeniable philosophical truths, could produce all possible knowledge. These machines were never actually built, as
				they were more of a thought experiment to produce new knowledge in systematic ways; although they could make simple logical operations, they still
				needed a human being for the interpretation of results. When John Napier discovered logarithms for computational purposes in the early 17th century,
				there followed a period of considerable progress by inventors and scientists in making calculating tools. The apex of this early era of formal
				computing can be seen in the difference engine and its successor the analytical engine (which was never completely constructed but was designed in
				detail), both by Charles Babbage. The analytical engine combined concepts from his work and that of others to create a device that if constructed
				as designed would have possessed many properties of a modern electronic computer. These properties include such features as an internal "scratch
				memory" equivalent to RAM, multiple forms of output including a bell, a graph-plotter, and simple printer, and a programmable input-output "hard"
				memory of punch cards which it could modify as well as read. Blaise Pascal, the French polymath was the first to invent the mechanical calculator
				which then inspired many similar machines. In 1938 Konrad Zuse of Berlin created the first mechanical binary programmable computer, the Z1. The
				 Z1 was based on boolean algebra.

				 Alan Turing is an important figure in the history of computing as he is considered the father of modern computing. This is due to him being a
				 pioneering theoretical computer scientist. One of his most famous works was the the turing machine which can be considered a model of a general
				 purpose computer. A Turing machine is an abstract machine that manipulates symbols on a strip of tape according to a table of rules; to be more
				 exact, it is a mathematical model of computation that defines such a device. Despite the model's simplicity, given any computer algorithm, a
				 Turing machine can be constructed that is capable of simulating that algorithm's logic.

				 Turing's most famous work was his efforts during World War II for the Government Code and Cypher School at Bletchley Park, Britain's codebreaking
				 centre. For a time he led Hut 8, the section responsible for German naval cryptanalysis. Originally he devised a number of techniques for breaking
				 German ciphers, including improvements to the pre-war Polish bombe method and an electromechanical machine that could find settings for the Enigma
				 machine. This last machine was designed on the concept Turing hypothesized of Banburismus. This idea used sequential conditional probability to
				 infer information about the likely settings of the Enigma machine. The aim of Banburismus was to reduce the time required of the electromechanical
				 Bombe machines by identifying the most likely right-hand and middle wheels of the Enigma. In probability theory, conditional probability is a
				 measure of the probability of an event given that (by assumption, presumption, assertion or evidence) another event has occurred. For example,
				 the probability that any given person has a cough on any given day may be only 5%. But if we know or assume that the person has a cold, then they
				 are much more likely to be coughing. The conditional probability of coughing given that you have a cold might be a much higher 75%.

				 Tim Berners-Lee is another prominent figure in computing history as he is credited with creating the world wide web. This is because he proposed
				 the idea of Hypertext Transfer Protocol or HTTP. HTTP is an application protocol for distributed, collaborative, hypermedia information systems.
				 While Tim Berners-Lee did not invent the internet (as the World Wide Web and the internet are two different things) he was the one to combine the
				 internet with HTTP to create the World Wide Web.

				 Charles Babbage was another person who shaped what computing is today. He, along with Ada Lovelace, is best remembered for originating the concept
				 of a programmable computer. The two are credited with inventing the first mechanical computer that eventually led to more complex designs.

				 Another prominent figure was John von Neumann. He was a was a Hungarian-American pure and applied mathematician, physicist, inventor, computer
				 scientist, and polymath. He made major contributions to computing which pertains to Von Neumann architecture, linear programming, self-replicating
				 machines stochastic computing. The von Neumann architecture, which is also known as the von Neumann model and Princeton architecture, is a computer
				 architecture based on that described in 1945 by von Neumann and others in the First Draft of a Report on the EDVAC. This describes a design
				 architecture for an electronic digital computer with parts consisting of a processing unit containing an arithmetic logic unit and processor registers;
				 a control unit containing an instruction register and program counter; a memory to store both data and instructions; external mass storage; and input
				 and output mechanisms. The meaning has evolved to be any stored-program computer in which an instruction fetch and a data operation cannot occur at
				 the same time because they share a common bus. This is referred to as the von Neumann bottleneck and often limits the performance of the system.

				 Robert Noyce is an important historical figure as he co-founded Fairchild Semiconductor in 1957 and Intel Corporation in 1968. He is also credited
				 (along with Jack Kilby) with the realization of the first integrated circuit or microchip that fueled the personal computer revolution. This creation
				 was so important as it allowed for there to be  up to several billion transistors and other electronic components in an area the size of a human
				 fingernail meaning that computers could get smaller and smaller.

				 Jon Postel was an American computer scientist who made many significant contributions to the development of the Internet, particularly with respect to
				 standards. He defined the basic protocols of the Internet protocol suite. The Internet protocol suite is the computer networking model and set of
				 communications protocols used on the Internet and similar computer networks. It is commonly known as TCP/IP, because its most important protocols, the
				 Transmission Control Protocol (TCP) and the Internet Protocol (IP) were the first networking protocols defined during its development. TCP/IP provides
				 end-to-end data communication specifying how data should be packetized, addressed, transmitted, routed and received.

				 James Gosling is a famous figure in computing as the creator of Java code. He created the original design of Java and implemented the language's
				 original compiler and virtual machine.

				 Marvin Minsky was another prominent figure in computing history. He is credited with creating the first Head Mounted Display or HMD and the logo
				 programing language (along with Seymour Papert. His main contribution was his work on artificial neural networks. An artificial neural network is a
				 network inspired by biological neural networks (the central nervous systems of animals, in particular the brain) which are used to estimate functions
				 that can depend on a large number of inputs that are generally unknown.

There are currently five generations of computers dating back to 1940 when the first electrical computers were made. This first generation of computers used vacuum tubes as circuitry and magnetic drums for memory. This resulted in the computers being huge, requiring large rooms to house them and costing a fortune to run. The first generation of computers used machine language which is the most basic form of programming language that can be understood by computers. The computers could only solve one problem at a time and created a huge amount of heat. The way to input data to these machines was through the use of punch cards and paper tape while outputs came out on print-outs.

The second generation of computers saw the replacement of vacuum tube by transistors. This didn't happen till 1956 even though transistors were invented in 1947. The transistors were a significant improvement over vacuum tubes despite them still creating large amounts of heat. Transistors allowed computers to become smaller faster, cheaper and less heavy on electricity. The machines still used punched cards as input and printouts as output. With the change of hardware came a change of language going from a simple machine language to symbolic assembly languages. This change allowed programmers to create instructions in words. At this time high level languages were being developed. The main ones were early versions of COBOL and FORTRAN.

By around 1964, computers transitioned towards the third generation which was caused by miniaturizing transistors and putting them on silicon chips. This meant there were huge increases in speed and efficiency of the machines. The third generation computers were the first ones where the user could interact using keyboards and monitors which interfaced with an operating system. This advancement allowed the computers to run several applications at once using a central program which functioned to monitor memory. The advantages of these new machines of being cheaper and smaller than ever caused a mass market of users to emerge during the 60's.

The fourth generation started in 1972 after the release of the Intel 4004 chip in 1971. What was so amazing about this chip was that all the main computer components was housed on the one chip such as the CPU, memory and input/output controls. During the fourth generation the first ever computer designed for home use was created by IBM in 1981 and 1984 saw the MacIntosh be introduced by Apple. Microprocessors now moved into an increasing number of everyday products such as dishwashers, microwaves, TVs, etc. The increased power of these small computers meant they could be linked together, creating networks. Which ultimately led to the creation and fast evolution of the internet. Over the 38 year span of the fourth generation there have been many other major advances including the Graphical User Interface (GUI), the mouse and very recently the large leaps in laptop capability and hand-held devices.

The fifth and current generation, the generation of artificial intelligence, sees the incorporation of simple artificial intelligence being incorporated into computers, tablets and smartphones in the form of voice recognition software allowing the user to search for things without having to type a single character. AI is a reality made possible by using parallel processing and superconductors. The future of computing will most likely be shaped by quantum computation, molecular and nano technology. Essentially the fifth generation will be all about using these technologies to create machines which can process and respond to natural language, and have capability to learn and organise themselves.

Return to the main page

                    Main Page


text:
package org.powermock.api.mockito.repackaged.asm.tree.analysis;

/**
 * Thrown if a problem occurs during the analysis of a method.
 *
 * @author Bing Ran
 * @author Eric Bruneton
 */
public class AnalyzerException extends Exception {

    public AnalyzerException(final String msg) {
        super(msg);
    }

    public AnalyzerException(final String msg, final Throwable exception) {
        super(msg, exception);
    }

    public AnalyzerException(
        final String msg,
        final Object expected,
        final Value encountered)
    {
        super((msg == null ? "Expected " : msg + ": expected ") + expected
                + ", but found " + encountered);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Composer\Util;

use Composer\Config;
use Composer\IO\IOInterface;

/**
 * @author Till Klampaeckel <till@php.net>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class Svn
{
    const MAX_QTY_AUTH_TRIES = 5;

    /**
     * @var array
     */
    protected $credentials;

    /**
     * @var bool
     */
    protected $hasAuth;

    /**
     * @var \Composer\IO\IOInterface
     */
    protected $io;

    /**
     * @var string
     */
    protected $url;

    /**
     * @var bool
     */
    protected $cacheCredentials = true;

    /**
     * @var ProcessExecutor
     */
    protected $process;

    /**
     * @var int
     */
    protected $qtyAuthTries = 0;

    /**
     * @var \Composer\Config
     */
    protected $config;

    /**
     * @param string                   $url
     * @param \Composer\IO\IOInterface $io
     * @param Config                   $config
     * @param ProcessExecutor          $process
     */
    public function __construct($url, IOInterface $io, Config $config, ProcessExecutor $process = null)
    {
        $this->url = $url;
        $this->io = $io;
        $this->config = $config;
        $this->process = $process ?: new ProcessExecutor;
    }

    public static function cleanEnv()
    {
        // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940
        putenv("DYLD_LIBRARY_PATH");
        unset($_SERVER['DYLD_LIBRARY_PATH']);
    }

    /**
     * Execute an SVN remote command and try to fix up the process with credentials
     * if necessary.
     *
     * @param string $command SVN command to run
     * @param string $url     SVN url
     * @param string $cwd     Working directory
     * @param string $path    Target for a checkout
     * @param bool   $verbose Output all output to the user
     *
     * @throws \RuntimeException
     * @return string
     */
    public function execute($command, $url, $cwd = null, $path = null, $verbose = false)
    {
        // Ensure we are allowed to use this URL by config
        $this->config->prohibitUrlByConfig($url, $this->io);

        $svnCommand = $this->getCommand($command, $url, $path);

        return $this->executeWithAuthRetry($svnCommand, $cwd, $path, $verbose);
    }

    /**
     * Execute an SVN local command and try to fix up the process with credentials
     * if necessary.
     *
     * @param string $command SVN command to run
     * @param string $path    Path argument passed thru to the command
     * @param string $cwd     Working directory
     * @param bool   $verbose Output all output to the user
     *
     * @throws \RuntimeException
     * @return string
     */
    public function executeLocal($command, $path, $cwd = null, $verbose = false)
    {
        $svnCommand = sprintf('%s %s%s %s',
            $command,
            '--non-interactive ',
            $this->getCredentialString(),
            ProcessExecutor::escape($path)
        );

        return $this->executeWithAuthRetry($svnCommand, $cwd, $path, $verbose);
    }

    private function executeWithAuthRetry($command, $cwd, $path, $verbose)
    {
        $output = null;
        $io = $this->io;
        $handler = function ($type, $buffer) use (&$output, $io, $verbose) {
            if ($type !== 'out') {
                return;
            }
            if ('Redirecting to URL ' === substr($buffer, 0, 19)) {
                return;
            }
            $output .= $buffer;
            if ($verbose) {
                $io->writeError($buffer, false);
            }
        };
        $status = $this->process->execute($command, $handler, $cwd);
        if (0 === $status) {
            return $output;
        }

        $errorOutput = $this->process->getErrorOutput();
        $fullOutput = implode("\n", array($output, $errorOutput));

        // the error is not auth-related
        if (false === stripos($fullOutput, 'Could not authenticate to server:')
            && false === stripos($fullOutput, 'authorization failed')
            && false === stripos($fullOutput, 'svn: E170001:')
            && false === stripos($fullOutput, 'svn: E215004:')) {
            throw new \RuntimeException($fullOutput);
        }

        if (!$this->hasAuth()) {
            $this->doAuthDance();
        }

        // try to authenticate if maximum quantity of tries not reached
        if ($this->qtyAuthTries++ < self::MAX_QTY_AUTH_TRIES) {
            // restart the process
            return $this->executeWithAuthRetry($command, $cwd, $path, $verbose);
        }

        throw new \RuntimeException(
            'wrong credentials provided ('.$fullOutput.')'
        );
    }

    /**
     * @param bool $cacheCredentials
     */
    public function setCacheCredentials($cacheCredentials)
    {
        $this->cacheCredentials = $cacheCredentials;
    }

    /**
     * Repositories requests credentials, let's put them in.
     *
     * @throws \RuntimeException
     * @return \Composer\Util\Svn
     */
    protected function doAuthDance()
    {
        // cannot ask for credentials in non interactive mode
        if (!$this->io->isInteractive()) {
            throw new \RuntimeException(
                'can not ask for authentication in non interactive mode'
            );
        }

        $this->io->writeError("The Subversion server ({$this->url}) requested credentials:");

        $this->hasAuth = true;
        $this->credentials['username'] = $this->io->ask("Username: ");
        $this->credentials['password'] = $this->io->askAndHideAnswer("Password: ");

        $this->cacheCredentials = $this->io->askConfirmation("Should Subversion cache these credentials? (yes/no) ", true);

        return $this;
    }

    /**
     * A method to create the svn commands run.
     *
     * @param string $cmd  Usually 'svn ls' or something like that.
     * @param string $url  Repo URL.
     * @param string $path Target for a checkout
     *
     * @return string
     */
    protected function getCommand($cmd, $url, $path = null)
    {
        $cmd = sprintf('%s %s%s %s',
            $cmd,
            '--non-interactive ',
            $this->getCredentialString(),
            ProcessExecutor::escape($url)
        );

        if ($path) {
            $cmd .= ' ' . ProcessExecutor::escape($path);
        }

        return $cmd;
    }

    /**
     * Return the credential string for the svn command.
     *
     * Adds --no-auth-cache when credentials are present.
     *
     * @return string
     */
    protected function getCredentialString()
    {
        if (!$this->hasAuth()) {
            return '';
        }

        return sprintf(
            ' %s--username %s --password %s ',
            $this->getAuthCache(),
            ProcessExecutor::escape($this->getUsername()),
            ProcessExecutor::escape($this->getPassword())
        );
    }

    /**
     * Get the password for the svn command. Can be empty.
     *
     * @throws \LogicException
     * @return string
     */
    protected function getPassword()
    {
        if ($this->credentials === null) {
            throw new \LogicException("No svn auth detected.");
        }

        return isset($this->credentials['password']) ? $this->credentials['password'] : '';
    }

    /**
     * Get the username for the svn command.
     *
     * @throws \LogicException
     * @return string
     */
    protected function getUsername()
    {
        if ($this->credentials === null) {
            throw new \LogicException("No svn auth detected.");
        }

        return $this->credentials['username'];
    }

    /**
     * Detect Svn Auth.
     *
     * @return bool
     */
    protected function hasAuth()
    {
        if (null !== $this->hasAuth) {
            return $this->hasAuth;
        }

        if (false === $this->createAuthFromConfig()) {
            $this->createAuthFromUrl();
        }

        return $this->hasAuth;
    }

    /**
     * Return the no-auth-cache switch.
     *
     * @return string
     */
    protected function getAuthCache()
    {
        return $this->cacheCredentials ? '' : '--no-auth-cache ';
    }

    /**
     * Create the auth params from the configuration file.
     *
     * @return bool
     */
    private function createAuthFromConfig()
    {
        if (!$this->config->has('http-basic')) {
            return $this->hasAuth = false;
        }

        $authConfig = $this->config->get('http-basic');

        $host = parse_url($this->url, PHP_URL_HOST);
        if (isset($authConfig[$host])) {
            $this->credentials['username'] = $authConfig[$host]['username'];
            $this->credentials['password'] = $authConfig[$host]['password'];

            return $this->hasAuth = true;
        }

        return $this->hasAuth = false;
    }

    /**
     * Create the auth params from the url
     *
     * @return bool
     */
    private function createAuthFromUrl()
    {
        $uri = parse_url($this->url);
        if (empty($uri['user'])) {
            return $this->hasAuth = false;
        }

        $this->credentials['username'] = $uri['user'];
        if (!empty($uri['pass'])) {
            $this->credentials['password'] = $uri['pass'];
        }

        return $this->hasAuth = true;
    }
}


text:
namespace AH.ModuleController.UI.ACCMS.Reports.ParameterForms
{
    partial class frmACCMSReportvoucher
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.optIndividual = new AtiqsControlLibrary.SmartRadioButton();
            this.optAll = new AtiqsControlLibrary.SmartRadioButton();
            this.grpIndivudual = new System.Windows.Forms.GroupBox();
            this.label1 = new System.Windows.Forms.Label();
            this.cboVoucherNo = new AtiqsControlLibrary.SmartComboBox();
            this.lvlStartDate = new AtiqsControlLibrary.SmartLabel();
            this.lvlEndDate = new AtiqsControlLibrary.SmartLabel();
            this.smartLabel1 = new AtiqsControlLibrary.SmartLabel();
            this.cboCompany = new AtiqsControlLibrary.SmartComboBox();
            this.dtStartDate = new System.Windows.Forms.DateTimePicker();
            this.dtEndDate = new System.Windows.Forms.DateTimePicker();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.optContra = new AtiqsControlLibrary.SmartRadioButton();
            this.optJournal = new AtiqsControlLibrary.SmartRadioButton();
            this.optReceipt = new AtiqsControlLibrary.SmartRadioButton();
            this.optPayment = new AtiqsControlLibrary.SmartRadioButton();
            this.pnlMain.SuspendLayout();
            this.pnlTop.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.grpIndivudual.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.SuspendLayout();
            //
            // btnClose
            //
            this.btnClose.Location = new System.Drawing.Point(477, 322);
            this.btnClose.TabIndex = 6;
            //
            // btnPrint
            //
            this.btnPrint.Location = new System.Drawing.Point(363, 322);
            this.btnPrint.TabIndex = 3;
            this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
            //
            // frmLabel
            //
            this.frmLabel.Location = new System.Drawing.Point(239, 9);
            this.frmLabel.Size = new System.Drawing.Size(253, 32);
            this.frmLabel.TabIndex = 5;
            this.frmLabel.Text = "Individual Voucher";
            //
            // pnlMain
            //
            this.pnlMain.Controls.Add(this.groupBox3);
            this.pnlMain.Controls.Add(this.dtEndDate);
            this.pnlMain.Controls.Add(this.dtStartDate);
            this.pnlMain.Controls.Add(this.smartLabel1);
            this.pnlMain.Controls.Add(this.cboCompany);
            this.pnlMain.Controls.Add(this.lvlStartDate);
            this.pnlMain.Controls.Add(this.lvlEndDate);
            this.pnlMain.Controls.Add(this.grpIndivudual);
            this.pnlMain.Controls.Add(this.groupBox2);
            this.pnlMain.Location = new System.Drawing.Point(0, 61);
            this.pnlMain.Size = new System.Drawing.Size(691, 260);
            //
            // pnlTop
            //
            this.pnlTop.Size = new System.Drawing.Size(689, 57);
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.optIndividual);
            this.groupBox2.Controls.Add(this.optAll);
            this.groupBox2.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox2.Location = new System.Drawing.Point(18, 12);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(143, 75);
            this.groupBox2.TabIndex = 19;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Report Type";
            //
            // optIndividual
            //
            this.optIndividual.AutoSize = true;
            this.optIndividual.Font = new System.Drawing.Font("Georgia", 11F);
            this.optIndividual.ForeColor = System.Drawing.Color.Gray;
            this.optIndividual.Location = new System.Drawing.Point(18, 47);
            this.optIndividual.Name = "optIndividual";
            this.optIndividual.Size = new System.Drawing.Size(95, 22);
            this.optIndividual.TabIndex = 1;
            this.optIndividual.Text = "Individual";
            this.optIndividual.UseVisualStyleBackColor = true;
            this.optIndividual.CheckedChanged += new System.EventHandler(this.optIndividual_CheckedChanged);
            //
            // optAll
            //
            this.optAll.AutoSize = true;
            this.optAll.Checked = true;
            this.optAll.Font = new System.Drawing.Font("Georgia", 11F);
            this.optAll.ForeColor = System.Drawing.Color.Gray;
            this.optAll.Location = new System.Drawing.Point(18, 21);
            this.optAll.Name = "optAll";
            this.optAll.Size = new System.Drawing.Size(44, 22);
            this.optAll.TabIndex = 0;
            this.optAll.TabStop = true;
            this.optAll.Text = "All";
            this.optAll.UseVisualStyleBackColor = true;
            this.optAll.CheckedChanged += new System.EventHandler(this.optAll_CheckedChanged);
            //
            // grpIndivudual
            //
            this.grpIndivudual.Controls.Add(this.label1);
            this.grpIndivudual.Controls.Add(this.cboVoucherNo);
            this.grpIndivudual.Location = new System.Drawing.Point(167, 52);
            this.grpIndivudual.Name = "grpIndivudual";
            this.grpIndivudual.Size = new System.Drawing.Size(491, 63);
            this.grpIndivudual.TabIndex = 2;
            this.grpIndivudual.TabStop = false;
            this.grpIndivudual.Visible = false;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(45, 25);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(84, 14);
            this.label1.TabIndex = 1;
            this.label1.Text = "Voucher No:";
            //
            // cboVoucherNo
            //
            this.cboVoucherNo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboVoucherNo.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cboVoucherNo.ForeColor = System.Drawing.Color.Blue;
            this.cboVoucherNo.FormattingEnabled = true;
            this.cboVoucherNo.Location = new System.Drawing.Point(133, 19);
            this.cboVoucherNo.Name = "cboVoucherNo";
            this.cboVoucherNo.Size = new System.Drawing.Size(347, 26);
            this.cboVoucherNo.TabIndex = 4;
            //
            // lvlStartDate
            //
            this.lvlStartDate.AutoSize = true;
            this.lvlStartDate.BackColor = System.Drawing.Color.Transparent;
            this.lvlStartDate.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Bold);
            this.lvlStartDate.Location = new System.Drawing.Point(223, 141);
            this.lvlStartDate.Name = "lvlStartDate";
            this.lvlStartDate.Size = new System.Drawing.Size(71, 18);
            this.lvlStartDate.TabIndex = 22;
            this.lvlStartDate.Text = "Start Date:";
            //
            // lvlEndDate
            //
            this.lvlEndDate.AutoSize = true;
            this.lvlEndDate.BackColor = System.Drawing.Color.Transparent;
            this.lvlEndDate.Font = new System.Drawing.Font("Book Antiqua", 9.75F, System.Drawing.FontStyle.Bold);
            this.lvlEndDate.Location = new System.Drawing.Point(451, 141);
            this.lvlEndDate.Name = "lvlEndDate";
            this.lvlEndDate.Size = new System.Drawing.Size(67, 18);
            this.lvlEndDate.TabIndex = 23;
            this.lvlEndDate.Text = "End Date:";
            //
            // smartLabel1
            //
            this.smartLabel1.AutoSize = true;
            this.smartLabel1.BackColor = System.Drawing.Color.Transparent;
            this.smartLabel1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold);
            this.smartLabel1.Location = new System.Drawing.Point(169, 24);
            this.smartLabel1.Name = "smartLabel1";
            this.smartLabel1.Size = new System.Drawing.Size(128, 16);
            this.smartLabel1.TabIndex = 25;
            this.smartLabel1.Text = "Company Name:";
            //
            // cboCompany
            //
            this.cboCompany.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboCompany.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cboCompany.ForeColor = System.Drawing.Color.Blue;
            this.cboCompany.FormattingEnabled = true;
            this.cboCompany.Location = new System.Drawing.Point(301, 20);
            this.cboCompany.Name = "cboCompany";
            this.cboCompany.Size = new System.Drawing.Size(346, 26);
            this.cboCompany.TabIndex = 0;
            //
            // dtStartDate
            //
            this.dtStartDate.Font = new System.Drawing.Font("Verdana", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dtStartDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
            this.dtStartDate.Location = new System.Drawing.Point(300, 141);
            this.dtStartDate.Name = "dtStartDate";
            this.dtStartDate.Size = new System.Drawing.Size(118, 26);
            this.dtStartDate.TabIndex = 1;
            //
            // dtEndDate
            //
            this.dtEndDate.Font = new System.Drawing.Font("Verdana", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dtEndDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
            this.dtEndDate.Location = new System.Drawing.Point(524, 139);
            this.dtEndDate.Name = "dtEndDate";
            this.dtEndDate.Size = new System.Drawing.Size(123, 26);
            this.dtEndDate.TabIndex = 2;
            //
            // groupBox3
            //
            this.groupBox3.Controls.Add(this.optContra);
            this.groupBox3.Controls.Add(this.optJournal);
            this.groupBox3.Controls.Add(this.optReceipt);
            this.groupBox3.Controls.Add(this.optPayment);
            this.groupBox3.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox3.Location = new System.Drawing.Point(18, 93);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(143, 156);
            this.groupBox3.TabIndex = 26;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Voucher Type";
            //
            // optContra
            //
            this.optContra.AutoSize = true;
            this.optContra.Font = new System.Drawing.Font("Georgia", 11F);
            this.optContra.ForeColor = System.Drawing.Color.Gray;
            this.optContra.Location = new System.Drawing.Point(18, 118);
            this.optContra.Name = "optContra";
            this.optContra.Size = new System.Drawing.Size(72, 22);
            this.optContra.TabIndex = 19;
            this.optContra.Text = "Contra";
            this.optContra.UseVisualStyleBackColor = true;
            //
            // optJournal
            //
            this.optJournal.AutoSize = true;
            this.optJournal.Font = new System.Drawing.Font("Georgia", 11F);
            this.optJournal.ForeColor = System.Drawing.Color.Gray;
            this.optJournal.Location = new System.Drawing.Point(18, 90);
            this.optJournal.Name = "optJournal";
            this.optJournal.Size = new System.Drawing.Size(78, 22);
            this.optJournal.TabIndex = 18;
            this.optJournal.Text = "Journal";
            this.optJournal.UseVisualStyleBackColor = true;
            //
            // optReceipt
            //
            this.optReceipt.AutoSize = true;
            this.optReceipt.Font = new System.Drawing.Font("Georgia", 11F);
            this.optReceipt.ForeColor = System.Drawing.Color.Gray;
            this.optReceipt.Location = new System.Drawing.Point(18, 62);
            this.optReceipt.Name = "optReceipt";
            this.optReceipt.Size = new System.Drawing.Size(75, 22);
            this.optReceipt.TabIndex = 17;
            this.optReceipt.Text = "Receipt";
            this.optReceipt.UseVisualStyleBackColor = true;
            //
            // optPayment
            //
            this.optPayment.AutoSize = true;
            this.optPayment.Checked = true;
            this.optPayment.Font = new System.Drawing.Font("Georgia", 11F);
            this.optPayment.ForeColor = System.Drawing.Color.Gray;
            this.optPayment.Location = new System.Drawing.Point(18, 34);
            this.optPayment.Name = "optPayment";
            this.optPayment.Size = new System.Drawing.Size(86, 22);
            this.optPayment.TabIndex = 16;
            this.optPayment.TabStop = true;
            this.optPayment.Text = "Payment";
            this.optPayment.UseVisualStyleBackColor = true;
            //
            // frmACCMSReportvoucher
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.ClientSize = new System.Drawing.Size(689, 381);
            this.Name = "frmACCMSReportvoucher";
            this.Load += new System.EventHandler(this.frmACCMSReportvoucher_Load);
            this.pnlMain.ResumeLayout(false);
            this.pnlMain.PerformLayout();
            this.pnlTop.ResumeLayout(false);
            this.pnlTop.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.grpIndivudual.ResumeLayout(false);
            this.grpIndivudual.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox2;
        private AtiqsControlLibrary.SmartRadioButton optIndividual;
        private AtiqsControlLibrary.SmartRadioButton optAll;
        private System.Windows.Forms.GroupBox grpIndivudual;
        private AtiqsControlLibrary.SmartLabel lvlStartDate;
        private AtiqsControlLibrary.SmartLabel lvlEndDate;
        private AtiqsControlLibrary.SmartLabel smartLabel1;
        private AtiqsControlLibrary.SmartComboBox cboCompany;
        private System.Windows.Forms.DateTimePicker dtEndDate;
        private System.Windows.Forms.DateTimePicker dtStartDate;
        private System.Windows.Forms.GroupBox groupBox3;
        private AtiqsControlLibrary.SmartRadioButton optContra;
        private AtiqsControlLibrary.SmartRadioButton optJournal;
        private AtiqsControlLibrary.SmartRadioButton optReceipt;
        private AtiqsControlLibrary.SmartRadioButton optPayment;
        private System.Windows.Forms.Label label1;
        private AtiqsControlLibrary.SmartComboBox cboVoucherNo;
    }
}


text:
package fwk

import (
	"image"
	"image/draw"
	"io/ioutil"
	"log"

	"code.google.com/p/freetype-go/freetype"
	"code.google.com/p/freetype-go/freetype/truetype"
)

type Font struct {
	font   *truetype.Font
	config FontConfig
}

type FontConfig struct {
	Dpi     float64
	Size    float64
	Spacing float64
}

func NewFont(fontfile string, param ...FontParam) (font *Font, err error) {
	var trueTypeFont *truetype.Font
	if trueTypeFont, err = loadFont(fontfile); err == nil {
		font = &Font{font: trueTypeFont, config: newFontConfig(param...)}
	}
	return
}

func loadFont(fontfile string) (font *truetype.Font, err error) {
	var fontBytes []byte
	if fontBytes, err = ioutil.ReadFile(fontfile); err == nil {
		font, err = freetype.ParseFont(fontBytes)
	}
	return
}

type FontParam func(config *FontConfig)

func newFontConfig(params ...FontParam) FontConfig {
	config := FontConfig{
		Dpi:     72,
		Size:    12,
		Spacing: 1.2,
	}
	for _, p := range params {
		p(&config)
	}
	return config
}

func FontSize(size float64) FontParam {
	return func(config *FontConfig) {
		config.Size = size
	}
}

func FontDpi(dpi float64) FontParam {
	return func(config *FontConfig) {
		config.Dpi = dpi
	}
}

func FontSpacing(spacing float64) FontParam {
	return func(config *FontConfig) {
		config.Spacing = spacing
	}
}

func (f *Font) PrintLines(text []string) draw.Image {
	// Initialize the context.
	fg, bg := image.Black, image.White

	// context
	width, height := f.calcDimensions(text)
	rgba := image.NewRGBA(image.Rect(0, 0, width, height))

	// draw background
	draw.Draw(rgba, rgba.Bounds(), bg, image.ZP, draw.Over)

	// setup the freetype context
	c := freetype.NewContext()
	c.SetDPI(f.config.Dpi)
	c.SetFont(f.font)
	c.SetFontSize(f.config.Size)
	c.SetSrc(fg)
	c.SetDst(rgba)
	c.SetClip(rgba.Bounds())

	cspacing := c.PointToFix32(f.config.Size * f.config.Spacing)

	// Draw the text.
	pt := freetype.Pt(0, int(f.config.Size))
	for _, s := range text {
		if _, err := c.DrawString(s, pt); err != nil {
			log.Println(err)
			return nil
		}
		pt.Y += cspacing
	}

	return rgba
}

func (f *Font) calcDimensions(text []string) (width, height int) {
	size := int(f.config.Size)
	for _, line := range text {
		lineWidth := 0
		lineHeight := 0
		for _, ch := range line {
			ind := f.font.Index(ch)
			lineWidth += int(f.font.HMetric(int32(size), ind).AdvanceWidth)
			if hm := int(f.font.VMetric(int32(size), ind).AdvanceHeight); hm > lineHeight {
				lineHeight = hm
			}
		}
		if lineWidth > width {
			width = lineWidth
		}
		height += lineHeight + int(f.config.Size*f.config.Spacing-f.config.Size)
	}
	return
}


text:
package org.apache.kafka.connect.mirror;

import org.apache.kafka.common.config.types.Password;
import org.apache.kafka.common.config.provider.ConfigProvider;
import org.apache.kafka.common.config.ConfigData;
import org.apache.kafka.common.metrics.FakeMetricsReporter;

import org.junit.Test;

import java.util.Map;
import java.util.Set;
import java.util.Collections;
import java.util.HashMap;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

public class MirrorMakerConfigTest {

    private Map<String, String> makeProps(String... keyValues) {
        Map<String, String> props = new HashMap<>();
        for (int i = 0; i < keyValues.length; i += 2) {
            props.put(keyValues[i], keyValues[i + 1]);
        }
        return props;
    }

    @Test
    public void testClusterConfigProperties() {
        MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
            "clusters", "a, b",
            "a.bootstrap.servers", "servers-one",
            "b.bootstrap.servers", "servers-two",
            "security.protocol", "SASL",
            "replication.factor", "4"));
        Map<String, String> connectorProps = mirrorConfig.connectorBaseConfig(new SourceAndTarget("a", "b"),
            MirrorSourceConnector.class);
        assertEquals("source.cluster.bootstrap.servers is set",
            "servers-one", connectorProps.get("source.cluster.bootstrap.servers"));
        assertEquals("target.cluster.bootstrap.servers is set",
            "servers-two", connectorProps.get("target.cluster.bootstrap.servers"));
        assertEquals("top-level security.protocol is passed through to connector config",
            "SASL", connectorProps.get("security.protocol"));
    }

    @Test
    public void testReplicationConfigProperties() {
        MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
            "clusters", "a, b",
            "a->b.tasks.max", "123"));
        Map<String, String> connectorProps = mirrorConfig.connectorBaseConfig(new SourceAndTarget("a", "b"),
            MirrorSourceConnector.class);
        assertEquals("connector props should include tasks.max",
            "123", connectorProps.get("tasks.max"));
    }

    @Test
    public void testClientConfigProperties() {
        MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
            "clusters", "a, b",
            "config.providers", "fake",
            "config.providers.fake.class", FakeConfigProvider.class.getName(),
            "replication.policy.separator", "__",
            "ssl.truststore.password", "secret1",
            "ssl.key.password", "${fake:secret:password}",  // resolves to "secret2"
            "security.protocol", "SSL",
            "a.security.protocol", "PLAINTEXT",
            "a.producer.security.protocol", "SASL",
            "a.bootstrap.servers", "one:9092, two:9092",
            "metrics.reporter", FakeMetricsReporter.class.getName(),
            "a.metrics.reporter", FakeMetricsReporter.class.getName(),
            "b->a.metrics.reporter", FakeMetricsReporter.class.getName(),
            "a.xxx", "yyy",
            "xxx", "zzz"));
        MirrorClientConfig aClientConfig = mirrorConfig.clientConfig("a");
        MirrorClientConfig bClientConfig = mirrorConfig.clientConfig("b");
        assertEquals("replication.policy.separator is picked up in MirrorClientConfig",
            "__", aClientConfig.getString("replication.policy.separator"));
        assertEquals("replication.policy.separator is honored",
            "b__topic1", aClientConfig.replicationPolicy().formatRemoteTopic("b", "topic1"));
        assertEquals("client configs include boostrap.servers",
            "one:9092, two:9092", aClientConfig.adminConfig().get("bootstrap.servers"));
        assertEquals("client configs include security.protocol",
            "PLAINTEXT", aClientConfig.adminConfig().get("security.protocol"));
        assertEquals("producer configs include security.protocol",
            "SASL", aClientConfig.producerConfig().get("security.protocol"));
        assertFalse("unknown properties aren't included in client configs",
            aClientConfig.adminConfig().containsKey("xxx"));
        assertFalse("top-leve metrics reporters aren't included in client configs",
            aClientConfig.adminConfig().containsKey("metric.reporters"));
        assertEquals("security properties are picked up in MirrorClientConfig",
            "secret1", aClientConfig.getPassword("ssl.truststore.password").value());
        assertEquals("client configs include top-level security properties",
            "secret1", ((Password) aClientConfig.adminConfig().get("ssl.truststore.password")).value());
        assertEquals("security properties are translated from external sources",
            "secret2", aClientConfig.getPassword("ssl.key.password").value());
        assertEquals("client configs are translated from external sources",
            "secret2", ((Password) aClientConfig.adminConfig().get("ssl.key.password")).value());
        assertFalse("client configs should not include metrics reporter",
            aClientConfig.producerConfig().containsKey("metrics.reporter"));
        assertFalse("client configs should not include metrics reporter",
            bClientConfig.adminConfig().containsKey("metrics.reporter"));
    }

    @Test
    public void testIncludesConnectorConfigProperties() {
        MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
            "clusters", "a, b",
            "tasks.max", "100",
            "topics", "topic-1",
            "groups", "group-2",
            "replication.policy.separator", "__",
            "config.properties.blacklist", "property-3",
            "metric.reporters", "FakeMetricsReporter",
            "topic.filter.class", DefaultTopicFilter.class.getName(),
            "xxx", "yyy"));
        SourceAndTarget sourceAndTarget = new SourceAndTarget("source", "target");
        Map<String, String> connectorProps = mirrorConfig.connectorBaseConfig(sourceAndTarget,
            MirrorSourceConnector.class);
        MirrorConnectorConfig connectorConfig = new MirrorConnectorConfig(connectorProps);
        assertEquals("Connector properties like tasks.max should be passed through to underlying Connectors.",
            100, (int) connectorConfig.getInt("tasks.max"));
        assertEquals("Topics whitelist should be passed through to underlying Connectors.",
            Arrays.asList("topic-1"), connectorConfig.getList("topics"));
        assertEquals("Groups whitelist should be passed through to underlying Connectors.",
            Arrays.asList("group-2"), connectorConfig.getList("groups"));
        assertEquals("Config properties blacklist should be passed through to underlying Connectors.",
            Arrays.asList("property-3"), connectorConfig.getList("config.properties.blacklist"));
        assertEquals("Metrics reporters should be passed through to underlying Connectors.",
            Arrays.asList("FakeMetricsReporter"), connectorConfig.getList("metric.reporters"));
        assertEquals("Filters should be passed through to underlying Connectors.",
            "DefaultTopicFilter", connectorConfig.getClass("topic.filter.class").getSimpleName());
        assertEquals("replication policy separator should be passed through to underlying Connectors.",
            "__", connectorConfig.getString("replication.policy.separator"));
        assertFalse("Unknown properties should not be passed through to Connectors.",
            connectorConfig.originals().containsKey("xxx"));
    }

    @Test
    public void testIncludesTopicFilterProperties() {
        MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
            "clusters", "a, b",
            "source->target.topics", "topic1, topic2",
            "source->target.topics.blacklist", "topic3"));
        SourceAndTarget sourceAndTarget = new SourceAndTarget("source", "target");
        Map<String, String> connectorProps = mirrorConfig.connectorBaseConfig(sourceAndTarget,
            MirrorSourceConnector.class);
        DefaultTopicFilter.TopicFilterConfig filterConfig =
            new DefaultTopicFilter.TopicFilterConfig(connectorProps);
        assertEquals("source->target.topics should be passed through to TopicFilters.",
            Arrays.asList("topic1", "topic2"), filterConfig.getList("topics"));
        assertEquals("source->target.topics.blacklist should be passed through to TopicFilters.",
            Arrays.asList("topic3"), filterConfig.getList("topics.blacklist"));
    }

    @Test
    public void testWorkerConfigs() {
        MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
            "clusters", "a, b",
            "config.providers", "fake",
            "config.providers.fake.class", FakeConfigProvider.class.getName(),
            "replication.policy.separator", "__",
            "offset.storage.replication.factor", "123",
            "b.status.storage.replication.factor", "456",
            "b.producer.client.id", "client-one",
            "b.security.protocol", "PLAINTEXT",
            "b.producer.security.protocol", "SASL",
            "ssl.truststore.password", "secret1",
            "ssl.key.password", "${fake:secret:password}",  // resolves to "secret2"
            "b.xxx", "yyy"));
        SourceAndTarget a = new SourceAndTarget("b", "a");
        SourceAndTarget b = new SourceAndTarget("a", "b");
        Map<String, String> aProps = mirrorConfig.workerConfig(a);
        assertEquals("123", aProps.get("offset.storage.replication.factor"));
        Map<String, String> bProps = mirrorConfig.workerConfig(b);
        assertEquals("456", bProps.get("status.storage.replication.factor"));
        assertEquals("producer props should be passed through to worker producer config: " + bProps,
            "client-one", bProps.get("producer.client.id"));
        assertEquals("replication-level security props should be passed through to worker producer config",
            "SASL", bProps.get("producer.security.protocol"));
        assertEquals("replication-level security props should be passed through to worker producer config",
            "SASL", bProps.get("producer.security.protocol"));
        assertEquals("replication-level security props should be passed through to worker consumer config",
            "PLAINTEXT", bProps.get("consumer.security.protocol"));
        assertEquals("security properties should be passed through to worker config: " + bProps,
            "secret1", bProps.get("ssl.truststore.password"));
        assertEquals("security properties should be passed through to worker producer config: " + bProps,
            "secret1", bProps.get("producer.ssl.truststore.password"));
        assertEquals("security properties should be transformed in worker config",
            "secret2", bProps.get("ssl.key.password"));
        assertEquals("security properties should be transformed in worker producer config",
            "secret2", bProps.get("producer.ssl.key.password"));
    }

    public static class FakeConfigProvider implements ConfigProvider {

        Map<String, String> secrets = Collections.singletonMap("password", "secret2");

        @Override
        public void configure(Map<String, ?> props) {
        }

        @Override
        public void close() {
        }

        @Override
        public ConfigData get(String path) {
            return new ConfigData(secrets);
        }

        @Override
        public ConfigData get(String path, Set<String> keys) {
            return get(path);
        }
    }
}


text:
import { addBooleanParameter } from '@ovh-ux/ui-kit.core/src/js/component-utils';

export default class {
  constructor($attrs, $element, $timeout) {
    'ngInject';

    this.$attrs = $attrs;
    this.$element = $element;
    this.$timeout = $timeout;
  }

  $onInit() {
    addBooleanParameter(this, 'loading');
  }

  $postLink() {
    this.$timeout(() => this.$element
      .addClass('oui-tile'));
  }
}


text:
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union

from google.api_core import gapic_v1
from google.api_core import grpc_helpers_async
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore

import grpc  # type: ignore
from grpc.experimental import aio  # type: ignore

from google.cloud.monitoring_v3.types import notification
from google.cloud.monitoring_v3.types import notification_service
from google.protobuf import empty_pb2  # type: ignore
from .base import NotificationChannelServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import NotificationChannelServiceGrpcTransport

class NotificationChannelServiceGrpcAsyncIOTransport(
    NotificationChannelServiceTransport
):
    """gRPC AsyncIO backend transport for NotificationChannelService.

    The Notification Channel API provides access to configuration
    that controls how messages related to incidents are sent.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends protocol buffers over the wire using gRPC (which is built on
    top of HTTP/2); the ``grpcio`` package must be installed.
    """

    _grpc_channel: aio.Channel
    _stubs: Dict[str, Callable] = {}

    @classmethod
    def create_channel(
        cls,
        host: str = "monitoring.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        **kwargs,
    ) -> aio.Channel:
        """Create and return a gRPC AsyncIO channel object.
        Args:
            host (Optional[str]): The host for the channel to use.
            credentials (Optional[~.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If
                none are specified, the client will attempt to ascertain
                the credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            kwargs (Optional[dict]): Keyword arguments, which are passed to the
                channel creation.
        Returns:
            aio.Channel: A gRPC AsyncIO channel object.
        """

        return grpc_helpers_async.create_channel(
            host,
            credentials=credentials,
            credentials_file=credentials_file,
            quota_project_id=quota_project_id,
            default_scopes=cls.AUTH_SCOPES,
            scopes=scopes,
            default_host=cls.DEFAULT_HOST,
            **kwargs,
        )

    def __init__(
        self,
        *,
        host: str = "monitoring.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        channel: aio.Channel = None,
        api_mtls_endpoint: str = None,
        client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
        ssl_channel_credentials: grpc.ChannelCredentials = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id=None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is ignored if ``channel`` is provided.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            channel (Optional[aio.Channel]): A ``Channel`` instance through
                which to make calls.
            api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
                If provided, it overrides the ``host`` argument and tries to create
                a mutual TLS channel with client SSL credentials from
                ``client_cert_source`` or application default SSL credentials.
            client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
                Deprecated. A callback to provide client SSL certificate bytes and
                private key bytes, both in PEM format. It is ignored if
                ``api_mtls_endpoint`` is None.
            ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
                for the grpc channel. It is ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
                A callback to provide client certificate bytes and private key bytes,
                both in PEM format. It is used to configure a mutual TLS channel. It is
                ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
              creation failed for any reason.
          google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """
        self._grpc_channel = None
        self._ssl_channel_credentials = ssl_channel_credentials
        self._stubs: Dict[str, Callable] = {}

        if api_mtls_endpoint:
            warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
        if client_cert_source:
            warnings.warn("client_cert_source is deprecated", DeprecationWarning)

        if channel:
            # Ignore credentials if a channel was passed.
            credentials = False
            # If a channel was explicitly provided, set it.
            self._grpc_channel = channel
            self._ssl_channel_credentials = None
        else:
            if api_mtls_endpoint:
                host = api_mtls_endpoint

                # Create SSL credentials with client_cert_source or application
                # default SSL credentials.
                if client_cert_source:
                    cert, key = client_cert_source()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )
                else:
                    self._ssl_channel_credentials = SslCredentials().ssl_credentials

            else:
                if client_cert_source_for_mtls and not ssl_channel_credentials:
                    cert, key = client_cert_source_for_mtls()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )

        # The base transport sets the host, credentials and scopes
        super().__init__(
            host=host,
            credentials=credentials,
            credentials_file=credentials_file,
            scopes=scopes,
            quota_project_id=quota_project_id,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )

        if not self._grpc_channel:
            self._grpc_channel = type(self).create_channel(
                self._host,
                # use the credentials which are saved
                credentials=self._credentials,
                # Set ``credentials_file`` to ``None`` here as
                # the credentials that we saved earlier should be used.
                credentials_file=None,
                scopes=self._scopes,
                ssl_credentials=self._ssl_channel_credentials,
                quota_project_id=quota_project_id,
                options=[
                    ("grpc.max_send_message_length", -1),
                    ("grpc.max_receive_message_length", -1),
                ],
            )

        # Wrap messages. This must be done after self._grpc_channel exists
        self._prep_wrapped_messages(client_info)

    @property
    def grpc_channel(self) -> aio.Channel:
        """Create the channel designed to connect to this service.

        This property caches on the instance; repeated calls return
        the same channel.
        """
        # Return the channel from cache.
        return self._grpc_channel

    @property
    def list_notification_channel_descriptors(
        self,
    ) -> Callable[
        [notification_service.ListNotificationChannelDescriptorsRequest],
        Awaitable[notification_service.ListNotificationChannelDescriptorsResponse],
    ]:
        r"""Return a callable for the list notification channel
        descriptors method over gRPC.

        Lists the descriptors for supported channel types.
        The use of descriptors makes it possible for new channel
        types to be dynamically added.

        Returns:
            Callable[[~.ListNotificationChannelDescriptorsRequest],
                    Awaitable[~.ListNotificationChannelDescriptorsResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_notification_channel_descriptors" not in self._stubs:
            self._stubs[
                "list_notification_channel_descriptors"
            ] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/ListNotificationChannelDescriptors",
                request_serializer=notification_service.ListNotificationChannelDescriptorsRequest.serialize,
                response_deserializer=notification_service.ListNotificationChannelDescriptorsResponse.deserialize,
            )
        return self._stubs["list_notification_channel_descriptors"]

    @property
    def get_notification_channel_descriptor(
        self,
    ) -> Callable[
        [notification_service.GetNotificationChannelDescriptorRequest],
        Awaitable[notification.NotificationChannelDescriptor],
    ]:
        r"""Return a callable for the get notification channel
        descriptor method over gRPC.

        Gets a single channel descriptor. The descriptor
        indicates which fields are expected / permitted for a
        notification channel of the given type.

        Returns:
            Callable[[~.GetNotificationChannelDescriptorRequest],
                    Awaitable[~.NotificationChannelDescriptor]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_notification_channel_descriptor" not in self._stubs:
            self._stubs[
                "get_notification_channel_descriptor"
            ] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/GetNotificationChannelDescriptor",
                request_serializer=notification_service.GetNotificationChannelDescriptorRequest.serialize,
                response_deserializer=notification.NotificationChannelDescriptor.deserialize,
            )
        return self._stubs["get_notification_channel_descriptor"]

    @property
    def list_notification_channels(
        self,
    ) -> Callable[
        [notification_service.ListNotificationChannelsRequest],
        Awaitable[notification_service.ListNotificationChannelsResponse],
    ]:
        r"""Return a callable for the list notification channels method over gRPC.

        Lists the notification channels that have been
        created for the project.

        Returns:
            Callable[[~.ListNotificationChannelsRequest],
                    Awaitable[~.ListNotificationChannelsResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_notification_channels" not in self._stubs:
            self._stubs["list_notification_channels"] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/ListNotificationChannels",
                request_serializer=notification_service.ListNotificationChannelsRequest.serialize,
                response_deserializer=notification_service.ListNotificationChannelsResponse.deserialize,
            )
        return self._stubs["list_notification_channels"]

    @property
    def get_notification_channel(
        self,
    ) -> Callable[
        [notification_service.GetNotificationChannelRequest],
        Awaitable[notification.NotificationChannel],
    ]:
        r"""Return a callable for the get notification channel method over gRPC.

        Gets a single notification channel. The channel
        includes the relevant configuration details with which
        the channel was created. However, the response may
        truncate or omit passwords, API keys, or other private
        key matter and thus the response may not be 100%
        identical to the information that was supplied in the
        call to the create method.

        Returns:
            Callable[[~.GetNotificationChannelRequest],
                    Awaitable[~.NotificationChannel]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_notification_channel" not in self._stubs:
            self._stubs["get_notification_channel"] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/GetNotificationChannel",
                request_serializer=notification_service.GetNotificationChannelRequest.serialize,
                response_deserializer=notification.NotificationChannel.deserialize,
            )
        return self._stubs["get_notification_channel"]

    @property
    def create_notification_channel(
        self,
    ) -> Callable[
        [notification_service.CreateNotificationChannelRequest],
        Awaitable[notification.NotificationChannel],
    ]:
        r"""Return a callable for the create notification channel method over gRPC.

        Creates a new notification channel, representing a
        single notification endpoint such as an email address,
        SMS number, or PagerDuty service.

        Returns:
            Callable[[~.CreateNotificationChannelRequest],
                    Awaitable[~.NotificationChannel]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "create_notification_channel" not in self._stubs:
            self._stubs["create_notification_channel"] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/CreateNotificationChannel",
                request_serializer=notification_service.CreateNotificationChannelRequest.serialize,
                response_deserializer=notification.NotificationChannel.deserialize,
            )
        return self._stubs["create_notification_channel"]

    @property
    def update_notification_channel(
        self,
    ) -> Callable[
        [notification_service.UpdateNotificationChannelRequest],
        Awaitable[notification.NotificationChannel],
    ]:
        r"""Return a callable for the update notification channel method over gRPC.

        Updates a notification channel. Fields not specified
        in the field mask remain unchanged.

        Returns:
            Callable[[~.UpdateNotificationChannelRequest],
                    Awaitable[~.NotificationChannel]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "update_notification_channel" not in self._stubs:
            self._stubs["update_notification_channel"] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/UpdateNotificationChannel",
                request_serializer=notification_service.UpdateNotificationChannelRequest.serialize,
                response_deserializer=notification.NotificationChannel.deserialize,
            )
        return self._stubs["update_notification_channel"]

    @property
    def delete_notification_channel(
        self,
    ) -> Callable[
        [notification_service.DeleteNotificationChannelRequest],
        Awaitable[empty_pb2.Empty],
    ]:
        r"""Return a callable for the delete notification channel method over gRPC.

        Deletes a notification channel.

        Returns:
            Callable[[~.DeleteNotificationChannelRequest],
                    Awaitable[~.Empty]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "delete_notification_channel" not in self._stubs:
            self._stubs["delete_notification_channel"] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/DeleteNotificationChannel",
                request_serializer=notification_service.DeleteNotificationChannelRequest.serialize,
                response_deserializer=empty_pb2.Empty.FromString,
            )
        return self._stubs["delete_notification_channel"]

    @property
    def send_notification_channel_verification_code(
        self,
    ) -> Callable[
        [notification_service.SendNotificationChannelVerificationCodeRequest],
        Awaitable[empty_pb2.Empty],
    ]:
        r"""Return a callable for the send notification channel
        verification code method over gRPC.

        Causes a verification code to be delivered to the channel. The
        code can then be supplied in ``VerifyNotificationChannel`` to
        verify the channel.

        Returns:
            Callable[[~.SendNotificationChannelVerificationCodeRequest],
                    Awaitable[~.Empty]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "send_notification_channel_verification_code" not in self._stubs:
            self._stubs[
                "send_notification_channel_verification_code"
            ] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/SendNotificationChannelVerificationCode",
                request_serializer=notification_service.SendNotificationChannelVerificationCodeRequest.serialize,
                response_deserializer=empty_pb2.Empty.FromString,
            )
        return self._stubs["send_notification_channel_verification_code"]

    @property
    def get_notification_channel_verification_code(
        self,
    ) -> Callable[
        [notification_service.GetNotificationChannelVerificationCodeRequest],
        Awaitable[notification_service.GetNotificationChannelVerificationCodeResponse],
    ]:
        r"""Return a callable for the get notification channel
        verification code method over gRPC.

        Requests a verification code for an already verified
        channel that can then be used in a call to
        VerifyNotificationChannel() on a different channel with
        an equivalent identity in the same or in a different
        project. This makes it possible to copy a channel
        between projects without requiring manual reverification
        of the channel. If the channel is not in the verified
        state, this method will fail (in other words, this may
        only be used if the
        SendNotificationChannelVerificationCode and
        VerifyNotificationChannel paths have already been used
        to put the given channel into the verified state).

        There is no guarantee that the verification codes
        returned by this method will be of a similar structure
        or form as the ones that are delivered to the channel
        via SendNotificationChannelVerificationCode; while
        VerifyNotificationChannel() will recognize both the
        codes delivered via
        SendNotificationChannelVerificationCode() and returned
        from GetNotificationChannelVerificationCode(), it is
        typically the case that the verification codes delivered
        via
        SendNotificationChannelVerificationCode() will be
        shorter and also have a shorter expiration (e.g. codes
        such as "G-123456") whereas GetVerificationCode() will
        typically return a much longer, websafe base 64 encoded
        string that has a longer expiration time.

        Returns:
            Callable[[~.GetNotificationChannelVerificationCodeRequest],
                    Awaitable[~.GetNotificationChannelVerificationCodeResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_notification_channel_verification_code" not in self._stubs:
            self._stubs[
                "get_notification_channel_verification_code"
            ] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/GetNotificationChannelVerificationCode",
                request_serializer=notification_service.GetNotificationChannelVerificationCodeRequest.serialize,
                response_deserializer=notification_service.GetNotificationChannelVerificationCodeResponse.deserialize,
            )
        return self._stubs["get_notification_channel_verification_code"]

    @property
    def verify_notification_channel(
        self,
    ) -> Callable[
        [notification_service.VerifyNotificationChannelRequest],
        Awaitable[notification.NotificationChannel],
    ]:
        r"""Return a callable for the verify notification channel method over gRPC.

        Verifies a ``NotificationChannel`` by proving receipt of the
        code delivered to the channel as a result of calling
        ``SendNotificationChannelVerificationCode``.

        Returns:
            Callable[[~.VerifyNotificationChannelRequest],
                    Awaitable[~.NotificationChannel]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "verify_notification_channel" not in self._stubs:
            self._stubs["verify_notification_channel"] = self.grpc_channel.unary_unary(
                "/google.monitoring.v3.NotificationChannelService/VerifyNotificationChannel",
                request_serializer=notification_service.VerifyNotificationChannelRequest.serialize,
                response_deserializer=notification.NotificationChannel.deserialize,
            )
        return self._stubs["verify_notification_channel"]

    def close(self):
        return self.grpc_channel.close()

__all__ = ("NotificationChannelServiceGrpcAsyncIOTransport",)


text:
<?php

/** Docker testing */
ini_set( 'display_errors', 0 );
define( 'WP_DEBUG_DISPLAY', false );
define( 'SCRIPT_DEBUG', false );
/** Disable all file modifications including updates and update notifications */
define( 'DISALLOW_FILE_MODS', true );


text:
div.mean-container {
    width: 80%;
}

div.container-table-unit-test .table-body {
    width: 100%;
    height: 500px;
    overflow-y: auto;
}

div.container-table-unit-test table {
    width: 100%;
    margin-bottom: 0;
    table-layout:fixed;
}

div.container-table-unit-test table thead {
    width: 100%;
}

div.container-table-unit-test table tbody {
    width: 100%;
    overflow: hidden;
}

div.container-table-unit-test table .column-nro-1 abbr {
    cursor: default;
    border-bottom: none;
}

div.container-table-unit-test table .column-nro-1 {
    width: 30%;
    overflow:hidden;
    white-space:nowrap;
    text-overflow: ellipsis;
}

div.container-table-unit-test table .column-nro-2 {
    width: 10%;
}

div.container-table-unit-test table .column-nro-3 {
    width: 30%;
}

div.container-table-unit-test table .column-nro-4 {
    width: 30%;
}


text:
<?php

namespace vox\AdminBundle\Service;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraints\DateTime;
use vox\AdminBundle\Entity\FacebookStats;
use vox\AdminBundle\Entity\SoundCloudStats;
use vox\AdminBundle\Entity\YoutubeStats;
use SimpleXMLElement;

class MediaUpdate {

    protected $em;

    public function __construct(EntityManager $em) {

        $this->em = $em;
    }

    public function updateAll() {
        $this->facebook();
        $this->youtube();
        $this->soundcloud();

        return "everything updated";
    }

    public function facebook() {

        $fp = fopen('https://graph.facebook.com/voxpopulirecords?fields=likes', 'r');
        $str = stream_get_contents($fp);
        $likes = json_decode($str)->likes;
        fclose($fp);

        $facebookStats = new FacebookStats();
        $facebookStats->setLikes($likes);
        $facebookStats->setDate(new \DateTime());

        $this->em->persist($facebookStats);
        $this->em->flush();

        return 'facebook stats updated';
    }

    public function youtube() {

        $data = file_get_contents("http://gdata.youtube.com/feeds/api/users/v0xpopulirecords");

        $xml = new SimpleXMLElement($data);
        $stats_data = (array)$xml->children('yt', true)->statistics->attributes();
        $stats_data = $stats_data['@attributes'];

        $youtubeStats = new YoutubeStats();
        $youtubeStats->setSubs($stats_data['subscriberCount']);
        $youtubeStats->setTotalViews($stats_data['totalUploadViews']);
        $youtubeStats->setDate(new \DateTime());

        $this->em->persist($youtubeStats);
        $this->em->flush();

        return "youtube updated";
    }

    public function soundcloud () {

        $sc_content = file_get_contents("http://api.soundcloud.com/users/voxpopuli-records?consumer_key=726de19451503113d25d881bec2d2d67");
        $sc_xml = simplexml_load_string($sc_content);

        $soundcloudStats = new SoundCloudStats();
        $soundcloudStats->setFollowers($sc_xml -> {'followers-count'});
        $soundcloudStats->setDate(new \DateTime());

        $this->em->persist($soundcloudStats);
        $this->em->flush();

        return "soundcloud updated";
    }

}


text:
![Ruby](https://github.com/philihp/tarot/workflows/Ruby/badge.svg)
[![Build Status](https://travis-ci.com/philihp/tarot.svg?branch=master)](https://travis-ci.com/philihp/tarot)

# Tarot

This is an implementation of Kingdominion that I wrote so I could write an AI to play against.

## Using it

Fire up a console

    bin/console

Then create an initial gamestate with

    state = Tarot::State.new

You can check out the available moves with

    state.available_moves

Or try out one of the moves with

    state2 = state.play_move(move: game.available_moves.sample)

Each command you run should duplicate the state, muck around with the new one, and then freeze it,
so you can also still keep doing this and try different moves

    state3 = state.play_move(move: game.available_moves.sample)
    state4 = state.play_move(move: game.available_moves.sample)
    state5 = state.play_move(move: game.available_moves.sample)

## Notes

### State Phases

* `:init_claim`
* `:init_commit`
Repeat until all old_claims are taken
* `:claim`
* `:place`
* `:commit`

### What's the deal with rand?

It's important to explicitly define the random seed, so that the same gamelist can be played through
repeatedly without having to reshuffle the tiles. However, the computer AI can't be allowed ot have
knowledge of the tiles to be drawn, because the computer can't cheat.

One method of tackling this would be to develop a heuristic where the computer looks at the
distribution of tiles left; sort of like card counting in blackjack... however this really bakes in
the strategy that the AI will use and makes it relatively predictable. The advantage here, however,
is that it would allow us to go relatively deep in the game-state-space.

Another strategy would a stochastic monte carlo search the same moves a handful of times. The idea
here is that the move (especially a later-game move) might be good 50% of the time, so let's go for
it, while a bad move might only be good 10% of the time. Usually it's going to pick a decent move.

Another benefit of going about it this way is the computer will never play perfectly. Sometimes it
will make a wildcard play that appears to be bad, even though in its imagined trials, it happened
to luck out.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

## Thanks

* https://github.com/PragTob/rubykon - for his ruby implementation of MCTS, of which this was derived.

* https://github.com/dbravender/tilerealm - for his python implementation of the game. It turns out enumerating possible places to drop a tile is hard.


text:
#include "tensorflow/lite/delegates/gpu/gl/kernels/pad.h"

#include <algorithm>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

#include "absl/memory/memory.h"
#include "tensorflow/lite/delegates/gpu/common/operations.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
#include "tensorflow/lite/delegates/gpu/gl/variable.h"

namespace tflite {
namespace gpu {
namespace gl {
namespace {

class Pad : public NodeShader {
 public:
  Status GenerateCode(const GenerationContext& ctx,
                      GeneratedCode* generated_code) const final {
    auto input = ctx.graph->FindInputs(ctx.node->id)[0];
    auto attr = absl::any_cast<PadAttributes>(ctx.node->operation.attributes);

    if (attr.type != PaddingContentType::ZEROS) {
      return UnimplementedError(
          "Padding with content type ~= ZEROS is not supported.");
    }
    if (attr.appended.h < 0 || attr.appended.w < 0 || attr.appended.c < 0 ||
        attr.prepended.h < 0 || attr.prepended.w < 0 || attr.prepended.c < 0) {
      return UnimplementedError("Negative padding is not supported.");
    }
    std::vector<Variable> parameters = {
        {"input_data_0_h", input->tensor.shape.h},
        {"input_data_0_w", input->tensor.shape.w},
        {"prepended",
         int4(attr.prepended.w, attr.prepended.h, attr.prepended.c, 0)},
        {"src_channels", input->tensor.shape.c},
    };

    std::string source = R"(
  int src_x = gid.x - $prepended.x$;
  int src_y = gid.y - $prepended.y$;
  if (src_x >= 0 && src_x < $input_data_0_w$ && src_y >= 0 && src_y < $input_data_0_h$) {
    int start_channel = gid.z * 4;
    for (int i = 0; i < 4; ++i) {
      int channel = start_channel + i;
      int src_z = channel - $prepended.z$;
      if (src_z >= 0 && src_z < $src_channels$) {
        value_0[i] = $input_data_0[src_x, src_y, src_z / 4]$[src_z % 4];
      }
    }
  }
)";
    *generated_code = {
        /*parameters=*/std::move(parameters),
        /*objects=*/{},
        /*shared_variables=*/{},
        /*workload=*/uint3(),
        /*workgroup=*/uint3(),
        /*source_code=*/std::move(source),
        /*input=*/IOStructure::ONLY_DEFINITIONS,
        /*output=*/IOStructure::AUTO,
    };
    return OkStatus();
  }
};

}  // namespace

std::unique_ptr<NodeShader> NewPadNodeShader() {
  return absl::make_unique<Pad>();
}

}  // namespace gl
}  // namespace gpu
}  // namespace tflite


text:
module Furnace::AVM2::ABC
  class AS3DecrementI < ArithmeticOpcode
    instruction 0xc1

    consume 1
    produce 1

    type :integer
    ast_type :decrement
  end
end


text:
var useImages = false,
    cancelable = null;

$.show = show;
$.hide = hide;
$.update = update;
$.cancel = cancel;

Object.defineProperty($, 'visible', {
    get: function() {
        return $.loadingMask.visible;
    },
    set: function(visible) {
        return visible ? show() : hide();
    }
});

(function constructor(args) {

    if ($.loadingMask.images) {
        useImages = true;

        $.loadingInner.remove($.loadingIndicator);
        $.loadingIndicator = null;

    } else {
        $.loadingInner.remove($.loadingImages);
        $.loadingImages = null;
    }

    update(args.message, args.cancelable);

    args = null;

})(arguments[0] || {});

function update(_message, _cancelable) {
    $.loadingMessage.text = _message || L('loadingMessage', 'Loading...');
    cancelable = _cancelable;
}

function cancel() {

    if (_.isFunction(cancelable)) {
        cancelable();

        $.trigger('cancel');

        hide();
    }
}

function show(_message, _cancelable) {
    update(_message, _cancelable);

    $.loadingMask.show();

    if (useImages) {
        $.loadingImages.start();
    } else {
        $.loadingIndicator.show();
    }
}

function hide() {
    $.loadingMask.hide();
}


text:
import os
import platform
import subprocess

import pytest

from topaz.main import _entry_point

class TestMain(object):
    def run(self, space, tmpdir, file=None, status=0, ruby_args=[], argv=[]):
        args = ["topaz"]
        args += ruby_args
        f = os.path.abspath(os.path.join(__file__, "..", "constraintfixtures", file))
        args.append(str(f))
        args += argv
        res = _entry_point(space, args)
        assert res == status
        return f

    # this version of the program outputs the solution rather than just saying that it worked
    def test_smm(self, space, tmpdir, capfd):
        self.run(space, tmpdir, "smm.rb")
        out, err = capfd.readouterr()
        assert out.split('\n')[-2] == u"solution: [s,e,n,d,m,o,r,y] = [9, 5, 6, 7, 1, 0, 8, 2]"


text:
create view "Current Product List" AS
SELECT Product_List.ProductID, Product_List.ProductName
FROM Products AS Product_List
WHERE (((Product_List.Discontinued)=0))
--ORDER BY Product_List.ProductName


text:
function urldecode(str) {
  return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

// Get params --
// Source : http://stackoverflow.com/questions/10001726/access-get-variables-using-jquery-javascript
function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = urldecode(hash[1]);
  }
  return vars;
}

$(document).ready(function() {
  var params = getUrlVars();
  console.log(params);

  params['first'] = parseInt(params['first']);
  params['end'] = parseInt(params['end']);

  if(isNaN(params['first']) || isNaN(params['end'])) { // Display the form --
    console.log('Form');
  }
  else { // Display the result --
    console.log('Results');
    $('#form').hide();

    var container = $('#display');

    // Prepare keys' label --
    var keyLabels = {
      'exp':    'Expérience :',
      'person': 'Personne concernée :',
      'souche': 'Souche :',
      'gender': 'Sexe :',
      'age':    'Age :',
      'source': 'Provenance :',
      'number': 'Lot N° :',
      'ethics': 'N° Com. ETH :',
      'expend': 'Fin d\'expé :'
    };

    // Prepare gender --
    params['gender'] = params['gender'] == 1 ? 'M' : 'F';

    // For each label --
    for(var i = params['first']; i <= params['end']; i++) {
      var item = '
';

      // For each info in the label --
      for (var key in params){
        if (isNaN(parseInt(key)) && key != 'first' && key != 'end') { // Textual --
          item += '

'
            + keyLabels[key]
            + '

'
            + params[key]
            + '

';
        }
      }

      // Number and end --
      item += '
' + i + '
';
      item += '
';

      container.append(item);
    }
  }
});