text:
<?php

final class AphrontFormSelectControl extends AphrontFormControl {

  protected function getCustomControlClass() {
    return 'aphront-form-control-select';
  }

  private $options;

  public function setOptions(array $options) {
    $this->options = $options;
    return $this;
  }

  public function getOptions() {
    return $this->options;
  }

  protected function renderInput() {
    return self::renderSelectTag(
      $this->getValue(),
      $this->getOptions(),
      array(
        'name'      => $this->getName(),
        'disabled'  => $this->getDisabled() ? 'disabled' : null,
        'id'        => $this->getID(),
      ));
  }

  public static function renderSelectTag(
    $selected,
    array $options,
    array $attrs = array()) {

    $option_tags = self::renderOptions($selected, $options);

    return javelin_tag(
      'select',
      $attrs,
      $option_tags);
  }

  private static function renderOptions($selected, array $options) {
    $tags = array();
    foreach ($options as $value => $thing) {
      if (is_array($thing)) {
        $tags[] = phutil_tag(
          'optgroup',
          array(
            'label' => $value,
          ),
          self::renderOptions($selected, $thing));
      } else {
        $tags[] = phutil_tag(
          'option',
          array(
            'selected' => ($value == $selected) ? 'selected' : null,
            'value'    => $value,
          ),
          $thing);
      }
    }
    return $tags;
  }

}


text:
'use strict';

/**
 * @ngdoc service
 * @name publicApp.Auth
 * @description
 * # Auth
 * Factory in the publicApp.
 */
angular.module( 'publicApp' )
    .factory( 'Auth', [ 'Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
    function ( Base64, $http, $cookieStore, $rootScope, $timeout ) {
            var service = {};
            service.Login = function ( username, password, callback ) {

                $http.post( '/login', {
                    username: username,
                    password: Base64.encode( password )
                } )
                    .success( function ( response ) {
                        callback( response );
                    } );

            };
            service.Register = function ( data, callback ) {

                $http.post( '/register', {
                    name: data.name,
                    email: data.email,
                    username: data.username,
                    password: Base64.encode( data.password ),

                } )
                    .success( function ( response ) {
                        callback( response );
                    } );

            };
            service.Logout = function ( callback ) {

                /* Use this for real authentication
             ----------------------------------------------*/
                $http.post( '/logout', {} )
                    .success( function ( response ) {
                        callback( response );
                    } );

            };
            service.SetCredentials = function ( user ) {
                var authdata = Base64.encode( user.username + ':' + user.name + ':' + user.email );

                $rootScope.globals = {
                    currentUser: user
                };

                $http.defaults.headers.common[ 'Authorization' ] = 'Basic ' + authdata; // jshint ignore:line
                $cookieStore.put( 'globals', $rootScope.globals );
            };

            service.ClearCredentials = function () {
                $rootScope.globals = {};
                $cookieStore.remove( 'globals' );
                $http.defaults.headers.common.Authorization = 'Basic ';
            };

            return service;
    } ] )

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: 100 Dagen Daytum
date: 2009-07-11 13:46:42.000000000 +02:00
type: post
published: true
status: publish
categories:
- Joost
tags:
- Appels
- Beleg
- daytum
- Drinken
- Ijs
- Selftracking
meta:
  aktt_notify_twitter: 'yes'
  _edit_last: '1'
  aktt_tweeted: '1'
  dsq_thread_id: '415178190'
  _jetpack_related_posts_cache: a:1:{s:32:"8f6677c9d6b0f903e98ad32ec61f8deb";a:2:{s:7:"expires";i:1443754409;s:7:"payload";a:3:{i:0;a:1:{s:2:"id";i:619;}i:1;a:1:{s:2:"id";i:511;}i:2;a:1:{s:2:"id";i:714;}}}}
author:
  login: Joost Plattel
  email: jsplattel@gmail.com
  display_name: Joost Plattel
  first_name: Joost
  last_name: Plattel
---

Self-tracking, personal informatics of voor de lol, Daytum houd ik inmiddels al 100 dagen bij, daar om even een lijst met punten wat ik inmiddels van mezelf heb geleerd.

In 100 dagen heb ik:

1226 keer gedronken, alles totaal dus

257 keer water

206 keer koffie

118 keer limonade

387 keer bier (diverse soorten)

411 boterhammen gegeten

vruchtenhageslag is het lekkerste met 41 keer

daarna sandwichspread met 39 keer

ook krentenbollen zijn goed te kanen met 32 keer

35 ijsjes, waarvan 20 raketten :) Mjum!

191 elstars, het appels eten is wat ingezakt, maar dat komt omdat de elstar nu niet lekker is :p

Waarom doe ik dit nu? Deels voor de lol en deels omdat ik het gewoon graag wil weten, self-tracking en personal informatics zijn intressant omdat je feedback kan halen uit dingen waarop mensen normaal niet letten. Daarnaast ben je hiermee niet van andere mensen afhankelijk voor gegevens die je zelf ophaalt.

Voordat je hieruit conclusies kan trekken moet je wel aan jezelf vragen of je het eerlijk hebt ingevult, want ik wil nog wel eens sjoemelen met bier als ik die volgende ochtend wakker wordt met een kater ;) Niet omdat ik wil overdrijven, maar het vaak gewoon niet meer weet :p


text:
/**
 * OsmMapProvider is a Backbone model that extends the MapProvider model.
 * It contains the attributed necessary to support the Leaflet OSM plugin.
 * Its main responsibility is initializing the various MapLayer models supported by OSM.
 */
define(function(require) {
    "use strict";
    var MapProvider              = require('models/MapProvider'),
        MapLayer                 = require('models/MapLayer'),
        MapLayers                = require('collections/MapLayers'),
        MapQuestLocationService = require('services/MapQuestLocationService'),
        L                        = require('leaflet');

    var OsmMapProvider = MapProvider.extend({

        /**
         * defaults contains properties unique to OSM maps.
         */
        defaults: {
            name: MapProvider.OSM,
            isSelected: false,
            mapLayers: new MapLayers(),
            roadAttribution: '© OpenStreetMap',
            satelliteAttribution: 'Tiles Courtesy of MapQuest — ' +
            'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency'
        },

        /**
         * The initialize function is responsible for initializing the MapLayer models supported by OSM.
         * @param args - Contains a reference to the MapEventDispatcher.
         */
        initialize: function (args) {
            this.dispatcher = args.dispatcher;
            this.on('change:isSelected', this.onMapProviderChanged, this);
            var osmLayers = [];
            var roadOptions = {attribution: this.get('roadAttribution')};
            var satelliteOptions = {
                attribution: this.get('satelliteAttribution'),
                subdomains: '1234'
            };
            if (args.mapOptions) {
                roadOptions = L.extend({}, args.mapOptions, roadOptions);
                satelliteOptions = L.extend({}, args.mapOptions, satelliteOptions);
            }
            osmLayers[0] = new MapLayer({
                type: MapLayer.ROAD,
                isBaseLayer: true,
                dispatcher: this.dispatcher,
                leafletLayer: new L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', roadOptions)
            });
            osmLayers[1]= new MapLayer({
                type: MapLayer.SATELLITE,
                isBaseLayer: true,
                dispatcher: this.dispatcher,
                leafletLayer: new L.tileLayer('http://oatile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg', satelliteOptions)
            });
            this.get('mapLayers').set(osmLayers);
        },

        getGeoCoder: function() {
            return new MapQuestLocationService();
        }
    });

    return OsmMapProvider;
});


text:
core-ng is a webapp framework, it's designed to support our own projects.

