text:
# ### Lock animated

# This is a simulation of a ship lock, similar to the ones we can see in the Panama Canal or in some North European ports.
# The lock has two doors (left and right) which can open when the level of water is the same at both sides of the door.
# The picture below shows a particular moment of the simulation where we can observe the different components of the system.
# Ships are queueing at both sides of the lock: those coming from the left side(lship.number) are presented in blue colour while those coming from the right side(rship.number) are presented in red colour. In the picture below, lship.6 and lship.7 are queueing on the left, while rship.12, rship.13 and rship.14 are waiting on the right side. Both doors of the lock are closed because the water level inside the lock is switching from low level to high level, carrying two ships.

# ![image.png](attachment:image.png)

# In[1]:

import salabim as sim

left = -1  # Lock on the left side, actually meaning that the lock is open on the left (left door is open).
right = +1  # Lock on the right side, actually meaning that the lock is open on the right (right door is open).

# In[2]:

# We name the lock sides as 'l' for left and 'r' right
def sidename(side):
    return "l" if side == left else "r"

# Ships coming from the left are blue and those coming from the right are red
def shipcolor(side):
    return "blue" if side == left else "red"

# We create a polygon to represent a ship, this polygon has four coordinates (x, y).
# The polygon has a lenght according to the ship length and 3 units in height.
# This will be used later by the Class Ship to create an animation object.
def ship_polygon(ship):
    return (ship.side * (ship.length - 2), 0, ship.side * 3, 0, ship.side * 2, 3, ship.side * (ship.length - 2), 3)

# In[3]:

# We define a rectangle representing the water inside the lock.
# If the lock is in mode 'Switch' the water level will be moving between the two lock levels (low and high).
def lock_water_rectangle(t):
    if lock.mode() == "Switch":
        y = sim.interpolate(t, lock.mode_time(), lock.scheduled_time(), ylevel[lock.side], ylevel[-lock.side])
    # Interpolate is a method of Salabim that provides linear interpolation: (t, t0, t1, f(t0), f(t1))
    # mode_time() is a method of sim.Component that returns the time the component got its latest mode
    # schedule_time() is a method of Component that returns the time the component is scheduled for
    else:
        y = ylevel[lock.side]
        # When not switching, the water level will be one of the door levels
    return (xdoor[left], -waterdepth, xdoor[right], y)
    # Returns the two coordinates (x,y) defining the rectangle

# We define a rectangle representing the left door
def lock_door_left_rectangle(t):
    if lock.mode() == "Switch" or lock.side == right:
        # The left door will be closed when the lock is switching water level or when the right door is open.
        # The height of the door is 2 units above the water level
        y = ylevel[right] + 2  # y = lockheight + 2 = 7
    else:
        y = ylevel[left] - waterdepth  # 0 - waterdepth = -2
    return (xdoor[left] - 1, -waterdepth, xdoor[left] + 1, y)
    # Returns the two coordinates defining the rectangle

# We define a rectangle representing the right door; the logic is similar to the one used for the left door.
def lock_door_right_rectangle(t):
    if lock.mode() == "Switch" or lock.side == left:
        y = ylevel[right] + 2  # y = lockheight + 2 = 7
    else:
        y = ylevel[right] - waterdepth  # Lockheight - waterdepth = 5 - 2 = 3
    return (xdoor[right] - 1, -waterdepth, xdoor[right] + 1, y)

# The following sketch can help in understanding the variables used in the animation:

# ![image.png](attachment:image.png)

# In[4]:

def do_animation():
    global ylevel, xdoor, waterdepth

    lockheight = 5  # Maximum height of the water inside the lock
    waterdepth = 2  # Minimum level of water
    ylevel = {left: 0, right: lockheight}  # Dictionary, defining the (fixed) water level at both sides of the lock
    xdoor = {left: -0.5 * locklength, right: 0.5 * locklength}  # x-coordinate of the doors
    xbound = {left: -1.2 * locklength, right: 1.2 * locklength}  # x-coordinate of the limits of the screen

    # animation_parameters is a method of salabim.Environment to set animation parameters and to start the animation
    env.animation_parameters(animate=True, x0=xbound[left], y0=-waterdepth, x1=xbound[right], modelname="Lock", speed=8, background_color="20%gray")

    for side in [left, right]:
        sim.AnimateQueue(queue=wait[side], x=xdoor[side], y=10 + ylevel[side], direction="n")
        # AnimateQueue is a class of Salabim to animate the component in a queue
        # wait[left] and wait[right] are ship queues at both sides of the lock

    # AnimateRectangle is a class of Salabim to display a rectangle, optinally with a text
    # The first rectangle represents the water at the left side of the lock (fixed level)
    sim.AnimateRectangle(spec=(xbound[left], ylevel[left] - waterdepth, xdoor[left], ylevel[left]), fillcolor="aqua")
    # The second rectangle represents the water at the right side of the lock (fixed level)
    sim.AnimateRectangle(spec=(xdoor[right], ylevel[right] - waterdepth, xbound[right], ylevel[right]), fillcolor="aqua")
    # The third rectangle represents the water inside the lock, which will be switching
    sim.AnimateRectangle(spec=lock_water_rectangle, fillcolor="aqua")
    # The fourth rectangle is the left door, which will be apearing and dissapearing
    sim.AnimateRectangle(spec=lock_door_left_rectangle)
    # The fifth rectangle is the right door, which will be apearing and dissapearing
    sim.AnimateRectangle(spec=lock_door_right_rectangle)

    # AnimateSlider is a class of Salabim to allow adjusting some parameters on the screen during the simulation
    # In this example, we can adjust the interarrival time and the ships mean length
    sim.AnimateSlider(x=520, y=0, width=100, height=20, vmin=16, vmax=60, resolution=4, v=iat, label="iat", action=set_iat, xy_anchor="nw")
    sim.AnimateSlider(
        x=660, y=0, width=100, height=20, vmin=10, vmax=60, resolution=5, v=meanlength, label="mean length", action=set_meanlength, xy_anchor="nw"
    )

    # The class AnimateMonitor allows display monitors on the screen while running the simulation
    sim.AnimateMonitor(
        wait[left].length,
        linecolor="orange",
        fillcolor="bg",
        x=-225,
        y=-200,
        xy_anchor="n",
        horizontal_scale=1,
        width=450,
        linewidth=2,
        title=lambda: "Number of waiting ships left. Mean={:10.2f}".format(wait[left].length.mean()),
    )
    sim.AnimateMonitor(
        wait[right].length,
        linecolor="orange",
        fillcolor="bg",
        x=-225,
        y=-300,
        xy_anchor="n",
        horizontal_scale=1,
        width=450,
        linewidth=2,
        title=lambda: "Number of waiting ships right. Mean={:10.2f}".format(wait[right].length.mean()),
    )
    sim.AnimateMonitor(
        wait[left].length_of_stay,
        linecolor="white",
        fillcolor="bg",
        x=-225,
        y=-400,
        xy_anchor="n",
        vertical_scale=0.5,
        horizontal_scale=5,
        width=450,
        height=75,
        linewidth=4,
        title=lambda: "Waiting time of ships left. Mean={:10.2f}".format(wait[left].length_of_stay.mean()),
    )
    sim.AnimateMonitor(
        wait[right].length_of_stay,
        linecolor="white",
        fillcolor="bg",
        x=-225,
        y=-500,
        xy_anchor="n",
        vertical_scale=0.5,
        horizontal_scale=5,
        width=450,
        height=75,
        linewidth=4,
        title=lambda: "Waiting time of ships left. Mean={:10.2f}".format(wait[right].length_of_stay.mean()),
    )

    # There is another queue in the system, the one inside the lock while switching: lockqueue
    sim.AnimateQueue(queue=lockqueue, x=lambda: xdoor[-lock.sideq], y=lock_y, direction=lambda: "w" if lock.sideq == left else "e")
    #  Note that the y-coordinate is dynamic, making it possible that the queue moves up or down

# In[5]:

# A function to set the global variable iat (interarrival time)
def set_iat(val):
    global iat
    iat = float(val)

# A function to set the global variable meanlength (mean length of the ships)
def set_meanlength(val):
    global meanlength
    meanlength = float(val)

# In[6]:

# Generator of ships for each side of the lock
class Shipgenerator(sim.Component):
    def process(self):
        while True:  # Infinite loop to generate ships
            yield self.hold(sim.Exponential(iat).sample())
            ship = Ship(name=sidename(self.side) + "ship.")  # The name os the ship is lship.# of rship.#
            ship.side = self.side
            ship.length = meanlength * sim.Uniform(2.0 / 3, 4.0 / 3).sample()
            if lock.mode() == "Idle":  # If lock is idle then activate it
                lock.activate()

# The component Ship can have the following modes:
# - Wait
# - Sail in
# - In lock
# - Sail out

# In[7]:

class Ship(sim.Component):
    # animation_objects is a method of Component that defines how to display a component in AnimateQueue
    def animation_objects(self, q):
        size_x = self.length  # how much to display the ship in x-direction
        size_y = 5  # how much to display the ship in y-direction
        # an0 is an instance of Animate class - a polygon representing the ship
        an0 = sim.AnimatePolygon(
            spec=ship_polygon(self),
            fillcolor=shipcolor(self.side),
            linewidth=0,
            text=" " + self.name(),
            textcolor="white",
            layer=1,
            fontsize=2.6,
            text_anchor=("e" if self.side == left else "w"),
        )
        return (size_x, size_y, an0)

    def process(self):
        self.enter(wait[self.side])  # Ship enters the queue at the corresponding side
        yield self.passivate(mode="Wait")  # Ship is passivated and mode is set at Wait
        yield self.hold(intime, mode="Sail in")  # Ship starts moving towards the lock
        self.leave(wait[self.side])  # Ship leaves the queue at one side of the lock
        self.enter(lockqueue)  # Ship enters the queue inside the lock
        lock.activate()  # Ship activates the lock after accessing the lock
        yield self.passivate(mode="In lock")  # Ship is passivated and mode is set at In Lock
        self.leave(lockqueue)  # Ship leaves the queue located inside the lock
        yield self.hold(outtime, mode="Sail out")  # Ship sails out the lock
        lock.activate()  # Ship activates the lock after sailing out

# In[8]:

# This function calculates, by interpolation, the level of the water inside the lock when switching
def lock_y(t):
    if lock.mode() == "Switch":
        y = sim.interpolate(t, lock.mode_time(), lock.scheduled_time(), ylevel[lock.side], ylevel[-lock.side])
    else:
        y = ylevel[lock.side]
    return y

# The component Lock can have the following modes:
# - Idle
# - Wait for sail in
# - Switch
# - Wait for sail out

# In[9]:

class Lock(sim.Component):
    def process(self):
        while True:
            if len(wait[left]) + len(wait[right]) == 0:
                yield self.passivate(mode="Idle")  # Passivate lock if no ships in queue

            usedlength = 0  # Occupied length within the lock

            for ship in wait[self.side]:  # We check if another ship in the queue fits into the remaining space
                if usedlength + ship.length <= locklength:  # There is still room for this ship
                    usedlength += ship.length
                    ship.activate()
                    yield self.passivate("Wait for sail in")  # Passivate (mode)

            yield self.hold(switchtime, mode="Switch")  # Component.hold(duration, mode), water level moving
            self.side = -self.side  # After switching the water level, the side is changed
            for ship in lockqueue:  # Ships inside the lock
                ship.activate()  # Activates the ships that has to sail out and then they leave the system
                yield self.passivate("Wait for sail out")  # Lock waits for the ship to sail out
            self.sideq = -self.sideq  # Now we are ready to serve the opposite queue

# In[10]:

env = sim.Environment()

# In[11]:

locklength = 60  # Length of the lock (see sketch above)
switchtime = 10  # Time required to switch the water level from high to low or vice versa
intime = 2  # Time required to let ships sail in
outtime = 2  # Time required to let ships sail out
meanlength = 30  # Ships mean length (used to generate ships)
iat = 20  # Interarrival time of ships

# In[12]:

lockqueue = sim.Queue("lockqueue")  # This is the queue inside the lock

# In[13]:

wait = {}  # A dictionary containing the two queues: left and right

# In[14]:

for side in (left, right):
    wait[side] = sim.Queue(name=sidename(side) + "Wait")  # Queues at both sides are generated
    shipgenerator = Shipgenerator(name=sidename(side) + "Shipgenerator")  # lShipgenerator or rShipgenerator
    shipgenerator.side = side

# In[15]:

lock = Lock(name="lock")  # Lock is instantiated
lock.side = left  # When starting the simulation the side is left
lock.sideq = left  # The queue we are going to serve

# In[16]:

do_animation()

# In[17]:

env.run()


text:
<?php

include_once('functions.php');

?>

<!DOCTYPE html>

	<title>GreenStreet</title>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
	<meta charset="utf-8">

        <link rel="stylesheet" type="text/css" href="style.css">

</script>

<?php

$rewards = '[API_IP]/api/api.php/route-test?columns=rpm_score&transform=1';
$rewards = file_get_contents($rewards);
$rewards = json_decode($rewards, true);

$total_reward = 0;

$rewards_string = '[';
    foreach ($rewards['route-test'] as $reward) {

        $total_reward = ($total_reward + ($reward['rpm_score']));

        if ($total_reward <= '0') { $total_reward = 0; }

        $rewards_string .= $total_reward . ',';

    }
$rewards_string .= ']';

$coordinates = 'data/coordinates.json';
$coordinates = file_get_contents($coordinates);

?>

GreenStreet

You collected <?php $total_reward; ?>

Hereby you're not only saving the climate

redpajama_set_name: RedPajamaGithub


text:
(function(doc){
    var list = {
        // adds a post to the list with the data you give it
        // TODO probs make this a bit better
        // @param {object} obj - object's properties are in json_posts.json
        addPost: function (obj,li_id,callback) {
            var post_list = document.querySelector('#index_posts');
            // create the li elem
            var e = document.createElement('li');
            e.className = 'post__item';
            if (li_id)
                e.id = li_id;

            // for the title stuff h2>a
            var title = document.createElement('h2');
            var title_a = document.createElement('a');
            title.className = 'item__title';
            title_a.setAttribute('href', obj.url);
            title_a.textContent = obj.title;
            title.appendChild(title_a);
            e.appendChild(title);

            // for the meta_date
            var s_d = document.createElement('span');
            s_d.className = 'item__date';
            s_d.textContent = obj.date;
            // e.appendChild(s_d);

            // for the meta_author (or not)
            var s_a = document.createElement('span');
            s_a.className = 'item__author';
            s_a.innerHTML = obj.author;
            // e.appendChild(s_a);

            // for the meta container
            var meta = document.createElement('div');
            meta.className = 'item__meta';

            // tack on the sub-meta elements
            meta.appendChild(s_d);
            meta.appendChild(s_a);
            e.appendChild(meta);

            // for the content container
            var d_content = document.createElement('div');
            d_content.className = 'item__content';
            d_content.innerHTML = obj.content;
            e.appendChild(d_content);

            // e.innerHTML += obj.content;
            console.log(obj.content);
            post_list.appendChild(e);
            if (callback)
                callback();
        },
        // gets the ammnt of posts on the page
        // @returns {number}
        getLength: function () {
            var post_list = document.querySelectorAll('#index_posts > li');
            var post_list_length = post_list.length;
            return post_list_length;
        },
        // gets url params
        // @param {string} url - the current url, normally window.location.href
        // @param {string} id  - the url param's name that you want the value for
        // @returns {string|number}
        getUrlParam: function (id,url) {
            if (!url) {
                url = window.location.href;
            }
            url_arr = url.split("?");
            for (var i=1;i<url_arr.length;i++) {
                var param_arr = url_arr[i].split("=");
                if (param_arr[0] == id) {
                    return param_arr[1];
                }
            }
        },
        // removes the load more button
        removeButton: function () {
            console.log("all posts loaded, removing load more button");
            document.getElementById('index_posts_append').parentNode.removeChild(document.getElementById('index_posts_append'));
        },
        // scrolls to post number
        // @param {number} num - post number starting from index 0
        scrollToPost : function (num) {
            var idSelector = 'list_num_' + num;
            var elem = document.getElementById(idSelector);
            elem.scrollIntoView();
        }
    };
    var load_button = document.getElementById('posts_more');
    var spinner = document.getElementById('index_posts_spinner');
    var liquid_post_loop = 2;
    if (list.getUrlParam("posts")) {
        qwest.get('/json_posts.json').then(function(xhr,res){
            for (var i=list.getLength();i<list.getUrlParam("posts");i++) {
                list.addPost(res.posts[i],'list_num_'+i);
            }
            if (list.getUrlParam("posts") == res.posts.length)
                list.removeButton();
            list.scrollToPost(list.getUrlParam("posts")-1);
            // tell mathjax to parse any added math in these posts
            MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
        })
        .catch(function(e){
            console.log(e);
        });
    }

    if (load_button) {

    load_button.addEventListener('click', function(){

        spinner.style.display = 'block';

        qwest.get('/json_posts.json')
        .then(function(xhr,res){

            if (list.getLength() !== res.posts.length) {
                list.addPost(res.posts[list.getLength()],'list_num_'+list.getLength());
                console.log("loading more stuff");
                var state = {
                    posts_loaded: list.getLength()
                };
                history.replaceState(state,document.title,"?posts="+list.getLength());
                // tell mathjax to parse any added math in this post
                MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                if (list.getLength() == res.posts.length) {
                    list.removeButton();
                }
                spinner.style.display = 'none';
            }
        })
        .catch(function(e,xhr,res){
            console.log(e);
        });
    });
    }
})(document);


text:
/*
 * The Extensible Ethernet Monitor (EEMO)
 * DNS sensor forwarding module
 */

#include "config.h"
#include "eemo.h"
#include "eemo_log.h"
#include "eemo_dnssensorfw_ipfw.h"
#include "ip_handler.h"
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <errno.h>

/* Configuration */
char*	sensor_hostname		= NULL;
int	sensor_port		= 0;
int	reconn_maxinterval	= 0;

/* Retry state */
int	reconn_interval	= 1;

/* Sensor connection */
int		sensor_socket		= -1;
int		stop_conn_thread	= 0;
int		sensor_connected	= 0;
pthread_t	conn_thread_handle;

/* Sensor connection thread */
void* sensor_conn_thread(void* thread_args)
{
	/* FIXME: debug message */
	INFO_MSG("Entering sensor connection thread");

	while (!stop_conn_thread)
	{
		struct addrinfo* sensor_addrs = NULL;
		struct addrinfo* addr_it = NULL;
		struct addrinfo hints;
		char port_str[16];
		int reconn_interval_timer = reconn_interval;
		unsigned char dummy_buf[16384];

		/* Wait the reconnect interval and determine the new interval */
		while (!stop_conn_thread && reconn_interval_timer--) sleep(1);

		if (stop_conn_thread) break;

		reconn_interval *= 2;

		if (reconn_interval > reconn_maxinterval)
		{
			reconn_interval = reconn_maxinterval;
		}

		/* Resolve the address of the sensor */
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_flags = 0;
		hints.ai_protocol = 0;

		snprintf(port_str, 16, "%d", sensor_port);

		if (getaddrinfo(sensor_hostname, port_str, &hints, &sensor_addrs) != 0)
		{
			ERROR_MSG("Unable to resolve host %s", sensor_hostname);
			continue;
		}

		/* Attempt to connect to one of the addresses that was found */
		addr_it = sensor_addrs;

		while(addr_it != NULL)
		{
			if ((addr_it->ai_family == AF_INET) || (addr_it->ai_family == AF_INET6))
			{
				struct timeval socket_timeout = { 1, 0}; /* socket time-out is 1 second */
#ifdef __APPLE__
				int yes = 1;
#endif /* __APPLE__ */

				INFO_MSG("Attempting to connect to %s:%d over IPv%d",
					sensor_hostname, sensor_port,
					addr_it->ai_family == AF_INET ? 4 : 6);

				sensor_socket = socket(addr_it->ai_family, SOCK_STREAM, 0);

				if (sensor_socket == -1)
				{
					ERROR_MSG("Failed to open a new socket");
					continue;
				}

				/* Set socket time-out value for both sending as well as receiving */
				if (setsockopt(sensor_socket, SOL_SOCKET, SO_RCVTIMEO, (char*) &socket_timeout, sizeof(socket_timeout)) != 0)
				{
					ERROR_MSG("Failed to set receive time-out on sensor socket");
				}

				if (setsockopt(sensor_socket, SOL_SOCKET, SO_SNDTIMEO, (char*) &socket_timeout, sizeof(socket_timeout)) != 0)
				{
					ERROR_MSG("Failed to set send time-out on sensor socket");
				}

#ifdef __APPLE__
				if (setsockopt(sensor_socket, SOL_SOCKET, SO_NOSIGPIPE, (void*) &yes, sizeof(int)) != 0)
				{
					ERROR_MSG("Failed to disable SIGPIPE on socket error");
				}
#endif /* __APPLE__ */

				/* Attempt to connect the socket */
				if (connect(sensor_socket, addr_it->ai_addr, addr_it->ai_addrlen) != 0)
				{
					ERROR_MSG("Failed to connect to %s:%d (%s)", sensor_hostname, sensor_port, strerror(errno));
					close(sensor_socket);
					addr_it = addr_it->ai_next;
					continue;
				}

				INFO_MSG("Established a connection to %s:%d", sensor_hostname, sensor_port);

				sensor_connected = 1;
				reconn_interval = 1;

				break;
			}

			addr_it = addr_it->ai_next;
		}

		freeaddrinfo(sensor_addrs);

		while (sensor_connected && !stop_conn_thread)
		{
			/* Consume data received on the socket */
			int result = recv(sensor_socket, dummy_buf, 16384, MSG_DONTWAIT);

			if (result <= 0)
			{
				if ((result == 0) || ((errno != EAGAIN) && (errno != EWOULDBLOCK)))
				{
					/* The connection was closed */
					ERROR_MSG("Connection to %s:%d lost", sensor_hostname, sensor_port);

					sensor_connected = 0;
					close(sensor_socket);

					break;
				}
			}

			sleep(1);
		}
	}

	if (sensor_socket >= 0)
	{
		close(sensor_socket);
		sensor_connected = 0;
	}

	/* FIXME: debug message */
	INFO_MSG("Sensor connection thread finished");

	return NULL;
}

