text:
namespace blink {

void V8PromiseRejectionEvent::promiseAttributeGetterCustom(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Isolate* isolate = info.GetIsolate();
  PromiseRejectionEvent* event = V8PromiseRejectionEvent::toImpl(info.Holder());
  ScriptPromise promise = event->promise(ScriptState::current(isolate));
  if (promise.isEmpty()) {
    v8SetReturnValue(info, v8::Null(isolate));
    return;
  }

  v8SetReturnValue(info, promise.v8Value());
}

void V8PromiseRejectionEvent::visitDOMWrapperCustom(
    v8::Isolate* isolate,
    ScriptWrappable* scriptWrappable,
    const v8::Persistent<v8::Object>& wrapper) {
  PromiseRejectionEvent* event =
      scriptWrappable->toImpl<PromiseRejectionEvent>();
  event->setWrapperReference(isolate, wrapper);
}

}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace VCAPI\Model;

use VCAPI\Common\Collection;
use VCAPI\Common\Error;
use VCAPI\Common\Request;

class Corporations {

    public $instanceIdentifier = '';

    public function __construct($instanceIdentifier = '') {
        $this->instanceIdentifier = $instanceIdentifier;

        $this->getShortList();
    }

    /**
     * @return mixed
     * @throws \ErrorException
     */
    public function getShortList() {
        $result = Request::get('/corporations/corporation_list.json', $this->instanceIdentifier);

        if (!empty($result->error)) {
            Error::exception($result->setFlash[0]->msg);
        }

        return $result->corporations;
    }

    /**
     * @return Collection
     */
    public function getAll() {
        $list = new Collection();
        $items = $this->getShortList();

        if(empty($items)) {
            return $list;
        }

        foreach($items as $item) {
            $list->add(new Corporation($item->id, $this->instanceIdentifier));
        }

        return $list;
    }

}


text:
by Scumdog Steev / Steve Myles

