text:
package gov.opm.scrd.entities.application;

import gov.opm.scrd.entities.common.IdentifiableEntity;
import gov.opm.scrd.entities.lookup.State;
import gov.opm.scrd.entities.lookup.Suffix;

import java.util.Date;

/**
 *

 * This is the class representing the person holding the account.
 *

 *
 *

 * Changes in 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0):
 *

 *
Added fields: position, agencyCode

 *

 *

 *
 *

 * Thread Safety:  This class is mutable and not thread safe.
 *

 *
 * @author faeton, sparemax
 * @version 1.1
 */
public class AccountHolder extends IdentifiableEntity {
    /**
     *

     * Represents the last name of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     */
    private String lastName;
    /**
     *

     * Represents the first name of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     */
    private String firstName;
    /**
     *

     * Represents the middle initial of account holder. It is managed with a getter and setter. It may have any value.
     * It is fully mutable.
     *

     */
    private String middleInitial;
    /**
     *

     * Represents the suffix (Mr., Ms.) of the account holder. It is managed with a getter and setter. It may have any
     * value. It is fully mutable.
     *

     */
    private Suffix suffix;
    /**
     *

     * Represents the birth date of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     */
    private Date birthDate;
    /**
     *

     * Represents the social security number of account holder. It is managed with a getter and setter. It may have any
     * value. It is fully mutable.
     *

     */
    private String ssn;
    /**
     *

     * Represents the telephone of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     */
    private String telephone;
    /**
     *

     * Represents the email of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     */
    private String email;
    /**
     *

     * Represents the title of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     */
    private String title;
    /**
     *

     * Represents the department code of account holder. It is managed with a getter and setter. It may have any value.
     * It is fully mutable.
     *

     */
    private String departmentCode;
    /**
     *

     * Represents the address data of account holder. It is managed with a getter and setter. It may have any value. It
     * is fully mutable.
     *

     */
    private Address address;
    /**
     *

     * Represents the geographical code of account holder. It is managed with a getter and setter. It may have any
     * value. It is fully mutable.
     *

     */
    private String geoCode;
    /**
     *

     * Represents the city of employment of account holder. It is managed with a getter and setter. It may have any
     * value. It is fully mutable.
     *

     */
    private String cityOfEmployment;
    /**
     *

     * Represents the state of employment of account holder. It is managed with a getter and setter. It may have any
     * value. It is fully mutable.
     *

     */
    private State stateOfEmployment;
    /**
     *

     * Represents the position of account holder. It is managed with a getter and setter. It may have any value. It is
     * fully mutable.
     *

     *
     * @since 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0)
     */
    private String position;
    /**
     *

     * Represents the agency code of account holder. It is managed with a getter and setter. It may have any value. It
     * is fully mutable.
     *

     *
     * @since 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0)
     */
    private String agencyCode;

    /**
     * Creates an instance of AccountHolder.
     */
    public AccountHolder() {
        // Empty
    }

    /**
     * Gets the last name of account holder.
     *
     * @return the last name of account holder.
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * Sets the last name of account holder.
     *
     * @param lastName
     *            the last name of account holder.
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * Gets the first name of account holder.
     *
     * @return the first name of account holder.
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * Sets the first name of account holder.
     *
     * @param firstName
     *            the first name of account holder.
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * Gets the middle initial of account holder.
     *
     * @return the middle initial of account holder.
     */
    public String getMiddleInitial() {
        return middleInitial;
    }

    /**
     * Sets the middle initial of account holder.
     *
     * @param middleInitial
     *            the middle initial of account holder.
     */
    public void setMiddleInitial(String middleInitial) {
        this.middleInitial = middleInitial;
    }

    /**
     * Gets the suffix (Mr.
     *
     * @return the suffix (Mr.
     */
    public Suffix getSuffix() {
        return suffix;
    }

    /**
     * Sets the suffix (Mr.
     *
     * @param suffix
     *            the suffix (Mr.
     */
    public void setSuffix(Suffix suffix) {
        this.suffix = suffix;
    }

    /**
     * Gets the birth date of account holder.
     *
     * @return the birth date of account holder.
     */
    public Date getBirthDate() {
        return birthDate;
    }

    /**
     * Sets the birth date of account holder.
     *
     * @param birthDate
     *            the birth date of account holder.
     */
    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    /**
     * Gets the social security number of account holder.
     *
     * @return the social security number of account holder.
     */
    public String getSsn() {
        return ssn;
    }

    /**
     * Sets the social security number of account holder.
     *
     * @param ssn
     *            the social security number of account holder.
     */
    public void setSsn(String ssn) {
        this.ssn = ssn;
    }

    /**
     * Gets the telephone of account holder.
     *
     * @return the telephone of account holder.
     */
    public String getTelephone() {
        return telephone;
    }

    /**
     * Sets the telephone of account holder.
     *
     * @param telephone
     *            the telephone of account holder.
     */
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    /**
     * Gets the email of account holder.
     *
     * @return the email of account holder.
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets the email of account holder.
     *
     * @param email
     *            the email of account holder.
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * Gets the title of account holder.
     *
     * @return the title of account holder.
     */
    public String getTitle() {
        return title;
    }

    /**
     * Sets the title of account holder.
     *
     * @param title
     *            the title of account holder.
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * Gets the department code of account holder.
     *
     * @return the department code of account holder.
     */
    public String getDepartmentCode() {
        return departmentCode;
    }

    /**
     * Sets the department code of account holder.
     *
     * @param departmentCode
     *            the department code of account holder.
     */
    public void setDepartmentCode(String departmentCode) {
        this.departmentCode = departmentCode;
    }

    /**
     * Gets the address data of account holder.
     *
     * @return the address data of account holder.
     */
    public Address getAddress() {
        return address;
    }

    /**
     * Sets the address data of account holder.
     *
     * @param address
     *            the address data of account holder.
     */
    public void setAddress(Address address) {
        this.address = address;
    }

    /**
     * Gets the geographical code of account holder.
     *
     * @return the geographical code of account holder.
     */
    public String getGeoCode() {
        return geoCode;
    }

    /**
     * Sets the geographical code of account holder.
     *
     * @param geoCode
     *            the geographical code of account holder.
     */
    public void setGeoCode(String geoCode) {
        this.geoCode = geoCode;
    }

    /**
     * Gets the city of employment of account holder.
     *
     * @return the city of employment of account holder.
     */
    public String getCityOfEmployment() {
        return cityOfEmployment;
    }

    /**
     * Sets the city of employment of account holder.
     *
     * @param cityOfEmployment
     *            the city of employment of account holder.
     */
    public void setCityOfEmployment(String cityOfEmployment) {
        this.cityOfEmployment = cityOfEmployment;
    }

    /**
     * Gets the state of employment of account holder.
     *
     * @return the state of employment of account holder.
     */
    public State getStateOfEmployment() {
        return stateOfEmployment;
    }

    /**
     * Sets the state of employment of account holder.
     *
     * @param stateOfEmployment
     *            the state of employment of account holder.
     */
    public void setStateOfEmployment(State stateOfEmployment) {
        this.stateOfEmployment = stateOfEmployment;
    }

    /**
     * Gets the position of account holder.
     *
     * @return the position of account holder.
     *
     * @since 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0)
     */
    public String getPosition() {
        return position;
    }

    /**
     * Sets the position of account holder.
     *
     * @param position
     *            the position of account holder.
     *
     * @since 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0)
     */
    public void setPosition(String position) {
        this.position = position;
    }

    /**
     * Gets the agency code of account holder.
     *
     * @return the agency code of account holder.
     *
     * @since 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0)
     */
    public String getAgencyCode() {
        return agencyCode;
    }

    /**
     * Sets the agency code of account holder.
     *
     * @param agencyCode
     *            the agency code of account holder.
     *
     * @since 1.1 (OPM - Data Migration - Entities Update Module Assembly 1.0)
     */
    public void setAgencyCode(String agencyCode) {
        this.agencyCode = agencyCode;
    }
}


text:
'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var DepSchema = new Schema({
  uri: {
    type: String,
    unique: true,
    index: true,
    require: true
  },
  description: String,
  product: String,
  creator: { type: Schema.Types.ObjectId, ref: 'User' },
  createTime: Date,
  pages: [{ type: Schema.Types.ObjectId, ref: 'Page' }],
  jsonpConf: {
    enable: Boolean,
    callback: String
  },
  autoPublish: Boolean,
  lastModified: Date,
  lastPublished: Date
});

module.exports = mongoose.model('Dep', DepSchema);

redpajama_set_name: RedPajamaGithub


text:
- [ ] Check that you are up-to-date with the master branch of keras-vis. You can update with:
pip install git+git://github.com/raghakot/keras-vis.git --upgrade --no-deps

- [ ] If running on TensorFlow, check that you are up-to-date with the latest version. The installation instructions can be found [here](https://www.tensorflow.org/get_started/os_setup).

- [ ] If running on Theano, check that you are up-to-date with the master branch of Theano. You can update with:
pip install git+git://github.com/Theano/Theano.git --upgrade --no-deps

- [ ] Provide a link to a GitHub Gist of a Python script that can reproduce your issue (or just copy the script here if it is short).


text:
namespace MyCrazyProject.Core
{
    using Contracts;
    using Models.Contracts;

    public class Engine : IEngine
    {
        private readonly IWriter fileWriter;
        private readonly IReader consoleReader;

        public Engine(IWriter fileWriter, IReader consoleReader)
        {
            this.fileWriter = fileWriter;
            this.consoleReader = consoleReader;
        }

        public void Run()
        {
            string content = consoleReader.Read();
            this.fileWriter.Write(content);
        }
    }
}


text:
<?php

namespace StoryTellBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * StoryGenre
 *
 * @ORM\Table(name="story_genre")
 * @ORM\Entity(repositoryClass="StoryTellBundle\Repository\StoryGenreRepository")
 */
class StoryGenre
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return StoryGenre
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}


text:
This is `dnstap-ldns`, a reference utility that can decode [dnstap] encoded files. It uses the [ldns], [fstrm], and [protobuf-c] libraries to perform most of the heavy lifting.

## Building

First, install the dependencies: [ldns], [fstrm], and [protobuf-c].

Then, build and install `dnstap-ldns`:

    ./configure && make && make install

If building from a git checkout, the `autotools` must be installed. Run the `./autogen.sh` script first to bootstrap the build system.

## Synopsis

`dnstap` encoded files can be decoded and printed to `stdout` by running `dnstap-ldns -r` on the `dnstap` file.

The output format can be selected by passing additional command-line flags. The `-q` flag specifies the "quiet text" output format, which is compact (one line per `dnstap` frame), and excludes full DNS message details. The `-y` flag specifies a more verbose multi-document YAML-encoded output format that includes full DNS message details, as parsed by the [ldns] library.

`dnstap-ldns` can also read bare hex-encoded dnstap protobufs without Frame Stream encoding. The `-x` flag will automatically detect whether the input data is a string of hex characters (possibly with embedded whitespace), or is in the generic record data format defined by [RFC 3597].

