text:
import os
import sys
import time
import glob
import shelve

from collections import defaultdict

import misopy
import misopy.gff_utils as gff_utils
import misopy.pickle_utils as pickle_utils
import misopy.Gene as gene_utils
import misopy.misc_utils as misc_utils

COMPRESS_PREFIX = misc_utils.COMPRESS_PREFIX

def compress_event_name(event_name,
                        prefix=COMPRESS_PREFIX):
    event_hash = hash(event_name)
    compressed_event_name = "%s_%s" %(prefix, event_hash)
    return compressed_event_name

def serialize_genes(gff_genes,
                    gff_filename,
                    output_dir,
                    compress_id=False):
    """
    Output genes into pickle files by chromosome, by gene.

    If asked, use compressed IDs (hashes) of the 'ID=' field in the GFF.
    """
    genes_by_chrom = defaultdict(dict)

    # Split up genes by chromosome
    for gene_id, gene_info in gff_genes.iteritems():
        gene_obj = gene_info["gene_object"]
        gene_hierarchy = gene_info["hierarchy"]
        genes_by_chrom[gene_obj.chrom][gene_id] = \
            {'gene_object': gene_obj,
             'hierarchy': gene_hierarchy}
        if compress_id:
            gene_compressed_id = compress_event_name(gene_id)
            # Store compressed ID
            genes_by_chrom[gene_obj.chrom][gene_id]['compressed_id'] \
                = gene_compressed_id

    # Mapping from gene IDs to pickled filename
    gene_id_to_filename = {}
    # Mapping from compressed IDs (hashes) to gene IDs
    compressed_id_to_gene_id = {}

    # Serialize all the genes in each chromosome into their
    # own directory
    for chrom, chrom_genes in genes_by_chrom.iteritems():
        if chrom.startswith("chr"):
            chrom_dir_name = chrom
        else:
            # Add chr-prefix for ease of finding directory
            # in downstream steps.
            chrom_dir_name = "chr%s" %(str(chrom))

        # Make directory for chromosome if it doesn't already exist
        chrom_dir = os.path.join(output_dir, chrom_dir_name)
        if not os.path.isdir(chrom_dir):
            #print "Making directory: %s" %(chrom_dir)
            os.makedirs(chrom_dir)

        t1 = time.time()
        # Serialize each gene into a separate file
        num_genes = len(genes_by_chrom[chrom])

        for gene_id, gene_info in genes_by_chrom[chrom].iteritems():
            gene_compressed_id = None
            if compress_id:
                gene_compressed_id = \
                    genes_by_chrom[chrom][gene_id]['compressed_id']
                gene_filename = \
                    os.path.abspath(os.path.join(chrom_dir,
                                                 "%s.pickle" \
                                                 %(gene_compressed_id)))
            else:
                gene_filename = \
                    os.path.abspath(os.path.join(chrom_dir,
                                                 "%s.pickle" %(gene_id)))
            # Write each gene/event's pickle file
            pickle_utils.write_pickled_file({gene_id:
                                             genes_by_chrom[chrom][gene_id]},
                                            gene_filename)
            # Record what filename was associated with this gene ID
            gene_id_to_filename[gene_id] = gene_filename
            # Record compressed ID (hash) to gene ID
            if gene_compressed_id is not None:
                compressed_id_to_gene_id[gene_compressed_id] = gene_id

        t2 = time.time()
        #print "  - Chromosome serialization took %.2f seconds" %(t2 - t1)
        print '.',

    # Shelve the mapping from gene ids to filenames
    shelved_filename = os.path.join(output_dir,
                                    "genes_to_filenames.shelve")
    shelved_data = shelve.open(shelved_filename)
    for k, v in gene_id_to_filename.iteritems():
        shelved_data[k] = v
    shelved_data.close()

    # Shelve the mapping from compressed gene ids to gene ids
    shelved_filename = os.path.join(output_dir,
                                    "compressed_ids_to_genes.shelve")
    shelved_data = shelve.open(shelved_filename)
    for k, v in compressed_id_to_gene_id.iteritems():
        shelved_data[k] = v
    shelved_data.close()

    # Output a list of genes in ordinary GFF format
    genes_filename = os.path.join(output_dir, "genes.gff")
    #print "Outputting gene records in GFF format..."
    #print "  - Output file: %s" %(genes_filename)
    with open(gff_filename) as gff_in:
        with open(genes_filename, "w") as gff_out:
            for line in gff_in:
                if line.startswith("#"): continue
                record_type = line.strip().split("\t")[2]
                if record_type == "gene":
                    gff_out.write(line)

def index_gff(gff_filename, output_dir,
              compress_id=False):
    """
    Index the given GFF and placed the indexed representation
    in the output directory.
    """
    print "Indexing GFF..."
    if compress_id:
        print "  - Using compressed IDs to create indexed filenames."
    # First check that the GFF is not already indexed
    indexed_files = glob.glob(os.path.join(output_dir, "chr*"))
    if len(indexed_files) >= 1:
        print "%s appears to already be indexed. Aborting." \
            %(gff_filename)
        return

    #print "  - GFF: %s" %(gff_filename)
    #print "  - Outputting to: %s" %(output_dir)
    overall_t1 = time.time()
    t1 = time.time()
    gff_genes = gene_utils.load_genes_from_gff(gff_filename)
    t2 = time.time()
    #print "  - Loading of genes from GFF took %.2f seconds" %(t2 - t1)

    t1 = time.time()
    serialize_genes(gff_genes,
                    gff_filename,
                    output_dir,
                    compress_id=compress_id)
    t2 = time.time()
    print " Serialization of genes from GFF took %.2f seconds" %(t2 - t1)
    overall_t2 = time.time()
    print "Indexing of GFF took %.2f seconds." %(overall_t2 - overall_t1)

def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("--index", dest="index_gff", nargs=2, default=None,
                      help="Index the given GFF. Takes as arguments as GFF filename "
                      "and an output directory.")
    parser.add_option("--compress-id", dest="compress_id", default=False,
                      action="store_true",
                      help="Use the compressed version of the GFF \'ID=\' "
                      "field rather than the ID itself when creating "
                      ".miso output filenames.")
    (options, args) = parser.parse_args()

    if options.index_gff != None:
        gff_filename = \
            os.path.abspath(os.path.expanduser(options.index_gff[0]))
        output_dir = \
            os.path.abspath(os.path.expanduser(options.index_gff[1]))

        if not os.path.isdir(output_dir):
            os.makedirs(output_dir)

        index_gff(gff_filename, output_dir,
                  compress_id=options.compress_id)
    else:
        print "Indexer of GFF files for use with MISO."
        print "Need to pass --index, for example:\n"
        print "index_gff --index annotation.gff indexed_annotation/"

if __name__ == '__main__':
    main()


text:
'use strict';
// This test binds to one port, then attempts to start a server on that
// port. It should be EADDRINUSE but be able to then bind to another port.
const common = require('../common');
const assert = require('assert');
const net = require('net');

const server1 = net.Server();

const server2 = net.Server();

server2.on('error', common.mustCall(function(e) {
  assert.strictEqual(e.code, 'EADDRINUSE');

  server2.listen(0, common.mustCall(function() {
    server1.close();
    server2.close();
  }));
}));

server1.listen(0, common.mustCall(function() {
  // This should make server2 emit EADDRINUSE
  server2.listen(this.address().port);
}));

redpajama_set_name: RedPajamaGithub


text:
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.Msie;

namespace FollowTheTask.Web
{
    public class JsEngineSwitcherConfig
    {
        public static void Configure(JsEngineSwitcher engineSwitcher)
        {
            engineSwitcher.EngineFactories
                .AddMsie(new MsieSettings
                {
                    UseEcmaScript5Polyfill = true,
                    UseJson2Library = true
                });

            engineSwitcher.DefaultEngineName = MsieJsEngine.EngineName;
        }
    }
}


text:
package cloud::azure::database::sqlmanagedinstance::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_custom);

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new( package => __PACKAGE__, %options );
    bless $self, $class;

    $self->{version} = '0.1';
    $self->{modes} = {
        'cpu'       => 'cloud::azure::database::sqlmanagedinstance::mode::cpu',
        'discovery' => 'cloud::azure::database::sqlmanagedinstance::mode::discovery',
        'health'    => 'cloud::azure::database::sqlmanagedinstance::mode::health',
        'storage'   => 'cloud::azure::database::sqlmanagedinstance::mode::storage',
        'diskio'    => 'cloud::azure::database::sqlmanagedinstance::mode::diskio'
    };

    $self->{custom_modes}->{azcli} = 'cloud::azure::custom::azcli';
    $self->{custom_modes}->{api} = 'cloud::azure::custom::api';
    return $self;
}

sub init {
    my ($self, %options) = @_;

    $self->{options}->add_options(arguments => {
        'api-version:s'  => { name => 'api_version', default => '2018-01-01' }
    });

    $self->SUPER::init(%options);
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check Microsoft Azure SQL Managed Instance.

=cut


text:
from django.views.generic.simple import direct_to_template
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models import get_model
from django.core.exceptions import ImproperlyConfigured

from subscriptions.models import Episode
from djson.http import JSONResponse
from djson.decorators import login_required
from __init__ import flix
from models import NetflixProfile
from decorators import netflix_account_required
# this should be kept generic
try:
    UserProfile = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
    if UserProfile is None:
        raise ImproperlyConfigured("Your AUTH_PROFILE_MODULE setting doesn't point to a valid model")
    elif not issubclass(UserProfile, NetflixProfile):
        raise ImproperlyConfigured("Your UserProfile class should inherit from %s" % NetflixProfile)
except AttributeError:
    raise ImproperlyConfigured("You must set AUTH_PROFILE_MODULE in your settings.py")

import urllib

@login_required
def login(request):
    next = request.GET.get('next', '')
    return direct_to_template(request, template="flix/login.html", extra_context={'next': next})

@login_required
def ask(request):
    next = request.GET.get('next', '')
    return direct_to_template(request, template="flix/ask.html", extra_context={'next': next})

@login_required
def auth(request):
    "/auth/"
    callback = "http://%s%s" % (Site.objects.get_current().domain, reverse('netflix_oauth_return'))

    try:
        next = request.GET['next']
    except KeyError:
        pass
    else:
        callback += '?%s' % urllib.urlencode({'next': next})

    auth_url, token = flix.get_authorization_url(
        callback=callback,
        )
    request.session['unauthed_token'] = token
    return HttpResponseRedirect(auth_url)

def return_(request, next=None):
    try:
        token = request.session['unauthed_token']
    except KeyError:
        return HttpResponse("No un-authed token")
    if not token.key == request.GET.get('oauth_token', None):
        return HttpResponse("Something went wrong! Tokens do not match")
    user_id, access_token = flix.authorize(token)
    try:
        profile = request.user.get_profile()
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=request.user)

    profile.netflix_authorize(user_id, access_token)

    next = request.GET.get('next', next) or getattr(settings, 'NETFLIX_AFTER_OAUTH_URL', '/')
    return HttpResponseRedirect(next)