License:  [MIT License](https://github.com/scumdogsteev/mls-junk-generator/blob/master/LICENSE)

About:  This is a pseudo-random number generator implemented in Excel/VBA and [R](https://github.com/scumdogsteev/mls-junk-generatR).

Project Home:  http://steve.mylesandmyles.info/projects/mls-junk-generator/

Algorithm:
```
For any seed values of w, x, y, z:
r_i = 5.980217w^2 + 9.446377x^0.25 + 4.81379y^0.33 + 8.91197z^0.5
r_i = r_i - Int(r_i) For r_i+1:
w = x
x = y
y = z
z = r_i
```

Files:

1. [mls_junk_generator1.xlsm](https://github.com/scumdogsteev/mls-junk-generator/blob/master/mls_junk_generator1.xlsm) - simple Excel implementation

2. [mls_junk_generator.bas](https://github.com/scumdogsteev/mls-junk-generator/blob/master/mls_junk_generator.bas) - VBA source for #1

3. [mls_junk_generator2.xlsm](https://github.com/scumdogsteev/mls-junk-generator/blob/master/mls_junk_generator2.xlsm) - second Excel implementation (allows for clearing of the RN stream)

4. [MLSJunkGen.bas](https://github.com/scumdogsteev/mls-junk-generator/blob/master/MLSJunkGen.bas) - VBA module for #3

Project Info:

* VBA Source last updated: 2015.01.31
* Originally posted online: 2012.07.06
* Moved to GitHub: 2015.02.01


text:
package org.xbib.tools;

import org.elasticsearch.common.settings.Settings;
import org.xbib.pipeline.PipelineRequest;
import org.xbib.pipeline.element.PipelineElement;

public class SettingsPipelineElement implements PipelineElement<Settings>, PipelineRequest {

    private Settings settings;

    @Override
    public Settings get() {
        return settings;
    }

    @Override
    public SettingsPipelineElement set(Settings settings) {
        this.settings = settings;
        return this;
    }

    @Override
    public String toString() {
        return settings.getAsMap().toString();
    }
}


text:
	Why? MooTools features mouseenter and mouseleave because mouseover/mouseout sometimes
	just does not work as expected. Mouseenter only fires once you enter the element and
	does not fire again if your mouse crosses over children of the element.

Menu Example

	This example explains how to open a menu-like element on mouseenter and
	how it closes again on mouseleave.

	Menu

		Menuelement 1
		Menuelement 2
		Menuelement 3


text:
/**
 * Main application file
 */

'use strict';

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var express 	= require('express');
var mongoose 	= require('mongoose');
var redis 		= require("redis"),
		client 		= redis.createClient();
var config 		= require('./config/environment');

// Connect to redis
client.on("error", function (err) {
	console.log("Error " + err);
});

// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);

// Setup server
var app = express();
var server = require('http').createServer(app);

require('./config/express')(app);
require('./api/user')(app);
require('./routes')(app);

// Start server
server.listen(3000, config.ip, function () {
  console.log('Express server listening on %d, in %s mode', 3000, app.get('env'));
});

// Expose app
exports = module.exports = app;


text:
dev-base
========

Docker development base image


text:
#ifndef DNS_LOOKUP_H
#define DNS_LOOKUP_H

struct dns_lookup_settings {
	const char *dns_client_socket_path;
	unsigned int timeout_msecs;
};

struct dns_lookup_result {
	/* all is ok if ret=0, otherwise it contains net_gethosterror()
	   compatible error code. error string is always set if ret != 0. */
	int ret;
	const char *error;

	/* how many milliseconds the lookup took. */
	unsigned int msecs;

	unsigned int ips_count;
	const struct ip_addr *ips;
};

typedef void dns_lookup_callback_t(const struct dns_lookup_result *result,
				   void *context);

int dns_lookup(const char *host, const struct dns_lookup_settings *set,
	       dns_lookup_callback_t *callback, void *context);
#define dns_lookup(host, set, callback, context) \
	CONTEXT_CALLBACK2(dns_lookup, dns_lookup_callback_t, \
			  callback, const struct dns_lookup_result *, \
			  context, host, set)

#endif


text:
import {Field, Form as FormikForm, Formik, FormikBag, FormikErrors, FormikProps, withFormik} from "formik";
import * as React from "react";
import * as Yup from "yup";
import {Organization} from "../../store/organization/types";

import {
    Button,
    Divider,
    Label,
    Form,
    Header,
    Icon,
    Grid
} from "semantic-ui-react";

export interface IOrganizationFormProps {
    data?: Organization;
    id?: string | number;
    loading: boolean;
    onSubmit: (values: IOrganizationFormValues) => void;
}

export interface IOrganizationFormValues extends Organization {

}

const initialValues: IOrganizationFormValues = {
    name: "",
    payload_prefix: "org.github.cmdmnt",
    x509_c: "US",
    x509_o: "",
    x509_ou: "",
    x509_st: "",
};

const InnerForm = ({
   handleSubmit,
   handleChange,
   handleBlur,
   values,
   errors,
   touched,
   isSubmitting,
}: FormikProps<IOrganizationFormValues>) => (
    <Form onSubmit={handleSubmit}>
        <Form.Field required>
            Name
            <input type="text" name="name"
                   placeholder="Acme Inc."
                   onChange={handleChange} onBlur={handleBlur}
                   value={values.name}/>

            {errors.name &&
            touched.name &&
            {errors.name}}
        </Form.Field>

        <Form.Field required>
            Payload Prefix
            <input type="text" name="payload_prefix"
                   onChange={handleChange} onBlur={handleBlur}
                   placeholder="com.acme"
                   value={values.payload_prefix}/>

            {errors.payload_prefix &&
            touched.payload_prefix &&
            {errors.payload_prefix}}
        </Form.Field>

        <Icon name="certificate"/> Certificate Details
        <Grid columns={2}>
            <Grid.Column>
                <Form.Field>
                    X.509 Organizational Unit
                    <input type="text" name="x509_ou"
                           onChange={handleChange} onBlur={handleBlur}
                           placeholder="IT Department"
                           value={values.x509_ou}/>

                    {errors.x509_ou &&
                    touched.x509_ou &&
                    {errors.x509_ou}}
                </Form.Field>
                <Form.Field>
                    X.509 Organization
                    <input type="text" name="x509_o"
                           onChange={handleChange} onBlur={handleBlur}
                           placeholder="Acme Inc."
                           value={values.x509_o}/>

                    {errors.x509_o &&
                    touched.x509_o &&
                    {errors.x509_o}}
                </Form.Field>
            </Grid.Column>
            <Grid.Column>
                <Form.Field>
                    X.509 State
                    <input type="text" name="x509_st"
                           onChange={handleChange} onBlur={handleBlur}
                           value={values.x509_st}/>

                    {errors.x509_st &&
                    touched.x509_st &&
                    {errors.x509_st}}
                </Form.Field>
                <Form.Field>
                    X.509 Country Code
                    <input type="text" name="x509_c"
                           onChange={handleChange} onBlur={handleBlur}
                           placeholder="US"
                           value={values.x509_c}/>

                    {errors.x509_c &&
                    touched.x509_c &&
                    {errors.x509_c}}
                </Form.Field>
            </Grid.Column>
        </Grid>

        <Divider hidden/>

        <Button type="submit" disabled={isSubmitting} primary>
            Update
        </Button>
    </Form>
);

export const OrganizationForm = withFormik<IOrganizationFormProps, IOrganizationFormValues>({
    displayName: "OrganizationForm",
    enableReinitialize: true,
    handleSubmit: (values, formikBag: FormikBag<IOrganizationFormProps, IOrganizationFormValues>) => {
        formikBag.props.onSubmit(values);
        formikBag.setSubmitting(false);
    },

    mapPropsToValues: (props) => {
        return props.data || initialValues;
    },

    validationSchema: Yup.object().shape({
        name: Yup.string().required("Required"),
        payload_prefix: Yup.string().required("Required"),
    }),
})(InnerForm);


text:
package com.kashoo.ws

import org.scalatest.{FlatSpec, Matchers}
import play.api.Configuration
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import scala.concurrent.ExecutionContext.Implicits.global

class RequestRateLimitSpec extends FlatSpec with Matchers with MockitoSugar {

  trait TestScope {
    val mockRateConfig = mock[Configuration]
    val mockInnerRateConfig = mock[Configuration]
    when(mockRateConfig.getOptional[Configuration]("rate1")).thenReturn(Some(mockInnerRateConfig))
    when(mockInnerRateConfig.getOptional[Int]("queries")).thenReturn(Some(5))
    when(mockInnerRateConfig.getOptional[String]("period")).thenReturn(Some("5 seconds"))

    val mockRateLimitConfig = mock[Configuration]
    when(mockRateLimitConfig.getOptional[String]("host")).thenReturn(Some("example.com"))

    def fullVerify = {
      verify(mockRateLimitConfig).getOptional[String]("rate")
      verify(mockRateLimitConfig).getOptional[String]("host")
      verify(mockRateLimitConfig).getOptional[Int]("port")
      verify(mockRateLimitConfig).getOptional[String]("path")
    }
  }

  "RequestRateLimit" should "instantiate from a full, valid configuration" in new TestScope() {
    when(mockRateLimitConfig.getOptional[String]("rate")).thenReturn(Some("rate1"))

    RequestRateLimit(mockRateConfig, mockRateLimitConfig)

    fullVerify
  }

  it should "throw an exception when instantiated from a configuration without a rate" in new TestScope() {
    when(mockRateLimitConfig.getOptional[String]("rate")).thenReturn(None)

    intercept[IllegalStateException] {
      RequestRateLimit(mockRateConfig, mockRateLimitConfig)
    }
  }

}


text:
<?php session_start();?>
<!DOCTYPE html>
          <?php require('header.php');?>
    <?php require('sidebar.php');?>

		<form method = POST>
<legend > Equipment Maintenance </legend>

	<input name="search" id="search" placeholder = "Input Business Name"/>
    <button class="btn btn-info" name = "s1">Search</button></form>

<?php if(isset($_POST['s1'])){
$_SESSION['s'] = $_POST['search'];
	echo "";}?>
	<button  class="btn btn-info" onclick = "window.location.href='EquipmentAdd.php'">Add Equipment</button>

						 Equipment
						 Category
						 Quantity
						 EDIT

<?php
					require('connection.php');
					$s = $_SESSION['s'];
						$sql = "select * from tblequipment where strEquipCode LIKE '%$s%'";
						$query = mysqli_query($con, $sql);

						if(mysqli_num_rows($query) > 0){
							$i = 1;

							while($row = mysqli_fetch_object($query)){?>

 <?php echo $row->strEquipCode?>
									<?php

								$query2 = mysqli_query($con,"Select * from tblCategory where strcategorycode = '$row->strCategoryCode'");

								if(mysqli_num_rows($query2) > 0){

									while($row1 = mysqli_fetch_object($query2)){
										echo  $row1->strCategoryDesc;

									}
								}
					?>
									<?php echo $row->intQuantity?>
									<button class= "btn btn-success"  type = submit name = "btnEdit" id = "btnEdit" value = <?php echo $row->intEquipno; ?> >EDIT</button>

		<?php }} ?>

				<?php
					if(isset($_POST['btnEdit'])){
						$equipcode = $_POST['btnEdit'];
						$query = mysqli_query($con,"Select * from tblEquipment where intEquipno = '$equipcode'");
							$row = mysqli_fetch_object($query);
							$_SESSION['contno'] = $equipcode;
							$_SESSION['stat'] = $row->intQuantity;

							$query2 = mysqli_query($con,"Select * from tblCategory where strCategoryCode = '$row->strCategoryCode'");
							$row2 = mysqli_fetch_object($query2);
							$_SESSION['cat'] = $row2->strCategoryDesc;

							echo "";
					}?>
                    </form>

<! --/wrapper -->


text:
package samples.reporting;

import com.messagebus.client.MessageBusFactory;
import com.messagebus.client.spi.*;
import com.messagebus.client.v5.client.MessageBusReportingClient;
import com.messagebus.client.v5.model.MessageBusException;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;

/**
 * This example tells Message Bus to asynchronously create a feedback report
 *

 * Update with YOUR_API_KEY, verify the DOMAIN and use Maven to compile. From the top directory :
 *

 * messagebus-java-sdk>  mvn clean install
 *

 * To run this example use Maven. From the top directory :
 *

 * messagebus-java-sdk> mvn exec:java  -Dexec.mainClass="examples.api.ExampleGetReport"
 */
public class SampleCreateFeedbackReport {

    String channelKey= "<YOUR_CHANNEL_KEY>";
    String sessionKey= "<YOUR_SESSION_KEY>";

    private MessageBusReportingClient messageBusReportingClient;

    public SampleCreateFeedbackReport(MessageBusReportingClient messageBusReportingClient) {
        this.messageBusReportingClient = messageBusReportingClient;
    }

    public static void main(final String[] args) {

        SampleCreateFeedbackReport exampleGetReport = new SampleCreateFeedbackReport(MessageBusFactory
                .createReportingClient("<YOUR_API_KEY>", "https://api.messagebus.com"));

        exampleGetReport.examplePollAndSaveFeedbackToFile();

    }

    public void examplePollAndSaveFeedbackToFile() {
        final String fileName = "testFeedback.csv";

        try {
            FileOutputStream fos = new FileOutputStream(fileName);

            final Date endDate = new Date();
            final Date startDate = new Date(endDate.getTime() - 1000 * 60 * 60 * 24); //24 hour offset in millis

            final FeedbackReportRequest feedbackReportRequest = new FeedbackReportRequest(MessageBusReportingClient.FeedbackReportScopeType.BOUNCES, startDate, endDate, channelKey,sessionKey,MessageBusReportingClient.ReportFormat.CSV);

            final ReportCreateResponse reportCreateResponse = messageBusReportingClient.createFeedbackReport(feedbackReportRequest);

            final String reportKey = reportCreateResponse.getReportKey();

            ReportStatusResponse reportStatus = messageBusReportingClient.getReportStatus(reportKey);

            while (!reportStatus.isFinished()) {
                reportStatus = messageBusReportingClient.getReportStatus(reportKey);
                try{
                    Thread.sleep(5000); // sleep 5 sec
                }catch(Exception e){}
            }

            if (reportStatus.isSuccessful()) {
                if (messageBusReportingClient.streamReport(reportKey, fos)) {
                    System.out.println(String.format("Report saved to %s", fileName));
                } else {
                    System.out.println(String.format("Unable to stream report for key %s", reportKey));
                }
            } else if (reportStatus.isEmpty()) {
                System.out.println(String.format("No Data Was Found For reportKey %s", reportKey));
            } else {
                System.out.println(String.format("Report with key %s returned status %s", reportKey, reportStatus.getReportStatus()));
            }

        } catch (MessageBusException e) {
            System.out.println(String.format("Error Message: %s \n \n Exception: %s", e.getStatusMessage(), e));
        } catch (FileNotFoundException fe) {
            System.out.println(String.format("Error Message: %s", fe.getMessage()));
        }
    }
}


text:
package net.netzgut.integral.streams;

import java.util.function.Predicate;
import java.util.stream.Stream;

public class IntegralPredicates {

    /**
     * Negates a predicate.
     */
    public static <T> Predicate<T> not(Predicate<T> predicate) {
        return predicate.negate();
    }

    /**
     * Compares with ==/identity.
     */
    public static <T> Predicate<T> identity(T value) {
        return input -> input == value;
    }

    /**
     * Checks if an object is assignable from a class.
     */
    public static <T> Predicate<T> assignableFrom(Class<?> clazz) {
        return input -> clazz.isAssignableFrom(input.getClass());
    }

    /**
     * Checks if an object is an instance of a class.
     */
    public static <T> Predicate<T> isInstance(Class<?> clazz) {
        return input -> clazz.isInstance(input);
    }

    /**
     * Ensures all predicates are met.
     */
    @SafeVarargs
    public static <T> Predicate<T> allOf(Predicate<T>... predicates) {
        return Stream.of(predicates) //
                     .reduce(always(), //
                             (p1, p2) -> p1.and(p2));
    }

    /**
     * Ensures any predicate is met.
     */
    @SafeVarargs
    public static <T> Predicate<T> anyOf(Predicate<T>... predicates) {
        return Stream.of(predicates) //
                     .reduce(never(), //
                             (p1, p2) -> p1.or(p2));
    }

    /**
     * Ensures no predicate is met at all.
     */
    @SafeVarargs
    public static <T> Predicate<T> none(Predicate<T>... predicates) {
        return not(anyOf(predicates));
    }

    public static <T> Predicate<T> always() {
        return ignored -> true;
    }

    public static <T> Predicate<T> never() {
        return ignored -> false;
    }

}


text:
/*
 * Projet de AAV - IUT Informatique Paris Descartes 2014/2015
 * Victor LE - Groupe Alternance
 */

package InOut.SudoGuiSwing;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;

import SudoGen.SudoGen;
import SudoSolve.SudoSolveBT;
import Sudoku.Sudoku;

/**
*

* La classe Menu est utilisée par MainWindow
* pour afficher le menu de l'application Sudoku.
*

*

* Elle permet à l'utilisateur de l'application d'accéder à différentes
* fonctions via un menu déroulant. Menu gère ainsi les
* évènements liés à ce menu comme la sélection/clic mais aussi les raccourcis
* clavier.
*

*
*

* L'utilisateur peut changer la valeur de la case de son choix. La classe
* implémente ActionListener pour gérer les évènements de clic.
*

*
*
* @author Victor LE
* @version 1.0
*
* @see MainWindow
* @see CaseButton
*
* @since 1.0
*/
@SuppressWarnings("serial")
public class MainWindow extends JPanel implements ActionListener
{
	private CaseButton[][] board = new CaseButton[Sudoku.NB_ROW][Sudoku.NB_COL];
	private JFrame fenetre;
	private Menu menu;
	private Sudoku sudoku;

	/**
	 * Construit l'application Sudoku
	 * @param args Ignored
	 */
	public static void main(String[] args)
	{
		new MainWindow();
	}

	/**
	 * Instancie la fenêtre, la grille de Sudoku, le generateur et le
	 * solver du Sudoku
	 */
	public MainWindow()
	{
		initBoard();
		sudoku = new Sudoku();
		sudoku.setGen(new SudoGen(sudoku));
		sudoku.setSolver(new SudoSolveBT(sudoku));

		fenetre = new JFrame("Sudoku");
		menu = new Menu(this);
		fenetre.setJMenuBar(menu.createMenuBar());
		fenetre.getContentPane().add(this);

		fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		fenetre.setSize(500, 530);
		fenetre.setResizable(false);
		fenetre.setVisible(true);

		GridLayout grid = new GridLayout(Sudoku.NB_ROW, Sudoku.NB_COL);
		grid.setVgap(2);
		grid.setHgap(2);

		this.setLayout(grid);

	}

	/**
	 * actionPerformed est nécessaire puisque la classe implémente ActionListener.
	 * Cette méthode gère les évenements liés au clic sur une case du Sudoku.
	 */
	@Override
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() instanceof CaseButton)
		{
			CaseButton temp = (CaseButton)e.getSource();
			String in = JOptionPane.showInputDialog(null);

			try
			{
				int oldValue = temp.getValue();
				temp.setValue(Integer.parseInt(in));
				sudoku.setValue(temp.getRow(), temp.getCol(), Integer.parseInt(in));

				if(!sudoku.isValid()) {
					JOptionPane.showMessageDialog(this, "Valeur incorrecte", "Erreur", JOptionPane.INFORMATION_MESSAGE);
					sudoku.setValue(temp.getRow(), temp.getCol(), oldValue);
					temp.setValue(oldValue);
				}

			}
			catch (NumberFormatException err)
			{

			}
		}
	}

	/**
	 * Affiche la fenêtre "à propos"
	 */
	public void about()
	{
		String str = "Réalisé par Victor LE\nIUT Informatique Paris Descartes 2014/2015\nVersion du 19/01/2015";
		String title = "A propos - Sudoku v1.0";

		JOptionPane.showMessageDialog(this, str, title, JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * Efface la grille de sudoku
	 */
	public void clear()
	{
		sudoku.reset();
		for(int row = 0; row < 9; row++)
			for(int col = 0; col < 9; col++)
				board[row][col].clear();

	}

	/**
	 * Affiche la fenêtre d'aide
	 */
	public void help()
	{
		String str = "Remplir la grille de tel sorte que chaque ligne," +
				" chaque colonne, and et chaque bloc de 3x3 contienne" +
				" les chiffres de 1 à 9 sans doublons.";
		String title = "Sudoku v1.0 - Aide";

		JOptionPane.showMessageDialog(this, str, title, JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * Génère un Sudoku dont le nombre de cases déja remplies est spécifié
	 * en paramètres
	 *
	 * @param nbValue le nombre de cases déjà remplies
	 */
	public void newGame(int nbValue)
	{
		sudoku.generate(nbValue);
		sudokuToBoard();
	}

	/**
	 * Copie les valeurs de la grille de Sudoku dans le tableau de CaseButton
	 *
	 */
	private void sudokuToBoard() {
		for (int i = 0; i < Sudoku.NB_ROW; i++) {
			for (int j = 0; j < Sudoku.NB_COL; j++) {
				board[i][j].setValue(sudoku.getValue(i, j));
			}
		}
	}

	/**
	 * Permet de quitter l'application
	 */
	public void quit()
	{
		fenetre.dispose();
	}

	/**
	 * Permet d'initialiser la liste de CaseButton
	 */
	private void initBoard()
	{
		Font font = new Font("Ariel", Font.PLAIN, 31);
		CaseButton caseButton;

		for(int row = 0; row < 9; row++)
		{
			for(int col = 0; col < 9; col++)
			{
				caseButton = new CaseButton(row, col);
				caseButton.setBackground(Color.white);

				if (row <= 2 && (col <= 2 || col > 5)){
					caseButton.setBackground (Color.gray);
				}
				if (row >2 && row <= 5 &&  col > 2 && col  <= 5){
					caseButton.setBackground (Color.gray);
				}
				if (row > 5 && ((col <= 2) || (col > 5))){
					caseButton.setBackground (Color.gray);
				}

				caseButton.setValue(0);
				caseButton.addActionListener(this);
				caseButton.setFont(font);
				caseButton.setForeground(Color.black);
				caseButton.setFocusable(false);

				add(caseButton);
				board[row][col] = caseButton;
			}
		}
	}

	/**
	 * Permet de résoudre le sudoku
	 */
	public void solve() {
		sudoku.solve();
		sudokuToBoard();

	}
}


text:
index = []

def add_to_index(index,keyword,url):
    for entry in index:
        if entry[0] == keyword:
            entry[1].append(url)
            return
    index.append([keyword,[url]])

def add_page_to_index(index,url,content):
    split_list = content.split()
    for word in split_list:
        add_to_index(index,word,url)
    return index

add_page_to_index(index,'fake.text',"This is a test")
print index
#>>> [['This', ['fake.text']], ['is', ['fake.text']], ['a', ['fake.text']],
#>>> ['test',['fake.text']]]


text:
import { jsdom } from 'jsdom';
import * as fp from 'lodash/fp';

global.document = jsdom('');
global.window = document.defaultView;
global.navigator = {
  userAgent: 'node.js',
};

function copyProps(src: Window, target: NodeJS.Global) {
  const props = Object.getOwnPropertyNames(src)
    .filter((prop) => fp.isUndefined(target[prop]))
    .reduce((accum, prop) => ({
      ...accum,
      [prop]: Object.getOwnPropertyDescriptor(src, prop),
    }), {});

  Object.defineProperties(target, props);
}

copyProps(document.defaultView, global);


text:
module.exports = {
	alert: {
		message: 'Mensagem',
		title: 'Aviso',
		btnOk: {
			label: 'OK',
			className: 'btn-primary'
		},
		callbackReturnOk: function () {
			return true;
		},
		className: '',
		type: 'alert'
	},
	confirm: {
		message: 'Mensagem',
		title: 'Importante',
		btnOk: {
			label: 'OK',
			className: 'btn-primary'
		},
		callbackReturnOk: function () {
			return true;
		},
		btnCancel: {
			label: 'Cancelar',
			className: 'btn-default'
		},
		callbackReturnCancel: function () {
			return false;
		},
		className: '',
		type: 'confirm'
	},
	confirmInline: {
		message: 'Confirm Action?',
		btnOk: {
			label: 'OK',
			className: 'btn-primary'
		},
		callbackReturnOk: function () {
			return true;
		},
		btnCancel: {
			label: 'Cancelar',
			className: 'btn-default'
		},
		callbackReturnCancel: function () {
			return false;
		},
		className: '',
		type: 'confirmInline'
	},
	prompt: {
		message: 'Mensagem',
		title: '',
		customEl: '',
		btnOk: {
			label: 'OK',
			className: 'btn-primary'
		},
		callbackReturnOk: function (msg) {
			return msg;
		},
		btnCancel: {
			label: 'Cancelar',
			className: 'btn-default'
		},
		callbackReturnCancel: function () {
			return null;
		},
		className: '',
		type: 'prompt'
	},
	notify: {
		ele: "body",
		type: "info",
		offset: {
			from: "top",
			amount: 20
		},
		align: "right",
		width: 250,
		delay: 4000,
		allow_dismiss: true,
		stackup_spacing: 10
	}
};


text:
"""A trainable ADAM optimizer that learns its internal variables."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

from learned_optimizer.optimizer import trainable_optimizer as opt
from learned_optimizer.optimizer import utils

class TrainableAdam(opt.TrainableOptimizer):
  """Adam optimizer with learnable scalar parameters.

  See Kingma et. al., 2014 for algorithm (http://arxiv.org/abs/1412.6980).
  """

  def __init__(self,
               learning_rate=1e-3,
               beta1=0.9,
               beta2=0.999,
               epsilon=1e-8,
               **kwargs):
    """Initializes the TrainableAdam optimizer with the given initial values.

    Args:
      learning_rate: The learning rate (default: 1e-3).
      beta1: The exponential decay rate for the 1st moment estimates.
      beta2: The exponential decay rate for the 2nd moment estimates.
      epsilon: A small constant for numerical stability.
      **kwargs: Any additional keyword arguments for TrainableOptimizer.

    Raises:
      ValueError: if the learning rate or epsilon is not positive
      ValueError: if beta1 or beta2 is not in (0, 1).
    """
    if learning_rate <= 0:
      raise ValueError("Learning rate must be positive.")
    if epsilon <= 0:
      raise ValueError("Epsilon must be positive.")
    if not 0 < beta1 < 1 or not 0 < beta2 < 1:
      raise ValueError("Beta values must be between 0 and 1, exclusive.")

    self._reuse_vars = False

    with tf.variable_scope(opt.OPTIMIZER_SCOPE):
      def inv_sigmoid(x):
        return np.log(x / (1.0 - x))

      self.log_learning_rate = tf.get_variable(
          "log_learning_rate",
          shape=[],
          initializer=tf.constant_initializer(np.log(learning_rate)))
      self.beta1_logit = tf.get_variable(
          "beta1_logit",
          shape=[],
          initializer=tf.constant_initializer(inv_sigmoid(beta1)))
      self.beta2_logit = tf.get_variable(
          "beta2_logit",
          shape=[],
          initializer=tf.constant_initializer(inv_sigmoid(beta2)))
      self.log_epsilon = tf.get_variable(
          "log_epsilon",
          shape=[],
          initializer=tf.constant_initializer(np.log(epsilon)))

    # Key names are derived from Algorithm 1 described in
    # https://arxiv.org/pdf/1412.6980.pdf
    state_keys = ["m", "v", "t"]
    super(TrainableAdam, self).__init__("Adam", state_keys, **kwargs)

  def _initialize_state(self, var):
    """Returns a dictionary mapping names of state variables to their values."""
    vectorized_shape = var.get_shape().num_elements(), 1

    return {key: tf.zeros(vectorized_shape) for key in self.state_keys}

  def _compute_update(self, param, grad, state):
    """Calculates the new internal state and parameters.

    If the gradient is sparse, updates the appropriate slices in the internal
    state and stacks the update tensor.

    Args:
      param: A tensor of parameters.
      grad: A tensor of gradients with the same shape as param.
      state: A dictionary containing any state for the optimizer.

    Returns:
      updated_param: The updated parameters.
      updated_state: The updated state variables in a dictionary.
    """

    with tf.variable_scope(opt.OPTIMIZER_SCOPE) as scope:

      if self._reuse_vars:
        scope.reuse_variables()
      else:
        self._reuse_vars = True

      (grad_values, first_moment, second_moment, timestep, grad_indices
      ) = self._extract_gradients_and_internal_state(
          grad, state, tf.shape(param))

      beta1 = tf.nn.sigmoid(self.beta1_logit)
      beta2 = tf.nn.sigmoid(self.beta2_logit)
      epsilon = tf.exp(self.log_epsilon) + 1e-10
      learning_rate = tf.exp(self.log_learning_rate)

      old_grad_shape = tf.shape(grad_values)
      grad_values = tf.reshape(grad_values, [-1, 1])

      new_timestep = timestep + 1
      new_first_moment = self._update_adam_estimate(
          first_moment, grad_values, beta1)
      new_second_moment = self._debias_adam_estimate(
          second_moment, tf.square(grad_values), beta2)

      debiased_first_moment = self._debias_adam_estimate(
          new_first_moment, beta1, new_timestep)
      debiased_second_moment = self._debias_adam_estimate(
          new_second_moment, beta2, new_timestep)

      # Propagating through the square root of 0 is very bad for stability.
      update = (learning_rate * debiased_first_moment /
                (tf.sqrt(debiased_second_moment + 1e-10) + epsilon))

      update = tf.reshape(update, old_grad_shape)

      if grad_indices is not None:
        param_shape = tf.shape(param)
        update = utils.stack_tensor(
            update, grad_indices, param, param_shape[:1])
        new_first_moment = utils.update_slices(
            new_first_moment, grad_indices, state["m"], param_shape)
        new_second_moment = utils.update_slices(
            new_second_moment, grad_indices, state["v"], param_shape)
        new_timestep = utils.update_slices(
            new_timestep, grad_indices, state["t"], param_shape)

      new_param = param - update

      # collect the update and new state
      new_state = {
          "m": new_first_moment,
          "v": new_second_moment,
          "t": new_timestep
      }

    return new_param, new_state

  def _update_adam_estimate(self, estimate, value, beta):
    """Returns a beta-weighted average of estimate and value."""
    return (beta * estimate) + ((1 - beta) * value)

  def _debias_adam_estimate(self, estimate, beta, t_step):
    """Returns a debiased estimate based on beta and the timestep."""
    return estimate / (1 - tf.pow(beta, t_step))

  def _extract_gradients_and_internal_state(self, grad, state, param_shape):
    """Extracts the gradients and relevant internal state.

    If the gradient is sparse, extracts the appropriate slices from the state.

    Args:
      grad: The current gradient.
      state: The current state.
      param_shape: The shape of the parameter (used if gradient is sparse).

    Returns:
      grad_values: The gradient value tensor.
      first_moment: The first moment tensor (internal state).
      second_moment: The second moment tensor (internal state).
      timestep: The current timestep (internal state).
      grad_indices: The indices for the gradient tensor, if sparse.
          None otherwise.
    """
    grad_values = grad
    grad_indices = None
    first_moment = state["m"]
    second_moment = state["v"]
    timestep = state["t"]

    if isinstance(grad, tf.IndexedSlices):
      grad_indices, grad_values = utils.accumulate_sparse_gradients(grad)
      first_moment = utils.slice_tensor(
          first_moment, grad_indices, param_shape)
      second_moment = utils.slice_tensor(
          second_moment, grad_indices, param_shape)
      timestep = utils.slice_tensor(timestep, grad_indices, param_shape)

    return grad_values, first_moment, second_moment, timestep, grad_indices


text:
package org.apache.logging.log4j.perf.jmh;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LifeCycle;
import org.apache.logging.log4j.perf.util.BenchmarkMessageParams;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;

import static org.apache.logging.log4j.perf.util.BenchmarkMessageParams.*;

/**
 * Tests Log4j2 Async Appender performance.
 */
// ============================== HOW TO RUN THIS TEST: ====================================
//
// single thread:
// java -jar log4j-perf/target/benchmarks.jar ".*AsyncAppenderLog4j2Benchmark.*" -f 1 -wi 10 -i 20
//
// multiple threads (for example, 4 threads):
// java -jar log4j-perf/target/benchmarks.jar ".*AsyncAppenderLog4j2Benchmark.*" -f 1 -wi 10 -i 20 -t 4 -si true
//
// Usage help:
// java -jar log4j-perf/target/benchmarks.jar -help
//
@State(Scope.Benchmark)
public class AsyncAppenderLog4j2Benchmark {
    Logger logger;

    @Setup(Level.Trial)
    public void up() {
        System.setProperty("log4j.configurationFile", "perf5AsyncApndNoLoc-noOpAppender.xml");
        logger = LogManager.getLogger(getClass());
    }

    @TearDown(Level.Trial)
    public void down() {
        ((LifeCycle) LogManager.getContext(false)).stop();
        new File("perftest.log").delete();
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughputSimple() {
        logger.info(BenchmarkMessageParams.TEST);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput1Param() {
        logger.info("p1={}", one);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput2Params() {
        logger.info("p1={}, p2={}", one, two);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput3Params() {
        logger.info("p1={}, p2={}, p3={}", one, two, three);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput4Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}", one, two, three, four);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput5Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}", one, two, three, four, five);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput6Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}", one, two, three, four, five, six);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput7Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}", one, two, three, four, five, six, seven);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput8Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}, p8={}", one, two, three, four, five, six, seven,
                eight);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput9Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}, p8={}, p9={}", one, two, three, four, five, six,
                seven, eight, nine);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput10Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}, p8={}, p9={}, p10={}", one, two, three, four,
                five, six, seven, eight, nine, ten);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void throughput11Params() {
        logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}, p8={}, p9={}, p10={}, p11={}", one, two, three,
                four, five, six, seven, eight, nine, ten, eleven);
    }
}


text:
package org.apache.commons.collections;

import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 *
A customized implementation of java.util.TreeMap designed
 * to operate in a multithreaded environment where the large majority of
 * method calls are read-only, instead of structural changes.  When operating
 * in "fast" mode, read calls are non-synchronized and write calls perform the
 * following steps:

 *

 *
Clone the existing collection
 *
Perform the modification on the clone
 *
Replace the existing collection with the (modified) clone
 *

 *
When first created, objects of this class default to "slow" mode, where
 * all accesses of any type are synchronized but no cloning takes place.  This
 * is appropriate for initially populating the collection, followed by a switch
 * to "fast" mode (by calling setFast(true)) after initialization
 * is complete.

 *
 *
NOTE: If you are creating and accessing a
 * TreeMap only within a single thread, you should use
 * java.util.TreeMap directly (with no synchronization), for
 * maximum performance.

 *
 *
NOTE: This class is not cross-platform.
 * Using it may cause unexpected failures on some architectures.
 * It suffers from the same problems as the double-checked locking idiom.
 * In particular, the instruction that clones the internal collection and the
 * instruction that sets the internal reference to the clone can be executed
 * or perceived out-of-order.  This means that any read operation might fail
 * unexpectedly, as it may be reading the state of the internal collection
 * before the internal collection is fully formed.
 * For more information on the double-checked locking idiom, see the
 *
 * Double-Checked Locking Idiom Is Broken Declaration.

 *
 * @since Commons Collections 1.0
 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
 *
 * @author Craig R. McClanahan
 * @author Stephen Colebourne
 */
public class FastTreeMap extends TreeMap {

    /**
     * The underlying map we are managing.
     */
    protected TreeMap map = null;

    /**
     * Are we operating in "fast" mode?
     */
    protected boolean fast = false;

    // Constructors
    // ----------------------------------------------------------------------

    /**
     * Construct a an empty map.
     */
    public FastTreeMap() {
        super();
        this.map = new TreeMap();
    }

    /**
     * Construct an empty map with the specified comparator.
     *
     * @param comparator  the comparator to use for ordering tree elements
     */
    public FastTreeMap(Comparator comparator) {
        super();
        this.map = new TreeMap(comparator);
    }

    /**
     * Construct a new map with the same mappings as the specified map,
     * sorted according to the keys's natural order
     *
     * @param map  the map whose mappings are to be copied
     */
    public FastTreeMap(Map map) {
        super();
        this.map = new TreeMap(map);
    }

    /**
     * Construct a new map with the same mappings as the specified map,
     * sorted according to the same ordering
     *
     * @param map  the map whose mappings are to be copied
     */
    public FastTreeMap(SortedMap map) {
        super();
        this.map = new TreeMap(map);
    }

    // Property access
    // ----------------------------------------------------------------------

    /**
     *  Returns true if this map is operating in fast mode.
     *
     *  @return true if this map is operating in fast mode
     */
    public boolean getFast() {
        return (this.fast);
    }

    /**
     *  Sets whether this map is operating in fast mode.
     *
     *  @param fast true if this map should operate in fast mode
     */
    public void setFast(boolean fast) {
        this.fast = fast;
    }

    // Map access
    // ----------------------------------------------------------------------
    // These methods can forward straight to the wrapped Map in 'fast' mode.
    // (because they are query methods)

    /**
     * Return the value to which this map maps the specified key.  Returns
     * null if the map contains no mapping for this key, or if
     * there is a mapping with a value of null.  Use the
     * containsKey() method to disambiguate these cases.
     *
     * @param key  the key whose value is to be returned
     * @return the value mapped to that key, or null
     */
    public Object get(Object key) {
        if (fast) {
            return (map.get(key));
        } else {
            synchronized (map) {
                return (map.get(key));
            }
        }
    }

    /**
     * Return the number of key-value mappings in this map.
     *
     * @return the current size of the map
     */
    public int size() {
        if (fast) {
            return (map.size());
        } else {
            synchronized (map) {
                return (map.size());
            }
        }
    }

    /**
     * Return true if this map contains no mappings.
     *
     * @return is the map currently empty
     */
    public boolean isEmpty() {
        if (fast) {
            return (map.isEmpty());
        } else {
            synchronized (map) {
                return (map.isEmpty());
            }
        }
    }

    /**
     * Return true if this map contains a mapping for the
     * specified key.
     *
     * @param key  the key to be searched for
     * @return true if the map contains the key
     */
    public boolean containsKey(Object key) {
        if (fast) {
            return (map.containsKey(key));
        } else {
            synchronized (map) {
                return (map.containsKey(key));
            }
        }
    }

    /**
     * Return true if this map contains one or more keys mapping
     * to the specified value.
     *
     * @param value  the value to be searched for
     * @return true if the map contains the value
     */
    public boolean containsValue(Object value) {
        if (fast) {
            return (map.containsValue(value));
        } else {
            synchronized (map) {
                return (map.containsValue(value));
            }
        }
    }

    /**
     * Return the comparator used to order this map, or null
     * if this map uses its keys' natural order.
     *
     * @return the comparator used to order the map, or null if natural order
     */
    public Comparator comparator() {
        if (fast) {
            return (map.comparator());
        } else {
            synchronized (map) {
                return (map.comparator());
            }
        }
    }

    /**
     * Return the first (lowest) key currently in this sorted map.
     *
     * @return the first key in the map
     */
    public Object firstKey() {
        if (fast) {
            return (map.firstKey());
        } else {
            synchronized (map) {
                return (map.firstKey());
            }
        }
    }

    /**
     * Return the last (highest) key currently in this sorted map.
     *
     * @return the last key in the map
     */
    public Object lastKey() {
        if (fast) {
            return (map.lastKey());
        } else {
            synchronized (map) {
                return (map.lastKey());
            }
        }
    }

    // Map modification
    // ----------------------------------------------------------------------
    // These methods perform special behaviour in 'fast' mode.
    // The map is cloned, updated and then assigned back.
    // See the comments at the top as to why this won't always work.

    /**
     * Associate the specified value with the specified key in this map.
     * If the map previously contained a mapping for this key, the old
     * value is replaced and returned.
     *
     * @param key  the key with which the value is to be associated
     * @param value  the value to be associated with this key
     * @return the value previously mapped to the key, or null
     */
    public Object put(Object key, Object value) {
        if (fast) {
            synchronized (this) {
                TreeMap temp = (TreeMap) map.clone();
                Object result = temp.put(key, value);
                map = temp;
                return (result);
            }
        } else {
            synchronized (map) {
                return (map.put(key, value));
            }
        }
    }

    /**
     * Copy all of the mappings from the specified map to this one, replacing
     * any mappings with the same keys.
     *
     * @param in  the map whose mappings are to be copied
     */
    public void putAll(Map in) {
        if (fast) {
            synchronized (this) {
                TreeMap temp = (TreeMap) map.clone();
                temp.putAll(in);
                map = temp;
            }
        } else {
            synchronized (map) {
                map.putAll(in);
            }
        }
    }

    /**
     * Remove any mapping for this key, and return any previously
     * mapped value.
     *
     * @param key  the key whose mapping is to be removed
     * @return the value removed, or null
     */
    public Object remove(Object key) {
        if (fast) {
            synchronized (this) {
                TreeMap temp = (TreeMap) map.clone();
                Object result = temp.remove(key);
                map = temp;
                return (result);
            }
        } else {
            synchronized (map) {
                return (map.remove(key));
            }
        }
    }

    /**
     * Remove all mappings from this map.
     */
    public void clear() {
        if (fast) {
            synchronized (this) {
                map = new TreeMap();
            }
        } else {
            synchronized (map) {
                map.clear();
            }
        }
    }

    // Basic object methods
    // ----------------------------------------------------------------------

    /**
     * Compare the specified object with this list for equality.  This
     * implementation uses exactly the code that is used to define the
     * list equals function in the documentation for the
     * Map.equals method.
     *
     * @param o  the object to be compared to this list
     * @return true if the two maps are equal
     */
    public boolean equals(Object o) {
        // Simple tests that require no synchronization
        if (o == this) {
            return (true);
        } else if (!(o instanceof Map)) {
            return (false);
        }
        Map mo = (Map) o;

        // Compare the two maps for equality
        if (fast) {
            if (mo.size() != map.size()) {
                return (false);
            }
            Iterator i = map.entrySet().iterator();
            while (i.hasNext()) {
                Map.Entry e = (Map.Entry) i.next();
                Object key = e.getKey();
                Object value = e.getValue();
                if (value == null) {
                    if (!(mo.get(key) == null && mo.containsKey(key))) {
                        return (false);
                    }
                } else {
                    if (!value.equals(mo.get(key))) {
                        return (false);
                    }
                }
            }
            return (true);
        } else {
            synchronized (map) {
                if (mo.size() != map.size()) {
                    return (false);
                }
                Iterator i = map.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry e = (Map.Entry) i.next();
                    Object key = e.getKey();
                    Object value = e.getValue();
                    if (value == null) {
                        if (!(mo.get(key) == null && mo.containsKey(key))) {
                            return (false);
                        }
                    } else {
                        if (!value.equals(mo.get(key))) {
                            return (false);
                        }
                    }
                }
                return (true);
            }
        }
    }

    /**
     * Return the hash code value for this map.  This implementation uses
     * exactly the code that is used to define the list hash function in the
     * documentation for the Map.hashCode method.
     *
     * @return a suitable integer hash code
     */
    public int hashCode() {
        if (fast) {
            int h = 0;
            Iterator i = map.entrySet().iterator();
            while (i.hasNext()) {
                h += i.next().hashCode();
            }
            return (h);
        } else {
            synchronized (map) {
                int h = 0;
                Iterator i = map.entrySet().iterator();
                while (i.hasNext()) {
                    h += i.next().hashCode();
                }
                return (h);
            }
        }
    }

    /**
     * Return a shallow copy of this FastTreeMap instance.
     * The keys and values themselves are not copied.
     *
     * @return a clone of this map
     */
    public Object clone() {
        FastTreeMap results = null;
        if (fast) {
            results = new FastTreeMap(map);
        } else {
            synchronized (map) {
                results = new FastTreeMap(map);
            }
        }
        results.setFast(getFast());
        return (results);
    }

    // Sub map views
    // ----------------------------------------------------------------------

    /**
     * Return a view of the portion of this map whose keys are strictly
     * less than the specified key.
     *
     * @param key Key higher than any in the returned map
     * @return a head map
     */
    public SortedMap headMap(Object key) {
        if (fast) {
            return (map.headMap(key));
        } else {
            synchronized (map) {
                return (map.headMap(key));
            }
        }
    }

    /**
     * Return a view of the portion of this map whose keys are in the
     * range fromKey (inclusive) to toKey (exclusive).
     *
     * @param fromKey Lower limit of keys for the returned map
     * @param toKey Upper limit of keys for the returned map
     * @return a sub map
     */
    public SortedMap subMap(Object fromKey, Object toKey) {
        if (fast) {
            return (map.subMap(fromKey, toKey));
        } else {
            synchronized (map) {
                return (map.subMap(fromKey, toKey));
            }
        }
    }

    /**
     * Return a view of the portion of this map whose keys are greater than
     * or equal to the specified key.
     *
     * @param key Key less than or equal to any in the returned map
     * @return a tail map
     */
    public SortedMap tailMap(Object key) {
        if (fast) {
            return (map.tailMap(key));
        } else {
            synchronized (map) {
                return (map.tailMap(key));
            }
        }
    }

    // Map views
    // ----------------------------------------------------------------------

    /**
     * Return a collection view of the mappings contained in this map.  Each
     * element in the returned collection is a Map.Entry.
     */
    public Set entrySet() {
        return new EntrySet();
    }

    /**
     * Return a set view of the keys contained in this map.
     */
    public Set keySet() {
        return new KeySet();
    }

    /**
     * Return a collection view of the values contained in this map.
     */
    public Collection values() {
        return new Values();
    }

    // Map view inner classes
    // ----------------------------------------------------------------------

    /**
     * Abstract collection implementation shared by keySet(), values() and entrySet().
     */
    private abstract class CollectionView implements Collection {

        public CollectionView() {
        }

        protected abstract Collection get(Map map);
        protected abstract Object iteratorNext(Map.Entry entry);

        public void clear() {
            if (fast) {
                synchronized (FastTreeMap.this) {
                    map = new TreeMap();
                }
            } else {
                synchronized (map) {
                    get(map).clear();
                }
            }
        }

        public boolean remove(Object o) {
            if (fast) {
                synchronized (FastTreeMap.this) {
                    TreeMap temp = (TreeMap) map.clone();
                    boolean r = get(temp).remove(o);
                    map = temp;
                    return r;
                }
            } else {
                synchronized (map) {
                    return get(map).remove(o);
                }
            }
        }

        public boolean removeAll(Collection o) {
            if (fast) {
                synchronized (FastTreeMap.this) {
                    TreeMap temp = (TreeMap) map.clone();
                    boolean r = get(temp).removeAll(o);
                    map = temp;
                    return r;
                }
            } else {
                synchronized (map) {
                    return get(map).removeAll(o);
                }
            }
        }

        public boolean retainAll(Collection o) {
            if (fast) {
                synchronized (FastTreeMap.this) {
                    TreeMap temp = (TreeMap) map.clone();
                    boolean r = get(temp).retainAll(o);
                    map = temp;
                    return r;
                }
            } else {
                synchronized (map) {
                    return get(map).retainAll(o);
                }
            }
        }

        public int size() {
            if (fast) {
                return get(map).size();
            } else {
                synchronized (map) {
                    return get(map).size();
                }
            }
        }

        public boolean isEmpty() {
            if (fast) {
                return get(map).isEmpty();
            } else {
                synchronized (map) {
                    return get(map).isEmpty();
                }
            }
        }

        public boolean contains(Object o) {
            if (fast) {
                return get(map).contains(o);
            } else {
                synchronized (map) {
                    return get(map).contains(o);
                }
            }
        }

        public boolean containsAll(Collection o) {
            if (fast) {
                return get(map).containsAll(o);
            } else {
                synchronized (map) {
                    return get(map).containsAll(o);
                }
            }
        }

        public Object[] toArray(Object[] o) {
            if (fast) {
                return get(map).toArray(o);
            } else {
                synchronized (map) {
                    return get(map).toArray(o);
                }
            }
        }

        public Object[] toArray() {
            if (fast) {
                return get(map).toArray();
            } else {
                synchronized (map) {
                    return get(map).toArray();
                }
            }
        }

        public boolean equals(Object o) {
            if (o == this) return true;
            if (fast) {
                return get(map).equals(o);
            } else {
                synchronized (map) {
                    return get(map).equals(o);
                }
            }
        }

        public int hashCode() {
            if (fast) {
                return get(map).hashCode();
            } else {
                synchronized (map) {
                    return get(map).hashCode();
                }
            }
        }

        public boolean add(Object o) {
            throw new UnsupportedOperationException();
        }

        public boolean addAll(Collection c) {
            throw new UnsupportedOperationException();
        }

        public Iterator iterator() {
            return new CollectionViewIterator();
        }

        private class CollectionViewIterator implements Iterator {

            private Map expected;
            private Map.Entry lastReturned = null;
            private Iterator iterator;

            public CollectionViewIterator() {
                this.expected = map;
                this.iterator = expected.entrySet().iterator();
            }

            public boolean hasNext() {
                if (expected != map) {
                    throw new ConcurrentModificationException();
                }
                return iterator.hasNext();
            }

            public Object next() {
                if (expected != map) {
                    throw new ConcurrentModificationException();
                }
                lastReturned = (Map.Entry)iterator.next();
                return iteratorNext(lastReturned);
            }

            public void remove() {
                if (lastReturned == null) {
                    throw new IllegalStateException();
                }
                if (fast) {
                    synchronized (FastTreeMap.this) {
                        if (expected != map) {
                            throw new ConcurrentModificationException();
                        }
                        FastTreeMap.this.remove(lastReturned.getKey());
                        lastReturned = null;
                        expected = map;
                    }
                } else {
                    iterator.remove();
                    lastReturned = null;
                }
            }
        }
   }

   /**
    * Set implementation over the keys of the FastTreeMap
    */
   private class KeySet extends CollectionView implements Set {

       protected Collection get(Map map) {
           return map.keySet();
       }

       protected Object iteratorNext(Map.Entry entry) {
           return entry.getKey();
       }

   }

   /**
    * Collection implementation over the values of the FastTreeMap
    */
   private class Values extends CollectionView {

       protected Collection get(Map map) {
           return map.values();
       }

       protected Object iteratorNext(Map.Entry entry) {
           return entry.getValue();
       }
   }

   /**
    * Set implementation over the entries of the FastTreeMap
    */
   private class EntrySet extends CollectionView implements Set {

       protected Collection get(Map map) {
           return map.entrySet();
       }

       protected Object iteratorNext(Map.Entry entry) {
           return entry;
       }

   }

}


text:
Name:
<input type="text" ng-model="yourName" placeholder="Enter a name here">
Hello {{yourName}}!

      Name:
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      Hello {{yourName}}!

Name: <input class="backbone_input" type="text" placeholder="Enter a name here">
Hello !

var NameOutputView = Backbone.View.extend({
template: _.template("Hello <%- name %>!"),
el: "#real_backbone_form",
events: {
"keyup .backbone_input":    "updateModel"
},
updateModel: function(e){
var name = $(e.currentTarget).val();
this.model.set({name:name});
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
},
render: function() {
this.$el.children('.backbone_output').html(this.template(this.model.attributes));
return this;
}
});
new NameOutputView({ model: new Backbone.Model({name:null}) });

      Name:
      <input class="backbone_input" type="text" placeholder="Enter a name here">
      Hello !

Demo: Backbone Source

Demo: Gitter

contribute!

Closing Thoughts

Important for Companies

Join MeetUps

Start Today


text:
enum E { e };

class C {

  int f() {
    int foo, bar;

    []; // expected-error {{expected body of lambda expression}}
    [+] {}; // expected-error {{expected variable name or 'this' in lambda capture list}}
    [foo+] {}; // expected-error {{expected ',' or ']' in lambda capture list}}
    [foo,&this] {}; // expected-error {{'this' cannot be captured by reference}}
    [&this] {}; // expected-error {{'this' cannot be captured by reference}}
    [&,] {}; // expected-error {{expected variable name or 'this' in lambda capture list}}
    [=,] {}; // expected-error {{expected variable name or 'this' in lambda capture list}}
    [] {};
    [=] (int i) {};
    [&] (int) mutable -> void {};
    [foo,bar] () { return 3; };
    [=,&foo] () {};
    [&,foo] () {};
    [this] () {};
    [] () -> class C { return C(); };
    [] () -> enum E { return e; };

    [] -> int { return 0; }; // expected-error{{lambda requires '()' before return type}}
    [] mutable -> int { return 0; }; // expected-error{{lambda requires '()' before 'mutable'}}
    return 1;
  }

  void designator_or_lambda() {
    typedef int T;
    const int b = 0;
    const int c = 1;
    int a1[1] = {[b] (T()) {}}; // expected-error{{no viable conversion from 'C::<lambda}}
    int a2[1] = {[b] = 1 };
    int a3[1] = {[b,c] = 1 }; // expected-error{{expected body of lambda expression}}
    int a4[1] = {[&b] = 1 }; // expected-error{{integral constant expression must have integral or unscoped enumeration type, not 'const int *'}}
    int a5[3] = { []{return 0;}() };
    int a6[1] = {[this] = 1 }; // expected-error{{integral constant expression must have integral or unscoped enumeration type, not 'C *'}}
  }
};


text:
"""Shared helper functions for connecting BigQuery and pandas."""

import concurrent.futures
from datetime import datetime
import functools
from itertools import islice
import logging
import queue
import warnings

try:
    import pandas  # type: ignore

    pandas_import_exception = None
except ImportError as exc:  # pragma: NO COVER
    pandas = None
    pandas_import_exception = exc
else:
    import numpy

try:
    import db_dtypes  # type: ignore

    date_dtype_name = db_dtypes.DateDtype.name
    time_dtype_name = db_dtypes.TimeDtype.name
    db_dtypes_import_exception = None
except ImportError as exc:  # pragma: NO COVER
    db_dtypes = None
    db_dtypes_import_exception = exc
    date_dtype_name = time_dtype_name = ""  # Use '' rather than None because pytype

import pyarrow  # type: ignore
import pyarrow.parquet  # type: ignore

try:
    # _BaseGeometry is used to detect shapely objevys in `bq_to_arrow_array`
    from shapely.geometry.base import BaseGeometry as _BaseGeometry  # type: ignore
except ImportError:  # pragma: NO COVER
    # No shapely, use NoneType for _BaseGeometry as a placeholder.
    _BaseGeometry = type(None)
else:
    if pandas is not None:  # pragma: NO COVER

        def _to_wkb():
            from shapely import wkb  # type: ignore

            write = wkb.dumps
            notnull = pandas.notnull

            def _to_wkb(v):
                return write(v) if notnull(v) else v

            return _to_wkb

        _to_wkb = _to_wkb()

try:
    from google.cloud.bigquery_storage import ArrowSerializationOptions
except ImportError:
    _ARROW_COMPRESSION_SUPPORT = False
else:
    # Having BQ Storage available implies that pyarrow >=1.0.0 is available, too.
    _ARROW_COMPRESSION_SUPPORT = True

from google.cloud.bigquery import _helpers
from google.cloud.bigquery import schema

_LOGGER = logging.getLogger(__name__)

_PROGRESS_INTERVAL = 0.2  # Maximum time between download status checks, in seconds.

_MAX_QUEUE_SIZE_DEFAULT = object()  # max queue size sentinel for BQ Storage downloads

_NO_PANDAS_ERROR = "Please install the 'pandas' package to use this function."
_NO_DB_TYPES_ERROR = "Please install the 'db-dtypes' package to use this function."

_PANDAS_DTYPE_TO_BQ = {
    "bool": "BOOLEAN",
    "datetime64[ns, UTC]": "TIMESTAMP",
    "datetime64[ns]": "DATETIME",
    "float32": "FLOAT",
    "float64": "FLOAT",
    "int8": "INTEGER",
    "int16": "INTEGER",
    "int32": "INTEGER",
    "int64": "INTEGER",
    "uint8": "INTEGER",
    "uint16": "INTEGER",
    "uint32": "INTEGER",
    "geometry": "GEOGRAPHY",
    date_dtype_name: "DATE",
    time_dtype_name: "TIME",
}

class _DownloadState(object):
    """Flag to indicate that a thread should exit early."""

    def __init__(self):
        # No need for a lock because reading/replacing a variable is defined to
        # be an atomic operation in the Python language definition (enforced by
        # the global interpreter lock).
        self.done = False

def pyarrow_datetime():
    return pyarrow.timestamp("us", tz=None)

def pyarrow_numeric():
    return pyarrow.decimal128(38, 9)

def pyarrow_bignumeric():
    # 77th digit is partial.
    # https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#decimal_types
    return pyarrow.decimal256(76, 38)

def pyarrow_time():
    return pyarrow.time64("us")

def pyarrow_timestamp():
    return pyarrow.timestamp("us", tz="UTC")

# This dictionary is duplicated in bigquery_storage/test/unite/test_reader.py
# When modifying it be sure to update it there as well.
BQ_TO_ARROW_SCALARS = {
    "BIGNUMERIC": pyarrow_bignumeric,
    "BOOL": pyarrow.bool_,
    "BOOLEAN": pyarrow.bool_,
    "BYTES": pyarrow.binary,
    "DATE": pyarrow.date32,
    "DATETIME": pyarrow_datetime,
    "FLOAT": pyarrow.float64,
    "FLOAT64": pyarrow.float64,
    "GEOGRAPHY": pyarrow.string,
    "INT64": pyarrow.int64,
    "INTEGER": pyarrow.int64,
    "NUMERIC": pyarrow_numeric,
    "STRING": pyarrow.string,
    "TIME": pyarrow_time,
    "TIMESTAMP": pyarrow_timestamp,
}
ARROW_SCALAR_IDS_TO_BQ = {
    # https://arrow.apache.org/docs/python/api/datatypes.html#type-classes
    pyarrow.bool_().id: "BOOL",
    pyarrow.int8().id: "INT64",
    pyarrow.int16().id: "INT64",
    pyarrow.int32().id: "INT64",
    pyarrow.int64().id: "INT64",
    pyarrow.uint8().id: "INT64",
    pyarrow.uint16().id: "INT64",
    pyarrow.uint32().id: "INT64",
    pyarrow.uint64().id: "INT64",
    pyarrow.float16().id: "FLOAT64",
    pyarrow.float32().id: "FLOAT64",
    pyarrow.float64().id: "FLOAT64",
    pyarrow.time32("ms").id: "TIME",
    pyarrow.time64("ns").id: "TIME",
    pyarrow.timestamp("ns").id: "TIMESTAMP",
    pyarrow.date32().id: "DATE",
    pyarrow.date64().id: "DATETIME",  # because millisecond resolution
    pyarrow.binary().id: "BYTES",
    pyarrow.string().id: "STRING",  # also alias for pyarrow.utf8()
    # The exact scale and precision don't matter, see below.
    pyarrow.decimal128(38, scale=9).id: "NUMERIC",
    # The exact decimal's scale and precision are not important, as only
    # the type ID matters, and it's the same for all decimal256 instances.
    pyarrow.decimal256(76, scale=38).id: "BIGNUMERIC",
}
BQ_FIELD_TYPE_TO_ARROW_FIELD_METADATA = {
    "GEOGRAPHY": {
        b"ARROW:extension:name": b"google:sqlType:geography",
        b"ARROW:extension:metadata": b'{"encoding": "WKT"}',
    },
    "DATETIME": {b"ARROW:extension:name": b"google:sqlType:datetime"},
}

def bq_to_arrow_struct_data_type(field):
    arrow_fields = []
    for subfield in field.fields:
        arrow_subfield = bq_to_arrow_field(subfield)
        if arrow_subfield:
            arrow_fields.append(arrow_subfield)
        else:
            # Could not determine a subfield type. Fallback to type
            # inference.
            return None
    return pyarrow.struct(arrow_fields)

def bq_to_arrow_data_type(field):
    """Return the Arrow data type, corresponding to a given BigQuery column.

    Returns:
        None: if default Arrow type inspection should be used.
    """
    if field.mode is not None and field.mode.upper() == "REPEATED":
        inner_type = bq_to_arrow_data_type(
            schema.SchemaField(field.name, field.field_type, fields=field.fields)
        )
        if inner_type:
            return pyarrow.list_(inner_type)
        return None

    field_type_upper = field.field_type.upper() if field.field_type else ""
    if field_type_upper in schema._STRUCT_TYPES:
        return bq_to_arrow_struct_data_type(field)

    data_type_constructor = BQ_TO_ARROW_SCALARS.get(field_type_upper)
    if data_type_constructor is None:
        return None
    return data_type_constructor()

def bq_to_arrow_field(bq_field, array_type=None):
    """Return the Arrow field, corresponding to a given BigQuery column.

    Returns:
        None: if the Arrow type cannot be determined.
    """
    arrow_type = bq_to_arrow_data_type(bq_field)
    if arrow_type is not None:
        if array_type is not None:
            arrow_type = array_type  # For GEOGRAPHY, at least initially
        is_nullable = bq_field.mode.upper() == "NULLABLE"
        metadata = BQ_FIELD_TYPE_TO_ARROW_FIELD_METADATA.get(
            bq_field.field_type.upper() if bq_field.field_type else ""
        )
        return pyarrow.field(
            bq_field.name, arrow_type, nullable=is_nullable, metadata=metadata
        )

    warnings.warn("Unable to determine type for field '{}'.".format(bq_field.name))
    return None

def bq_to_arrow_schema(bq_schema):
    """Return the Arrow schema, corresponding to a given BigQuery schema.

    Returns:
        None: if any Arrow type cannot be determined.
    """
    arrow_fields = []
    for bq_field in bq_schema:
        arrow_field = bq_to_arrow_field(bq_field)
        if arrow_field is None:
            # Auto-detect the schema if there is an unknown field type.
            return None
        arrow_fields.append(arrow_field)
    return pyarrow.schema(arrow_fields)

def default_types_mapper(date_as_object: bool = False):
    """Create a mapping from pyarrow types to pandas types.

    This overrides the pandas defaults to use null-safe extension types where
    available.

    See: https://arrow.apache.org/docs/python/api/datatypes.html for a list of
    data types. See:
    tests/unit/test__pandas_helpers.py::test_bq_to_arrow_data_type for
    BigQuery to Arrow type mapping.

    Note to google-cloud-bigquery developers: If you update the default dtypes,
    also update the docs at docs/usage/pandas.rst.
    """

    def types_mapper(arrow_data_type):
        if pyarrow.types.is_boolean(arrow_data_type):
            return pandas.BooleanDtype()

        elif (
            # If date_as_object is True, we know some DATE columns are
            # out-of-bounds of what is supported by pandas.
            not date_as_object
            and pyarrow.types.is_date(arrow_data_type)
        ):
            return db_dtypes.DateDtype()

        elif pyarrow.types.is_integer(arrow_data_type):
            return pandas.Int64Dtype()

        elif pyarrow.types.is_time(arrow_data_type):
            return db_dtypes.TimeDtype()

    return types_mapper

def bq_to_arrow_array(series, bq_field):
    if bq_field.field_type.upper() == "GEOGRAPHY":
        arrow_type = None
        first = _first_valid(series)
        if first is not None:
            if series.dtype.name == "geometry" or isinstance(first, _BaseGeometry):
                arrow_type = pyarrow.binary()
                # Convert shapey geometry to WKB binary format:
                series = series.apply(_to_wkb)
            elif isinstance(first, bytes):
                arrow_type = pyarrow.binary()
        elif series.dtype.name == "geometry":
            # We have a GeoSeries containing all nulls, convert it to a pandas series
            series = pandas.Series(numpy.array(series))

        if arrow_type is None:
            arrow_type = bq_to_arrow_data_type(bq_field)
    else:
        arrow_type = bq_to_arrow_data_type(bq_field)

    field_type_upper = bq_field.field_type.upper() if bq_field.field_type else ""

    if bq_field.mode.upper() == "REPEATED":
        return pyarrow.ListArray.from_pandas(series, type=arrow_type)
    if field_type_upper in schema._STRUCT_TYPES:
        return pyarrow.StructArray.from_pandas(series, type=arrow_type)
    return pyarrow.Array.from_pandas(series, type=arrow_type)

def get_column_or_index(dataframe, name):
    """Return a column or index as a pandas series."""
    if name in dataframe.columns:
        return dataframe[name].reset_index(drop=True)

    if isinstance(dataframe.index, pandas.MultiIndex):
        if name in dataframe.index.names:
            return (
                dataframe.index.get_level_values(name)
                .to_series()
                .reset_index(drop=True)
            )
    else:
        if name == dataframe.index.name:
            return dataframe.index.to_series().reset_index(drop=True)

    raise ValueError("column or index '{}' not found.".format(name))

def list_columns_and_indexes(dataframe):
    """Return all index and column names with dtypes.

    Returns:
        Sequence[Tuple[str, dtype]]:
            Returns a sorted list of indexes and column names with
            corresponding dtypes. If an index is missing a name or has the
            same name as a column, the index is omitted.
    """
    column_names = frozenset(dataframe.columns)
    columns_and_indexes = []
    if isinstance(dataframe.index, pandas.MultiIndex):
        for name in dataframe.index.names:
            if name and name not in column_names:
                values = dataframe.index.get_level_values(name)
                columns_and_indexes.append((name, values.dtype))
    else:
        if dataframe.index.name and dataframe.index.name not in column_names:
            columns_and_indexes.append((dataframe.index.name, dataframe.index.dtype))

    columns_and_indexes += zip(dataframe.columns, dataframe.dtypes)
    return columns_and_indexes

def _first_valid(series):
    first_valid_index = series.first_valid_index()
    if first_valid_index is not None:
        return series.at[first_valid_index]

def _first_array_valid(series):
    """Return the first "meaningful" element from the array series.

    Here, "meaningful" means the first non-None element in one of the arrays that can
    be used for type detextion.
    """
    first_valid_index = series.first_valid_index()
    if first_valid_index is None:
        return None

    valid_array = series.at[first_valid_index]
    valid_item = next((item for item in valid_array if not pandas.isna(item)), None)

    if valid_item is not None:
        return valid_item

    # Valid item is None because all items in the "valid" array are invalid. Try
    # to find a true valid array manually.
    for array in islice(series, first_valid_index + 1, None):
        try:
            array_iter = iter(array)
        except TypeError:
            continue  # Not an array, apparently, e.g. None, thus skip.
        valid_item = next((item for item in array_iter if not pandas.isna(item)), None)
        if valid_item is not None:
            break

    return valid_item

def dataframe_to_bq_schema(dataframe, bq_schema):
    """Convert a pandas DataFrame schema to a BigQuery schema.

    Args:
        dataframe (pandas.DataFrame):
            DataFrame for which the client determines the BigQuery schema.
        bq_schema (Sequence[Union[ \
            :class:`~google.cloud.bigquery.schema.SchemaField`, \
            Mapping[str, Any] \
        ]]):
            A BigQuery schema. Use this argument to override the autodetected
            type for some or all of the DataFrame columns.

    Returns:
        Optional[Sequence[google.cloud.bigquery.schema.SchemaField]]:
            The automatically determined schema. Returns None if the type of
            any column cannot be determined.
    """
    if bq_schema:
        bq_schema = schema._to_schema_fields(bq_schema)
        bq_schema_index = {field.name: field for field in bq_schema}
        bq_schema_unused = set(bq_schema_index.keys())
    else:
        bq_schema_index = {}
        bq_schema_unused = set()

    bq_schema_out = []
    unknown_type_fields = []

    for column, dtype in list_columns_and_indexes(dataframe):
        # Use provided type from schema, if present.
        bq_field = bq_schema_index.get(column)
        if bq_field:
            bq_schema_out.append(bq_field)
            bq_schema_unused.discard(bq_field.name)
            continue

        # Otherwise, try to automatically determine the type based on the
        # pandas dtype.
        bq_type = _PANDAS_DTYPE_TO_BQ.get(dtype.name)
        if bq_type is None:
            sample_data = _first_valid(dataframe[column])
            if (
                isinstance(sample_data, _BaseGeometry)
                and sample_data is not None  # Paranoia
            ):
                bq_type = "GEOGRAPHY"
        bq_field = schema.SchemaField(column, bq_type)
        bq_schema_out.append(bq_field)

        if bq_field.field_type is None:
            unknown_type_fields.append(bq_field)

    # Catch any schema mismatch. The developer explicitly asked to serialize a
    # column, but it was not found.
    if bq_schema_unused:
        raise ValueError(
            "bq_schema contains fields not present in dataframe: {}".format(
                bq_schema_unused
            )
        )

    # If schema detection was not successful for all columns, also try with
    # pyarrow, if available.
    if unknown_type_fields:
        # The augment_schema() helper itself will also issue unknown type
        # warnings if detection still fails for any of the fields.
        bq_schema_out = augment_schema(dataframe, bq_schema_out)

    return tuple(bq_schema_out) if bq_schema_out else None

def augment_schema(dataframe, current_bq_schema):
    """Try to deduce the unknown field types and return an improved schema.

    This function requires ``pyarrow`` to run. If all the missing types still
    cannot be detected, ``None`` is returned. If all types are already known,
    a shallow copy of the given schema is returned.

    Args:
        dataframe (pandas.DataFrame):
            DataFrame for which some of the field types are still unknown.
        current_bq_schema (Sequence[google.cloud.bigquery.schema.SchemaField]):
            A BigQuery schema for ``dataframe``. The types of some or all of
            the fields may be ``None``.
    Returns:
        Optional[Sequence[google.cloud.bigquery.schema.SchemaField]]
    """
    # pytype: disable=attribute-error
    augmented_schema = []
    unknown_type_fields = []

    for field in current_bq_schema:
        if field.field_type is not None:
            augmented_schema.append(field)
            continue

        arrow_table = pyarrow.array(dataframe[field.name])

        if pyarrow.types.is_list(arrow_table.type):
            # `pyarrow.ListType`
            detected_mode = "REPEATED"
            detected_type = ARROW_SCALAR_IDS_TO_BQ.get(arrow_table.values.type.id)

            # For timezone-naive datetimes, pyarrow assumes the UTC timezone and adds
            # it to such datetimes, causing them to be recognized as TIMESTAMP type.
            # We thus additionally check the actual data to see if we need to overrule
            # that and choose DATETIME instead.
            # Note that this should only be needed for datetime values inside a list,
            # since scalar datetime values have a proper Pandas dtype that allows
            # distinguishing between timezone-naive and timezone-aware values before
            # even requiring the additional schema augment logic in this method.
            if detected_type == "TIMESTAMP":
                valid_item = _first_array_valid(dataframe[field.name])
                if isinstance(valid_item, datetime) and valid_item.tzinfo is None:
                    detected_type = "DATETIME"
        else:
            detected_mode = field.mode
            detected_type = ARROW_SCALAR_IDS_TO_BQ.get(arrow_table.type.id)

        if detected_type is None:
            unknown_type_fields.append(field)
            continue

        new_field = schema.SchemaField(
            name=field.name,
            field_type=detected_type,
            mode=detected_mode,
            description=field.description,
            fields=field.fields,
        )
        augmented_schema.append(new_field)

    if unknown_type_fields:
        warnings.warn(
            "Pyarrow could not determine the type of columns: {}.".format(
                ", ".join(field.name for field in unknown_type_fields)
            )
        )
        return None

    return augmented_schema
    # pytype: enable=attribute-error

def dataframe_to_arrow(dataframe, bq_schema):
    """Convert pandas dataframe to Arrow table, using BigQuery schema.

    Args:
        dataframe (pandas.DataFrame):
            DataFrame to convert to Arrow table.
        bq_schema (Sequence[Union[ \
            :class:`~google.cloud.bigquery.schema.SchemaField`, \
            Mapping[str, Any] \
        ]]):
            Desired BigQuery schema. The number of columns must match the
            number of columns in the DataFrame.

    Returns:
        pyarrow.Table:
            Table containing dataframe data, with schema derived from
            BigQuery schema.
    """
    column_names = set(dataframe.columns)
    column_and_index_names = set(
        name for name, _ in list_columns_and_indexes(dataframe)
    )

    bq_schema = schema._to_schema_fields(bq_schema)
    bq_field_names = set(field.name for field in bq_schema)

    extra_fields = bq_field_names - column_and_index_names
    if extra_fields:
        raise ValueError(
            "bq_schema contains fields not present in dataframe: {}".format(
                extra_fields
            )
        )

    # It's okay for indexes to be missing from bq_schema, but it's not okay to
    # be missing columns.
    missing_fields = column_names - bq_field_names
    if missing_fields:
        raise ValueError(
            "bq_schema is missing fields from dataframe: {}".format(missing_fields)
        )

    arrow_arrays = []
    arrow_names = []
    arrow_fields = []
    for bq_field in bq_schema:
        arrow_names.append(bq_field.name)
        arrow_arrays.append(
            bq_to_arrow_array(get_column_or_index(dataframe, bq_field.name), bq_field)
        )
        arrow_fields.append(bq_to_arrow_field(bq_field, arrow_arrays[-1].type))

    if all((field is not None for field in arrow_fields)):
        return pyarrow.Table.from_arrays(
            arrow_arrays, schema=pyarrow.schema(arrow_fields)
        )
    return pyarrow.Table.from_arrays(arrow_arrays, names=arrow_names)

def dataframe_to_parquet(
    dataframe,
    bq_schema,
    filepath,
    parquet_compression="SNAPPY",
    parquet_use_compliant_nested_type=True,
):
    """Write dataframe as a Parquet file, according to the desired BQ schema.

    This function requires the :mod:`pyarrow` package. Arrow is used as an
    intermediate format.

    Args:
        dataframe (pandas.DataFrame):
            DataFrame to convert to Parquet file.
        bq_schema (Sequence[Union[ \
            :class:`~google.cloud.bigquery.schema.SchemaField`, \
            Mapping[str, Any] \
        ]]):
            Desired BigQuery schema. Number of columns must match number of
            columns in the DataFrame.
        filepath (str):
            Path to write Parquet file to.
        parquet_compression (Optional[str]):
            The compression codec to use by the the ``pyarrow.parquet.write_table``
            serializing method. Defaults to "SNAPPY".
            https://arrow.apache.org/docs/python/generated/pyarrow.parquet.write_table.html#pyarrow-parquet-write-table
        parquet_use_compliant_nested_type (bool):
            Whether the ``pyarrow.parquet.write_table`` serializing method should write
            compliant Parquet nested type (lists). Defaults to ``True``.
            https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#nested-types
            https://arrow.apache.org/docs/python/generated/pyarrow.parquet.write_table.html#pyarrow-parquet-write-table

            This argument is ignored for ``pyarrow`` versions earlier than ``4.0.0``.
    """
    import pyarrow.parquet  # type: ignore

    kwargs = (
        {"use_compliant_nested_type": parquet_use_compliant_nested_type}
        if _helpers.PYARROW_VERSIONS.use_compliant_nested_type
        else {}
    )

    bq_schema = schema._to_schema_fields(bq_schema)
    arrow_table = dataframe_to_arrow(dataframe, bq_schema)
    pyarrow.parquet.write_table(
        arrow_table,
        filepath,
        compression=parquet_compression,
        **kwargs,
    )

def _row_iterator_page_to_arrow(page, column_names, arrow_types):
    # Iterate over the page to force the API request to get the page data.
    try:
        next(iter(page))
    except StopIteration:
        pass

    arrays = []
    for column_index, arrow_type in enumerate(arrow_types):
        arrays.append(pyarrow.array(page._columns[column_index], type=arrow_type))

    if isinstance(column_names, pyarrow.Schema):
        return pyarrow.RecordBatch.from_arrays(arrays, schema=column_names)
    return pyarrow.RecordBatch.from_arrays(arrays, names=column_names)

def download_arrow_row_iterator(pages, bq_schema):
    """Use HTTP JSON RowIterator to construct an iterable of RecordBatches.

    Args:
        pages (Iterator[:class:`google.api_core.page_iterator.Page`]):
            An iterator over the result pages.
        bq_schema (Sequence[Union[ \
            :class:`~google.cloud.bigquery.schema.SchemaField`, \
            Mapping[str, Any] \
        ]]):
            A decription of the fields in result pages.
    Yields:
        :class:`pyarrow.RecordBatch`
        The next page of records as a ``pyarrow`` record batch.
    """
    bq_schema = schema._to_schema_fields(bq_schema)
    column_names = bq_to_arrow_schema(bq_schema) or [field.name for field in bq_schema]
    arrow_types = [bq_to_arrow_data_type(field) for field in bq_schema]

    for page in pages:
        yield _row_iterator_page_to_arrow(page, column_names, arrow_types)

def _row_iterator_page_to_dataframe(page, column_names, dtypes):
    # Iterate over the page to force the API request to get the page data.
    try:
        next(iter(page))
    except StopIteration:
        pass

    columns = {}
    for column_index, column_name in enumerate(column_names):
        dtype = dtypes.get(column_name)
        columns[column_name] = pandas.Series(page._columns[column_index], dtype=dtype)

    return pandas.DataFrame(columns, columns=column_names)

def download_dataframe_row_iterator(pages, bq_schema, dtypes):
    """Use HTTP JSON RowIterator to construct a DataFrame.

    Args:
        pages (Iterator[:class:`google.api_core.page_iterator.Page`]):
            An iterator over the result pages.
        bq_schema (Sequence[Union[ \
            :class:`~google.cloud.bigquery.schema.SchemaField`, \
            Mapping[str, Any] \
        ]]):
            A decription of the fields in result pages.
        dtypes(Mapping[str, numpy.dtype]):
            The types of columns in result data to hint construction of the
            resulting DataFrame. Not all column types have to be specified.
    Yields:
        :class:`pandas.DataFrame`
        The next page of records as a ``pandas.DataFrame`` record batch.
    """
    bq_schema = schema._to_schema_fields(bq_schema)
    column_names = [field.name for field in bq_schema]
    for page in pages:
        yield _row_iterator_page_to_dataframe(page, column_names, dtypes)

def _bqstorage_page_to_arrow(page):
    return page.to_arrow()

def _bqstorage_page_to_dataframe(column_names, dtypes, page):
    # page.to_dataframe() does not preserve column order in some versions
    # of google-cloud-bigquery-storage. Access by column name to rearrange.
    return page.to_dataframe(dtypes=dtypes)[column_names]

def _download_table_bqstorage_stream(
    download_state, bqstorage_client, session, stream, worker_queue, page_to_item
):
    reader = bqstorage_client.read_rows(stream.name)

    # Avoid deprecation warnings for passing in unnecessary read session.
    # https://github.com/googleapis/python-bigquery-storage/issues/229
    if _helpers.BQ_STORAGE_VERSIONS.is_read_session_optional:
        rowstream = reader.rows()
    else:
        rowstream = reader.rows(session)

    for page in rowstream.pages:
        if download_state.done:
            return
        item = page_to_item(page)
        worker_queue.put(item)

def _nowait(futures):
    """Separate finished and unfinished threads, much like
    :func:`concurrent.futures.wait`, but don't wait.
    """
    done = []
    not_done = []
    for future in futures:
        if future.done():
            done.append(future)
        else:
            not_done.append(future)
    return done, not_done

def _download_table_bqstorage(
    project_id,
    table,
    bqstorage_client,
    preserve_order=False,
    selected_fields=None,
    page_to_item=None,
    max_queue_size=_MAX_QUEUE_SIZE_DEFAULT,
):
    """Use (faster, but billable) BQ Storage API to construct DataFrame."""

    # Passing a BQ Storage client in implies that the BigQuery Storage library
    # is available and can be imported.
    from google.cloud import bigquery_storage

    if "$" in table.table_id:
        raise ValueError(
            "Reading from a specific partition is not currently supported."
        )
    if "@" in table.table_id:
        raise ValueError("Reading from a specific snapshot is not currently supported.")

    requested_streams = 1 if preserve_order else 0

    requested_session = bigquery_storage.types.ReadSession(
        table=table.to_bqstorage(), data_format=bigquery_storage.types.DataFormat.ARROW
    )
    if selected_fields is not None:
        for field in selected_fields:
            requested_session.read_options.selected_fields.append(field.name)

    if _ARROW_COMPRESSION_SUPPORT:
        requested_session.read_options.arrow_serialization_options.buffer_compression = (
            ArrowSerializationOptions.CompressionCodec.LZ4_FRAME
        )

    session = bqstorage_client.create_read_session(
        parent="projects/{}".format(project_id),
        read_session=requested_session,
        max_stream_count=requested_streams,
    )

    _LOGGER.debug(
        "Started reading table '{}.{}.{}' with BQ Storage API session '{}'.".format(
            table.project, table.dataset_id, table.table_id, session.name
        )
    )

    # Avoid reading rows from an empty table.
    if not session.streams:
        return

    total_streams = len(session.streams)

    # Use _DownloadState to notify worker threads when to quit.
    # See: https://stackoverflow.com/a/29237343/101923
    download_state = _DownloadState()

    # Create a queue to collect frames as they are created in each thread.
    #
    # The queue needs to be bounded by default, because if the user code processes the
    # fetched result pages too slowly, while at the same time new pages are rapidly being
    # fetched from the server, the queue can grow to the point where the process runs
    # out of memory.
    if max_queue_size is _MAX_QUEUE_SIZE_DEFAULT:
        max_queue_size = total_streams
    elif max_queue_size is None:
        max_queue_size = 0  # unbounded

    worker_queue = queue.Queue(maxsize=max_queue_size)

    with concurrent.futures.ThreadPoolExecutor(max_workers=total_streams) as pool:
        try:
            # Manually submit jobs and wait for download to complete rather
            # than using pool.map because pool.map continues running in the
            # background even if there is an exception on the main thread.
            # See: https://github.com/googleapis/google-cloud-python/pull/7698
            not_done = [
                pool.submit(
                    _download_table_bqstorage_stream,
                    download_state,
                    bqstorage_client,
                    session,
                    stream,
                    worker_queue,
                    page_to_item,
                )
                for stream in session.streams
            ]

            while not_done:
                # Don't block on the worker threads. For performance reasons,
                # we want to block on the queue's get method, instead. This
                # prevents the queue from filling up, because the main thread
                # has smaller gaps in time between calls to the queue's get
                # method. For a detailed explaination, see:
                # https://friendliness.dev/2019/06/18/python-nowait/
                done, not_done = _nowait(not_done)
                for future in done:
                    # Call result() on any finished threads to raise any
                    # exceptions encountered.
                    future.result()

                try:
                    frame = worker_queue.get(timeout=_PROGRESS_INTERVAL)
                    yield frame
                except queue.Empty:  # pragma: NO COVER
                    continue

            # Return any remaining values after the workers finished.
            while True:  # pragma: NO COVER
                try:
                    frame = worker_queue.get_nowait()
                    yield frame
                except queue.Empty:  # pragma: NO COVER
                    break
        finally:
            # No need for a lock because reading/replacing a variable is
            # defined to be an atomic operation in the Python language
            # definition (enforced by the global interpreter lock).
            download_state.done = True

            # Shutdown all background threads, now that they should know to
            # exit early.
            pool.shutdown(wait=True)

def download_arrow_bqstorage(
    project_id,
    table,
    bqstorage_client,
    preserve_order=False,
    selected_fields=None,
    max_queue_size=_MAX_QUEUE_SIZE_DEFAULT,
):
    return _download_table_bqstorage(
        project_id,
        table,
        bqstorage_client,
        preserve_order=preserve_order,
        selected_fields=selected_fields,
        page_to_item=_bqstorage_page_to_arrow,
        max_queue_size=max_queue_size,
    )

def download_dataframe_bqstorage(
    project_id,
    table,
    bqstorage_client,
    column_names,
    dtypes,
    preserve_order=False,
    selected_fields=None,
    max_queue_size=_MAX_QUEUE_SIZE_DEFAULT,
):
    page_to_item = functools.partial(_bqstorage_page_to_dataframe, column_names, dtypes)
    return _download_table_bqstorage(
        project_id,
        table,
        bqstorage_client,
        preserve_order=preserve_order,
        selected_fields=selected_fields,
        page_to_item=page_to_item,
        max_queue_size=max_queue_size,
    )

def dataframe_to_json_generator(dataframe):
    for row in dataframe.itertuples(index=False, name=None):
        output = {}
        for column, value in zip(dataframe.columns, row):
            # Omit NaN values.
            is_nan = pandas.isna(value)

            # isna() can also return an array-like of bools, but the latter's boolean
            # value is ambiguous, hence an extra check. An array-like value is *not*
            # considered a NaN, however.
            if isinstance(is_nan, bool) and is_nan:
                continue
            output[column] = value

        yield output

def verify_pandas_imports():
    if pandas is None:
        raise ValueError(_NO_PANDAS_ERROR) from pandas_import_exception
    if db_dtypes is None:
        raise ValueError(_NO_DB_TYPES_ERROR) from db_dtypes_import_exception


text:
/* global previewMarkdown */
/* exported previewQueueMarkdown */

function previewQueueMarkdown(){
    const announcement_textarea = $('#queue-announcement-message');
    const preview = $('#queue_announcement_message_preview');
    const preview_button = $('button[title="Preview Markdown"]');
    const announcement_content = announcement_textarea.val();

    previewMarkdown(announcement_textarea, preview, preview_button, { content: announcement_content });
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class GoZap extends React.Component<IconBaseProps> { }


text:
<!DOCTYPE html>
<html>
<head>
	<title>HTML5 Pong</title>
	<meta charset="UTF-8">
	<link rel="stylesheet" type="text/css" href="./css/style.css">
	<script type="text/javascript" data-main="js/main.js" src="./js/lib/require.js"></script>
</head>
<body>
</body>
</html>