text:
package ru.job4j.presentation;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**.
 * Task 9.2.1.
 * Class servlet for filter
 *
 * @author Anton Vasilyuk
 * @version 1.0.
 */
public class AuthFilter implements Filter {

    /**.
     * Method init
     * @param filterConfig is filter config
     * @throws ServletException may be exception
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**.
     * Is do filter
     * @param req is request
     * @param resp is response
     * @param chain is chain
     * @throws IOException may be exception
     * @throws ServletException may be exception
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        if (request.getRequestURI().contains("/signin")) {
            chain.doFilter(req, resp);
        } else {
            HttpSession session = request.getSession();
            if (session.getAttribute("login") == null) {
                ((HttpServletResponse) resp).sendRedirect(String.format("%s/signin", request.getContextPath()));
                return;
            }
            chain.doFilter(req, resp);
        }
    }

    /**.
     * Method for destroy
     */
    @Override
    public void destroy() {
    }
}


text:
package queue

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestNewMessage(t *testing.T) {
	m := NewMessage("test", "http://example.com", 0)

	assert.Equal(t, "test", m.JobUUID)
	assert.Equal(t, "http://example.com", m.URL)
	assert.Equal(t, 0, m.Depth)
}

redpajama_set_name: RedPajamaGithub


text:
package com.netflix.spinnaker.clouddriver.ecs.deploy.ops;

import com.netflix.spinnaker.clouddriver.deploy.DeploymentResult;
import com.netflix.spinnaker.clouddriver.ecs.deploy.description.CloneServiceDescription;
import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperation;
import com.netflix.spinnaker.clouddriver.orchestration.events.OperationEvent;

import java.util.Collection;
import java.util.List;

public class CloneServiceAtomicOperation implements AtomicOperation<Void> {

  CloneServiceDescription description;

  public CloneServiceAtomicOperation(CloneServiceDescription description) {
    this.description = description;
  }

  @Override
  public Void operate(List priorOutputs) {

    // TODO - implement this stub

    return null;
  }

}


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="dynamic-menu/dynamic-menu.css" />
    <title>RnD</title>


text:
(function() {
  if(typeof Object.observe === 'undefined') {
    console.error("Object.observe not supported (or enabled) in your browser! If you're using Chrome, go to chrome://flags and 'Enable Experimental JavaScript'");
  }

  var ObjectObserveWrapper = function(ractive, obj, keypath, prefix) {
    this.value = obj;
    this.keypath = keypath;
    this.observeCallback = function(changes) {
      var keyPathsToUpdate = [];

      function scheduleKeyPathUpdate(keyPath) {
        if(keyPathsToUpdate.indexOf(keyPath) === -1) {
          keyPathsToUpdate.push(keyPath);
        }
      }

      changes.forEach(function(change) {
        switch (change.type) {
          case "updated":
            scheduleKeyPathUpdate(Object.keys(prefix(change.name))[0]);
            break;
          case "new":
          case "splice":
          case "deleted":
            var keyPath = Object.keys(prefix(change.name))[0];

            // Array deletions (task.list.length = 0) will trigger one change pr. element
            // in order to update ractive only once, we normalize the keyPath to represent their containing
            // array instead, e.g.:
            //    task.list.1 => task.list
            // This allows us to trigger 1 update instead of N updates
            keyPath = keyPath.replace(/\.[0-9]+$/, "");
            scheduleKeyPathUpdate(keyPath);
            break;
          default:
            console.error("Unhandled change event: " + change.type);
            break;
        }
      });

      keyPathsToUpdate.forEach(function(kp) {
        ractive.update(kp.keyPath);
      });
    };

    Object.observe(this.value, this.observeCallback);
  };

  ObjectObserveWrapper.prototype = {
    teardown: function() {
      Object.unobserve(this.value, this.observeCallback);
    },

    get: function() {
      return this.value;
    },

    set: function(keypath, value) {
      this.value[keypath] = value;
    },

    reset: function() {
      this.value = {};
    }
  };

  Ractive.adaptors.ObjectObserve = {
    filter: function(object) {
      return typeof object === "object";
    },

    wrap: function(ractive, object, keypath, prefix) {
      if(ractive.modifyArrays) {
        console.error("Object.Observe incompatible with modifyArrays: true. Set to false and try again!");
        return null;
      } else {
        return new ObjectObserveWrapper(ractive, object, keypath, prefix);
      }
    }
  };

}());


text:
'''
zstack image test class

@author: Youyk
'''
import apibinding.inventory as inventory
import zstackwoodpecker.header.header as zstack_header
import zstackwoodpecker.header.image as image_header
import zstackwoodpecker.operations.image_operations as img_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import random

class ZstackTestImage(image_header.TestImage):

    def __init__(self):
        super(ZstackTestImage, self).__init__()
        self.image_creation_option = test_util.ImageOption()
        self.original_checking_points = []
        self.delete_policy = test_lib.lib_get_delete_policy('image')
        self.delete_delay_time = test_lib.lib_get_expunge_time('image')

    def create(self, apiid=None, root=True):
        '''
        Create image template from Root Volume using CreateRootVolumeTemplateFromRootVolume
        '''
        if test_lib.lib_check_version_is_mevoco_1_8():
            if test_lib.lib_check_version_is_mevoco():
                self.image = img_ops.commit_volume_as_image_apiid(self.image_creation_option, apiid)
            else:
                self.image = img_ops.create_root_volume_template_apiid(self.image_creation_option, apiid)
        else:
            if root:
                self.image = img_ops.create_root_volume_template_apiid(self.image_creation_option, apiid)
            else:
                self.image = img_ops.create_data_volume_template(self.image_creation_option)
        super(ZstackTestImage, self).create()

    def delete(self):
        img_ops.delete_image(self.image.uuid)
        super(ZstackTestImage, self).delete()

    def recover(self):
        img_ops.recover_image(self.image.uuid)
        super(ZstackTestImage, self).recover()

    def expunge(self, bs_uuid_list = None):
        img_ops.expunge_image(self.image.uuid, bs_uuid_list)
        super(ZstackTestImage, self).expunge()

    def update(self):
        if self.get_state() != image_header.EXPUNGED:
            updated_image = test_lib.lib_get_image_by_uuid(self.image.uuid)
            if updated_image:
                self.image = updated_image
            else:
                self.set_state(image_header.EXPUNGED)
        return self.image

    def clean(self):
        if self.delete_policy != zstack_header.DELETE_DIRECT:
            if self.get_state() == image_header.DELETED:
                self.expunge()
            elif self.get_state() == image_header.EXPUNGED:
                pass
            else:
                self.delete()
                self.expunge()
        else:
            self.delete()

    def export(self):
        bs_uuid = self.image_creation_option.get_backup_storage_uuid_list()[0]
        return img_ops.export_image_from_backup_storage(self.image.uuid, bs_uuid)

    def delete_exported_image(self):
        bs_uuid = self.image_creation_option.get_backup_storage_uuid_list()[0]
        return img_ops.delete_exported_image_from_backup_storage(self.image.uuid, bs_uuid)

    def check(self):
        import zstackwoodpecker.zstack_test.checker_factory as checker_factory
        checker = checker_factory.CheckerFactory().create_checker(self)
        checker.check()
        super(ZstackTestImage, self).check()

    def set_creation_option(self, image_creation_option):
        self.image_creation_option = image_creation_option

    def get_creation_option(self):
        return self.image_creation_option

    def create_data_volume(self, ps_uuid, name = None, host_uuid = None):
        import zstackwoodpecker.header.volume as volume_header
        import zstackwoodpecker.zstack_test.zstack_test_volume \
                as zstack_volume_header
        volume_inv = vol_ops.create_volume_from_template(self.get_image().uuid,\
                ps_uuid, name, host_uuid)
        volume = zstack_volume_header.ZstackTestVolume()
        volume.set_volume(volume_inv)
        volume.set_state(volume_header.DETACHED)
        volume.set_original_checking_points(self.get_original_checking_points())
        super(ZstackTestImage, self).create_data_volume()
        return volume

    def add_data_volume_template(self):
        self.set_image(img_ops.add_data_volume_template(self.get_creation_option))
        return self

    def add_root_volume_template(self):
        self.set_image(img_ops.add_root_volume_template(self.get_creation_option()))
        return self

    def add_root_volume_template_apiid(self, apiid):
        self.set_image(img_ops.add_root_volume_template_apiid(self.get_creation_option(), apiid))
        return self

    def set_original_checking_points(self, original_checking_points):
        '''
        If the tmpt is created from a snapshot, it should inherit snapshot's
        checking points. Otherwise the previous checking points will lost, when
        create a new snapshot from the volume created from current template.
        '''
        self.original_checking_points = original_checking_points

    def get_original_checking_points(self):
        return self.original_checking_points

    def set_delete_policy(self, policy):
        test_lib.lib_set_delete_policy(category = 'image', value = policy)
        super(ZstackTestImage, self).set_delete_policy(policy)

    def set_delete_delay_time(self, delay_time):
        test_lib.lib_set_expunge_time(category = 'image', value = delay_time)
        super(ZstackTestImage, self).set_delete_delay_time(delay_time)


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

describe 'core_extensions' do

  it "should define an Enumerable method called collect_with_index" do
    Array.new.should respond_to(:collect_with_index)
  end

  it "should define map_with_index to be an alias of collect_with_index" do
    Array.new.should respond_to(:map_with_index)
  end

  it "should return a new version of an Enumerable with each element modified by a block that accepts the index of the element" do
    [1,1,1,1].collect_with_index { |e,i| e + i }.should == [1,2,3,4]
    [1,1,1,1].map_with_index { |e,i| e + i }.should == [1,2,3,4]
  end

end


text:
/*
 * curand_mtgp32_host.h
 *
 *
 * MTGP32-11213
 *
 * Mersenne Twister RNG for the GPU
 *
 * The period of generated integers is 211213-1.
 *
 * This code generates 32-bit unsigned integers, and
 * single precision floating point numbers uniformly distributed
 * in the range [1, 2). (float r; 1.0 <= r < 2.0)
 */

/*
 * Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima
 * University.  All rights reserved.
 * Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima
 * University and University of Tokyo.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the Hiroshima University nor the names of
 *       its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written
 *       permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#if !defined CURAND_MTGP32_HOST_H
#define CURAND_MTGP32_HOST_H

#if !defined(QUALIFIERS)
#define QUALIFIERS static inline __device__
#endif

#include <cuda.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include "curand.h"
#include "curand_mtgp32.h"
#include "curand_mtgp32dc_p_11213.h"

/**
 * \addtogroup DEVICE Device API
 *
 * @{
 */