/* Initialise the IP/ICMP to DNS sensor forwarder */
void eemo_dnssensorfw_ipfw_init(const char* hostname, const int port, const int maxinterval)
{
	sensor_hostname = (char*) hostname;
	sensor_port = port;
	reconn_maxinterval = maxinterval;

	/* Initialise sensor connection thread */
	if (pthread_create(&conn_thread_handle, NULL, &sensor_conn_thread, NULL) != 0)
	{
		ERROR_MSG("Failed to start the sensor connection thread");
	}
}

/* Uninitialise the IP/ICMP to DNS sensor forwarder */
void eemo_dnssensorfw_ipfw_uninit(eemo_conf_free_string_array_fn free_strings)
{
	/* Stop the sensor connection thread */
	stop_conn_thread = 1;

	pthread_join(conn_thread_handle, NULL);
}

/* Handle all packets */
eemo_rv eemo_dnssensorfw_ipfw_handle_pkt(const eemo_packet_buf* packet, eemo_ether_packet_info pktinfo)
{
#pragma pack(push,1)
	static struct
	{
		unsigned short pkt_len;
		unsigned char buf[65536];
	} send_packet;
#pragma pack(pop)

	unsigned short ip4_ofs = 0;

	eemo_hdr_ipv4* v4hdr = (eemo_hdr_ipv4*) packet->data;
	eemo_hdr_ipv6* v6hdr = (eemo_hdr_ipv6*) packet->data;

	/* Check if a sensor connection exists; we don't lock here since this isn't a critical check */
	if (!sensor_connected)
	{
		return ERV_SKIPPED;
	}

	/* Check packet length */
	if (packet->len < sizeof(eemo_hdr_ipv4))
	{
		return ERV_MALFORMED;
	}

	ip4_ofs = ntohs(v4hdr->ip4_ofs) & 0x1fff;

	/* Check the IP version */
	if (IP_VER(v4hdr->ip4_ver_hl) == 4)
	{
		unsigned short* src_port = NULL;
		unsigned short* dst_port = NULL;

		/* If it is a fragment, always forward it */
		if (ip4_ofs == 0)
		{
			/* Not a fragment, check protocol */
			switch (v4hdr->ip4_proto)
			{
			case 0x01:	/* ICMP */
				break;	/* packet will be forwarded */
			case 0x06:	/* TCP */
			case 0x11:	/* UDP */
				/* Check destination port */
				if (packet->len < ((IP_HDRLEN(v4hdr->ip4_ver_hl) << 2) + 4))
				{
					return ERV_MALFORMED;
				}

				src_port = (unsigned short*) &packet->data[IP_HDRLEN(v4hdr->ip4_ver_hl) << 2];
				dst_port = src_port + 1;

				if ((ntohs(*src_port) != 53) && (ntohs(*dst_port) != 53))
				{
					return ERV_SKIPPED;
				}

				break;	/* packet will be forwarded */
			default:
				return ERV_SKIPPED;
			}
		}
	}
	else if (IP_VER(v6hdr->ip6_ver_tc) == 6)
	{
		unsigned short* src_port = NULL;
		unsigned short* dst_port = NULL;

		/* Check protocol */
		switch (v6hdr->ip6_next_hdr)
		{
		case 0x3a:	/* ICMPv6 */
			break;	/* packet will be forwarded */
		case 0x06:	/* TCP */
		case 0x11:	/* UDP */
			/* Check destination port */
			if (packet->len < (sizeof(eemo_hdr_ipv6) + 4))
			{
				return ERV_MALFORMED;
			}

			src_port = (unsigned short*) &packet->data[sizeof(eemo_hdr_ipv6)];
			dst_port = src_port + 1;

			if ((ntohs(*src_port) != 53) && (ntohs(*dst_port) != 53))
			{
				return ERV_SKIPPED;
			}
			break;	/* packet will be forwarded */
		case 0x2C:	/* IPv6 fragment header */
			break;	/* fragments will be forwarded */
		default:
			return ERV_SKIPPED;
		}
	}
	else
	{
		return ERV_MALFORMED;
	}

	memcpy(send_packet.buf, packet->data, packet->len);
	send_packet.pkt_len = packet->len;

	if (sensor_connected)
	{
#ifndef __APPLE__
		send(sensor_socket, &send_packet, packet->len + 2, MSG_NOSIGNAL);
#else
		send(sensor_socket, &send_packet, packet->len + 2, 0);
#endif /* __APPLE__ */
	}

	return ERV_HANDLED;
}


text:
<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/core/test_utils.html">
<link rel="import" href="/tracing/extras/chrome/event_finder_utils.html">
<link rel="import" href="/tracing/model/helpers/chrome_model_helper.html">

<script>
'use strict';

const EventFinderUtils = tr.e.chrome.EventFinderUtils;

tr.b.unittest.testSuite(function() {
  test('getSortedMainThreadEventsByFrame', () => {
    const model = tr.c.TestUtils.newModel(model => {
      const rendererProcess = model.getOrCreateProcess(1);
      const mainThread = rendererProcess.getOrCreateThread(2);
      mainThread.name = 'CrRendererMain';
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: 200,
        duration: 0.0,
        args: {frame: '0x0'}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: 300,
        duration: 0.0,
        args: {frame: '0x1'}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: 400,
        duration: 0.0,
        args: {frame: '0x0'}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'devtools.timeline',
        title: 'navigationStart',
        start: 500,
        duration: 0.0,
        args: {frame: '0x0'}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'firstPaint',
        start: 600,
        duration: 0.0,
        args: {frame: '0x0'}
      }));
    });

    const chromeHelper = model.getOrCreateHelper(
        tr.model.helpers.ChromeModelHelper);
    const rendererHelper = chromeHelper.rendererHelpers[1];
    const frameToSlices = EventFinderUtils.getSortedMainThreadEventsByFrame(
        rendererHelper, 'navigationStart', 'blink.user_timing');

    assert.strictEqual(frameToSlices.size, 2);
    assert.strictEqual(frameToSlices.get('0x0').length, 2);
    assert.strictEqual(frameToSlices.get('0x0')[0].start, 200);
    assert.strictEqual(frameToSlices.get('0x0')[1].start, 400);
    assert.strictEqual(frameToSlices.get('0x1').length, 1);
    assert.strictEqual(frameToSlices.get('0x1')[0].start, 300);
  });

  test('getSortedMainThreadEventsByNavId', () => {
    const model = tr.c.TestUtils.newModel(model => {
      const rendererProcess = model.getOrCreateProcess(1);
      const mainThread = rendererProcess.getOrCreateThread(2);
      mainThread.name = 'CrRendererMain';
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: 200,
        duration: 0.0,
        args: {frame: '0x0', data: { navigationId: '0xa' }}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: 300,
        duration: 0.0,
        args: {frame: '0x1', data: { navigationId: '0xb' }}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: 400,
        duration: 0.0,
        args: {frame: '0x0', data: { navigationId: '0xc' }}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'devtools.timeline',
        title: 'navigationStart',
        start: 500,
        duration: 0.0,
        args: {frame: '0x0', data: { navigationId: '0xd' }}
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'firstPaint',
        start: 600,
        duration: 0.0,
        args: {frame: '0x0'}
      }));
    });

    const chromeHelper = model.getOrCreateHelper(
        tr.model.helpers.ChromeModelHelper);
    const rendererHelper = chromeHelper.rendererHelpers[1];
    const navIdToSlices = EventFinderUtils.getSortedMainThreadEventsByNavId(
        rendererHelper, 'navigationStart', 'blink.user_timing');

    assert.strictEqual(navIdToSlices.size, 3);
    assert.strictEqual(navIdToSlices.get('0xa').start, 200);
    assert.strictEqual(navIdToSlices.get('0xb').start, 300);
    assert.strictEqual(navIdToSlices.get('0xc').start, 400);
  });

  test('multipleCategoriesOnAnEvent', () => {
    const model = tr.c.TestUtils.newModel(model => {
      const rendererProcess = model.getOrCreateProcess(1);
      const mainThread = rendererProcess.getOrCreateThread(2);
      mainThread.name = 'CrRendererMain';
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing,rail',
        title: 'navigationStart',
        start: 200,
        duration: 0.0,
        args: {frame: '0x0'}
      }));
    });

    const chromeHelper = model.getOrCreateHelper(
        tr.model.helpers.ChromeModelHelper);
    const rendererHelper = chromeHelper.rendererHelpers[1];
    const frameToSlices = EventFinderUtils.getSortedMainThreadEventsByFrame(
        rendererHelper, 'navigationStart', 'blink.user_timing');

    assert.strictEqual(frameToSlices.get('0x0')[0].start, 200);
  });

  test('findLastEventStartingOnOrBeforeTimestamp', () => {
    const sortedEvents = [50, 100, 150, 200].map(ts =>
      tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: ts,
        duration: 40.0}));

    assert.strictEqual(
        EventFinderUtils.findLastEventStartingOnOrBeforeTimestamp(
            sortedEvents, 100).start,
        100);
    assert.strictEqual(
        EventFinderUtils.findLastEventStartingOnOrBeforeTimestamp(
            sortedEvents, 99).start,
        50);
    assert.isUndefined(
        EventFinderUtils.findLastEventStartingOnOrBeforeTimestamp(
            sortedEvents, 49));
  });

  test('findNextEventStartingAfterTimestamp', () => {
    const sortedEvents = [50, 50, 50, 200].map(ts =>
      tr.c.TestUtils.newSliceEx({
        cat: 'blink.user_timing',
        title: 'navigationStart',
        start: ts,
        duration: 40.0}));

    assert.strictEqual(
        EventFinderUtils.findNextEventStartingAfterTimestamp(
            sortedEvents, 49).start,
        50);
    assert.strictEqual(
        EventFinderUtils.findNextEventStartingAfterTimestamp(
            sortedEvents, 50).start,
        200);
    assert.isUndefined(
        EventFinderUtils.findNextEventStartingAfterTimestamp(
            sortedEvents, 201));
  });

  test('findToplevelSchedulerTasks', () => {
    const model = tr.c.TestUtils.newModel(model => {
      const rendererProcess = model.getOrCreateProcess(1);
      const mainThread = rendererProcess.getOrCreateThread(2);
      mainThread.name = 'CrRendererMain';
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'toplevel',
        title: 'ThreadControllerImpl::RunTask',
        start: 10,
        duration: 1,
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'toplevel',
        title: 'ThreadControllerImpl::DoWork',
        start: 20,
        duration: 2,
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'toplevel',
        title: 'TaskQueueManager::ProcessTaskFromWorkQueue',
        start: 30,
        duration: 3,
      }));
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'toplevel',
        title: 'MessageLoop::RunTask',
        start: 40,
        duration: 4,
      }));
      // The category of 'ThreadControllerImpl::DoWork' slice was changed to
      // 'sequence_manager' because it is not longer a scheduler top level task.
      // See crbug.com/871204 for context.
      mainThread.sliceGroup.pushSlice(tr.c.TestUtils.newSliceEx({
        cat: 'sequence_manager',
        title: 'ThreadControllerImpl::DoWork',
        start: 50,
        duration: 5,
      }));
    });

    const chromeHelper = model.getOrCreateHelper(
        tr.model.helpers.ChromeModelHelper);
    const rendererHelper = chromeHelper.rendererHelpers[1];
    const tasks = EventFinderUtils.findToplevelSchedulerTasks(
        rendererHelper.mainThread);

    assert.strictEqual(tasks.length, 3);
    assert.strictEqual(tasks[0].title,
        'ThreadControllerImpl::RunTask');
    assert.strictEqual(tasks[0].start, 10);
    assert.strictEqual(tasks[0].duration, 1);
    assert.strictEqual(tasks[1].title,
        'ThreadControllerImpl::DoWork');
    assert.strictEqual(tasks[1].start, 20);
    assert.strictEqual(tasks[1].duration, 2);
    assert.strictEqual(tasks[2].title,
        'TaskQueueManager::ProcessTaskFromWorkQueue');
    assert.strictEqual(tasks[2].start, 30);
    assert.strictEqual(tasks[2].duration, 3);
  });
});
</script>


