text:
<?php

namespace app\controllers;

use app\models\Access;
use Yii;
use app\models\Note;
use app\models\search\NoteSearch;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * NoteController implements the CRUD actions for Note model.
 */
class NoteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['mynotes', 'friendnotes', 'create', 'update', 'delete'],
                'rules' => [
                    [
                        'actions' => ['mynotes', 'friendnotes', 'create', 'update', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists my Note models.
     * @return mixed
     */
    public function actionMynotes()
    {
        $searchModel = new NoteSearch();
        $dataProvider = $searchModel->search([
            'NoteSearch'=> [
                'creator' => Yii::$app->user->id
            ]
        ]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Lists friend Note models.
     * @param int $id
     * @return mixed
     */
    public function actionFriendnotes($id)
    {
        $searchModel = new NoteSearch();
        $dataProvider = $searchModel->search([
            'NoteSearch' => [
                'creator' => $id,
                'access' => [
                    'user_id' => Yii::$app->user->id
                ]
            ]
        ]);

        return $this->render('friendnotes', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Note model.
     * @param $id
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $result = Access::checkAccess($model);

        if($result)
        {
            switch($result) {
                case Access::ACCESS_CREATOR:
                    return $this->render('viewCreator', [
                        'model' => $model,
                    ]);
                break;
                case Access::ACCESS_GUEST:
                    return $this->render('viewGuest', [
                        'model' => $model,
                    ]);
                break;
            }
        }
        throw new ForbiddenHttpException("Not allowed! ");
    }

    /**
     * Creates a new Note model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Note();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Note model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param $id
     * @return string|\yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Access::checkIsCreator($model)) {
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
        throw new ForbiddenHttpException("Not allowed change note other user");
    }

    /**
     * Deletes an existing Note model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param $id
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \Exception
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if(Access::checkIsCreator($model)) {
            $model->delete();
            return $this->redirect(['index']);
        }
        throw new ForbiddenHttpException("Not allowed delete note other user");

    }

    /**
     * Finds the Note model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Note the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Note::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
module Footnotes
  module Notes
    class LogNote
      class NoteLogger < Logger

        def initialize(logs)
          @logs = logs
        end

        def add(severity, message = nil, progname = nil, &block)
          severity ||= UNKNOWN
          if severity < level
            return true
          end
          formatter = @formatter || Logger::Formatter.new
          @logs << formatter.call(format_severity(severity), Time.now, message, progname)
        end

        ## Backport from rails 4 for handling logging broadcast, should be removed when rails 3 is deprecated :

        # Broadcasts logs to multiple loggers.
        def self.broadcast(logger) # :nodoc:
          Module.new do
            define_method(:add) do |*args, &block|
              logger.add(*args, &block)
              super(*args, &block)
            end

            define_method(:<<) do |x|
              logger << x
              super(x)
            end

            define_method(:close) do
              logger.close
              super()
            end

            define_method(:progname=) do |name|
              logger.progname = name
              super(name)
            end

            define_method(:formatter=) do |formatter|
              logger.formatter = formatter
              super(formatter)
            end

            define_method(:level=) do |level|
              logger.level = level
              super(level)
            end
          end
        end

      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
AddCSLuaFile("shared.lua")

include("shared.lua")

function ENT:Initialize()
    DarkRP.ValidatedPhysicsInit(self, SOLID_VPHYSICS)
    self:SetMoveType(MOVETYPE_VPHYSICS)
    self:SetSolid(SOLID_VPHYSICS)
    self:SetUseType(SIMPLE_USE)

    local phys = self:GetPhysicsObject()

    if phys:IsValid() then
        phys:Wake()
    end
end

function ENT:OnTakeDamage(dmg)
    self:Remove()
end

function ENT:Use(activator, caller)
    local canUse, reason = hook.Call("canDarkRPUse", nil, activator, self, caller)
    if canUse == false then
        if reason then DarkRP.notify(activator, 1, 4, reason) end
        return
    end

    local override = self.foodItem.onEaten and self.foodItem.onEaten(self, activator, self.foodItem)

    if override then
        self:Remove()
        return
    end

    hook.Call("playerAteFood", nil, activator, self.foodItem, self)

    activator:setSelfDarkRPVar("Energy", math.Clamp((activator:getDarkRPVar("Energy") or 100) + (self.FoodEnergy or 1), 0, 100))
    umsg.Start("AteFoodIcon", activator)
    umsg.End()

    self:Remove()
    activator:EmitSound(self.EatSound, 100, 100)
end

DarkRP.hookStub{
    name = "playerAteFood",
    description = "When a player eats food.",
    parameters = {
        {
            name = "ply",
            description = "The player who ate food.",
            type = "Player"
        },
        {
            name = "food",
            description = "Food table.",
            type = "table"
        },
        {
            name = "spawnedfood",
            description = "Entity of spawned food.",
            type = "Entity"
        },
    },
    returns = {
    },
}


text:
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Setup the search options.
    var options = Word.SearchOptions.newObject(context);
    options.matchCase = false

    // Queue a commmand to search the document.
    var searchResults = context.document.body.search('video', options);

    // Queue a commmand to load the results.
    context.load(searchResults, 'text, font');

    // Synchronize the document state by executing the queued-up commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        var results = 'Found count: ' + searchResults.items.length +
                      '; we highlighted the results.';

        // Queue a command to change the font for each found item.
        for (var i = 0; i < searchResults.items.length; i++) {
          searchResults.items[i].font.color = '#FF0000'    // Change color to Red
          searchResults.items[i].font.highlightColor = '#FFFF00';
          searchResults.items[i].font.bold = true;
        }

        // Synchronize the document state by executing the queued-up commands,
        // and return a promise to indicate task completion.
        return context.sync().then(function () {
            console.log(results);
        });
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});


text:
var expect = require('chai').expect;
var mongo = require('mongodb-connect');
var Validate = require(__dirname + '/../lib/is.valid.mongo');
var config = {
	mongodb: {
		host: '127.0.0.1',
		port: 27017,
		db: 'is_valid_mongo_test'
	}
};

describe('validate', function(){

	var mongodb;

	before(function(done){
		mongo.connect(config.mongodb, function(err, db){
			mongodb = db;
			mongodb.dropDatabase();
			mongodb.collection('validations').update({'email': 'bahaa.galal@crowdanalyzer.com'}, {'email': 'bahaa.galal@crowdanalyzer.com', 'delete_flag': '0'}, {safe: true, upsert: true}, function(err, success){
				mongodb.collection('validations').update({'user': {'email': 'bahaa@crowdanalyzer.com'}}, {'user': {'email': 'bahaa@crowdanalyzer.com'}, 'delete_flag': '0'}, {safe: true, upsert: true}, function(err, success){
					done();
				});
			});
		});
	});

	describe('init', function(){

		it('should initialize error messages for except, unique, uniqueExcept rules', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			expect(validate.errorMessages).to.have.property('exists');
			expect(validate.errorMessages).to.have.property('unique');
			expect(validate.errorMessages).to.have.property('uniqueExcept');
			expect(validate.errorMessages['exists']).to.be.equal('%s doesn\'t exist.');
			expect(validate.errorMessages['unique']).to.be.equal('%s isn\'t unique.');
			expect(validate.errorMessages['uniqueExcept']).to.be.equal('%s isn\'t unique.');
			done();
		});

		it('should add except, unique and uniqueExcept rules to the optionable rules array', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			expect(validate.rulesWithOptions[validate.rulesWithOptions.length - 3]).to.be.equal('exists');
			expect(validate.rulesWithOptions[validate.rulesWithOptions.length - 2]).to.be.equal('unique');
			expect(validate.rulesWithOptions[validate.rulesWithOptions.length - 1]).to.be.equal('uniqueExcept');
			done();
		});
	});

	describe('exists', function(){

		it('should return false if the value provided doesn\'t exist in the database', function(done){
			var validate = new Validate({
				email: 'bahaa@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|exists[validations.email]');
			validate.run(function(err, data){
				expect(err).to.not.be.null;
				expect(err).to.be.an('object');
				expect(err).to.have.property('email');
				expect(err.email).to.be.equal('email doesn\'t exist.');
				done();
			});
		});

		it('should be able to track complex inside object validation', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|exists[validations.user.email]');
			validate.run(function(err, data){
				expect(err).to.not.be.null;
				expect(err).to.be.an('object');
				expect(err).to.have.property('email');
				expect(err.email).to.be.equal('email doesn\'t exist.');
				done();
			});
		});

		it('should return true if email exists', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|exists[validations.email]');
			validate.run(function(err, data){
				expect(err).to.be.null;
				done();
			});
		});

		it('should return true if user.email exists', function(done){
			var validate = new Validate({
				email: 'bahaa@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|exists[validations.user.email]');
			validate.run(function(err, data){
				expect(err).to.be.null;
				done();
			});
		});
	});

	describe('unique', function(){

		it('should return false if the value provided does exist in the database', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|unique[validations.email]');
			validate.run(function(err, data){
				expect(err).to.not.be.null;
				expect(err).to.be.an('object');
				expect(err).to.have.property('email');
				expect(err.email).to.be.equal('email isn\'t unique.');
				done();
			});
		});

		it('should be able to track nested objects', function(done){
			var validate = new Validate({
				email: 'bahaa@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|unique[validations.user.email]');
			validate.run(function(err, data){
				expect(err).to.not.be.null;
				expect(err).to.be.an('object');
				expect(err).to.have.property('email');
				expect(err.email).to.be.equal('email isn\'t unique.');
				done();
			});
		});

		it('should return true if email is unique', function(done){
			var validate = new Validate({
				email: 'bahaa@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|unique[validations.email]');
			validate.run(function(err, data){
				expect(err).to.be.null;
				done();
			});
		});

		it('should return true if user.email is unique', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|unique[validations.user.email]');
			validate.run(function(err, data){
				expect(err).to.be.null;
				done();
			});
		});

		it('should return error if id isn\'t mongo id', function(done){
			var validate = new Validate({
				_id: '1234567890'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('_id', 'id', 'required|unique[validations._id]');
			validate.run(function(err, data){
				expect(err).to.not.be.null;
				expect(err).to.be.an('object');
				expect(err).to.have.property('_id');
				expect(err._id).to.be.equal('id isn\'t unique.');
				done();
			});
		});
	});

	describe('uniqueExcept', function(){

		it('should return false if the value provided does exist in the database and the exception codition isn\'t matching', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|uniqueExcept[validations.email.delete_flag.1]');
			validate.run(function(err, data){
				expect(err).to.not.be.null;
				expect(err).to.be.an('object');
				expect(err).to.have.property('email');
				expect(err.email).to.be.equal('email isn\'t unique.');
				done();
			});
		});

		it('should return true if email is unique with only one exception', function(done){
			var validate = new Validate({
				email: 'bahaa.galal@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|uniqueExcept[validations.email.delete_flag.0]');
			validate.run(function(err, data){
				expect(err).to.be.null;
				done();
			});
		});

		it('should return true if email is unique', function(done){
			var validate = new Validate({
				email: 'bahaa@crowdanalyzer.com'
			});

			validate.setDBDriver(mongodb);
			validate.addRule('email', 'email', 'required|uniqueExcept[validations.email.delete_flag.1]');
			validate.run(function(err, data){
				expect(err).to.be.null;
				done();
			});
		});
	});
});


text:
#include "stdio.h"
#ifndef mips
#include "stdlib.h"
#endif
#include "xlisp.h"
#include "sound.h"

#include "falloc.h"
#include "cext.h"
#include "alpassvc.h"

void alpassvc_free();

typedef struct alpassvc_susp_struct {
    snd_susp_node susp;
    long terminate_cnt;
    sound_type input;
    long input_cnt;
    sample_block_values_type input_ptr;
    sound_type delaysnd;
    long delaysnd_cnt;
    sample_block_values_type delaysnd_ptr;

    float delay_scale_factor;
    double feedback;
    long buflen;
    sample_type *delaybuf;
    sample_type *delayptr;
    sample_type *endptr;
} alpassvc_susp_node, *alpassvc_susp_type;

void alpassvc_nn_fetch(register alpassvc_susp_type susp, snd_list_type snd_list)
{
    int cnt = 0; /* how many samples computed */
    int togo;
    int n;
    sample_block_type out;
    register sample_block_values_type out_ptr;

    register sample_block_values_type out_ptr_reg;

    register float delay_scale_factor_reg;
    register double feedback_reg;
    register long buflen_reg;
    register sample_type * delayptr_reg;
    register sample_type * endptr_reg;
    register sample_block_values_type delaysnd_ptr_reg;
    register sample_block_values_type input_ptr_reg;
    falloc_sample_block(out, "alpassvc_nn_fetch");
    out_ptr = out->samples;
    snd_list->block = out;

    while (cnt < max_sample_block_len) { /* outer loop */
	/* first compute how many samples to generate in inner loop: */
	/* don't overflow the output sample block: */
	togo = max_sample_block_len - cnt;

	/* don't run past the input input sample block: */
	susp_check_term_samples(input, input_ptr, input_cnt);
	togo = min(togo, susp->input_cnt);

	/* don't run past the delaysnd input sample block: */
	susp_check_samples(delaysnd, delaysnd_ptr, delaysnd_cnt);
	togo = min(togo, susp->delaysnd_cnt);

	/* don't run past terminate time */
	if (susp->terminate_cnt != UNKNOWN &&
	    susp->terminate_cnt <= susp->susp.current + cnt + togo) {
	    togo = susp->terminate_cnt - (susp->susp.current + cnt);
	    if (togo == 0) break;
	}

	n = togo;
	delay_scale_factor_reg = susp->delay_scale_factor;
	feedback_reg = susp->feedback;
	buflen_reg = susp->buflen;
	delayptr_reg = susp->delayptr;
	endptr_reg = susp->endptr;
	delaysnd_ptr_reg = susp->delaysnd_ptr;
	input_ptr_reg = susp->input_ptr;
	out_ptr_reg = out_ptr;
	if (n) do { /* the inner sample computation loop */
        register sample_type y, z, delaysamp;
        register int delayi;
        register sample_type *yptr;

        /* compute where to read y, we want y to be delay_snd samples
         * after delay_ptr, where we write the new sample. First,
         * conver from seconds to samples. Note: don't use actual sound_type
         * names in comments! The translator isn't smart enough.
         */
        delaysamp = *delaysnd_ptr_reg++ * delay_scale_factor_reg;
        delayi = (int) delaysamp; /* get integer part */
        delaysamp = delaysamp - delayi; /* get phase */
        yptr = delayptr_reg + buflen_reg - (delayi + 1);
        if (yptr >= endptr_reg) yptr -= buflen_reg;
        /* now get y, the out-put of the delay, using interpolation */
        /* note that as phase increases, we use more of yptr[0] because
           positive phase means longer buffer means read earlier sample */
        y = (float) ((yptr[0] * delaysamp) + (yptr[1] * (1.0 - delaysamp)));
        /* WARNING: no check to keep delaysamp in range, so do this in LISP */

        *delayptr_reg++ = z = (sample_type) (feedback_reg * y + *input_ptr_reg++);
        /* Time out to update the buffer:
         * this is a tricky buffer: buffer[0] == buffer[bufflen]
         * the logical length is bufflen, but the actual length
         * is bufflen + 1 to allow for a repeated sample at the
         * end. This allows for efficient interpolation.
         */
        if (delayptr_reg > endptr_reg) {
            delayptr_reg = susp->delaybuf;
            *delayptr_reg++ = *endptr_reg;
        }
        *out_ptr_reg++ = (sample_type) (y - feedback_reg * z);;
	} while (--n); /* inner loop */

	susp->buflen = buflen_reg;
	susp->delayptr = delayptr_reg;
	/* using delaysnd_ptr_reg is a bad idea on RS/6000: */
	susp->delaysnd_ptr += togo;
	/* using input_ptr_reg is a bad idea on RS/6000: */
	susp->input_ptr += togo;
	out_ptr += togo;
	susp_took(input_cnt, togo);
	susp_took(delaysnd_cnt, togo);
	cnt += togo;
    } /* outer loop */

    /* test for termination */
    if (togo == 0 && cnt == 0) {
	snd_list_terminate(snd_list);
    } else {
	snd_list->block_len = cnt;
	susp->susp.current += cnt;
    }
} /* alpassvc_nn_fetch */

void alpassvc_ns_fetch(register alpassvc_susp_type susp, snd_list_type snd_list)
{
    int cnt = 0; /* how many samples computed */
    int togo;
    int n;
    sample_block_type out;
    register sample_block_values_type out_ptr;

    register sample_block_values_type out_ptr_reg;

    register float delay_scale_factor_reg;
    register double feedback_reg;
    register long buflen_reg;
    register sample_type * delayptr_reg;
    register sample_type * endptr_reg;
    register sample_type delaysnd_scale_reg = susp->delaysnd->scale;
    register sample_block_values_type delaysnd_ptr_reg;
    register sample_block_values_type input_ptr_reg;
    falloc_sample_block(out, "alpassvc_ns_fetch");
    out_ptr = out->samples;
    snd_list->block = out;

    while (cnt < max_sample_block_len) { /* outer loop */
	/* first compute how many samples to generate in inner loop: */
	/* don't overflow the output sample block: */
	togo = max_sample_block_len - cnt;

	/* don't run past the input input sample block: */
	susp_check_term_samples(input, input_ptr, input_cnt);
	togo = min(togo, susp->input_cnt);

	/* don't run past the delaysnd input sample block: */
	susp_check_samples(delaysnd, delaysnd_ptr, delaysnd_cnt);
	togo = min(togo, susp->delaysnd_cnt);

	/* don't run past terminate time */
	if (susp->terminate_cnt != UNKNOWN &&
	    susp->terminate_cnt <= susp->susp.current + cnt + togo) {
	    togo = susp->terminate_cnt - (susp->susp.current + cnt);
	    if (togo == 0) break;
	}

	n = togo;
	delay_scale_factor_reg = susp->delay_scale_factor;
	feedback_reg = susp->feedback;
	buflen_reg = susp->buflen;
	delayptr_reg = susp->delayptr;
	endptr_reg = susp->endptr;
	delaysnd_ptr_reg = susp->delaysnd_ptr;
	input_ptr_reg = susp->input_ptr;
	out_ptr_reg = out_ptr;
	if (n) do { /* the inner sample computation loop */
        register sample_type y, z, delaysamp;
        register int delayi;
        register sample_type *yptr;

        /* compute where to read y, we want y to be delay_snd samples
         * after delay_ptr, where we write the new sample. First,
         * conver from seconds to samples. Note: don't use actual sound_type
         * names in comments! The translator isn't smart enough.
         */
        delaysamp = (delaysnd_scale_reg * *delaysnd_ptr_reg++) * delay_scale_factor_reg;
        delayi = (int) delaysamp; /* get integer part */
        delaysamp = delaysamp - delayi; /* get phase */
        yptr = delayptr_reg + buflen_reg - (delayi + 1);
        if (yptr >= endptr_reg) yptr -= buflen_reg;
        /* now get y, the out-put of the delay, using interpolation */
        /* note that as phase increases, we use more of yptr[0] because
           positive phase means longer buffer means read earlier sample */
        y = (float) ((yptr[0] * delaysamp) + (yptr[1] * (1.0 - delaysamp)));
        /* WARNING: no check to keep delaysamp in range, so do this in LISP */

        *delayptr_reg++ = z = (sample_type) (feedback_reg * y + *input_ptr_reg++);
        /* Time out to update the buffer:
         * this is a tricky buffer: buffer[0] == buffer[bufflen]
         * the logical length is bufflen, but the actual length
         * is bufflen + 1 to allow for a repeated sample at the
         * end. This allows for efficient interpolation.
         */
        if (delayptr_reg > endptr_reg) {
            delayptr_reg = susp->delaybuf;
            *delayptr_reg++ = *endptr_reg;
        }
        *out_ptr_reg++ = (sample_type) (y - feedback_reg * z);;
	} while (--n); /* inner loop */

	susp->buflen = buflen_reg;
	susp->delayptr = delayptr_reg;
	/* using delaysnd_ptr_reg is a bad idea on RS/6000: */
	susp->delaysnd_ptr += togo;
	/* using input_ptr_reg is a bad idea on RS/6000: */
	susp->input_ptr += togo;
	out_ptr += togo;
	susp_took(input_cnt, togo);
	susp_took(delaysnd_cnt, togo);
	cnt += togo;
    } /* outer loop */

    /* test for termination */
    if (togo == 0 && cnt == 0) {
	snd_list_terminate(snd_list);
    } else {
	snd_list->block_len = cnt;
	susp->susp.current += cnt;
    }
} /* alpassvc_ns_fetch */

void alpassvc_toss_fetch(susp, snd_list)
  register alpassvc_susp_type susp;
  snd_list_type snd_list;
{
    long final_count = susp->susp.toss_cnt;
    time_type final_time = susp->susp.t0;
    long n;

    /* fetch samples from input up to final_time for this block of zeros */
    while ((round((final_time - susp->input->t0) * susp->input->sr)) >=
	   susp->input->current)
	susp_get_samples(input, input_ptr, input_cnt);
    /* fetch samples from delaysnd up to final_time for this block of zeros */
    while ((round((final_time - susp->delaysnd->t0) * susp->delaysnd->sr)) >=
	   susp->delaysnd->current)
	susp_get_samples(delaysnd, delaysnd_ptr, delaysnd_cnt);
    /* convert to normal processing when we hit final_count */
    /* we want each signal positioned at final_time */
    n = round((final_time - susp->input->t0) * susp->input->sr -
         (susp->input->current - susp->input_cnt));
    susp->input_ptr += n;
    susp_took(input_cnt, n);
    n = round((final_time - susp->delaysnd->t0) * susp->delaysnd->sr -
         (susp->delaysnd->current - susp->delaysnd_cnt));
    susp->delaysnd_ptr += n;
    susp_took(delaysnd_cnt, n);
    susp->susp.fetch = susp->susp.keep_fetch;
    (*(susp->susp.fetch))(susp, snd_list);
}

void alpassvc_mark(alpassvc_susp_type susp)
{
    sound_xlmark(susp->input);
    sound_xlmark(susp->delaysnd);
}

void alpassvc_free(alpassvc_susp_type susp)
{
free(susp->delaybuf);    sound_unref(susp->input);
    sound_unref(susp->delaysnd);
    ffree_generic(susp, sizeof(alpassvc_susp_node), "alpassvc_free");
}

void alpassvc_print_tree(alpassvc_susp_type susp, int n)
{
    indent(n);
    stdputstr("input:");
    sound_print_tree_1(susp->input, n);

    indent(n);
    stdputstr("delaysnd:");
    sound_print_tree_1(susp->delaysnd, n);
}

sound_type snd_make_alpassvc(sound_type input, sound_type delaysnd, double feedback, double maxdelay)
{
    register alpassvc_susp_type susp;
    rate_type sr = max(input->sr, delaysnd->sr);
    time_type t0 = max(input->t0, delaysnd->t0);
    int interp_desc = 0;
    sample_type scale_factor = 1.0F;
    time_type t0_min = t0;
    /* combine scale factors of linear inputs (INPUT) */
    scale_factor *= input->scale;
    input->scale = 1.0F;

    /* try to push scale_factor back to a low sr input */
    if (input->sr < sr) { input->scale = scale_factor; scale_factor = 1.0F; }

    falloc_generic(susp, alpassvc_susp_node, "snd_make_alpassvc");
    susp->delay_scale_factor = (float) (input->sr * delaysnd->scale);
    susp->feedback = feedback;
    susp->buflen = max(2, (long) (input->sr * maxdelay + 2.5));
    susp->delaybuf = (sample_type *) calloc (susp->buflen + 1, sizeof(sample_type));
    susp->delayptr = susp->delaybuf;
    susp->endptr = susp->delaybuf + susp->buflen;

    /* select a susp fn based on sample rates */
    interp_desc = (interp_desc << 2) + interp_style(input, sr);
    interp_desc = (interp_desc << 2) + interp_style(delaysnd, sr);
    switch (interp_desc) {
      case INTERP_nn: susp->susp.fetch = alpassvc_nn_fetch; break;
      case INTERP_ns: susp->susp.fetch = alpassvc_ns_fetch; break;
      default: snd_badsr(); break;
    }

    susp->terminate_cnt = UNKNOWN;
    /* handle unequal start times, if any */
    if (t0 < input->t0) sound_prepend_zeros(input, t0);
    if (t0 < delaysnd->t0) sound_prepend_zeros(delaysnd, t0);
    /* minimum start time over all inputs: */
    t0_min = min(input->t0, min(delaysnd->t0, t0));
    /* how many samples to toss before t0: */
    susp->susp.toss_cnt = (long) ((t0 - t0_min) * sr + 0.5);
    if (susp->susp.toss_cnt > 0) {
	susp->susp.keep_fetch = susp->susp.fetch;
	susp->susp.fetch = alpassvc_toss_fetch;
    }

    /* initialize susp state */
    susp->susp.free = alpassvc_free;
    susp->susp.sr = sr;
    susp->susp.t0 = t0;
    susp->susp.mark = alpassvc_mark;
    susp->susp.print_tree = alpassvc_print_tree;
    susp->susp.name = "alpassvc";
    susp->susp.log_stop_cnt = UNKNOWN;
    susp->susp.current = 0;
    susp->input = input;
    susp->input_cnt = 0;
    susp->delaysnd = delaysnd;
    susp->delaysnd_cnt = 0;
    return sound_create((snd_susp_type)susp, t0, sr, scale_factor);
}

sound_type snd_alpassvc(sound_type input, sound_type delaysnd, double feedback, double maxdelay)
{
    sound_type input_copy = sound_copy(input);
    sound_type delaysnd_copy = sound_copy(delaysnd);
    return snd_make_alpassvc(input_copy, delaysnd_copy, feedback, maxdelay);
}


text:
namespace Z {

//! Input/output stream handler
class Stream
{
public:
   enum MessageLevel
   {
      INFO,
      WARNING,
      ERROR
   };

   Stream(Console&       console_,
          const Options& options_,
          unsigned       version_,
          IF::Memory&    memory_)
      : console(console_)
      , memory(memory_)
   {
      console_enable                  = true;
      console_extended_colours_enable = version_ == 6;

      printer_enable     = options_.print;
      printer_echo_input = version_ <= 5;

      memory_enable  = false;
      snooper_enable = options_.key;

      buffer_enable = true;
      buffer_size   = 0;
      buffer_col    = 1;

      if(options_.info)
      {
         message_filter = INFO;
      }
      else if(options_.warn)
      {
         message_filter = WARNING;
      }

      trace_enable = options_.trace;
   }

   bool getBuffering() const { return buffer_enable; }

   bool getStreamEnable(unsigned index) const
   {
      switch(index)
      {
      case 1: return console_enable;
      case 2: return printer_enable;
      case 3: return memory_enable;
      case 4: return snooper_enable;

      default: assert(!"unexpected index"); return false;
      }
   }

   //! Select the current font
   bool setFont(unsigned font_idx)
   {
      flush();

      return console.setFont(font_idx);
   }

   //! Set Z-code text style
   void setFontStyle(unsigned text_style)
   {
      flush();

      if (text_style == 0)
      {
         console_text_style = 0;
      }
      else
      {
         console_text_style |= uint8_t(text_style);
      }

      // Convert Z-code text style to a Console font style. Might be a 1-1
      // mapping of bits, but copying each bit is more robust
      Console::FontStyle font_style = 0;
      if(console_text_style & (1 << 0)) font_style |= Console::FONT_STYLE_REVERSE;
      if(console_text_style & (1 << 1)) font_style |= Console::FONT_STYLE_BOLD;
      if(console_text_style & (1 << 2)) font_style |= Console::FONT_STYLE_ITALIC;
      if(console_text_style & (1 << 3)) font_style |= Console::FONT_STYLE_FIXED;

      console.setFontStyle(font_style);
   }

   //! Set colours
   void setColours(signed fg, signed bg)
   {
      flush();

      Console::Colour fg_col;
      if(convertCodeToConsoleColour(fg, fg_col))
      {
         console.setForegroundColour(fg_col);
      }

      Console::Colour bg_col;
      if(convertCodeToConsoleColour(bg, bg_col))
      {
         console.setBackgroundColour(bg_col);
      }
   }

   //! Synchronise current col used for line breaking
   void setCol(unsigned col_)
   {
      buffer_col = col_;
   }

   //! Control automatic line breaking
   void setBuffering(bool buffer_enable_)
   {
      flush();
      buffer_enable = buffer_enable_;
   }

   //! Flush any output that has been buffered
   void flush()
   {
      // TODO is the test required? flush elsewhere in this module
      //      is not conditional
      if(buffer_enable) flushOutputBuffer();
   }

   //! Control state of output streams
   void enableStream(unsigned index, bool next = true)
   {
      switch(index)
      {
      case 1: console_enable = next; break;
      case 2: printer_enable = next; break;
      case 3: memory_enable  = next; break;
      case 4: snooper_enable = next; break;

      default: assert(!"unexpected index"); break;
      }
   }

   //! Enable use of memory stream
   void enableMemoryStream(uint32_t ptr_, int16_t width_)
   {
      memory_len_ptr = ptr_;
      memory_ptr     = ptr_ + 2;
      memory_width   = width_;
      memory_enable  = true;

      memory.write16(memory_len_ptr, 0);
   }

   //! Read ZSCII character
   bool readChar(uint16_t& zscii, unsigned timeout_100ms, bool echo)
   {
      flushOutputBuffer();

      uint8_t ch;

      while(true)
      {
         if (console.read(ch, timeout_100ms * 100))
         {
            if (ch == '\b')
            {
               break;
            }
            else if ((ch == '\n') ||
                     (ch == 27) ||
                     ((ch >= 32) && (ch <= 126)) ||
                     ((ch >= 129) && (ch <= 254)))
            {
               if(echo)
               {
                  // Echo input to enabled output streams
                  if(console_enable)                       console.write(ch);
                  if(printer_enable && printer_echo_input) print(ch);
                  if(snooper_enable)                       snooper.write(ch);
                  if(trace_enable)                         trace_log.writePart("IN <= \"", ch, "\"\n");

                  if(ch == '\n') buffer_col = 1;
               }
               break;
            }
         }
         else
         {
            // Timeout
            return false;
         }
      }

      zscii = ch;
      return true;
   }

   //! Write ZSCII character (may be buffered)
   void writeChar(uint16_t zscii)
   {
      if(memory_enable)
      {
         memory.write16(memory_len_ptr, memory.read16(memory_len_ptr) + 1);
         memory.write8(memory_ptr++, zscii);
      }
      else if(buffer_enable)
      {
         sendBuffered(zscii);
      }
      else
      {
         send(zscii);
      }

      if(trace_enable)   trace_log.writePart("OUT => \"", char(zscii), "\"\n");
   }

   //! Delete the last character written
   void deleteChar()
   {
      send('\b');
      send(' ');
      send('\b');
   }

   //! Write signed integer value (may be buffered)
   void writeNumber(int16_t value_)
   {
      int32_t value = value_; // So that 32768 can be represented

      if(value < 0)
      {
         writeChar('-');
         value = -value;
      }

      int place = 10000;

      while((place > 1) && (value < place))
      {
         place = place / 10;
      }

      for(; place; place = place / 10)
      {
         unsigned digit = value / place;

         writeChar('0' + digit);

         value -= place * digit;
      }
   }

   void error(const std::string& text)
   {
      message(ERROR, text);
   }

   void warning(const std::string& text)
   {
      message(WARNING, text);
   }

   void info(const std::string& text)
   {
      message(INFO, text);
   }

   void trace(const std::string& string)
   {
      trace_log.write(string);
   }

   Log& getTrace()
   {
      return trace_log;
   }

private:
   static const unsigned MAX_WORD_LENGTH       = 16;
   static const unsigned PRINTER_NEWLINE_LIMIT = 3;

   //! Unbuffered write of a ZSCII character
   void send(uint16_t zscii)
   {
      if((zscii < ' ') || (zscii > 0x7E))
      {
         // Filter undefined output codes
         switch(zscii)
         {
         case '\0': return; // ignore
         case '\t': break;
         case '\n': break;
         case '\b': break;
         case '\r': zscii = '\n'; break;
         case 0x11: zscii = ' '; break; // v6 sentence space

         default:
            // "extra" characters
            if((zscii >= 155) && (zscii <=251))
            {
               zscii = '?';
               break;
            }
            return;
         }
      }

      uint8_t ch = uint8_t(zscii);
      if(ch == '\n')
         buffer_col = 1;
      else
         buffer_col++;

      if(console_enable) console.write(ch);
      if(printer_enable) print(ch);
   }

   //! Write raw string with no buffering
   void sendString(const char* s)
   {
      for(; *s; s++)
      {
         send(*s);
      }
   }

   //! Flush any output that has been buffered
   void flushOutputBuffer()
   {
      for(unsigned i = 0; i < buffer_size; i++)
      {
         send(buffer[i]);
      }

      buffer_size = 0;
   }

   //! Buffered write of an output character
   void sendBuffered(uint16_t zscii)
   {
      if((zscii == ' ') || (zscii == '\n') || (buffer_size == MAX_WORD_LENGTH))
      {
         if((buffer_col + buffer_size) > console.getAttr(Console::COLS))
         {
            send('\n');
         }

         flushOutputBuffer();

         send(zscii);
      }
      else
      {
         buffer[buffer_size++] = zscii;
      }
   }

   //! Send ZSCII character to the printer
   void print(uint16_t zscii)
   {
      // Filter repeated new-line
      if(zscii == '\r')
      {
         zscii = '\n';
      }
      if(zscii == '\n')
      {
         if(++printer_newline_count >= PRINTER_NEWLINE_LIMIT) return;
      }
      else
      {
         printer_newline_count = 0;
      }

      printer.write(zscii);
   }

   // Convert Z colour code to a console colour index
   bool convertCodeToConsoleColour(signed code, Console::Colour& colour)
   {
      // clang-format off
      switch(code)
      {
      case 0: return false; // No change
      case 1: colour = Console::DEFAULT; return true;
      case 2: colour = Console::BLACK;   return true;
      case 3: colour = Console::RED;     return true;
      case 4: colour = Console::GREEN;   return true;
      case 5: colour = Console::YELLOW;  return true;
      case 6: colour = Console::BLUE;    return true;
      case 7: colour = Console::MAGENTA; return true;
      case 8: colour = Console::CYAN;    return true;
      case 9: colour = Console::WHITE;   return true;
      default: break;
      }

      if(console_extended_colours_enable)
      {
         switch(code)
         {
         case -1: return false; // TODO colour of pixel under cursor
         case 10: colour = Console::LIGHT_GREY;  return true;
         case 11: colour = Console::MEDIUM_GREY; return true;
         case 12: colour = Console::DARK_GREY;   return true;
         default: break;
         }
      }
      // clang-format on

      return false;
   }

   //! Report a message
   void message(MessageLevel level, const std::string& text)
   {
      if(level < message_filter) return;

      // Start message on a new-line
      unsigned line, col;
      console.getCursorPos(line, col);
      if(col != 1)
      {
         send('\n');
      }

      // Identify message source
      console.setFontStyle(Console::FONT_STYLE_REVERSE);
      sendString("ZIF");
      console.setFontStyle(Console::FONT_STYLE_NORMAL);

      switch(level)
      {
      case INFO:    sendString(" "); break;
      case WARNING: sendString(" WRN: "); break;
      case ERROR:   sendString(" ERR: "); break;
      }

      sendString(text.c_str());
      send('\n');
   }

   // Console stream state
   bool     console_enable{true};
   bool     console_extended_colours_enable{false};
   uint8_t  console_text_style{0};
   Console& console;

   // Buffer used for automatic line breaks
   bool     buffer_enable{false};
   uint8_t  buffer_size{0};
   uint8_t  buffer[MAX_WORD_LENGTH];
   unsigned buffer_col{1};

   // Printer stream state
   bool     printer_enable{false};
   bool     printer_echo_input{false};
   unsigned printer_newline_count{1};
   Log      printer{"print.log"};

   // Memory stream state
   bool        memory_enable{false};
   int16_t     memory_width;
   uint32_t    memory_len_ptr;
   uint32_t    memory_ptr;
   IF::Memory& memory;

   // Input snooper stream state
   bool snooper_enable{false};
   Log  snooper{"key.log"};

   // Debug state
   bool trace_enable{false};
   Log  trace_log{"trace.log"};

   MessageLevel message_filter{ERROR};
};

} // namespace Z

#endif


text:
DEFAULT_HOST = ''
DEFAULT_PORT = 9000
DEFAULT_IDE_KEY = 'sublime.xdebug'

PACKAGE_PATH = None
PACKAGE_FOLDER = None

FILE_LOG_OUTPUT = 'Xdebug.log'
FILE_BREAKPOINT_DATA = 'Xdebug.breakpoints'
FILE_PACKAGE_SETTINGS = 'Xdebug.sublime-settings'
FILE_WATCH_DATA = 'Xdebug.expressions'

KEY_SETTINGS = 'settings'
KEY_XDEBUG = 'xdebug'

KEY_PATH_MAPPING = 'path_mapping'
KEY_URL = 'url'
KEY_IDE_KEY = 'ide_key'
KEY_HOST = 'host'
KEY_PORT = 'port'
KEY_MAX_CHILDREN = 'max_children'
KEY_MAX_DATA = 'max_data'
KEY_MAX_DEPTH = 'max_depth'
KEY_BREAK_ON_START = 'break_on_start'
KEY_BREAK_ON_EXCEPTION = 'break_on_exception'
KEY_CLOSE_ON_STOP = 'close_on_stop'
KEY_SUPER_GLOBALS = 'super_globals'
KEY_FULLNAME_PROPERTY = 'fullname_property'
KEY_HIDE_PASSWORD = 'hide_password'
KEY_PRETTY_OUTPUT = 'pretty_output'
KEY_LAUNCH_BROWSER = 'launch_browser'
KEY_BROWSER_NO_EXECUTE = 'browser_no_execute'
KEY_DISABLE_LAYOUT = 'disable_layout'
KEY_DEBUG_LAYOUT = 'debug_layout'

KEY_BREAKPOINT_GROUP = 'breakpoint_group'
KEY_BREAKPOINT_INDEX = 'breakpoint_index'
KEY_CONTEXT_GROUP = 'context_group'
KEY_CONTEXT_INDEX = 'context_index'
KEY_STACK_GROUP = 'stack_group'
KEY_STACK_INDEX = 'stack_index'
KEY_WATCH_GROUP = 'watch_group'
KEY_WATCH_INDEX = 'watch_index'

KEY_BREAKPOINT_CURRENT = 'breakpoint_current'
KEY_BREAKPOINT_DISABLED = 'breakpoint_disabled'
KEY_BREAKPOINT_ENABLED = 'breakpoint_enabled'
KEY_CURRENT_LINE = 'current_line'

KEY_PYTHON_PATH = 'python_path'
KEY_DEBUG = 'debug'

# Region scope sources
REGION_KEY_BREAKPOINT = 'xdebug_breakpoint'
REGION_KEY_CURRENT = 'xdebug_current'
REGION_KEY_DISABLED = 'xdebug_disabled'
REGION_SCOPE_BREAKPOINT = 'comment.line.xdebug.gutter.breakpoint'
REGION_SCOPE_CURRENT = 'string.quoted.xdebug.gutter.current'

# Window layout for debugging output
LAYOUT_DEBUG = {
    'cols': [0.0, 0.5, 1.0],
    'rows': [0.0, 0.7, 1.0],
    'cells': [
        [0, 0, 2, 1],
        [0, 1, 1, 2],
        [1, 1, 2, 2]
    ]
}
# Default single layout (similar to Alt+Shift+1)
LAYOUT_NORMAL = {
    'cols': [0.0, 1.0],
    'rows': [0.0, 1.0],
    'cells': [
        [0, 0, 1, 1]
    ]
}

RESTORE_LAYOUT = None
RESTORE_INDEX = None

SESSION_BUSY = False

SESSION = None
BREAKPOINT = {}
CONTEXT_DATA = {}
WATCH = []

BREAKPOINT_EXCEPTION = None
# Breakpoint line number in script being debugged
BREAKPOINT_ROW = None
# Placeholder for temporary breakpoint filename and line number
BREAKPOINT_RUN = None
# Will hold breakpoint line number to show for file which is being loaded
SHOW_ROW_ONLOAD = {}

CONFIG_PROJECT = None
CONFIG_PACKAGE = None
CONFIG_KEYS = [
    KEY_PATH_MAPPING,
    KEY_URL,
    KEY_IDE_KEY,
    KEY_HOST,
    KEY_PORT,
    KEY_MAX_CHILDREN,
    KEY_MAX_DATA,
    KEY_MAX_DEPTH,
    KEY_BREAK_ON_START,
    KEY_BREAK_ON_EXCEPTION,
    KEY_CLOSE_ON_STOP,
    KEY_SUPER_GLOBALS,
    KEY_FULLNAME_PROPERTY,
    KEY_HIDE_PASSWORD,
    KEY_PRETTY_OUTPUT,
    KEY_LAUNCH_BROWSER,
    KEY_BROWSER_NO_EXECUTE,
    KEY_DISABLE_LAYOUT,
    KEY_DEBUG_LAYOUT,
    KEY_BREAKPOINT_GROUP,
    KEY_BREAKPOINT_INDEX,
    KEY_CONTEXT_GROUP,
    KEY_CONTEXT_INDEX,
    KEY_STACK_GROUP,
    KEY_STACK_INDEX,
    KEY_WATCH_GROUP,
    KEY_WATCH_INDEX,
    KEY_BREAKPOINT_CURRENT,
    KEY_BREAKPOINT_DISABLED,
    KEY_BREAKPOINT_ENABLED,
    KEY_CURRENT_LINE,
    KEY_PYTHON_PATH,
    KEY_DEBUG
]


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

	var module = angular.module('app');

	/**
	 * Registra a url base e seus controller e html.
	 */
	module.config( configStates );

	configStates.$inject = [ '$stateProvider', '$urlRouterProvider' ];

	function configStates( $stateProvider, $urlRouterProvider ) {

		$urlRouterProvider
			.when('', '/home')
			.when('/', '/home')
			.otherwise('/home');

		var mainState = {
			abstract: true,
			views: {
				master: {
					controller: 'MainCtrl',
					controllerAs: 'main',
					templateUrl: '/app/main/template.html'
				}
			}
		};

		$stateProvider.state( 'main', mainState );
	}

}());


text:
<resources>
    <string name="app_name">LumberJill</string>
</resources>


text:
.. include global.rst

Base definitions
================

Basic utility stuff.

.. automodule:: pyvips.base
        :members:


text:
require 'socket'
require 'fcntl'
require 'timeout'
require 'server/starter/version'
require 'server/starter/helper'

class Server::Starter
  include Helper

  def initialize
    @signals_received  = []
    @current_worker    = nil
    @old_workers       = {}
    @last_restart_time = []
  end

  def start_server(opts)
    # symbolize keys
    opts = opts.map {|k, v| [k.to_sym, v] }.to_h
    opts[:interval] ||= 1
    opts[:signal_on_hup]  ||= 'TERM'
    opts[:signal_on_term] ||= 'TERM'
    opts[:backlog] ||= Socket::SOMAXCONN
    [:signal_on_hup, :signal_on_term].each do |key|
      # normalize to the one that can be passed to kill
      opts[key].tr!("a-z", "A-Z")
      opts[key].sub!(/^SIG/i, "")
    end

    # prepare args
    ports = Array(opts[:port])
    paths = Array(opts[:path])
    unless ports.empty? || paths.empty?
      croak "either of ``port'' or ``path'' option is mandatory"
    end
    unless opts[:exec] && opts[:exec].is_a?(Array)
      croak "mandatory option ``exec'' is missing or not an array"
    end

    # set envs
    ENV['ENVDIR'] = opts[:envdir] if opts[:envdir]
    ENV['ENABLE_AUTO_RESTART'] = opts[:enable_auto_restart] ? '1' : nil
    ENV['KILL_OLD_DELAY'] = opts[:kill_old_delay].to_s if opts[:kill_old_delay]
    ENV['AUTO_RESTART_INTERVAL'] = opts[:auto_restart_interval].to_s if opts[:auto_restart_interval]

    # open pid file
    if opts[:pid_file]
      File.open(opts[:pid_file], "w") do |fh|
        fh.puts $$
      end rescue die "failed to open file:#{opts[:pid_file]}"
      at_exit { File.unlink opts[:pid_file] rescue nil }
    end

    # open log file
    if opts[:log_file]
      File.open(opts[:log_file], "a") do |fh|
        $stdout.flush
        $stderr.flush
        $stdout.reopen(fh) rescue die "failed to reopen STDOUT to file"
        $stderr.reopen(fh) rescue die "failed to reopen STDERR to file"
      end
    end

    # create guard that removes the status file
    if opts[:status_file]
      at_exit { File.unlink opts[:status_file] rescue nil }
    end

    $stderr.puts "start_server (pid:#{$$}) starting now..."

    # start listening, setup envvar
    socks = []
    sockenvs = []
    ports.each do |port|
      sock = nil
      begin
        if port =~ /^\s*(\d+)\s*$/
          # sock = Socket.new(:INET, :STREAM)
          # addr = Socket.pack_sockaddr_in(port, '0.0.0.0')
          # sock.setsockopt(:SOCKET, :REUSEADDR, true)
          # sock.bind(addr)
          # sock.listen(opts[:backlog])
          sock = TCPServer.new("0.0.0.0", port)
          sock.setsockopt(:SOCKET, :REUSEADDR, true)
          sock.listen(opts[:backlog])
        elsif port =~ /^\s*(.*)\s*:\s*(\d+)\s*$/
          _bind, _port = $1, $2
          sock = TCPServer.new(_bind, _port)
          sock.setsockopt(:SOCKET, :REUSEADDR, true)
          sock.listen(opts[:backlog])
        else
          croak "invalid ``port'' value:#{port}"
        end
      rescue
        die "failed to listen to #{port}"
      end
      sock.fcntl(Fcntl::F_SETFD, 0) rescue die "fcntl(F_SETFD, 0) failed"
      sockenvs.push "#{port}=#{sock.fileno}"
      socks.push sock
    end

    at_exit {
      paths.each do |path|
        File.symlink?(path) and File.unlink(path) rescue nil
      end
    }
    paths.each do |path|
      if File.symlink?(path)
        warn "removing existing socket file:#{path}"
        File.unlink(path) rescue die "failed to remove existing socket file:#{path}"
      end
      File.unlink(path) rescue nil
      saved_umask = File.umask(0)
      begin
        sock = UNIXServer.new(path)
        sock.listen(opts[:backlog])
      rescue
        die "failed to listen to file #{path}"
      end
      sock.fcntl(Fcntl::F_SETFD, 0) rescue die "fcntl(F_SETFD, 0) failed"
      sockenvs.push "#{path}=#{sock.fileno}"
      socks.push sock
    end
    ENV['SERVER_STARTER_PORT'] = sockenvs.join(";")
    ENV['SERVER_STARTER_GENERATION'] = "0"

    # setup signal handlers
    %w(INT TERM HUP ALRM).each do |signal|
      Signal.trap(signal) {
        @signals_received.push(signal)
        @signal_wait_thread.kill if @signal_wait_thread
      }
    end
    Signal.trap('PIPE') { 'IGNORE' }

    # setup status monitor
    update_status =
      if opts[:status_file]
        Proc.new {
          tmpfn = "#{opts[:status_file]}.#{$$}"
          File.open(tmpfn, "w") do |tmpfh|
            gen_pids = @current_worker ?
              {ENV['SERVER_STARTER_GENERATION'] => @current_worker} :
              {}
            @old_workers.each {|pid, gen| gen_pids[gen] = pid }
            gen_pids.keys.map(&:to_i).sort.each {|gen| tmpfh.puts "#{gen}:#{gen_pids[gen.to_s]}" }
          end rescue die "failed to create temporary file:#{tmpfn}"
          begin
            File.rename(tmpfn, opts[:status_file])
          rescue
            die "failed to rename #{tmpfn} to #{opts[:status_file]}"
          end
        }
      else
        Proc.new {}
      end

    # setup the start_worker function
    start_worker = Proc.new {
      pid = nil
      while true
        ENV['SERVER_STARTER_GENERATION'] = (ENV['SERVER_STARTER_GENERATION'].to_i + 1).to_s
        begin
          pid = fork
        rescue
          die "fork(2) failed"
        end
        if pid.nil? # child process
          args = Array(opts[:exec]).dup
          if opts[:dir]
            Dir.chdir opts[:dir] rescue die "failed to chdir"
          end
          begin
            bundler_with_clean_env do
              args << {:close_others => false}
              exec(*args)
            end
          rescue
            $stderr.puts "failed to exec #{args[0]}:#{$!.class} #{$!.message}"
            exit(255)
          end
        end
        $stderr.puts "starting new worker #{pid}"
        sleep opts[:interval]
        break if (@signals_received - [:HUP]).size > 0
        break if Process.waitpid(pid, Process::WNOHANG).nil?
        $stderr.puts "new worker #{pid} seems to have failed to start, exit status:#{$?.exitstatus}"
      end
      # ready, update the environment
      @current_worker = pid
      @last_restart_time = Time.now
      update_status.call
    }

    # setup the wait function
    wait = Proc.new {
      flags = @signals_received.empty? ? 0 : Process::WNOHANG
      r = nil
      # waitpid can not get EINTR on receiving signal, so create a thread,
      # and kill the thread on receiving signal to exit blocking
      #
      # there is another way to use wait3 which raises EINTR on receiving signal,
      # but proc-wait3 gem requires gcc, etc to compile its C codes.
      #
      #     require 'proc/wait3'
      #     begin
      #       rusage = Process.wait3(flags)
      #       r = [rusage.pid, rusage.status] if rusage
      #     rescue Errno::EINTR
      #       sleep 0.1 # need to wait until Signal.trap finishes its operation, terrible
      #       nil
      #     end
      @signal_wait_thread = Thread.start do
        if flags != 0 && ENV['ENABLE_AUTO_RESTART']
          begin
            Timeout.timeout(1) do
              pid = Process.waitpid(-1, flags)
              r = [pid, $?.exitstatus] if pid
            end
          rescue Timeout::Error
            # Process.kill('ALRM', Process.pid)
            Thread.exit
          end
        else
          pid = Process.waitpid(-1, flags)
          r = [pid, $?.exitstatus] if pid
        end
      end
      @signal_wait_thread.join
      @signal_wait_thread = nil
      r
    }

    # setup the cleanup function
    cleanup = Proc.new {|sig|
      term_signal = sig == 'TERM' ? opts[:signal_on_term] : 'TERM'
      @old_workers[@current_worker] = ENV['SERVER_STARTER_GENERATION']
      @current_worker = nil
      $stderr.print "received #{sig}, sending #{term_signal} to all workers:",
        @old_workers.keys.sort.join(','), "\n"
      @old_workers.keys.sort.each {|pid| Process.kill(term_signal, pid) }
      while true
        died_worker = Process.waitpid(-1, Process::WNOHANG)
        if died_worker
          $stderr.puts "worker #{died_worker} died, status:#{$?.exitstatus}"
          @old_workers.delete(died_worker)
          update_status.call
          break if @old_workers.empty?
        end
      end
      $stderr.puts "exiting"
    }

    # the main loop
    start_worker.call
    while true
      # wait for next signal (or when auto-restart becomes necessary)
      r = wait.call
      # reload env if necessary
      loaded_env = _reload_env
      ENV['AUTO_RESTART_INTERVAL'] ||= "360" if ENV['ENABLE_AUTO_RESTART']
      with_local_env(loaded_env) do
        # restart if worker died
        if r
          died_worker, status = r
          if died_worker == @current_worker
            $stderr.puts "worker #{died_worker} died unexpectedly with status:#{status}, restarting"
            start_worker.call
          else
            $stderr.puts "old worker #{died_worker} died, status:#{status}"
            @old_workers.delete(died_worker)
            update_status.call
          end
        end
        # handle signals
        restart = nil
        while !@signals_received.empty?
          sig = @signals_received.shift
          if sig == 'HUP'
            $stderr.puts "received HUP, spawning a new worker"
            restart = true
            break
          elsif sig == 'ALRM'
            # skip
          else
            return cleanup.call(sig)
          end
        end
        if !restart && ENV['ENABLE_AUTO_RESTART']
          auto_restart_interval = ENV['AUTO_RESTART_INTERVAL'].to_i
          elapsed_since_restart = Time.now - @last_restart_time
          if elapsed_since_restart >= auto_restart_interval && @old_workers.empty?
            $stderr.puts "autorestart triggered (interval=#{auto_restart_interval})"
            restart = true
          elsif elapsed_since_restart >= auto_restart_interval * 2
            $stderr.puts "autorestart triggered (forced, interval=#{auto_restart_interval})"
            restart = true
          end
        end
        # restart if requested
        if restart
          @old_workers[@current_worker] = ENV['SERVER_STARTER_GENERATION']
          start_worker.call
          $stderr.print "new worker is now running, sending #{opts[:signal_on_hup]} to old workers:"
          if !@old_workers.empty?
            $stderr.puts @old_workers.keys.sort.join(',')
          else
            $stderr.puts "none"
          end
          kill_old_delay = ENV['KILL_OLD_DELAY'] ? ENV['KILL_OLD_DELAY'].to_i : ENV['ENABLE_AUTO_RESTART'] ? 5 : 0
          if kill_old_delay != 0
            $stderr.puts "sleeping #{kill_old_delay} secs before killing old workers"
            sleep kill_old_delay
          end
          $stderr.puts "killing old workers"
          @old_workers.keys.sort.each {|pid| Process.kill(opts[:signal_on_hup], pid) }
        end
      end
    end

    die "unreachable"
  end

  def restart_server(opts)
    unless opts[:pid_file] && opts[:status_file]
      die "--restart option requires --pid-file and --status-file to be set as well"
    end

    # get first pid
    pid = Proc.new {
      begin
        File.open(opts[:pid_file]) do |fd|
          line = fd.gets
          line.chomp
        end
      rescue
        die "failed to open file:#{opts[:pid_file]}"
      end
    }.call

    # function that returns a list of active generations in sorted order
    get_generations = Proc.new {
      begin
        File.readlines(opts[:status_file]).map do |line|
          line =~ /^(\d+):/ ? $1 : nil
        end.compact.map(&:to_i).sort.uniq
      rescue
        die "failed to open file:#{opts[:status_file]}"
      end
    }

    # wait for this generation
    wait_for = Proc.new {
      gens = get_generations.call
      die "no active process found in the status file" if gens.empty?
      gens.last.to_i + 1
    }.call

    # send HUP
    Process.kill('HUP', pid.to_i) rescue die "failed to send SIGHUP to the server process"

    # wait for the generation
    while true
      gens = get_generations.call
      break if gens.size == 1 && gens[0].to_i == wait_for.to_i
      sleep 1
    end
  end

  def server_ports
    die "no environment variable SERVER_STARTER_PORT. Did you start the process using server_starter?" unless ENV['SERVER_STARTER_PORT']
    ENV['SERVER_STARTER_PORT'].split(';').map do |_|
      _.split('=', 2)
    end.to_h
  end

  def _reload_env
    dn = ENV['ENVDIR']
    return {} if dn.nil? or !File.exist?(dn)
    env = {}
    Dir.open(dn) do |d|
      while n = d.read
        next if n =~ /^\./
        File.open("#{dn}/#{n}") do |fh|
          first_line = fh.gets.chomp
          env[n] = first_line if first_line
        end
      end
    end
    env
  end
end

__END__

package Server::Starter;

use 5.008;
use strict;
use warnings;
use Carp;
use Fcntl;
use IO::Handle;
use IO::Socket::INET;
use IO::Socket::UNIX;
use List::MoreUtils qw(uniq);
use POSIX qw(:sys_wait_h);
use Proc::Wait3;
use Scope::Guard;

use Exporter qw(import);

our $VERSION = '0.19';
our @EXPORT_OK = qw(start_server restart_server server_ports);

my @signals_received;

sub start_server {
    my $opts = {
        (@_ == 1 ? @$_[0] : @_),
    };
    $opts->{interval} = 1
        if not defined $opts->{interval};
    $opts->{signal_on_hup}  ||= 'TERM';
    $opts->{signal_on_term} ||= 'TERM';
    $opts->{backlog} ||= Socket::SOMAXCONN();
    for ($opts->{signal_on_hup}, $opts->{signal_on_term}) {
        # normalize to the one that can be passed to kill
        tr/a-z/A-Z/;
        s/^SIG//i;
    }

    # prepare args
    my $ports = $opts->{port};
    my $paths = $opts->{path};
    croak "either of ``port'' or ``path'' option is mandatory\n"
        unless $ports || $paths;
    $ports = [ $ports ]
        if ! ref $ports && defined $ports;
    $paths = [ $paths ]
        if ! ref $paths && defined $paths;
    croak "mandatory option ``exec'' is missing or is not an arrayref\n"
        unless $opts->{exec} && ref $opts->{exec} eq 'ARRAY';

    # set envs
    $ENV{ENVDIR} = $opts->{envdir}
        if defined $opts->{envdir};
    $ENV{ENABLE_AUTO_RESTART} = $opts->{enable_auto_restart}
        if defined $opts->{enable_auto_restart};
    $ENV{KILL_OLD_DELAY} = $opts->{kill_old_delay}
        if defined $opts->{kill_old_delay};
    $ENV{AUTO_RESTART_INTERVAL} = $opts->{auto_restart_interval}
        if defined $opts->{auto_restart_interval};

    # open pid file
    my $pid_file_guard = sub {
        return unless $opts->{pid_file};
        open my $fh, '>', $opts->{pid_file}
            or die "failed to open file:$opts->{pid_file}: $!";
        print $fh "$$\n";
        close $fh;
        return Scope::Guard->new(
            sub {
                unlink $opts->{pid_file};
            },
        );
    }->();

    # open log file
    if ($opts->{log_file}) {
        open my $fh, '>>', $opts->{log_file}
            or die "failed to open log file:$opts->{log_file}: $!";
        STDOUT->flush;
        STDERR->flush;
        open STDOUT, '>&', $fh
            or die "failed to dup STDOUT to file: $!";
        open STDERR, '>&', $fh
            or die "failed to dup STDERR to file: $!";
        close $fh;
    }

    # create guard that removes the status file
    my $status_file_guard = $opts->{status_file} && Scope::Guard->new(
        sub {
            unlink $opts->{status_file};
        },
    );

    print STDERR "start_server (pid:$$) starting now...\n";

    # start listening, setup envvar
    my @sock;
    my @sockenv;
    for my $port (@$ports) {
        my $sock;
        if ($port =~ /^\s*(\d+)\s*$/) {
            $sock = IO::Socket::INET->new(
                Listen    => $opts->{backlog},
                LocalPort => $port,
                Proto     => 'tcp',
                ReuseAddr => 1,
            );
        } elsif ($port =~ /^\s*(.*)\s*:\s*(\d+)\s*$/) {
            $port = "$1:$2";
            $sock = IO::Socket::INET->new(
                Listen    => $opts->{backlog},
                LocalAddr => $port,
                Proto     => 'tcp',
                ReuseAddr => 1,
            );
        } else {
            croak "invalid ``port'' value:$port\n"
        }
        die "failed to listen to $port:$!"
            unless $sock;
        fcntl($sock, F_SETFD, my $flags = '')
                or die "fcntl(F_SETFD, 0) failed:$!";
        push @sockenv, "$port=" . $sock->fileno;
        push @sock, $sock;
    }
    my $path_remove_guard = Scope::Guard->new(
        sub {
            -S $_ and unlink $_
                for @$paths;
        },
    );
    for my $path (@$paths) {
        if (-S $path) {
            warn "removing existing socket file:$path";
            unlink $path
                or die "failed to remove existing socket file:$path:$!";
        }
        unlink $path;
        my $saved_umask = umask(0);
        my $sock = IO::Socket::UNIX->new(
            Listen => $opts->{backlog},
            Local  => $path,
        ) or die "failed to listen to file $path:$!";
        umask($saved_umask);
        fcntl($sock, F_SETFD, my $flags = '')
            or die "fcntl(F_SETFD, 0) failed:$!";
        push @sockenv, "$path=" . $sock->fileno;
        push @sock, $sock;
    }
    $ENV{SERVER_STARTER_PORT} = join ";", @sockenv;
    $ENV{SERVER_STARTER_GENERATION} = 0;

    # setup signal handlers
    $SIG{$_} = sub {
        push @signals_received, $_[0];
    } for (qw/INT TERM HUP ALRM/);
    $SIG{PIPE} = 'IGNORE';

    # setup status monitor
    my ($current_worker, %old_workers, $last_restart_time);
    my $update_status = $opts->{status_file}
        ? sub {
            my $tmpfn = "$opts->{status_file}.$$";
            open my $tmpfh, '>', $tmpfn
                or die "failed to create temporary file:$tmpfn:$!";
            my %gen_pid = (
                ($current_worker
                 ? ($ENV{SERVER_STARTER_GENERATION} => $current_worker)
                 : ()),
                map { $old_workers{$_} => $_ } keys %old_workers,
            );
            print $tmpfh "$_:$gen_pid{$_}\n"
                for sort keys %gen_pid;
            close $tmpfh;
            rename $tmpfn, $opts->{status_file}
                or die "failed to rename $tmpfn to $opts->{status_file}:$!";
        } : sub {
        };

    # setup the start_worker function
    my $start_worker = sub {
        my $pid;
        while (1) {
            $ENV{SERVER_STARTER_GENERATION}++;
            $pid = fork;
            die "fork(2) failed:$!"
                unless defined $pid;
            if ($pid == 0) {
                my @args = @{$opts->{exec}};
                # child process
                if (defined $opts->{dir}) {
                    chdir $opts->{dir} or die "failed to chdir:$!";
                }
                { exec { $args[0] } @args };
                print STDERR "failed to exec $args[0]$!";
                exit(255);
            }
            print STDERR "starting new worker $pid\n";
            sleep $opts->{interval};
            if ((grep { $_ ne 'HUP' } @signals_received)
                    || waitpid($pid, WNOHANG) <= 0) {
                last;
            }
            print STDERR "new worker $pid seems to have failed to start, exit status:$?\n";
        }
        # ready, update the environment
        $current_worker = $pid;
        $last_restart_time = time;
        $update_status->();
    };

    # setup the wait function
    my $wait = sub {
        my $block = @signals_received == 0;
        my @r;
        if ($block && $ENV{ENABLE_AUTO_RESTART}) {
            alarm(1);
            @r = wait3($block);
            alarm(0);
        } else {
            @r = wait3($block);
        }
        return @r;
    };

    # setup the cleanup function
    my $cleanup = sub {
        my $sig = shift;
        my $term_signal = $sig eq 'TERM' ? $opts->{signal_on_term} : 'TERM';
        $old_workers{$current_worker} = $ENV{SERVER_STARTER_GENERATION};
        undef $current_worker;
        print STDERR "received $sig, sending $term_signal to all workers:",
            join(',', sort keys %old_workers), "\n";
        kill $term_signal, $_
            for sort keys %old_workers;
        while (%old_workers) {
            if (my @r = wait3(1)) {
                my ($died_worker, $status) = @r;
                print STDERR "worker $died_worker died, status:$status\n";
                delete $old_workers{$died_worker};
                $update_status->();
            }
        }
        print STDERR "exiting\n";
    };

    # the main loop
    $start_worker->();
    while (1) {
        # wait for next signal (or when auto-restart becomes necessary)
        my @r = $wait->();
        # reload env if necessary
        my %loaded_env = _reload_env();
        my @loaded_env_keys = keys %loaded_env;
        local @ENV{@loaded_env_keys} = map { $loaded_env{$_} } (@loaded_env_keys);
        $ENV{AUTO_RESTART_INTERVAL} ||= 360
            if $ENV{ENABLE_AUTO_RESTART};
        # restart if worker died
        if (@r) {
            my ($died_worker, $status) = @r;
            if ($died_worker == $current_worker) {
                print STDERR "worker $died_worker died unexpectedly with status:$status, restarting\n";
                $start_worker->();
            } else {
                print STDERR "old worker $died_worker died, status:$status\n";
                delete $old_workers{$died_worker};
                $update_status->();
            }
        }
        # handle signals
        my $restart;
        while (@signals_received) {
            my $sig = shift @signals_received;
            if ($sig eq 'HUP') {
                print STDERR "received HUP, spawning a new worker\n";
                $restart = 1;
                last;
            } elsif ($sig eq 'ALRM') {
                # skip
            } else {
                return $cleanup->($sig);
            }
        }
        if (! $restart && $ENV{ENABLE_AUTO_RESTART}) {
            my $auto_restart_interval = $ENV{AUTO_RESTART_INTERVAL};
            my $elapsed_since_restart = time - $last_restart_time;
            if ($elapsed_since_restart >= $auto_restart_interval && ! %old_workers) {
                print STDERR "autorestart triggered (interval=$auto_restart_interval)\n";
                $restart = 1;
            } elsif ($elapsed_since_restart >= $auto_restart_interval * 2) {
                print STDERR "autorestart triggered (forced, interval=$auto_restart_interval)\n";
                $restart = 1;
            }
        }
        # restart if requested
        if ($restart) {
            $old_workers{$current_worker} = $ENV{SERVER_STARTER_GENERATION};
            $start_worker->();
            print STDERR "new worker is now running, sending $opts->{signal_on_hup} to old workers:";
            if (%old_workers) {
                print STDERR join(',', sort keys %old_workers), "\n";
            } else {
                print STDERR "none\n";
            }
            my $kill_old_delay = defined $ENV{KILL_OLD_DELAY} ? $ENV{KILL_OLD_DELAY} : $ENV{ENABLE_AUTO_RESTART} ? 5 : 0;
            if ($kill_old_delay != 0) {
                print STDERR "sleeping $kill_old_delay secs before killing old workers\n";
                sleep $kill_old_delay;
            }
            print STDERR "killing old workers\n";
            kill $opts->{signal_on_hup}, $_
                for sort keys %old_workers;
        }
    }

    die "unreachable";
}

sub restart_server {
    my $opts = {
        (@_ == 1 ? @$_[0] : @_),
    };
    die "--restart option requires --pid-file and --status-file to be set as well\n"
        unless $opts->{pid_file} && $opts->{status_file};

    # get pid
    my $pid = do {
        open my $fh, '<', $opts->{pid_file}
            or die "failed to open file:$opts->{pid_file}:$!";
        my $line = <$fh>;
        chomp $line;
        $line;
    };

    # function that returns a list of active generations in sorted order
    my $get_generations = sub {
        open my $fh, '<', $opts->{status_file}
            or die "failed to open file:$opts->{status_file}:$!";
        uniq sort { $a <=> $b } map { /^(\d+):/ ? ($1) : () } <$fh>;
    };

    # wait for this generation
    my $wait_for = do {
        my @gens = $get_generations->()
            or die "no active process found in the status file";
        pop(@gens) + 1;
    };

    # send HUP
    kill 'HUP', $pid
        or die "failed to send SIGHUP to the server process:$!";

    # wait for the generation
    while (1) {
        my @gens = $get_generations->();
        last if scalar(@gens) == 1 && $gens[0] == $wait_for;
        sleep 1;
    }
}

sub server_ports {
    die "no environment variable SERVER_STARTER_PORT. Did you start the process using server_starter?",
        unless $ENV{SERVER_STARTER_PORT};
    my %ports = map {
        +(split /=/, $_, 2)
    } split /;/, $ENV{SERVER_STARTER_PORT};
    \%ports;
}

sub _reload_env {
    my $dn = $ENV{ENVDIR};
    return if !defined $dn or !-d $dn;
    my $d;
    opendir($d, $dn) or return;
    my %env;
    while (my $n = readdir($d)) {
        next if $n =~ /^\./;
        open my $fh, '<', "$dn/$n" or next;
        chomp(my $v = <$fh>);
        $env{$n} = $v if defined $v;
    }
    return %env;
}

1;


text: - add more test cases


text:
package example

import akka.actor._
import Messages._

object HelloWorld {

  def main(args: Array[String]) {
    val system = ActorSystem("HelloWorld")
    val bob = system.actorOf(Props[Bob])
    system.awaitTermination()
  }

}

object Messages {
  case class Hi_I_am(name: String)
  case class Say(message: String)
}

class Bob extends Actor with ActorLogging {

  val alice = context.actorOf(Props[Alice])

  override def preStart() {
    log.info("in preStart, saying hi to Alice")
    alice ! Hi_I_am("bob")
  }

  def receive: Receive = {
    case Say(msg) =>
      log.info(s"Alice said '$msg'")
      context.system.shutdown()
  }

}

class Alice extends Actor with ActorLogging {

  def receive: Receive = {
    case Hi_I_am(name) =>
      sender ! Say(s"Hello $name!")
      //log.info(s"Alice's path: ${self.path}")
  }
}


text:
package net.nemerosa.ontrack.boot.ui;

import net.nemerosa.ontrack.common.Document;
import net.nemerosa.ontrack.model.Ack;
import net.nemerosa.ontrack.model.form.Form;
import net.nemerosa.ontrack.model.security.PromotionLevelCreate;
import net.nemerosa.ontrack.model.security.SecurityService;
import net.nemerosa.ontrack.model.structure.*;
import net.nemerosa.ontrack.ui.controller.AbstractResourceController;
import net.nemerosa.ontrack.ui.resource.Link;
import net.nemerosa.ontrack.ui.resource.Resource;
import net.nemerosa.ontrack.ui.resource.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

import static net.nemerosa.ontrack.ui.support.UIUtils.setupDefaultImageCache;
import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on;

@RestController
@RequestMapping("/rest/structure")
public class PromotionLevelController extends AbstractResourceController {

    private final StructureService structureService;
    private final SecurityService securityService;

    @Autowired
    public PromotionLevelController(StructureService structureService, SecurityService securityService) {
        this.structureService = structureService;
        this.securityService = securityService;
    }

    // Promotion levels

    @RequestMapping(value = "branches/{branchId}/promotionLevels", method = RequestMethod.GET)
    public Resources<PromotionLevel> getPromotionLevelListForBranch(@PathVariable ID branchId) {
        Branch branch = structureService.getBranch(branchId);
        return Resources.of(
                structureService.getPromotionLevelListForBranch(branchId),
                uri(on(PromotionLevelController.class).getPromotionLevelListForBranch(branchId))
        )
                // Create
                .with(
                        Link.CREATE,
                        uri(on(PromotionLevelController.class).newPromotionLevelForm(branchId)),
                        securityService.isProjectFunctionGranted(branch.getProject().id(), PromotionLevelCreate.class)
                )
                ;
    }

    @RequestMapping(value = "branches/{branchId}/promotionLevels/reorder", method = RequestMethod.PUT)
    public Resources<PromotionLevel> reorderPromotionLevelListForBranch(@PathVariable ID branchId, @RequestBody Reordering reordering) {
        // Reordering
        structureService.reorderPromotionLevels(branchId, reordering);
        // OK
        return getPromotionLevelListForBranch(branchId);
    }

    @RequestMapping(value = "branches/{branchId}/promotionLevels/create", method = RequestMethod.GET)
    public Form newPromotionLevelForm(@PathVariable ID branchId) {
        structureService.getBranch(branchId);
        return PromotionLevel.form();
    }

    @RequestMapping(value = "branches/{branchId}/promotionLevels/create", method = RequestMethod.POST)
    public PromotionLevel newPromotionLevel(@PathVariable ID branchId, @RequestBody @Valid NameDescription nameDescription) {
        // Gets the holding branch
        Branch branch = structureService.getBranch(branchId);
        // Creates a new promotion level
        PromotionLevel promotionLevel = PromotionLevel.of(branch, nameDescription);
        // Saves it into the repository
        promotionLevel = structureService.newPromotionLevel(promotionLevel);
        // OK
        return promotionLevel;
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}", method = RequestMethod.GET)
    public PromotionLevel getPromotionLevel(@PathVariable ID promotionLevelId) {
        return structureService.getPromotionLevel(promotionLevelId);
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}/update", method = RequestMethod.GET)
    public Form updatePromotionLevelForm(@PathVariable ID promotionLevelId) {
        return structureService.getPromotionLevel(promotionLevelId).asForm();
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}/update", method = RequestMethod.PUT)
    public PromotionLevel updatePromotionLevel(@PathVariable ID promotionLevelId, @RequestBody @Valid NameDescription nameDescription) {
        // Gets from the repository
        PromotionLevel promotionLevel = structureService.getPromotionLevel(promotionLevelId);
        // Updates
        promotionLevel = promotionLevel.update(nameDescription);
        // Saves in repository
        structureService.savePromotionLevel(promotionLevel);
        // As resource
        return promotionLevel;
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}", method = RequestMethod.DELETE)
    public Ack deletePromotionLevel(@PathVariable ID promotionLevelId) {
        return structureService.deletePromotionLevel(promotionLevelId);
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}/image", method = RequestMethod.GET)
    public Document getPromotionLevelImage_(HttpServletResponse response, @PathVariable ID promotionLevelId) {
        Document document = structureService.getPromotionLevelImage(promotionLevelId);
        setupDefaultImageCache(response, document);
        return document;
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}/image", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.ACCEPTED)
    public void setPromotionLevelImage(@PathVariable ID promotionLevelId, @RequestParam MultipartFile file) throws IOException {
        structureService.setPromotionLevelImage(promotionLevelId, new Document(
                file.getContentType(),
                file.getBytes()
        ));
    }

    @RequestMapping(value = "promotionLevels/{promotionLevelId}/runs", method = RequestMethod.GET)
    public Resource<PromotionRunView> getPromotionRunView(@PathVariable ID promotionLevelId) {
        return Resource.of(
                structureService.getPromotionRunView(structureService.getPromotionLevel(promotionLevelId)),
                uri(on(PromotionLevelController.class).getPromotionRunView(promotionLevelId))
        );
    }

    /**
     * Bulk update of all promotion levels in other projects/branches and in predefined promotion levels,
     * following the model designed by the promotion level ID.
     *
     * @param promotionLevelId ID of the promotion level model
     * @return Result of the update
     */
    @PutMapping("promotionLevels/{promotionLevelId}/bulk")
    public Ack bulkUpdate(@PathVariable ID promotionLevelId) {
        return structureService.bulkUpdatePromotionLevels(promotionLevelId);
    }

}


text:
from pytest_djangoapp import configure_djangoapp_plugin

pytest_plugins = configure_djangoapp_plugin(
    admin_contrib=True,
)


text:
<?php
  include_once('../form_orders/form_orders.php');
?>


text:
#ifndef configment_platform_compat_h_20130328
#define configment_platform_compat_h_20130328

namespace configment
    {
    namespace platform
    {

        //
        // Explicit conversion from expression to bool.
        //
        template< typename T > inline bool coerce_to_bool(const T& value) throw()
        {
            #if defined( _MSC_VER )
            //
            // MSVC11 Warning 4800:
            // forcing value to bool 'true' or 'false' (performance warning)
            // http://msdn.microsoft.com/en-us/library/b6801kcy.aspx
            //
            return value != static_cast<T>(0);
            //
            #else
            // Everything else: just let the language do the cast:
            return static_cast<bool>(value);
            #endif
        }

    } // namespace configment::platform
} // namespace configment

#endif // configment_platform_compat_h_20130328


text:
module Azure::ARM::Network
  module Models
    #
    # Defines values for ExpressRouteCircuitPeeringState
    #
    module ExpressRouteCircuitPeeringState
      Disabled = "Disabled"
      Enabled = "Enabled"
    end
  end
end


text:
<?php

/**
 * This file is part of the Branches package.
 * For the full license information, see the file LICENSE.
 *
 * @author   Alberto Piu <alberteddu@gmail.com>
 * @license  MIT
 */
namespace Branches\Node;

/**
 * Class NodeType.
 */
abstract class NodeType
{
    const POST = 'post';
    const FILE = 'file';
}


text:
import { SkyVisualTest } from '../../../config/utils/visual-test-commands';

describe('Alert', () => {

  it('should match previous alert screenshot', () => {
    return SkyVisualTest
      .setupTest('alert')
      .then(() => {
        return SkyVisualTest.compareScreenshot({
          screenshotName: 'alert',
          selector: '#screenshot-alert'
        });
      });

  });
});


text:
using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

using PHP.Core.AST;
using PHP.Core.Emit;
using PHP.Core.Parsers;
using PHP.Core.Reflection;
using System.IO;

namespace PHP.Core.Compiler.AST
{
    partial class NodeCompilers
    {
        #region NewEx

        [NodeCompiler(typeof(NewEx))]
        sealed class NewExCompiler : VarLikeConstructUseCompiler<NewEx>
        {
            private DRoutine constructor;
            private bool runtimeVisibilityCheck;
            private bool typeArgsResolved;

            public override Evaluation Analyze(NewEx node, Analyzer analyzer, ExInfoFromParent info)
            {
                Debug.Assert(node.IsMemberOf == null);

                access = info.Access;

                this.typeArgsResolved = TypeRefHelper.Analyze(node.ClassNameRef, analyzer);

                DType type = TypeRefHelper.ResolvedType(node.ClassNameRef);
                RoutineSignature signature;

                if (typeArgsResolved)
                    analyzer.AnalyzeConstructedType(type);

                if (type != null)
                {
                    bool error_reported = false;

                    // make checks if we are sure about character of the type:
                    if (type.IsIdentityDefinite)
                    {
                        if (type.IsAbstract || type.IsInterface)
                        {
                            analyzer.ErrorSink.Add(Errors.AbstractClassOrInterfaceInstantiated, analyzer.SourceUnit,
                                node.Span, type.FullName);
                            error_reported = true;
                        }
                    }

                    // disallow instantiation of Closure
                    if (type.RealType == typeof(PHP.Library.SPL.Closure))
                    {
                        analyzer.ErrorSink.Add(Errors.ClosureInstantiated, analyzer.SourceUnit, node.Span, type.FullName);
                        error_reported = true;
                    }

                    // type name resolved, look the constructor up:
                    constructor = analyzer.ResolveConstructor(type, node.Span, analyzer.CurrentType, analyzer.CurrentRoutine,
                      out runtimeVisibilityCheck);

                    if (constructor.ResolveOverload(analyzer, node.CallSignature, node.Span, out signature) == DRoutine.InvalidOverloadIndex)
                    {
                        if (!error_reported)
                        {
                            analyzer.ErrorSink.Add(Errors.ClassHasNoVisibleCtor, analyzer.SourceUnit, node.Span, type.FullName);
                        }
                    }
                }
                else
                {
                    signature = UnknownSignature.Default;
                }

                CallSignatureHelpers.Analyze(node.CallSignature, analyzer, signature, info, false);

                return new Evaluation(node);
            }

            public override bool IsDeeplyCopied(NewEx node, CopyReason reason, int nestingLevel)
            {
                return false;
            }

            public override PhpTypeCode Emit(NewEx node, CodeGenerator codeGenerator)
            {
                Statistics.AST.AddNode("NewEx");

                PhpTypeCode result;
                var newextype = TypeRefHelper.ResolvedType(node.ClassNameRef);

                if (newextype != null && typeArgsResolved)
                {
                    // constructor is resolvable (doesn't mean that known) //

                    result = newextype.EmitNew(codeGenerator, null, constructor, node.CallSignature, runtimeVisibilityCheck);
                }
                else
                {
                    // constructor is unresolvable (a variable is used in type name => type is unresolvable as well) //

                    codeGenerator.EmitNewOperator(null, node.ClassNameRef, null, node.CallSignature);
                    result = PhpTypeCode.Object;
                }

                codeGenerator.EmitReturnValueHandling(node, false, ref result);
                return result;
            }
        }

        #endregion

        #region InstanceOfEx

        [NodeCompiler(typeof(InstanceOfEx))]
        sealed class InstanceOfExCompiler : ExpressionCompiler<InstanceOfEx>
        {
            private bool typeArgsResolved;

            public override Evaluation Analyze(InstanceOfEx node, Analyzer analyzer, ExInfoFromParent info)
            {
                access = info.Access;

                node.Expression = node.Expression.Analyze(analyzer, ExInfoFromParent.DefaultExInfo).Literalize();

                typeArgsResolved = TypeRefHelper.Analyze(node.ClassNameRef, analyzer);

                if (typeArgsResolved)
                    analyzer.AnalyzeConstructedType(TypeRefHelper.ResolvedType(node.ClassNameRef));

                return new Evaluation(node);
            }

            public override bool IsDeeplyCopied(InstanceOfEx node, CopyReason reason, int nestingLevel)
            {
                return false;
            }

            public override PhpTypeCode Emit(InstanceOfEx node, CodeGenerator codeGenerator)
            {
                Statistics.AST.AddNode("InstanceOfEx");

                // emits load of expression value on the stack:
                codeGenerator.EmitBoxing(node.Expression.Emit(codeGenerator));

                var resolvedType = TypeRefHelper.ResolvedType(node.ClassNameRef);

                if (resolvedType != null && typeArgsResolved)
                {
                    // type is resolvable (doesn't mean known) //

                    resolvedType.EmitInstanceOf(codeGenerator, null);
                }
                else
                {
                    // type is unresolvable (there is some variable or the type is a generic parameter) //

                    codeGenerator.EmitInstanceOfOperator(null, node.ClassNameRef, null);
                }

                if (access == AccessType.None)
                {
                    codeGenerator.IL.Emit(OpCodes.Pop);
                    return PhpTypeCode.Void;
                }
                else
                {
                    return PhpTypeCode.Boolean;
                }
            }
        }

        #endregion

        #region TypeOfEx

        [NodeCompiler(typeof(TypeOfEx))]
        sealed class TypeOfExCompiler : ExpressionCompiler<TypeOfEx>
        {
            public bool/*!*/ TypeArgsResolved { get { return typeArgsResolved; } }
            private bool typeArgsResolved;

            public override Evaluation Analyze(TypeOfEx node, Analyzer analyzer, ExInfoFromParent info)
            {
                access = info.Access;

                typeArgsResolved = TypeRefHelper.Analyze(node.ClassNameRef, analyzer);

                if (typeArgsResolved)
                    analyzer.AnalyzeConstructedType(TypeRefHelper.ResolvedType(node.ClassNameRef));

                return new Evaluation(node);
            }

            public override bool IsCustomAttributeArgumentValue(TypeOfEx node)
            {
                var resolvedtype = TypeRefHelper.ResolvedType(node.ClassNameRef);
                return resolvedtype != null && typeArgsResolved && resolvedtype.IsDefinite;
            }

            public override bool IsDeeplyCopied(TypeOfEx node, CopyReason reason, int nestingLevel)
            {
                return false;
            }

            public override PhpTypeCode Emit(TypeOfEx node, CodeGenerator codeGenerator)
            {
                Statistics.AST.AddNode("TypeOfEx");

                var resolvedtype = TypeRefHelper.ResolvedType(node.ClassNameRef);

                if (resolvedtype != null && typeArgsResolved)
                {
                    // type is resolvable (doesn't mean known) //

                    resolvedtype.EmitTypeOf(codeGenerator, null);
                }
                else
                {
                    // type is unresolvable (there is some variable or the type is a generic parameter) //

                    codeGenerator.EmitTypeOfOperator(null, node.ClassNameRef, null);
                }

                if (access == AccessType.None)
                {
                    codeGenerator.IL.Emit(OpCodes.Pop);
                    return PhpTypeCode.Void;
                }
                else
                {
                    return PhpTypeCode.DObject;
                }
            }
        }

        #endregion
    }
}


text:
package edu.cmu.graphchi.datablocks;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author akyrola
 *         Date: 7/15/12
 */
public class TestIntConverter {

    @Test
    public void testIntConversion() {
        IntConverter conv = new IntConverter();
        byte[] arr = new byte[conv.sizeOf()];
        assertEquals(arr.length, 4);

        int[] tests = new int[] {0, -5, 4, 81912, 839423, 92291, 10000, 2000000000, Integer.MAX_VALUE, Integer.MIN_VALUE};
        for(int x : tests) {
            conv.setValue(arr, x);
            int y = conv.getValue(arr);
            assertEquals(x, y);
        }
    }
}


text:
namespace AnimalHierarchy.Models.Animals
{
    using Infrastructure.Enumerations;
    using AnimalHierarchy.Models.Abstract;
    using System;

    public class Frog : Animal
    {
        public Frog(int age, string name, GenderType gender) : base(age, name, gender) { }

        public override void MakeSound()
        {
            Console.WriteLine("Croak");
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
org.apache.solr.client.solrj.impl Class Hierarchy (Solr 5.0-2012-07-18_13-07-53 API)
</TITLE>

<META NAME="date" CONTENT="2012-07-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.apache.solr.client.solrj.impl

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.apache.solr.client.solrj.impl.HttpClientUtil
org.apache.solr.client.solrj.impl.LBHttpSolrServer.Req
org.apache.solr.client.solrj.impl.LBHttpSolrServer.Rsp
org.apache.solr.client.solrj.request.RequestWriter

org.apache.solr.client.solrj.impl.BinaryRequestWriter

org.apache.solr.client.solrj.ResponseParser

org.apache.solr.client.solrj.impl.BinaryResponseParser

org.apache.solr.client.solrj.impl.StreamingBinaryResponseParser

org.apache.solr.client.solrj.impl.XMLResponseParser

org.apache.solr.client.solrj.SolrServer (implements java.io.Serializable)

org.apache.solr.client.solrj.impl.CloudSolrServer
org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer
org.apache.solr.client.solrj.impl.HttpSolrServer
org.apache.solr.client.solrj.impl.LBHttpSolrServer

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

org.apache.solr.client.solrj.impl.XMLResponseParser.KnownType

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

          <address>Copyright © 2000-2012 Apache Software Foundation.  All Rights Reserved.</address>