@netflix_account_required
def deauthorize(request, blocked=None):
    next = request.GET.get('next') or request.POST.get("next")
    if request.method == "POST":
        request.user.get_profile().netflix_deauthorize()
        url = reverse('netflix_oauth_login')
        if next:
            url += '?%s' % next
        return HttpResponseRedirect(reverse('netflix_oauth_login'))
    else:
        return direct_to_template(request, "flix/deauthorize.html", {"blocked": blocked,
                                                                     "next": next, })

# this should be removed!
@netflix_account_required
def flix_test(request):
    import pprint
    profile = request.user.get_profile()
    recommendations = profile._netflix_request('http://api.netflix.com/users/%s/recommendations' % profile.netflix_id)
    return HttpResponse('
' + pprint.pformat(recommendations, 2) + '
')

@netflix_account_required
def show_queue(request, queue='disc'):
    the_queue = request.user.get_profile().netflix_queue(queue=queue)
    return direct_to_template(request, 'flix/queue.html', {'queue': the_queue,
                                                           'type':queue})

@netflix_account_required
def add_to_queue(request, id=None, queue='disc'):
    # this should be done in a post
    episode = get_object_or_404(Episode, pk=id)
    request.user.get_profile().netflix_add_to_queue(episode)
    if request.method == 'GET':
        return HttpResponseRedirect(reverse('subscriptions'))
    else:
        if request.is_ajax():
            return JSONResponse(True)
        else:
            return HttpResponseRedirect(episode.subscription.get_absolute_url())


text:
ALTER TABLE proxyconfig ADD CONSTRAINT uk_proxyconfig_account_name UNIQUE (account, name);

-- //@UNDO
-- SQL to undo the change goes here.

ALTER TABLE proxyconfig DROP CONSTRAINT IF EXISTS uk_proxyconfig_account_name;


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Rusts of Australia 179 (1906)

#### Original name
Puccinia geranii-pilosi McAlpine, 1906

### Remarks
null


text:
export class Util {
    static query(selector) {
        return document.querySelector(selector) ||
            console.error(selector, "not found");
    }

    static handleEvent(context, e, payload) {
        const type = e.type;
        const id = e.target.id || console.warn(e.target, "target without id");
        const method = `on${id[0].toUpperCase()}${id.split("-")[0].slice(1)}` +
            `${type[0].toUpperCase()}${type.slice(1)}`;

        return method in context ? context[method](e, payload)
            : console.warn(method, "not implemented");
    }

    static getYYYYMMDDfromDate(date) {
        if (!date) {
            return "";
        }

        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");

        return `${year}/${month}/${day}`;
    }

    static formatDate(date) {
        if (!date || !date.toString()) {
            return "";
        }

        return (new Date(date)).toLocaleString("en-US", {
            month: "short",
            day: "2-digit",
            hour12: false,
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit"
        });
    }

    static formatNumber(num, decimals = 0) {
        if (!Number.isFinite(num) || !num.toString()) {
            return "";
        }

        return parseFloat(num).toFixed(decimals);
    }
}


text:
<?php

/* @var $this \yii\web\View */
/* @var $content string */

use backend\assets\AppAsset;
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use common\widgets\Alert;

$controller = Yii::$app->controller;
/** @var $user common\models\User */
$user = Yii::$app->user->getIdentity();

$controller->assetsManager($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">

    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>

<?php $this->beginBody() ?>

        <?php
            if($controller->panelRightControls()) {
                echo $controller->panelRightControls();
            }
        ?>

        <?= Breadcrumbs::widget([
            'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
        ]) ?>

                <?= $content;?>

            <?= Html::img($user->getAvatarUrl())?>

<?= $user->email;?>

        <?= Yii::$app->controller->renderLeftMenu();?>

<?php $this->endBody() ?>

<?php $this->endPage() ?>


text:
package com.amazonaws.util.awsclientgenerator.generators.cpp.glacier;

import com.amazonaws.util.awsclientgenerator.domainmodels.SdkFileEntry;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.ServiceModel;
import com.amazonaws.util.awsclientgenerator.generators.cpp.JsonCppClientGenerator;

import java.util.HashMap;
import java.util.Map;

public class GlacierRestJsonCppClientGenerator extends JsonCppClientGenerator {

    public GlacierRestJsonCppClientGenerator() throws Exception {
        super();
    }

    @Override
    public SdkFileEntry[] generateSourceFiles(ServiceModel serviceModel) throws Exception {

        Map<String, String> customHeaders = new HashMap<>();
        customHeaders.put("x-amz-glacier-version", serviceModel.getMetadata().getApiVersion());
        serviceModel.getMetadata().setAdditionalHeaders(customHeaders);

        return super.generateSourceFiles(serviceModel);
    }
}


text:
A java & arduino tool to measure the force applied in a sensor (FSR).

![Running screenshot](/screenshots/connected_small.png)
## Required Java libraries (included in lib folder)
* **RXTX**, library for serial comunication.
* **JFreeChart**, library for graph drawing.
* **JCommon**, JFreeChart need it for working.
* **JSON-Java**, used for data handling between comunications.

## Installation
You can use the libraries included in *lib* folder or download them (e.g. if libs are outdate).
Necessary rxtxSerial.dll bins are in *res* folder in a zip file.

### Download libraries
* Download RXTX binaries (You can download it from [here](http://rxtx.qbang.org/wiki/index.php/Download)).
* Download JFreeChart & JCommon libraries from its [sourceforge](https://sourceforge.net/projects/jfreechart/files/).
* You can download and compile JSON-Java into jar file, from the original repo, [here](https://github.com/stleary/JSON-java).

### Import & configure
1. When you download the binary package, you have to copy "**rxtxSerial.dll**" file to "*%PROGRAMFILES%\\Java\\jre.x.x_xxx\\bin*".
2. The project was made with eclipse. You have to import with eclipse and then import "**RXTXcomm.jar**" as an external jar file. (Also in RXTX downloaded package)
3. Finally, import the json, JFreeChart & JCommon needed libraries as jar files too.

## Required Hardware
* **Arduino board** (this project was implemented in *Mini Pro*).
* If arduino board doesn't have, an **usb-to-ttl** serial adapter.
* **16x2 LCD** Screen (optionally **LCD-I2C** adapter, less cables, there are two codes for each one).
* **FSR** Sensor (in this project we have used an Interlink 402 round from adafruit).
* Buttons, cables, case, etc...


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/section_pressed" android:state_pressed="true"/>
    <item android:drawable="@color/section_pressed" android:state_enabled="false"/>
    <item android:drawable="@color/section_pressed" android:state_focused="true"/>
    <item android:drawable="@color/section"/>
</selector>


text:
/* jshint node: true */
'use strict';

var Q = require('q'),
    _ = require('busyman'),
    Ziee = require('ziee'),
    debug = require('debug')('zigbee-shepherd:init');

var Coordinator = require('../model/coord'),
    Coordpoint = require('../model/coordpoint');

var init = {};

/*************************************************************************************************/
/*** Public APIs                                                                               ***/
/*************************************************************************************************/
init.setupCoord = function (controller, callback) {
    return controller.checkNvParams().then(function () {
        return init._bootCoordFromApp(controller);
    }).then(function (netInfo) {
        return init._registerDelegators(controller, netInfo);
    }).nodeify(callback);
};

/*************************************************************************************************/
/*** Private APIs                                                                              ***/
/*************************************************************************************************/
init._bootCoordFromApp = function (controller) {
    return controller.querie.coordState().then(function (state) {
        if (state !== 'ZB_COORD' && state !== 0x09) {
            debug('Start the ZNP as a coordinator...');
            return init._startupCoord(controller);
        }
    }).then(function () {
        debug('Now the ZNP is a coordinator.');
        return controller.querie.network();
    }).then(function (netInfo) {
        // netInfo: { state, channel, panId, extPanId, ieeeAddr, nwkAddr }
        controller.setNetInfo(netInfo);
        return netInfo;
    });
};

init._startupCoord = function (controller) {
    var deferred = Q.defer(),
        stateChangeHdlr;

    stateChangeHdlr = function (data) {
        if (data.state === 9) {
            deferred.resolve();
            controller.removeListener('ZDO:stateChangeInd', stateChangeHdlr);
        }
    };

    controller.on('ZDO:stateChangeInd', stateChangeHdlr);
    controller.request('ZDO', 'startupFromApp', { startdelay: 100 });

    return deferred.promise;
};

init._registerDelegators = function (controller, netInfo) {
    var coord = controller.getCoord(),
        dlgInfos =  [
            { profId: 0x0104, epId: 1 }, { profId: 0x0101, epId: 2 }, { profId: 0x0105, epId: 3 },
            { profId: 0x0107, epId: 4 }, { profId: 0x0108, epId: 5 }, { profId: 0x0109, epId: 6 }
        ];

    return controller.simpleDescReq(0, netInfo.ieeeAddr).then(function (devInfo) {
        var deregisterEps = [];

        _.forEach(devInfo.epList, function (epId) {
            if (epId > 10) {
                deregisterEps.push(function () {
                    return controller.request('AF', 'delete', { endpoint: epId }).delay(10).then(function () {
                        debug('Deregister endpoint, epId: %s', epId);
                    });
                });
            }
        });

        if (!deregisterEps.length) {
            return devInfo;
        } else {
            return deregisterEps.reduce(function (soFar, fn) {
                return soFar.then(fn);
            }, Q(0)).then(function () {
                return devInfo;
            });
        }
    }).then(function (devInfo) {
        var registerDlgs = [];

        if (!coord)
            coord = controller._coord = new Coordinator(devInfo);
        else
            coord.endpoints = {};

        _.forEach(dlgInfos, function (dlgInfo) {
            var dlgDesc = { profId: dlgInfo.profId, epId: dlgInfo.epId, devId: 0x0005, inClusterList: [], outClusterList: [] },
                dlgEp = new Coordpoint(coord, dlgDesc, true),
                simpleDesc;

            dlgEp.clusters = new Ziee();
            coord.endpoints[dlgEp.getEpId()] = dlgEp;

            simpleDesc = _.find(devInfo.endpoints, function (ep) {
                return ep.epId === dlgInfo.epId;
            });

            if (!_.isEqual(dlgDesc, simpleDesc)) {
                registerDlgs.push(function () {
                    return controller.registerEp(dlgEp).delay(10).then(function () {
                        debug('Register delegator, epId: %s, profId: %s ', dlgEp.getEpId(), dlgEp.getProfId());
                    });
                });
            }
        });

        return registerDlgs.reduce(function (soFar, fn) {
            return soFar.then(fn);
        }, Q(0));
    }).then(function () {
        return controller.querie.coordInfo().then(function (coordInfo) {
            coord.update(coordInfo);
        });
    });
};

module.exports = init;


text:
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include "compat.h"
#include "io_handler_data.h"
#include "reactor_runner.h"
#include "error.h"
#include "file_utils.h"
#include "inet_addr.h"

#include <cassert>
#include <chrono>
#include <iostream>

extern "C" {
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
}

namespace palo {

ssize_t
IOHandlerData::et_socket_read(int fd, void *vptr, size_t n, int *errnop, bool *eofp) {
    size_t nleft = n;
    ssize_t nread = 0;
    char *ptr = (char *)vptr;
    while (nleft > 0) {
        if ((nread = ::read(fd, ptr, nleft)) < 0) {
            if (errno == EINTR) {
                nread = 0; /* and call read() again */
                continue;
            }
            *errnop = errno;
            if (*errnop == EAGAIN || nleft < n) {
                break;     /* already read something, most likely EAGAIN */
            }
            return -1;   /* other errors and nothing read */
        }
        else if (nread == 0) {
            *eofp = true;
            break;
        }
        nleft -= nread;
        ptr   += nread;
    }
    return n - nleft;
}

ssize_t
IOHandlerData::et_socket_writev(int fd, const iovec *vector, int count, int *errnop) {
    ssize_t nwritten = 0;
    while ((nwritten = writev(fd, vector, count)) <= 0) {
        if (errno == EINTR) {
            nwritten = 0; /* and call write() again */
            continue;
        }
        *errnop = errno;
        return -1;
    }
    return nwritten;
}

bool
IOHandlerData::handle_event(struct epoll_event *event,
                            ClockT::time_point arrival_time) {
    int error = 0;
    bool eof = false;
    try {
        if (event->events & EPOLLOUT) {
            if (handle_write_readiness()) {
                handle_disconnect();
                return true;
            }
        }
        if (event->events & EPOLLIN) {
            size_t nread = 0;
            while (true) {
                if (!m_got_header) {
                    nread = et_socket_read(m_sd, m_message_header_ptr,
                                           m_message_header_remaining, &error, &eof);
                    if (nread == (size_t)-1) {
                        if (errno != ECONNREFUSED) {
                            LOG(ERROR) << "read data from socket failed."
                                << "[socket=" << m_sd << ", "
                                << "remaining_message=" << (int)m_message_header_remaining << ", "
                                << "error=" << strerror(errno) << "]";
                        }
                        else {
                            test_and_set_error(error::COMM_CONNECT_ERROR);
                        }
                        handle_disconnect();
                        return true;
                    }
                    else if (nread < m_message_header_remaining) {
                        m_message_header_remaining -= nread;
                        m_message_header_ptr += nread;
                        if (error == EAGAIN) {
                            break;
                        }
                        error = 0;
                    }
                    else {
                        m_message_header_ptr += nread;
                        handle_message_header(arrival_time);
                    }
                    if (eof) {
                        break;
                    }
                }
                else { // got header
                    nread = et_socket_read(m_sd, m_message_ptr, m_message_remaining,
                                           &error, &eof);
                    if (nread == (size_t)-1) {
                        LOG(ERROR) << "read data from socket failed."
                                   << "[socket=" << m_sd << ", "
                                   << "remaining_message=" << (int)m_message_header_remaining
                                   << "error=" << strerror(errno) << "]";
                        handle_disconnect();
                        return true;
                    }
                    else if (nread < m_message_remaining) {
                        m_message_ptr += nread;
                        m_message_remaining -= nread;
                        if (error == EAGAIN) {
                            break;
                        }
                        error = 0;
                    }
                    else {
                        handle_message_body();
                    }
                    if (eof) {
                        break;
                    }
                }
            }
        }
        if (ReactorFactory::ms_epollet) {
            if (event->events & EPOLLRDHUP) {
                LOG(ERROR) << "received EPOLLRDHUP on socket."
                           << "[socket=" << m_sd << ", "
                           << "addr=" << inet_ntoa(m_addr.sin_addr) << ", "
                           << "port=" << ntohs(m_addr.sin_port) << "]";
                handle_disconnect();
                return true;
            }
        }
        else {
            if (eof) {
                LOG(ERROR) << "received EOF on socket."
                           << "[socket=" << m_sd << ", "
                           << "addr=" << inet_ntoa(m_addr.sin_addr) << ", "
                           << "port=" << ntohs(m_addr.sin_port) << "]";
                handle_disconnect();
                return true;
            }
        }
        if (event->events & EPOLLERR) {
            LOG(ERROR) << "received EPOLLERR on socket."
                       << "[socket=" << m_sd << ", "
                       << "addr=" << inet_ntoa(m_addr.sin_addr) << ", "
                       << "port=" << ntohs(m_addr.sin_port) << "]";
            handle_disconnect();
            return true;
        }
        if (event->events & EPOLLHUP) {
            LOG(ERROR) << "received EPOLLHUP on socket."
                       << "[socket=" << m_sd << ", "
                       << "addr=" << inet_ntoa(m_addr.sin_addr) << ", "
                       << "port=" << ntohs(m_addr.sin_port) << "]";
            handle_disconnect();
            return true;
        }
    }
    catch (palo::Exception &e) {
        LOG(ERROR)  << e ;
        handle_disconnect();
        return true;
    }
    return false;
}

void IOHandlerData::handle_message_header(ClockT::time_point arrival_time) {
    size_t header_len = (size_t)m_message_header[1];
    // check to see if there is any variable length header
    // after the fixed length portion that needs to be read
    if (header_len > (size_t)(m_message_header_ptr - m_message_header)) {
        m_message_header_remaining = header_len - (size_t)(m_message_header_ptr
                                     - m_message_header);
        return;
    }
    m_event = std::make_shared<Event>(Event::MESSAGE, m_addr);
    m_event->load_message_header(m_message_header, header_len);
    m_event->arrival_time = arrival_time;
    m_message_aligned = false;
    if (m_event->header.alignment > 0) {
        void *vptr = 0;
        posix_memalign(&vptr, m_event->header.alignment,
                       m_event->header.total_len - header_len);
        m_message = (uint8_t *)vptr;
        m_message_aligned = true;
    } else {
        m_message = new uint8_t[m_event->header.total_len - header_len];
    }
    m_message_ptr = m_message;
    m_message_remaining = m_event->header.total_len - header_len;
    m_message_header_remaining = 0;
    m_got_header = true;
}

void IOHandlerData::handle_message_body() {
    DispatchHandler *dh {};
    if (m_event->header.flags & CommHeader::FLAGS_BIT_PROXY_MAP_UPDATE) {
        ReactorRunner::handler_map->update_proxy_map((const char *)m_message,
                m_event->header.total_len - m_event->header.header_len);
        free_message_buffer();
        m_event.reset();
    }
    else if ((m_event->header.flags & CommHeader::FLAGS_BIT_REQUEST) == 0 &&
             (m_event->header.id == 0
              || !m_reactor->remove_request(m_event->header.id, dh))) {
        if ((m_event->header.flags & CommHeader::FLAGS_BIT_IGNORE_RESPONSE) == 0) {
            LOG(WARNING) << "received response for non-pending event."
                         << "[request_id=" << m_event->header.id << ", "
                         << "header_version=" << m_event->header.version << ", "
                         << "total_len=" << m_event->header.total_len << "]";
        }
        free_message_buffer();
        m_event.reset();
    }
    else {
        m_event->payload = m_message;
        m_event->payload_len = m_event->header.total_len
                               - m_event->header.header_len;
        m_event->payload_aligned = m_message_aligned;
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            m_event->set_proxy(m_proxy);
        }
        deliver_event(m_event, dh);
    }
    reset_incoming_message_state();
}

void IOHandlerData::handle_disconnect() {
    ReactorRunner::handler_map->decomission_handler(this);
}

bool IOHandlerData::handle_write_readiness() {
    bool deliver_conn_estab_event = false;
    bool rval = true;
    int error = error::OK;
    while (true) {
        std::lock_guard<std::mutex> lock(m_mutex);
        if (m_connected == false) {
            socklen_t name_len = sizeof(m_local_addr);
            int sockerr = 0;
            socklen_t sockerr_len = sizeof(sockerr);
            if (getsockopt(m_sd, SOL_SOCKET, SO_ERROR, &sockerr, &sockerr_len) < 0) {
                LOG(ERROR) << "get SO_ERROR socket option failed."
                           << "[error=" << strerror(errno) << "]";
            }
            if (sockerr) {
                LOG(ERROR) << "connect completion error."
                           << "[error=" << strerror(sockerr) << "]";
                break;
            }
            int bufsize = 4*32768;
            if (setsockopt(m_sd, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize,
                           sizeof(bufsize)) < 0) {
                LOG(ERROR) << "set SO_SNDBUF socket failed."
                           << "[error=" << strerror(errno) << "]";
            }
            if (setsockopt(m_sd, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize,
                           sizeof(bufsize)) < 0) {
                LOG(ERROR) << "set SO_RCVBUF socket option failed."
                           << "[error=" << strerror(errno) << "]";
            }
            int one = 1;
            if (setsockopt(m_sd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)) < 0) {
                LOG(ERROR) << "set SO_KEEPALIVE socket option failed."
                           << "[error=" << strerror(errno) << "]";
            }
            if (getsockname(m_sd, (struct sockaddr *)&m_local_addr, &name_len) < 0) {
                LOG(ERROR) << "get socket name failed."
                           << "[socket=" << m_sd << ", "
                           << "error=" << strerror(errno) << "]";
                break;
            }
            //LOG(INFO) << "Connection established.";
            m_connected = true;
            deliver_conn_estab_event = true;
        }
        //LOG(INFO) << "about to flush send queue";
        if ((error = flush_send_queue()) != error::OK) {
            LOG(ERROR) << "flush send queue failed.";
            if (m_error == error::OK)
                m_error = error;
            return true;
        }
        //LOG(INFO) << "about to remove poll interest";
        if (m_send_queue.empty()) {
            if ((error = remove_epoll_interest(poll_event::WRITE)) != error::OK) {
                if (m_error == error::OK)
                    m_error = error;
                return true;
            }
        }
        rval = false;
        break;
    }
    if (deliver_conn_estab_event) {
        if (ReactorFactory::proxy_master) {
            if ((error = ReactorRunner::handler_map->propagate_proxy_map(this))
                    != error::OK) {
                LOG(ERROR) << "Problem sending proxy map to %s - %s"
                           << m_addr.format().c_str() << error::get_text(error);
                return true;
            }
        }
        EventPtr event = std::make_shared<Event>(Event::CONNECTION_ESTABLISHED, m_addr,
                         m_proxy, error::OK);
        deliver_event(event);
    }
    return rval;
}

int
IOHandlerData::send_message(CommBufPtr &cbp, uint32_t timeout_ms,
                            DispatchHandler *disp_handler) {
    std::lock_guard<std::mutex> lock(m_mutex);
    bool initially_empty = m_send_queue.empty() ? true : false;
    int error = error::OK;
    if (m_decomissioned)
        return error::COMM_NOT_CONNECTED;
    // If request, Add message ID to request cache
    if (cbp->header.id != 0 && disp_handler != 0
            && cbp->header.flags & CommHeader::FLAGS_BIT_REQUEST) {
        auto expire_time = ClockT::now() + std::chrono::milliseconds(timeout_ms);
        m_reactor->add_request(cbp->header.id, this, disp_handler, expire_time);
    }
    //LOG(INFO) << "About to send message of size %d", cbp->header.total_len;
    m_send_queue.push_back(cbp);
    if (m_connected) {
        if ((error = flush_send_queue()) != error::OK) {
            LOG(ERROR) << "flush send queue failed."
                       << "[error=" << error::get_text(error) << "]";
            ReactorRunner::handler_map->decomission_handler(this);
            if (m_error == error::OK) {
                m_error = error;
            }
            return error;
        }
    }
    if (initially_empty && !m_send_queue.empty()) {
        error = add_epoll_interest(poll_event::WRITE);
        if (error) {
            LOG(ERROR) << "add write interest failed. [error=" << (unsigned)error << "]";
        }
    }
    else if (!initially_empty && m_send_queue.empty()) {
        error = remove_epoll_interest(poll_event::WRITE);
        if (error) {
            LOG(ERROR) << "remove write interest failed. [error=" << (unsigned)error << "]";
        }
    }
    // Set m_error if not already set
    if (error != error::OK && m_error == error::OK) {
        m_error = error;
    }
    return error;
}

int IOHandlerData::flush_send_queue() {
    ssize_t nwritten = 0;
    ssize_t towrite = 0;
    ssize_t remaining = 0;
    struct iovec vec[2];
    int count = 0;
    int error = 0;
    while (!m_send_queue.empty()) {
        CommBufPtr &cbp = m_send_queue.front();
        count = 0;
        towrite = 0;
        remaining = cbp->data.size - (cbp->data_ptr - cbp->data.base);
        if (remaining > 0) {
            vec[0].iov_base = (void *)cbp->data_ptr;
            vec[0].iov_len = remaining;
            towrite = remaining;
            ++count;
        }
        if (cbp->ext.base != 0) {
            remaining = cbp->ext.size - (cbp->ext_ptr - cbp->ext.base);
            if (remaining > 0) {
                vec[count].iov_base = (void *)cbp->ext_ptr;
                vec[count].iov_len = remaining;
                towrite += remaining;
                ++count;
            }
        }
        nwritten = et_socket_writev(m_sd, vec, count, &error);
        if (nwritten == (ssize_t)-1) {
            if (error == EAGAIN)
                return error::OK;
            LOG(ERROR) << "write socket failed."
                       << "[socket=" << m_sd << ", "
                       << "towrite=" << (int)towrite << ", "
                       << "error=" << strerror(errno) << "]";
            return error::COMM_BROKEN_CONNECTION;
        }
        else if (nwritten < towrite) {
            if (nwritten == 0) {
                if (error == EAGAIN)
                    break;
                if (error) {
                    LOG(ERROR) << "write socket failed."
                               << "[socket=" << m_sd << ", "
                               << "towrite=" << (int)towrite << ", "
                               << "error=" << strerror(errno) << "]";
                    return error::COMM_BROKEN_CONNECTION;
                }
                continue;
            }
            remaining = cbp->data.size - (cbp->data_ptr - cbp->data.base);
            if (remaining > 0) {
                if (nwritten < remaining) {
                    cbp->data_ptr += nwritten;
                    if (error == EAGAIN) {
                        break;
                    }
                    error = 0;
                    continue;
                }
                else {
                    nwritten -= remaining;
                    cbp->data_ptr += remaining;
                }
            }
            if (cbp->ext.base != 0) {
                cbp->ext_ptr += nwritten;
                if (error == EAGAIN) {
                    break;
                }
                error = 0;
                continue;
            }
        }
        // buffer written successfully, now remove from queue (destroys buffer)
        m_send_queue.pop_front();
    }
    return error::OK;
}

} //namespace palo


text:
from zope.interface import Interface, Attribute, implementer
from crow2.util import AttrDict
import functools
import types
from twisted.python.reflect import namedAny
from twisted.python import log
from collections import defaultdict
from crow2.util import paramdecorator
from .util import topological_sort
from .exceptions import (NameResolutionError, NotRegisteredError, DuplicateRegistrationError,
        InvalidOrderRequirementsError, DependencyMissingError)

class IRegistrationContainer(Interface):
    """
    A container that can be sorted by Hook's dependency sort and then resolved to some handlers
    """
    targets = Attribute("a set of all targets contained")
    before = Attribute("an iterable of all things this should be before")
    after = Attribute("an iterable of all things this should be after")

@implementer(IRegistrationContainer)
class SingleRegistration(object):
    """
    Container for a single registration
    """
    _is_taggroup = False
    def __init__(self, target, before, after):
        self.target = target
        self.before = before
        self.after = after

    @property
    def targets(self):
        """
        Returns a list of
        """
        return set((self.target,))

    def __repr__(self):
        return "SingleRegistration(%r)" % self.target

class TagDict(dict):
    """
    Defaultdict-like dict which creates a TaggedGroup with the context of the dict and key.
    Oh, and it automatically saves the key if it's referenced at all, too.
    """
    def __missing__(self, key):
        value = TaggedGroup(key, self)
        self[key] = value
        return value

@implementer(IRegistrationContainer)
class TaggedGroup(object):
    """
    Container for a group of registrations tagged with a name
    """
    _is_taggroup = True
    def __init__(self, name, parent):
        self.name = name
        self._parent = parent
        self.before = ()
        self.after = ()
        self.targets = set()

    def add(self, target):
        "add a target handler"
        self.targets.add(target)

    def remove(self, target):
        "remove a target handler"
        self.targets.remove(target)

    def dependencies(self, before, after):
        """
        set the dependencies, overwriting any that may have been there before
        """
        #TODO: this needs to assert that there were none there before
        self.before = tuple(set(before) | set(self.before))
        self.after = tuple(set(after) | set(self.after))

    def __repr__(self):
        return "<Tag:%s>" % self.name # pragma: no cover

class IHook(Interface):
    def register(target, **keywords):
        """
        Register a callable to be called by this hook.
        The callable must take at least one argument and
        have no more than one required arguments.
        """
    def register_once(target, **keywords):
        """
        Register a callable to be called by this hook and then unregistered
        """
    def unregister(target):
        """
        Unregister a callable from this hook
        """
    def fire(*contexts, **arguments):
        """
        Call all handlers associated with this hook.
        Each positional argument must be a dictionary; each
        keyword argument is added to any dictionaries to form the
        event passed into the handlers.
        """

class IDecoratorHook(IHook): # pragma: no cover
    def __call__(**keywords):
        "Create an IPartialHook for register()"

    def once(**keywords):
        "Create a partial for register_once()"

class IPartialRegistration(Interface):
    func = Attribute("the method-function which this partial is for")
    args = Attribute("the list of arguments passed to create partial. 0 is self.")
    def __call__(target):
        """
        Complete registration with this target
        """
    def copy():
        "Return a full copy of this partial"

@implementer(IHook)
class BaseHook(object):
    """
    Contains the registration methods that are called to register a hook

    To create a hook, simply instantiate this class. if you want to customize your hook, subclass this class.
    It's designed to be highly subclassable. Be sure to read all the docs and preferably a large amount of the code
    before you start subclassing; a lot is already provided.
    """
    def __init__(self, default_tags=(), stop_exceptions=False, name=None):
        self.sorted_call_list = None
        self.handler_references = {}
        self.references = {}
        self.referencenames = {}
        self.registration_groups = set()
        self.tags = TagDict()
        self.stop_exceptions = stop_exceptions

        self._name = name

        lasttag = ()
        for tagname in default_tags:
            self.tags[tagname].dependencies((), lasttag)
            lasttag = (self.tags[tagname],)

        self._toposort = []

    ### Firing ------------------------------------------

    def fire(self, *args, **keywords):
        """
        Fire the hook. Ensures call list is sorted and calls everything.
        """

        if self.sorted_call_list == None:
            self._toposort, self.sorted_call_list = self._build_call_list(self.registration_groups)
        event = self._make_eventobj(*args, **keywords)
        self._fire_call_list(self.sorted_call_list, event)

        return event

    def _make_eventobj(self, *dicts, **keywords):
        """
        Prepare the objects which will be passed into handlers
        """
        event = AttrDict()
        for context_dict in dicts:
            event.update(context_dict)
        event.update(keywords)
        event.update({"calling_hook": self})
        return event

    def _fire_call_list(self, calllist, event):
        """
        actually call all the handlers in our call list
        """
        for handler in calllist:
            try:
                handler(event)
            except:
                if self.stop_exceptions:
                    log.err()
                else:
                    raise

    ### Baking/fire preparation -------------------------

    def _get_name(self, obj):
        """
        Attempt to determine what an object's fully qualified name is. If we can't find one,
        NameResolutionError is raised.
        """
        cachename = '_crow2events_fully_qualified_name_'

        try:
            result = getattr(obj, cachename)
        except AttributeError:
            pass

        if type(obj) == types.MethodType:
            return '.'.join((obj.__module__, obj.im_class.__name__, obj.__name__))
        elif type(obj) in (type, types.ClassType, types.FunctionType):
            result = obj.__module__ + "." + obj.__name__
        elif type(obj) == types.ModuleType:
            result = obj.__name__
        else:
            # should give a best effort before erroring
            raise NameResolutionError("cannot determine full qualified name for type %r" % type(obj))
        try:
            resolved_obj = namedAny(result)
        except AttributeError:
            pass
        else:
            if resolved_obj is not obj:
                log.msg("WARNING: name resolved to different object: %r -> %r -> %r" % # pragma: no cover
                        (obj, result, resolved_obj))
        try:
            setattr(obj, cachename, result)
        except AttributeError: # shouldn't normally happen, so: pragma: no cover
            pass # cannot cache
        return result

    def _lookup_strdep(self, node, dep):
        """
        Search the things this hook knows about for a string representing a dependency

        checks:

        0. check if it's explicitly a tag; if so, skip 1 and 2
        1. Check to see if we know about anything from the same file which matches
        2. Check to see if we know about anything from a neighboring file which matches
        3. Check to see if we have a tag by the name
        4. error
        """
        if not node._is_taggroup and not dep.startswith(":"):
            # relative/local
            depsplit = dep.split(".")
            namesplit = self._get_name(node.target).split(".")
            for steps_up in (1, 2):
                relative_dep = ".".join(namesplit[:-steps_up] + depsplit)
                try:
                    return self.referencenames[relative_dep]
                except KeyError:
                    pass

            # absolute
            try:
                return self.referencenames[dep]
            except KeyError:
                pass

        if dep.startswith(":"): # starting a dependency with a colon ensures that it refers to a tag
            tag_dep = dep[1:]
        else:
            tag_dep = dep

        if tag_dep in self.tags: # don't want to create it if missing!
            return self.tags[tag_dep]

        raise DependencyMissingError(self, dep, node)

    def _resolve_dep(self, node, dep):
        """
        Resolve a dependency

        1. if it's a string reference, look it up
        2. if we have any known proxies for the found object, use those instead of the object itself
        """
        if type(dep) == str:
            registration = self._lookup_strdep(node, dep)
        elif hasattr(dep, "_is_taggroup"):
            return dep
        else:
            handler = self.references[dep]
            registration = self.handler_references[handler]
        return registration

    def _build_call_list(self, registrations):
        """
        Sort the call list by dependencies and expand each registration group's targets
        """
        # todo: expansion handling
        deptree = defaultdict(set)
        for reg_group in registrations:
            dependencies = deptree[reg_group]

            for dep in reg_group.after:
                dep = self._resolve_dep(reg_group, dep)
                dependencies.add(dep)

            for dep in reg_group.before:
                dep = self._resolve_dep(reg_group, dep)
                deptree[dep].add(reg_group)

        toposorted = topological_sort(deptree)
        result = []
        for reg_group in toposorted:
            result.extend(reg_group.targets)
        return toposorted, tuple(result)

    ### Registration ------------------------------------
    def _ensure_list(self, deplist):
        """
        wrap provided argument in a list if it isn't already one.
        """
        if type(deplist) not in (list, tuple, set):
            return (deplist,)
        else:
            return tuple(deplist)

    def register(self, func, **keywords):
        """
        Register an object as a handler, with any keywords you might like
        """
        # Note: keywords.get is used because register(func, "name") would be ambiguous
        before = self._ensure_list(keywords.get("before", tuple()))
        after = self._ensure_list(keywords.get("after", tuple()))
        tag = keywords.get("tag", None)

        if tag and (len(before) or len(after)):
            raise InvalidOrderRequirementsError(func, self)

        try:
            references = func._proxy_for
        except AttributeError:
            references = [func]
        for reference in references:
            if reference in self.references:
                raise DuplicateRegistrationError("%r (%r) registered twice to hook %r" %
                        (reference, func, self))

        if tag:
            self.tags[tag].add(func)
            self.handler_references[func] = self.tags[tag]
        else:
            registration = SingleRegistration(func, before, after)
            self.handler_references[func] = registration

        for reference in references:
            self.references[reference] = func
            try:
                self.referencenames[self._get_name(reference)] = self.handler_references[func]
            except NameResolutionError:
                log.msg("WARNING: unable to determine name of object %r (%s, %r, %r)" %
                            (reference, str(reference), type(reference), dir(reference)))

        self.registration_groups.add(self.handler_references[func])

        self.sorted_call_list = None # need to recalculate

        return func

    def register_once(self, func, *reg_args, **reg_keywords):
        """
        Register a handler to be called once
        """
        #TODO: ensure that unregistration works if someone tries to unregister a register_once'd handler
        @functools.wraps(func)
        def unregister_callback(*call_args, **call_keywords):
            "this docstring to shut pylint up - nobody will ever see it except reading the code itself"
            try:
                return func(*call_args, **call_keywords)
            finally:
                self.unregister(unregister_callback)
        self.register(unregister_callback, *reg_args, **reg_keywords)
        return func

    def unregister(self, func):
        """
        Unregister a handler
        """
        try:
            references = func._proxy_for
        except AttributeError:
            references = [func]
        for reference in references:
            if reference not in self.references:
                raise NotRegisteredError("%r: cannot unregister %r (%r) as it is not registered" %
                        (self, reference, func))
        for reference in references:
            del self.references[reference]
            try:
                del self.referencenames[self._get_name(reference)]
            except NameResolutionError:
                log.msg("WARNING: unable to determine name of object %r (%s, %r, %r)" %
                            (reference, str(reference), type(reference), dir(reference)))

        registration = self.handler_references[func]
        del self.handler_references[func]
        if registration._is_taggroup:
            registration.remove(func)
        else:
            self.registration_groups.remove(registration)

        self.sorted_call_list = None

    def tag(self, tagname, before=(), after=()):
        before = self._ensure_list(before)
        after = self._ensure_list(after)

        tag = self.tags[tagname]

        tag.dependencies(before, after)
        self.sorted_call_list = None # need to recalculate

    def __repr__(self):
        if self._name is not None:
            return "<%s %s>" % (type(self).__name__, self._name)
        else:
            return object.__repr__(self)

class DecoratorMixin(object):
    @paramdecorator(partialiface=IPartialRegistration)
    def __call__(self, func, *args, **keywords):
        """
        Decorator version of register()
        """
        return self.register(func, *args, **keywords)

@implementer(IDecoratorHook)
class Hook(BaseHook, DecoratorMixin):
    pass

class _CancellerAttrDict(AttrDict):
    def cancel(self):
        self.cancelled = True

class CancellableHook(Hook):
    def _make_eventobj(self, *dicts, **keywords):
        event = _CancellerAttrDict(super(CancellableHook, self)._make_eventobj(*dicts, **keywords))
        event.cancelled = False
        return event

    def _fire_call_list(self, calllist, event):
        for handler in calllist:
            try:
                handler(event)
            except:
                if self.stop_exceptions:
                    log.err()
                else:
                    raise
            if event.cancelled:
                break


text:
using UnityEngine;

/// <summary>
/// Responsible for drawing the selected weapon loadout
/// </summary>
public class GuiSelectedLoadout:MonoBehaviour
{

}


text:
<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Mail\Struct\InviteTest;

/**
 * Testcase class for InviteTest.
 */
class InviteTestTest extends ZimbraMailTestCase
{
    public function testInviteTest()
    {
        $index = mt_rand(1, 10);
        $method1 = $this->faker->word;
        $method2 = $this->faker->word;

        $inviteTest = new InviteTest(
            $index, [$method1], true
        );
        $this->assertInstanceOf('\Zimbra\Mail\Struct\FilterTest', $inviteTest);
        $this->assertSame([$method1], $inviteTest->getMethods()->all());
        $inviteTest->addMethod($method2);
        $this->assertSame([$method1, $method2], $inviteTest->getMethods()->all());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<inviteTest index="' . $index . '" negative="true">'
                .'<method>' . $method1 . '</method>'
                .'<method>' . $method2 . '</method>'
            .'</inviteTest>';
        $this->assertXmlStringEqualsXmlString($xml, (string) $inviteTest);

        $array = array(
            'inviteTest' => array(
                'index' => $index,
                'negative' => true,
                'method' => array(
                    $method1,
                    $method2,
                ),
            ),
        );
        $this->assertEquals($array, $inviteTest->toArray());
    }
}


text:
/**
Generic Backbone View for a button
*/
module.exports = Backbone.View.extend({
    tagName: 'button',
    className: 'btn',
    initialize: function(opts) {
        opts = opts || {};
        this.text = opts.text || '';
        this.onClick = opts.onClick || function() {};
        this.css = opts.css || {};
    },
    render: function() {
        // Create a new icon using the Bootstrap Glyphicons set, to display
        // in the button
        var icon = $('<i>').addClass('glyphicon glyphicon-' + this.icon);
        // Set any CSS classes
        this.setClasses();
        // Add the icon and the text label to the button
        this.$el.append(icon).append(' ' + this.text);

        this.$el.css(this.css);
        // Return a reference to this view for method chaining
        return this;
    },
    events: {
        'click': 'click'
    },
    /**
    Called when the user clicks on the button
    */
    click: function (e) {
        e.preventDefault();
        this.onClick();
    }
});


text:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace BusinessAccounting.Converters
{
    [ValueConversion(typeof(string), typeof(Visibility))]
    public class NullToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null ? Visibility.Collapsed : Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


text:
// Type definitions for mongoose-paginate 5.0.0
// Project: https://github.com/edwardhotchkiss/mongoose-paginate
// Definitions by: Linus Brolin <https://github.com/linusbrolin>, simonxca <https://github.com/simonxca>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0

/// <reference types="mongoose" />

declare module 'mongoose' {
  export interface PaginateOptions {
    select?: Object | string;
    sort?: Object | string;
    populate?:
      | Array<Object>
      | Array<string>
      | Object
      | string
      | QueryPopulateOptions;
    lean?: boolean;
    leanWithId?: boolean;
    offset?: number;
    page?: number;
    limit?: number;
  }

  interface QueryPopulateOptions {
    /** space delimited path(s) to populate */
    path: string;
    /** optional fields to select */
    select?: any;
    /** optional query conditions to match */
    match?: any;
    /** optional model to use for population */
    model?: string | Model<any>;
    /** optional query options like sort, limit, etc */
    options?: any;
    /** deep populate */
    populate?: QueryPopulateOptions | QueryPopulateOptions[];
  }

  export interface PaginateResult<T> {
    docs: Array<T>;
    total: number;
    limit: number;
    page?: number;
    pages?: number;
    offset?: number;
  }

  interface PaginateModel<T extends Document> extends Model<T> {
    paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult<T>) => void): Promise<PaginateResult<T>>;
  }

  export function model<T extends Document>(
    name: string,
    schema?: Schema,
    collection?: string,
    skipInit?: boolean): PaginateModel<T>;

  export function model<T extends Document, U extends PaginateModel<T>>(
    name: string,
    schema?: Schema,
    collection?: string,
    skipInit?: boolean): U;
}

declare module 'mongoose-paginate' {
  import mongoose = require('mongoose');
  var _: (schema: mongoose.Schema) => void;
  export = _;
}


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jitsi.impl.neomedia.rtp.remotebitrateestimator;

/**
 * webrtc/webrtc/modules/remote_bitrate_estimator/include/bwe_defines.h
 *
 * @author Lyubomir Marinov
 */
public enum RateControlRegion
{
    kRcNearMax,
    kRcAboveMax,
    kRcMaxUnknown
}


text:
require File.expand_path('../spec_helper', File.dirname(__FILE__))

RSpec.describe Resque::Job do
  before(:example) do
    Resque.redis.redis.flushall
  end

  it "should repush restriction queue when reserve" do
    Resque.push('restriction_normal', :class => 'OneHourRestrictionJob', :args => ['any args'])
    expect(Resque::Job.reserve('restriction_normal')).to eq Resque::Job.new('restriction_normal', {'class' => 'OneHourRestrictionJob', 'args' => ['any args']})
    expect(Resque::Job.reserve('restriction_normal')).to be_nil
    expect(Resque::Job.reserve('normal')).to be_nil
  end

  it "should push back to restriction queue when still restricted" do
    Resque.redis.set(OneHourRestrictionJob.redis_key(:per_hour), -1)
    Resque.push('restriction_normal', :class => 'OneHourRestrictionJob', :args => ['any args'])
    expect(Resque::Job.reserve('restriction_normal')).to be_nil
    expect(Resque.pop('restriction_normal')).to eq({'class' => 'OneHourRestrictionJob', 'args' => ['any args']})
    expect(Resque::Job.reserve('normal')).to be_nil
  end

  it "should not repush when reserve normal queue" do
    Resque.push('normal', :class => 'OneHourRestrictionJob', :args => ['any args'])
    expect(Resque::Job.reserve('normal')).to eq Resque::Job.new('normal', {'class' => 'OneHourRestrictionJob', 'args' => ['any args']})
    expect(Resque::Job.reserve('normal')).to be_nil
    expect(Resque::Job.reserve('restriction_normal')).to be_nil
  end

  it "should only push back queue_length times to restriction queue" do
    Resque.redis.set(OneHourRestrictionJob.redis_key(:per_hour), -1)
    3.times { Resque.push('restriction_normal', :class => 'OneHourRestrictionJob', :args => ['any args']) }
    expect(Resque.size('restriction_normal')).to eq 3
    expect(OneHourRestrictionJob).to receive(:repush).exactly(3).times.and_return(true)
    Resque::Job.reserve('restriction_normal')
  end
end


text:
#if !defined (MQ_SENSORS_H)
#define   MQ_SENSORS_H

/*-------------------------------------------------------------------------------------------------*\
 |    I N C L U D E   F I L E S
\*-------------------------------------------------------------------------------------------------*/
/* This file is meant to provide a common definition of sensor related enumerations/defines and
 * generally should not depend on any other includes
 */

/*-------------------------------------------------------------------------------------------------*\
 |    C O N S T A N T S   &   M A C R O S
\*-------------------------------------------------------------------------------------------------*/
#define SENSOR_SUBTYPE_UNUSED               0   //!< Subtype is not used for the sensor type
#define SENSOR_SUBTYPE_START                1   //!< Subtype enumeration starts with 1
#define SENSOR_DEVICE_PRIVATE_BASE          0x10000 //!< Android defined private sensor type base

#define M_PSensorToAndroidBase(type)        ((type) | SENSOR_DEVICE_PRIVATE_BASE)

/*-------------------------------------------------------------------------------------------------*\
 |    T Y P E   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/
//! use to specify the kind of sensor input or output
/*!
 * \sa OSP_RegisterInputSensor
 * \sa OSP_SubscribeOutputSensor
 *
 *  Final units of input/outputs are defined by the sensor data convention field of the sensor descriptor.
 *  Flags in the descriptor specify if sensor is calibrated/uncalibrated and/or used as input
 *  If a sensor type not is supported by the library implementation, an error will be returned on its usage
 */
/* Android sensor types - this should match the defines/enumeration in Android's sensors.h */
/* Note that these are defined as SENSOR_ instead of SENSOR_TYPE_ to avoid clash with Android defines in
 * situations where this header in included for packet processing in Sensor HAL
 */
typedef enum _ASensorType {
    SENSOR_META_DATA                        = 0,
    SENSOR_ACCELEROMETER                    = 1,
    SENSOR_GEOMAGNETIC_FIELD                = 2,
    SENSOR_MAGNETIC_FIELD                   = SENSOR_GEOMAGNETIC_FIELD,
    SENSOR_ORIENTATION                      = 3,
    SENSOR_GYROSCOPE                        = 4,
    SENSOR_LIGHT                            = 5,
    SENSOR_PRESSURE                         = 6,
    SENSOR_TEMPERATURE                      = 7,
    SENSOR_PROXIMITY                        = 8,
    SENSOR_GRAVITY                          = 9,
    SENSOR_LINEAR_ACCELERATION              = 10,
    SENSOR_ROTATION_VECTOR                  = 11,
    SENSOR_RELATIVE_HUMIDITY                = 12,
    SENSOR_AMBIENT_TEMPERATURE              = 13,
    SENSOR_MAGNETIC_FIELD_UNCALIBRATED      = 14,
    SENSOR_GAME_ROTATION_VECTOR             = 15,
    SENSOR_GYROSCOPE_UNCALIBRATED           = 16,
    SENSOR_SIGNIFICANT_MOTION               = 17,
    SENSOR_STEP_DETECTOR                    = 18,
    SENSOR_STEP_COUNTER                     = 19,
    SENSOR_GEOMAGNETIC_ROTATION_VECTOR      = 20,

    NUM_ANDROID_SENSOR_TYPE                      //!< Total number of Android sensor type
} ASensorType_t;

/* Private Sensor types (translates to Android SENSOR_TYPE_DEVICE_PRIVATE_BASE start) */
typedef enum _PSensorType {
    PSENSOR_ENUM_FIRST_SENSOR                =  0,

    PSENSOR_DEBUG_TUNNEL                     =  PSENSOR_ENUM_FIRST_SENSOR, //!< Debug message pipe to host
    PSENSOR_ACCELEROMETER_RAW                =  1, //!< raw accelerometer data (direct from sensor)
    PSENSOR_MAGNETIC_FIELD_RAW               =  2, //!< magnetometer data (direct from sensor)
    PSENSOR_GYROSCOPE_RAW                    =  3, //!< calibrated gyroscope data (direct from sensor)
    PSENSOR_LIGHT_UV                         =  4, //!< UV light sensor data (Android Units)
    PSENSOR_LIGHT_RGB                        =  5, //!< RGB light sensor data (Android Units)
    PSENSOR_STEP                             =  6, //!< step data
    PSENSOR_ACCELEROMETER_UNCALIBRATED       =  7, //!< uncalibrated accelerometer data (Android Units)
    PSENSOR_ORIENTATION                      =  8, //!< yaw, pitch, roll (also use this for Win8 Inclinometer)
    PSENSOR_CONTEXT_DEVICE_MOTION            =  9, //!< context of device relative to world frame
    PSENSOR_CONTEXT_CARRY                    = 10, //!< context of device relative to user
    PSENSOR_CONTEXT_POSTURE                  = 11, //!< context of user relative to world frame
    PSENSOR_CONTEXT_TRANSPORT                = 12, //!< context of environment relative to world frame
    PSENSOR_GESTURE_EVENT                    = 13, //!< gesture event such as a double-tap or shake
    PSENSOR_HEART_RATE                       = 15, //!< heart-rate data
    SYSTEM_REAL_TIME_CLOCK                   = 16, //!< Real time clock used for time stamp

    NUM_PRIVATE_SENSOR_TYPE                        //!< Total number of Private sensor type
} PSensorType_t;

/* Sensor Parameter Identifiers */
typedef enum _SensorParamId {
    SENSOR_PARAM_ERROR_CODE                 = 0, //!< Used to convey error code instead of parameter value
    SENSOR_PARAM_OFFSET                     = 1, //!< Offset or bias of a sensor
    SENSOR_PARAM_DATA_RATE                  = 2, //!< Datarate for the sensor
    SENSOR_PARAM_BAND_WIDTH                 = 3, //!< Bandwidth setting for the sensor
    SENSOR_PARAM_HP_FILTER                  = 4, //!< High Pass filter setting for the sensor
    SENSOR_PARAM_LP_FILTER                  = 5, //!< Low Pass filter setting for the sensor
    SENSOR_PARAM_ENABLE                     = 6, //!< Sensor Enable control

    NUM_SENSOR_PARAM
} SensorParamId_t;

//!  Use these values as a sub-type for  STEP result
typedef enum _StepSubType {
    CONTEXT_STEP  = SENSOR_SUBTYPE_START,  //!< only one kind of step now
    STEP_SEGMENT_DETECTOR,                 //!< low compute trigger for analyzing if step may have occured

    NUM_PSENSOR_STEP_SUBTYPE
} StepSubType_t;

//! Use these values as a sub-type for CONTEXT_DEVICE_MOTION result
typedef enum _ContextDeviceMotionSubType {
    CONTEXT_DEVICE_MOTION_STILL  = SENSOR_SUBTYPE_START,
    CONTEXT_DEVICE_MOTION_ACCELERATING,
    CONTEXT_DEVICE_MOTION_ROTATING,
    CONTEXT_DEIVCE_MOTION_TRANSLATING,
    CONTEXT_DEVICE_MOTION_FREE_FALLING,
    CONTEXT_DEVICE_MOTION_SIGNIFICANT_MOTION,        //!< significant motion (as specified by Android HAL 1.0)
    CONTEXT_DEVICE_MOTION_SIGNIFICANT_STILLNESS,     //!< complement to significant motion
    CONTEXT_DEVICE_MOTION_CHANGE_DETECTOR,           //!< low compute trigger for seeing if context may have changed

    NUM_PSENSOR_CONTEXT_DEVICE_MOTION_SUBTYPE
} ContextDeviceMotionSubType_t;

//!  Use these values as a sub-type for  CONTEXT_CARRY result
typedef enum _ContextCarrySubType {
    CONTEXT_CARRY_IN_POCKET     = SENSOR_SUBTYPE_START,
    CONTEXT_CARRY_IN_HAND,
    CONTEXT_CARRY_NOT_ON_PERSON,
    CONTEXT_CARRY_IN_HAND_FRONT,
    CONTEXT_CARRY_IN_HAND_SIDE,

    NUM_PSENSOR_CONTEXT_CARRY_SUBTYPE
} ContextCarrySubType_t;

//!  Use these values as a sub-type for CONTEXT_POSTURE result
typedef enum _ContextPostureSubType {
    CONTEXT_POSTURE_WALKING     = SENSOR_SUBTYPE_START,
    CONTEXT_POSTURE_STANDING,
    CONTEXT_POSTURE_SITTING,
    CONTEXT_POSTURE_JOGGING,
    CONTEXT_POSTURE_RUNNING,

    NUM_PSENSOR_CONTEXT_POSTURE_SUBTYPE
} ContextPostureSubType_t;

//!  Use these values as a sub-type for  CONTEXT_TRANSPORT result
typedef enum _ContextTransportSubType {
    CONTEXT_TRANSPORT_VEHICLE   = SENSOR_SUBTYPE_START,
    CONTEXT_TRANSPORT_CAR,
    CONTEXT_TRANSPORT_TRAIN,
    CONTEXT_TRANSPORT_UP_STAIRS,
    CONTEXT_TRANSPORT_DOWN_STAIRS,
    CONTEXT_TRANSPORT_UP_ELEVATOR,
    CONTEXT_TRANSPORT_DOWN_ELEVATOR,
    CONTEXT_TRANSPORT_ON_BIKE,

    NUM_PSENSOR_CONTEXT_TRANSPORT_SUBTYPE
} ContextTransportSubType_t;

//!  Use these values as a sub-type for  GESTURE_EVENT result
typedef enum _GestureSubType {
    SENSOR_GESTURE_TAP          = SENSOR_SUBTYPE_START,
    SENSOR_GESTURE_DOUBLE_TAP,
    SENSOR_GESTURE_SHAKE,

    NUM_PSENSOR_GESTURE_SUBTYPE
} GestureSubType_t;

//! Time Stamp definition for capturing raw time counts
typedef union _TimeStamp {
    uint64_t TS64;
    uint32_t TS32[2];
    uint8_t  TS8[8];
} TimeStamp_t;

//! Generic structure definition for a 3-axis sensor raw values in 2's complement format
typedef struct TriAxisRawData_t
{
    TimeStamp_t  TStamp;
    int32_t      Axis[3];
} TriAxisRawData_t;

/*-------------------------------------------------------------------------------------------------*\
 |    E X T E R N A L   V A R I A B L E S   &   F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P U B L I C   V A R I A B L E S   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P U B L I C   F U N C T I O N   D E C L A R A T I O N S
\*-------------------------------------------------------------------------------------------------*/

#endif /* MQ_SENSORS_H */
/*-------------------------------------------------------------------------------------------------*\
 |    E N D   O F   F I L E
\*-------------------------------------------------------------------------------------------------*/


text:
package com.yahoo.bullet.storm;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichSpout;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.apache.storm.utils.Utils;

import java.util.Map;
import java.util.Random;

import static com.yahoo.bullet.storm.TopologyConstants.ID_FIELD;
import static com.yahoo.bullet.storm.TopologyConstants.TICK_FIELD;
import static com.yahoo.bullet.storm.TopologyConstants.TICK_STREAM;

@Slf4j @Getter(AccessLevel.PACKAGE)
public class TickSpout extends ConfigComponent implements IRichSpout {
    private static final long serialVersionUID = 4448013633000246058L;

    protected transient SpoutOutputCollector collector;

    public static final long GRACEFUL_SLEEP = BulletStormConfig.TICK_INTERVAL_MINIMUM / 2;

    private final int tickInterval;
    private int id;
    private long tick = 0;
    @Setter(AccessLevel.PACKAGE)
    private long lastTickTime;

    /**
     * Creates an instance of this class with the given non-null config.
     *
     * @param config The non-null {@link BulletStormConfig} which is the config for this component.
     */
    public TickSpout(BulletStormConfig config) {
        super(config);
        tickInterval = config.getAs(BulletStormConfig.TICK_SPOUT_INTERVAL, Integer.class);
    }

    @Override
    public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) {
        this.collector = collector;
        tick = 0;
        lastTickTime = System.currentTimeMillis();
        id = new Random().nextInt();
    }

    @Override
    public void nextTuple() {
        long timeNow = System.currentTimeMillis();
        if (timeNow - lastTickTime < tickInterval) {
            Utils.sleep(GRACEFUL_SLEEP);
        } else {
            lastTickTime = timeNow;
            tick++;
            collector.emit(new Values(id, tick));
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declareStream(TICK_STREAM, new Fields(ID_FIELD, TICK_FIELD));
    }

    // Unused methods

    @Override
    public void activate() {
    }

    @Override
    public void deactivate() {
    }

    @Override
    public void ack(Object msgId) {
    }

    @Override
    public void fail(Object msgId) {
    }

    @Override
    public void close() {
    }
}


text:
import * as Joi from "joi";

export const createTaskModel = Joi.object().keys({
    name: Joi.string().required(),
    description: Joi.string().required()
});

export const updateTaskModel = Joi.object().keys({
    name: Joi.string().required(),
    description: Joi.string().required(),
    completed: Joi.boolean()
});


text:
<?php

namespace Retext\Hub\ApiBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class RetextHubApiBundle extends Bundle
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

    <plurals name="duration_seconds">
        <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> seconde</item>
        <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> secondes</item>
    </plurals>
    <plurals name="duration_minutes">
        <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> minute</item>
        <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> minutes</item>
    </plurals>
    <plurals name="duration_hours">
        <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> heure</item>
        <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> heures</item>
    </plurals>
    <plurals name="duration_days">
        <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> jour</item>
        <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> jours</item>
    </plurals>
</resources>


text:
package infowall.domain.persistence.sql;

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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import infowall.domain.model.Dashboard;
import infowall.domain.persistence.DashboardRepository;

/**
 *
 */
public class InMemoryDashboardRepository implements DashboardRepository{

    private final Map<String,Dashboard> dashboards;

    public InMemoryDashboardRepository() {
        this.dashboards = Maps.newHashMap();
    }

    private void putDashboard(Dashboard dashboard) {
        dashboards.put(dashboard.getId(), dashboard);
    }

    @Override
    public void put(Dashboard entity) {
        putDashboard(entity);
    }

    @Override
    public boolean contains(String dashboardId) {
        return dashboards.containsKey(dashboardId);
    }

    @Override
    public Dashboard get(String id) {
        Dashboard dashboard = dashboards.get(id);
        // TODO
        if(dashboard == null){
            throw new NotFoundException();
        }
        return dashboard;
    }

    @Override
    public List<Dashboard> getAll() {
        return Lists.newArrayList(dashboards.values());
    }
}


text:
package im_13_8.multecpanel.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import im_13_8.multecpanel.entiteiten.Cluster;
import im_13_8.multecpanel.entiteiten.DetailInfo;
import im_13_8.multecpanel.entiteiten.ListItem;

/**
 *
 * @author Sam Coenen
 * Integration: Multiscreen
 * Erasmushogeschool Brussel 2Ba Multimedia & Communicatietechnologie
 *
 * This class is used to fetch information about a course from the database.
 *
 */
public class VakModel {

	/**
	 *
	 * @return All courses stored in the database.
	 */
	public ArrayList<ListItem> getVakken() {
		ResultSet queryResult = null;
		DatabaseQuery dbQuery = null;
		try {
			dbQuery = new DatabaseQuery(
					"SELECT * FROM vak ORDER BY pijler, vaknaam;");
			queryResult = dbQuery.getResult();
		} catch (SQLException e) {
			System.out.println("There was an error while "
					+ "executing the query. Error:" + e);
		}

		ArrayList<ListItem> vakken = new ArrayList<ListItem>();
		try {
			while(queryResult.next()) {
				vakken.add(new ListItem(
						queryResult.getString("path_afbeelding"),
						queryResult.getString("vaknaam"),
						"",
						"vak", queryResult.getString("pijler")));
			}

		} catch (SQLException e) {
			System.out.println("There was an error while "
					+ "getting the row from the query result. Error:" + e);
		}
		dbQuery.close();

		return vakken;
	}

	/**
	 *
	 * @return The clusters for all our courses.
	 */
	public ArrayList<Cluster> getClusters() {
		ResultSet queryResult = null;
		DatabaseQuery dbQuery = null;
		try {
			dbQuery = new DatabaseQuery("SELECT count(*) AS number, "
					+ "pijler FROM vak GROUP BY pijler;");
			queryResult = dbQuery.getResult();
		} catch (SQLException e) {
			System.out.println("There was an error while "
					+ "executing the query. Error:" + e);
		}

		ArrayList<Cluster> clusters = new ArrayList<Cluster>();
		try {
			while(queryResult.next()) {
				clusters.add(new Cluster(queryResult.getString("pijler"),
						queryResult.getInt("number")));
			}

		} catch (SQLException e) {
			System.out.println("There was an error while "
					+ "getting the row from the query result. Error:" + e);
		}
		dbQuery.close();

		return clusters;
	}

	/**
	 *
	 * @param name The name of the course that you want information from.
	 * @return The information of the course fetched from the database.
	 */
	public DetailInfo getDetailInfo(String name) {
		ResultSet queryResult = null;
		DatabaseQuery dbQuery = null;
		try {
			dbQuery = new DatabaseQuery("SELECT * FROM vak WHERE "
					+ "vaknaam = ? limit 1;", name);
			queryResult = dbQuery.getResult();
		} catch (SQLException e) {
			System.out.println("There was an error while executing "
					+ "the query. Error:" + e);
		}

		DetailInfo detail = null;
		try {
			if(queryResult.next()) {
				detail = new DetailInfo(queryResult.getString("vaknaam"),
						queryResult.getString("vakbeschrijving"),
						queryResult.getString("path_afbeelding"));
			}

		} catch (SQLException e) {
			System.out.println("There was an error while "
					+ "getting the row from the query result. Error:" + e);
		}
		dbQuery.close();

		return detail;
	}

}


text:
from loguru import logger

from flexget import plugin
from flexget.event import event
from flexget.plugin import PluginError

logger = logger.bind(name='list_match')

class ListMatch:
    schema = {
        'type': 'object',
        'properties': {
            'from': {
                'type': 'array',
                'items': {
                    'allOf': [
                        {'$ref': '/schema/plugins?interface=list'},
                        {
                            'maxProperties': 1,
                            'error_maxProperties': 'Plugin options within list_match plugin must be indented '
                            '2 more spaces than the first letter of the plugin name.',
                            'minProperties': 1,
                        },
                    ]
                },
            },
            'action': {'type': 'string', 'enum': ['accept', 'reject'], 'default': 'accept'},
            'remove_on_match': {'type': 'boolean', 'default': True},
            'single_match': {'type': 'boolean', 'default': True},
        },
        'additionalProperties': False,
    }

    @plugin.priority(0)
    def on_task_filter(self, task, config):
        for item in config['from']:
            for plugin_name, plugin_config in item.items():
                try:
                    thelist = plugin.get(plugin_name, self).get_list(plugin_config)
                except AttributeError:
                    raise PluginError('Plugin %s does not support list interface' % plugin_name)
                already_accepted = []
                for entry in task.entries:
                    result = thelist.get(entry)
                    if not result:
                        continue
                    if config['action'] == 'accept':
                        if config['single_match']:
                            if result not in already_accepted:
                                already_accepted.append(result)
                                # Add all new result data to entry
                                for key in result:
                                    if key not in entry:
                                        entry[key] = result[key]
                                entry.accept()
                        else:
                            entry.accept()
                    elif config['action'] == 'reject':
                        entry.reject()

    def on_task_learn(self, task, config):
        if not config['remove_on_match'] or not len(task.accepted) > 0:
            return
        for item in config['from']:
            for plugin_name, plugin_config in item.items():
                try:
                    thelist = plugin.get(plugin_name, self).get_list(plugin_config)
                except AttributeError:
                    raise PluginError('Plugin %s does not support list interface' % plugin_name)
                if task.manager.options.test and thelist.online:
                    logger.info(
                        '`{}` is marked as online, would remove accepted items outside of --test mode.',
                        plugin_name,
                    )
                    continue
                logger.verbose(
                    'removing accepted entries from {} - {}', plugin_name, plugin_config
                )
                thelist -= task.accepted

@event('plugin.register')
def register_plugin():
    plugin.register(ListMatch, 'list_match', api_ver=2)


text:
package edu.virginia.uvacluster.internal.statistic;

import java.util.List;

import edu.virginia.uvacluster.internal.Cluster;

public class Ordinal extends Statistic {
	private Integer ordinalNum;

	public Ordinal(StatisticRange range, int ordinalNum) {
		super(range,"Ordinal");
		this.ordinalNum = ordinalNum;
	}

	@Override
	public double transform(List<Double> values, Cluster cluster) {
		return values.get(getIndex());
	}

	@Override
	public String getDescription(String name) {
		String prefix = ordinalNum.toString();
		switch(ordinalNum % 10) {
		case 1: prefix += "st";
				break;
		case 2: prefix += "nd";
				break;
		case 3: prefix += "rd";
				break;
        default: prefix += "th";
        		 break;
		}
		return prefix + " : " + name;
	}

	public int getIndex() {return ordinalNum-1;}

}


text:
package io.bootique.help;

import java.util.Collection;

import static java.util.Arrays.asList;

/*
 * A helper for building a text help document with consistent formatting. It will include line breaks to separate
 * sections, will provide consistent offsets, text wrapping, etc.
 *
 * @since 0.21
 */
public class HelpAppender {

    private ConsoleAppender rootAppender;
    private ConsoleAppender offsetAppender;
    private ConsoleAppender doubleOffsetAppender;

    private int sectionCount;
    private int subsectionCount;

    public HelpAppender(ConsoleAppender appender) {
        this.rootAppender = appender;
    }

    public ConsoleAppender getAppender() {
        return rootAppender;
    }

    public void printSectionName(String name) {

        // line break between sections
        if (sectionCount++ > 0) {
            subsectionCount = 0;
            rootAppender.println();
        }

        rootAppender.println(name);
    }

    public void printSubsectionHeader(String... parts) {
        printSubsectionHeader(asList(parts));
    }

    public void printSubsectionHeader(Collection<String> parts) {

        // line break between subsections
        if (subsectionCount++ > 0) {
            rootAppender.println();
        }

        getOrCreateOffsetAppender().foldPrintln(parts);
    }

    public void printText(String... parts) {
        getOrCreateOffsetAppender().println(parts);
    }

    public void printDescription(String... parts) {
        getOrCreateDoubleOffsetAppender().foldPrintln(parts);
    }

    public void println() {
        rootAppender.println();
    }

    private ConsoleAppender getOrCreateOffsetAppender() {
        if (this.offsetAppender == null) {
            this.offsetAppender = rootAppender.withOffset(6);
        }

        return offsetAppender;
    }

    private ConsoleAppender getOrCreateDoubleOffsetAppender() {
        if (this.doubleOffsetAppender == null) {
            // "5" is the magic number used for decsription offset. It seems to look best when description is printed
            // under the options
            this.doubleOffsetAppender = getOrCreateOffsetAppender().withOffset(5);
        }

        return doubleOffsetAppender;
    }
}


text:
/**
 * \file
 * \brief Bench library.
 */

/*
 * Copyright (c) 2007, 2008, 2009, 2010, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

#ifndef BENCH_H
#define BENCH_H

#include <barrelfish/types.h> // for cycles_t
#include <bench/bench_arch.h>
#include <sys/cdefs.h>

#define BENCH_IGNORE_WATERMARK 0XDEADBEEF

__BEGIN_DECLS
void bench_init(void);
cycles_t bench_avg(cycles_t *array, size_t len);
cycles_t bench_variance(cycles_t *array, size_t len);
cycles_t bench_tscoverhead(void);
__END_DECLS

#endif // BENCH_H


text:
import json
import http

from requests_toolbelt import MultipartEncoder
from requests.exceptions import HTTPError
from hyper import HTTP20Connection

from alexa_client.alexa_client import constants, helpers

class ConnectionManager:
    connection = None
    # TODO: in next breaking change release rename to `base_url` and move to
    # client.connect default kwargs
    host = constants.BASE_URL_EUROPE

    def create_connection(self, base_url=None):
        self.connection = HTTP20Connection(
            host=base_url or self.host, secure=True, force_proto='h2'
        )

    def establish_downchannel_stream(self, authentication_headers):
        self.connection.request(
            'GET',
            '/v20160207/directives',
            headers=authentication_headers
        )

    def synchronise_device_state(self, device_state, authentication_headers):
        """
        Synchronizing the component states with AVS

        Components state must be synchronised with AVS after establishing the
        downchannel stream in order to create a persistent connection with AVS.

        Note that currently this function is paying lip-service synchronising
        the device state: the device state is hard-coded.

        """

        payload = {
            'context': device_state,
            'event': {
                'header': {
                    'namespace': 'System',
                    'name': 'SynchronizeState',
                    'messageId': ''
                },
                'payload': {}
            }
        }
        multipart_data = MultipartEncoder(
            fields=[
                (
                    'metadata', (
                        'metadata',
                        json.dumps(payload),
                        'application/json',
                        {'Content-Disposition': "form-data; name='metadata'"}
                    )
                ),
            ],
            boundary='boundary'
        )
        headers = {
            **authentication_headers,
            'Content-Type': multipart_data.content_type
        }
        stream_id = self.connection.request(
            'POST',
            '/v20160207/events',
            body=multipart_data,
            headers=headers,
        )
        response = self.connection.get_response(stream_id)
        assert response.status in (http.client.NO_CONTENT, http.client.OK)

    def send_audio_file(
        self, audio_file, device_state, authentication_headers,
        dialog_request_id, distance_profile, audio_format
    ):
        """
        Send audio to AVS

        The file-like object are steaming uploaded for improved latency.

        Returns:
            bytes -- wav audio bytes returned from AVS

        """

        payload = {
            'context': device_state,
            'event': {
                'header': {
                    'namespace': 'SpeechRecognizer',
                    'name': 'Recognize',
                    'messageId': self.generate_message_id(),
                    'dialogRequestId': dialog_request_id,
                },
                'payload': {
                    'profile': distance_profile,
                    'format': audio_format
                }
            }
        }
        multipart_data = MultipartEncoder(
            fields=[
                (
                    'request', (
                        'request',
                        json.dumps(payload),
                        'application/json;',
                        {'Content-Disposition': "form-data; name='request'"}
                    ),
                ),
                (
                    'audio', (
                        'audio',
                        audio_file,
                        'application/octet-stream',
                        {'Content-Disposition': "form-data; name='audio'"}
                    )
                ),
            ],
            boundary='boundary',
        )
        headers = {
            **authentication_headers,
            'Content-Type': multipart_data.content_type
        }
        stream_id = self.connection.request(
            'POST',
            '/v20160207/events',
            headers=headers,
            body=multipart_data,
        )
        response = self.connection.get_response(stream_id)
        return self.parse_response(response)

    def ping(self, authentication_headers):
        stream_id = self.connection.request(
            'GET',
            '/ping',
            headers=authentication_headers,
        )
        return self.connection.get_response(stream_id)

    @staticmethod
    def parse_response(response):
        if response.status == http.client.NO_CONTENT:
            return None
        if not response.status == http.client.OK:
            raise HTTPError(response=response)
        return helpers.AVSMultipartDecoder(response).directives

    @staticmethod
    def generate_message_id():
        return helpers.generate_unique_id()


text: define("dojox/editor/plugins/nls/fi/InsertEntity",{insertEntity:"Lis\u00e4\u00e4 symboli"});