extern mtgp32_params_fast_t mtgp32dc_params_fast_11213[];
static const unsigned int non_zero = 0x4d544750;

/*
 * This function represents a function used in the initialization
 * by mtgp32_init_by_array() and mtgp32_init_by_str().
 * @param[in] x 32-bit integer
 * @return 32-bit integer
 */
static unsigned int ini_func1(unsigned int x) {
    return (x ^ (x >> 27)) * (1664525);
}

/*
 * This function represents a function used in the initialization
 * by mtgp32_init_by_array() and mtgp32_init_by_str().
 * @param[in] x 32-bit integer
 * @return 32-bit integer
 */
static unsigned int ini_func2(unsigned int x) {
    return (x ^ (x >> 27)) * (1566083941);
}

/*
 * This function initializes the internal state array with a 32-bit
 * integer seed. The allocated memory should be freed by calling
 * mtgp32_free(). \b para should be one of the elements in the
 * parameter table (mtgp32-param-ref.c).
 *
 * This function is call by cuda program, because cuda program uses
 * another structure and another allocation method.
 *
 * @param[out] array MTGP internal status vector.
 * @param[in] para parameter structure
 * @param[in] seed a 32-bit integer used as the seed.
 */

void mtgp32_init_state(unsigned int state[],
              const mtgp32_params_fast_t *para, unsigned int seed) {
    int i;
    int size = para->mexp / 32 + 1;
    unsigned int hidden_seed;
    unsigned int tmp;
    hidden_seed = para->tbl[4] ^ (para->tbl[8] << 16);
    tmp = hidden_seed;
    tmp += tmp >> 16;
    tmp += tmp >> 8;
    memset(state, tmp & 0xff, sizeof(unsigned int) * size);
    state[0] = seed;
    state[1] = hidden_seed;
    for (i = 1; i < size; i++) {
    state[i] ^= (1812433253) * (state[i - 1]
                        ^ (state[i - 1] >> 30))
        + i;
    }
}

/*
 * This function initializes the internal state array
 * with a 32-bit integer array. \b para should be one of the elements in
 * the parameter table (mtgp32-param-ref.c).
 *
 * @param[out] mtgp32 MTGP structure.
 * @param[in] para parameter structure
 * @param[in] array a 32-bit integer array used as a seed.
 * @param[in] length length of the array.
 * @return CURAND_STATUS_SUCCESS
 */
int mtgp32_init_by_array(unsigned int state[],
             const mtgp32_params_fast_t *para,
             unsigned int *array, int length) {
    int i, j, count;
    unsigned int r;
    int lag;
    int mid;
    int size = para->mexp / 32 + 1;
    unsigned int hidden_seed;
    unsigned int tmp;

    if (size >= 623) {
    lag = 11;
    } else if (size >= 68) {
    lag = 7;
    } else if (size >= 39) {
    lag = 5;
    } else {
    lag = 3;
    }
    mid = (size - lag) / 2;

    hidden_seed = para->tbl[4] ^ (para->tbl[8] << 16);
    tmp = hidden_seed;
    tmp += tmp >> 16;
    tmp += tmp >> 8;
    memset(state, tmp & 0xff, sizeof(unsigned int) * size);
    state[0] = hidden_seed;

    if (length + 1 > size) {
    count = length + 1;
    } else {
    count = size;
    }
    r = ini_func1(state[0] ^ state[mid] ^ state[size - 1]);
    state[mid] += r;
    r += length;
    state[(mid + lag) % size] += r;
    state[0] = r;
    i = 1;
    count--;
    for (i = 1, j = 0; (j < count) && (j < length); j++) {
    r = ini_func1(state[i] ^ state[(i + mid) % size]
              ^ state[(i + size - 1) % size]);
    state[(i + mid) % size] += r;
    r += array[j] + i;
    state[(i + mid + lag) % size] += r;
    state[i] = r;
    i = (i + 1) % size;
    }
    for (; j < count; j++) {
    r = ini_func1(state[i] ^ state[(i + mid) % size]
              ^ state[(i + size - 1) % size]);
    state[(i + mid) % size] += r;
    r += i;
    state[(i + mid + lag) % size] += r;
    state[i] = r;
    i = (i + 1) % size;
    }
    for (j = 0; j < size; j++) {
    r = ini_func2(state[i] + state[(i + mid) % size]
              + state[(i + size - 1) % size]);
    state[(i + mid) % size] ^= r;
    r -= i;
    state[(i + mid + lag) % size] ^= r;
    state[i] = r;
    i = (i + 1) % size;
    }
    if (state[size - 1] == 0) {
    state[size - 1] = non_zero;
    }
    return 0;
}

/*
 * This function initializes the internal state array
 * with a character array. \b para should be one of the elements in
 * the parameter table (mtgp32-param-ref.c).
 * This is the same algorithm with mtgp32_init_by_array(), but hope to
 * be more useful.
 *
 * @param[out] mtgp32 MTGP structure.
 * @param[in] para parameter structure
 * @param[in] array a character array used as a seed. (terminated by zero.)
 * @return memory allocation result. if 0 then O.K.
 */
int mtgp32_init_by_str(unsigned int state[],
               const mtgp32_params_fast_t *para, char *array) {
    int i, j, count;
    unsigned int r;
    int lag;
    int mid;
    int size = para->mexp / 32 + 1;
    int length = (unsigned int)strlen(array);
    unsigned int hidden_seed;
    unsigned int tmp;

    if (size >= 623) {
    lag = 11;
    } else if (size >= 68) {
    lag = 7;
    } else if (size >= 39) {
    lag = 5;
    } else {
    lag = 3;
    }
    mid = (size - lag) / 2;

    hidden_seed = para->tbl[4] ^ (para->tbl[8] << 16);
    tmp = hidden_seed;
    tmp += tmp >> 16;
    tmp += tmp >> 8;
    memset(state, tmp & 0xff, sizeof(unsigned int) * size);
    state[0] = hidden_seed;

    if (length + 1 > size) {
    count = length + 1;
    } else {
    count = size;
    }
    r = ini_func1(state[0] ^ state[mid] ^ state[size - 1]);
    state[mid] += r;
    r += length;
    state[(mid + lag) % size] += r;
    state[0] = r;
    i = 1;
    count--;
    for (i = 1, j = 0; (j < count) && (j < length); j++) {
    r = ini_func1(state[i] ^ state[(i + mid) % size]
              ^ state[(i + size - 1) % size]);
    state[(i + mid) % size] += r;
    r += array[j] + i;
    state[(i + mid + lag) % size] += r;
    state[i] = r;
    i = (i + 1) % size;
    }
    for (; j < count; j++) {
    r = ini_func1(state[i] ^ state[(i + mid) % size]
              ^ state[(i + size - 1) % size]);
    state[(i + mid) % size] += r;
    r += i;
    state[(i + mid + lag) % size] += r;
    state[i] = r;
    i = (i + 1) % size;
    }
    for (j = 0; j < size; j++) {
    r = ini_func2(state[i] + state[(i + mid) % size]
              + state[(i + size - 1) % size]);
    state[(i + mid) % size] ^= r;
    r -= i;
    state[(i + mid + lag) % size] ^= r;
    state[i] = r;
    i = (i + 1) % size;
    }
    if (state[size - 1] == 0) {
    state[size - 1] = non_zero;
    }
    return 0;
}

/**
 * \brief Set up constant parameters for the mtgp32 generator
 *
 * This host-side helper function re-organizes CURAND_NUM_MTGP32_PARAMS sets of
 * generator parameters for use by kernel functions and copies the
 * result to the specified location in device memory.
 *
 * \param params - Pointer to an array of type mtgp32_params_fast_t in host memory
 * \param p - pointer to a structure of type mtgp32_kernel_params_t in device memory.
 *
 * \return
 * - CURAND_STATUS_ALLOCATION_FAILED if host memory could not be allocated
 * - CURAND_STATUS_INITIALIZATION_FAILED if the copy to device memory failed
 * - CURAND_STATUS_SUCCESS otherwise
 */