text:
namespace boost { namespace python {

template <class T>
inline python::detail::borrowed<T>* borrowed(T* p)
{
    return (detail::borrowed<T>*)p;
}

}} // namespace boost::python

#endif // BORROWED_DWA2002614_HPP


text:
module PaperTrail
  # The version number of the paper_trail gem. Not to be confused with
  # `PaperTrail::Version`. Ruby constants are case-sensitive, apparently,
  # and they are two different modules! It would be nice to remove `VERSION`,
  # because of this confusion, but it's not worth the breaking change.
  # People are encouraged to use `PaperTrail.gem_version` instead.
  module VERSION
    MAJOR = 8
    MINOR = 1
    TINY = 1
    PRE = nil

    STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".").freeze

    def self.to_s
      STRING
    end
  end
end


text:
import sys

try:
    import pygments
except:  # pragma: no cover
    pass

def pygmentize(content, lexer):
    def trim(pygment_entry):
        token, value = pygment_entry
        if token is pygments.token.Token.Text and value.strip(u" ") == u"\n":
            return (token, value.strip(u" "))
        return pygment_entry

    if not pygments:  # pragma: no cover
        raise ImportError("no pygments")
    pygments_list = list(pygments.lex(content, lexer))
    pygments_list = list(map(trim, pygments_list))
    return _join(pygments_list, (pygments.token.Token.Text, u"\n"))

def _join(markup_list, join_tag):
    combined_list = []
    while markup_list:
        if join_tag not in markup_list:
            combined_list.append(markup_list)
            break
        index = markup_list.index(join_tag)
        if index:
            combined_list.append(markup_list[:index])
        else:
            combined_list.append("")
        markup_list = markup_list[index + 1:]
    return combined_list

def stringfy(unicode_str):  # pragma: no cover
    """Use to support py27 py35 __str__"""
    if sys.version_info >= (3,):
        return unicode_str
    else:
        return unicode_str.encode("utf8")

def unicode_it(any_str):  # pragma: no cover
    if isinstance(any_str, bytes):
        return any_str.decode("utf8")
    return any_str


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic
  PUBLIC "-//OASIS//DTD DITA Composite//EN" "ditabase.dtd">
<topic id="topic1">
  <title id="ks137980">gpdetective</title>

Collects diagnostic information from a running Greenplum Database system.

The <codeph>gpdetective</codeph> utility is deprecated and will be removed in a future
      release.

      <title>Synopsis</title>
      <codeblock>gpdetective [-h <varname>hostname</varname>] [-p <varname>port</varname>] [-U <varname>username</varname>] [-P <varname>password</varname>]
     [--start_date <varname>number_of_days</varname> | <varname>YYYY-MM-DD</varname>]
     [--end_date <varname>YYYY-MM-DD</varname>]
     [--diagnostics a|n|s|o|c]
     [--logs a|n|<varname>dbid</varname> [,<varname>dbid</varname>,... | -<varname>dbid</varname>]]
     [--cores t|f]
     [--pg_dumpall t|f] [--pg_dump_options <varname>option</varname>[,...]]
     [--tempdir <varname>temp_dir</varname>]
     [--connect t|f]

gpdetective -v

gpdetective -?</codeblock>

      <title>Description</title>

The <codeph>gpdetective</codeph> utility collects information from a running Greenplum
        Database system and creates a bzip2-compressed tar output file. This output file can then be
        sent to Greenplum Customer Support to help with the diagnosis of Greenplum Database errors
        or system failures. The <codeph>gpdetective</codeph> utility runs the following diagnostic
        tests:

<codeph><xref href="./gpstate.xml#topic1" type="topic" format="dita"
            /></codeph> to check the system status

<codeph><xref href="gpcheck.xml#topic1" type="topic" format="dita"
            /></codeph> to make sure the recommended OS settings are set on all hosts

<codeph>gpcheckcat</codeph> to check the
          system catalog tables for inconsistencies

<codeph>gpdetective</codeph> captures the following files and Greenplum system
        information:

<codeph>postgresql.conf</codeph> configuration files (master and
          segments)

log files (master and segments)

Greenplum Database system configuration information

(optional) Core files

(optional) Schema DDL dumps for all databases and global objects (using
              <codeph><xref href="../client_utilities/pg_dumpall.xml#topic1"/></codeph>)

A bzip2-compressed tar output file containing this information is created in the current
        directory with a file name of
          <codeph>gpdetective<</codeph><varname>timestamp</varname><codeph>>.tar.bz2.</codeph>

      <title>Options</title>
      <parml>
        <plentry>
          <pt>--connect t|f</pt>
          <pd>Specifies if <codeph>gpdetective</codeph> should connect to the database to obtain
            system information. The default is true (<codeph>t</codeph>). If false
              (<codeph>f</codeph>), <codeph>gpdetective</codeph> only gathers information it can
            obtain without making a connection to the database. This information includes (from the
            master host):

Log files

The <varname>master_data_directory/</varname><codeph>postgresql.conf</codeph>
                file

The <codeph>~/gpAdminLogs</codeph> directory

<codeph>gpcheck</codeph> output

Core
              files

</pd>
        </plentry>
        <plentry>
          <pt>--cores t|f </pt>
          <pd>Determines whether or not the utility retrieves core files. The default is true
              (<codeph>t</codeph>).</pd>
        </plentry>
        <plentry>
          <pt>--diagnostics a|n|s|o|c</pt>
          <pd>Specifies the diagnostic tests to run: all (<codeph>a</codeph>), none
              (<codeph>n</codeph>), operating system (<codeph>o</codeph>) diagnostics, or catalog
              (<codeph>c</codeph>) diagnostics. The default is all (<codeph>a</codeph>).</pd>
        </plentry>
        <plentry>
          <pt>--end_date <varname>YYYY-MM-DD</varname></pt>
          <pd>Sets the end date for the diagnostic information collected. The collected information
            ends at 00:00:00 of the specified date. </pd>
        </plentry>
        <plentry>
          <pt>-h <varname>hostname</varname></pt>
          <pd>The host name of the machine on which the Greenplum master database server is running.
            If not specified, reads from the environment variable <codeph>PGHOST</codeph> or
            defaults to localhost.</pd>
        </plentry>
        <plentry>
          <pt>--logs a|n|dbid_list</pt>
          <pd>Specifies which log file(s) to retrieve: all (<codeph>a</codeph>), none
              (<codeph>n</codeph>), a comma separated list of segment <codeph>dbid</codeph> numbers,
            or a range of <codeph>dbid</codeph> numbers divided by a dash (<codeph>-</codeph>) (for
            example, <codeph>3-6</codeph> retrieves logs from segments 3, 4, 5, and 6). The default
            is all (<codeph>a</codeph>).</pd>
        </plentry>
        <plentry>
          <pt>-P <varname>password</varname></pt>
          <pd>If Greenplum Database is configured to use password authentication, you must also
            supply the database superuser password. If not specified, reads from
              <codeph>~/.pgpass</codeph> if it exists.</pd>
        </plentry>
        <plentry>
          <pt>--pg_dumpall t|f</pt>
          <pd>Determines whether or not the utility runs <codeph><xref
                href="../client_utilities/pg_dumpall.xml#topic1"/></codeph> to collect schema DDL
            for all databases and global objects. The default is true (<codeph>t</codeph>).</pd>
        </plentry>
        <plentry>
          <pt>--pg_dump_options <varname>option</varname>[,...]</pt>
          <pd>If <codeph>--pg_dumpall</codeph> is true, specifies a comma separated list of dump
            options to use when the <codeph>pg_dumpall</codeph> utility is called. See <codeph><xref
                href="../client_utilities/pg_dumpall.xml#topic1"/></codeph> for a valid list of dump
            options.</pd>
        </plentry>
        <plentry>
          <pt>-p <varname>port</varname></pt>
          <pd>The TCP port on which the Greenplum master database server is listening for
            connections. If not specified, reads from the environment variable
              <codeph>PGPORT</codeph> or defaults to 5432.</pd>
        </plentry>
        <plentry>
          <pt>--start_datenumber_of_days | <varname>YYYY-MM-DD</varname></pt>
          <pd>Sets the start date for the diagnostic information collected. Specify either the
            number of days prior, or an explicit past date.</pd>
        </plentry>
        <plentry>
          <pt>--tempdir <varname>temp_dir</varname></pt>
          <pd>Specifies the temporary directory used by <codeph>gpdetective</codeph>. The default
            value is determined by the <codeph>$TEMP</codeph>, <codeph>$TMP</codeph> and
              <codeph>$TMPDIR</codeph> environment variables.</pd>
        </plentry>
        <plentry>
          <pt>-U <varname>gp_superuser</varname></pt>
          <pd>The Greenplum database superuser role name to connect as (typically
              <codeph>gpadmin</codeph>). If not specified, reads from the environment variable
              <codeph>PGUSER</codeph> or defaults to the current system user name.</pd>
        </plentry>
        <plentry>
          <pt>-v (show utility version)</pt>
          <pd>Displays the version of this utility.</pd>
        </plentry>
        <plentry>
          <pt>-? (help)</pt>
          <pd>Displays the utility usage and syntax.</pd>
        </plentry>
      </parml>

      <title>Examples</title>