[![Build Status](https://github.com/neowu/core-ng-project/workflows/build/badge.svg)](https://github.com/neowu/core-ng-project/actions)
[![Code Coverage](https://codecov.io/gh/neowu/core-ng-project/branch/master/graph/badge.svg)](https://codecov.io/gh/neowu/core-ng-project)
[![Code Quality: Java](https://img.shields.io/lgtm/grade/java/g/neowu/core-ng-project.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/neowu/core-ng-project/context:java)
[![Total Alerts](https://img.shields.io/lgtm/alerts/g/neowu/core-ng-project.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/neowu/core-ng-project/alerts)

## Maven repo
```
repositories {
    maven {
        url 'https://neowu.github.io/maven-repo/'
        content {
            includeGroupByRegex 'core\\.framework.*'
        }
    }
}
```

## Wiki
[https://github.com/neowu/core-ng-project/wiki](https://github.com/neowu/core-ng-project/wiki)

## Change log
please check [CHANGELOG.md](CHANGELOG.md)


text:
export const environment = {
  production: false,
  apiUrl:'http://localhost:9080',
  dateFormet:'dd/MM/yyyy',
  pagingSize:10
};


text:
#pragma once

#include "interactionbase_api.h"

#include "commands/Command.h"

namespace Interaction {

class INTERACTIONBASE_API CAddNodeToViewByName : public Command
{
	public:
		CAddNodeToViewByName();

		virtual bool canInterpret(Visualization::Item* source, Visualization::Item* target,
				const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& cursor) override;
		virtual CommandResult* execute(Visualization::Item* source, Visualization::Item* target,
				const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& cursor) override;

		virtual QList<CommandSuggestion*> suggest(Visualization::Item* source, Visualization::Item* target,
				const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>& cursor) override;

	private:
		QStringList findNames(QStringList nameParts, Model::Node* root);
		Model::Node* findNode(QStringList fullyQualifiedName, Model::Node* root);
		bool isSuggestable(Model::Node::SymbolTypes symbolType);
};

}


text:
A basic CURL wrapper for PHP (see [http://php.net/curl](http://php.net/curl) for more information about the libcurl extension for PHP)

## Installation

Click the `download` link above or `git clone git://github.com/shuber/curl.git`

## Usage

### Initialization

Simply require and initialize the `Curl` class like so:

	require_once 'autoload.php';
	$curl = new Curl;

### Performing a Request

The Curl object supports 5 types of requests: HEAD, GET, POST, PUT, and DELETE. You must specify a url to request and optionally specify an associative array or string of variables to send along with it. The Curl object will append the array of $vars to the $url as a query string for all methods except POST.

	$response = $curl->head($url, $vars = array());
	$response = $curl->get($url, $vars = array());
	$response = $curl->post($url, $vars = array());
	$response = $curl->put($url, $put_data, $vars = array());
	$response = $curl->delete($url, $vars = array());

To use a custom request methods, you can call the `request` method:

	$response = $curl->request('YOUR_CUSTOM_REQUEST_TYPE', $url, $vars = array(), $put_data = null);

All of the built in request methods like `put` and `get` simply wrap the `request` method. For example, the `post` method is implemented like:

	function post($url, $vars = array()) {
	    return $this->request('POST', $url, $vars);
	}

Examples:

	$response = $curl->get('google.com?q=test');

	# The Curl object will append '&some_variable=some_value' to the url
	$response = $curl->get('google.com?q=test', array('some_variable' => 'some_value'));

	$response = $curl->post('test.com/posts', array('title' => 'Test', 'body' => 'This is a test'));

All requests return a CurlResponse object (see below) or false if an error occurred. You can access the error string with the `$curl->error()` method.

### The CurlResponse Object

A normal CURL request will return the headers and the body in one response string. This class parses the two and places them into separate properties.

For example

	$response = $curl->get('google.com');
	echo $response->body; # A string containing everything in the response except for the headers
	print_r($response->headers); # An associative array containing the response headers

Which would display something like

	<html>
	<head>
	<title>Google.com</title>
	</head>
	<body>
	Some more html...
	</body>
	</html>

	Array
	(
	    [Http-Version] => 1.0
	    [Status-Code] => 200
	    [Status] => 200 OK
	    [Cache-Control] => private
	    [Content-Type] => text/html; charset=ISO-8859-1
	    [Date] => Wed, 07 May 2008 21:43:48 GMT
	    [Server] => gws
	    [Connection] => close
	)

The CurlResponse class defines the magic [__toString()](http://php.net/__toString) method which will return the response body, so `echo $response` is the same as `echo $response->body`

### Cookie Sessions

By default, cookies will be stored in a file called `curl_cookie.txt`. You can change this file's name by setting it like this

	$curl->cookie_file = 'some_other_filename';

This allows you to maintain a session across requests

### Basic Configuration Options

You can easily set the referer or user-agent

	$curl->referer = 'http://google.com';
	$curl->user_agent = 'some user agent string';

You may even set these headers manually if you wish (see below)

### Setting Custom Headers

You can set custom headers to send with the request

	$curl->setHeader('Host', 12.345.678.90);
	$curl->setHeader('Some-Custom-Header', 'Some Custom Value');

### Setting Custom CURL request options

By default, the `Curl` object will follow redirects. You can disable this by setting:

	$curl->follow_redirects = false;

You can set/override many different options for CURL requests (see the [curl_setopt documentation](http://php.net/curl_setopt) for a list of them)

	# any of these will work
	$curl->setOption('AUTOREFERER', true);
	$curl->setOption('CURLOPT_AUTOREFERER', true);
	$curl->setOption(CURLOPT_AUTOREFERER, true);

## Testing

Uses [ztest](http://github.com/jaz303/ztest), simply download it to `path/to/curl/test/ztest` (or anywhere else in your php include_path)

Then run `test/runner.php`

## Contact

Problems, comments, and suggestions all welcome: [shuber@huberry.com](mailto:shuber@huberry.com)


text:
Braintree Dropin built with Node on the backend, with server-side rendering.

## Installation and usage

* Run `npm install` to install all dependencies
* Run `npm start` to start the Express app
* Visit [http://localhost:3000](http://localhost:3000) in your browser
* Fill in the form using a Credit Card:
    * Number: `4111 1111 1111 1111`
    * CVV: `123`
    * Expiration date: `11/2020`

## Running the test

* Run `npm test` to start the test

## Useful links

* [v.zero](https://www.braintreepayments.com/v.zero)
* [The Braintree Node.js SDK](https://developers.braintreepayments.com/javascript+node/sdk/server/overview)


text:
package com.benromberg.cordonbleu.main;

import com.benromberg.cordonbleu.main.config.TestModule;

import com.benromberg.cordonbleu.main.CordonBleuApplication;
import com.benromberg.cordonbleu.main.config.GuiceModule;
import com.google.inject.Injector;
import com.google.inject.util.Modules;

public class CordonBleuTestApplication extends CordonBleuApplication {
    public CordonBleuTestApplication() {
        super(Modules.override(new GuiceModule()).with(new TestModule()));
    }

    @Override
    public Injector getInjector() {
        return super.getInjector();
    }

    @Override
    protected void scheduleTasks() {
    }
}


text:
describe "Quickeebooks::Windows::Service::CompanyMetaData" do
  before(:all) do
    construct_windows_service :company_meta_data
  end

  it "can fetch the company meta data" do
    xml = windowsFixture("company_meta_data.xml")
    model = Quickeebooks::Windows::Model::CompanyMetaData
    FakeWeb.register_uri(:get, @service.url_for_resource(model::REST_RESOURCE), :status => ["200", "OK"], :body => xml)
    company_meta_data_response = @service.load

    company_meta_data_response.registered_company_name.should == "Castle Rock Construction"
  end
end


text:
- Logs would not print in python. Would print in java app.
- Dropping Callback Events.
- Errors when closing down system.


text:
import { SnowBlizzard24 } from "../../";

export = SnowBlizzard24;


text:
package com.tinkerpop.blueprints.util.wrappers.batch;

import com.tinkerpop.blueprints.BaseTest;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Features;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.GraphQuery;
import com.tinkerpop.blueprints.TransactionalGraph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.tg.IgnoreIdTinkerGraph;
import com.tinkerpop.blueprints.impls.tg.MockTransactionalGraph;
import com.tinkerpop.blueprints.impls.tg.TinkerGraph;
import junit.framework.TestCase;

import java.util.Random;

/**
 * Tests {@link BatchGraph} by creating a variable length chain and verifying that the chain is correctly inserted into the wrapped TinkerGraph.
 *

 * Tests the various different Vertex caches and different length of chains.
 *

 *
 * @author Matthias Broecheler (http://www.matthiasb.com)
 */

public class BatchGraphTest extends TestCase {

    private static final String UID = "uid";

    private static final String vertexIDKey = "vid";
    private static final String edgeIDKey = "eid";
    private static boolean assignKeys = false;
    private static boolean ignoreIDs = false;

    public void testNumberIdLoading() {
        loadingTest(5000, 100, VertexIDType.NUMBER, new NumberLoadingFactory());
        loadingTest(200000, 10000, VertexIDType.NUMBER, new NumberLoadingFactory());

        assignKeys = true;
        loadingTest(5000, 100, VertexIDType.NUMBER, new NumberLoadingFactory());
        loadingTest(50000, 10000, VertexIDType.NUMBER, new NumberLoadingFactory());
        assignKeys = false;

        ignoreIDs = true;
        loadingTest(5000, 100, VertexIDType.NUMBER, new NumberLoadingFactory());
        loadingTest(50000, 10000, VertexIDType.NUMBER, new NumberLoadingFactory());
        ignoreIDs = false;
    }

    public void testObjectIdLoading() {
        loadingTest(5000, 100, VertexIDType.OBJECT, new StringLoadingFactory());
        loadingTest(200000, 10000, VertexIDType.OBJECT, new StringLoadingFactory());
    }

    public void testStringIdLoading() {
        loadingTest(5000, 100, VertexIDType.STRING, new StringLoadingFactory());
        loadingTest(200000, 10000, VertexIDType.STRING, new StringLoadingFactory());
    }

    public void testURLIdLoading() {
        loadingTest(5000, 100, VertexIDType.URL, new URLLoadingFactory());
        loadingTest(200000, 10000, VertexIDType.URL, new URLLoadingFactory());
    }

    public void testQuadLoading() {
        int numEdges = 10000;
        String[][] quads = generateQuads(100, numEdges, new String[]{"knows", "friend"});
        TinkerGraph graph = new TinkerGraph();
        BatchGraph bgraph = new BatchGraph(new WritethroughGraph(graph), VertexIDType.STRING, 1000);
        for (String[] quad : quads) {
            Vertex[] vertices = new Vertex[2];
            for (int i = 0; i < 2; i++) {
                vertices[i] = bgraph.getVertex(quad[i]);
                if (vertices[i] == null) vertices[i] = bgraph.addVertex(quad[i]);
            }
            Edge edge = bgraph.addEdge(null, vertices[0], vertices[1], quad[2]);
            edge.setProperty("annotation", quad[3]);
        }
        assertEquals(numEdges, BaseTest.count(graph.getEdges()));

        bgraph.shutdown();
    }

    public void testLoadingWithExisting1() {
        int numEdges = 1000;
        String[][] quads = generateQuads(100, numEdges, new String[]{"knows", "friend"});
        TinkerGraph tg = new TinkerGraph();
        BatchGraph bg = new BatchGraph(new WritethroughGraph(tg), VertexIDType.STRING, 100);
        bg.setLoadingFromScratch(false);
        Graph graph = null;
        int counter = 0;
        for (String[] quad : quads) {
            if (counter < numEdges / 2) graph = tg;
            else graph = bg;

            Vertex[] vertices = new Vertex[2];
            for (int i = 0; i < 2; i++) {
                vertices[i] = graph.getVertex(quad[i]);
                if (vertices[i] == null) vertices[i] = graph.addVertex(quad[i]);
            }
            Edge edge = graph.addEdge(null, vertices[0], vertices[1], quad[2]);
            edge.setProperty("annotation", quad[3]);
            counter++;
        }
        assertEquals(numEdges, BaseTest.count(tg.getEdges()));

        bg.shutdown();
    }

    public void testLoadingWithExisting2() {
        int numEdges = 1000;
        String[][] quads = generateQuads(100, numEdges, new String[]{"knows", "friend"});
        TinkerGraph tg = new IgnoreIdTinkerGraph();
        BatchGraph bg = new BatchGraph(new WritethroughGraph(tg), VertexIDType.STRING, 100);
        try {
            bg.setLoadingFromScratch(false);
            fail();
        } catch (IllegalStateException e) {
        }
        bg.setVertexIdKey("uid");
        bg.setLoadingFromScratch(false);
        try {
            bg.setVertexIdKey(null);
            fail();
        } catch (IllegalStateException e) {
        }

        Graph graph = null;
        int counter = 0;
        for (String[] quad : quads) {
            if (counter < numEdges / 2) graph = tg;
            else graph = bg;

            Vertex[] vertices = new Vertex[2];
            for (int i = 0; i < 2; i++) {
                vertices[i] = graph.getVertex(quad[i]);
                if (vertices[i] == null) vertices[i] = graph.addVertex(quad[i]);
            }
            Edge edge = graph.addEdge(null, vertices[0], vertices[1], quad[2]);
            edge.setProperty("annotation", quad[3]);
            counter++;
        }
        assertEquals(numEdges, BaseTest.count(tg.getEdges()));

        bg.shutdown();
    }

    public static String[][] generateQuads(int numVertices, int numEdges, String[] labels) {
        Random random = new Random();
        String[][] edges = new String[numEdges][4];
        for (int i = 0; i < numEdges; i++) {
            edges[i][0] = "v" + random.nextInt(numVertices) + 1;
            edges[i][1] = "v" + random.nextInt(numVertices) + 1;
            edges[i][2] = labels[random.nextInt(labels.length)];
            edges[i][3] = "" + random.nextInt();
        }
        return edges;
    }

    public void loadingTest(int total, int bufferSize, VertexIDType type, LoadingFactory ids) {
        final VertexEdgeCounter counter = new VertexEdgeCounter();

        MockTransactionalGraph tgraph = null;
        if (ignoreIDs) {
            tgraph = new MockTransactionalGraph(new IgnoreIdTinkerGraph());
        } else {
            tgraph = new MockTransactionalGraph(new TinkerGraph());
        }

        BLGraph graph = new BLGraph(tgraph, counter, ids);
        BatchGraph<BLGraph> loader = new BatchGraph<BLGraph>(graph, type, bufferSize);

        if (assignKeys) {
            loader.setVertexIdKey(vertexIDKey);
            loader.setEdgeIdKey(edgeIDKey);
        }

        //Create a chain
        int chainLength = total;
        Vertex previous = null;
        for (int i = 0; i <= chainLength; i++) {
            Vertex next = loader.addVertex(ids.getVertexID(i));
            next.setProperty(UID, i);
            counter.numVertices++;
            counter.totalVertices++;
            if (previous != null) {
                Edge e = loader.addEdge(ids.getEdgeID(i), loader.getVertex(previous.getId()), loader.getVertex(next.getId()), "next");
                e.setProperty(UID, i);
                counter.numEdges++;
            }
            previous = next;
        }

        loader.stopTransaction(TransactionalGraph.Conclusion.SUCCESS);
        assertTrue(tgraph.allSuccessful());

        loader.shutdown();
    }

    static class VertexEdgeCounter {

        int numVertices = 0;
        int numEdges = 0;
        int totalVertices = 0;

    }

    static class BLGraph implements TransactionalGraph {

        private static final int keepLast = 10;

        private final VertexEdgeCounter counter;
        private boolean first = true;
        private final LoadingFactory ids;

        private final TransactionalGraph graph;

        BLGraph(TransactionalGraph graph, final VertexEdgeCounter counter, LoadingFactory ids) {
            this.graph = graph;
            this.counter = counter;
            this.ids = ids;
        }

        private static final Object parseID(Object id) {
            if (id instanceof String) {
                try {
                    return Integer.parseInt((String) id);
                } catch (NumberFormatException e) {
                    return id;
                }
            } else return id;
        }

        @Override
        public void commit() {
            graph.commit();
            verifyCounts();
        }

        @Override
        public void rollback() {
            graph.rollback();
            verifyCounts();
        }

        @Override
        public void stopTransaction(Conclusion conclusion) {
            if (Conclusion.SUCCESS == conclusion)
                commit();
            else
                rollback();
        }

        private void verifyCounts() {
            //System.out.println("Committed (vertices/edges): " + counter.numVertices + " / " + counter.numEdges);
            assertEquals(counter.numVertices, BaseTest.count(graph.getVertices()) - (first ? 0 : keepLast));
            assertEquals(counter.numEdges, BaseTest.count(graph.getEdges()));
            for (Edge e : getEdges()) {
                int id = ((Number) e.getProperty(UID)).intValue();
                if (!ignoreIDs) {
                    assertEquals(ids.getEdgeID(id), parseID(e.getId()));
                }
                assertEquals(1, (Integer) e.getVertex(Direction.IN).getProperty(UID) - (Integer) e.getVertex(Direction.OUT).getProperty(UID));
                if (assignKeys) {
                    assertEquals(ids.getEdgeID(id), e.getProperty(edgeIDKey));
                }
            }
            for (Vertex v : getVertices()) {
                int id = ((Number) v.getProperty(UID)).intValue();
                if (!ignoreIDs) {
                    assertEquals(ids.getVertexID(id), parseID(v.getId()));
                }
                assertTrue(2 >= BaseTest.count(v.getEdges(Direction.BOTH)));
                assertTrue(1 >= BaseTest.count(v.getEdges(Direction.IN)));
                assertTrue(1 >= BaseTest.count(v.getEdges(Direction.OUT)));

                if (assignKeys) {
                    assertEquals(ids.getVertexID(id), v.getProperty(vertexIDKey));
                }

            }
            for (Vertex v : getVertices()) {
                int id = ((Number) v.getProperty(UID)).intValue();
                if (id < counter.totalVertices - keepLast) {
                    removeVertex(v);
                }
            }
            for (Edge e : getEdges()) removeEdge(e);
            assertEquals(keepLast, BaseTest.count(graph.getVertices()));
            counter.numVertices = 0;
            counter.numEdges = 0;
            first = false;
            //System.out.println("------");
        }

        @Override
        public Features getFeatures() {
            return graph.getFeatures();
        }

        @Override
        public Vertex addVertex(Object id) {
            return graph.addVertex(id);
        }

        @Override
        public Vertex getVertex(Object id) {
            return graph.getVertex(id);
        }

        @Override
        public void removeVertex(Vertex vertex) {
            graph.removeVertex(vertex);
        }

        @Override
        public Iterable<Vertex> getVertices() {
            return graph.getVertices();
        }

        @Override
        public Iterable<Vertex> getVertices(String key, Object value) {
            return graph.getVertices(key, value);
        }

        @Override
        public Edge addEdge(Object id, Vertex outVertex, Vertex inVertex, String label) {
            return graph.addEdge(id, outVertex, inVertex, label);
        }

        @Override
        public Edge getEdge(Object id) {
            return graph.getEdge(id);
        }

        @Override
        public void removeEdge(Edge edge) {
            graph.removeEdge(edge);
        }

        @Override
        public Iterable<Edge> getEdges() {
            return graph.getEdges();
        }

        @Override
        public Iterable<Edge> getEdges(String key, Object value) {
            return graph.getEdges(key, value);
        }

        @Override
        public void shutdown() {
            graph.shutdown();
        }

        @Override
        public GraphQuery query() {
            return graph.query();
        }

    }

    interface LoadingFactory {

        public Object getVertexID(int id);

        public Object getEdgeID(int id);

    }

    class StringLoadingFactory implements LoadingFactory {

        @Override
        public Object getVertexID(int id) {
            return "V" + id;
        }

        @Override
        public Object getEdgeID(int id) {
            return "E" + id;
        }
    }

    class NumberLoadingFactory implements LoadingFactory {

        @Override
        public Object getVertexID(int id) {
            return Integer.valueOf(id * 2);
        }

        @Override
        public Object getEdgeID(int id) {
            return Integer.valueOf(id * 2 + 1);
        }
    }

    class URLLoadingFactory implements LoadingFactory {

        @Override
        public Object getVertexID(int id) {
            return "http://www.tinkerpop.com/rdf/ns/vertex/" + id;
        }

        @Override
        public Object getEdgeID(int id) {
            return "http://www.tinkerpop.com/rdf/ns/edge#" + id;
        }
    }

}


text:
package releaser

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/gohugoio/hugo/common/hexec"
	"github.com/gohugoio/hugo/common/hugo"
)

const commitPrefix = "releaser:"

// New initialises a ReleaseHandler.
func New(skipPush, try bool, step int) (*ReleaseHandler, error) {
	if step < 1 || step > 2 {
		return nil, fmt.Errorf("step must be 1 or 2")
	}

	prefix := "release-"
	branch, err := git("rev-parse", "--abbrev-ref", "HEAD")
	if err != nil {
		return nil, err
	}
	branch = strings.TrimSpace(branch)

	if !strings.HasPrefix(branch, prefix) {
		return nil, fmt.Errorf("branch %q is not a release branch", branch)
	}

	version := strings.TrimPrefix(branch, prefix)
	version = strings.TrimPrefix(version, "v")

	logf("Branch: %s|Version: v%s\n", branch, version)

	rh := &ReleaseHandler{branchVersion: version, skipPush: skipPush, try: try, step: step}

	if try {
		rh.git = func(args ...string) (string, error) {
			logln("git", strings.Join(args, " "))
			return "", nil
		}
	} else {
		rh.git = git
	}

	return rh, nil
}

// ReleaseHandler provides functionality to release a new version of Hugo.
// Test this locally without doing an actual release:
// go run -tags release main.go release --skip-publish --try -r 0.90.0
// Or a variation of the above -- the skip-publish flag makes sure that any changes are performed to the local Git only.
type ReleaseHandler struct {
	branchVersion string

	// 1 or 2.
	step int

	// No remote pushes.
	skipPush bool

	// Just simulate, no actual changes.
	try bool

	git func(args ...string) (string, error)
}

// Run creates a new release.
func (r *ReleaseHandler) Run() error {
	newVersion, finalVersion := r.calculateVersions()
	version := newVersion.String()
	tag := "v" + version
	mainVersion := newVersion
	mainVersion.PatchLevel = 0

	defer r.gitPush()

	if r.step == 1 {
		if err := r.bumpVersions(newVersion); err != nil {
			return err
		}

		if _, err := r.git("commit", "-a", "-m", fmt.Sprintf("%s Bump versions for release of %s\n\n[ci skip]", commitPrefix, newVersion)); err != nil {
			return err
		}

		// The above commit will be the target for this release, so print it to the console in a env friendly way.
		sha, err := git("rev-parse", "HEAD")
		if err != nil {
			return err
		}

		// Hugoreleaser will do the actual release using these values.
		if err := r.replaceInFile("hugoreleaser.env",
			`HUGORELEASER_TAG=(\S*)`, "HUGORELEASER_TAG="+tag,
			`HUGORELEASER_COMMITISH=(\S*)`, "HUGORELEASER_COMMITISH="+sha,
		); err != nil {
			return err
		}
		logf("HUGORELEASER_TAG=%s\n", tag)
		logf("HUGORELEASER_COMMITISH=%s\n", sha)

		return nil
	}

	if err := r.bumpVersions(finalVersion); err != nil {
		return err
	}

	if _, err := r.git("commit", "-a", "-m", fmt.Sprintf("%s Prepare repository for %s\n\n[ci skip]", commitPrefix, finalVersion)); err != nil {
		return err
	}

	return nil
}

func (r *ReleaseHandler) bumpVersions(ver hugo.Version) error {
	toDev := ""

	if ver.Suffix != "" {
		toDev = ver.Suffix
	}

	if err := r.replaceInFile("common/hugo/version_current.go",
		`Minor:(\s*)(\d*),`, fmt.Sprintf(`Minor:${1}%d,`, ver.Minor),
		`PatchLevel:(\s*)(\d*),`, fmt.Sprintf(`PatchLevel:${1}%d,`, ver.PatchLevel),
		`Suffix:(\s*)".*",`, fmt.Sprintf(`Suffix:${1}"%s",`, toDev)); err != nil {
		return err
	}

	var minVersion string
	if ver.Suffix != "" {
		// People use the DEV version in daily use, and we cannot create new themes
		// with the next version before it is released.
		minVersion = ver.Prev().String()
	} else {
		minVersion = ver.String()
	}

	if err := r.replaceInFile("commands/new.go",
		`min_version = "(.*)"`, fmt.Sprintf(`min_version = "%s"`, minVersion)); err != nil {
		return err
	}

	return nil
}

func (r ReleaseHandler) calculateVersions() (hugo.Version, hugo.Version) {
	newVersion := hugo.MustParseVersion(r.branchVersion)
	finalVersion := newVersion.Next()
	finalVersion.PatchLevel = 0

	if newVersion.Suffix != "-test" {
		newVersion.Suffix = ""
	}

	finalVersion.Suffix = "-DEV"

	return newVersion, finalVersion
}

func (r *ReleaseHandler) gitPush() {
	if r.skipPush {
		return
	}
	if _, err := r.git("push", "origin", "HEAD"); err != nil {
		log.Fatal("push failed:", err)
	}
}

func (r *ReleaseHandler) replaceInFile(filename string, oldNew ...string) error {
	filename = filepath.FromSlash(filename)
	fi, err := os.Stat(filename)
	if err != nil {
		return err
	}

	if r.try {
		logf("Replace in %q: %q\n", filename, oldNew)
		return nil
	}

	b, err := os.ReadFile(filename)
	if err != nil {
		return err
	}
	newContent := string(b)

	for i := 0; i < len(oldNew); i += 2 {
		re := regexp.MustCompile(oldNew[i])
		newContent = re.ReplaceAllString(newContent, oldNew[i+1])
	}

	return os.WriteFile(filename, []byte(newContent), fi.Mode())
}

func git(args ...string) (string, error) {
	cmd, _ := hexec.SafeCommand("git", args...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("git failed: %q: %q (%q)", err, out, args)
	}
	return string(out), nil
}

func logf(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format, args...)
}

func logln(args ...interface{}) {
	fmt.Fprintln(os.Stderr, args...)
}


text:
NS_ASSUME_NONNULL_BEGIN

@class RBDateTime;

/// Represents a duration of time.
@interface RBDuration : NSObject

#pragma mark - Initializers

/// Initializes a new @c RBDuration instance with given time interval.
///
/// @param  seconds         The number of seconds.
- (instancetype)initWithTimeInterval:(NSTimeInterval)seconds NS_DESIGNATED_INITIALIZER;

/// Initializes a new @c RBDuration instance with given numbers of days, hours, minutes, seconds, and
/// milliseconds.
///
/// @param  days            The number of days.
/// @param  hours           The number of hours.
/// @param  minutes         The number of minutes.
/// @param  seconds         The number of seconds.
/// @param  milliseconds    The number of milliseconds.
- (instancetype)initWithDays:(NSInteger)days
                       hours:(NSInteger)hours minutes:(NSInteger)minutes seconds:(NSInteger)seconds
                milliseconds:(NSInteger)milliseconds NS_DESIGNATED_INITIALIZER;

/// Creates a new @c RBDuration instance with given numbers of days, hours, minutes, seconds, and
/// milliseconds.
///
/// @param  days            The number of days.
/// @param  hours           The number of hours.
/// @param  minutes         The number of minutes.
/// @param  seconds         The number of seconds.
/// @param  milliseconds    The number of milliseconds.
+ (instancetype)durationWithDays:(NSInteger)days
                           hours:(NSInteger)hours minutes:(NSInteger)minutes seconds:(NSInteger)seconds
                    milliseconds:(NSInteger)milliseconds;
/// Creates a new @c RBDuration instance with given numbers of hours, minutes, and seconds.
///
/// @param  hours           The number of hours.
/// @param  minutes         The number of minutes.
/// @param  seconds         The number of seconds.
+ (instancetype)durationWithHours:(NSInteger)hours minutes:(NSInteger)minutes seconds:(NSInteger)seconds;

/// Creates a new @c RBDuration instance with a given number of days.
/// @param  days            The number of days.
+ (instancetype)durationWithDays:(NSInteger)days;
/// Creates a new @c RBDuration instance with a given number of hours.
/// @param  hours           The number of hours.
+ (instancetype)durationWithHours:(NSInteger)hours;
/// Creates a new @c RBDuration instance with a given number of minutes.
/// @param  minutes         The number of minutes.
+ (instancetype)durationWithMinutes:(NSInteger)minutes;
/// Creates a new @c RBDuration instance with a given number of seconds.
/// @param  seconds         The number of seconds.
+ (instancetype)durationWithSeconds:(NSInteger)seconds;
/// Creates a new @c RBDuration instance with a given number of milliseconds.
/// @param  milliseconds    The number of milliseconds.
+ (instancetype)durationWithMilliseconds:(NSInteger)milliseconds;

/// Returns a @c RBDuration instance that is the difference between two given dates. A negative
/// duration will be returned if the start date is later than the end date.
///
/// @param  date1           The start date for the calculation.
/// @param  date2           The end date for the calculation.
+ (instancetype)durationFromDate:(RBDateTime *)date1 toDate:(RBDateTime *)date2;

#pragma mark - Components

/// Returns the time interval of this duration.
@property (readonly) NSTimeInterval timeInterval;

/// Returns the days component.
@property (readonly) NSInteger days;
/// Returns the hours component.
@property (readonly) NSInteger hours;
/// Returns the minutes component.
@property (readonly) NSInteger minutes;
/// Returns the seconds component.
@property (readonly) NSInteger seconds;
/// Returns the milliseconds component.
@property (readonly) NSInteger milliseconds;

#pragma mark - Convenient Computation

/// Returns the value of this duration expressed in whole and fractional days.
@property (readonly) double totalDays;
/// Returns the value of this duration expressed in whole and fractional hours.
@property (readonly) double totalHours;
/// Returns the value of this duration expressed in whole and fractional minutes.
@property (readonly) double totalMinutes;
/// Returns the value of this duration expressed in whole and fractional seconds.
@property (readonly) double totalSeconds;
/// Returns the value of this duration expressed in whole and fractional milliseconds.
@property (readonly) double totalMilliseconds;

#pragma mark - Operations

/// Returns a new @c RBDuration that adds the given duration to the value of this instance.
/// @param  duration        The specific duration to add.
- (instancetype)durationByAdding:(RBDuration *)duration;
/// Returns a new @c RBDuration that subtracts the given duration to the value of this instance.
/// @param  duration        The specified duration to subtract.
- (instancetype)durationBySubtracting:(RBDuration *)duration;

/// Adds the value of the given @c RBDuration to the value of this instance.
/// @param  duration        The specified duration to add.
- (void)add:(RBDuration *)duration;
/// Subtracts the value of the given @c RBDuration to the value of this instance.
/// @param  duration        The specified duration to subtract.
- (void)subtract:(RBDuration *)duration;

/// Returns a new @c RBDuration that is the negated value of this instance.
- (instancetype)negatedDuration;
/// Negates the value of this instance.
- (void)negate;

/// Compares two @c RBDuration instances and returns a @c NSComparisonResult that indicates
/// whether the first value is shorter than, equal to, or longer than the second value.
///
/// @param  duration1       The first duration to compare.
/// @param  duration2       The second duration to compare.
+ (NSComparisonResult)compare:(nullable RBDuration *)duration1 to:(nullable RBDuration *)duration2;
/// Compares this instance to a given @c RBDuration instance and returns a @c NSComparisonResult
/// that indicates whether this instance is shorter than, equal to, or longer than the given
/// @c RBDuration instance.
///
/// @param  duration        The other @RBDuration instance to compare with.
- (NSComparisonResult)compareTo:(nullable RBDuration *)duration;

/// Returns a Boolean value that indicates whether the given duration equals to this instance.
///
/// @param  duration        The other @RBDuration instance to compare with.
- (BOOL)equalsTo:(RBDuration *)duration;

@end

NS_ASSUME_NONNULL_END


text:
package org.ringojs.jsgi;

import org.eclipse.jetty.continuation.ContinuationSupport;
import org.mozilla.javascript.RhinoException;
import org.ringojs.engine.RingoConfig;
import org.ringojs.engine.RingoWorker;
import org.ringojs.engine.ScriptError;
import org.ringojs.tools.RingoRunner;
import org.ringojs.repository.Repository;
import org.ringojs.repository.FileRepository;
import org.ringojs.repository.WebappRepository;
import org.ringojs.engine.RhinoEngine;
import org.ringojs.util.StringUtils;
import org.mozilla.javascript.Callable;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class JsgiServlet extends HttpServlet {

    String module;
    Object function;
    RhinoEngine engine;
    JsgiRequest requestProto;
    boolean hasContinuation = false;

    public JsgiServlet() {}

    public JsgiServlet(RhinoEngine engine) throws ServletException {
        this(engine, null);
    }

    public JsgiServlet(RhinoEngine engine, Callable callable) throws ServletException {
        this.engine = engine;
        this.function = callable;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        // don't overwrite function if it was set in constructor
        if (function == null) {
            module = getStringParameter(config, "app-module", "main");
            function = getStringParameter(config, "app-name", "app");
        }

        if (engine == null) {
            String ringoHome = getStringParameter(config, "ringo-home", "/WEB-INF");
            String modulePath = getStringParameter(config, "module-path", "WEB-INF/app");
            String bootScripts = getStringParameter(config, "bootscript", null);
            int optlevel = getIntParameter(config, "optlevel", 0);
            boolean debug = getBooleanParameter(config, "debug", false);
            boolean production = getBooleanParameter(config, "production", false);
            boolean verbose = getBooleanParameter(config, "verbose", false);
            boolean legacyMode = getBooleanParameter(config, "legacy-mode", false);

            ServletContext context = config.getServletContext();
            Repository base = new WebappRepository(context, "/");
            Repository home = new WebappRepository(context, ringoHome);

            try {
                if (!home.exists()) {
                    home = new FileRepository(ringoHome);
                    System.err.println("Resource \"" + ringoHome + "\" not found, "
                            + "reverting to file repository " + home);
                }
                // Use ',' as platform agnostic path separator
                String[] paths = StringUtils.split(modulePath, ",");
                String[] systemPaths = {"modules", "packages"};
                RingoConfig ringoConfig =
                        new RingoConfig(home, base, paths, systemPaths);
                ringoConfig.setDebug(debug);
                ringoConfig.setVerbose(verbose);
                ringoConfig.setParentProtoProperties(legacyMode);
                ringoConfig.setStrictVars(!legacyMode && !production);
                ringoConfig.setReloading(!production);
                ringoConfig.setOptLevel(optlevel);
                if (bootScripts != null) {
                    ringoConfig.setBootstrapScripts(Arrays.asList(
                            StringUtils.split(bootScripts, ",")));
                }
                engine = new RhinoEngine(ringoConfig, null);
            } catch (Exception x) {
                throw new ServletException(x);
            }
        }

        try {
            hasContinuation = ContinuationSupport.class != null;
        } catch (NoClassDefFoundError ignore) {
            hasContinuation = false;
        }

        requestProto = new JsgiRequest(engine.getScope(), hasContinuation);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            if (hasContinuation && ContinuationSupport
                    .getContinuation(request).isExpired()) {
                return; // continuation timeouts are handled by ringo/jsgi module
            }
        } catch (Exception x) {
            // Continuations may not be set up even if class is available.
            // Set flag to false and ignore otherwise.
            log("Caught exception, disabling continuation support", x);
            hasContinuation = false;
            requestProto = new JsgiRequest(engine.getScope(), false);
        }
        JsgiRequest req = new JsgiRequest(request, response, requestProto,
                engine.getScope(), this);
        RingoWorker worker = engine.getWorker();
        try {
            worker.invoke("ringo/jsgi/connector", "handleRequest", module,
                    function, req);
        } catch (Exception x) {
            List


text:
{% if page.carousel %}

		{% for image in page.carousel- %}

		{% endfor %}

		{% for image in page.carousel %}

{{ image.title }}

{{ image.caption }}

{{ image.action }}

		{% endfor %}

{% endif %}


text:
#include "uv.h"
#include "internal.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <unistd.h>
#include <limits.h> /* IOV_MAX */

#if defined(__APPLE__)
# include <sys/event.h>
# include <sys/time.h>
# include <sys/select.h>

/* Forward declaration */
typedef struct uv__stream_select_s uv__stream_select_t;

struct uv__stream_select_s {
  uv_stream_t* stream;
  uv_thread_t thread;
  uv_sem_t close_sem;
  uv_sem_t async_sem;
  uv_async_t async;
  int events;
  int fake_fd;
  int int_fd;
  int fd;
  fd_set* sread;
  size_t sread_sz;
  fd_set* swrite;
  size_t swrite_sz;
};
#endif /* defined(__APPLE__) */

static void uv__stream_connect(uv_stream_t*);
static void uv__write(uv_stream_t* stream);
static void uv__read(uv_stream_t* stream);
static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events);
static void uv__write_callbacks(uv_stream_t* stream);
static size_t uv__write_req_size(uv_write_t* req);

void uv__stream_init(uv_loop_t* loop,
                     uv_stream_t* stream,
                     uv_handle_type type) {
  int err;

  uv__handle_init(loop, (uv_handle_t*)stream, type);
  stream->read_cb = NULL;
  stream->alloc_cb = NULL;
  stream->close_cb = NULL;
  stream->connection_cb = NULL;
  stream->connect_req = NULL;
  stream->shutdown_req = NULL;
  stream->accepted_fd = -1;
  stream->queued_fds = NULL;
  stream->delayed_error = 0;
  QUEUE_INIT(&stream->write_queue);
  QUEUE_INIT(&stream->write_completed_queue);
  stream->write_queue_size = 0;

  if (loop->emfile_fd == -1) {
    err = uv__open_cloexec("/dev/null", O_RDONLY);
    if (err < 0)
        /* In the rare case that "/dev/null" isn't mounted open "/"
         * instead.
         */
        err = uv__open_cloexec("/", O_RDONLY);
    if (err >= 0)
      loop->emfile_fd = err;
  }

#if defined(__APPLE__)
  stream->select = NULL;
#endif /* defined(__APPLE_) */

  uv__io_init(&stream->io_watcher, uv__stream_io, -1);
}

static void uv__stream_osx_interrupt_select(uv_stream_t* stream) {
#if defined(__APPLE__)
  /* Notify select() thread about state change */
  uv__stream_select_t* s;
  int r;

  s = stream->select;
  if (s == NULL)
    return;

  /* Interrupt select() loop
   * NOTE: fake_fd and int_fd are socketpair(), thus writing to one will
   * emit read event on other side
   */
  do
    r = write(s->fake_fd, "x", 1);
  while (r == -1 && errno == EINTR);

  assert(r == 1);
#else  /* !defined(__APPLE__) */
  /* No-op on any other platform */
#endif  /* !defined(__APPLE__) */
}

#if defined(__APPLE__)
static void uv__stream_osx_select(void* arg) {
  uv_stream_t* stream;
  uv__stream_select_t* s;
  char buf[1024];
  int events;
  int fd;
  int r;
  int max_fd;

  stream = arg;
  s = stream->select;
  fd = s->fd;

  if (fd > s->int_fd)
    max_fd = fd;
  else
    max_fd = s->int_fd;

  while (1) {
    /* Terminate on semaphore */
    if (uv_sem_trywait(&s->close_sem) == 0)
      break;

    /* Watch fd using select(2) */
    memset(s->sread, 0, s->sread_sz);
    memset(s->swrite, 0, s->swrite_sz);

    if (uv__io_active(&stream->io_watcher, POLLIN))
      FD_SET(fd, s->sread);
    if (uv__io_active(&stream->io_watcher, POLLOUT))
      FD_SET(fd, s->swrite);
    FD_SET(s->int_fd, s->sread);

    /* Wait indefinitely for fd events */
    r = select(max_fd + 1, s->sread, s->swrite, NULL, NULL);
    if (r == -1) {
      if (errno == EINTR)
        continue;

      /* XXX: Possible?! */
      abort();
    }

    /* Ignore timeouts */
    if (r == 0)
      continue;

    /* Empty socketpair's buffer in case of interruption */
    if (FD_ISSET(s->int_fd, s->sread))
      while (1) {
        r = read(s->int_fd, buf, sizeof(buf));

        if (r == sizeof(buf))
          continue;

        if (r != -1)
          break;

        if (errno == EAGAIN || errno == EWOULDBLOCK)
          break;

        if (errno == EINTR)
          continue;

        abort();
      }

    /* Handle events */
    events = 0;
    if (FD_ISSET(fd, s->sread))
      events |= POLLIN;
    if (FD_ISSET(fd, s->swrite))
      events |= POLLOUT;

    assert(events != 0 || FD_ISSET(s->int_fd, s->sread));
    if (events != 0) {
      ACCESS_ONCE(int, s->events) = events;

      uv_async_send(&s->async);
      uv_sem_wait(&s->async_sem);

      /* Should be processed at this stage */
      assert((s->events == 0) || (stream->flags & UV_CLOSING));
    }
  }
}

static void uv__stream_osx_select_cb(uv_async_t* handle) {
  uv__stream_select_t* s;
  uv_stream_t* stream;
  int events;

  s = container_of(handle, uv__stream_select_t, async);
  stream = s->stream;

  /* Get and reset stream's events */
  events = s->events;
  ACCESS_ONCE(int, s->events) = 0;

  assert(events != 0);
  assert(events == (events & (POLLIN | POLLOUT)));

  /* Invoke callback on event-loop */
  if ((events & POLLIN) && uv__io_active(&stream->io_watcher, POLLIN))
    uv__stream_io(stream->loop, &stream->io_watcher, POLLIN);

  if ((events & POLLOUT) && uv__io_active(&stream->io_watcher, POLLOUT))
    uv__stream_io(stream->loop, &stream->io_watcher, POLLOUT);

  if (stream->flags & UV_CLOSING)
    return;

  /* NOTE: It is important to do it here, otherwise `select()` might be called
   * before the actual `uv__read()`, leading to the blocking syscall
   */
  uv_sem_post(&s->async_sem);
}

static void uv__stream_osx_cb_close(uv_handle_t* async) {
  uv__stream_select_t* s;

  s = container_of(async, uv__stream_select_t, async);
  uv__free(s);
}

int uv__stream_try_select(uv_stream_t* stream, int* fd) {
  /*
   * kqueue doesn't work with some files from /dev mount on osx.
   * select(2) in separate thread for those fds
   */

  struct kevent filter[1];
  struct kevent events[1];
  struct timespec timeout;
  uv__stream_select_t* s;
  int fds[2];
  int err;
  int ret;
  int kq;
  int old_fd;
  int max_fd;
  size_t sread_sz;
  size_t swrite_sz;

  kq = kqueue();
  if (kq == -1) {
    perror("(libuv) kqueue()");
    return -errno;
  }

  EV_SET(&filter[0], *fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, 0);

  /* Use small timeout, because we only want to capture EINVALs */
  timeout.tv_sec = 0;
  timeout.tv_nsec = 1;

  do
    ret = kevent(kq, filter, 1, events, 1, &timeout);
  while (ret == -1 && errno == EINTR);

  uv__close(kq);

  if (ret == -1)
    return -errno;

  if (ret == 0 || (events[0].flags & EV_ERROR) == 0 || events[0].data != EINVAL)
    return 0;

  /* At this point we definitely know that this fd won't work with kqueue */

  /*
   * Create fds for io watcher and to interrupt the select() loop.
   * NOTE: do it ahead of malloc below to allocate enough space for fd_sets
   */
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds))
    return -errno;

  max_fd = *fd;
  if (fds[1] > max_fd)
    max_fd = fds[1];

  sread_sz = ROUND_UP(max_fd + 1, sizeof(uint32_t) * NBBY) / NBBY;
  swrite_sz = sread_sz;

  s = uv__malloc(sizeof(*s) + sread_sz + swrite_sz);
  if (s == NULL) {
    err = -ENOMEM;
    goto failed_malloc;
  }

  s->events = 0;
  s->fd = *fd;
  s->sread = (fd_set*) ((char*) s + sizeof(*s));
  s->sread_sz = sread_sz;
  s->swrite = (fd_set*) ((char*) s->sread + sread_sz);
  s->swrite_sz = swrite_sz;

  err = uv_async_init(stream->loop, &s->async, uv__stream_osx_select_cb);
  if (err)
    goto failed_async_init;

  s->async.flags |= UV__HANDLE_INTERNAL;
  uv__handle_unref(&s->async);

  err = uv_sem_init(&s->close_sem, 0);
  if (err != 0)
    goto failed_close_sem_init;

  err = uv_sem_init(&s->async_sem, 0);
  if (err != 0)
    goto failed_async_sem_init;

  s->fake_fd = fds[0];
  s->int_fd = fds[1];

  old_fd = *fd;
  s->stream = stream;
  stream->select = s;
  *fd = s->fake_fd;

  err = uv_thread_create(&s->thread, uv__stream_osx_select, stream);
  if (err != 0)
    goto failed_thread_create;

  return 0;

failed_thread_create:
  s->stream = NULL;
  stream->select = NULL;
  *fd = old_fd;

  uv_sem_destroy(&s->async_sem);

failed_async_sem_init:
  uv_sem_destroy(&s->close_sem);

failed_close_sem_init:
  uv__close(fds[0]);
  uv__close(fds[1]);
  uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close);
  return err;

failed_async_init:
  uv__free(s);

failed_malloc:
  uv__close(fds[0]);
  uv__close(fds[1]);

  return err;
}
#endif /* defined(__APPLE__) */

int uv__stream_open(uv_stream_t* stream, int fd, int flags) {
#if defined(__APPLE__)
  int enable;
#endif

  if (!(stream->io_watcher.fd == -1 || stream->io_watcher.fd == fd))
    return -EBUSY;

  assert(fd >= 0);
  stream->flags |= flags;

  if (stream->type == UV_TCP) {
    if ((stream->flags & UV_TCP_NODELAY) && uv__tcp_nodelay(fd, 1))
      return -errno;

    /* TODO Use delay the user passed in. */
    if ((stream->flags & UV_TCP_KEEPALIVE) && uv__tcp_keepalive(fd, 1, 60))
      return -errno;
  }

#if defined(__APPLE__)
  enable = 1;
  if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &enable, sizeof(enable)) &&
      errno != ENOTSOCK &&
      errno != EINVAL) {
    return -errno;
  }
#endif

  stream->io_watcher.fd = fd;

  return 0;
}

void uv__stream_flush_write_queue(uv_stream_t* stream, int error) {
  uv_write_t* req;
  QUEUE* q;
  while (!QUEUE_EMPTY(&stream->write_queue)) {
    q = QUEUE_HEAD(&stream->write_queue);
    QUEUE_REMOVE(q);

    req = QUEUE_DATA(q, uv_write_t, queue);
    req->error = error;

    QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue);
  }
}

void uv__stream_destroy(uv_stream_t* stream) {
  assert(!uv__io_active(&stream->io_watcher, POLLIN | POLLOUT));
  assert(stream->flags & UV_CLOSED);

  if (stream->connect_req) {
    uv__req_unregister(stream->loop, stream->connect_req);
    stream->connect_req->cb(stream->connect_req, -ECANCELED);
    stream->connect_req = NULL;
  }

  uv__stream_flush_write_queue(stream, -ECANCELED);
  uv__write_callbacks(stream);

  if (stream->shutdown_req) {
    /* The ECANCELED error code is a lie, the shutdown(2) syscall is a
     * fait accompli at this point. Maybe we should revisit this in v0.11.
     * A possible reason for leaving it unchanged is that it informs the
     * callee that the handle has been destroyed.
     */
    uv__req_unregister(stream->loop, stream->shutdown_req);
    stream->shutdown_req->cb(stream->shutdown_req, -ECANCELED);
    stream->shutdown_req = NULL;
  }

  assert(stream->write_queue_size == 0);
}

/* Implements a best effort approach to mitigating accept() EMFILE errors.
 * We have a spare file descriptor stashed away that we close to get below
 * the EMFILE limit. Next, we accept all pending connections and close them
 * immediately to signal the clients that we're overloaded - and we are, but
 * we still keep on trucking.
 *
 * There is one caveat: it's not reliable in a multi-threaded environment.
 * The file descriptor limit is per process. Our party trick fails if another
 * thread opens a file or creates a socket in the time window between us
 * calling close() and accept().
 */
static int uv__emfile_trick(uv_loop_t* loop, int accept_fd) {
  int err;
  int emfile_fd;

  if (loop->emfile_fd == -1)
    return -EMFILE;

  uv__close(loop->emfile_fd);
  loop->emfile_fd = -1;

  do {
    err = uv__accept(accept_fd);
    if (err >= 0)
      uv__close(err);
  } while (err >= 0 || err == -EINTR);

  emfile_fd = uv__open_cloexec("/", O_RDONLY);
  if (emfile_fd >= 0)
    loop->emfile_fd = emfile_fd;

  return err;
}

#if defined(UV_HAVE_KQUEUE)
# define UV_DEC_BACKLOG(w) w->rcount--;
#else
# define UV_DEC_BACKLOG(w) /* no-op */
#endif /* defined(UV_HAVE_KQUEUE) */

void uv__server_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
  uv_stream_t* stream;
  int err;

  stream = container_of(w, uv_stream_t, io_watcher);
  assert(events == POLLIN);
  assert(stream->accepted_fd == -1);
  assert(!(stream->flags & UV_CLOSING));

  uv__io_start(stream->loop, &stream->io_watcher, POLLIN);

  /* connection_cb can close the server socket while we're
   * in the loop so check it on each iteration.
   */
  while (uv__stream_fd(stream) != -1) {
    assert(stream->accepted_fd == -1);

#if defined(UV_HAVE_KQUEUE)
    if (w->rcount <= 0)
      return;
#endif /* defined(UV_HAVE_KQUEUE) */

    err = uv__accept(uv__stream_fd(stream));
    if (err < 0) {
      if (err == -EAGAIN || err == -EWOULDBLOCK)
        return;  /* Not an error. */

      if (err == -ECONNABORTED)
        continue;  /* Ignore. Nothing we can do about that. */

      if (err == -EMFILE || err == -ENFILE) {
        err = uv__emfile_trick(loop, uv__stream_fd(stream));
        if (err == -EAGAIN || err == -EWOULDBLOCK)
          break;
      }

      stream->connection_cb(stream, err);
      continue;
    }

    UV_DEC_BACKLOG(w)
    stream->accepted_fd = err;
    stream->connection_cb(stream, 0);

    if (stream->accepted_fd != -1) {
      /* The user hasn't yet accepted called uv_accept() */
      uv__io_stop(loop, &stream->io_watcher, POLLIN);
      return;
    }

    if (stream->type == UV_TCP && (stream->flags & UV_TCP_SINGLE_ACCEPT)) {
      /* Give other processes a chance to accept connections. */
      struct timespec timeout = { 0, 1 };
      nanosleep(&timeout, NULL);
    }
  }
}

#undef UV_DEC_BACKLOG

int uv_accept(uv_stream_t* server, uv_stream_t* client) {
  int err;

  assert(server->loop == client->loop);

  if (server->accepted_fd == -1)
    return -EAGAIN;

  switch (client->type) {
    case UV_NAMED_PIPE:
    case UV_TCP:
      err = uv__stream_open(client,
                            server->accepted_fd,
                            UV_STREAM_READABLE | UV_STREAM_WRITABLE);
      if (err) {
        /* TODO handle error */
        uv__close(server->accepted_fd);
        goto done;
      }
      break;

    case UV_UDP:
      err = uv_udp_open((uv_udp_t*) client, server->accepted_fd);
      if (err) {
        uv__close(server->accepted_fd);
        goto done;
      }
      break;

    default:
      return -EINVAL;
  }

  client->flags |= UV_HANDLE_BOUND;

done:
  /* Process queued fds */
  if (server->queued_fds != NULL) {
    uv__stream_queued_fds_t* queued_fds;

    queued_fds = server->queued_fds;

    /* Read first */
    server->accepted_fd = queued_fds->fds[0];

    /* All read, free */
    assert(queued_fds->offset > 0);
    if (--queued_fds->offset == 0) {
      uv__free(queued_fds);
      server->queued_fds = NULL;
    } else {
      /* Shift rest */
      memmove(queued_fds->fds,
              queued_fds->fds + 1,
              queued_fds->offset * sizeof(*queued_fds->fds));
    }
  } else {
    server->accepted_fd = -1;
    if (err == 0)
      uv__io_start(server->loop, &server->io_watcher, POLLIN);
  }
  return err;
}

int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) {
  int err;

  switch (stream->type) {
  case UV_TCP:
    err = uv_tcp_listen((uv_tcp_t*)stream, backlog, cb);
    break;

  case UV_NAMED_PIPE:
    err = uv_pipe_listen((uv_pipe_t*)stream, backlog, cb);
    break;

  default:
    err = -EINVAL;
  }

  if (err == 0)
    uv__handle_start(stream);

  return err;
}

static void uv__drain(uv_stream_t* stream) {
  uv_shutdown_t* req;
  int err;

  assert(QUEUE_EMPTY(&stream->write_queue));
  uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
  uv__stream_osx_interrupt_select(stream);

  /* Shutdown? */
  if ((stream->flags & UV_STREAM_SHUTTING) &&
      !(stream->flags & UV_CLOSING) &&
      !(stream->flags & UV_STREAM_SHUT)) {
    assert(stream->shutdown_req);

    req = stream->shutdown_req;
    stream->shutdown_req = NULL;
    stream->flags &= ~UV_STREAM_SHUTTING;
    uv__req_unregister(stream->loop, req);

    err = 0;
    if (shutdown(uv__stream_fd(stream), SHUT_WR))
      err = -errno;

    if (err == 0)
      stream->flags |= UV_STREAM_SHUT;

    if (req->cb != NULL)
      req->cb(req, err);
  }
}

static size_t uv__write_req_size(uv_write_t* req) {
  size_t size;

  assert(req->bufs != NULL);
  size = uv__count_bufs(req->bufs + req->write_index,
                        req->nbufs - req->write_index);
  assert(req->handle->write_queue_size >= size);

  return size;
}

static void uv__write_req_finish(uv_write_t* req) {
  uv_stream_t* stream = req->handle;

  /* Pop the req off tcp->write_queue. */
  QUEUE_REMOVE(&req->queue);

  /* Only free when there was no error. On error, we touch up write_queue_size
   * right before making the callback. The reason we don't do that right away
   * is that a write_queue_size > 0 is our only way to signal to the user that
   * they should stop writing - which they should if we got an error. Something
   * to revisit in future revisions of the libuv API.
   */
  if (req->error == 0) {
    if (req->bufs != req->bufsml)
      uv__free(req->bufs);
    req->bufs = NULL;
  }

  /* Add it to the write_completed_queue where it will have its
   * callback called in the near future.
   */
  QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue);
  uv__io_feed(stream->loop, &stream->io_watcher);
}

static int uv__handle_fd(uv_handle_t* handle) {
  switch (handle->type) {
    case UV_NAMED_PIPE:
    case UV_TCP:
      return ((uv_stream_t*) handle)->io_watcher.fd;

    case UV_UDP:
      return ((uv_udp_t*) handle)->io_watcher.fd;

    default:
      return -1;
  }
}

static void uv__write(uv_stream_t* stream) {
  struct iovec* iov;
  QUEUE* q;
  uv_write_t* req;
  int iovmax;
  int iovcnt;
  ssize_t n;

start:

  assert(uv__stream_fd(stream) >= 0);

  if (QUEUE_EMPTY(&stream->write_queue))
    return;

  q = QUEUE_HEAD(&stream->write_queue);
  req = QUEUE_DATA(q, uv_write_t, queue);
  assert(req->handle == stream);

  /*
   * Cast to iovec. We had to have our own uv_buf_t instead of iovec
   * because Windows's WSABUF is not an iovec.
   */
  assert(sizeof(uv_buf_t) == sizeof(struct iovec));
  iov = (struct iovec*) &(req->bufs[req->write_index]);
  iovcnt = req->nbufs - req->write_index;

  iovmax = uv__getiovmax();

  /* Limit iov count to avoid EINVALs from writev() */
  if (iovcnt > iovmax)
    iovcnt = iovmax;

  /*
   * Now do the actual writev. Note that we've been updating the pointers
   * inside the iov each time we write. So there is no need to offset it.
   */

  if (req->send_handle) {
    struct msghdr msg;
    struct cmsghdr *cmsg;
    int fd_to_send = uv__handle_fd((uv_handle_t*) req->send_handle);
    union {
      char data[64];
      struct cmsghdr alias;
    } scratch;

    memset(&scratch, 0, sizeof(scratch));

    assert(fd_to_send >= 0);

    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_iov = iov;
    msg.msg_iovlen = iovcnt;
    msg.msg_flags = 0;

    msg.msg_control = &scratch.alias;
    msg.msg_controllen = CMSG_SPACE(sizeof(fd_to_send));

    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    cmsg->cmsg_len = CMSG_LEN(sizeof(fd_to_send));

    /* silence aliasing warning */
    {
      void* pv = CMSG_DATA(cmsg);
      int* pi = pv;
      *pi = fd_to_send;
    }

    do {
      n = sendmsg(uv__stream_fd(stream), &msg, 0);
    }
#if defined(__APPLE__)
    /*
     * Due to a possible kernel bug at least in OS X 10.10 "Yosemite",
     * EPROTOTYPE can be returned while trying to write to a socket that is
     * shutting down. If we retry the write, we should get the expected EPIPE
     * instead.
     */
    while (n == -1 && (errno == EINTR || errno == EPROTOTYPE));
#else
    while (n == -1 && errno == EINTR);
#endif
  } else {
    do {
      if (iovcnt == 1) {
        n = write(uv__stream_fd(stream), iov[0].iov_base, iov[0].iov_len);
      } else {
        n = writev(uv__stream_fd(stream), iov, iovcnt);
      }
    }
#if defined(__APPLE__)
    /*
     * Due to a possible kernel bug at least in OS X 10.10 "Yosemite",
     * EPROTOTYPE can be returned while trying to write to a socket that is
     * shutting down. If we retry the write, we should get the expected EPIPE
     * instead.
     */
    while (n == -1 && (errno == EINTR || errno == EPROTOTYPE));
#else
    while (n == -1 && errno == EINTR);
#endif
  }

  if (n < 0) {
    if (errno != EAGAIN && errno != EWOULDBLOCK) {
      /* Error */
      req->error = -errno;
      uv__write_req_finish(req);
      uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
      if (!uv__io_active(&stream->io_watcher, POLLIN))
        uv__handle_stop(stream);
      uv__stream_osx_interrupt_select(stream);
      return;
    } else if (stream->flags & UV_STREAM_BLOCKING) {
      /* If this is a blocking stream, try again. */
      goto start;
    }
  } else {
    /* Successful write */

    while (n >= 0) {
      uv_buf_t* buf = &(req->bufs[req->write_index]);
      size_t len = buf->len;

      assert(req->write_index < req->nbufs);

      if ((size_t)n < len) {
        buf->base += n;
        buf->len -= n;
        stream->write_queue_size -= n;
        n = 0;

        /* There is more to write. */
        if (stream->flags & UV_STREAM_BLOCKING) {
          /*
           * If we're blocking then we should not be enabling the write
           * watcher - instead we need to try again.
           */
          goto start;
        } else {
          /* Break loop and ensure the watcher is pending. */
          break;
        }

      } else {
        /* Finished writing the buf at index req->write_index. */
        req->write_index++;

        assert((size_t)n >= len);
        n -= len;

        assert(stream->write_queue_size >= len);
        stream->write_queue_size -= len;

        if (req->write_index == req->nbufs) {
          /* Then we're done! */
          assert(n == 0);
          uv__write_req_finish(req);
          /* TODO: start trying to write the next request. */
          return;
        }
      }
    }
  }

  /* Either we've counted n down to zero or we've got EAGAIN. */
  assert(n == 0 || n == -1);

  /* Only non-blocking streams should use the write_watcher. */
  assert(!(stream->flags & UV_STREAM_BLOCKING));

  /* We're not done. */
  uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);

  /* Notify select() thread about state change */
  uv__stream_osx_interrupt_select(stream);
}

static void uv__write_callbacks(uv_stream_t* stream) {
  uv_write_t* req;
  QUEUE* q;

  while (!QUEUE_EMPTY(&stream->write_completed_queue)) {
    /* Pop a req off write_completed_queue. */
    q = QUEUE_HEAD(&stream->write_completed_queue);
    req = QUEUE_DATA(q, uv_write_t, queue);
    QUEUE_REMOVE(q);
    uv__req_unregister(stream->loop, req);

    if (req->bufs != NULL) {
      stream->write_queue_size -= uv__write_req_size(req);
      if (req->bufs != req->bufsml)
        uv__free(req->bufs);
      req->bufs = NULL;
    }

    /* NOTE: call callback AFTER freeing the request data. */
    if (req->cb)
      req->cb(req, req->error);
  }

  assert(QUEUE_EMPTY(&stream->write_completed_queue));
}

uv_handle_type uv__handle_type(int fd) {
  struct sockaddr_storage ss;
  socklen_t sslen;
  socklen_t len;
  int type;

  memset(&ss, 0, sizeof(ss));
  sslen = sizeof(ss);

  if (getsockname(fd, (struct sockaddr*)&ss, &sslen))
    return UV_UNKNOWN_HANDLE;

  len = sizeof type;

  if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &len))
    return UV_UNKNOWN_HANDLE;

  if (type == SOCK_STREAM) {
#if defined(_AIX) || defined(__DragonFly__)
    /* on AIX/DragonFly the getsockname call returns an empty sa structure
     * for sockets of type AF_UNIX.  For all other types it will
     * return a properly filled in structure.
     */
    if (sslen == 0)
      return UV_NAMED_PIPE;
#endif
    switch (ss.ss_family) {
      case AF_UNIX:
        return UV_NAMED_PIPE;
      case AF_INET:
      case AF_INET6:
        return UV_TCP;
      }
  }

  if (type == SOCK_DGRAM &&
      (ss.ss_family == AF_INET || ss.ss_family == AF_INET6))
    return UV_UDP;

  return UV_UNKNOWN_HANDLE;
}

static void uv__stream_eof(uv_stream_t* stream, const uv_buf_t* buf) {
  stream->flags |= UV_STREAM_READ_EOF;
  uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
  if (!uv__io_active(&stream->io_watcher, POLLOUT))
    uv__handle_stop(stream);
  uv__stream_osx_interrupt_select(stream);
  stream->read_cb(stream, UV_EOF, buf);
  stream->flags &= ~UV_STREAM_READING;
}

static int uv__stream_queue_fd(uv_stream_t* stream, int fd) {
  uv__stream_queued_fds_t* queued_fds;
  unsigned int queue_size;

  queued_fds = stream->queued_fds;
  if (queued_fds == NULL) {
    queue_size = 8;
    queued_fds = uv__malloc((queue_size - 1) * sizeof(*queued_fds->fds) +
                            sizeof(*queued_fds));
    if (queued_fds == NULL)
      return -ENOMEM;
    queued_fds->size = queue_size;
    queued_fds->offset = 0;
    stream->queued_fds = queued_fds;

    /* Grow */
  } else if (queued_fds->size == queued_fds->offset) {
    queue_size = queued_fds->size + 8;
    queued_fds = uv__realloc(queued_fds,
                             (queue_size - 1) * sizeof(*queued_fds->fds) +
                              sizeof(*queued_fds));

    /*
     * Allocation failure, report back.
     * NOTE: if it is fatal - sockets will be closed in uv__stream_close
     */
    if (queued_fds == NULL)
      return -ENOMEM;
    queued_fds->size = queue_size;
    stream->queued_fds = queued_fds;
  }

  /* Put fd in a queue */
  queued_fds->fds[queued_fds->offset++] = fd;

  return 0;
}

#define UV__CMSG_FD_COUNT 64
#define UV__CMSG_FD_SIZE (UV__CMSG_FD_COUNT * sizeof(int))

static int uv__stream_recv_cmsg(uv_stream_t* stream, struct msghdr* msg) {
  struct cmsghdr* cmsg;

  for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) {
    char* start;
    char* end;
    int err;
    void* pv;
    int* pi;
    unsigned int i;
    unsigned int count;

    if (cmsg->cmsg_type != SCM_RIGHTS) {
      fprintf(stderr, "ignoring non-SCM_RIGHTS ancillary data: %d\n",
          cmsg->cmsg_type);
      continue;
    }

    /* silence aliasing warning */
    pv = CMSG_DATA(cmsg);
    pi = pv;

    /* Count available fds */
    start = (char*) cmsg;
    end = (char*) cmsg + cmsg->cmsg_len;
    count = 0;
    while (start + CMSG_LEN(count * sizeof(*pi)) < end)
      count++;
    assert(start + CMSG_LEN(count * sizeof(*pi)) == end);

    for (i = 0; i < count; i++) {
      /* Already has accepted fd, queue now */
      if (stream->accepted_fd != -1) {
        err = uv__stream_queue_fd(stream, pi[i]);
        if (err != 0) {
          /* Close rest */
          for (; i < count; i++)
            uv__close(pi[i]);
          return err;
        }
      } else {
        stream->accepted_fd = pi[i];
      }
    }
  }

  return 0;
}

#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wgnu-folding-constant"
#endif

static void uv__read(uv_stream_t* stream) {
  uv_buf_t buf;
  ssize_t nread;
  struct msghdr msg;
  char cmsg_space[CMSG_SPACE(UV__CMSG_FD_SIZE)];
  int count;
  int err;
  int is_ipc;

  stream->flags &= ~UV_STREAM_READ_PARTIAL;

  /* Prevent loop starvation when the data comes in as fast as (or faster than)
   * we can read it. XXX Need to rearm fd if we switch to edge-triggered I/O.
   */
  count = 32;

  is_ipc = stream->type == UV_NAMED_PIPE && ((uv_pipe_t*) stream)->ipc;

  /* XXX: Maybe instead of having UV_STREAM_READING we just test if
   * tcp->read_cb is NULL or not?
   */
  while (stream->read_cb
      && (stream->flags & UV_STREAM_READING)
      && (count-- > 0)) {
    assert(stream->alloc_cb != NULL);

    buf = uv_buf_init(NULL, 0);
    stream->alloc_cb((uv_handle_t*)stream, 64 * 1024, &buf);
    if (buf.base == NULL || buf.len == 0) {
      /* User indicates it can't or won't handle the read. */
      stream->read_cb(stream, UV_ENOBUFS, &buf);
      return;
    }

    assert(buf.base != NULL);
    assert(uv__stream_fd(stream) >= 0);

    if (!is_ipc) {
      do {
        nread = read(uv__stream_fd(stream), buf.base, buf.len);
      }
      while (nread < 0 && errno == EINTR);
    } else {
      /* ipc uses recvmsg */
      msg.msg_flags = 0;
      msg.msg_iov = (struct iovec*) &buf;
      msg.msg_iovlen = 1;
      msg.msg_name = NULL;
      msg.msg_namelen = 0;
      /* Set up to receive a descriptor even if one isn't in the message */
      msg.msg_controllen = sizeof(cmsg_space);
      msg.msg_control = cmsg_space;

      do {
        nread = uv__recvmsg(uv__stream_fd(stream), &msg, 0);
      }
      while (nread < 0 && errno == EINTR);
    }

    if (nread < 0) {
      /* Error */
      if (errno == EAGAIN || errno == EWOULDBLOCK) {
        /* Wait for the next one. */
        if (stream->flags & UV_STREAM_READING) {
          uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
          uv__stream_osx_interrupt_select(stream);
        }
        stream->read_cb(stream, 0, &buf);
#if defined(__CYGWIN__) || defined(__MSYS__)
      } else if (errno == ECONNRESET && stream->type == UV_NAMED_PIPE) {
        uv__stream_eof(stream, &buf);
        return;
#endif
      } else {
        /* Error. User should call uv_close(). */
        stream->read_cb(stream, -errno, &buf);
        if (stream->flags & UV_STREAM_READING) {
          stream->flags &= ~UV_STREAM_READING;
          uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
          if (!uv__io_active(&stream->io_watcher, POLLOUT))
            uv__handle_stop(stream);
          uv__stream_osx_interrupt_select(stream);
        }
      }
      return;
    } else if (nread == 0) {
      uv__stream_eof(stream, &buf);
      return;
    } else {
      /* Successful read */
      ssize_t buflen = buf.len;

      if (is_ipc) {
        err = uv__stream_recv_cmsg(stream, &msg);
        if (err != 0) {
          stream->read_cb(stream, err, &buf);
          return;
        }
      }

#if defined(__MVS__)
      if (is_ipc && msg.msg_controllen > 0) {
        uv_buf_t blankbuf;
        int nread;
        struct iovec *old;

        blankbuf.base = 0;
        blankbuf.len = 0;
        old = msg.msg_iov;
        msg.msg_iov = (struct iovec*) &blankbuf;
        nread = 0;
        do {
          nread = uv__recvmsg(uv__stream_fd(stream), &msg, 0);
          err = uv__stream_recv_cmsg(stream, &msg);
          if (err != 0) {
            stream->read_cb(stream, err, &buf);
            msg.msg_iov = old;
            return;
          }
        } while (nread == 0 && msg.msg_controllen > 0);
        msg.msg_iov = old;
      }
#endif
      stream->read_cb(stream, nread, &buf);

      /* Return if we didn't fill the buffer, there is no more data to read. */
      if (nread < buflen) {
        stream->flags |= UV_STREAM_READ_PARTIAL;
        return;
      }
    }
  }
}

#ifdef __clang__
# pragma clang diagnostic pop
#endif

#undef UV__CMSG_FD_COUNT
#undef UV__CMSG_FD_SIZE

int uv_shutdown(uv_shutdown_t* req, uv_stream_t* stream, uv_shutdown_cb cb) {
  assert((stream->type == UV_TCP || stream->type == UV_NAMED_PIPE) &&
         "uv_shutdown (unix) only supports uv_handle_t right now");

  if (!(stream->flags & UV_STREAM_WRITABLE) ||
      stream->flags & UV_STREAM_SHUT ||
      stream->flags & UV_STREAM_SHUTTING ||
      uv__is_closing(stream)) {
    return -ENOTCONN;
  }

  assert(uv__stream_fd(stream) >= 0);

  /* Initialize request */
  uv__req_init(stream->loop, req, UV_SHUTDOWN);
  req->handle = stream;
  req->cb = cb;
  stream->shutdown_req = req;
  stream->flags |= UV_STREAM_SHUTTING;

  uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
  uv__stream_osx_interrupt_select(stream);

  return 0;
}

static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
  uv_stream_t* stream;

  stream = container_of(w, uv_stream_t, io_watcher);

  assert(stream->type == UV_TCP ||
         stream->type == UV_NAMED_PIPE ||
         stream->type == UV_TTY);
  assert(!(stream->flags & UV_CLOSING));

  if (stream->connect_req) {
    uv__stream_connect(stream);
    return;
  }

  assert(uv__stream_fd(stream) >= 0);

  /* Ignore POLLHUP here. Even it it's set, there may still be data to read. */
  if (events & (POLLIN | POLLERR | POLLHUP))
    uv__read(stream);

  if (uv__stream_fd(stream) == -1)
    return;  /* read_cb closed stream. */

  /* Short-circuit iff POLLHUP is set, the user is still interested in read
   * events and uv__read() reported a partial read but not EOF. If the EOF
   * flag is set, uv__read() called read_cb with err=UV_EOF and we don't
   * have to do anything. If the partial read flag is not set, we can't
   * report the EOF yet because there is still data to read.
   */
  if ((events & POLLHUP) &&
      (stream->flags & UV_STREAM_READING) &&
      (stream->flags & UV_STREAM_READ_PARTIAL) &&
      !(stream->flags & UV_STREAM_READ_EOF)) {
    uv_buf_t buf = { NULL, 0 };
    uv__stream_eof(stream, &buf);
  }

  if (uv__stream_fd(stream) == -1)
    return;  /* read_cb closed stream. */

  if (events & (POLLOUT | POLLERR | POLLHUP)) {
    uv__write(stream);
    uv__write_callbacks(stream);

    /* Write queue drained. */
    if (QUEUE_EMPTY(&stream->write_queue))
      uv__drain(stream);
  }
}

/**
 * We get called here from directly following a call to connect(2).
 * In order to determine if we've errored out or succeeded must call
 * getsockopt.
 */
static void uv__stream_connect(uv_stream_t* stream) {
  int error;
  uv_connect_t* req = stream->connect_req;
  socklen_t errorsize = sizeof(int);

  assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE);
  assert(req);

  if (stream->delayed_error) {
    /* To smooth over the differences between unixes errors that
     * were reported synchronously on the first connect can be delayed
     * until the next tick--which is now.
     */
    error = stream->delayed_error;
    stream->delayed_error = 0;
  } else {
    /* Normal situation: we need to get the socket error from the kernel. */
    assert(uv__stream_fd(stream) >= 0);
    getsockopt(uv__stream_fd(stream),
               SOL_SOCKET,
               SO_ERROR,
               &error,
               &errorsize);
    error = -error;
  }

  if (error == -EINPROGRESS)
    return;

  stream->connect_req = NULL;
  uv__req_unregister(stream->loop, req);

  if (error < 0 || QUEUE_EMPTY(&stream->write_queue)) {
    uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
  }

  if (req->cb)
    req->cb(req, error);

  if (uv__stream_fd(stream) == -1)
    return;

  if (error < 0) {
    uv__stream_flush_write_queue(stream, -ECANCELED);
    uv__write_callbacks(stream);
  }
}

int uv_write2(uv_write_t* req,
              uv_stream_t* stream,
              const uv_buf_t bufs[],
              unsigned int nbufs,
              uv_stream_t* send_handle,
              uv_write_cb cb) {
  int empty_queue;

  assert(nbufs > 0);
  assert((stream->type == UV_TCP ||
          stream->type == UV_NAMED_PIPE ||
          stream->type == UV_TTY) &&
         "uv_write (unix) does not yet support other types of streams");

  if (uv__stream_fd(stream) < 0)
    return -EBADF;

  if (send_handle) {
    if (stream->type != UV_NAMED_PIPE || !((uv_pipe_t*)stream)->ipc)
      return -EINVAL;

    /* XXX We abuse uv_write2() to send over UDP handles to child processes.
     * Don't call uv__stream_fd() on those handles, it's a macro that on OS X
     * evaluates to a function that operates on a uv_stream_t with a couple of
     * OS X specific fields. On other Unices it does (handle)->io_watcher.fd,
     * which works but only by accident.
     */
    if (uv__handle_fd((uv_handle_t*) send_handle) < 0)
      return -EBADF;

#if defined(__CYGWIN__) || defined(__MSYS__)
    /* Cygwin recvmsg always sets msg_controllen to zero, so we cannot send it.
       See https://github.com/mirror/newlib-cygwin/blob/86fc4bf0/winsup/cygwin/fhandler_socket.cc#L1736-L1743 */
    return -ENOSYS;
#endif
  }

  /* It's legal for write_queue_size > 0 even when the write_queue is empty;
   * it means there are error-state requests in the write_completed_queue that
   * will touch up write_queue_size later, see also uv__write_req_finish().
   * We could check that write_queue is empty instead but that implies making
   * a write() syscall when we know that the handle is in error mode.
   */
  empty_queue = (stream->write_queue_size == 0);

  /* Initialize the req */
  uv__req_init(stream->loop, req, UV_WRITE);
  req->cb = cb;
  req->handle = stream;
  req->error = 0;
  req->send_handle = send_handle;
  QUEUE_INIT(&req->queue);

  req->bufs = req->bufsml;
  if (nbufs > ARRAY_SIZE(req->bufsml))
    req->bufs = uv__malloc(nbufs * sizeof(bufs[0]));

  if (req->bufs == NULL)
    return -ENOMEM;

  memcpy(req->bufs, bufs, nbufs * sizeof(bufs[0]));
  req->nbufs = nbufs;
  req->write_index = 0;
  stream->write_queue_size += uv__count_bufs(bufs, nbufs);

  /* Append the request to write_queue. */
  QUEUE_INSERT_TAIL(&stream->write_queue, &req->queue);

  /* If the queue was empty when this function began, we should attempt to
   * do the write immediately. Otherwise start the write_watcher and wait
   * for the fd to become writable.
   */
  if (stream->connect_req) {
    /* Still connecting, do nothing. */
  }
  else if (empty_queue) {
    uv__write(stream);
  }
  else {
    /*
     * blocking streams should never have anything in the queue.
     * if this assert fires then somehow the blocking stream isn't being
     * sufficiently flushed in uv__write.
     */
    assert(!(stream->flags & UV_STREAM_BLOCKING));
    uv__io_start(stream->loop, &stream->io_watcher, POLLOUT);
    uv__stream_osx_interrupt_select(stream);
  }

  return 0;
}

/* The buffers to be written must remain valid until the callback is called.
 * This is not required for the uv_buf_t array.
 */
int uv_write(uv_write_t* req,
             uv_stream_t* handle,
             const uv_buf_t bufs[],
             unsigned int nbufs,
             uv_write_cb cb) {
  return uv_write2(req, handle, bufs, nbufs, NULL, cb);
}

void uv_try_write_cb(uv_write_t* req, int status) {
  /* Should not be called */
  abort();
}

int uv_try_write(uv_stream_t* stream,
                 const uv_buf_t bufs[],
                 unsigned int nbufs) {
  int r;
  int has_pollout;
  size_t written;
  size_t req_size;
  uv_write_t req;

  /* Connecting or already writing some data */
  if (stream->connect_req != NULL || stream->write_queue_size != 0)
    return -EAGAIN;

  has_pollout = uv__io_active(&stream->io_watcher, POLLOUT);

  r = uv_write(&req, stream, bufs, nbufs, uv_try_write_cb);
  if (r != 0)
    return r;

  /* Remove not written bytes from write queue size */
  written = uv__count_bufs(bufs, nbufs);
  if (req.bufs != NULL)
    req_size = uv__write_req_size(&req);
  else
    req_size = 0;
  written -= req_size;
  stream->write_queue_size -= req_size;

  /* Unqueue request, regardless of immediateness */
  QUEUE_REMOVE(&req.queue);
  uv__req_unregister(stream->loop, &req);
  if (req.bufs != req.bufsml)
    uv__free(req.bufs);
  req.bufs = NULL;

  /* Do not poll for writable, if we wasn't before calling this */
  if (!has_pollout) {
    uv__io_stop(stream->loop, &stream->io_watcher, POLLOUT);
    uv__stream_osx_interrupt_select(stream);
  }

  if (written == 0 && req_size != 0)
    return -EAGAIN;
  else
    return written;
}

int uv_read_start(uv_stream_t* stream,
                  uv_alloc_cb alloc_cb,
                  uv_read_cb read_cb) {
  assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE ||
      stream->type == UV_TTY);

  if (stream->flags & UV_CLOSING)
    return -EINVAL;

  /* The UV_STREAM_READING flag is irrelevant of the state of the tcp - it just
   * expresses the desired state of the user.
   */
  stream->flags |= UV_STREAM_READING;

  /* TODO: try to do the read inline? */
  /* TODO: keep track of tcp state. If we've gotten a EOF then we should
   * not start the IO watcher.
   */
  assert(uv__stream_fd(stream) >= 0);
  assert(alloc_cb);

  stream->read_cb = read_cb;
  stream->alloc_cb = alloc_cb;

  uv__io_start(stream->loop, &stream->io_watcher, POLLIN);
  uv__handle_start(stream);
  uv__stream_osx_interrupt_select(stream);

  return 0;
}

int uv_read_stop(uv_stream_t* stream) {
  if (!(stream->flags & UV_STREAM_READING))
    return 0;

  stream->flags &= ~UV_STREAM_READING;
  uv__io_stop(stream->loop, &stream->io_watcher, POLLIN);
  if (!uv__io_active(&stream->io_watcher, POLLOUT))
    uv__handle_stop(stream);
  uv__stream_osx_interrupt_select(stream);

  stream->read_cb = NULL;
  stream->alloc_cb = NULL;
  return 0;
}

int uv_is_readable(const uv_stream_t* stream) {
  return !!(stream->flags & UV_STREAM_READABLE);
}

int uv_is_writable(const uv_stream_t* stream) {
  return !!(stream->flags & UV_STREAM_WRITABLE);
}

#if defined(__APPLE__)
int uv___stream_fd(const uv_stream_t* handle) {
  const uv__stream_select_t* s;

  assert(handle->type == UV_TCP ||
         handle->type == UV_TTY ||
         handle->type == UV_NAMED_PIPE);

  s = handle->select;
  if (s != NULL)
    return s->fd;

  return handle->io_watcher.fd;
}
#endif /* defined(__APPLE__) */

void uv__stream_close(uv_stream_t* handle) {
  unsigned int i;
  uv__stream_queued_fds_t* queued_fds;

#if defined(__APPLE__)
  /* Terminate select loop first */
  if (handle->select != NULL) {
    uv__stream_select_t* s;

    s = handle->select;

    uv_sem_post(&s->close_sem);
    uv_sem_post(&s->async_sem);
    uv__stream_osx_interrupt_select(handle);
    uv_thread_join(&s->thread);
    uv_sem_destroy(&s->close_sem);
    uv_sem_destroy(&s->async_sem);
    uv__close(s->fake_fd);
    uv__close(s->int_fd);
    uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close);

    handle->select = NULL;
  }
#endif /* defined(__APPLE__) */

  uv__io_close(handle->loop, &handle->io_watcher);
  uv_read_stop(handle);
  uv__handle_stop(handle);

  if (handle->io_watcher.fd != -1) {
    /* Don't close stdio file descriptors.  Nothing good comes from it. */
    if (handle->io_watcher.fd > STDERR_FILENO)
      uv__close(handle->io_watcher.fd);
    handle->io_watcher.fd = -1;
  }

  if (handle->accepted_fd != -1) {
    uv__close(handle->accepted_fd);
    handle->accepted_fd = -1;
  }

  /* Close all queued fds */
  if (handle->queued_fds != NULL) {
    queued_fds = handle->queued_fds;
    for (i = 0; i < queued_fds->offset; i++)
      uv__close(queued_fds->fds[i]);
    uv__free(handle->queued_fds);
    handle->queued_fds = NULL;
  }

  assert(!uv__io_active(&handle->io_watcher, POLLIN | POLLOUT));
}