[dnstap]:     http://dnstap.info/
[ldns]:       http://www.nlnetlabs.nl/projects/ldns/
[fstrm]:      https://github.com/farsightsec/fstrm
[protobuf-c]: https://github.com/protobuf-c/protobuf-c
[yaml]:       http://www.yaml.org/
[RFC 3597]:   http://tools.ietf.org/html/rfc3597


text:
#ifndef REDFISH_MSG_MSGR_DOT_H
#define REDFISH_MSG_MSGR_DOT_H

#include "msg/msg.h" /* for msgr_cb_t */

#include <stdint.h> /* for uint32_t, etc. */
#include <unistd.h> /* for size_t */

/** Length of a messenger timeout period in seconds */
#define MSGR_TIMEOUT_PERIOD 1.0

/** Number of messenger time periods to wait before timing out an incoming
 * transactor */
#define MSGR_INCOMING_TIMEO 30

/** The maximum timeout that can be specified, in seconds */
#define MSGR_TIMEOUT_MAX 16384

struct fast_log_mgr;
struct mconn;
struct msgr;

/** Information about a port we are listening on */
struct listen_info {
	/** Callback to invoke on sent/recv */
	msgr_cb_t cb;
	/** Private data to store in transactor */
	void *priv;
	/** TCP port number */
	uint16_t port;
};

/** Configuration to use for a messenger */
struct msgr_conf {
	/** Maximum number of connections to allow. */
	int max_conn;
	/** Maximum number of simultaneous transactors to allow */
	int max_tran;
	/* Number of seconds to allow a TCP connection to sit idle before
	 * tearing it down */
	int tcp_teardown_timeo;
	/** Messenger name.  Will be deep-copied */
	const char *name;
	/** Fast log manager to use for fast logs.  Will be shallow-copied */
	struct fast_log_mgr *fl_mgr;
};

/* The messenger
 *
 * Each messenger has a single thread which is handling potentially thousands of
 * TCP sockets at once. All network I/O is nonblocking. On Linux, we use epoll to
 * handle all these sockets.
 *
 * To use the messenger, you need to structure your code in terms of
 * 'transactors.' Each transactor represents an ongoing transaction.  The
 * messenger will execute callbacks whenever a complete message is sent or
 * received on a connection. It will deal with the tedious details of the socket
 * API like partial reads and writes.
 *
 * All callbacks happen in the context of the messenger thread. That means that
 * we do not need to lock any of the messenger data structures for the duration
 * of the callback. It also means that callbacks should never perform blocking
 * I/O or perform an excessive amount of computation.
 *
 * Opening new TCP sockets is expensive in terms of latency, because of the
 * overhead of the 3-way handshake and other things. So we open a connection
 * (mconn) to service one transactor, we will keep it open and potentially use
 * it for other transactors. The messenger handles all these details behind the
 * scenes. If there is a network problem, the messenger will invoke the callback
 * with an error pointer set to the errno code.
 */

/** Initialize the messenger.
 *
 * @param err			(out param) error buffer
 * @param err_len		length of err
 * @param conf			The messenger configuration
 *
 * @return			the messenger on success; NULL otherwise
 */
extern struct msgr *msgr_init(char *err, size_t err_len,
	const struct msgr_conf *conf);

/** Configure the messenger to listen on a given TCP port.
 *
 * @param msgr		the messenger
 * @param linfo		information about the port to listen on
 * @param err		(out param) error buffer
 * @param err_len	length of err
 *
 * @return		the messenger on success; NULL otherwise
 */
extern void msgr_listen(struct msgr *msgr, const struct listen_info *linfo,
		char *err, size_t err_len);

/** Start the messenger.
 *
 * This starts the messenger thread.  If you have configured the messenger to
 * listen for incoming connections, they will begin to arrive once you call this
 * function.
 *
 * @param msgr		the messenger
 * @param err		(out param) error buffer
 * @param err_len	length of err
 *
 * @return		the messenger on success; NULL otherwise
 */
extern void msgr_start(struct msgr *msgr, char *err, size_t err_len);

/** Allocate a new messenger transactor.
 *
 * We zero-initialize the memory.
 *
 * @param msgr		the messenger
 *
 * @return		A new messenger transactor, or NULL on OOM
 */
extern void *mtran_alloc(struct msgr* msgr);

/** Free a messenger transactor
 *
 * @param tr		The messenger transactor to free
 */
extern void mtran_free(struct mtran *tr);

/** Queue a message for sending
 *
 * If there is a pre-existing connection to the remote host, it will be used.
 * Otherwise, a new connection will be opened.
 *
 * This can be called from any context.
 *
 * @param msgr		the messenger
 * @param tr		the transactor
 * @param cb		Callback to invoke when a complete message is sent.
 * @param priv		Private data for transactor
 * @param m		The message to send.
 * 			This must be dynamically allocated. The messenger will
 * 			take ownership of this pointer and free it later.
 * @param timeo		Timeout in seconds
 */
extern void mtran_send(struct msgr *msgr, struct mtran *tr,
		msgr_cb_t cb, void *priv, struct msg *m, int timeo);

/** Queue a message for sending on a currently open connection
 *
 * This must be called from the context of a msgr_cb_t function.
 *
 * @param conn		the connection that the transactor is associated with
 * @param tr		the transactor
 * @param m		The message to send.
 * 			This must be dynamically allocated. The messenger will
 * 			take ownership of this pointer and free it later.
 * @param timeo		Timeout in seconds
 */
extern void mtran_send_next(struct mconn *conn, struct mtran *tr,
			struct msg *m, int timeo);

/** Register to receive a message from a currently open connection
 *
 * This must be called from the context of a msgr_cb_t function.
 *
 * @param conn		the connection that the transactor is associated with
 * @param tr		the transactor
 */
extern void mtran_recv_next(struct mconn *conn, struct mtran *tr);

/** Cancel all connections to a particular endpoint
 *
 * This must be called from the context of a msgr_cb_t function.
 *
 * @param conn		the connection that the transactor is associated with
 * @param tr		the transactor
 *
 * @return		0 on success; -ENOMEM on OOM
 */
extern int mconn_cancel(struct msgr *msgr, uint32_t addr, uint16_t port);

/** Get the messenger associated with a connection
 *
 * @param conn		The connection
 *
 * @return		A pointer to the messenger
 */
extern struct msgr *mconn_get_msgr(struct mconn *conn);

/** Shut down a messenger.
 *
 * Shutdown will close all open connections and join the messenger thread.
 * Currently pending messages will receive ECANCELED.  Further attempts to send
 * messages through the messenger will result in ECANCELED getting delivered
 * immediately.
 *
 * @param msgr		The messenger
 */
extern void msgr_shutdown(struct msgr *msgr);

/** Free the memory associated with a messenger.
 *
 * You can only free messengers that have been shut down (or never started up in
 * the first place.)  Before you free a messenger, you must make absolutely sure
 * that no threads are referencing it.  Most likely this means you will need to
 * join those threads.
 *
 * @param msgr		The messenger
 */
extern void msgr_free(struct msgr *msgr);

#endif


text:
class Admin::PaymentsController < Admin::BaseController
  resource_controller
  belongs_to :order
  ssl_required
end


text:
                <button type="button" class="close"
                        data-dismiss="modal">
                    ×
                    Close
                </button>

                    Modal title

                <form class="form-horizontal" role="form">

                        Email

                            <input type="email" class="form-control"
                                   id="inputEmail3" placeholder="Email"/>

                        Password

                            <input type="password" class="form-control"
                                   id="inputPassword3" placeholder="Password"/>

                                    <input type="checkbox"/> Remember me

                            <button type="submit" class="btn btn-default">Sign in</button>

                </form>

                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    Close
                </button>
                <button type="button" class="btn btn-primary">
                    Save changes
                </button>

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModalNorm">
    Launch Normal Form
</button>

                <button type="button" class="close"
                        data-dismiss="modal">
                    ×
                    Close
                </button>

                    Modal title

                <form role="form">

                        Email address
                        <input type="email" class="form-control"
                               id="exampleInputEmail1" placeholder="Enter email"/>

                        Password
                        <input type="password" class="form-control"
                               id="exampleInputPassword1" placeholder="Password"/>

                            <input type="checkbox"/> Check me out

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    Close
                </button>
                <button type="button" class="btn btn-primary">
                    Save changes
                </button>


text:
Vulkan may use memory as one of two types of memory objects : buffers and images.

Images are used as simple textures that you place on top of the geometries, you may also use images to store results of rendering ( framebuffer images, swapchain images ) and many more.

Similarly you may use buffers as vertex buffers that send vertex data to vertex shaders, you may also use it as uniform buffers, storage buffers, etc.

In Pumex library each of these objects is implemented using **pumex::MemoryBuffer** and **pumex::MemoryImage** class - both classes derive from common **pumex::MemoryObject** class.

## pumex::MemoryBuffer and pumex:Buffer<T>

pumex::Buffer class is a convenient interface to pumex::MemoryBuffer.

It may represent a single structure defined by user :

```
std::shared_ptr<pumex::Buffer<MyStructure>> buffer;
```

or it may store a vector of objects defined by user :

```
std::shared_ptr<pumex::Buffer<std::vector<MyStructure>>> buffer;
```

To make structure defined by user fully visible to shaders - this structure must obey its alignment rules :

- for uniform buffers it may obey std140 rules
- for storage buffers it must obey std430 rules

Hint: the simplest way to have these requirements met is to use glm::vec4 and glm::mat4 variables only. See [tutorial](tutorial.md) .

**pumex::Buffer** class has two constructors available :

- we use first constructor when data stored on GPU side may be different for each surface or device ( like for example when buffer stores camera parameters and these parameters are different for each surface ) :

```
Buffer::Buffer(std::shared_ptr<DeviceMemoryAllocator> allocator, VkBufferUsageFlags bufferUsage, PerObjectBehaviour perObjectBehaviour = pbPerDevice, SwapChainImageBehaviour swapChainImageBehaviour = swForEachImage, bool useSetDataMethods = true);
```

- second constructor is used when data must be the same on each device or surface ( for example when positions of rendered objects are independent from surface that renders it ) - in that case constructor ensures that pointer to data is stored internally in **pumex::Buffer** instance.

```
Buffer::Buffer(std::shared_ptr<T> data, std::shared_ptr<DeviceMemoryAllocator> allocator, VkBufferUsageFlags bufferUsage, PerObjectBehaviour perObjectBehaviour, SwapChainImageBehaviour swapChainImageBehaviour);
```

Constructor parameters :