__host__ curandStatus_t curandMakeMTGP32Constants(const mtgp32_params_fast_t params[],mtgp32_kernel_params_t * p) {
    const int block_num = CURAND_NUM_MTGP32_PARAMS;
    const int size1 = sizeof(unsigned int) * block_num;
    const int size2 = sizeof(unsigned int) * block_num * TBL_SIZE;
    unsigned int *h_pos_tbl;
    unsigned int *h_sh1_tbl;
    unsigned int *h_sh2_tbl;
    unsigned int *h_param_tbl;
    unsigned int *h_temper_tbl;
    unsigned int *h_single_temper_tbl;
    unsigned int *h_mask;
    curandStatus_t status = CURAND_STATUS_SUCCESS;

    h_pos_tbl = (unsigned int *)malloc(size1);
    h_sh1_tbl = (unsigned int *)malloc(size1);
    h_sh2_tbl = (unsigned int *)malloc(size1);
    h_param_tbl = (unsigned int *)malloc(size2);
    h_temper_tbl = (unsigned int *)malloc(size2);
    h_single_temper_tbl = (unsigned int *)malloc(size2);
    h_mask = (unsigned int *)malloc(sizeof(unsigned int));
    if (h_pos_tbl == NULL
	    || h_sh1_tbl == NULL
	    || h_sh2_tbl == NULL
	    || h_param_tbl == NULL
	    || h_temper_tbl == NULL
	    || h_single_temper_tbl == NULL
	    || h_mask == NULL) {
        if (h_pos_tbl != NULL) free(h_pos_tbl);
        if (h_sh1_tbl != NULL) free(h_sh1_tbl);
        if (h_sh2_tbl != NULL) free(h_sh2_tbl);
        if (h_param_tbl != NULL) free(h_param_tbl);
        if (h_temper_tbl != NULL) free(h_temper_tbl);
        if (h_single_temper_tbl != NULL) free(h_single_temper_tbl);
        if (h_mask != NULL) free(h_mask);
        status = CURAND_STATUS_ALLOCATION_FAILED;
    } else {

        h_mask[0] = params[0].mask;
        for (int i = 0; i < block_num; i++) {
	        h_pos_tbl[i] = params[i].pos;
	        h_sh1_tbl[i] = params[i].sh1;
	        h_sh2_tbl[i] = params[i].sh2;
	        for (int j = 0; j < TBL_SIZE; j++) {
	            h_param_tbl[i * TBL_SIZE + j] = params[i].tbl[j];
	            h_temper_tbl[i * TBL_SIZE + j] = params[i].tmp_tbl[j];
	            h_single_temper_tbl[i * TBL_SIZE + j] = params[i].flt_tmp_tbl[j];
	        }
        }
        if (cudaMemcpy( p->pos_tbl,
                        h_pos_tbl, size1, cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        } else
        if (cudaMemcpy( p->sh1_tbl,
                        h_sh1_tbl, size1, cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        } else
        if (cudaMemcpy( p->sh2_tbl,
                        h_sh2_tbl, size1, cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        } else
        if (cudaMemcpy( p->param_tbl,
                        h_param_tbl, size2, cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        } else
        if (cudaMemcpy( p->temper_tbl,
                        h_temper_tbl, size2, cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        } else
        if (cudaMemcpy( p->single_temper_tbl,
                        h_single_temper_tbl, size2, cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        } else
        if (cudaMemcpy( p->mask,
                        h_mask, sizeof(unsigned int), cudaMemcpyHostToDevice) != cudaSuccess)
        {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        }
    }
    if (h_pos_tbl != NULL) free(h_pos_tbl);
    if (h_sh1_tbl != NULL) free(h_sh1_tbl);
    if (h_sh2_tbl != NULL) free(h_sh2_tbl);
    if (h_param_tbl != NULL) free(h_param_tbl);
    if (h_temper_tbl != NULL) free(h_temper_tbl);
    if (h_single_temper_tbl != NULL)free(h_single_temper_tbl);
    if (h_mask != NULL) free(h_mask);
    return status;
}

/**
 * \brief Set up initial states for the mtgp32 generator
 *
 * This host-side helper function initializes a number of states (one parameter set per state) for
 * an mtgp32 generator. To accomplish this it allocates a state array in host memory,
 * initializes that array, and copies the result to device memory.
 *
 * \param s - pointer to an array of states in device memory
 * \param params - Pointer to an array of type mtgp32_params_fast_t in host memory
 * \param k - pointer to a structure of type mtgp32_kernel_params_t in device memory
 * \param n - number of parameter sets/states to initialize
 * \param seed - seed value
 *
 * \return
 * - CURAND_STATUS_ALLOCATION_FAILED if host memory state could not be allocated
 * - CURAND_STATUS_INITIALIZATION_FAILED if the copy to device memory failed
 * - CURAND_STATUS_SUCCESS otherwise
 */
__host__ curandStatus_t CURANDAPI curandMakeMTGP32KernelState(curandStateMtgp32_t *s,
                                            mtgp32_params_fast_t params[],
                                            mtgp32_kernel_params_t *k,
                                            int n,
                                            unsigned long long seed)
{
    int i;
    curandStatus_t status = CURAND_STATUS_SUCCESS;
    curandStateMtgp32_t *h_status =(curandStateMtgp32_t *) malloc(sizeof(curandStateMtgp32_t) * n);
    if (h_status == NULL) {
        status = CURAND_STATUS_ALLOCATION_FAILED;
    } else {
        seed = seed ^ (seed >> 32);
        for (i = 0; i < n; i++) {
            mtgp32_init_state(&(h_status[i].s[0]), &params[i],(unsigned int)seed + i + 1);
            h_status[i].offset = 0;
            h_status[i].pIdx = i;
            h_status[i].k = k;
            h_status[i].precise_double_flag = 0;
        }
        if (cudaMemcpy(s, h_status,
                       sizeof(curandStateMtgp32_t) * n,
                       cudaMemcpyHostToDevice) != cudaSuccess) {
            status = CURAND_STATUS_INITIALIZATION_FAILED;
        }
     }
    free(h_status);
    return status;
}

/** @} */

#endif


text:
import { pick, map } from 'lodash';
import log from '../services/logger_service';

function mapErrorList(errorItem) {
  return pick(errorItem, 'message');
}

export default (message, code, errorList) => {
  if (!message || !code) {
    log.fatal('Logger used incorrectly.');
    return {
      error: {
        message: 'Create Error Response used incorrectly.'
      }
    };
  }

  if (errorList) {
    return {
      error: {
        message,
        statusCode: code,
        errors: map(errorList, mapErrorList)
      }
    };
  }

  return {
    error: {
      message,
      statusCode: code
    }
  };
};


text:
#include <arch_helpers.h>
#include <arm_gic.h>
#include <assert.h>
#include <bakery_lock.h>
#include <cci400.h>
#include <debug.h>
#include <mmio.h>
#include <platform.h>
#include <plat_config.h>
#include <platform_def.h>
#include <psci.h>
#include <errno.h>
#include "drivers/pwrc/fvp_pwrc.h"
#include "fvp_def.h"
#include "fvp_private.h"

/*******************************************************************************
 * Private FVP function to program the mailbox for a cpu before it is released
 * from reset.
 ******************************************************************************/
static void fvp_program_mailbox(uint64_t mpidr, uint64_t address)
{
	uint64_t linear_id;
	mailbox_t *fvp_mboxes;

	linear_id = platform_get_core_pos(mpidr);
	fvp_mboxes = (mailbox_t *)MBOX_BASE;
	fvp_mboxes[linear_id].value = address;
	flush_dcache_range((unsigned long) &fvp_mboxes[linear_id],
			   sizeof(unsigned long));
}

/*******************************************************************************
 * Function which implements the common FVP specific operations to power down a
 * cpu in response to a CPU_OFF or CPU_SUSPEND request.
 ******************************************************************************/
static void fvp_cpu_pwrdwn_common()
{
	/* Prevent interrupts from spuriously waking up this cpu */
	arm_gic_cpuif_deactivate();

	/* Program the power controller to power off this cpu. */
	fvp_pwrc_write_ppoffr(read_mpidr_el1());
}

/*******************************************************************************
 * Function which implements the common FVP specific operations to power down a
 * cluster in response to a CPU_OFF or CPU_SUSPEND request.
 ******************************************************************************/
static void fvp_cluster_pwrdwn_common()
{
	uint64_t mpidr = read_mpidr_el1();

	/* Disable coherency if this cluster is to be turned off */
	if (get_plat_config()->flags & CONFIG_HAS_CCI)
		cci_disable_cluster_coherency(mpidr);

	/* Program the power controller to turn the cluster off */
	fvp_pwrc_write_pcoffr(mpidr);
}

/*******************************************************************************
 * Private FVP function which is used to determine if any platform actions
 * should be performed for the specified affinity instance given its
 * state. Nothing needs to be done if the 'state' is not off or if this is not
 * the highest affinity level which will enter the 'state'.
 ******************************************************************************/
static int32_t fvp_do_plat_actions(unsigned int afflvl, unsigned int state)
{
	unsigned int max_phys_off_afflvl;

	assert(afflvl <= MPIDR_AFFLVL1);

	if (state != PSCI_STATE_OFF)
		return -EAGAIN;

	/*
	 * Find the highest affinity level which will be suspended and postpone
	 * all the platform specific actions until that level is hit.
	 */
	max_phys_off_afflvl = psci_get_max_phys_off_afflvl();
	assert(max_phys_off_afflvl != PSCI_INVALID_DATA);
	if (afflvl != max_phys_off_afflvl)
		return -EAGAIN;

	return 0;
}

/*******************************************************************************
 * FVP handler called when an affinity instance is about to enter standby.
 ******************************************************************************/
void fvp_affinst_standby(unsigned int power_state)
{
	/*
	 * Enter standby state
	 * dsb is good practice before using wfi to enter low power states
	 */
	dsb();
	wfi();
}

/*******************************************************************************
 * FVP handler called when an affinity instance is about to be turned on. The
 * level and mpidr determine the affinity instance.
 ******************************************************************************/
int fvp_affinst_on(unsigned long mpidr,
		   unsigned long sec_entrypoint,
		   unsigned int afflvl,
		   unsigned int state)
{
	int rc = PSCI_E_SUCCESS;
	unsigned int psysr;

	/*
	 * It's possible to turn on only affinity level 0 i.e. a cpu
	 * on the FVP. Ignore any other affinity level.
	 */
	if (afflvl != MPIDR_AFFLVL0)
		return rc;

	/*
	 * Ensure that we do not cancel an inflight power off request
	 * for the target cpu. That would leave it in a zombie wfi.
	 * Wait for it to power off, program the jump address for the
	 * target cpu and then program the power controller to turn
	 * that cpu on
	 */
	do {
		psysr = fvp_pwrc_read_psysr(mpidr);
	} while (psysr & PSYSR_AFF_L0);

	fvp_program_mailbox(mpidr, sec_entrypoint);
	fvp_pwrc_write_pponr(mpidr);

	return rc;
}

/*******************************************************************************
 * FVP handler called when an affinity instance is about to be turned off. The
 * level and mpidr determine the affinity instance. The 'state' arg. allows the
 * platform to decide whether the cluster is being turned off and take apt
 * actions.
 *
 * CAUTION: There is no guarantee that caches will remain turned on across calls
 * to this function as each affinity level is dealt with. So do not write & read
 * global variables across calls. It will be wise to do flush a write to the
 * global to prevent unpredictable results.
 ******************************************************************************/
void fvp_affinst_off(unsigned int afflvl,
		    unsigned int state)
{
	/* Determine if any platform actions need to be executed */
	if (fvp_do_plat_actions(afflvl, state) == -EAGAIN)
		return;

	/*
	 * If execution reaches this stage then this affinity level will be
	 * suspended. Perform at least the cpu specific actions followed the
	 * cluster specific operations if applicable.
	 */
	fvp_cpu_pwrdwn_common();

	if (afflvl != MPIDR_AFFLVL0)
		fvp_cluster_pwrdwn_common();

}

/*******************************************************************************
 * FVP handler called when an affinity instance is about to be suspended. The
 * level and mpidr determine the affinity instance. The 'state' arg. allows the
 * platform to decide whether the cluster is being turned off and take apt
 * actions.
 *
 * CAUTION: There is no guarantee that caches will remain turned on across calls
 * to this function as each affinity level is dealt with. So do not write & read
 * global variables across calls. It will be wise to do flush a write to the
 * global to prevent unpredictable results.
 ******************************************************************************/
void fvp_affinst_suspend(unsigned long sec_entrypoint,
			unsigned int afflvl,
			unsigned int state)
{
	unsigned long mpidr;

	/* Determine if any platform actions need to be executed. */
	if (fvp_do_plat_actions(afflvl, state) == -EAGAIN)
		return;

	/* Get the mpidr for this cpu */
	mpidr = read_mpidr_el1();

	/* Program the jump address for the this cpu */
	fvp_program_mailbox(mpidr, sec_entrypoint);

	/* Program the power controller to enable wakeup interrupts. */
	fvp_pwrc_set_wen(mpidr);

	/* Perform the common cpu specific operations */
	fvp_cpu_pwrdwn_common();

	/* Perform the common cluster specific operations */
	if (afflvl != MPIDR_AFFLVL0)
		fvp_cluster_pwrdwn_common();
}

/*******************************************************************************
 * FVP handler called when an affinity instance has just been powered on after
 * being turned off earlier. The level and mpidr determine the affinity
 * instance. The 'state' arg. allows the platform to decide whether the cluster
 * was turned off prior to wakeup and do what's necessary to setup it up
 * correctly.
 ******************************************************************************/
void fvp_affinst_on_finish(unsigned int afflvl,
			  unsigned int state)
{
	unsigned long mpidr;

	/* Determine if any platform actions need to be executed. */
	if (fvp_do_plat_actions(afflvl, state) == -EAGAIN)
		return;

	/* Get the mpidr for this cpu */
	mpidr = read_mpidr_el1();

	/* Perform the common cluster specific operations */
	if (afflvl != MPIDR_AFFLVL0) {
		/*
		 * This CPU might have woken up whilst the cluster was
		 * attempting to power down. In this case the FVP power
		 * controller will have a pending cluster power off request
		 * which needs to be cleared by writing to the PPONR register.
		 * This prevents the power controller from interpreting a
		 * subsequent entry of this cpu into a simple wfi as a power
		 * down request.
		 */
		fvp_pwrc_write_pponr(mpidr);

		/* Enable coherency if this cluster was off */
		fvp_cci_enable();
	}

	/*
	 * Clear PWKUPR.WEN bit to ensure interrupts do not interfere
	 * with a cpu power down unless the bit is set again
	 */
	fvp_pwrc_clr_wen(mpidr);

	/* Zero the jump address in the mailbox for this cpu */
	fvp_program_mailbox(mpidr, 0);

	/* Enable the gic cpu interface */
	arm_gic_cpuif_setup();

	/* TODO: This setup is needed only after a cold boot */
	arm_gic_pcpu_distif_setup();
}

/*******************************************************************************
 * FVP handler called when an affinity instance has just been powered on after
 * having been suspended earlier. The level and mpidr determine the affinity
 * instance.
 * TODO: At the moment we reuse the on finisher and reinitialize the secure
 * context. Need to implement a separate suspend finisher.
 ******************************************************************************/
void fvp_affinst_suspend_finish(unsigned int afflvl,
			       unsigned int state)
{
	fvp_affinst_on_finish(afflvl, state);
}

/*******************************************************************************
 * FVP handlers to shutdown/reboot the system
 ******************************************************************************/
static void __dead2 fvp_system_off(void)
{
	/* Write the System Configuration Control Register */
	mmio_write_32(VE_SYSREGS_BASE + V2M_SYS_CFGCTRL,
		CFGCTRL_START | CFGCTRL_RW | CFGCTRL_FUNC(FUNC_SHUTDOWN));
	wfi();
	ERROR("FVP System Off: operation not handled.\n");
	panic();
}

static void __dead2 fvp_system_reset(void)
{
	/* Write the System Configuration Control Register */
	mmio_write_32(VE_SYSREGS_BASE + V2M_SYS_CFGCTRL,
		CFGCTRL_START | CFGCTRL_RW | CFGCTRL_FUNC(FUNC_REBOOT));
	wfi();
	ERROR("FVP System Reset: operation not handled.\n");
	panic();
}

/*******************************************************************************
 * FVP handler called to check the validity of the power state parameter.
 ******************************************************************************/
int fvp_validate_power_state(unsigned int power_state)
{
	/* Sanity check the requested state */
	if (psci_get_pstate_type(power_state) == PSTATE_TYPE_STANDBY) {
		/*
		 * It's possible to enter standby only on affinity level 0
		 * i.e. a cpu on the fvp. Ignore any other affinity level.
		 */
		if (psci_get_pstate_afflvl(power_state) != MPIDR_AFFLVL0)
			return PSCI_E_INVALID_PARAMS;
	}

	/*
	 * We expect the 'state id' to be zero.
	 */
	if (psci_get_pstate_id(power_state))
		return PSCI_E_INVALID_PARAMS;

	return PSCI_E_SUCCESS;
}

/*******************************************************************************
 * Export the platform handlers to enable psci to invoke them
 ******************************************************************************/
static const plat_pm_ops_t fvp_plat_pm_ops = {
	.affinst_standby = fvp_affinst_standby,
	.affinst_on = fvp_affinst_on,
	.affinst_off = fvp_affinst_off,
	.affinst_suspend = fvp_affinst_suspend,
	.affinst_on_finish = fvp_affinst_on_finish,
	.affinst_suspend_finish = fvp_affinst_suspend_finish,
	.system_off = fvp_system_off,
	.system_reset = fvp_system_reset,
	.validate_power_state = fvp_validate_power_state
};

/*******************************************************************************
 * Export the platform specific power ops & initialize the fvp power controller
 ******************************************************************************/
int platform_setup_pm(const plat_pm_ops_t **plat_ops)
{
	*plat_ops = &fvp_plat_pm_ops;
	return 0;
}


text:
layout: post
category: post
published: true
title: Public Domain Day 2020!
---
It's January 1st, and for the second time in recent memory, it's public domain day in the US. That means that dozens of works from 1924 have now entered the public domain. Let's run through a few things that were released in 1924, and talk about what you can do with them now.

I won't give a full list of works that entered the public domain, because that'd take a long time and be kind of boring. Instead I'm going to highlight a few important works, and share links to those works. If you want more general information, there are I recommend [Duke.edu's Public Domain Day Post](https://web.law.duke.edu/cspd/publicdomainday/2020/)

## [Gershwin's Rhapsody in Blue](https://archive.org/embed/Rhapsody-in-Blue-Remixes)

Gershwin's estate is a big part of the reason that works stopped entering the US public domain when I was a kid. I thought it would be fitting to kick things off with a couple of covers of Rhapsody in Blue. One is a straight piano cover (via Midi), the other two (also via midi) use various NES/SNES soundfonts. Gershwin's estate would no doubt find this pretty distasteful, but I think it's super neat! Listening to the NES/8-bit version (which is my favorite), I can *almost see* Link walking through Hyrule with a Thompson on his shoulder.

(Note that while the sheet music is in the public domain, audio copyright in the US is a massive clusterfuck, and any given recording of the track is definitely still under copyright.)

## [See See Rider](https://archive.org/embed/78_see-see-rider-blues_bea-booze-rainey_gbia0049689a)

Ma Rainey's classic blues tune, covered by every garage band and rock and roll upstart of the 50s and 60s!

As mentioned previously, this recording (which is a cover from the 40s) is still under copyright for at least another few years, but The Internet Archive has been kind enough to find a way to share it anyway. Now that the music and lyrics are in the public domain, you can record your own cover or re-interpret the song as you see fit, and I hope you will (and I hope you'll tell me abou tit!)

## [Tarzan and the Ant-Men](http://gutenberg.net.au/ebooks06/0600651h.html)

Currently available from Project Gutenburg AU, but soon to be available in many more places, because it's in the PD in the US.

## Sherlock Jr.

<video width="500" src="https://upload.wikimedia.org/wikipedia/commons/9/95/Sherlock_Jr._%281924%29.webm
"  controls>

</video>

Starring Buster Keaton, Directed by Buster Keaton, Entering the Public Domain in the US Today (January 1st, 2020)

Watch Buster Keaton daydream about being the hero in this 1924 Sherlock Holmes Fan Film. Features some of Keaton's most complex trick photography to date.

Silent comedy, medium length, lots of fun.

[(Also available on Peertube)](https://vidcommons.org/videos/watch/f917dde3-c2a1-4e05-a183-9c0e62e32094) with a full review coming soon!

## What else?

Lots of other interesting works entered the Public Domain in the US this year, and I'm looking forward to exploring them with you. I'm going to try to make PD Day a monthly exercise all year.


text:
using MediaBrowser.Naming.Common;
using MediaBrowser.Naming.Video;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using Interfaces.IO;
using Patterns.Logging;

namespace MediaBrowser.Naming.Tests.Video
{
    [TestClass]
    public class MultiVersionTests
    {
        [TestMethod]
        public void TestMultiEdition1()
        {
            var files = new[]
            {
                @"\\movies\X-Men Days of Future Past\X-Men Days of Future Past - 1080p.mkv",
                @"\\movies\X-Men Days of Future Past\X-Men Days of Future Past-trailer.mp4",
                @"\\movies\X-Men Days of Future Past\X-Men Days of Future Past - [hsbs].mkv"
            };

            var resolver = GetResolver();

            var result = resolver.Resolve(files.Select(i => new FileMetadata
            {
                IsFolder = false,
                Id = i

            }).ToList()).ToList();

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(1, result[0].Extras.Count);
        }

        [TestMethod]
        public void TestMultiEdition2()
        {
            var files = new[]
            {
                @"\\movies\X-Men Days of Future Past\X-Men Days of Future Past - apple.mkv",
                @"\\movies\X-Men Days of Future Past\X-Men Days of Future Past-trailer.mp4",
                @"\\movies\X-Men Days of Future Past\X-Men Days of Future Past - banana.mkv"
            };

            var resolver = GetResolver();

            var result = resolver.Resolve(files.Select(i => new FileMetadata
            {
                IsFolder = false,
                Id = i

            }).ToList()).ToList();

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(1, result[0].Extras.Count);
            Assert.AreEqual(1, result[0].AlternateVersions.Count);
        }

        private VideoListResolver GetResolver()
        {
            var options = new ExtendedNamingOptions();
            return new VideoListResolver(options, new NullLogger());
        }
    }
}


text:
<!DOCTYPE HTML>

<{header}>
<link rel="stylesheet" href="images/styles.css" />

<{require file="block/header.html"}>

    <{main}>

<{require file="block/footer.html"}>


text:
static int chunked = 0;
static struct GlobalData *data = NULL;
static struct StreamRequest *stream_request = NULL;
static struct evhttp_connection *evhttp_source_connection = NULL;
static struct evhttp_request *evhttp_source_request = NULL;
static struct StreamRequest *autodetect_sr = NULL;
extern struct event_base *current_base;

struct GlobalData {
    void (*message_cb)(char *data, void *cbarg);
    void (*error_cb)(int status_code, void *cbarg);
    void *cbarg;
    const char *source_address;
    int source_port;
    const char *path;
};

void pubsubclient_termination_handler(int signum)
{
    event_loopbreak();
}

int pubsubclient_parse_one_message(struct evbuffer *evb, void *arg)
{
    char *line;
    size_t line_len;
    struct GlobalData *client_data;
    char *data;
    int has_more = 0;

    _DEBUG("pubsubclient_parse_one_message()\n");

    client_data = (struct GlobalData *)arg;
    line = evbuffer_readline(evb);
    if (line && (line_len = strlen(line))) {
        _DEBUG("line (%p): %s (%d)\n", line, line, line_len);
        (*client_data->message_cb)(line, client_data->cbarg);
        if (EVBUFFER_LENGTH(evb)) {
            has_more = 1;
        }
    }
    free(line);
    return has_more;
}

void pubsubclient_source_readcb(struct bufferevent *bev, void *arg)
{
    while (pubsubclient_parse_one_message(EVBUFFER_INPUT(bev), arg)) {}
}

void pubsubclient_errorcb(struct bufferevent *bev, void *arg)
{
    struct GlobalData *client_data = (struct GlobalData *)arg;

    fprintf(stderr, "ERROR: request failed\n");

    if (client_data->error_cb) {
        (*client_data->error_cb)(-1, client_data->cbarg);
    }
}

void pubsubclient_source_request_done(struct evhttp_request *req, void *arg)
{
    struct GlobalData *client_data = (struct GlobalData *)arg;
    int status_code = -1;

    _DEBUG("pubsubclient_source_request_done()\n");

    fprintf(stderr, "ERROR: request failed\n");

    if (req) {
        status_code = req->response_code;
    }

    if (client_data->error_cb) {
        (*client_data->error_cb)(status_code, client_data->cbarg);
    }
}

void pubsubclient_source_callback(struct evhttp_request *req, void *arg)
{
    // keep parsing out messages until there aren't any left
    while (pubsubclient_parse_one_message(req->input_buffer, arg)) {}
}

int pubsubclient_connect()
{
    fprintf(stdout, "CONNECTING TO SOURCE http://%s:%d%s\n", data->source_address, data->source_port, data->path);
    if (chunked) {
        if (evhttp_source_connection) {
            evhttp_connection_free(evhttp_source_connection);
        }

        // use libevent's built in evhttp methods to parse chunked responses
        evhttp_source_connection = evhttp_connection_new(data->source_address, data->source_port);
        if (evhttp_source_connection == NULL) {
            fprintf(stderr, "ERROR: evhttp_connection_new() failed for %s:%d\n", data->source_address, data->source_port);
            return 0;
        }

        evhttp_source_request = evhttp_request_new(pubsubclient_source_request_done, data);
        evhttp_add_header(evhttp_source_request->output_headers, "Host", data->source_address);
        evhttp_request_set_chunked_cb(evhttp_source_request, pubsubclient_source_callback);

        if (evhttp_make_request(evhttp_source_connection, evhttp_source_request, EVHTTP_REQ_GET, data->path) == -1) {
            fprintf(stderr, "ERROR: evhttp_make_request() failed for %s\n", data->path);
            evhttp_connection_free(evhttp_source_connection);
            return 0;
        }
    } else {
        if (stream_request) {
            free_stream_request(stream_request);
        }

        // use our stream_request library to handle non-chunked
        stream_request = new_stream_request("GET", data->source_address, data->source_port, data->path,
                                            NULL, pubsubclient_source_readcb, pubsubclient_errorcb, data);
        if (!stream_request) {
            fprintf(stderr, "ERROR: new_stream_request() failed for %s:%d%s\n", data->source_address, data->source_port, data->path);
            return 0;
        }
    }

    return 1;
}

void pubsubclient_autodetect_headercb(struct bufferevent *bev, struct evkeyvalq *headers, void *arg)
{
    const char *encoding_header = NULL;

    _DEBUG("pubsubclient_autodetect_headercb() headers: %p\n", headers);

    if ((encoding_header = evhttp_find_header(headers, "Transfer-Encoding")) != NULL) {
        if (strncmp(encoding_header, "chunked", 7) == 0) {
            chunked = 1;
        }
    }

    // turn off the events for this buffer
    // its free'd later
    bufferevent_disable(bev, EV_READ);

    _DEBUG("chunked = %d\n", chunked);

    if (!pubsubclient_connect(arg)) {
        event_loopbreak();
    }
}

void pubsubclient_init(const char *source_address, int source_port, const char *path,
                       void (*message_cb)(char *data, void *arg),
                       void (*error_cb)(int status_code, void *arg),
                       void *cbarg)
{

    signal(SIGINT, pubsubclient_termination_handler);
    signal(SIGQUIT, pubsubclient_termination_handler);
    signal(SIGTERM, pubsubclient_termination_handler);
    signal(SIGHUP, pubsubclient_termination_handler);

    if (!current_base) {
        event_init();
    }

    data = calloc(1, sizeof(struct GlobalData));
    data->message_cb = message_cb;
    data->error_cb = error_cb;
    data->cbarg = cbarg;
    data->source_address = source_address;
    data->source_port = source_port;
    data->path = path;

    // perform a request for headers so we can autodetect whether or not we're
    // getting a chunked response
    fprintf(stdout, "AUTODETECTING ENCODING FOR http://%s:%d%s\n", source_address, source_port, path);
    autodetect_sr = new_stream_request("HEAD", source_address, source_port, path,
                                       pubsubclient_autodetect_headercb, NULL, pubsubclient_errorcb, data);
    if (!autodetect_sr) {
        fprintf(stderr, "ERROR: new_stream_request() failed for %s:%d%s\n", source_address, source_port, path);
        exit(1);
    }
}

int pubsubclient_main(const char *source_address, int source_port, const char *path,
                      void (*message_cb)(char *data, void *arg),
                      void (*error_cb)(int status_code, void *arg),
                      void *cbarg)
{
    pubsubclient_init(source_address, source_port, path, message_cb, error_cb, cbarg);
    event_dispatch();
    pubsubclient_free();
    return 0;
}

void pubsubclient_run()
{
    event_dispatch();
}

void pubsubclient_free()
{
    free_stream_request(autodetect_sr);

    if (chunked) {
        evhttp_connection_free(evhttp_source_connection);
    } else {
        free_stream_request(stream_request);
    }

    free(data);
}


text:
require 'active_support/all'
require 'sinatra'
require 'resque'
require 'yaml'

require 'dashing_resque/version'

require 'dashing_resque/routes'

require 'dashing_resque/job'
require 'dashing_resque/jobs/failed_jobs.rb'
require 'dashing_resque/jobs/queued_jobs.rb'

module DashingResque
  class << self
    def init
      config = parse_config
      Resque.redis = config['redis_url']
      Sinatra::Application.settings.sprockets.append_path(assets_path)
    end

    private

    def parse_config
      config_file = File.join(Sinatra::Application.settings.root, *%w(config resque.yml))
      YAML.load_file(config_file)[ENV['RACK_ENV']]
    end

    def assets_path
      File.expand_path(File.dirname(__FILE__))
    end
  end
end


text:
/*
 * Xero AppStore API
 * These endpoints are for Xero Partners to interact with the App Store Billing platform
 *
 * Contact: api@xero.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.xero.models.appstore;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.xero.api.StringUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
import org.threeten.bp.OffsetDateTime;

/** Data transfer object for public create usage end point */
@ApiModel(description = "Data transfer object for public create usage end point")
public class CreateUsageRecord {
  StringUtil util = new StringUtil();

  @JsonProperty("quantity")
  private Integer quantity;

  @JsonProperty("timestamp")
  private OffsetDateTime timestamp;
  /**
   * The initial quantity for the usage record. Must be a whole number that is greater than or equal
   * to 0
   *
   * @param quantity Integer
   * @return CreateUsageRecord
   */
  public CreateUsageRecord quantity(Integer quantity) {
    this.quantity = quantity;
    return this;
  }

  /**
   * The initial quantity for the usage record. Must be a whole number that is greater than or equal
   * to 0
   *
   * @return quantity
   */
  @ApiModelProperty(
      required = true,
      value =
          "The initial quantity for the usage record. Must be a whole number that is greater than"
              + " or equal to 0")
  /**
   * The initial quantity for the usage record. Must be a whole number that is greater than or equal
   * to 0
   *
   * @return quantity Integer
   */
  public Integer getQuantity() {
    return quantity;
  }

  /**
   * The initial quantity for the usage record. Must be a whole number that is greater than or equal
   * to 0
   *
   * @param quantity Integer
   */
  public void setQuantity(Integer quantity) {
    this.quantity = quantity;
  }

  /**
   * DateTime in UTC of when the the product was consumed/used
   *
   * @param timestamp OffsetDateTime
   * @return CreateUsageRecord
   */
  public CreateUsageRecord timestamp(OffsetDateTime timestamp) {
    this.timestamp = timestamp;
    return this;
  }

  /**
   * DateTime in UTC of when the the product was consumed/used
   *
   * @return timestamp
   */
  @ApiModelProperty(
      required = true,
      value = "DateTime in UTC of when the the product was consumed/used")
  /**
   * DateTime in UTC of when the the product was consumed/used
   *
   * @return timestamp OffsetDateTime
   */
  public OffsetDateTime getTimestamp() {
    return timestamp;
  }

  /**
   * DateTime in UTC of when the the product was consumed/used
   *
   * @param timestamp OffsetDateTime
   */
  public void setTimestamp(OffsetDateTime timestamp) {
    this.timestamp = timestamp;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CreateUsageRecord createUsageRecord = (CreateUsageRecord) o;
    return Objects.equals(this.quantity, createUsageRecord.quantity)
        && Objects.equals(this.timestamp, createUsageRecord.timestamp);
  }

  @Override
  public int hashCode() {
    return Objects.hash(quantity, timestamp);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class CreateUsageRecord {\n");
    sb.append("    quantity: ").append(toIndentedString(quantity)).append("\n");
    sb.append("    timestamp: ").append(toIndentedString(timestamp)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
package com.hazelcast.simulator.protocol;

import com.hazelcast.simulator.protocol.connector.AgentConnector;
import com.hazelcast.simulator.protocol.connector.WorkerConnector;
import com.hazelcast.simulator.protocol.core.Response;
import com.hazelcast.simulator.protocol.core.ResponseFuture;
import com.hazelcast.simulator.protocol.core.ResponseType;
import com.hazelcast.simulator.protocol.core.SimulatorAddress;
import com.hazelcast.simulator.protocol.operation.IntegrationTestOperation;
import com.hazelcast.simulator.protocol.operation.LogOperation;
import com.hazelcast.simulator.protocol.operation.SimulatorOperation;
import com.hazelcast.simulator.utils.AssertTask;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import static com.hazelcast.simulator.protocol.ProtocolUtil.DEFAULT_OPERATION;
import static com.hazelcast.simulator.protocol.ProtocolUtil.DEFAULT_TEST_TIMEOUT_MILLIS;
import static com.hazelcast.simulator.protocol.ProtocolUtil.assertAllTargets;
import static com.hazelcast.simulator.protocol.ProtocolUtil.assertEmptyFutureMaps;
import static com.hazelcast.simulator.protocol.ProtocolUtil.assertSingleTarget;
import static com.hazelcast.simulator.protocol.ProtocolUtil.getAgentConnector;
import static com.hazelcast.simulator.protocol.ProtocolUtil.getCoordinatorConnector;
import static com.hazelcast.simulator.protocol.ProtocolUtil.getWorkerConnector;
import static com.hazelcast.simulator.protocol.ProtocolUtil.resetLogLevel;
import static com.hazelcast.simulator.protocol.ProtocolUtil.sendFromCoordinator;
import static com.hazelcast.simulator.protocol.ProtocolUtil.setLogLevel;
import static com.hazelcast.simulator.protocol.ProtocolUtil.startSimulatorComponents;
import static com.hazelcast.simulator.protocol.ProtocolUtil.stopSimulatorComponents;
import static com.hazelcast.simulator.protocol.core.AddressLevel.AGENT;
import static com.hazelcast.simulator.protocol.core.AddressLevel.TEST;
import static com.hazelcast.simulator.protocol.core.AddressLevel.WORKER;
import static com.hazelcast.simulator.protocol.core.ResponseType.FAILURE_AGENT_NOT_FOUND;
import static com.hazelcast.simulator.protocol.core.ResponseType.FAILURE_TEST_NOT_FOUND;
import static com.hazelcast.simulator.protocol.core.ResponseType.FAILURE_WORKER_NOT_FOUND;
import static com.hazelcast.simulator.protocol.core.ResponseType.SUCCESS;
import static com.hazelcast.simulator.protocol.core.SimulatorAddress.COORDINATOR;
import static com.hazelcast.simulator.utils.TestUtils.assertTrueEventually;
import static org.junit.Assert.assertEquals;

public class ProtocolIntegrationTest {

    private static final long ASSERT_EVENTUALLY_TIMEOUT_SECONDS = 3;

    @BeforeClass
    public static void setUp() {
        setLogLevel(Level.TRACE);

        startSimulatorComponents(2, 2, 2);
    }

    @AfterClass
    public static void tearDown() {
        stopSimulatorComponents();

        resetLogLevel();
    }

    @After
    public void commonAsserts() {
        assertEmptyFutureMaps();
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_SingleAgent() {
        SimulatorAddress destination = new SimulatorAddress(AGENT, 1, 0, 0);
        Response response = sendFromCoordinator(destination);

        assertSingleTarget(response, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_AllAgents() {
        SimulatorAddress destination = new SimulatorAddress(AGENT, 0, 0, 0);
        Response response = sendFromCoordinator(destination);

        assertAllTargets(response, destination, SUCCESS, 2);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_AgentNotFound() {
        SimulatorAddress destination = new SimulatorAddress(AGENT, 3, 0, 0);
        Response response = sendFromCoordinator(destination);

        assertSingleTarget(response, destination.getParent(), FAILURE_AGENT_NOT_FOUND);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_SingleWorker() {
        SimulatorAddress destination = new SimulatorAddress(WORKER, 1, 1, 0);
        Response response = sendFromCoordinator(destination);

        assertSingleTarget(response, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_AllWorker() {
        SimulatorAddress destination = new SimulatorAddress(WORKER, 0, 0, 0);
        Response response = sendFromCoordinator(destination);

        assertAllTargets(response, destination, SUCCESS, 4);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_WorkerNotFound() {
        SimulatorAddress destination = new SimulatorAddress(WORKER, 1, 3, 0);
        Response response = sendFromCoordinator(destination);

        assertSingleTarget(response, destination.getParent(), FAILURE_WORKER_NOT_FOUND);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_AllAgents_WorkerNotFound() {
        SimulatorAddress destination = new SimulatorAddress(WORKER, 0, 3, 0);
        Response response = sendFromCoordinator(destination);

        assertAllTargets(response, destination.getParent(), FAILURE_WORKER_NOT_FOUND, 2);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_SingleTest() {
        SimulatorAddress destination = new SimulatorAddress(TEST, 1, 1, 1);
        Response response = sendFromCoordinator(destination);

        assertSingleTarget(response, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_AllTests() {
        SimulatorAddress destination = new SimulatorAddress(TEST, 0, 0, 0);
        Response response = sendFromCoordinator(destination);

        assertAllTargets(response, destination, SUCCESS, 8);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_TestNotFound() {
        SimulatorAddress destination = new SimulatorAddress(TEST, 1, 1, 3);
        Response response = sendFromCoordinator(destination);

        assertSingleTarget(response, destination.getParent(), FAILURE_TEST_NOT_FOUND);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_AllAgents_AllWorkers_TestNotFound() {
        SimulatorAddress destination = new SimulatorAddress(TEST, 0, 0, 3);
        Response response = sendFromCoordinator(destination);

        assertAllTargets(response, destination.getParent(), FAILURE_TEST_NOT_FOUND, 4);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_Coordinator_fromAgent() {
        AgentConnector agent = getAgentConnector(0);
        SimulatorAddress source = agent.getAddress();
        SimulatorAddress destination = COORDINATOR;
        Response response = agent.write(destination, DEFAULT_OPERATION);

        assertSingleTarget(response, source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_Coordinator_fromAgent_async() throws Exception {
        AgentConnector agent = getAgentConnector(0);
        SimulatorAddress source = agent.getAddress();
        SimulatorAddress destination = COORDINATOR;
        ResponseFuture future = agent.writeAsync(destination, DEFAULT_OPERATION);

        assertSingleTarget(future.get(), source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_Coordinator_fromWorker() {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress();
        SimulatorAddress destination = COORDINATOR;
        Response response = worker.write(destination, DEFAULT_OPERATION);

        assertSingleTarget(response, source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_Coordinator_fromWorker_async() throws Exception {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress();
        SimulatorAddress destination = COORDINATOR;
        ResponseFuture future = worker.writeAsync(destination, DEFAULT_OPERATION);

        assertSingleTarget(future.get(), source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_Coordinator_fromTest() {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress().getChild(1);
        SimulatorAddress destination = COORDINATOR;
        Response response = worker.write(source, destination, DEFAULT_OPERATION);

        assertSingleTarget(response, source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_Coordinator_fromTest_async() throws Exception {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress().getChild(1);
        SimulatorAddress destination = COORDINATOR;
        ResponseFuture future = worker.writeAsync(source, destination, DEFAULT_OPERATION);

        assertSingleTarget(future.get(), source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_ParentAgent_fromWorker() {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress();
        SimulatorAddress destination = source.getParent();
        Response response = worker.write(destination, DEFAULT_OPERATION);

        assertSingleTarget(response, source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_ParentAgent_fromWorker_async() throws Exception {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress();
        SimulatorAddress destination = source.getParent();
        ResponseFuture future = worker.writeAsync(destination, DEFAULT_OPERATION);

        assertSingleTarget(future.get(), source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_ParentAgent_fromTest() {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress().getChild(1);
        SimulatorAddress destination = worker.getAddress().getParent();
        Response response = worker.write(source, destination, DEFAULT_OPERATION);

        assertSingleTarget(response, source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_ParentAgent_fromTest_async() throws Exception {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress().getChild(1);
        SimulatorAddress destination = worker.getAddress().getParent();
        ResponseFuture future = worker.writeAsync(source, destination, DEFAULT_OPERATION);

        assertSingleTarget(future.get(), source, destination, SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_SingleWorker_withExceptionDuringOperationProcessing() {
        SimulatorAddress destination = getWorkerConnector(0).getAddress();
        SimulatorOperation operation = new IntegrationTestOperation("foobar");

        Response response = sendFromCoordinator(destination, operation);

        assertSingleTarget(response, destination, ResponseType.EXCEPTION_DURING_OPERATION_EXECUTION);

        assertTrueEventually(new AssertTask() {
            @Override
            public void run() {
                assertEquals(1, getCoordinatorConnector().getExceptionCount());
                assertEmptyFutureMaps();
            }
        }, ASSERT_EVENTUALLY_TIMEOUT_SECONDS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_LogOperation_SingleAgent() {
        SimulatorAddress destination = new SimulatorAddress(AGENT, 1, 0, 0);
        SimulatorOperation operation = new LogOperation(COORDINATOR, "Please log me on " + destination + "!");

        Response response = sendFromCoordinator(destination, operation);

        assertSingleTarget(response, destination, ResponseType.SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_LogOperation_SingleWorker() {
        SimulatorAddress destination = new SimulatorAddress(WORKER, 1, 1, 0);
        SimulatorOperation operation = new LogOperation(COORDINATOR, "Please log me on " + destination + "!", Level.WARN);

        Response response = sendFromCoordinator(destination, operation);

        assertSingleTarget(response, destination, ResponseType.SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_LogOperation_SingleTest() {
        SimulatorAddress destination = new SimulatorAddress(TEST, 1, 1, 1);
        SimulatorOperation operation = new LogOperation(COORDINATOR, "Please log me on " + destination + "!", Level.ERROR);

        Response response = sendFromCoordinator(destination, operation);

        assertSingleTarget(response, destination, ResponseType.SUCCESS);
    }

    @Test(timeout = DEFAULT_TEST_TIMEOUT_MILLIS)
    public void test_LogOperation_Coordinator_fromTest() {
        WorkerConnector worker = getWorkerConnector(0);
        SimulatorAddress source = worker.getAddress().getChild(1);
        SimulatorAddress destination = COORDINATOR;

        SimulatorOperation operation = new LogOperation(COORDINATOR, "Please log me on " + destination + "!", Level.FATAL);

        Response response = worker.write(source, destination, operation);

        assertSingleTarget(response, source, destination, ResponseType.SUCCESS);
    }
}


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

		<title>sotdl-chargen</title>

			See the GitHub repo for license and code.
			Any text taken from the game is used with permission and remains © 2015 Schwalb Entertainment, LLC.


text:
module AuthNetReceiver
  class ApplicationController < ActionController::Base
  end
end


text:
package hmi.graphics.collada;

import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;

import java.io.IOException;

/**
 * Declares the binding of geometric primitives and vertex attributes for a mesh element.
 * @author Job Zwiers
 */
public class PolyList extends PrimitiveMeshElement {

   private P p;
   private VCount vcount;

   /**
    * Default constructor
    */
   public PolyList() {
      super();
      setMeshType(Mesh.MeshType.Polylist);
   }

   /**
    * Constructor used to create a PolyList Object from XML
    */
   public PolyList(Collada collada, XMLTokenizer tokenizer) throws IOException {
      super(collada);
      readXML(tokenizer);
      setMeshType(Mesh.MeshType.Polylist);
   }

   /**
    * Returns the polygon vertex counts, i.e. one integer value for every polygon,
    * denoting the number of vertices for that polygon
    */
   public int[] getVCounts() {
      return vcount.getCounts();
   }

   @Override
   public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt) {
      appendXMLStructureList(buf, fmt, getInputs());
      appendXMLStructure(buf, fmt, vcount);
      appendXMLStructure(buf, fmt, p);
      appendXMLStructureList(buf, fmt, getExtras());
      return buf;
   }

   @Override
   public void decodeContent(XMLTokenizer tokenizer) throws IOException {
      while (tokenizer.atSTag()) {
         String tag = tokenizer.getTagName();
         if (tag.equals(Input.xmlTag()))  {
             Input inp = new Input(getCollada(), tokenizer);
             getInputs().add(inp);
             if (inp.getOffset() > getMaxOffset()) setMaxOffset(inp.getOffset());
         } else if (tag.equals(Extra.xmlTag()))  {
             getExtras().add(new Extra(getCollada(), tokenizer));
         } else if (tag.equals(VCount.xmlTag()))  {
             vcount = new VCount(getCollada(), tokenizer);
         } else if (tag.equals(P.xmlTag()))  {
             p = new P(getCollada(), tokenizer);
         } else {
            getCollada().warning(tokenizer.getErrorMessage("PolyList: skip : " + tokenizer.getTagName()));
            tokenizer.skipTag();
         }
      }
      addColladaNodes(getInputs());
      addColladaNodes(getExtras());
      addColladaNode(vcount);
      addColladaNode(p);
   }

   /*
    * The XML Stag for XML encoding
    */
   private static final String XMLTAG = "polylist";

   /**
    * The XML Stag for XML encoding
    */
   public static String xmlTag() { return XMLTAG; }

   /**
    * returns the XML Stag for XML encoding
    */
   @Override
   public String getXMLTag() {
      return XMLTAG;
   }

   /*
    * creates separate index arrays from the single P index list, dividing up according
    * to the number of offsets used in the inputs
    */
   @Override
   public void createIndexArrays() {
      int[] pindices = p.getIndices();
      setNrOfOffsets(getMaxOffset()+1);
      setIndexArrayLength(pindices.length/getNrOfOffsets());
      if (pindices.length % getNrOfOffsets() != 0 ) {
         getCollada().warning("Warning: PolyList.createIndexArrays: number of P indices ("
           + pindices.length + ") is not a multiple of the number of offsets (" + getNrOfOffsets() + ")" );
      }
      allocateIndices(getNrOfOffsets(), getIndexArrayLength());
      int noffsets = getNrOfOffsets();
      for (int indexOffset = 0; indexOffset < noffsets; indexOffset++) {
         int[] indices = getIndices(indexOffset);
         for (int i=0; i<getIndexArrayLength(); i++) {
            indices[i] = pindices[ i*noffsets + indexOffset];
         }
      }
   }

}


text:
"""
The :class:`~IPython.core.application.Application` object for the command
line :command:`ipython` program.

Authors
-------

* Brian Granger
* Fernando Perez
* Min Ragan-Kelley
"""

#-----------------------------------------------------------------------------
#  Copyright (C) 2008-2011  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from __future__ import absolute_import

import logging
import os
import sys

from IPython.config.loader import (
    Config, PyFileConfigLoader, ConfigFileNotFound
)
from IPython.config.application import boolean_flag, catch_config_error
from IPython.core import release
from IPython.core import usage
from IPython.core.completer import IPCompleter
from IPython.core.crashhandler import CrashHandler
from IPython.core.formatters import PlainTextFormatter
from IPython.core.history import HistoryManager
from IPython.core.prompts import PromptManager
from IPython.core.application import (
    ProfileDir, BaseIPythonApplication, base_flags, base_aliases
)
from IPython.core.magics import ScriptMagics
from IPython.core.shellapp import (
    InteractiveShellApp, shell_flags, shell_aliases
)
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
from IPython.lib import inputhook
from IPython.utils import warn
from IPython.utils.path import get_ipython_dir, check_for_old_config
from IPython.utils.traitlets import (
    Bool, List, Dict, CaselessStrEnum
)

#-----------------------------------------------------------------------------
# Globals, utilities and helpers
#-----------------------------------------------------------------------------

#: The default config file name for this application.
default_config_file_name = u'ipython_config.py'

_examples = """
ipython --pylab            # start in pylab mode
ipython --pylab=qt         # start in pylab mode with the qt4 backend
ipython --log-level=DEBUG  # set logging to DEBUG
ipython --profile=foo      # start with profile foo

ipython qtconsole          # start the qtconsole GUI application
ipython help qtconsole     # show the help for the qtconsole subcmd

ipython console            # start the terminal-based console application
ipython help console       # show the help for the console subcmd

ipython notebook           # start the IPython notebook
ipython help notebook      # show the help for the notebook subcmd

ipython profile create foo # create profile foo w/ default config files
ipython help profile       # show the help for the profile subcmd

ipython locate             # print the path to the IPython directory
ipython locate profile foo # print the path to the directory for profile `foo`
"""

#-----------------------------------------------------------------------------
# Crash handler for this application
#-----------------------------------------------------------------------------

class IPAppCrashHandler(CrashHandler):
    """sys.excepthook for IPython itself, leaves a detailed report on disk."""

    def __init__(self, app):
        contact_name = release.authors['Fernando'][0]
        contact_email = release.author_email
        bug_tracker = 'https://github.com/ipython/ipython/issues'
        super(IPAppCrashHandler,self).__init__(
            app, contact_name, contact_email, bug_tracker
        )

    def make_report(self,traceback):
        """Return a string containing a crash report."""

        sec_sep = self.section_sep
        # Start with parent report
        report = [super(IPAppCrashHandler, self).make_report(traceback)]
        # Add interactive-specific info we may have
        rpt_add = report.append
        try:
            rpt_add(sec_sep+"History of session input:")
            for line in self.app.shell.user_ns['_ih']:
                rpt_add(line)
            rpt_add('\n*** Last line of input (may not be in above history):\n')
            rpt_add(self.app.shell._last_input_line+'\n')
        except:
            pass

        return ''.join(report)

#-----------------------------------------------------------------------------
# Aliases and Flags
#-----------------------------------------------------------------------------
flags = dict(base_flags)
flags.update(shell_flags)
frontend_flags = {}
addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
        'Turn on auto editing of files with syntax errors.',
        'Turn off auto editing of files with syntax errors.'
)
addflag('banner', 'TerminalIPythonApp.display_banner',
        "Display a banner upon starting IPython.",
        "Don't display a banner upon starting IPython."
)
addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
    """Set to confirm when you try to exit IPython with an EOF (Control-D
    in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
    you can force a direct exit without any confirmation.""",
    "Don't prompt the user when exiting."
)
addflag('term-title', 'TerminalInteractiveShell.term_title',
    "Enable auto setting the terminal title.",
    "Disable auto setting the terminal title."
)
classic_config = Config()
classic_config.InteractiveShell.cache_size = 0
classic_config.PlainTextFormatter.pprint = False
classic_config.PromptManager.in_template = '>>> '
classic_config.PromptManager.in2_template = '... '
classic_config.PromptManager.out_template = ''
classic_config.InteractiveShell.separate_in = ''
classic_config.InteractiveShell.separate_out = ''
classic_config.InteractiveShell.separate_out2 = ''
classic_config.InteractiveShell.colors = 'NoColor'
classic_config.InteractiveShell.xmode = 'Plain'

frontend_flags['classic']=(
    classic_config,
    "Gives IPython a similar feel to the classic Python prompt."
)
# # log doesn't make so much sense this way anymore
# paa('--log','-l',
#     action='store_true', dest='InteractiveShell.logstart',
#     help="Start logging to the default log file (./ipython_log.py).")
#
# # quick is harder to implement
frontend_flags['quick']=(
    {'TerminalIPythonApp' : {'quick' : True}},
    "Enable quick startup with no config files."
)

frontend_flags['i'] = (
    {'TerminalIPythonApp' : {'force_interact' : True}},
    """If running code from the command line, become interactive afterwards.
    Note: can also be given simply as '-i.'"""
)
flags.update(frontend_flags)

aliases = dict(base_aliases)
aliases.update(shell_aliases)

#-----------------------------------------------------------------------------
# Main classes and functions
#-----------------------------------------------------------------------------

class LocateIPythonApp(BaseIPythonApplication):
    description = """print the path to the IPython dir"""
    subcommands = Dict(dict(
        profile=('IPython.core.profileapp.ProfileLocate',
            "print the path to an IPython profile directory",
        ),
    ))
    def start(self):
        if self.subapp is not None:
            return self.subapp.start()
        else:
            print self.ipython_dir

class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
    name = u'ipython'
    description = usage.cl_usage
    default_config_file_name = default_config_file_name
    crash_handler_class = IPAppCrashHandler
    examples = _examples

    flags = Dict(flags)
    aliases = Dict(aliases)
    classes = List()
    def _classes_default(self):
        """This has to be in a method, for TerminalIPythonApp to be available."""
        return [
            InteractiveShellApp, # ShellApp comes before TerminalApp, because
            self.__class__,      # it will also affect subclasses (e.g. QtConsole)
            TerminalInteractiveShell,
            PromptManager,
            HistoryManager,
            ProfileDir,
            PlainTextFormatter,
            IPCompleter,
            ScriptMagics,
        ]

    subcommands = Dict(dict(
        qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
            """Launch the IPython Qt Console."""
        ),
        notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
            """Launch the IPython HTML Notebook Server."""
        ),
        profile = ("IPython.core.profileapp.ProfileApp",
            "Create and manage IPython profiles."
        ),
        kernel = ("IPython.zmq.ipkernel.IPKernelApp",
            "Start a kernel without an attached frontend."
        ),
        console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp',
            """Launch the IPython terminal-based Console."""
        ),
        locate=('IPython.frontend.terminal.ipapp.LocateIPythonApp',
            LocateIPythonApp.description
        ),
    ))

    # *do* autocreate requested profile, but don't create the config file.
    auto_create=Bool(True)
    # configurables
    ignore_old_config=Bool(False, config=True,
        help="Suppress warning messages about legacy config files"
    )
    quick = Bool(False, config=True,
        help="""Start IPython quickly by skipping the loading of config files."""
    )
    def _quick_changed(self, name, old, new):
        if new:
            self.load_config_file = lambda *a, **kw: None
            self.ignore_old_config=True

    display_banner = Bool(True, config=True,
        help="Whether to display a banner upon starting IPython."
    )

    # if there is code of files to run from the cmd line, don't interact
    # unless the --i flag (App.force_interact) is true.
    force_interact = Bool(False, config=True,
        help="""If a command or file is given via the command-line,
        e.g. 'ipython foo.py"""
    )
    def _force_interact_changed(self, name, old, new):
        if new:
            self.interact = True

    def _file_to_run_changed(self, name, old, new):
        if new:
            self.something_to_run = True
        if new and not self.force_interact:
                self.interact = False
    _code_to_run_changed = _file_to_run_changed
    _module_to_run_changed = _file_to_run_changed

    # internal, not-configurable
    interact=Bool(True)
    something_to_run=Bool(False)

    def parse_command_line(self, argv=None):
        """override to allow old '-pylab' flag with deprecation warning"""

        argv = sys.argv[1:] if argv is None else argv

        if '-pylab' in argv:
            # deprecated `-pylab` given,
            # warn and transform into current syntax
            argv = argv[:] # copy, don't clobber
            idx = argv.index('-pylab')
            warn.warn("`-pylab` flag has been deprecated.\n"
            "    Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
            sub = '--pylab'
            if len(argv) > idx+1:
                # check for gui arg, as in '-pylab qt'
                gui = argv[idx+1]
                if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
                    sub = '--pylab='+gui
                    argv.pop(idx+1)
            argv[idx] = sub

        return super(TerminalIPythonApp, self).parse_command_line(argv)

    @catch_config_error
    def initialize(self, argv=None):
        """Do actions after construct, but before starting the app."""
        super(TerminalIPythonApp, self).initialize(argv)
        if self.subapp is not None:
            # don't bother initializing further, starting subapp
            return
        if not self.ignore_old_config:
            check_for_old_config(self.ipython_dir)
        # print self.extra_args
        if self.extra_args and not self.something_to_run:
            self.file_to_run = self.extra_args[0]
        self.init_path()
        # create the shell
        self.init_shell()
        # and draw the banner
        self.init_banner()
        # Now a variety of things that happen after the banner is printed.
        self.init_gui_pylab()
        self.init_extensions()
        self.init_code()

    def init_shell(self):
        """initialize the InteractiveShell instance"""
        # Create an InteractiveShell instance.
        # shell.display_banner should always be False for the terminal
        # based app, because we call shell.show_banner() by hand below
        # so the banner shows *before* all extension loading stuff.
        self.shell = TerminalInteractiveShell.instance(config=self.config,
                        display_banner=False, profile_dir=self.profile_dir,
                        ipython_dir=self.ipython_dir)
        self.shell.configurables.append(self)

    def init_banner(self):
        """optionally display the banner"""
        if self.display_banner and self.interact:
            self.shell.show_banner()
        # Make sure there is a space below the banner.
        if self.log_level <= logging.INFO: print

    def _pylab_changed(self, name, old, new):
        """Replace --pylab='inline' with --pylab='auto'"""
        if new == 'inline':
            warn.warn("'inline' not available as pylab backend, "
                      "using 'auto' instead.\n")
            self.pylab = 'auto'

    def start(self):
        if self.subapp is not None:
            return self.subapp.start()
        # perform any prexec steps:
        if self.interact:
            self.log.debug("Starting IPython's mainloop...")
            self.shell.mainloop()
        else:
            self.log.debug("IPython not interactive...")

def load_default_config(ipython_dir=None):
    """Load the default config file from the default ipython_dir.

    This is useful for embedded shells.
    """
    if ipython_dir is None:
        ipython_dir = get_ipython_dir()
    profile_dir = os.path.join(ipython_dir, 'profile_default')
    cl = PyFileConfigLoader(default_config_file_name, profile_dir)
    try:
        config = cl.load_config()
    except ConfigFileNotFound:
        # no config found
        config = Config()
    return config

def launch_new_instance():
    """Create and run a full blown IPython instance"""
    app = TerminalIPythonApp.instance()
    app.initialize()
    app.start()

if __name__ == '__main__':
    launch_new_instance()


text:
FROM jenkinsci/jenkins
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
COPY executors.groovy /usr/share/jenkins/ref/init.groovy.d/executors.groovy
USER root
# TODO docker-compose oracle-java9-installer oracle-java9-set-default oracle-java9-unlimited-jce-policy php-cli
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y \
 apt-transport-https \
 aptitude \
 ca-certificates-java \
 software-properties-common \
 && apt-add-repository -y non-free \
 && apt-add-repository -y contrib \
 && apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys \
 58118E89F3A912897C070ADBF76221572C52609D \
 && apt-add-repository -y "deb https://apt.dockerproject.org/repo debian-jessie main" \
 && aptitude update \
 && DEBIAN_FRONTEND=noninteractive aptitude --with-recommends full-upgrade -y \
 && DEBIAN_FRONTEND=noninteractive aptitude --with-recommends -y install \
 ant \
 binfmt-support \
 default-jdk \
 docker.io \
 git \
 gradle \
 gradle-doc \
 maven \
 mercurial \
 phing \
 php5-cli \
 scala \
 scala-doc \
 doxygen \
 doxygen-doc \
 doxygen-latex \
 graphviz \
 graphviz-doc \
 gsfonts
USER jenkins
ENV CURL_CONNECTION_TIMEOUT 60
RUN /usr/local/bin/install-plugins.sh < /usr/share/jenkins/ref/plugins.txt


text:
(function(buster, unfold, when) {

var assert, refute, fail, sentinel, other;

assert = buster.assert;
refute = buster.refute;
fail = buster.assertions.fail;

sentinel = {};
other = {};

function noop() {}

buster.testCase('when/unfold', {

	'should invoke condition first': function(done) {
		var condition;

		condition = this.stub().returns(true);

		unfold(noop, condition, noop, sentinel).then(
			function(value) {
				assert.same(value, sentinel);
			}
		).always(done);
	},

	'should call generator until condition returns truthy': function(done) {
		function condition(i) {
			return i == 0;
		}

		var unspool = this.spy(function(x) {
			return [x, x-1];
		});

		unfold(unspool, condition, noop, 3).then(
			function() {
				assert.equals(unspool.callCount, 3);
			}
		).always(done);
	},

	'generator': {
		'should be allowed to return an array of promises': function(done) {
			function condition(i) {
				return i == 0;
			}

			var unspool = this.spy(function(x) {
				return [when.resolve(x), when.resolve(x-1)];
			});

			unfold(unspool, condition, noop, 3).then(
				function() {
					assert.equals(unspool.callCount, 3);
				}
			).always(done);
		},

		'should be allowed to return a promise for an array': function(done) {
			function condition(i) {
				return i == 0;
			}

			var unspool = this.spy(function(x) {
				return when.resolve([x, x-1]);
			});

			unfold(unspool, condition, noop, 3).then(
				function() {
					assert.equals(unspool.callCount, 3);
				}
			).always(done);
		},

		'should be allowed to return a promise for an array of promises': function(done) {
			function condition(i) {
				return i == 0;
			}

			var unspool = this.spy(function(x) {
				return when.resolve([when.resolve(x), when.resolve(x-1)]);
			});

			unfold(unspool, condition, noop, 3).then(
				function() {
					assert.equals(unspool.callCount, 3);
				}
			).always(done);
		}
	},

	'condition': {
		'should be allowed to return a promise that fulfills': function(done) {
			function condition(i) {
				return when.resolve(i == 0);
			}

			var unspool = this.spy(function(x) {
				return [x, x-1];
			});

			unfold(unspool, condition, noop, 3).then(
				function() {
					assert.equals(unspool.callCount, 3);
				}
			).always(done);
		},

		'should abort unfold by returning a rejection': function(done) {
			function condition() {
				return when.reject();
			}

			var unspool = this.spy();

			unfold(unspool, condition, noop, 3).then(
				fail,
				function() {
					refute.called(unspool);
				}
			).always(done);
		}
	},

	'should call handler with generator result': function(done) {
		function condition(i) {
			return i == 0;
		}

		var handler = this.spy();

		unfold(this.stub().returns([sentinel, 0]), condition, handler).then(
			function() {
				assert.calledOnceWith(handler, sentinel);
			}
		).always(done);
	},

	'should reject when condition throws': function(done) {
		var condition, handler, generator;

		generator = this.spy();
		handler = this.spy();
		condition = this.stub().throws(sentinel);

		unfold(generator, condition, handler, other).then(
			fail,
			function(e) {
				refute.called(generator);
				refute.called(handler);
				assert.same(e, sentinel);
			}
		).always(done);

	},

	'should reject when generator throws': function(done) {
		var condition, handler, generator;

		condition = this.stub().returns(false);
		handler = this.spy();
		generator = this.stub().throws(sentinel);

		unfold(generator, condition, handler, other).then(
			fail,
			function(e) {
				refute.called(handler);
				assert.same(e, sentinel);
			}
		).always(done);
	},

	'should reject when transform throws': function(done) {
		var condition, transform, generator;

		condition = this.stub().returns(false);
		transform = this.stub().throws(sentinel);
		generator = this.stub().returns([other, other]);

		unfold(generator, condition, transform, other).then(
			fail,
			function(e) {
				assert.same(e, sentinel);
			}
		).always(done);
	}

});
})(
	this.buster || require('buster'),
	this.when_unfold || require('../unfold'),
	this.when || require('../when')
);