Collect all diagnostic information for a Greenplum Database system and supply the required
        connection information for the master host:

      <codeblock>gpdetective -h mdw -p 54320 -U gpadmin -P mypassword</codeblock>

Run diagnostics and collect all logs and system information for the past two days:

      <codeblock>gpdetective --start_date 2</codeblock>

Do not run diagnostic tests or schema dumps, just collect the log files of the master and
        segment 3:

      <codeblock>gpdetective --diagnostics n --logs -1,3 --pg_dumpall f</codeblock>

      <title>See Also</title>

<codeph><xref href="./gpstate.xml#topic1" type="topic" format="dita"/></codeph>,
            <codeph><xref href="gpcheck.xml#topic1" type="topic" format="dita"/></codeph>,
            <codeph><xref href="../client_utilities/pg_dumpall.xml#topic1"/></codeph>

</topic>


text:
from tsvector_field import SearchVectorField
from django.db.backends.postgresql.schema import DatabaseSchemaEditor as PostgreSQLSchemaEditor
from django import VERSION as DJANGO_VERSION

class DatabaseSchemaEditor(PostgreSQLSchemaEditor):
    """

    A nice trick to managing multiple schema editors in your project is to
    merge them using the type() function like so (as long as all the editors
    properly call super() in the overloaded methods):

        import tsvector_field
        from . import schema as your_app_schema

        class DatabaseWrapper(base.DatabaseWrapper):
            SchemaEditorClass = type('DatabaseSchemaEditor', (
                tsvector_field.DatabaseSchemaEditor,
                your_app_schema.DatabaseSchemaEditor,
            ), {})

    """

    def create_model(self, model):
        super().create_model(model)
        DatabaseTriggerEditor(self).create_model(model)

    def delete_model(self, model):
        super().delete_model(model)
        DatabaseTriggerEditor(self).delete_model(model)

    def add_field(self, model, field):
        super().add_field(model, field)
        DatabaseTriggerEditor(self).add_field(model, field)

    def remove_field(self, model, field):
        super().remove_field(model, field)
        DatabaseTriggerEditor(self).remove_field(model, field)

    def alter_field(self, model, old_field, new_field, strict=False):
        super().alter_field(model, old_field, new_field)
        DatabaseTriggerEditor(self).alter_field(model, old_field, new_field)

class DatabaseTriggerEditor:

    def __init__(self, schema_editor):
        self.schema_editor = schema_editor
        self.deferred_sql = schema_editor.deferred_sql

    # Instead of directly inheriting from the DatabaseSchemaEditor
    # we piecemeal expose the necessary functionality in case something
    # changes in the base class that has unintended consequences.

    def quote_name(self, name):
        return self.schema_editor.quote_name(name)

    def quote_value(self, value):
        return self.schema_editor.quote_value(value)

    @property
    def connection(self):
        return self.schema_editor.connection

    def _create_index_name(self, model, column_names, suffix=""):
        if DJANGO_VERSION >= (2,):
            return self.schema_editor._create_index_name(model._meta.db_table, column_names, suffix)
        else:
            return self.schema_editor._create_index_name(model, column_names, suffix)

    def create_model(self, model):
        for field in model._meta.local_fields:
            if isinstance(field, SearchVectorField):
                self.deferred_sql.extend(self._create_tsvector(model, field))

    def delete_model(self, model):
        for field in model._meta.local_fields:
            if isinstance(field, SearchVectorField):
                self.deferred_sql.extend(self._drop_tsvector(model, field))

    def add_field(self, model, field):
        if isinstance(field, SearchVectorField):
            self.deferred_sql.extend(self._create_tsvector(model, field))

    def remove_field(self, model, field):
        if isinstance(field, SearchVectorField):
            self.deferred_sql.extend(self._drop_tsvector(model, field))

    def alter_field(self, model, old_field, new_field, strict=False):
        self.remove_field(model, old_field)
        self.add_field(model, new_field)

    def get_names(self, model, field):
        return (
            self._create_index_name(model, [field.column], '_tsvector'),
            self._create_index_name(model, [field.column], '_function')+'()',
            self._create_index_name(model, [field.column], '_trigger')
        )

    def _to_tsvector_weights(self, field):

        if field.language_column and field.language:
            language = 'COALESCE(NEW.{}::regconfig, {})'.format(
                self.quote_name(field.language_column),
                self.quote_value(field.language)
            )

        elif field.language_column:
            language = 'NEW.{}::regconfig'.format(
                self.quote_name(field.language_column)
            )

        else:
            language = self.quote_value(field.language or 'english')

        sql_setweight = (
            " setweight(to_tsvector({language}, COALESCE(NEW.{column}, '')), {weight}) ||"
        )

        weights = []
        for column in field.columns:
            weights.append(sql_setweight.format(
                language=language,
                column=self.quote_name(column.name),
                weight=self.quote_value(column.weight)
            ))
        weights[-1] = weights[-1][:-3] + ';'

        return weights

    def _to_tsvector(self, field):
        yield "NEW.{} :=".format(self.quote_name(field.column))
        yield from self._to_tsvector_weights(field)

    def _to_tsvector_preconditions(self, field):
        yield "IF (TG_OP = 'INSERT') THEN do_update = true;"
        yield "ELSIF (TG_OP = 'UPDATE') THEN"
        yield " IF (NEW.{column} IS NULL) THEN do_update = true;".format(
            column=self.quote_name(field.column)
        )

        for column in field.columns:
            yield " ELSIF (NEW.{column} IS DISTINCT FROM OLD.{column}) THEN do_update = true;".format(
                column=self.quote_name(column.name)
            )

        yield " END IF;"
        yield "END IF;"

    sql_create_function = (
        "CREATE FUNCTION {function} RETURNS trigger AS $$\n"
        "DECLARE\n"
        " do_update bool default false;\n"
        "BEGIN\n"
        " {preconditions}\n"
        " IF do_update THEN\n"
        "  {to_tsvector}\n"
        " END IF;\n"
        " RETURN NEW;\n"
        "END\n"
        "$$ LANGUAGE plpgsql"
    )

    def _create_function(self, function, field):
        preconditions = ["do_update = true;"]
        if not field.force_update:
            preconditions = self._to_tsvector_preconditions(field)
        return self.sql_create_function.format(
            function=function,
            preconditions='\n '.join(preconditions),
            to_tsvector='\n  '.join(self._to_tsvector(field))
        )

    sql_create_index = (
        "CREATE INDEX {index} ON {table} USING {index_type} ({column})"
    )

    sql_create_trigger = (
        "CREATE TRIGGER {trigger} BEFORE INSERT OR UPDATE"
        " ON {table} FOR EACH ROW EXECUTE PROCEDURE {function}"
    )

    def _create_tsvector(self, model, field):

        index, function, trigger = self.get_names(model, field)
        table = self.quote_name(model._meta.db_table)

        yield self.sql_create_index.format(
            index=self.quote_name(index),
            table=table,
            index_type='GIN',
            column=self.quote_name(field.column)
        )

        if not field.columns:
            return

        yield self._create_function(function, field)

        yield self.sql_create_trigger.format(
            trigger=self.quote_name(trigger),
            table=table,
            function=function,
        )

    def _drop_tsvector(self, model, field):

        index, function, trigger = self.get_names(model, field)
        table = self.quote_name(model._meta.db_table)

        yield "DROP TRIGGER IF EXISTS {trigger} ON {table}".format(
            trigger=trigger, table=table,
        )

        yield "DROP FUNCTION IF EXISTS {function}".format(
            function=function,
        )

        yield "DROP INDEX IF EXISTS {index}".format(
            index=index
        )


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

namespace pe_bliss
{
	//Helper class to read and edit version information
	//lang_string_values_map: map of version info strings with encodings
	//translation_values_map: map of translations
	class version_info_editor : public version_info_viewer
	{
	public:
		//Default constructor
		//strings - version info strings with charsets
		//translations - version info translations map
		version_info_editor(lang_string_values_map& strings, translation_values_map& translations);

		//Below functions have parameter translation
		//If it's empty, the default language translation will be taken
		//If there's no default language translation, the first one will be taken