- allocator - allocates GPU/CPU memory that Vulkan will use.
- bufferUsage - every created buffer must declare its usage ( will it be used as vertex buffer, index buffer, uniform buffer, etc)
- perObjectBehaviour - buffer may allocate its copies **on each used device** ( pumex::pbPerDevice ) or **on each used surface** ( pumex::pbPerSurface ).
- swapChainImageBehaviour - on each device/surface buffer will have only one copy ( pumex::swOnce ), or it will have as many copies as there is swapchain images ( pumex::swForEachImage )
- useSetDataMethods - buffer must declare if it will be sending data using *setData()* methods. Some buffers do not need to use setData(), because for example its data is generated by compute shaders. This variable is always true for buffers created using second constructor.
- data - data used by second constructor.

During command buffer building surface uses as many primary command buffers as there is swapchain images. If you use three swapchain images - surface creates three primary command buffers : one for each swapchain image. When you acquire a swapchain image - it means that corresponding command buffer is not in use and may be rebuilt if required - or it may just be submited to queue instantly when there's no need to rebuild.

Question is : in what situation there is a need to rebuild a primary command buffer?

For memory buffers the answer is simple: when buffer was removed and created again. When does that happen ? When you want to change the size of the buffer. You may do it only by destroying old buffer and creating a new one with bigger size.

If you have buffer created with **pumex::swOnce** flag - it means that all three primary command buffers use the same buffer and at least one of them is currently executed on GPU ( command buffer is in pending state ). You cannot remove a memory buffer which is used by command buffer in pending state.

Conclusion : **WHEN YOU KNOW THAT YOUR BUFFER WILL NOT CHANGE SIZE DURING ITS LIFETIME - USE pumex::swOnce FLAG DURING CREATION. **
**OTHERWISE ALWAYS USE pumex::swForEachImage FLAG** .

*setData()* and *setBufferSize()* methods declared in pumex::Buffer class have a group of limitations listed below :

- **void setData(const T& dt)** - sets data for all surfaces/devices. May be called only when buffer was created with **second** constructor
- **void setData(Surface\* surface, std::shared_ptr<T> data)** - sets data for specific surface. May only be called when
  - buffer was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerSurface
  - useSetDataMethods is equal to true
- **void setData(Surface\* surface, const T& data)** - same as previous one
- **void setData(Device\* device, std::shared_ptr<T> data)** - sets data for specific device. May only be called when
  - buffer was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerDevice
  - useSetDataMethods is equal to true
- **void setData(Device\* device, const T& data)** - same as previous one
- **std::shared_ptr<T> getData()** - may be called only when object was created using **second** constructor
- **void invalidateData()** -  may be called only when object was created using **second** constructor. After modyfying data pointed by buffer this method should be called to inform buffer that data needs validation.
- **void setBufferSize(Surface\* surface, size_t bufferSize)** - sets buffer size for specific surface. May be called only when object was created using **first** constructor. This method works when perObjectBehaviour is pumex::pbPerSurface
- **void setBufferSize(Device\* device, size_t bufferSize)** - sets data for specific device. May be called only when object was created using **first** constructor. This method works when perObjectBehaviour is pumex::pbPerDevice

When user calls *setData()*, or *setBufferSize()* methods - the actual operations that update the buffers on GPU side are not called immediately, but are postponed to node validation phase ( for vertex and index buffers ) or to descriptor validation phase - for uniform buffers, storage buffers, etc ( see: [Main render loop](render_loop.md) ).

## pumex::MemoryImage

**pumex::MemoryImage** class is similar to its buffer counterpart. Main difference is that it only accepts **gli::texture** objects as the ones storing image data. Also there are more methods to manipulate the data.

As with the **pumex::Buffer** class we have two similar constructors :

- first one is able to use different data on each device/surface ( in case of MemoryImage it not only means that pixels are different, but also that VkImage properties declared by **pumex::ImageTraits** may be different for each surface/device )

```
MemoryImage::MemoryImage(const ImageTraits& imageTraits, std::shared_ptr<DeviceMemoryAllocator> allocator, VkImageAspectFlags aspectMask, PerObjectBehaviour perObjectBehaviour = pbPerDevice, SwapChainImageBehaviour swapChainImageBehaviour = swForEachImage, bool sameTraitsPerObject = true, bool useSetImageMethods = true);
```

- second one has the same data on each device / surface

```
MemoryImage::MemoryImage(std::shared_ptr<gli::texture> texture, std::shared_ptr<DeviceMemoryAllocator> allocator, VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_SAMPLED_BIT, PerObjectBehaviour perObjectBehaviour = pbPerDevice);
```

Constructor parameters :

- imageTraits - describes properties of a *VkImage* created on a device / surface, such as :
  - image usage ( *VkImageUsageFlags* )
  - image format ( *VkFormat* )
  - image extent ( *VkExtent3D* )
  - number of mipmap levels
  - number of array layers
  - number of samples per texel
  - initial image layout ( *VkImageLayout* )
  - image type ( *VkImageType* )
  - and others...
- allocator - allocates GPU/CPU memory that Vulkan will use.
- aspectMask - image aspect mask ( *VkImageAspectFlags*  )
- perObjectBehaviour - image may allocate its copies **on each used device** ( pumex::pbPerDevice ) or **on each used surface** ( pumex::pbPerSurface ).
- swapChainImageBehaviour - on each device/surface image will have only one copy ( pumex::swOnce ), or it will have as many copies as there is swapchain images ( pumex::swForEachImage )
- sameTraitsPerObject - image declares if imageTraits will be the same for all VkImage copies on GPU
- useSetImageMethods - image must declare if it will be sending data using *setImage()* methods. Some images do not need to use setImage(), because for example its data is created during render pass on a GPU side. This variable is always true for images created using second constructor.
- texture - gli::texture object that will be the same for all VkImage copies on GPU side

Remarks concerning  **pumex::swOnce** and **pumex::swForEachImage** meant for buffers also apply to images.

*setImageTraits()*, *setImage()* and *clearImage()* methods have following limitations :

- **void setImageTraits(const ImageTraits& traits)** - sets image traits for all surfaces/devices. May be called only when image was created by **second** constructor.
- **void setImageTraits(Surface\* surface, const ImageTraits& traits)** - sets image traits for specific surface. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerSurface
- **void setImageTraits(Device\* device, const ImageTraits& traits)** - sets image traits for specific device. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerDevice
- **void setImage(Surface\* surface, std::shared_ptr<gli::texture> tex)** - sets image data for specific surface. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerSurface
  - useSetImageMethods is equal to true
- **void setImage(Device\* device, std::shared_ptr<gli::texture> tex)** - sets image data for specific device. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerDevice
  - useSetImageMethods is equal to true
- **void setImages(Surface\* surface, std::vector<std::shared_ptr<Image>>& images)** - sets images created outside MemoryImage as internal. This method is used to register swapchain images, as a objects belonging to MemoryImage. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerSurface
  - sameTraitsPerObject is equal to false
- **void setImages(Device\* device, std::vector<std::shared_ptr<Image>>& images)** - sets images created outside MemoryImage as internal. This method is used to register swapchain images, as a objects belonging to MemoryImage. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerDevice
  - sameTraitsPerObject is equal to false
- **void clearImages(const glm::vec4& clearValue, const ImageSubresourceRange& range)** - clears image with provided value on for all surfaces/devices
- **void clearImage(Surface\* surface, const glm::vec4& clearValue, const ImageSubresourceRange& range)** - clears image with provided value on a specific surface. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerSurface
- **void clearImage(Device\* device, const glm::vec4& clearValue, const ImageSubresourceRange& range)** - clears image with provided value on a specific surface. May only be called when:
  - image was created by **first** constructor
  - perObjectBehaviour is equal to pumex::pbPerDevice

## Descriptor resources

Buffers and images are not used directly in Pumex ( except for vertex and index buffers ), but through descriptors. Descriptor requires **pumex::Resource** class descendant to know how to interpret data in buffer or image.

Currently Pumex library has following **pumex::Resource** descendants for buffers :

- **pumex::UniformBuffer**
- **pumex::StorageBuffer**

There are following **pumex::Resource** descendants available for **pumex::MemoryImage** :

- **pumex::SampledImage**
- **pumex::StorageImage**
- **pumex::CombinedImageSampler**
- **pumex::InputAttachment**

There is also one resource that is not associated directly with Images, but it's necessary for sampllng pumex::SampledImage in a shaders :

- **pumex::Sampler**

## Examples

MemoryBuffers are connected to resource directly :

```
auto cameraBuffer = std::make_shared<pumex::Buffer<pumex::Camera>>(buffersAllocator, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, pumex::pbPerSurface, pumex::swOnce, true);

auto descriptorSet = std::make_shared<pumex::DescriptorSet>(descriptorPool, descriptorSetLayout);
descriptorSet->setDescriptor(0, std::make_shared<pumex::UniformBuffer>(cameraBuffer));
```

MemoryImages are connected to Resource through ImageView class :

```
auto volumeMemoryImage = std::make_shared<pumex::MemoryImage>(volumeImageTraits, volumeAllocator, VK_IMAGE_ASPECT_COLOR_BIT, pumex::pbPerSurface, pumex::swOnce);

auto volumeImageView = std::make_shared<pumex::ImageView>(volumeMemoryImage, volumeMemoryImage->getFullImageRange(), VK_IMAGE_VIEW_TYPE_3D);

auto descriptorSet = std::make_shared<pumex::DescriptorSet>(descriptorPool, descriptorSetLayout);
descriptorSet->setDescriptor(0, std::make_shared<pumex::SampledImage>(volumeImageView));
```

There exists another way to connect images and buffers - when images or buffers are associated to **render graphs** ( using **viewer->getExternalMemoryObjects()->addMemoryObject()** method before render graph is compiled ). In case of images **pumex::RenderWorkflow** creates pumex::ImageView objects for us :

```
auto volumeMemoryImage = std::make_shared<pumex::MemoryImage>(volumeImageTraits, volumeAllocator, VK_IMAGE_ASPECT_COLOR_BIT, pumex::pbPerSurface, pumex::swOnce);

pumex::ResourceDefinition image_3d(pumex::rmtImage, "image_3d");

viewer->getExternalMemoryObjects()->addMemoryObject("voxels", image_3d, volumeMemoryImage, VK_IMAGE_VIEW_TYPE_3D);

auto descriptorSet = std::make_shared<pumex::DescriptorSet>(descriptorPool, descriptorSetLayout);
descriptorSet->setDescriptor(0, std::make_shared<pumex::StorageImage>("voxels"));
```

Input attachments are created internally by **pumex::RenderWorkflow**. Each input attachment is associated to a render graph by default. To sample input attachment as an image you need to :

- provide sampler in pumex::InputAttachment constructor
- use provided external sampler in a shader.

First case looks like this :

```
auto iaSampler = std::make_shared<pumex::Sampler>(pumex::SamplerTraits());

auto descriptorSet = std::make_shared<pumex::DescriptorSet>(descriptorPool, descriptorSetLayout);
descriptorSet->setDescriptor(0, std::make_shared<pumex::InputAttachment>("albedo", iaSampler));
```

Second case :