int uv_stream_set_blocking(uv_stream_t* handle, int blocking) {
  /* Don't need to check the file descriptor, uv__nonblock()
   * will fail with EBADF if it's not valid.
   */
  return uv__nonblock(uv__stream_fd(handle), !blocking);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="-1" />

    <title>Native Client PPAPI Post Message Example</title>

Native Client PPAPI Post Message Example

    <embed id="naclModule"
           name="naclModule"
           width=400 height=400
           src="ppapi_example_post_message.nmf"
           basic_tests="2"
           stress_tests="0"
           style="background-color:gray"
           type="application/x-nacl" />


text:
<?php
namespace empire\framework\login\storage;

/**
 * A storage for storing logins.
 *
 * @author Tobias Hornberger [tobias.hornberger@falsemirror.de]
 */
interface LoginStorage {

	/**
	 * Adds a token.
	 *
	 * @param string $gid the GID of the user
	 * @param string $token the token
	 */
	public function addToken($gid, $token);

	/**
	 * Checks whether a token exists.
	 *
	 * @param string $gid the GID of the user
	 * @param string $token the token
	 * @return boolean whether the token exists
	 */
	public function tokenExists($gid, $token);

	/**
	 * Deletes a token.
	 *
	 * @param string $gid the GID of the user
	 * @param string $token the token to delete
	 * @param boolean whether the token existed and has been deleted
	 */
	public function deleteToken($gid, $token);

	/**
	 * Deletes all tokens.
	 *
	 * @param string $gid the GID of the user
	 * @return boolean whether tokens existed for this gid
	 */
	public function deleteAll($gid);

	/**
	 * Removes this storage.
	 *
	 * This method removes all stored login data.
	 */
	public function remove();

}


text:
/******************************************************************************/
/* Files to Include                                                           */
/******************************************************************************/

#ifdef __XC32
#include <xc.h>          /* Defines special function registers, CP0 regs  */
#endif

#include <stdint.h>          /* For uint32_t definition                       */
#include <stdbool.h>         /* For true/false definition                     */
#include "user.h"            /* variables/params used by user.c               */
#include <sys/attribs.h>
#include "ADC.h"

/******************************************************************************/
/* User Functions                                                             */
/******************************************************************************/
void InitTimer2AndOC5(void) {
    // Initialize Timer2. See details in Section 14 (Timers)
    // of the PIC32 Family Reference Manual
    T2CON = 0; // clear timer settings to defaults
    T2CONbits.TCKPS = 7; // divide clock by 256 with prescaler
    TMR2 = 0;  // clear counter to 0
    // Set period for timer using symbol PWM_PERIOD_COUNTS from user.h
    PR2 = PWM_PERIOD_COUNTS - 1;

    // Initialize OC5. See details in Section 16 (Output Compare)
    // of the PIC32 Family Reference Manual. Use Pulse Width Modulation, which
    // is described in Section 16.3.3.
    // Set initial duty cycle to 20%
    OC5R = PWM_PERIOD_COUNTS / 5;
    // Set reload duty cycle to 20%
    OC5RS = PWM_PERIOD_COUNTS / 5;
    // Configure OC5 control register
    OC5CONbits.ON = 1;  // Turn on OC5
    OC5CONbits.OC32 = 0;    // Select 16 bit mode
    OC5CONbits.OCTSEL = 0; // Select timer 2
    OC5CONbits.OCM = 6; // Select PWM mode without fault pin

    // Configure Peripheral Pin Select to connect OC5 output signal to pin G6,
    // which drives LED LD1.
    // See details in Section 12.4 of the PIC32MZ EF Data Manual.
    // There is also general information in Section 12.3.1 of the PIC32 Family
    // Reference Manual.
    RPG6R = 11;

    // Start Timer 2
    T2CONbits.ON = 1;
}

void AdjustLED1Brightness(void) {
    //it is full because interrupt and peripheral units do everything
    valuePot = ReadPotentiometerWithADC();
    int32_t q = (valuePot - valuePotOld);
    if ((q < 10) && (q > -10)) { // defence from noises
        LD4_PORT_BIT = 0;
    }
    else {
        LD4_PORT_BIT = 1;
    }
    valuePotOld = valuePot;
}

void InitGPIO(void) {
    /* Setup functionality and port direction */
    // potentiometer analog input config
    ANSELBbits.ANSB13 = 1;

    // LED output
    // Disable analog mode
    ANSELGbits.ANSG6 = 0;
    ANSELBbits.ANSB11 = 0;
    ANSELGbits.ANSG15 = 0;
    // Set directions to output
    TRISGbits.TRISG6 = 0;
    TRISBbits.TRISB11 = 0;
    TRISGbits.TRISG15 = 0;
    TRISDbits.TRISD4 = 0;

    // Turn off LEDs for initialization
    LD1_PORT_BIT = 0;
    LD2_PORT_BIT = 1;
    LD3_PORT_BIT = 0;
    LD4_PORT_BIT = 0;

    // Button inputs
    // Disable analog mode
    ANSELAbits.ANSA5 = 0;
    // Set directions to input
    TRISAbits.TRISA5 = 1;
    TRISAbits.TRISA4 = 1;

    // 3. Configure peripheral to generate interrupts
    // Enable change notification interrupt in CN
    CNENAbits.CNIEA5 = 1;
    CNENAbits.CNIEA4 = 1;
    // Enable change notification  interrupts
    IEC3bits.CNAIE = 1;
    // Set priority
    IPC29bits.CNAIP = 2;
    // Clear interrupt Flag
    IFS3bits.CNAIF = 0;
    // 5. Set Interrupt Controller for multi-vector mode
    INTCONSET = _INTCON_MVEC_MASK;
    // 6. Globally enable interrupts
    __builtin_enable_interrupts();
    // 7. Enable peripheral
    CNCONAbits.ON = 1;
}

void InitApp(void) {
    // Add code to call functions which initialize peripherals: GPIO, ADC, Timer2, OC5
    InitGPIO();
    initWiFIREadc();
    InitTimer2AndOC5();
}


text:
#ifndef SOPNET_SKELETONS_FIND_INTERIOR_POINTS_H__
#define SOPNET_SKELETONS_FIND_INTERIOR_POINTS_H__

#include <pipeline/SimpleProcessNode.h>
#include <imageprocessing/ImageStack.h>
#include "Spheres.h"

/**
 * Find a set of spheres that approximate the shape of a neuron.
 */
class FindInteriorPoints : public pipeline::SimpleProcessNode<> {

public:

	FindInteriorPoints();

private:

	void updateOutputs();

	pipeline::Input<ImageStack>  _membranes;
	pipeline::Input<double>      _smooth;
	pipeline::Output<Spheres>    _spheres;
	pipeline::Output<ImageStack> _boundaries;
};

#endif // SOPNET_SKELETONS_FIND_INTERIOR_POINTS_H__


text:
package org.zstack.compute.vm;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.header.core.workflow.Flow;
import org.zstack.header.core.workflow.FlowRollback;
import org.zstack.header.core.workflow.FlowTrigger;
import org.zstack.header.core.Completion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.vm.VmInstanceConstant;
import org.zstack.header.vm.VmInstanceDeletionPolicyManager;
import org.zstack.header.vm.VmInstanceSpec;
import org.zstack.header.vm.VmReleaseResourceExtensionPoint;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class VmReleaseResourceFlow implements Flow {
    private static final CLogger logger = Utils.getLogger(VmReleaseResourceFlow.class);

    @Autowired
    private PluginRegistry pluginRgty;

    private static List<VmReleaseResourceExtensionPoint> extensions = null;

    public VmReleaseResourceFlow() {
        if (extensions == null) {
            extensions = pluginRgty.getExtensionList(VmReleaseResourceExtensionPoint.class);
        }
    }

    private void fireExtensions(final Iterator<VmReleaseResourceExtensionPoint> it, final VmInstanceSpec spec, final Map<String, Object> ctx, final FlowTrigger chain) {
        if (!it.hasNext()) {
            chain.next();
            return;
        }

        VmReleaseResourceExtensionPoint ext = it.next();
        ext.releaseVmResource(spec, new Completion(chain) {
            @Override
            public void success() {
                fireExtensions(it, spec, ctx, chain);
            }

            @Override
            public void fail(ErrorCode errorCode) {
                chain.fail(errorCode);
            }
        });
    }

    @Override
    public void run(FlowTrigger chain, Map data) {
        VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());
        fireExtensions(extensions.iterator(), spec, data, chain);
    }

    @Override
    public void rollback(FlowRollback chain, Map data) {
        chain.rollback();
    }
}


text:
<?php

/**
 * ProductOptionType.php
 *
 * @since 16/10/16
 * @author gseidel
 */

namespace Enhavo\Bundle\ShopBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductOptionType extends AbstractType
{
    /**
     * @var string
     */
    private $dataClass;

    public function __construct($dataClass)
    {
        $this->dataClass = $dataClass;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('code', TextType::class);
        $builder->add('values', 'enhavo_list', [
            'type' => 'sylius_product_option_value'
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => $this->dataClass
        ));
    }

    public function getBlockPrefix()
    {
        return 'enhavo_shop_product_option';
    }
}