		//Sets company name
		void set_company_name(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets file description
		void set_file_description(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets file version
		void set_file_version(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets internal file name
		void set_internal_name(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets legal copyright
		void set_legal_copyright(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets original file name
		void set_original_filename(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets product name
		void set_product_name(const std::wstring& value, const std::wstring& translation = std::wstring());
		//Sets product version
		void set_product_version(const std::wstring& value, const std::wstring& translation = std::wstring());

		//Sets version info property value
		//property_name - property name
		//value - property value
		//If translation does not exist, it will be added to strings and translations lists
		//If property does not exist, it will be added
		void set_property(const std::wstring& property_name, const std::wstring& value, const std::wstring& translation = std::wstring());

		//Adds translation to translation list
		void add_translation(const std::wstring& translation);
		void add_translation(uint16_t language_id, uint16_t codepage_id);

		//Removes translation from translations and strings lists
		void remove_translation(const std::wstring& translation);
		void remove_translation(uint16_t language_id, uint16_t codepage_id);

	private:
		lang_string_values_map& strings_edit_;
		translation_values_map& translations_edit_;
	};
}


text:
import expect from 'expect'
import { createStore, combineReducers } from '../src/index'
import { addTodo, dispatchInMiddle, throwError, unknownAction } from './helpers/actionCreators'
import * as reducers from './helpers/reducers'

describe('createStore', () => {
  it('exposes the public API', () => {
    const store = createStore(combineReducers(reducers))
    const methods = Object.keys(store)

    expect(methods.length).toBe(4)
    expect(methods).toContain('subscribe')
    expect(methods).toContain('dispatch')
    expect(methods).toContain('getState')
    expect(methods).toContain('replaceReducer')
  })

  it('throws if reducer is not a function', () => {
    expect(() =>
      createStore()
    ).toThrow()

    expect(() =>
      createStore('test')
    ).toThrow()

    expect(() =>
      createStore({})
    ).toThrow()

    expect(() =>
      createStore(() => {})
    ).toNotThrow()
  })

  it('passes the initial action and the initial state', () => {
    const store = createStore(reducers.todos, [
      {
        id: 1,
        text: 'Hello'
      }
    ])
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }
    ])
  })

  it('applies the reducer to the previous state', () => {
    const store = createStore(reducers.todos)
    expect(store.getState()).toEqual([])

    store.dispatch(unknownAction())
    expect(store.getState()).toEqual([])

    store.dispatch(addTodo('Hello'))
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }
    ])

    store.dispatch(addTodo('World'))
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }, {
        id: 2,
        text: 'World'
      }
    ])
  })

  it('applies the reducer to the initial state', () => {
    const store = createStore(reducers.todos, [
      {
        id: 1,
        text: 'Hello'
      }
    ])
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }
    ])

    store.dispatch(unknownAction())
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }
    ])

    store.dispatch(addTodo('World'))
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }, {
        id: 2,
        text: 'World'
      }
    ])
  })

  it('preserves the state when replacing a reducer', () => {
    const store = createStore(reducers.todos)
    store.dispatch(addTodo('Hello'))
    store.dispatch(addTodo('World'))
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      },
      {
        id: 2,
        text: 'World'
      }
    ])

    store.replaceReducer(reducers.todosReverse)
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }, {
        id: 2,
        text: 'World'
      }
    ])

    store.dispatch(addTodo('Perhaps'))
    expect(store.getState()).toEqual([
      {
        id: 3,
        text: 'Perhaps'
      },
      {
        id: 1,
        text: 'Hello'
      },
      {
        id: 2,
        text: 'World'
      }
    ])

    store.replaceReducer(reducers.todos)
    expect(store.getState()).toEqual([
      {
        id: 3,
        text: 'Perhaps'
      },
      {
        id: 1,
        text: 'Hello'
      },
      {
        id: 2,
        text: 'World'
      }
    ])

    store.dispatch(addTodo('Surely'))
    expect(store.getState()).toEqual([
      {
        id: 3,
        text: 'Perhaps'
      },
      {
        id: 1,
        text: 'Hello'
      },
      {
        id: 2,
        text: 'World'
      },
      {
        id: 4,
        text: 'Surely'
      }
    ])
  })

  it('supports multiple subscriptions', () => {
    const store = createStore(reducers.todos)
    const listenerA = expect.createSpy(() => {})
    const listenerB = expect.createSpy(() => {})

    let unsubscribeA = store.subscribe(listenerA)
    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(1)
    expect(listenerB.calls.length).toBe(0)

    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(2)
    expect(listenerB.calls.length).toBe(0)

    const unsubscribeB = store.subscribe(listenerB)
    expect(listenerA.calls.length).toBe(2)
    expect(listenerB.calls.length).toBe(0)

    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(3)
    expect(listenerB.calls.length).toBe(1)

    unsubscribeA()
    expect(listenerA.calls.length).toBe(3)
    expect(listenerB.calls.length).toBe(1)

    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(3)
    expect(listenerB.calls.length).toBe(2)

    unsubscribeB()
    expect(listenerA.calls.length).toBe(3)
    expect(listenerB.calls.length).toBe(2)

    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(3)
    expect(listenerB.calls.length).toBe(2)

    unsubscribeA = store.subscribe(listenerA)
    expect(listenerA.calls.length).toBe(3)
    expect(listenerB.calls.length).toBe(2)

    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(4)
    expect(listenerB.calls.length).toBe(2)
  })

  it('only removes listener once when unsubscribe is called', () => {
    const store = createStore(reducers.todos)
    const listenerA = expect.createSpy(() => {})
    const listenerB = expect.createSpy(() => {})

    const unsubscribeA = store.subscribe(listenerA)
    store.subscribe(listenerB)

    unsubscribeA()
    unsubscribeA()

    store.dispatch(unknownAction())
    expect(listenerA.calls.length).toBe(0)
    expect(listenerB.calls.length).toBe(1)
  })

  it('only removes relevant listener when unsubscribe is called', () => {
    const store = createStore(reducers.todos)
    const listener = expect.createSpy(() => {})

    store.subscribe(listener)
    const unsubscribeSecond = store.subscribe(listener)

    unsubscribeSecond()
    unsubscribeSecond()

    store.dispatch(unknownAction())
    expect(listener.calls.length).toBe(1)
  })

  it('supports removing a subscription within a subscription', () => {
    const store = createStore(reducers.todos)
    const listenerA = expect.createSpy(() => {})
    const listenerB = expect.createSpy(() => {})
    const listenerC = expect.createSpy(() => {})

    store.subscribe(listenerA)
    const unSubB = store.subscribe(() => {
      listenerB()
      unSubB()
    })
    store.subscribe(listenerC)

    store.dispatch(unknownAction())
    store.dispatch(unknownAction())

    expect(listenerA.calls.length).toBe(2)
    expect(listenerB.calls.length).toBe(1)
    expect(listenerC.calls.length).toBe(2)
  })

  it('delays unsubscribe until the end of current dispatch', () => {
    const store = createStore(reducers.todos)

    const unsubscribeHandles = []
    const doUnsubscribeAll = () => unsubscribeHandles.forEach(
      unsubscribe => unsubscribe()
    )

    const listener1 = expect.createSpy(() => {})
    const listener2 = expect.createSpy(() => {})
    const listener3 = expect.createSpy(() => {})

    unsubscribeHandles.push(store.subscribe(() => listener1()))
    unsubscribeHandles.push(store.subscribe(() => {
      listener2()
      doUnsubscribeAll()
    }))
    unsubscribeHandles.push(store.subscribe(() => listener3()))

    store.dispatch(unknownAction())
    expect(listener1.calls.length).toBe(1)
    expect(listener2.calls.length).toBe(1)
    expect(listener3.calls.length).toBe(1)

    store.dispatch(unknownAction())
    expect(listener1.calls.length).toBe(1)
    expect(listener2.calls.length).toBe(1)
    expect(listener3.calls.length).toBe(1)
  })

  it('delays subscribe until the end of current dispatch', () => {
    const store = createStore(reducers.todos)

    const listener1 = expect.createSpy(() => {})
    const listener2 = expect.createSpy(() => {})
    const listener3 = expect.createSpy(() => {})

    let listener3Added = false
    const maybeAddThirdListener = () => {
      if (!listener3Added) {
        listener3Added = true
        store.subscribe(() => listener3())
      }
    }

    store.subscribe(() => listener1())
    store.subscribe(() => {
      listener2()
      maybeAddThirdListener()
    })

    store.dispatch(unknownAction())
    expect(listener1.calls.length).toBe(1)
    expect(listener2.calls.length).toBe(1)
    expect(listener3.calls.length).toBe(0)

    store.dispatch(unknownAction())
    expect(listener1.calls.length).toBe(2)
    expect(listener2.calls.length).toBe(2)
    expect(listener3.calls.length).toBe(1)
  })

  it('provides an up-to-date state when a subscriber is notified', done => {
    const store = createStore(reducers.todos)
    store.subscribe(() => {
      expect(store.getState()).toEqual([
        {
          id: 1,
          text: 'Hello'
        }
      ])
      done()
    })
    store.dispatch(addTodo('Hello'))
  })

  it('only accepts plain object actions', () => {
    const store = createStore(reducers.todos)
    expect(() =>
      store.dispatch(unknownAction())
    ).toNotThrow()

    function AwesomeMap() { }
    [ null, undefined, 42, 'hey', new AwesomeMap() ].forEach(nonObject =>
      expect(() =>
        store.dispatch(nonObject)
      ).toThrow(/plain/)
    )
  })

  it('handles nested dispatches gracefully', () => {
    function foo(state = 0, action) {
      return action.type === 'foo' ? 1 : state
    }

    function bar(state = 0, action) {
      return action.type === 'bar' ? 2 : state
    }

    const store = createStore(combineReducers({ foo, bar }))

    store.subscribe(function kindaComponentDidUpdate() {
      const state = store.getState()
      if (state.bar === 0) {
        store.dispatch({ type: 'bar' })
      }
    })

    store.dispatch({ type: 'foo' })
    expect(store.getState()).toEqual({
      foo: 1,
      bar: 2
    })
  })

  it('does not allow dispatch() from within a reducer', () => {
    const store = createStore(reducers.dispatchInTheMiddleOfReducer)

    expect(() =>
      store.dispatch(dispatchInMiddle(store.dispatch.bind(store, unknownAction())))
    ).toThrow(/may not dispatch/)
  })

  it('recovers from an error within a reducer', () => {
    const store = createStore(reducers.errorThrowingReducer)
    expect(() =>
      store.dispatch(throwError())
    ).toThrow()

    expect(() =>
      store.dispatch(unknownAction())
    ).toNotThrow()
  })

  it('throws if action type is missing', () => {
    const store = createStore(reducers.todos)
    expect(() =>
      store.dispatch({})
    ).toThrow(/Actions may not have an undefined "type" property/)
  })

  it('throws if action type is undefined', () => {
    const store = createStore(reducers.todos)
    expect(() =>
      store.dispatch({ type: undefined })
    ).toThrow(/Actions may not have an undefined "type" property/)
  })

  it('does not throw if action type is falsy', () => {
    const store = createStore(reducers.todos)
    expect(() =>
      store.dispatch({ type: false })
    ).toNotThrow()
    expect(() =>
      store.dispatch({ type: 0 })
    ).toNotThrow()
    expect(() =>
      store.dispatch({ type: null })
    ).toNotThrow()
    expect(() =>
      store.dispatch({ type: '' })
    ).toNotThrow()
  })

  it('accepts enhancer as the third argument', () => {
    const emptyArray = []
    const spyEnhancer = vanillaCreateStore => (...args) => {
      expect(args[0]).toBe(reducers.todos)
      expect(args[1]).toBe(emptyArray)
      expect(args.length).toBe(2)
      const vanillaStore = vanillaCreateStore(...args)
      return {
        ...vanillaStore,
        dispatch: expect.createSpy(vanillaStore.dispatch).andCallThrough()
      }
    }

    const store = createStore(reducers.todos, emptyArray, spyEnhancer)
    const action = addTodo('Hello')
    store.dispatch(action)
    expect(store.dispatch).toHaveBeenCalledWith(action)
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }
    ])
  })

  it('accepts enhancer as the second argument if initial state is missing', () => {
    const spyEnhancer = vanillaCreateStore => (...args) => {
      expect(args[0]).toBe(reducers.todos)
      expect(args[1]).toBe(undefined)
      expect(args.length).toBe(2)
      const vanillaStore = vanillaCreateStore(...args)
      return {
        ...vanillaStore,
        dispatch: expect.createSpy(vanillaStore.dispatch).andCallThrough()
      }
    }

    const store = createStore(reducers.todos, spyEnhancer)
    const action = addTodo('Hello')
    store.dispatch(action)
    expect(store.dispatch).toHaveBeenCalledWith(action)
    expect(store.getState()).toEqual([
      {
        id: 1,
        text: 'Hello'
      }
    ])
  })

  it('throws if enhancer is neither undefined nor a function', () => {
    expect(() =>
      createStore(reducers.todos, undefined, {})
    ).toThrow()

    expect(() =>
      createStore(reducers.todos, undefined, [])
    ).toThrow()

    expect(() =>
      createStore(reducers.todos, undefined, null)
    ).toThrow()

    expect(() =>
      createStore(reducers.todos, undefined, false)
    ).toThrow()

    expect(() =>
      createStore(reducers.todos, undefined, undefined)
    ).toNotThrow()

    expect(() =>
      createStore(reducers.todos, undefined, x => x)
    ).toNotThrow()

    expect(() =>
      createStore(reducers.todos, x => x)
    ).toNotThrow()

    expect(() =>
      createStore(reducers.todos, [])
    ).toNotThrow()

    expect(() =>
      createStore(reducers.todos, {})
    ).toNotThrow()
  })

  it('throws if nextReducer is not a function', () => {
    const store = createStore(reducers.todos)

    expect(() =>
      store.replaceReducer()
    ).toThrow('Expected the nextReducer to be a function.')

    expect(() =>
      store.replaceReducer(() => {})
    ).toNotThrow()
  })

  it('throws if listener is not a function', () => {
    const store = createStore(reducers.todos)

    expect(() =>
      store.subscribe()
    ).toThrow()

    expect(() =>
      store.subscribe('')
    ).toThrow()

    expect(() =>
      store.subscribe(null)
    ).toThrow()

    expect(() =>
      store.subscribe(undefined)
    ).toThrow()
  })
})


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Model\CompositeConfigProvider">
        <arguments>
            <argument name="configProviders" xsi:type="array">
                <item name="helcim_api_config_provider" xsi:type="object">Helcim\HelcimAPI\Model\Ui\ConfigProvider</item>
            </argument>
        </arguments>
    </type>
    <type name="Helcim\HelcimAPI\Block\Info">
        <arguments>
            <argument name="data" xsi:type="array">
                <item xsi:type="string" name="is_secure_mode">1</item>
            </argument>
        </arguments>
    </type>