```
auto descriptorSet = std::make_shared<pumex::DescriptorSet>(descriptorPool, descriptorSetLayout);
descriptorSet->setDescriptor(0, std::make_shared<pumex::InputAttachment>("albedo"));
descriptorSet->setDescriptor(1, std::make_shared<pumex::Sampler>(pumex::SamplerTraits()));
```


text:
package play.core.j

import play.api.mvc._
import play.templates._

/** Defines a magic helper for Play templates in a Java context. */
object PlayMagicForJava {

  import scala.collection.JavaConverters._
  import scala.language.implicitConversions

  /** Transforms a Play Java `Option` to a proper Scala `Option`. */
  implicit def javaOptionToScala[T](x: play.libs.F.Option[T]): Option[T] = x match {
    case x: play.libs.F.Some[_] => Some(x.get)
    case x: play.libs.F.None[_] => None
  }

  implicit def implicitJavaLang: play.api.i18n.Lang = {
    try {
      play.mvc.Http.Context.Implicit.lang.asInstanceOf[play.api.i18n.Lang]
    } catch {
      case _: Throwable => play.api.i18n.Lang.defaultLang
    }
  }

  /**
   * Implicit conversion of a Play Java form `Field` to a proper Scala form `Field`.
   */
  implicit def javaFieldtoScalaField(jField: play.data.Form.Field): play.api.data.Field = {

    new play.api.data.Field(
      null,
      jField.name,
      jField.constraints.asScala.map { jT =>
        jT._1 -> jT._2.asScala
      },
      Option(jField.format).map(f => f._1 -> f._2.asScala),
      jField.errors.asScala.map { jE =>
        play.api.data.FormError(
          jE.key,
          jE.message,
          jE.arguments.asScala)
      },
      Option(jField.value)) {

      override def apply(key: String) = {
        javaFieldtoScalaField(jField.sub(key))
      }

      override lazy val indexes = jField.indexes.asScala.toSeq.map(_.toInt)

    }
  }

  implicit def requestHeader: play.api.mvc.RequestHeader = {
    play.mvc.Http.Context.Implicit.ctx._requestHeader
  }

}


text:
package org.hisp.dhis.system.objectmapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.hisp.dhis.datavalue.DeflatedDataValue;
import org.hisp.quick.mapper.RowMapper;

/**
 * @author Lars Helge Overland
 * @version $Id$
 */
public class DeflatedDataValueRowMapper
    implements RowMapper<DeflatedDataValue>, org.springframework.jdbc.core.RowMapper<DeflatedDataValue>
{
    @Override
    public DeflatedDataValue mapRow( ResultSet resultSet )
        throws SQLException
    {
        final DeflatedDataValue value = new DeflatedDataValue();

        value.setDataElementId( resultSet.getLong( "dataelementid" ) );
        value.setPeriodId( resultSet.getLong( "periodid" ) );
        value.setSourceId( resultSet.getLong( "sourceid" ) );
        value.setCategoryOptionComboId( resultSet.getLong( "categoryoptioncomboid" ) );
        value.setValue( resultSet.getString( "value" ) );
        value.setStoredBy( resultSet.getString( "storedby" ) );
        value.setCreated( resultSet.getTimestamp( "created" ) );
        value.setLastUpdated( resultSet.getTimestamp( "lastupdated" ) );
        value.setComment( resultSet.getString( "comment" ) );

        return value;
    }

    @Override
    public DeflatedDataValue mapRow( ResultSet resultSet, int rowNum )
        throws SQLException
    {
        return mapRow( resultSet );
    }
}


text:
<!DOCTYPE html>
<html>
<head>
	<title>Holi</title>

	<img src="http://placekitten.com/g/320/261" id="photo" alt="photo">
</head>
<body>
	<!--
		Ideally these elements aren't created until it's confirmed that the
		client supports video/camera, but for the sake of illustrating the
		elements involved, they are created with markup (not JavaScript)
	-->
	<video id="video" width="640" height="480" autoplay></video>
	<button id="snap">Snap Photo</button>
	<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>


text:
package com.fishercoder;

import com.fishercoder.solutions._71;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _71Test {
    private static _71.Solution1 solution1;

    @BeforeClass
    public static void setup() {
        solution1 = new _71.Solution1();
    }

    @Test
    public void test1() {
        assertEquals("/home", solution1.simplifyPath("/home/"));
    }

    @Test
    public void test2() {
        assertEquals("/c", solution1.simplifyPath("/a/./b/../../c/"));
    }

    @Test
    public void test3() {
        assertEquals("/a/b/c", solution1.simplifyPath("/a//b////c/d//././/.."));
    }

    @Test
    public void test4() {
        assertEquals("/", solution1.simplifyPath("/."));
    }
}


text:
//
//  TemplateShorthands-Private.h
//  Example
//
//  Created by Nicolas Goles on 9/2/13.
//  Copyright (c) 2013 HopIn. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 This is used to access the Category internals while testing, you don't
 really need to import it anywhere in your code.
 - Nicolas Goles Domic.
 */

@interface NSDictionary (TemplateShorthandsPrivate)

/** Core Template Resolving Methods */
- (NSDictionary *)expandDocument:(NSDictionary *)document withDocumentKeys:(NSDictionary *) links;
- (NSMutableDictionary *)subDocumentWithLinks:(NSDictionary *)links key:(id)documentKey andDocument:(NSDictionary *)document;
- (NSDictionary *)defaultDocumentWithId:(NSString *)documentId andExpandedURL:(NSString *)expandedURL;
- (NSMutableDictionary *)expandLinksInDocument:(NSDictionary *)document withDocumentLinks:(NSDictionary *) links;
- (NSDictionary *)objectKeysDictionaryFromDictionary:(NSDictionary *)jsonDocument;

/** Document Handling & Manipulation Helpers */
- (NSDictionary *)linkedResourceWithKey:(NSString *)key andIdentifier:(NSString *)guid;
- (NSString *)extractURLFromResourceDescription:(id)description;
- (void)replaceObjectWithArrayInDocument:(NSMutableDictionary *)document withKey:(NSString *)key;
- (void)assignLinkedDocument:(NSDictionary *)linkedDoc toDocument:(NSMutableDictionary *)document withKey:(NSString *)key andURL:(NSString *)expandedURL;

/** Shorthands Template & String Manipulation */
- (NSArray *)extractDocumentKeysFromString:(NSString *)key;
- (NSString *)extractTemplateFromURL:(NSString *)bracedURL;
- (NSString *)replaceTemplateInURL:(NSString *)bracedURL withString:(NSString *)replacement;
- (NSString *)expandURL:(NSString *)url withReplacement:(NSString *)replacement;
@end


text:
package com.heliosapm.metrichub.speedment.tsdb.public_.tsd_annotation.generated;

import com.heliosapm.metrichub.speedment.tsdb.public_.tsd_annotation.TsdAnnotation;
import com.speedment.runtime.core.manager.Manager;
import javax.annotation.Generated;

/**
 * The generated base interface for the manager of every {@link
 * com.heliosapm.metrichub.speedment.tsdb.public_.tsd_annotation.TsdAnnotation}
 * entity.
 * <p>
 * This file has been automatically generated by Speedment. Any changes made to
 * it will be overwritten.
 *
 * @author Speedment
 */
@Generated("Speedment")
public interface GeneratedTsdAnnotationManager extends Manager<TsdAnnotation> {

    @Override
    default Class<TsdAnnotation> getEntityClass() {
        return TsdAnnotation.class;
    }
}


text:
import Ember from 'ember';

/**
 Extends Ember.TextArea to add Bootstrap's 'form-control' class.

 @class Textarea
 @namespace Components
 @extends Ember.TextArea
 @public
 */
export default Ember.TextArea.extend({
  classNames: ['form-control']
});


text:
package sangria.macros

import sangria.parser.{QueryParser, SyntaxError}

import scala.reflect.macros.blackbox

class ParseMacro(context: blackbox.Context)
    extends {
      val c = context
    }
    with MacroAstLiftable {

  import c.universe._

  def impl(args: Expr[Any]*) =
    if (args.nonEmpty)
      c.abort(
        c.enclosingPosition,
        "String interpolation is not supported for `graphql`/`gql` macro at the moment.")
    else
      c.prefix.tree match {
        // Expects a string interpolation that doesn't contain any
        // expressions, thus containing only a single tree
        case Apply(_, List(Apply(_, t :: Nil))) =>
          val q"${gql: String}" = t

          try q"${QueryParser.parse(gql).get}"
          catch {
            case error: SyntaxError => syntaxError(error)
          }
        case _ =>
          c.abort(c.enclosingPosition, "Invalid `graphql` invocation syntax.")
      }

  def implInput(args: Expr[Any]*) =
    if (args.nonEmpty)
      c.abort(
        c.enclosingPosition,
        "String interpolation is not supported for `graphqlInput`/`gqlInp` macro at the moment.")
    else
      c.prefix.tree match {
        // Expects a string interpolation that doesn't contain any
        // expressions, thus containing only a single tree
        case Apply(_, List(Apply(_, t :: Nil))) =>
          val q"${gql: String}" = t

          try q"${QueryParser.parseInput(gql).get}"
          catch {
            case error: SyntaxError => syntaxError(error)
          }
        case _ =>
          c.abort(c.enclosingPosition, "Invalid `graphql` invocation syntax.")
      }

  def implInputDoc(args: Expr[Any]*) =
    if (args.nonEmpty)
      c.abort(
        c.enclosingPosition,
        "String interpolation is not supported for `gqlInpDoc` macro at the moment.")
    else
      c.prefix.tree match {
        // Expects a string interpolation that doesn't contain any
        // expressions, thus containing only a single tree
        case Apply(_, List(Apply(_, t :: Nil))) =>
          val q"${gql: String}" = t

          try q"${QueryParser.parseInputDocument(gql).get}"
          catch {
            case error: SyntaxError => syntaxError(error)
          }
        case _ =>
          c.abort(c.enclosingPosition, "Invalid `graphql` invocation syntax.")
      }

  def syntaxError(error: SyntaxError) = {
    val errorPos = error.originalError.position
    val enclosingCol = if (errorPos.line == 1) calcStringStart else 0
    val source = c.enclosingPosition.source
    val line = source.lineToOffset(c.enclosingPosition.line + (errorPos.line - 2))
    val col = line + enclosingCol + (errorPos.column - 1)
    val pos = c.enclosingPosition.withPoint(col)

    c.abort(pos, error.formattedError(showPosition = false))
  }

  def calcStringStart: Int = {
    val source = c.enclosingPosition.source
    val content = source.lineToString(c.enclosingPosition.line - 1)
    val contentStart = content.substring(c.enclosingPosition.column - 1)
    val offset = "(\\w+\"+)".r.findFirstMatchIn(contentStart).fold(0)(_.end)

    c.enclosingPosition.column - 1 + offset
  }
}


text:
"""
Tests for projectq.backends.circuits._drawer.py.
"""

import pytest

import projectq.backends._circuits._drawer as _drawer
from projectq import MainEngine
from projectq.backends._circuits._drawer import CircuitDrawer, CircuitItem
from projectq.ops import CNOT, Command, H, Measure, X
from projectq.types import WeakQubitRef

class MockInputFunction:
    def __init__(self, return_value=None):
        self.return_value = return_value
        self._orig_input_fn = __builtins__['input']

    def _mock_input_fn(self, prompt):
        print(prompt + str(self.return_value))
        return self.return_value

    def __enter__(self):
        __builtins__['input'] = self._mock_input_fn

    def __exit__(self, type, value, traceback):
        __builtins__['input'] = self._orig_input_fn

@pytest.mark.parametrize("ordered", [False, True])
def test_drawer_getlatex(ordered):
    old_latex = _drawer.to_latex
    _drawer.to_latex = lambda x, drawing_order, draw_gates_in_parallel: x

    drawer = CircuitDrawer()
    drawer.set_qubit_locations({0: 1, 1: 0})

    drawer2 = CircuitDrawer()

    eng = MainEngine(drawer, [drawer2])
    qureg = eng.allocate_qureg(2)
    H | qureg[1]
    H | qureg[0]
    X | qureg[0]
    CNOT | (qureg[0], qureg[1])

    lines = drawer2.get_latex(ordered=ordered)
    assert len(lines) == 2
    assert len(lines[0]) == 4
    assert len(lines[1]) == 3

    # check if it was sent on correctly:
    lines = drawer.get_latex(ordered=ordered)
    assert len(lines) == 2
    assert len(lines[0]) == 3
    assert len(lines[1]) == 4

    _drawer.to_latex = old_latex

def test_drawer_measurement():
    drawer = CircuitDrawer(default_measure=0)
    eng = MainEngine(drawer, [])
    qubit = eng.allocate_qubit()
    Measure | qubit
    assert int(qubit) == 0

    drawer = CircuitDrawer(default_measure=1)
    eng = MainEngine(drawer, [])
    qubit = eng.allocate_qubit()
    Measure | qubit
    assert int(qubit) == 1

    drawer = CircuitDrawer(accept_input=True)
    eng = MainEngine(drawer, [])
    qubit = eng.allocate_qubit()

    with MockInputFunction(return_value='1'):
        Measure | qubit
        assert int(qubit) == 1

    qb1 = WeakQubitRef(engine=eng, idx=1)
    qb2 = WeakQubitRef(engine=eng, idx=2)
    with pytest.raises(ValueError):
        eng.backend._print_cmd(Command(engine=eng, gate=Measure, qubits=([qb1],), controls=[qb2]))

def test_drawer_qubitmapping():
    drawer = CircuitDrawer()
    # mapping should still work (no gate has been applied yet)
    valid_mappings = [{0: 1, 1: 0}, {2: 1, 1: 2}]
    for valid_mapping in valid_mappings:
        drawer.set_qubit_locations(valid_mapping)
        drawer = CircuitDrawer()

    # invalid mapping should raise an error:
    invalid_mappings = [{3: 1, 0: 2}, {0: 1, 2: 1}]
    for invalid_mapping in invalid_mappings:
        drawer = CircuitDrawer()
        with pytest.raises(RuntimeError):
            drawer.set_qubit_locations(invalid_mapping)

    eng = MainEngine(drawer, [])
    qubit = eng.allocate_qubit()  # noqa: F841
    # mapping has begun --> can't assign it anymore
    with pytest.raises(RuntimeError):
        drawer.set_qubit_locations({0: 1, 1: 0})

class MockEngine:
    def is_available(self, cmd):
        self.cmd = cmd
        self.called = True
        return False

def test_drawer_isavailable():
    drawer = CircuitDrawer()
    drawer.is_last_engine = True

    assert drawer.is_available(None)
    assert drawer.is_available("Everything")

    mock_engine = MockEngine()
    mock_engine.called = False
    drawer.is_last_engine = False
    drawer.next_engine = mock_engine

    assert not drawer.is_available(None)
    assert mock_engine.called
    assert mock_engine.cmd is None

def test_drawer_circuititem():
    circuit_item = CircuitItem(1, 2, 3)
    assert circuit_item.gate == 1
    assert circuit_item.lines == 2
    assert circuit_item.ctrl_lines == 3
    assert circuit_item.id == -1

    circuit_item2 = CircuitItem(1, 2, 2)
    assert not circuit_item2 == circuit_item
    assert circuit_item2 != circuit_item

    circuit_item2.ctrl_lines = 3
    assert circuit_item2 == circuit_item
    assert not circuit_item2 != circuit_item

    circuit_item2.gate = 2
    assert not circuit_item2 == circuit_item
    assert circuit_item2 != circuit_item

    circuit_item2.gate = 1
    assert circuit_item2 == circuit_item
    assert not circuit_item2 != circuit_item

    circuit_item2.lines = 1
    assert not circuit_item2 == circuit_item
    assert circuit_item2 != circuit_item

    circuit_item2.lines = 2
    assert circuit_item2 == circuit_item
    assert not circuit_item2 != circuit_item


text:
import { ItemTemplate, RootObject } from '@core';

import { AvatarCustomization } from '@outcome/avatarCustomization';
import { Pipeline } from '@core/pipeline';

/**
 * Represents the Pipeline which converts Game Master Avatar Customization related
 * input data to AvatarCustomization models
 */
export class AvatarCustomizationPipeline extends Pipeline {
  constructor(input: RootObject) {
    super(input, 'avatarCustomization');
  }

  /**
   * Checks if the given ItemTemplate is indeed an avatar customization
   */
  isItemTemplate(item: ItemTemplate): boolean {
    return new RegExp('^(AVATAR_?.*)', 'g').test(item.templateId);
  }
}


text:
import thunkMiddleware from 'redux-thunk';
import { createStore, compose, combineReducers, applyMiddleware } from 'redux';
import { routerReducer } from 'react-router-redux';

import artists from '../reducers/artists';
import albums from '../reducers/albums';
import application from '../reducers/application';

const customCreateStore = compose(
  applyMiddleware(thunkMiddleware),
  (window.devToolsExtension ? window.devToolsExtension() : f => f)
)(createStore);

const reducers = combineReducers({
  routing: routerReducer,

  application,
  artists,
  albums,
});

export default customCreateStore(reducers);


text:
package edu.hm.cs.jenkins.notifier.provider;

import com.google.inject.Provider;

import java.awt.*;

/**
 * Provides an instance of {@link java.awt.GraphicsConfiguration}.
 *
 * @author Tobias Wochinger
 */
public class GraphicsConfigurationProvider implements Provider<GraphicsConfiguration> {

    @Override
    public GraphicsConfiguration get() {
        return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    }
}


text:
<?php namespace Ordercloud\Entities\Orders;

use JsonSerializable;
use Ordercloud\Entities\Products\ProductShort;
use Ordercloud\Entities\Products\ProductType;

class OrderItemDetail extends ProductShort implements JsonSerializable
{
    public function __construct($id, $name, $price, $description, $shortDescription, OrderItemMerchant $organisation, $available, $enabled, $sku, $availableOnline, ProductType $productType, array $groupItems)
    {
        parent::__construct(
            $id,
            $name,
            $price,
            $description,
            $shortDescription,
            $organisation,
            $available,
            $enabled,
            $sku,
            $availableOnline,
            $productType,
            $groupItems
        );
    }

    /**
     * @return OrderItemMerchant
     */
    public function getMerchant()
    {
        return $this->getOrganisation();
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        $json = parent::jsonSerialize();

        $json['merchant'] = $this->getMerchant();

        return $json;
    }
}


text:
module.exports = function (grunt) {
  'use strict';

  var fbBuilder = require('../firebolt-builder')('src', 'dist');

  grunt.registerTask('clean', 'Deletes the contents of the dist folder', function() {
    fbBuilder.cleanSync();
    grunt.log.ok('Cleaned dist folder.');
  });

  grunt.registerTask('build', 'Builds Firebolt from the source files', function(target) {
    grunt.config.requires(this.name);

    target = target || 'DEFAULT';

    var config = grunt.config(this.name);
    var configModules;

    if (target in config) { // Preset build
      var configPath = [this.name, target, 'modules'];
      grunt.config.requires(configPath);
      configModules = grunt.config(configPath);
    } else {                // Custom build
      configModules = target.split(',');
      grunt.task.run('uglify', 'package_release');
    }

    grunt.log.writeln('Building Firebolt with modules:', '[\n  ' + configModules.join(',\n  ') + '\n]');

    fbBuilder.buildSync(configModules);

    grunt.log.ok('Done building Firebolt');
  });

};


text:
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <item name="android.util.AtomicFile AtomicFile(java.io.File) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.AtomicFile byte[] readFully()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.AtomicFile java.io.File getBaseFile()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.AtomicFile java.io.FileInputStream openRead()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Base64 byte[] decode(byte[], int) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Base64 byte[] decode(java.lang.String, int) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Base64 byte[] encode(byte[], int) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Base64 java.lang.String encodeToString(byte[], int)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Base64 java.lang.String encodeToString(byte[], int) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Base64 java.lang.String encodeToString(byte[], int, int, int)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.DebugUtils boolean isObjectSelected(java.lang.Object) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.DisplayMetrics boolean equals(android.util.DisplayMetrics) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.DisplayMetrics void setTo(android.util.DisplayMetrics) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter beginArray()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter beginObject()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter endArray()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter endObject()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter name(java.lang.String)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter nullValue()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter value(boolean)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter value(double)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter value(java.lang.Number)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter value(java.lang.String)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter android.util.JsonWriter value(long)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.JsonWriter void setIndent(java.lang.String) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Log int wtf(java.lang.String, java.lang.Throwable) 1">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.LongSparseArray E valueAt(int)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.LruCache java.util.Map<K,V> snapshot()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.MonthDisplayHelper int[] getDigitsForRow(int)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Pair android.util.Pair<A,B> create(A, B)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Patterns java.lang.String concatGroups(java.util.regex.Matcher)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Patterns java.lang.String concatGroups(java.util.regex.Matcher) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Patterns java.lang.String digitsAndPlusOnly(java.util.regex.Matcher)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Patterns java.lang.String digitsAndPlusOnly(java.util.regex.Matcher) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Property android.util.Property<T,V> of(java.lang.Class<T>, java.lang.Class<V>, java.lang.String)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.SparseArray E valueAt(int)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StateSet boolean isWildCard(int[]) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StateSet boolean stateSetMatches(int[], int) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StateSet int[] trimStateSet(int[], int)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StateSet int[] trimStateSet(int[], int) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StateSet java.lang.String dump(int[])">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StateSet java.lang.String dump(int[]) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.StringBuilderPrinter void println(java.lang.String) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.TypedValue float applyDimension(int, float, android.util.DisplayMetrics) 2">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.TypedValue float complexToDimension(int, android.util.DisplayMetrics) 1">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.TypedValue float getDimension(android.util.DisplayMetrics) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.TypedValue int complexToDimensionPixelOffset(int, android.util.DisplayMetrics) 1">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.TypedValue int complexToDimensionPixelSize(int, android.util.DisplayMetrics) 1">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.TypedValue resourceId">
    <annotation name="android.support.annotation.AnyRes" />
  </item>
  <item name="android.util.TypedValue void setTo(android.util.TypedValue) 0">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Xml FEATURE_RELAXED">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Xml android.util.AttributeSet asAttributeSet(org.xmlpull.v1.XmlPullParser)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Xml android.util.Xml.Encoding findEncodingByName(java.lang.String)">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Xml org.xmlpull.v1.XmlPullParser newPullParser()">
    <annotation name="android.support.annotation.NonNull" />
  </item>
  <item name="android.util.Xml void parse(java.io.InputStream, android.util.Xml.Encoding, org.xml.sax.ContentHandler) 1">
    <annotation name="android.support.annotation.NonNull" />
  </item>