</config>


text:
<?php
/**
 * author: shenzhe
 * Date: 13-6-17
 */
namespace ZPHP\Cache;
use ZPHP\Core\Factory as ZFactory;

class Factory
{
    public static function getInstance($adapter = 'Redis', $config = null)
    {
        $className = __NAMESPACE__ . "\\Adapter\\{$adapter}";
        return ZFactory::getInstance($className, $config);
    }
}


text:
/*
 * Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.Glacier.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.Glacier.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// CompleteVaultLock Request Marshaller
    /// </summary>
    public class CompleteVaultLockRequestMarshaller : IMarshaller<IRequest, CompleteVaultLockRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
    {
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IRequest Marshall(AmazonWebServiceRequest input)
        {
            return this.Marshall((CompleteVaultLockRequest)input);
        }

        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(CompleteVaultLockRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.Glacier");
            request.Headers["Content-Type"] = "application/x-amz-json-";
            request.HttpMethod = "POST";

            string uriResourcePath = "/{accountId}/vaults/{vaultName}/lock-policy/{lockId}";
            uriResourcePath = uriResourcePath.Replace("{accountId}", publicRequest.IsSetAccountId() ? StringUtils.FromString(publicRequest.AccountId) : string.Empty);
            uriResourcePath = uriResourcePath.Replace("{lockId}", publicRequest.IsSetLockId() ? StringUtils.FromString(publicRequest.LockId) : string.Empty);
            uriResourcePath = uriResourcePath.Replace("{vaultName}", publicRequest.IsSetVaultName() ? StringUtils.FromString(publicRequest.VaultName) : string.Empty);
            request.ResourcePath = uriResourcePath;

            return request;
        }

    }
}


text:
#pragma once
#include <vector>
#include <assert.h>

/**
* Pool consisting of multiple contiguous blocks of a defined number of contiguous elements which are of a predefined size.
* Blocks are not necessarily contiguous. Only the elements in the blocks are guaranteed to be contiguous in memory.
*/
class BasePool
{
public:
    BasePool(size_t elemSize, size_t blockCapacity, size_t initialPoolCapacity);

    virtual ~BasePool();

    void resize(size_t size)
    {
        if (m_size < size)
        {
            m_size = size;

            // Make sure there is enough space
            if (m_capacity < size)
                reserve(size);
        }
    }

    /**
    * The pool will reserve at least the requested amount of memory.
    * It might have to reserve more than requested because pool capacity depends on
    * the block capacity.
    */
    void reserve(size_t capacity)
    {
        while (m_capacity < capacity)
        {
            // Allocate memory for the block, add it to the block container and increase the capacity
            char* block = new char[m_blockCapacity * m_elemSize];
            m_blocks.push_back(block);
            m_capacity += m_blockCapacity;
        }
    }

    void* get(size_t idx)
    {
        assert(idx < m_size);
        // Get pointer to the corresponding block first and then add the relative offset
        return m_blocks[idx / m_blockCapacity] + m_elemSize * (idx % m_blockCapacity);
    }

    const void* get(size_t idx) const
    {
        assert(idx < m_size);
        // Get pointer to the corresponding block first and then add the relative offset
        return m_blocks[idx / m_blockCapacity] + m_elemSize * (idx % m_blockCapacity);
    }

    void* operator[](size_t idx) { return get(idx); }

    const void* operator[](size_t idx) const { return get(idx); }

    size_t size() const { return m_size; }

    size_t capacity() const { return m_capacity; }

    bool empty() const { return m_size == 0; }

    virtual void destroy(size_t idx) = 0;

protected:
    std::vector<char*> m_blocks; // Vector of all contiguous memory blocks
    const size_t m_elemSize; // Size in bytes of one element
    const size_t m_blockCapacity; // Number of elements per block
    size_t m_size; // Number of elements in the pool
    size_t m_capacity; // How many elements can fit into the pool
};

template <class T, size_t BlockCapacity = 8192, size_t InitialCapacity = 0>
class Pool : public BasePool
{
public:
    Pool() : BasePool(sizeof(T), BlockCapacity, InitialCapacity) { }

    /**
    * Calls the destructor of the specified element.
    */
    void destroy(size_t idx) override
    {
        assert(idx < m_size);
        // The destructor needs to be called explicitly because placement new is used
        static_cast<T*>(get(idx))->~T();
    }

    /**
    * Constructs a new element at the specified index.
    * args are the constructor parameters for the class of the pool
    */
    template <class ... Args>
    T* create(size_t idx, Args&& ... args)
    {
        // Placement new into the pool
        return new(get(idx)) T(std::forward<Args>(args) ...);
    }

    T& getRef(size_t idx) { return *static_cast<T*>(get(idx)); }

    const T& getRef(size_t idx) const { return *static_cast<T*>(get(idx)); }

    T* getPtr(size_t idx) { return static_cast<T*>(get(idx)); }

    const T* getPtr(size_t idx) const { return static_cast<T*>(get(idx)); }
};


text:
(function() {
  'use strict';

  var keylime = require('keylime'),
      p = require('path'),
      _ = require('lodash'),

      Path = keylime('Path');

  Path
    .attr('value', '')

    .method('resolve', function resolve() {
      return p.resolve(_.partial(p.join, this.value).apply(this, arguments));
    })

    .method('relative', function relative() {
      var from = '.' + p.sep,
          prefix = '.' + p.sep;
      return prefix + p.relative(from, _.partial(p.join, this.value).apply(this, arguments));
    })

    .method('relativeFrom', function relativeFrom() {
      var prefix = '.' + p.sep,
          args = [].slice.call(arguments, 0, 1);
      return prefix + _.partialRight(p.relative, this.relative()).apply(this, args);
    })

    .method('extension', function extension() {
      return p.extname(this.value);
    })

    .method('withoutExtension', function withoutExtension() {
      return this.value.replace(this.extension(), '');
    })

    .method('hasExtension', function hasExtension(val) {
      return (new RegExp(val, 'i').test(this.extension()));
    })

    .method('withoutPrefix', function withoutPrefix() {
      return _.dropWhile(this.value, function testCharacter(ch) {
        return ch === '.' || ch === p.sep;
      }).join('');
    });

  module.exports = Path;
}());


text:
import { Component, OnInit,trigger, style, transition, animate, Output, EventEmitter } from '@angular/core';

import { Post } from '../post';
import { PostService } from '../post.service';

@Component({
  selector: 'app-post-list',
  animations: [
    trigger('fadeInOut', [
      transition(':enter', [   // :enter is alias to 'void => *'
        style({opacity:0}),
        animate(500, style({opacity:1}))
      ]),
      transition(':leave', [   // :leave is alias to '* => void'
        animate(50, style({opacity:0}))
      ])
    ])
  ],
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.less'],
  providers: [ PostService ],
})

export class PostListComponent implements OnInit {

  constructor( private postService : PostService) { }

  posts : Post[];
  current_page: number;
  @Output() listLoaded = new EventEmitter();

  getPosts(page:number){
    return this.postService
               .getPosts(page)
               .subscribe( res => {
                 this.listLoaded.emit('app-post-list');
                 this.posts = res;
               })
  }

  getNextPageOfPost(){
    this.current_page += 1;
    return this.getPosts(this.current_page);
  }

  getPreviousPageOfPost(){
    this.current_page += -1;
    return this.getPosts(this.current_page);
  }

  ngOnInit() {
    this.current_page = 1;
    this.getPosts(this.current_page);
  }

}


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests;

use Doctrine\Common\Annotations;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\Psr6\DoctrineProvider;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\Cache\CacheConfiguration;
use Doctrine\ORM\Cache\CacheFactory;
use Doctrine\ORM\Cache\DefaultCacheFactory;
use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Tests\Mocks\EntityManagerMock;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;

use function class_exists;
use function is_array;
use function realpath;

/**
 * Base testcase class for all ORM testcases.
 */
abstract class OrmTestCase extends DoctrineTestCase
{
    /**
     * The metadata cache that is shared between all ORM tests (except functional tests).
     *
     * @var CacheItemPoolInterface|null
     */
    private static $_metadataCache = null;