</root>


text:
/***** includes *****/
#include "internal.h"

/****************************************************************************/
void test_lfds700_queue_bss_dequeuing()
{
  enum lfds700_misc_validity
    dvs = LFDS700_MISC_VALIDITY_VALID;

  lfds700_pal_uint_t
    loop;

  struct lfds700_queue_bss_element
    element_array[128];

  struct lfds700_queue_bss_state
    qs;

  struct lfds700_misc_validation_info
    vi;

  void
    *value;

  /* TRD : create an empty queue
           enqueue 128 elements
           then dequeue the elements, in the same thread - we're API testing
           it's a single producer queue, so we just do this in our current thread
           since we're enqueuing and dequeuing in the same thread,

  */

  internal_display_test_name( "Dequeuing" );

  lfds700_queue_bss_init_valid_on_current_logical_core( &qs, element_array, 128, NULL );

  for( loop = 0 ; loop < 127 ; loop++ )
    lfds700_queue_bss_enqueue( &qs, NULL, (void *) loop );

  for( loop = 0 ; loop < 127 ; loop++ )
  {
    lfds700_queue_bss_dequeue( &qs, NULL, &value );
    if( (lfds700_pal_uint_t) value != 127 - loop )
      dvs = LFDS700_MISC_VALIDITY_INVALID_TEST_DATA;
  }

  vi.min_elements = vi.max_elements = 0;

  lfds700_queue_bss_query( &qs, LFDS700_QUEUE_BSS_QUERY_VALIDATE, &vi, &dvs );

  lfds700_queue_bss_cleanup( &qs, NULL );

  internal_display_test_result( 1, "queue_bss", dvs );

  return;
}


text:
import fileinput
import sys

import re

pointer = re.compile("0x[0-9a-f]{9,12}")
target_token = re.compile("TargetToken\\([0-9]*\\)")
address = re.compile("\\[[0-9a-f]{8,12}]")
line_num = re.compile("^\\+\\d*:")
long_number = re.compile("\\d{8,}")

for line in fileinput.input():
    filtered_line = re.sub(pointer, '(ptr)', line)
    filtered_line = re.sub(target_token, 'TargetToken(tkn)', filtered_line)
    filtered_line = re.sub(address, '[adr]', filtered_line)
    filtered_line = re.sub(line_num, '', filtered_line)
    filtered_line = re.sub(long_number, '(num)', filtered_line)

    sys.stdout.write(filtered_line)


text:
namespace vr {

namespace {

constexpr float kCursorWidthRatio = 0.07f;
constexpr int kTextPixelPerDmm = 1100;
constexpr float kTextShadowScaleFactor = 1000.0f;
constexpr char kDefaultFontFamily[] = "sans-serif";

int DmmToPixel(float dmm) {
  return static_cast<int>(dmm * kTextPixelPerDmm);
}

float PixelToDmm(int pixel) {
  return static_cast<float>(pixel) / kTextPixelPerDmm;
}

bool IsFixedWidthLayout(TextLayoutMode mode) {
  return mode == kSingleLineFixedWidth || mode == kMultiLineFixedWidth;
}

void UpdateRenderText(gfx::RenderText* render_text,
                      const base::string16& text,
                      const gfx::FontList& font_list,
                      SkColor color,
                      TextAlignment text_alignment,
                      bool shadows_enabled,
                      SkColor shadow_color,
                      float shadow_size) {
  // Disable the cursor to avoid reserving width for a trailing caret.
  render_text->SetCursorEnabled(false);

  // Subpixel rendering is counterproductive when drawing VR textures.
  render_text->set_subpixel_rendering_suppressed(true);

  render_text->SetText(text);
  render_text->SetFontList(font_list);
  render_text->SetColor(color);
  if (shadows_enabled) {
    render_text->set_shadows(
        {gfx::ShadowValue({0, 0}, shadow_size, shadow_color)});
  } else {
    render_text->set_shadows({});
  }

  switch (text_alignment) {
    case kTextAlignmentNone:
      break;
    case kTextAlignmentLeft:
      render_text->SetHorizontalAlignment(gfx::ALIGN_LEFT);
      break;
    case kTextAlignmentRight:
      render_text->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
      break;
    case kTextAlignmentCenter:
      render_text->SetHorizontalAlignment(gfx::ALIGN_CENTER);
      break;
  }

  const int font_style = font_list.GetFontStyle();
  render_text->SetStyle(gfx::TEXT_STYLE_ITALIC,
                        (font_style & gfx::Font::ITALIC) != 0);
  render_text->SetStyle(gfx::TEXT_STYLE_UNDERLINE,
                        (font_style & gfx::Font::UNDERLINE) != 0);
  render_text->SetWeight(font_list.GetFontWeight());
}

}  // namespace

TextFormattingAttribute::TextFormattingAttribute(SkColor color,
                                                 const gfx::Range& range)
    : type_(COLOR), range_(range), color_(color) {}

TextFormattingAttribute::TextFormattingAttribute(gfx::Font::Weight weight,
                                                 const gfx::Range& range)
    : type_(WEIGHT), range_(range), weight_(weight) {}

TextFormattingAttribute::TextFormattingAttribute(
    gfx::DirectionalityMode directionality)
    : type_(DIRECTIONALITY), directionality_(directionality) {}

bool TextFormattingAttribute::operator==(
    const TextFormattingAttribute& other) const {
  if (type_ != other.type_ || range_ != other.range_)
    return false;
  switch (type_) {
    case COLOR:
      return color_ == other.color_;
    case WEIGHT:
      return weight_ == other.weight_;
    case DIRECTIONALITY:
      return directionality_ == other.directionality_;
    default:
      NOTREACHED();
      return false;
  }
}

bool TextFormattingAttribute::operator!=(
    const TextFormattingAttribute& other) const {
  return !(*this == other);
}

void TextFormattingAttribute::Apply(RenderTextWrapper* render_text) const {
  switch (type_) {
    case COLOR: {
      if (range_.IsValid()) {
        render_text->ApplyColor(color_, range_);
      } else {
        render_text->SetColor(color_);
      }
      break;
    }
    case WEIGHT:
      if (range_.IsValid()) {
        render_text->ApplyWeight(weight_, range_);
      } else {
        render_text->SetWeight(weight_);
      }
      break;
    case DIRECTIONALITY:
      render_text->SetDirectionalityMode(directionality_);
      break;
    default:
      NOTREACHED();
  }
}

class TextTexture : public UiTexture {
 public:
  explicit TextTexture(Text* element) : element_(element) {}

  ~TextTexture() override {}

  void SetFontHeightInDmm(float font_height_dmms) {
    SetAndDirty(&font_height_dmms_, font_height_dmms);
  }

  void SetText(const base::string16& text) { SetAndDirty(&text_, text); }

  void SetColor(SkColor color) { SetAndDirty(&color_, color); }

  void SetSelectionColors(const TextSelectionColors& colors) {
    SetAndDirty(&selection_colors_, colors);
  }

  void SetFormatting(const TextFormatting& formatting) {
    SetAndDirty(&formatting_, formatting);
  }

  void SetAlignment(TextAlignment alignment) {
    SetAndDirty(&alignment_, alignment);
  }

  void SetLayoutMode(TextLayoutMode mode) {
    SetAndDirty(&text_layout_mode_, mode);
  }

  void SetCursorEnabled(bool enabled) {
    SetAndDirty(&cursor_enabled_, enabled);
  }

  void SetSelectionIndices(int start, int end) {
    SetAndDirty(&selection_start_, start);
    SetAndDirty(&selection_end_, end);
  }

  void SetShadowsEnabled(bool enabled) {
    SetAndDirty(&shadows_enabled_, enabled);
  }

  void SetTextWidth(float width) { SetAndDirty(&text_width_, width); }

  gfx::Rect get_cursor_bounds() { return cursor_bounds_; }

  // This method does all text preparation for the element other than drawing to
  // the texture. This allows for deeper unit testing of the Text element
  // without having to mock canvases and simulate frame rendering. The state of
  // the texture is modified here.
  gfx::Size LayOutText();

  const std::vector<std::unique_ptr<gfx::RenderText>>& lines() const {
    return lines_;
  }

  void SetOnRenderTextCreated(
      base::RepeatingCallback<void(gfx::RenderText*)> callback) {
    render_text_created_callback_ = callback;
  }

  void SetOnRenderTextRendered(
      base::RepeatingCallback<void(const gfx::RenderText&, SkCanvas* canvas)>
          callback) {
    render_text_rendered_callback_ = callback;
  }

  void set_unsupported_code_points_for_test(bool unsupported) {
    unsupported_code_point_for_test_ = unsupported;
  }

 private:
  void Draw(SkCanvas* sk_canvas, const gfx::Size& texture_size) override;

  void PrepareDrawStringRect(const base::string16& text,
                             const gfx::FontList& font_list,
                             gfx::Rect* bounds,
                             const TextRenderParameters& parameters);
  void PrepareDrawWrapText(const base::string16& text,
                           const gfx::FontList& font_list,
                           gfx::Rect* bounds,
                           const TextRenderParameters& parameters);
  void PrepareDrawSingleLineText(const base::string16& text,
                                 const gfx::FontList& font_list,
                                 gfx::Rect* bounds,
                                 const TextRenderParameters& parameters);

  gfx::SizeF size_;
  gfx::Vector2d texture_offset_;
  base::string16 text_;
  float font_height_dmms_ = 0;
  float text_width_ = 0;
  TextAlignment alignment_ = kTextAlignmentCenter;
  TextLayoutMode text_layout_mode_ = kMultiLineFixedWidth;
  SkColor color_ = SK_ColorBLACK;
  TextSelectionColors selection_colors_;
  TextFormatting formatting_;
  bool cursor_enabled_ = false;
  int selection_start_ = 0;
  int selection_end_ = 0;
  gfx::Rect cursor_bounds_;
  bool shadows_enabled_ = false;
  std::vector<std::unique_ptr<gfx::RenderText>> lines_;
  Text* element_ = nullptr;

  base::RepeatingCallback<void(gfx::RenderText*)> render_text_created_callback_;
  base::RepeatingCallback<void(const gfx::RenderText&, SkCanvas*)>
      render_text_rendered_callback_;

  bool unsupported_code_point_for_test_ = false;

  DISALLOW_COPY_AND_ASSIGN(TextTexture);
};

Text::Text(float font_height_dmms)
    : TexturedElement(), texture_(std::make_unique<TextTexture>(this)) {
  texture_->SetFontHeightInDmm(font_height_dmms);
}

Text::~Text() {}

void Text::SetFontHeightInDmm(float font_height_dmms) {
  texture_->SetFontHeightInDmm(font_height_dmms);
}

void Text::SetText(const base::string16& text) {
  texture_->SetText(text);
}

void Text::SetFieldWidth(float width) {
  field_width_ = width;
  texture_->SetTextWidth(width);
}

void Text::SetColor(SkColor color) {
  texture_->SetColor(color);
}

void Text::SetSelectionColors(const TextSelectionColors& colors) {
  texture_->SetSelectionColors(colors);
}

void Text::SetFormatting(const TextFormatting& formatting) {
  texture_->SetFormatting(formatting);
}

void Text::SetAlignment(TextAlignment alignment) {
  texture_->SetAlignment(alignment);
}

void Text::SetLayoutMode(TextLayoutMode mode) {
  text_layout_mode_ = mode;
  texture_->SetLayoutMode(mode);
}

void Text::SetCursorEnabled(bool enabled) {
  texture_->SetCursorEnabled(enabled);
}

void Text::SetSelectionIndices(int start, int end) {
  texture_->SetSelectionIndices(start, end);
}

gfx::Rect Text::GetRawCursorBounds() const {
  return texture_->get_cursor_bounds();
}

gfx::RectF Text::GetCursorBounds() const {
  // Note that gfx:: cursor bounds always indicate a one-pixel width, so we
  // override the width here to be a percentage of height for the sake of
  // arbitrary texture sizes.
  gfx::Rect bounds = texture_->get_cursor_bounds();
  float scale = size().width() / text_texture_size_.width();
  return gfx::RectF(
      bounds.CenterPoint().x() * scale, bounds.CenterPoint().y() * scale,
      bounds.height() * scale * kCursorWidthRatio, bounds.height() * scale);
}

int Text::GetCursorPositionFromPoint(const gfx::PointF& point) const {
  DCHECK_EQ(texture_->lines().size(), 1u);
  gfx::Point pixel_position(point.x() * text_texture_size_.width(),
                            point.y() * text_texture_size_.height());
  return texture_->lines()
      .front()
      ->FindCursorPosition(pixel_position)
      .caret_pos();
}

void Text::SetShadowsEnabled(bool enabled) {
  texture_->SetShadowsEnabled(enabled);
}

const std::vector<std::unique_ptr<gfx::RenderText>>& Text::LinesForTest() {
  return texture_->lines();
}

void Text::SetUnsupportedCodePointsForTest(bool unsupported) {
  texture_->set_unsupported_code_points_for_test(unsupported);
}

void Text::SetOnRenderTextCreated(
    base::RepeatingCallback<void(gfx::RenderText*)> callback) {
  texture_->SetOnRenderTextCreated(callback);
}

void Text::SetOnRenderTextRendered(
    base::RepeatingCallback<void(const gfx::RenderText&, SkCanvas* canvas)>
        callback) {
  texture_->SetOnRenderTextRendered(callback);
}

float Text::MetersToPixels(float meters) {
  return DmmToPixel(meters);
}

UiTexture* Text::GetTexture() const {
  return texture_.get();
}

bool Text::TextureDependsOnMeasurement() const {
  return true;
}

gfx::Size Text::MeasureTextureSize() {
  text_texture_size_ = texture_->LayOutText();

  // Adjust the actual size of the element to match the texture.
  float width = IsFixedWidthLayout(text_layout_mode_)
                    ? field_width_
                    : PixelToDmm(text_texture_size_.width());
  TexturedElement::SetSize(width, PixelToDmm(text_texture_size_.height()));

  return text_texture_size_;
}

gfx::Size TextTexture::LayOutText() {
  int pixel_font_height = DmmToPixel(font_height_dmms_);
  gfx::Rect text_bounds;
  if (IsFixedWidthLayout(text_layout_mode_)) {
    DCHECK(text_width_ > 0.f) << element_->DebugName();
    text_bounds.set_width(DmmToPixel(text_width_));
  }

  gfx::FontList fonts =
      gfx::FontList(gfx::Font(kDefaultFontFamily, pixel_font_height));

  TextRenderParameters parameters;
  parameters.color = color_;
  parameters.text_alignment = alignment_;
  parameters.wrapping_behavior = text_layout_mode_ == kMultiLineFixedWidth
                                     ? kWrappingBehaviorWrap
                                     : kWrappingBehaviorNoWrap;
  parameters.cursor_enabled = cursor_enabled_;
  parameters.cursor_position = selection_end_;
  parameters.shadows_enabled = shadows_enabled_;
  parameters.shadow_size = kTextShadowScaleFactor * font_height_dmms_;

  PrepareDrawStringRect(text_, fonts, &text_bounds, parameters);

  if (cursor_enabled_) {
    DCHECK_EQ(lines_.size(), 1u);
    gfx::RenderText* render_text = lines_.front().get();

    if (selection_start_ != selection_end_) {
      render_text->set_focused(true);
      gfx::Range range(selection_start_, selection_end_);
      render_text->SetSelection(gfx::SelectionModel(
          range, gfx::LogicalCursorDirection::CURSOR_FORWARD));
      render_text->set_selection_background_focused_color(
          selection_colors_.background);
      render_text->set_selection_color(selection_colors_.foreground);
    }

    cursor_bounds_ = render_text->GetUpdatedCursorBounds();
  }

  if (!formatting_.empty()) {
    DCHECK_EQ(parameters.wrapping_behavior, kWrappingBehaviorNoWrap);
    DCHECK_EQ(lines_.size(), 1u);
    RenderTextWrapper render_text(lines_.front().get());
    for (const auto& attribute : formatting_) {
      attribute.Apply(&render_text);
    }
  }

  if (render_text_created_callback_) {
    DCHECK_EQ(lines_.size(), 1u);
    render_text_created_callback_.Run(lines_.front().get());
  }

  // Note, there is no padding here whatsoever.
  if (parameters.shadows_enabled) {
    texture_offset_ = gfx::Vector2d(gfx::ToFlooredInt(parameters.shadow_size),
                                    gfx::ToFlooredInt(parameters.shadow_size));
  }

  set_measured();

  return text_bounds.size();
}

void TextTexture::Draw(SkCanvas* sk_canvas, const gfx::Size& texture_size) {
  cc::SkiaPaintCanvas paint_canvas(sk_canvas);
  gfx::Canvas gfx_canvas(&paint_canvas, 1.0f);
  gfx::Canvas* canvas = &gfx_canvas;
  canvas->Translate(texture_offset_);

  for (auto& render_text : lines_)
    render_text->Draw(canvas);

  if (render_text_rendered_callback_) {
    DCHECK_EQ(lines_.size(), 1u);
    render_text_rendered_callback_.Run(*lines_.front().get(), sk_canvas);
  }
}

void TextTexture::PrepareDrawStringRect(
    const base::string16& text,
    const gfx::FontList& font_list,
    gfx::Rect* bounds,
    const TextRenderParameters& parameters) {
  DCHECK(bounds);

  if (parameters.wrapping_behavior == kWrappingBehaviorWrap)
    PrepareDrawWrapText(text, font_list, bounds, parameters);
  else
    PrepareDrawSingleLineText(text, font_list, bounds, parameters);

  if (parameters.shadows_enabled) {
    bounds->Inset(-parameters.shadow_size, -parameters.shadow_size);
    bounds->Offset(parameters.shadow_size, parameters.shadow_size);
  }
}

void TextTexture::PrepareDrawWrapText(const base::string16& text,
                                      const gfx::FontList& font_list,
                                      gfx::Rect* bounds,
                                      const TextRenderParameters& parameters) {
  lines_.clear();
  DCHECK(!parameters.cursor_enabled);

  gfx::Rect rect(*bounds);
  std::vector<base::string16> strings;
  gfx::ElideRectangleText(text, font_list, bounds->width(),
                          bounds->height() ? bounds->height() : INT_MAX,
                          gfx::WRAP_LONG_WORDS, &strings);

  int height = 0;
  int line_height = 0;
  for (size_t i = 0; i < strings.size(); i++) {
    std::unique_ptr<gfx::RenderText> render_text =
        gfx::RenderText::CreateRenderText();
    UpdateRenderText(render_text.get(), strings[i], font_list, parameters.color,
                     parameters.text_alignment, parameters.shadows_enabled,
                     parameters.shadow_color, parameters.shadow_size);

    if (i == 0) {
      // Measure line and center text vertically.
      line_height = render_text->GetStringSize().height();
      rect.set_height(line_height);
      if (bounds->height()) {
        const int text_height = strings.size() * line_height;
        rect += gfx::Vector2d(0, (bounds->height() - text_height) / 2);
      }
    }

    render_text->SetDisplayRect(rect);
    height += line_height;
    rect += gfx::Vector2d(0, line_height);
    lines_.push_back(std::move(render_text));
  }

  // Set calculated height.
  if (bounds->height() == 0)
    bounds->set_height(height);
}

void TextTexture::PrepareDrawSingleLineText(
    const base::string16& text,
    const gfx::FontList& font_list,
    gfx::Rect* bounds,
    const TextRenderParameters& parameters) {
  if (lines_.size() != 1) {
    lines_.clear();
    lines_.push_back(gfx::RenderText::CreateRenderText());
  }

  auto* render_text = lines_.front().get();
  UpdateRenderText(render_text, text, font_list, parameters.color,
                   parameters.text_alignment, parameters.shadows_enabled,
                   parameters.shadow_color, parameters.shadow_size);
  if (bounds->width() != 0 && !parameters.cursor_enabled)
    render_text->SetElideBehavior(gfx::TRUNCATE);
  if (parameters.cursor_enabled) {
    render_text->SetCursorEnabled(true);
    render_text->SetCursorPosition(parameters.cursor_position);
  }
  if (bounds->width() == 0)
    bounds->set_width(render_text->GetStringSize().width());
  if (bounds->height() == 0)
    bounds->set_height(render_text->GetStringSize().height());

  render_text->SetDisplayRect(*bounds);
}

}  // namespace vr