    /**
     * The query cache that is shared between all ORM tests (except functional tests).
     *
     * @var Cache|null
     */
    private static $_queryCacheImpl = null;

    /** @var bool */
    protected $isSecondLevelCacheEnabled = false;

    /** @var bool */
    protected $isSecondLevelCacheLogEnabled = false;

    /** @var CacheFactory */
    protected $secondLevelCacheFactory;

    /** @var StatisticsCacheLogger */
    protected $secondLevelCacheLogger;

    /** @var Cache|null */
    protected $secondLevelCacheDriverImpl = null;

    /**
     * @param mixed $alias
     */
    protected function createAnnotationDriver(array $paths = [], $alias = null): AnnotationDriver
    {
        // Register the ORM Annotations in the AnnotationRegistry
        $reader = new Annotations\SimpleAnnotationReader();

        $reader->addNamespace('Doctrine\ORM\Mapping');

        if (class_exists(Annotations\PsrCachedReader::class)) {
            $reader = new Annotations\PsrCachedReader($reader, new ArrayAdapter());
        } else {
            $reader = new Annotations\CachedReader($reader, DoctrineProvider::wrap(new ArrayAdapter()));
        }

        Annotations\AnnotationRegistry::registerFile(__DIR__ . '/../../../lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');

        return new AnnotationDriver($reader, (array) $paths);
    }

    /**
     * Creates an EntityManager for testing purposes.
     *
     * NOTE: The created EntityManager will have its dependant DBAL parts completely
     * mocked out using a DriverMock, ConnectionMock, etc. These mocks can then
     * be configured in the tests to simulate the DBAL behavior that is desired
     * for a particular test,
     *
     * @param Connection|array $conn
     * @param mixed            $conf
     */
    protected function getTestEntityManager(
        $conn = null,
        $conf = null,
        ?EventManager $eventManager = null,
        bool $withSharedMetadata = true
    ): EntityManagerMock {
        $metadataCache = $withSharedMetadata
            ? self::getSharedMetadataCacheImpl()
            : new ArrayAdapter();

        $config = new Configuration();

        $config->setMetadataCache($metadataCache);
        $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([], true));
        $config->setQueryCacheImpl(self::getSharedQueryCacheImpl());
        $config->setProxyDir(__DIR__ . '/Proxies');
        $config->setProxyNamespace('Doctrine\Tests\Proxies');
        $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(
            [
                realpath(__DIR__ . '/Models/Cache'),
            ],
            true
        ));

        if ($this->isSecondLevelCacheEnabled) {
            $cacheConfig = new CacheConfiguration();
            $cache       = $this->getSharedSecondLevelCacheDriverImpl();
            $factory     = new DefaultCacheFactory($cacheConfig->getRegionsConfiguration(), $cache);

            $this->secondLevelCacheFactory = $factory;

            $cacheConfig->setCacheFactory($factory);
            $config->setSecondLevelCacheEnabled(true);
            $config->setSecondLevelCacheConfiguration($cacheConfig);
        }

        if ($conn === null) {
            $conn = [
                'driverClass'  => Mocks\DriverMock::class,
                'wrapperClass' => Mocks\ConnectionMock::class,
                'user'         => 'john',
                'password'     => 'wayne',
            ];
        }

        if (is_array($conn)) {
            $conn = DriverManager::getConnection($conn, $config, $eventManager);
        }

        return EntityManagerMock::create($conn, $config, $eventManager);
    }

    protected function enableSecondLevelCache($log = true): void
    {
        $this->isSecondLevelCacheEnabled    = true;
        $this->isSecondLevelCacheLogEnabled = $log;
    }

    private static function getSharedMetadataCacheImpl(): ?CacheItemPoolInterface
    {
        if (self::$_metadataCache === null) {
            self::$_metadataCache = new ArrayAdapter();
        }

        return self::$_metadataCache;
    }

    private static function getSharedQueryCacheImpl(): Cache
    {
        if (self::$_queryCacheImpl === null) {
            self::$_queryCacheImpl = DoctrineProvider::wrap(new ArrayAdapter());
        }

        return self::$_queryCacheImpl;
    }

    protected function getSharedSecondLevelCacheDriverImpl(): Cache
    {
        if ($this->secondLevelCacheDriverImpl === null) {
            $this->secondLevelCacheDriverImpl = DoctrineProvider::wrap(new ArrayAdapter());
        }

        return $this->secondLevelCacheDriverImpl;
    }
}


text:
'use strict';

exports.__esModule = true;

var _some2 = require('lodash/some');

var _some3 = _interopRequireDefault(_some2);

var _inherits = require('inherits');

var _inherits2 = _interopRequireDefault(_inherits);

var _compiler = require('../../../schema/compiler');

var _compiler2 = _interopRequireDefault(_compiler);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Schema Compiler
// -------

// SQLite3: Column Builder & Compiler
// -------
function SchemaCompiler_SQLite3() {
  _compiler2.default.apply(this, arguments);
}
(0, _inherits2.default)(SchemaCompiler_SQLite3, _compiler2.default);

// Compile the query to determine if a table exists.
SchemaCompiler_SQLite3.prototype.hasTable = function (tableName) {
  var sql = 'select * from sqlite_master ' + ('where type = \'table\' and name = ' + this.formatter.parameter(tableName));
  this.pushQuery({ sql: sql, output: function output(resp) {
      return resp.length > 0;
    } });
};

// Compile the query to determine if a column exists.
SchemaCompiler_SQLite3.prototype.hasColumn = function (tableName, column) {
  this.pushQuery({
    sql: 'PRAGMA table_info(' + this.formatter.wrap(tableName) + ')',
    output: function output(resp) {
      return (0, _some3.default)(resp, { name: column });
    }
  });
};

// Compile a rename table command.
SchemaCompiler_SQLite3.prototype.renameTable = function (from, to) {
  this.pushQuery('alter table ' + this.formatter.wrap(from) + ' rename to ' + this.formatter.wrap(to));
};

exports.default = SchemaCompiler_SQLite3;
module.exports = exports['default'];


text:
<?php

/* SonataAdminBundle:CRUD:edit_boolean.html.twig */
class __TwigTemplate_663e36e96cad8c31cded6e55b82770829ebdf4e0ec27730e465e1793be22fc93 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'field' => array($this, 'block_field'),
            'label' => array($this, 'block_label'),
            'errors' => array($this, 'block_errors'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 11
        echo "

env, $this->getAttribute($this->getAttribute((isset($context["field_element"]) ? $context["field_element"] : $this->getContext($context, "field_element")), "vars", array()), "errors", array())) > 0)) {
            echo "sonata-ba-field-error";
        }
        echo "\">
        ";
        // line 14
        $this->displayBlock('field', $context, $blocks);
        // line 15
        echo "        ";
        $this->displayBlock('label', $context, $blocks);
        // line 23
        echo "

            ";
        // line 25
        $this->displayBlock('errors', $context, $blocks);
        // line 26
        echo "

";
    }

    // line 14
    public function block_field($context, array $blocks = array())
    {
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["field_element"]) ? $context["field_element"] : $this->getContext($context, "field_element")), 'widget');
    }

    // line 15
    public function block_label($context, array $blocks = array())
    {
        // line 16
        echo "            ";
        if ($this->getAttribute($this->getAttribute((isset($context["field_description"]) ? $context["field_description"] : null), "options", array(), "any", false, true), "name", array(), "any", true, true)) {
            // line 17
            echo "                ";
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["field_element"]) ? $context["field_element"] : $this->getContext($context, "field_element")), 'label', (twig_test_empty($_label_ = $this->getAttribute($this->getAttribute((isset($context["field_description"]) ? $context["field_description"] : $this->getContext($context, "field_description")), "options", array()), "name", array())) ? array() : array("label" => $_label_)));
            echo "
            ";
        } else {
            // line 19
            echo "                ";
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["field_element"]) ? $context["field_element"] : $this->getContext($context, "field_element")), 'label');
            echo "
            ";
        }
        // line 21
        echo "

        ";
    }

    // line 25
    public function block_errors($context, array $blocks = array())
    {
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["field_element"]) ? $context["field_element"] : $this->getContext($context, "field_element")), 'errors');
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:edit_boolean.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  80 => 25,  75 => 21,  69 => 19,  63 => 17,  60 => 16,  57 => 15,  51 => 14,  43 => 26,  41 => 25,  37 => 23,  34 => 15,  32 => 14,  26 => 13,  22 => 11,);
    }
}


text:
/*
Compile: make traffic_light
Run: ./traffic_light
make traffic_light && ./traffic_light
*/

#include "base.h"

/*
Design a function that returns the next color of a traffic light
given the current color of the traffic light.
*/

enum TrafficLight {
    RED,
    GREEN,
    YELLOW
};

// enum TrafficLight -> enum TrafficLight
// Return the amount of tax for the given price.
enum TrafficLight traffic_light_next(enum TrafficLight);

static void traffic_light_next_test() {
    test_equal_i(traffic_light_next(RED), GREEN);
    test_equal_i(traffic_light_next(GREEN), YELLOW);
    test_equal_i(traffic_light_next(YELLOW), RED);
}

// Produces the next color of a traffic light
// given the current color of the traffic light.
enum TrafficLight traffic_light_next(enum TrafficLight tl) {
    if (tl == RED) {
        return GREEN;
    } else if (tl == GREEN) {
        return YELLOW;
    } else if (tl == YELLOW) {
        return RED;
    }
    return RED;
}

int main(void) {
    traffic_light_next_test();
    return 0;
}

/*
1. Problem statement (given)
Design a function that returns the next color of a traffic light
given the current color of the traffic light.

2. Write a data definition
enum TrafficLight {
    RED,
    GREEN,
    YELLOW
};

3. Write a function header
// enum TrafficLight -> enum TrafficLight
enum TrafficLight traffic_light_next(enum TrafficLight);

4. Write a purpose statement for the function
Produces the next color of a traffic light
given the current color of the traffic light.

5. Give examples and expected results
If the traffic light is RED, expect GREEN as the next state.
If the traffic light is GREEN, expect YELLOW as the next state.
If the traffic light is YELLOW, expect RED as the next state.

6. Implement the function body
enum TrafficLight traffic_light_next(enum TrafficLight tl) {
    if (tl == RED) {
        return GREEN;
    } else if (tl == GREEN) {
        return YELLOW;
    } else if (tl == YELLOW) {
        return RED;
    }
    return RED;
}

7. Test the function
static void traffic_light_next_test() {
    test_equal_i(traffic_light_next(RED), GREEN);
    test_equal_i(traffic_light_next(GREEN), YELLOW);
    test_equal_i(traffic_light_next(YELLOW), RED);
}

int main(void) {
    traffic_light_next_test();
    return 0;
}

8. Review and revise the function
no revision required
*/