text:
  <iron-pages attr-for-selected="id" selected="[[currentState_]]">
    <search-page id="searchPage" on-continue-click="handleContinueClick_"
        feedback-context="[[feedbackContext_]]"
        description-template="[[descriptionTemplate_]]"
        description-placeholder-text="[[descriptionPlaceholderText_]]"
        help-content-search-result-count="{{helpContentSearchResultCount_}}"
        no-help-content-displayed="{{noHelpContentDisplayed_}}">
    </search-page>
    <share-data-page id="shareDataPage" feedback-context="[[feedbackContext_]]"
        should-show-assistant-checkbox="[[shouldShowAssistantCheckbox_]]"
        should-show-bluetooth-checkbox="[[shouldShowBluetoothCheckbox_]]"
        on-continue-click="handleContinueClick_"
        on-go-back-click="handleGoBackClick_">
    </share-data-page>
    <confirmation-page id="confirmationPage"
        send-report-status="[[sendReportStatus_]]"
        on-go-back-click="handleGoBackClick_">
    </confirmation-page>
  </iron-pages>


text:
'''
   Summary:

           *  The purpose of the `agent` is to automate the entire Apache HTTPD
              server build.
           *  The process includes automating the entire dependency builds,
              required for compiling and installing Apache HTTPD web server.
           *  The HTTPD server installation requires APR* (Apache Portable Run-
              time) and PCRE (PERL Compatible Regular Expressions) library,
              to be built, compiled and installed first.
           *  Each of the dependent task has been given a seperate namespace,
              and the entire build is supervised by the `Agent` Process.
'''

# Module `IMPORT` Section
# Don't clutter the entire script with imports
# Make all imports here and here only
import subprocess
import tarfile
import os

# Configuration Options for `wget`
WGET = {
        'apr_uri'     : 'wget http://mirror.fibergrid.in/apache//apr/apr-1.5.2.tar.bz2',
        'apr_util_uri': 'wget http://mirror.fibergrid.in/apache//apr/apr-util-1.5.4.tar.bz2',
        'httpd_uri'   : 'wget http://mirror.fibergrid.in/apache//httpd/httpd-2.4.23.tar.bz2'
       }

# Function Definition for downloading Apache HTTPD build dependencies
def download_apr():
    try:
        subprocess.check_call(WGET['apr_uri'], shell=True)
    except subprocess.CalledProcessError as CPEErr:
        print('ERROR::', CPEErr)

    print('APR downloaded!!!')

def download_apr_util():
    try:
        subprocess.check_call(WGET['apr_util_uri'], shell=True)
    except subprocess.CalledProcessError as CPEErr:
        print('ERROR::', CPEErr)

    print('APR-UTIL downloaded!!!')

# Function Definition for downloading Apache HTTPD source tree
def download_httpd():
    try:
        subprocess.check_call(WGET['httpd_uri'], shell=True)
    except subprocess.CalledProccessError as CPEErr:
        print('ERROR::', CPEErr)

    print('HTTPD downloaded!!!')

# Function Definition for untaring of compressed tar files
def untar(fname):
    if fname.endswith("tar.bz2"):
        tar = tarfile.open(fname)
        tar.extractall()
        tar.close()
        print("Extracted `%s` in Current Directory!!!\n" % fname)
    else:
        print("Not a `tar.bz2` file: `%s`..." % fname)

def install_pcre():
    try:
        subprocess.check_call('sudo apt-get install libpcre3 libpcre3-dev', shell=True)
    except subprocess.CalledProcessError as CPEErr:
        print('ERROR::', CPEErr)

    print('PCRE Installed!!!\n\n')

# Tar file list
tar_packages = ['apr-1.5.2.tar.bz2', 'apr-util-1.5.4.tar.bz2', 'httpd-2.4.23.tar.bz2']

# Download the compressed tar packages first
download_apr()
download_apr_util()
download_httpd()

# Decompress and untar the packages
for compressed_tar in tar_packages:
    untar(compressed_tar)

# Building APR and APR-UTIL for Apache HTTPD Installation
BASE_DIR = '/home/vagrant/downloads/apache_download/'

# Initiate PCRE Installation
# Delegate it to Ubuntu's default Package Manager
install_pcre()

os.chdir(BASE_DIR + 'apr-1.5.2')
print('Changed to APR source directory\nRunning APR steps\n')
try:
    subprocess.check_call('sudo ./configure', shell=True)
    subprocess.check_call('sudo make', shell=True)
    subprocess.check_call('sudo make install', shell=True)
except subprocess.CalledProcessError as CPEErr:
    print('ERROR::', CPEErr)

print('APR Installed!!!\n')

os.chdir(BASE_DIR + 'apr-util-1.5.4')
print('Changed to APR-UTIL source directory\nRunning APR-UTIL steps\n')
try:
    subprocess.check_call('sudo ./configure --with-apr=/usr/local/apr', shell=True)
    subprocess.check_call('sudo make', shell=True)
    subprocess.check_call('sudo make install', shell=True)
except subprocess.CalledProcessError as CPEErr:
    print('ERROR::', CPEErr)

print('APR-UTIL Installed!!!\n')

os.chdir(BASE_DIR + 'httpd-2.4.23')
print('Changed to HTTPD source directory\nRunning HTTPD steps\n')
try:
    subprocess.check_call('sudo ./configure --enable-ssl --enable-so', shell=True)
    subprocess.check_call('sudo make', shell=True)
    # subprocess.check_call('sudo make install', shell=True)
    p = subprocess.Popen(['sudo', 'make', 'install'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
    grep_stdout = p.communicate(input=b'y')[0]
except subprocess.CalledProcessError as CPEErr:
    print('ERROR::', CPEErr)

print('HTTPD Installed!!!\n')


text:
package org.elasticsearch.xpack.transform.integration;

import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.transform.GetTransformRequest;
import org.elasticsearch.client.transform.GetTransformResponse;
import org.elasticsearch.client.transform.UpdateTransformRequest;
import org.elasticsearch.client.transform.UpdateTransformResponse;
import org.elasticsearch.client.transform.transforms.TransformConfigUpdate;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.core.transform.TransformField;
import org.elasticsearch.xpack.core.transform.transforms.TransformConfig;
import org.elasticsearch.xpack.core.transform.transforms.persistence.TransformInternalIndexConstants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;

import static org.elasticsearch.xpack.transform.persistence.TransformInternalIndex.addTransformsConfigMappings;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

public class TransformInternalIndexIT extends ESRestTestCase {

    private static final String CURRENT_INDEX = TransformInternalIndexConstants.LATEST_INDEX_NAME;
    private static final String OLD_INDEX = TransformInternalIndexConstants.INDEX_PATTERN + "001";

    public void testUpdateDeletesOldTransformConfig() throws Exception {
        TestRestHighLevelClient client = new TestRestHighLevelClient();
        // The mapping does not need to actually be the "OLD" mapping, we are testing that the old doc gets deleted, and the new one
        // created.
        try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
            builder.startObject();
            builder.startObject("properties");
            builder.startObject(TransformField.INDEX_DOC_TYPE.getPreferredName()).field("type", "keyword").endObject();
            addTransformsConfigMappings(builder);
            builder.endObject();
            builder.endObject();
            client.indices().create(new CreateIndexRequest(OLD_INDEX).mapping(builder), RequestOptions.DEFAULT);
        }
        String transformIndex = "transform-index-deletes-old";
        createSourceIndex(transformIndex);
        String transformId = "transform-update-deletes-old-transform-config";
        String config = "{\"dest\": {\"index\":\"bar\"},"
            + " \"source\": {\"index\":\"" + transformIndex + "\", \"query\": {\"match_all\":{}}},"
            + " \"id\": \""+transformId+"\","
            + " \"doc_type\": \"data_frame_transform_config\","
            + " \"pivot\": {"
            + "   \"group_by\": {"
            + "     \"reviewer\": {"
            + "       \"terms\": {"
            + "         \"field\": \"user_id\""
            + " } } },"
            + "   \"aggregations\": {"
            + "     \"avg_rating\": {"
            + "       \"avg\": {"
            + "         \"field\": \"stars\""
            + " } } } },"
            + "\"frequency\":\"1s\""
            + "}";
        client.index(new IndexRequest(OLD_INDEX)
                .id(TransformConfig.documentId(transformId))
                .source(config, XContentType.JSON)
                .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE),
            RequestOptions.DEFAULT);
        GetResponse getResponse = client.get(new GetRequest(OLD_INDEX, TransformConfig.documentId(transformId)),
            RequestOptions.DEFAULT);
        assertThat(getResponse.isExists(), is(true));

        GetTransformResponse response = client.transform()
            .getTransform(new GetTransformRequest(transformId), RequestOptions.DEFAULT);
        assertThat(response.getTransformConfigurations().get(0).getId(), equalTo(transformId));

        UpdateTransformResponse updated = client.transform().updateTransform(
            new UpdateTransformRequest(TransformConfigUpdate.builder().setDescription("updated").build(), transformId),
            RequestOptions.DEFAULT);

        assertThat(updated.getTransformConfiguration().getId(), equalTo(transformId));
        assertThat(updated.getTransformConfiguration().getDescription(), equalTo("updated"));

        // Old should now be gone
        getResponse = client.get(new GetRequest(OLD_INDEX, TransformConfig.documentId(transformId)), RequestOptions.DEFAULT);
        assertThat(getResponse.isExists(), is(false));

        // New should be here
        getResponse = client.get(new GetRequest(CURRENT_INDEX, TransformConfig.documentId(transformId)),
            RequestOptions.DEFAULT);
        assertThat(getResponse.isExists(), is(true));
    }

    @Override
    protected Settings restClientSettings() {
        final String token = "Basic " +
            Base64.getEncoder().encodeToString(("x_pack_rest_user:x-pack-test-password").getBytes(StandardCharsets.UTF_8));
        return Settings.builder()
            .put(ThreadContext.PREFIX + ".Authorization", token)
            .build();
    }

    private void createSourceIndex(String index) throws IOException {
        TestRestHighLevelClient client = new TestRestHighLevelClient();
        client.indices().create(new CreateIndexRequest(index), RequestOptions.DEFAULT);
    }

    private class TestRestHighLevelClient extends RestHighLevelClient {
        TestRestHighLevelClient() {
            super(client(), restClient -> {},
                new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents());
        }
    }
}


text:
package DAO;

import model.*;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class PassageDB
{
	private Connection conn;

	public PassageDB( Connection conn )
	{
		this.conn = conn;
	}

	public void insert( Passage pass, int idPassage )
	{
		String Sql;

		Sql = " INSERT INTO passageiro";
		Sql += " (`Nome`,`Sobrenome`,`Email`,`Telefone`,";
		Sql += " `Passagem_idPassagem`,`DataNascimento`,`Perfil`,`Tratamento`)";
		Sql += "  VALUES (?,?,?,?,?,?,?,?);";

		PreparedStatement stm = null;

		try
		{
			stm = conn.prepareStatement( Sql );

			stm.setString( 1, pass.getName() );
			stm.setString( 2, pass.getLastName() );
			stm.setString( 3, pass.getEmail() );
			stm.setString( 4, pass.getPhone() );
			stm.setInt( 5, idPassage );
			stm.setDate( 6, (java.sql.Date)pass.getDateBirth() );
			stm.setInt( 7, pass.getProfile() );
			stm.setInt( 8, pass.getFormTreatment() );

			stm.execute();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}

	}
}