text:
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->

# Beam Katas
Beam Katas are interactive Beam coding exercises (i.e. [code katas](http://codekata.com/))
that can help you to learn Apache Beam concepts and programming model hands-on.
Built based on [JetBrains Educational Products](https://www.jetbrains.com/education/), Beam Katas
objective is to provide a series of structured hands-on learning experiences for learners
to understand about Apache Beam and its SDKs by solving exercises with gradually increasing
complexity. Beam Katas are available for both Java and Python SDKs.

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0'?>
<test  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation="gDay_minExclusive002.xsd" >
<!-- facet=minExclusive and value=- - -15 and document value=- - -01 -->
  <foo>---01</foo>
</test>


text:
/*
 * File:   RPCRuntimeManagerObjectClient.h
 * Author: rmartins
 *
 * Created on February 8, 2011, 11:00 AM
 */

#ifndef RPCRUNTIMEMANAGEROBJECTCLIENT_H
#define	RPCRUNTIMEMANAGEROBJECTCLIENT_H

#include <stheno/services/rpc/RPCService.h>
#include <stheno/services/rpc/RPCServiceClient.h>
#include <stheno/services/rpc/RPCTestObject.h>

class RPCRuntimeManagerObjectClient {
public:
    RPCRuntimeManagerObjectClient(RPCServiceClient* rpcRPCServiceClient);
    virtual ~RPCRuntimeManagerObjectClient();

    void hardFault() {
        size_t size = 10024;
        ByteOutputStream os(size);
        os.write_ushort(RPCRuntimeManagerObject::HARD_FAULT_OP);
        ACE_Message_Block* payload = os.begin()->duplicate();
        try {
            m_rpcRPCServiceClient->oneWayInvocation(m_oid, payload);
        } catch (RPCException& ex) {
            printf("Exception! in RPC - 1way\n");
        }

    }

    bool temporaryFault(ACE_Time_Value& duration) {
        size_t size = 10024;
        ByteOutputStream os(size);
        os.write_ushort(RPCRuntimeManagerObject::TEMP_FAULT_OP);
        os.write_longlong(duration.sec());
        os.write_ulonglong(duration.usec());
        ACE_Message_Block* payload = os.begin()->duplicate();
        ACE_Message_Block* reply = 0;
        try {
            reply = m_rpcRPCServiceClient->twoWayInvocation(m_oid, payload);
        } catch (RPCException& ex) {
            printf("Exception! in RPC\n");
            return 0;
        }
        if (reply == 0) {
            ACE_Message_Block::release(reply);
            return 0;
        }

        ByteInputStream is(reply);
        ACE_Message_Block::release(reply);
        bool ret = 0;
        is.read_boolean(ret);
        return ret;
    }

    void close() {
        if (m_rpcRPCServiceClient != 0) {
            m_rpcRPCServiceClient->close();
            delete m_rpcRPCServiceClient;
            m_rpcRPCServiceClient = 0;
        }

    }

protected:
    RPCServiceClient* m_rpcRPCServiceClient;
    UUIDPtr m_oid;
};

#endif	/* RPCRUNTIMEMANAGEROBJECTCLIENT_H */


text:
using System.Threading;
using Xunit;

public partial class ThreadPoolBoundHandleTests
{
    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public void Dispose_CalledMultipleTimes_DoesNotThrow()
    {
        ThreadPoolBoundHandle boundHandle = CreateThreadPoolBoundHandle();

        boundHandle.Dispose();
        boundHandle.Dispose();
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public void Dispose_DoesNotDisposeHandle()
    {
        ThreadPoolBoundHandle boundHandle = CreateThreadPoolBoundHandle();

        Assert.False(boundHandle.Handle.IsClosed);

        boundHandle.Dispose();

        Assert.False(boundHandle.Handle.IsClosed);
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void Dispose_WithoutFreeingNativeOverlapped_DoesNotThrow()
    {
        ThreadPoolBoundHandle boundHandle = CreateThreadPoolBoundHandle();

        NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[1024]);

        boundHandle.Dispose();
    }
}


text:
require "immu/version"
require "immu/helpers"
require "immu/repo"

module Immu
  include Helpers

  def self.included model
    model.class_eval do
      extend Helpers
      include Repo

      class << self
        @@values = {}

        def val value, type, options = {}
          dogged_value = doggieze value

          define_method(value) do
            instance_variable_get dogged_value
          end

          @@values[value] = { type: type, default: options[:default] }
        end

        def create args = {}
          args.each do |k, v|
            raise ArgumentError.new('Invalid type') unless v.is_a?(@@values[k.to_sym][:type])
          end

          new_args = {}
          @@values.each do |value, options|
            new_args[value] = args[value] || args[value.to_s] || options[:default]
          end

          self.new new_args
        end
      end
    end
  end

  def initialize args = {}
    args.each do |k, v|
      instance_variable_set doggieze(k), v
    end
  end

  def values
    instance_variables.each_with_object({}) do |variable, object|
      object[variable[1..-1]] = instance_variable_get variable
    end
  end
end


text:
.class public interface abstract Lcom/upsight/android/internal/persistence/storable/StorableIdentifierAccessor;
.super Ljava/lang/Object;
.source "StorableIdentifierAccessor.java"

# virtual methods
.method public abstract getId(Ljava/lang/Object;)Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/upsight/android/UpsightException;
        }
    .end annotation
.end method

.method public abstract setId(Ljava/lang/Object;Ljava/lang/String;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/upsight/android/UpsightException;
        }
    .end annotation
.end method


text:
<?php namespace Aedart\Scaffold\Containers;

use Aedart\Scaffold\Exceptions\ForbiddenException;
use Aedart\Scaffold\Providers\ScaffoldServiceProvider;
use Aedart\Util\Interfaces\Populatable;
use Illuminate\Container\Container;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Support\Facades\App;

/**
 * IoC Service Container (Wrapper)
 *
 * This class acts first and foremost as a wrapper for Laravel's
 * service container. Secondly, additional application logic has
 * been added, in regards to resolving instances from specifiable
 * configuration repositories and bootstrapping; it ensures that
 * this package's service provider is registered.
 *
 * @see \Illuminate\Contracts\Container\Container
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Resolvers
 */
class IoC
{
    /**
     * Instance of this resolver
     *
     * @var self
     */
    private static $instance;

    /**
     * IoC Service Container instance
     *
     * @var \Illuminate\Contracts\Container\Container
     */
    protected $container;

    /**
     * List of service providers that
     * this IoC / application is using
     *
     * @var string[]
     */
    protected $providers = [
        ScaffoldServiceProvider::class
    ];

    /**
     * Get the resolver instance
     *
     * @return self
     */
    static public function getInstance()
    {
        if(null === static::$instance){
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * Boot the IoC (Alias for the getInstance method)
     *
     * @see getInstance()
     *
     * @return IoC
     */
    static public function boot()
    {
        return self::getInstance();
    }

    /**
     * IoC constructor.
     */
    private function __construct()
    {
        $this->setupContainer();
        $this->registerServiceProviders($this->providers);
    }

    /**
     * Force destroy the container
     *
     * WARNING: Avoid using this, unless you really need to
     * destroy the IoC!
     */
    public function destroy()
    {
        $this->container = null;

        App::clearResolvedInstances();
        App::setFacadeApplication(null);

        self::$instance = null;
    }

    /**
     * Initialise the IoC Service Container
     */
    protected function setupContainer(){
        // Only set the application on the Facade
        // if there is none yet set
        if(is_null(App::getFacadeApplication())){
            App::setFacadeApplication(new Container());
        }

        $this->container = App::getFacadeApplication();

        $this->container->singleton('app', $this->container);
    }

    /**
     * Register this application's service providers
     *
     * @param string[] $providers [optional]
     */
    public function registerServiceProviders(array $providers = [])
    {
        foreach($providers as $provider){
            (new $provider($this->container()))->register();
        }
    }

    /**
     * Resolve a given instance based on the concrete instance
     * that is found in the configuration. If there is no
     * instance that can be resolved from the config, then a
     * default instance is attempted to be resolved
     *
     * @param string $entry Configuration or instance identifier
     * @param Repository $config
     * @param array $parameters [optional]
     *
     * @return mixed
     */
    public function resolveFromConfig($entry, Repository $config, array $parameters = [])
    {
        if($config->has($entry)){
            $instance = $config->get($entry);
            $instance = new $instance;
        } else {
            $instance = $this->container()->make($entry);
        }

        if($instance instanceof Populatable){
            $instance->populate($parameters);
        }

        return $instance;
    }

    /**
     * Alias for Container::make
     *
     * @param string $concrete
     *
     * @see \Illuminate\Contracts\Container\Container::make()
     *
     * @return mixed
     */
    public function make($concrete)
    {
        return $this->container()->make($concrete);
    }

    /**
     * Resolve and configure a handler
     *
     * Method attempts to make an instance of a given handler,
     * from the given configuration, based on the alias.
     * If no alias is defined inside the configuration, a default
     * handler is attempted resolved, from the IoC.
     *
     * Furthermore, if a handler is created, it's base path and
     * output paths are also set, before it is returned. This
     * applies only if the given configuration has a 'basePath'
     * and an 'outputPath' set.
     *
     * @param string $alias
     * @param Repository $config
     * @param array $parameters [optional]
     *
     * @return \Aedart\Scaffold\Contracts\Handlers\Handler
     * @see IoC::resolveFromConfig()
     *
     */
    public function resolveHandler($alias, Repository $config, array $parameters = [])
    {
        /** @var \Aedart\Scaffold\Contracts\Handlers\Handler $handler */
        $handler = $this->resolveFromConfig($alias, $config, $parameters);

        // Set base path
        $basePathKey = 'basePath';
        if($config->has($basePathKey)){
            $handler->setBasePath($config->get($basePathKey));
        }

        // Set output path
        $outputPath = 'outputPath';
        if($config->has($outputPath)){
            $handler->setOutputPath($config->get($outputPath));
        }

        // Finally, return the handler
        return $handler;
    }

    /**
     * Get the IoC Service Container instance
     *
     * @return \Illuminate\Contracts\Container\Container
     */
    public function container()
    {
        return $this->container;
    }

    /**
     * Prevent clone operations
     */
    final public function __clone()
    {
        throw new ForbiddenException('Class is singleton. Clone is forbidden');
    }

    /**
     * Prevent initialisation
     */
    final public function __wakeup()
    {
        throw new ForbiddenException('Class is singleton. __wakeup is forbidden');
    }
}


text:
package com.piketec.tpt.api;

import java.rmi.RemoteException;

/**
 * An assessment variable is used to evaluate tests.
 *
 * @author Copyright (c) 2014-2021 Piketec GmbH - MIT License (MIT) - All rights reserved
 */
public interface AssessmentVariable extends Declaration {

  /**
   * Get if the assessment variable should be recorded during test execution.
   *
   * @return true if the assessment variable should be recorded, false
   *         otherwise.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  boolean isRecord() throws RemoteException;

  /**
   * Set if the assessment variable should be recorded during test execution.
   *
   * @param on
   *          true if the assessment variable should be recorded, false
   *          otherwise.
   *
   * @throws RemoteException
   *           remote communication problem
   */
  void setRecord(boolean on) throws RemoteException;

}


text:
Tabele dla "user has move to new location"

<tt>relocated_maps</tt>

Ten parametr okre¶la fakultatywne tabele zawieraj±ce informacje kontaktowe
dla u¿ytkowników, hostów lub domen, które ju¿ nie istniej±. Szczegó³y
znajdziesz w podstawianiu przeniesionych.

Domy¶lnie ta w³a¶ciwo¶æ jest wy³±czona.

Mo¿liwa rozs±dna warto¶æ: <tt>hash:/etc/postfix/relocated</tt>


text:
xl
==

*xml without mess.*

This is a Python module to process XML.

Why I am coding this?
---------------------
* lxml supports sub text node not clear enough.
* xml.etree.ElementTree doesn't care XML namespaces.
* I want to learn XML.

.. automodule:: epubaker.xl
    :members: parse, clean_whitespaces, pretty_insert

.. autoclass:: Xl
    :members:

.. autoclass:: Header
    :members:

.. autoclass:: DocType
    :members:

.. autoclass:: Element
    :members:


text:
#pragma once
#ifndef __BOXPLOT_H__
#define __BOXPLOT_H__

#include "plot/properties/boxPlotProperties.h"
#include "plot/pvec.h"

class Palette;

class BoxPlot
    : public BoxPlotProperties< BoxPlot >
{
public:

    enum Orientation
    {
        Vertical,
        Horizontal
    };

    BoxPlot(const PVec &x, const PVec &y);

    BoxPlot(const std::vector< std::pair< PVec, PVec >> &data);

    BoxPlot(const std::vector< std::pair< PVec, PVec >> &data, const std::vector< std::string > &hue);

    virtual std::string ToString() override;

    BoxPlot &SetOrder(const PVec &order);

    BoxPlot &SetHueOrder(const std::vector< std::string > &order);

    BoxPlot &SetOrientation(Orientation orientation);

    BoxPlot &SetColour(const std::string &colour);

    BoxPlot &SetColourMap(const Palette &pallet);

    BoxPlot &SetSaturation(double sat);

    BoxPlot &SetWidth(double width);

    BoxPlot &SetDodge(bool dodge);

    BoxPlot &SetFlierSize(double fliersize);

    BoxPlot &SetLineWidth(double width);

    BoxPlot &SetWhis(double whis);

    BoxPlot &Notch(bool notch);
};

#ifndef PLOTLIB_NO_HEADER_ONLY
#   include "../../src/boxPlot.cpp"
#endif

#endif


text:
/*
    You are given a MS SQL Server database "Ads" holding advertisements, organized by categories, towns and users, available as SQL script.
    Using Entity Framework write a SQL query to select all ads from the database and later print their title, status, category, town and user.
    Do not use Include(…) for the relationships of the Ads.
    Check how many SQL commands are executed with the SQL ExpressProfiler (or a similar tool).
    Add Include(…) to select statuses, categories, towns and users along with all ads.
    Compare the number of executed SQL statements and the performance before and after adding Include(…).
    For this problem you will have to submit the two versions of the program:
    the one with Include(…) and the one without Include(…). You will also need to fill the following table and submit it as a .txt file:

                            No Include(…)	With Include(…)
    Number of SQL statements

    You can optionally submit two screenshots of the SQL profiler tool – one for each case (with and without Include(…)).
    Here is a tool which can create text tables: http://ozh.github.io/ascii-tables/.
*/

namespace Problem01
{

    using System;
    using System.Data.Entity;
    using System.Linq;

    class RelatedTablesData
    {
        private static void RunQuery(string runParameter = null)
        {
            using (var db = new AdsEntities())
            {
                if (runParameter != null && runParameter.ToLower() == "include")
                {
                    // WITH INCLUDE
                    foreach (var ad in db.Ads
                        .Include(a => a.AdStatus).Include(a => a.Category).Include(a => a.AspNetUser).Include(a => a.Town))
                    {
                        Console.WriteLine("Title: {0}\r\nStatus: {1}\r\nCategory: {2}\r\nTown: {3}\r\nUser: {4}\r\n",
                            ad.Title,
                            ad.AdStatus.Status,
                            ad.CategoryId == null ? null : ad.Category.Name,
                            ad.TownId == null ? null : ad.Town.Name,
                            ad.AspNetUser.Name);
                    }
                }
                else if (runParameter == null || runParameter.ToLower() == "notInclude")
                {
                    // WITHOUT INCLUDE
                    foreach (var ad in db.Ads)
                    {
                        Console.WriteLine("Title: {0}\r\nStatus: {1}\r\nCategory: {2}\r\nTown: {3}\r\nUser: {4}\r\n",
                            ad.Title, ad.AdStatus.Status, ad.Category, ad.Town, ad.AspNetUser.Name);
                    }
                }
                else
                {
                    // INVALID RUN PARAMETER
                    throw new ArgumentException("Unknown run parameter.");
                }
            }
        }

        static void Main()
        {
            using (var db = new AdsEntities())
            {
                // QUERY WITHOUT INCLUDE
                RunQuery();

                // UNCOMENT TO USE (QUERY WITH INCLUDE)
                RunQuery("include");
            }
        }
    }
}


text:
package com.michaelbaranov.microba.gradient;

import java.awt.Color;

import javax.swing.SwingConstants;

import com.michaelbaranov.microba.common.BoundedTableModel;
import com.michaelbaranov.microba.common.MicrobaComponent;

/**
 * IMPORTANT: alpha featre not implemented. Stubs only.
 *

 *
 * A concrete implementation of JComponent. Displays an area filled with
 * gradient color (palette). The color and alpha value (transparency) is
 * linearly interpolated between key points.
 *

 * The color key points are provided by the data model in combination with color
 * column (index) and color position column (index). Each row in the model
 * represents a colored key point. Color values are expected to be of type
 * {@link Color} and position values of type {@link Number} with integer
 * precision.
 *

 * The alpha key points are provided by the alpha model in combination with
 * alpha column (index) and alpha position column (index). Each row in the model
 * represents an alpha key point. Alpha values are expected to be of type
 * {@link Number} with floating-point precision ranging form 0.0f (transparent)
 * to 1.0f (opaque) and position values of type {@link Number} with integer
 * precision.
 *
 * Example:
 *
 *

 * GradientBar bar = new GradientBar();
 * bar.setDataModel(myColorModel);
 * bar.setColorColumn(0);
 * bar.setColorPositionColumn(1);
 *
 * bar.setAlphaModel(myAlphaModel);
 * bar.setAlphaColumn(1);
 * bar.setAlphaPositionColumn(0);
 *

 *
 * @author Michael Baranov
 *
 */
public class GradientBar extends MicrobaComponent {

	/**
	 * The name of a "dataModel" property.
	 */
	public static final String PROPERTY_DATA_MODEL = "dataModel";

	/**
	 * The name of a "alphaModel" property.
	 */
	public static final String PROPERTY_ALPHA_MODEL = "alphaModel";

	/**
	 * The name of a "colorPositionColumn" property.
	 */
	public static final String PROPERTY_COLOR_POSITION_COLUMN = "colorPositionColumn";

	/**
	 * The name of a "alphaPositionColumn" property.
	 */
	public static final String PROPERTY_ALPHA_POSITION_COLUMN = "alphaPositionColumn";

	/**
	 * The name of a "colorColumn" property.
	 */
	public static final String PROPERTY_COLOR_COLUMN = "colorColumn";

	/**
	 * The name of a "alphaColumn" property.
	 */
	public static final String PROPERTY_ALPHA_COLUMN = "alphaColumn";

	/**
	 * The name of a "orientation" property.
	 */
	public static final String PROPERTY_ORIENTATION = "orientation";

	private static final String uiClassID = "microba.GradientUI";

	protected BoundedTableModel dataModel;

	protected BoundedTableModel alphaModel;

	protected int colorPositionColumn = 0;

	protected int alphaPositionColumn = 0;

	protected int colorColumn = 1;

	protected int alphaColumn = 1;

	protected int orientation = SwingConstants.HORIZONTAL;

	public String getUIClassID() {
		return uiClassID;
	}

	/**
	 * Constructor.
	 */
	public GradientBar() {
		super();
		dataModel = new DefaultGradientModel();
		setFocusable(false);
		updateUI();
	}

	/**
	 * Constructor.
	 */
	public GradientBar(BoundedTableModel model) {
		super();
		dataModel = model;
		setFocusable(false);
		updateUI();
	}

	/**
	 * Constructor.
	 */
	public GradientBar(BoundedTableModel model, int orientation) {
		super();
		dataModel = model;
		this.orientation = orientation;
		setFocusable(false);
		updateUI();
	}

	/**
	 * Returns the index of the color column for the data model.
	 *
	 * @return index of color column
	 * @see #setColorColumn(int)
	 */
	public int getColorColumn() {
		return colorColumn;
	}

	/**
	 * Sets the index of the color column for the data model.
	 *
	 * @param colorColumn
	 *            index of color column
	 * @see #getColorColumn()
	 */
	public void setColorColumn(int colorColumn) {
		int old = this.colorColumn;
		this.colorColumn = colorColumn;
		firePropertyChange(PROPERTY_COLOR_COLUMN, old, colorColumn);
	}

	/**
	 * Returns the index of the alpha column for the alpha model.
	 *
	 * @return index of alpha column
	 * @see #setAlphaColumn(int)
	 */
	public int getAlphaColumn() {
		return alphaColumn;
	}

	/**
	 * Sets the index of the alpha column for the alpha model.
	 *
	 * @param alphaColumn
	 *            index of alpha column
	 * @see #getAlphaColumn()
	 */
	public void setAlphaColumn(int alphaColumn) {
		int old = this.colorColumn;
		this.alphaColumn = alphaColumn;
		firePropertyChange(PROPERTY_ALPHA_COLUMN, old, alphaColumn);
	}

	/**
	 * Regturns the current data model. The data model provides key points for
	 * interpolation (position & color).
	 *
	 * @return current data model
	 * @see #setDataModel(BoundedTableModel)
	 * @see #getColorColumn()
	 */
	public BoundedTableModel getDataModel() {
		return dataModel;
	}

	/**
	 * Sets the current data model. The data model provides key points for
	 * interpolation (position & color).
	 *
	 * @param dataModel
	 *            current data model
	 * @see #getDataModel()
	 * @see #getColorColumn()
	 */
	public void setDataModel(BoundedTableModel dataModel) {
		BoundedTableModel old = this.dataModel;
		this.dataModel = dataModel;
		firePropertyChange(PROPERTY_DATA_MODEL, old, dataModel);
	}

	/**
	 * Regturns the current alpha model. The data model provides alpha key
	 * points for interpolation (position & alpha).
	 *
	 * @return current alpha model
	 * @see #setAlphaModel(BoundedTableModel)
	 * @see #getAlphaColumn()
	 */
	public BoundedTableModel getAlphaModel() {
		return alphaModel;
	}

	/**
	 * Sets the current alpha model. The alpha model provides alpha key points
	 * for interpolation (position & alpha).
	 *
	 * @param alphaModel
	 *            current alpha model
	 * @see #getAlphaModel()
	 * @see #getAlphaColumn()
	 */
	public void setAlphaModel(BoundedTableModel alphaModel) {
		BoundedTableModel old = this.alphaModel;
		this.alphaModel = alphaModel;
		firePropertyChange(PROPERTY_ALPHA_MODEL, old, alphaModel);
	}

	/**
	 * Returns current orientation of the component. Possible values are:
	 *

	 *
SwingConstants.HORIZONTAL
	 *
SwingConstants.VERTICAL
	 *

	 *
	 * @return orientation
	 * @see #setOrientation(int)
	 */
	public int getOrientation() {
		return orientation;
	}

	/**
	 * Sets orientation of the component. Possible values are:
	 *

	 *
SwingConstants.HORIZONTAL
	 *
SwingConstants.VERTICAL
	 *

	 *
	 * @param orientation
	 */
	public void setOrientation(int orientation) {
		int old = this.orientation;
		this.orientation = orientation;
		firePropertyChange(PROPERTY_ORIENTATION, old, orientation);
	}

	/**
	 * Returns the index of the position column for the data model.
	 *
	 * @return index of position column
	 * @see #setColorPositionColumn(int)
	 */
	public int getColorPositionColumn() {
		return colorPositionColumn;
	}

	/**
	 * Sets the index of the position column for the data model.
	 *
	 * @param positionColumn
	 *            index of position column
	 * @see #getColorPositionColumn()
	 */
	public void setColorPositionColumn(int positionColumn) {
		int old = this.colorPositionColumn;
		this.colorPositionColumn = positionColumn;
		firePropertyChange(PROPERTY_COLOR_POSITION_COLUMN, old, positionColumn);
	}

	/**
	 * Returns the index of the position column for the alpha model.
	 *
	 * @return index of position column
	 * @see #setAlphaPositionColumn(int)
	 */
	public int getAlphaPositionColumn() {
		return alphaPositionColumn;
	}

	/**
	 * Sets the index of the position column for the alpha model.
	 *
	 * @param positionColumn
	 *            index of position column
	 * @see #getAlphaPositionColumn()
	 */
	public void setAlphaPositionColumn(int positionColumn) {
		int old = this.alphaPositionColumn;
		this.alphaPositionColumn = positionColumn;
		firePropertyChange(PROPERTY_ALPHA_POSITION_COLUMN, old, positionColumn);
	}

}


text:
<#
Copyright 2016 ASOS.com Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#>

<#
.NAME
    Read-ScriptModuleVariableSet.Tests

.SYNOPSIS
    Pester tests for Read-ScriptModuleVariableSet.
#>

$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

InModuleScope "OctopusStepTemplateCi" {

    Describe "Read-ScriptModuleVariableSet" {

        Context "When reading a valid script file" {

            Mock -CommandName "Get-Content" `
                 -MockWith {
                     return @'
function test {
    $ScriptModuleName = "name";
    $ScriptModuleDescription = "description";
    write-host "test";
}
'@
                 };

            It "Should return a new object with the content type of script module" {
                $result = Read-ScriptModuleVariableSet -Path "my.variableset.ps1";
                $result.ContentType | Should Be "ScriptModule";
                Assert-VerifiableMock;
            }

            It "Should return a new object with the name from the script file" {
                $result = Read-ScriptModuleVariableSet -Path "my.variableset.ps1";
                $result.Name | Should Be "name";
                Assert-VerifiableMock;
            }

            It "Should return a new object with the description from the script file" {
                $result = Read-ScriptModuleVariableSet -Path "my.variableset.ps1";
                $result.Description | Should Be "description";
                Assert-VerifiableMock;
            }

        }

        Context "when script module name is not a string" {

            Mock -CommandName "Get-Content" `
                 -MockWith {
                     return @'
function test {
    $ScriptModuleName = 100;
    $ScriptModuleDescription = "description";
    write-host "test";
}
'@
            }

            It "Should throw when script module name is not a string" {
                {
                    $result = Read-ScriptModuleVariableSet -Path "my.scriptmodule.ps1";
                } | Should Throw "The '`$ScriptModuleName' variable does not evaluate to a string.";
             }

        }

        Context "when script module description is not a string" {

            Mock -CommandName "Get-Content" `
                 -MockWith {
                     return @'
function test {
    $ScriptModuleName = "name";
    $ScriptModuleDescription = 100;
    write-host "test";
}
'@
            }

            It "Should throw when script module description is not a string" {
                {
                    $result = Read-ScriptModuleVariableSet -Path "my.scriptmodule.ps1";
                } | Should Throw "The '`$ScriptModuleDescription' variable does not evaluate to a string.";
             }

        }

    }

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('reviews', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='reviewrequest',
            name='status',
            field=models.IntegerField(default=0, choices=[(0, 'Pending'), (1, 'Reviewed')]),
        ),
    ]


text:
package spark.storage

import java.nio.ByteBuffer
import java.util.concurrent.LinkedBlockingQueue

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashSet
import scala.collection.mutable.Queue

import io.netty.buffer.ByteBuf

import spark.Logging
import spark.Utils
import spark.SparkException
import spark.network.BufferMessage
import spark.network.ConnectionManagerId
import spark.network.netty.ShuffleCopier
import spark.serializer.Serializer

/**
 * A block fetcher iterator interface. There are two implementations:
 *
 * BasicBlockFetcherIterator: uses a custom-built NIO communication layer.
 * NettyBlockFetcherIterator: uses Netty (OIO) as the communication layer.
 *
 * Eventually we would like the two to converge and use a single NIO-based communication layer,
 * but extensive tests show that under some circumstances (e.g. large shuffles with lots of cores),
 * NIO would perform poorly and thus the need for the Netty OIO one.
 */

private[storage]
trait BlockFetcherIterator extends Iterator[(String, Option[Iterator[Any]])]
  with Logging with BlockFetchTracker {
  def initialize()
}

private[storage]
object BlockFetcherIterator {

  // A request to fetch one or more blocks, complete with their sizes
  class FetchRequest(val address: BlockManagerId, val blocks: Seq[(String, Long)]) {
    val size = blocks.map(_._2).sum
  }

  // A result of a fetch. Includes the block ID, size in bytes, and a function to deserialize
  // the block (since we want all deserializaton to happen in the calling thread); can also
  // represent a fetch failure if size == -1.
  class FetchResult(val blockId: String, val size: Long, val deserialize: () => Iterator[Any]) {
    def failed: Boolean = size == -1
  }

  class BasicBlockFetcherIterator(
      private val blockManager: BlockManager,
      val blocksByAddress: Seq[(BlockManagerId, Seq[(String, Long)])],
      serializer: Serializer)
    extends BlockFetcherIterator {

    import blockManager._

    private var _remoteBytesRead = 0l
    private var _remoteFetchTime = 0l
    private var _fetchWaitTime = 0l

    if (blocksByAddress == null) {
      throw new IllegalArgumentException("BlocksByAddress is null")
    }

    // Total number blocks fetched (local + remote). Also number of FetchResults expected
    protected var _numBlocksToFetch = 0

    protected var startTime = System.currentTimeMillis

    // This represents the number of local blocks, also counting zero-sized blocks
    private var numLocal = 0
    // BlockIds for local blocks that need to be fetched. Excludes zero-sized blocks
    protected val localBlocksToFetch = new ArrayBuffer[String]()

    // This represents the number of remote blocks, also counting zero-sized blocks
    private var numRemote = 0
    // BlockIds for remote blocks that need to be fetched. Excludes zero-sized blocks
    protected val remoteBlocksToFetch = new HashSet[String]()

    // A queue to hold our results.
    protected val results = new LinkedBlockingQueue[FetchResult]

    // Queue of fetch requests to issue; we'll pull requests off this gradually to make sure that
    // the number of bytes in flight is limited to maxBytesInFlight
    private val fetchRequests = new Queue[FetchRequest]

    // Current bytes in flight from our requests
    private var bytesInFlight = 0L

    protected def sendRequest(req: FetchRequest) {
      logDebug("Sending request for %d blocks (%s) from %s".format(
        req.blocks.size, Utils.memoryBytesToString(req.size), req.address.hostPort))
      val cmId = new ConnectionManagerId(req.address.host, req.address.port)
      val blockMessageArray = new BlockMessageArray(req.blocks.map {
        case (blockId, size) => BlockMessage.fromGetBlock(GetBlock(blockId))
      })
      bytesInFlight += req.size
      val sizeMap = req.blocks.toMap  // so we can look up the size of each blockID
      val fetchStart = System.currentTimeMillis()
      val future = connectionManager.sendMessageReliably(cmId, blockMessageArray.toBufferMessage)
      future.onSuccess {
        case Some(message) => {
          val fetchDone = System.currentTimeMillis()
          _remoteFetchTime += fetchDone - fetchStart
          val bufferMessage = message.asInstanceOf[BufferMessage]
          val blockMessageArray = BlockMessageArray.fromBufferMessage(bufferMessage)
          for (blockMessage <- blockMessageArray) {
            if (blockMessage.getType != BlockMessage.TYPE_GOT_BLOCK) {
              throw new SparkException(
                "Unexpected message " + blockMessage.getType + " received from " + cmId)
            }
            val blockId = blockMessage.getId
            results.put(new FetchResult(blockId, sizeMap(blockId),
              () => dataDeserialize(blockId, blockMessage.getData, serializer)))
            _remoteBytesRead += req.size
            logDebug("Got remote block " + blockId + " after " + Utils.getUsedTimeMs(startTime))
          }
        }
        case None => {
          logError("Could not get block(s) from " + cmId)
          for ((blockId, size) <- req.blocks) {
            results.put(new FetchResult(blockId, -1, null))
          }
        }
      }
    }

    protected def splitLocalRemoteBlocks(): ArrayBuffer[FetchRequest] = {
      // Split local and remote blocks. Remote blocks are further split into FetchRequests of size
      // at most maxBytesInFlight in order to limit the amount of data in flight.
      val remoteRequests = new ArrayBuffer[FetchRequest]
      for ((address, blockInfos) <- blocksByAddress) {
        if (address == blockManagerId) {
          numLocal = blockInfos.size
          // Filter out zero-sized blocks
          localBlocksToFetch ++= blockInfos.filter(_._2 != 0).map(_._1)
          _numBlocksToFetch += localBlocksToFetch.size
        } else {
          numRemote += blockInfos.size
          // Make our requests at least maxBytesInFlight / 5 in length; the reason to keep them
          // smaller than maxBytesInFlight is to allow multiple, parallel fetches from up to 5
          // nodes, rather than blocking on reading output from one node.
          val minRequestSize = math.max(maxBytesInFlight / 5, 1L)
          logInfo("maxBytesInFlight: " + maxBytesInFlight + ", minRequest: " + minRequestSize)
          val iterator = blockInfos.iterator
          var curRequestSize = 0L
          var curBlocks = new ArrayBuffer[(String, Long)]
          while (iterator.hasNext) {
            val (blockId, size) = iterator.next()
            // Skip empty blocks
            if (size > 0) {
              curBlocks += ((blockId, size))
              remoteBlocksToFetch += blockId
              _numBlocksToFetch += 1
              curRequestSize += size
            } else if (size < 0) {
              throw new BlockException(blockId, "Negative block size " + size)
            }
            if (curRequestSize >= minRequestSize) {
              // Add this FetchRequest
              remoteRequests += new FetchRequest(address, curBlocks)
              curRequestSize = 0
              curBlocks = new ArrayBuffer[(String, Long)]
            }
          }
          // Add in the final request
          if (!curBlocks.isEmpty) {
            remoteRequests += new FetchRequest(address, curBlocks)
          }
        }
      }
      logInfo("Getting " + _numBlocksToFetch + " non-zero-bytes blocks out of " +
        totalBlocks + " blocks")
      remoteRequests
    }

    protected def getLocalBlocks() {
      // Get the local blocks while remote blocks are being fetched. Note that it's okay to do
      // these all at once because they will just memory-map some files, so they won't consume
      // any memory that might exceed our maxBytesInFlight
      for (id <- localBlocksToFetch) {
        getLocalFromDisk(id, serializer) match {
          case Some(iter) => {
            // Pass 0 as size since it's not in flight
            results.put(new FetchResult(id, 0, () => iter))
            logDebug("Got local block " + id)
          }
          case None => {
            throw new BlockException(id, "Could not get block " + id + " from local machine")
          }
        }
      }
    }

    override def initialize() {
      // Split local and remote blocks.
      val remoteRequests = splitLocalRemoteBlocks()
      // Add the remote requests into our queue in a random order
      fetchRequests ++= Utils.randomize(remoteRequests)

      // Send out initial requests for blocks, up to our maxBytesInFlight
      while (!fetchRequests.isEmpty &&
        (bytesInFlight == 0 || bytesInFlight + fetchRequests.front.size <= maxBytesInFlight)) {
        sendRequest(fetchRequests.dequeue())
      }

      val numGets = remoteRequests.size - fetchRequests.size
      logInfo("Started " + numGets + " remote gets in " + Utils.getUsedTimeMs(startTime))

      // Get Local Blocks
      startTime = System.currentTimeMillis
      getLocalBlocks()
      logDebug("Got local blocks in " + Utils.getUsedTimeMs(startTime) + " ms")
    }

    //an iterator that will read fetched blocks off the queue as they arrive.
    @volatile protected var resultsGotten = 0

    override def hasNext: Boolean = resultsGotten < _numBlocksToFetch

    override def next(): (String, Option[Iterator[Any]]) = {
      resultsGotten += 1
      val startFetchWait = System.currentTimeMillis()
      val result = results.take()
      val stopFetchWait = System.currentTimeMillis()
      _fetchWaitTime += (stopFetchWait - startFetchWait)
      if (! result.failed) bytesInFlight -= result.size
      while (!fetchRequests.isEmpty &&
        (bytesInFlight == 0 || bytesInFlight + fetchRequests.front.size <= maxBytesInFlight)) {
        sendRequest(fetchRequests.dequeue())
      }
      (result.blockId, if (result.failed) None else Some(result.deserialize()))
    }

    // Implementing BlockFetchTracker trait.
    override def totalBlocks: Int = numLocal + numRemote
    override def numLocalBlocks: Int = numLocal
    override def numRemoteBlocks: Int = numRemote
    override def remoteFetchTime: Long = _remoteFetchTime
    override def fetchWaitTime: Long = _fetchWaitTime
    override def remoteBytesRead: Long = _remoteBytesRead
  }
  // End of BasicBlockFetcherIterator

  class NettyBlockFetcherIterator(
      blockManager: BlockManager,
      blocksByAddress: Seq[(BlockManagerId, Seq[(String, Long)])],
      serializer: Serializer)
    extends BasicBlockFetcherIterator(blockManager, blocksByAddress, serializer) {

    import blockManager._

    val fetchRequestsSync = new LinkedBlockingQueue[FetchRequest]

    private def startCopiers(numCopiers: Int): List[_ <: Thread] = {
      (for ( i <- Range(0,numCopiers) ) yield {
        val copier = new Thread {
          override def run(){
            try {
              while(!isInterrupted && !fetchRequestsSync.isEmpty) {
                sendRequest(fetchRequestsSync.take())
              }
            } catch {
              case x: InterruptedException => logInfo("Copier Interrupted")
              //case _ => throw new SparkException("Exception Throw in Shuffle Copier")
            }
          }
        }
        copier.start
        copier
      }).toList
    }

    // keep this to interrupt the threads when necessary
    private def stopCopiers() {
      for (copier <- copiers) {
        copier.interrupt()
      }
    }

    override protected def sendRequest(req: FetchRequest) {

      def putResult(blockId: String, blockSize: Long, blockData: ByteBuf) {
        val fetchResult = new FetchResult(blockId, blockSize,
          () => dataDeserialize(blockId, blockData.nioBuffer, serializer))
        results.put(fetchResult)
      }

      logDebug("Sending request for %d blocks (%s) from %s".format(
        req.blocks.size, Utils.memoryBytesToString(req.size), req.address.host))
      val cmId = new ConnectionManagerId(req.address.host, req.address.nettyPort)
      val cpier = new ShuffleCopier
      cpier.getBlocks(cmId, req.blocks, putResult)
      logDebug("Sent request for remote blocks " + req.blocks + " from " + req.address.host )
    }

    private var copiers: List[_ <: Thread] = null

    override def initialize() {
      // Split Local Remote Blocks and set numBlocksToFetch
      val remoteRequests = splitLocalRemoteBlocks()
      // Add the remote requests into our queue in a random order
      for (request <- Utils.randomize(remoteRequests)) {
        fetchRequestsSync.put(request)
      }

      copiers = startCopiers(System.getProperty("spark.shuffle.copier.threads", "6").toInt)
      logInfo("Started " + fetchRequestsSync.size + " remote gets in " +
        Utils.getUsedTimeMs(startTime))

      // Get Local Blocks
      startTime = System.currentTimeMillis
      getLocalBlocks()
      logDebug("Got local blocks in " + Utils.getUsedTimeMs(startTime) + " ms")
    }

    override def next(): (String, Option[Iterator[Any]]) = {
      resultsGotten += 1
      val result = results.take()
      // If all the results has been retrieved, copiers will exit automatically
      (result.blockId, if (result.failed) None else Some(result.deserialize()))
    }
  }
  // End of NettyBlockFetcherIterator
}


text:
package com.hazelcast.test.mocknetwork;

import com.hazelcast.cluster.Member;
import com.hazelcast.instance.EndpointQualifier;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.instance.impl.NodeState;
import com.hazelcast.internal.networking.NetworkStats;
import com.hazelcast.internal.networking.Networking;
import com.hazelcast.internal.util.concurrent.ThreadFactoryImpl;
import com.hazelcast.logging.ILogger;
import com.hazelcast.cluster.Address;
import com.hazelcast.internal.nio.AggregateEndpointManager;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.internal.nio.ConnectionLifecycleListener;
import com.hazelcast.internal.nio.ConnectionListener;
import com.hazelcast.internal.nio.DefaultAggregateEndpointManager;
import com.hazelcast.internal.nio.EndpointManager;
import com.hazelcast.internal.nio.IOService;
import com.hazelcast.internal.nio.NetworkingService;
import com.hazelcast.internal.nio.Packet;
import com.hazelcast.spi.impl.executionservice.ExecutionService;
import com.hazelcast.internal.util.executor.StripedRunnable;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static com.hazelcast.instance.EndpointQualifier.MEMBER;
import static com.hazelcast.test.HazelcastTestSupport.suspectMember;
import static com.hazelcast.internal.util.ThreadUtil.createThreadPoolName;
import static java.util.Collections.singletonMap;

class MockNetworkingService
        implements NetworkingService {

    private static final int RETRY_NUMBER = 5;
    private static final int DELAY_FACTOR = 100;

    private final ConcurrentMap<Address, MockConnection> mapConnections
            = new ConcurrentHashMap<Address, MockConnection>(10);
    private final TestNodeRegistry nodeRegistry;
    private final Node node;

    private final ScheduledExecutorService scheduler;
    private final IOService ioService;
    private final ILogger logger;

    private volatile boolean live;

    private final EndpointManager mockEndpointMgr;
    private final AggregateEndpointManager mockAggrEndpointManager;

    MockNetworkingService(IOService ioService, Node node, TestNodeRegistry testNodeRegistry) {
        this.ioService = ioService;
        this.nodeRegistry = testNodeRegistry;
        this.node = node;
        this.mockEndpointMgr = new MockEndpointManager(this);
        this.mockAggrEndpointManager = new DefaultAggregateEndpointManager(
                new ConcurrentHashMap(singletonMap(MEMBER, mockEndpointMgr)));
        this.scheduler = new ScheduledThreadPoolExecutor(4,
                new ThreadFactoryImpl(createThreadPoolName(ioService.getHazelcastName(), "MockConnectionManager")));
        this.logger = ioService.getLoggingService().getLogger(MockNetworkingService.class);
    }

    static class MockEndpointManager
            implements EndpointManager<MockConnection> {

        private final MockNetworkingService ns;
        private final ConnectionLifecycleListener lifecycleListener = new MockEndpointManager.MockConnLifecycleListener();
        private final Set<ConnectionListener> connectionListeners = new CopyOnWriteArraySet<ConnectionListener>();

        MockEndpointManager(MockNetworkingService ns) {
            this.ns = ns;
        }

        @Override
        public MockConnection getConnection(Address address) {
            return ns.mapConnections.get(address);
        }

        @Override
        public MockConnection getOrConnect(Address address) {
            MockConnection conn = ns.mapConnections.get(address);
            if (conn != null && conn.isAlive()) {
                return conn;
            }
            if (!ns.live) {
                return null;
            }

            Node targetNode = ns.nodeRegistry.getNode(address);
            if (targetNode == null || isTargetLeft(targetNode)) {
                suspectAddress(address);
                return null;
            }

            return createConnection(targetNode);
        }

        @Override
        public void accept(Packet packet) {

        }

        private void suspectAddress(final Address address) {
            // see NodeIOService#removeEndpoint()
            ns.node.getNodeEngine().getExecutionService().execute(ExecutionService.IO_EXECUTOR, new Runnable() {
                @Override
                public void run() {
                    ns.node.getClusterService().suspectAddressIfNotConnected(address);
                }
            });
        }

        public static boolean isTargetLeft(Node targetNode) {
            return !targetNode.isRunning() && !targetNode.getClusterService().isJoined();
        }

        private synchronized MockConnection createConnection(Node targetNode) {
            if (!ns.live) {
                throw new IllegalStateException("connection manager is not live!");
            }

            Node node = ns.node;
            Address local = node.getThisAddress();
            Address remote = targetNode.getThisAddress();

            MockConnection thisConnection = new MockConnection(lifecycleListener, remote, local,
                    node.getNodeEngine(), targetNode.getEndpointManager());

            MockConnection remoteConnection = new MockConnection(lifecycleListener, local, remote,
                    targetNode.getNodeEngine(), node.getEndpointManager());

            remoteConnection.localConnection = thisConnection;
            thisConnection.localConnection = remoteConnection;

            if (!remoteConnection.isAlive()) {
                // targetNode is not alive anymore.
                suspectAddress(remote);
                return null;
            }

            ns.mapConnections.put(remote, remoteConnection);
            ns.logger.info("Created connection to endpoint: " + remote + ", connection: " + remoteConnection);

            if (!remoteConnection.isAlive()) {
                // If connection is not alive after inserting it into connection map,
                // that means remote node is being stopping during connection creation.
                suspectAddress(remote);
            }
            return remoteConnection;
        }

        @Override
        public MockConnection getOrConnect(Address address, boolean silent) {
            return getOrConnect(address);
        }

        @Override
        public synchronized boolean registerConnection(final Address remoteEndpoint, final MockConnection connection) {
            if (!ns.live) {
                throw new IllegalStateException("connection manager is not live!");
            }
            if (!connection.isAlive()) {
                return false;
            }

            connection.setLifecycleListener(lifecycleListener);
            ns.mapConnections.put(remoteEndpoint, connection);
            ns.ioService.getEventService().executeEventCallback(new StripedRunnable() {
                @Override
                public void run() {
                    for (ConnectionListener listener : connectionListeners) {
                        listener.connectionAdded(connection);
                    }
                }

                @Override
                public int getKey() {
                    return remoteEndpoint.hashCode();
                }
            });
            return true;
        }

        @Override
        public void addConnectionListener(ConnectionListener connectionListener) {
            connectionListeners.add(connectionListener);
        }

        private void fireConnectionRemovedEvent(final MockConnection connection, final Address endPoint) {
            if (ns.live) {
                ns.ioService.getEventService().executeEventCallback(new StripedRunnable() {
                    @Override
                    public void run() {
                        for (ConnectionListener listener : connectionListeners) {
                            listener.connectionRemoved(connection);
                        }
                    }

                    @Override
                    public int getKey() {
                        return endPoint.hashCode();
                    }
                });
            }
        }

        @Override
        public Collection getConnections() {
            return ns.mapConnections.values();
        }

        @Override
        public Collection getActiveConnections() {
            return ns.mapConnections.values();
        }

        @Override
        public boolean transmit(Packet packet, MockConnection connection) {
            return (connection != null && connection.write(packet));
        }

        /**
         * Retries sending packet maximum 5 times until connection to target becomes available.
         */
        @Override
        public boolean transmit(Packet packet, Address target) {
            return send(packet, target, null);
        }

        private boolean send(Packet packet, Address target, SendTask sendTask) {
            MockConnection connection = getConnection(target);
            if (connection != null) {
                return transmit(packet, connection);
            }

            if (sendTask == null) {
                sendTask = new SendTask(packet, target);
            }

            int retries = sendTask.retries.get();
            if (retries < RETRY_NUMBER && ns.ioService.isActive()) {
                getOrConnect(target, true);
                // TODO: Caution: may break the order guarantee of the packets sent from the same thread!
                try {
                    ns.scheduler.schedule(sendTask, (retries + 1) * DELAY_FACTOR, TimeUnit.MILLISECONDS);
                } catch (RejectedExecutionException e) {
                    if (ns.live) {
                        throw e;
                    }
                    if (ns.logger.isFinestEnabled()) {
                        ns.logger.finest("Packet send task is rejected. Packet cannot be sent to " + target);
                    }
                }
                return true;
            }
            return false;
        }

        @Override
        public NetworkStats getNetworkStats() {
            return new MockNetworkStats();
        }

        private class MockConnLifecycleListener
                implements ConnectionLifecycleListener<MockConnection> {

            @Override
            public void onConnectionClose(MockConnection connection, Throwable t, boolean silent) {
                final Address endPoint = connection.getEndPoint();
                if (!ns.mapConnections.remove(endPoint, connection)) {
                    return;
                }

                NetworkingService remoteNetworkingService = connection.remoteNodeEngine.getNode().getNetworkingService();
                // all mock implementations of networking service ignore the provided endpoint qualifier
                // so we pass in null. Once they are changed to use the parameter, we should be notified
                // and this parameter can be changed
                Connection remoteConnection = remoteNetworkingService.getEndpointManager(null)
                                                                     .getConnection(connection.localEndpoint);
                if (remoteConnection != null) {
                    remoteConnection.close("Connection closed by the other side", null);
                }

                ns.logger.info("Removed connection to endpoint: " + endPoint + ", connection: " + connection);
                fireConnectionRemovedEvent(connection, endPoint);
            }

        }

        private final class SendTask implements Runnable {

            private final AtomicInteger retries = new AtomicInteger();

            private final Packet packet;
            private final Address target;

            private SendTask(Packet packet, Address target) {
                this.packet = packet;
                this.target = target;
            }

            @Override
            public void run() {
                int actualRetries = retries.incrementAndGet();
                if (ns.logger.isFinestEnabled()) {
                    ns.logger.finest("Retrying[" + actualRetries + "] packet send operation to: " + target);
                }
                send(packet, target, this);
            }
        }

        private static class MockNetworkStats implements NetworkStats {

            @Override
            public long getBytesReceived() {
                return 0;
            }

            @Override
            public long getBytesSent() {
                return 0;
            }

        }
    }

    @Override
    public IOService getIoService() {
        return ioService;
    }

    @Override
    public AggregateEndpointManager getAggregateEndpointManager() {
        return mockAggrEndpointManager;
    }

    @Override
    public EndpointManager getEndpointManager(EndpointQualifier qualifier) {
        return mockEndpointMgr;
    }

    @Override
    public void scheduleDeferred(Runnable task, long delay, TimeUnit unit) {
        scheduler.schedule(task, delay, unit);
    }

    @Override
    public boolean isLive() {
        return live;
    }

    @Override
    public Networking getNetworking() {
        return null;
    }

    @Override
    public synchronized void start() {
        logger.fine("Starting connection manager");
        live = true;
    }

    @Override
    public synchronized void stop() {
        if (!live) {
            return;
        }
        logger.fine("Stopping connection manager");
        live = false;

        for (Connection connection : mapConnections.values()) {
            connection.close(null, null);
        }
        mapConnections.clear();

        final Member localMember = node.getLocalMember();
        final Address thisAddress = localMember.getAddress();

        for (Address address : nodeRegistry.getAddresses()) {
            if (address.equals(thisAddress)) {
                continue;
            }

            Node otherNode = nodeRegistry.getNode(address);
            if (otherNode != null && otherNode.getState() != NodeState.SHUT_DOWN) {
                logger.fine(otherNode.getThisAddress() + " is instructed to suspect from " + thisAddress);
                try {
                    suspectMember(otherNode, node, "Connection manager is stopped on " + localMember);
                } catch (Throwable e) {
                    ILogger otherLogger = otherNode.getLogger(MockNetworkingService.class);
                    otherLogger.warning("While removing " + thisAddress, e);
                }
            }
        }
    }

    @Override
    public synchronized void shutdown() {
        stop();
        scheduler.shutdownNow();
    }

}


text:
package org.apache.s4.dispatcher.transformer;

public interface Transformer {
    public Object transform(Object event);
}


text:
namespace DictionaryIndexCompares
{
	partial class TestForm
	{
		/// <summary>
		/// 必要なデザイナー変数です。
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// 使用中のリソースをすべてクリーンアップします。
		/// </summary>
		/// <param name="disposing">マネージ リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null)) {
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows フォーム デザイナーで生成されたコード

		/// <summary>
		/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディターで変更しないでください。
		/// </summary>
		private void InitializeComponent()
		{
			this.lstResult = new System.Windows.Forms.ListView();
			this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
			this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
			this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
			this.SuspendLayout();
			//
			// lstResult
			//
			this.lstResult.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
			this.lstResult.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeader1,
            this.columnHeader2,
            this.columnHeader3});
			this.lstResult.FullRowSelect = true;
			this.lstResult.GridLines = true;
			this.lstResult.Location = new System.Drawing.Point(12, 12);
			this.lstResult.Name = "lstResult";
			this.lstResult.Size = new System.Drawing.Size(473, 366);
			this.lstResult.TabIndex = 1;
			this.lstResult.UseCompatibleStateImageBehavior = false;
			this.lstResult.View = System.Windows.Forms.View.Details;
			//
			// columnHeader1
			//
			this.columnHeader1.Text = "No";
			this.columnHeader1.Width = 30;
			//
			// columnHeader2
			//
			this.columnHeader2.Text = "Yomi";
			this.columnHeader2.Width = 200;
			//
			// columnHeader3
			//
			this.columnHeader3.Text = "Internal";
			this.columnHeader3.Width = 213;
			//
			// TestForm
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(497, 390);
			this.Controls.Add(this.lstResult);
			this.Font = new System.Drawing.Font("MS ゴシック", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.Name = "TestForm";
			this.Text = "Form1";
			this.ResumeLayout(false);

		}

		#endregion
		private System.Windows.Forms.ListView lstResult;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.ColumnHeader columnHeader3;
	}
}


text:
Syncs local folders to one or more remote machines when a change on the filesystem occurs.

Syncwatch uses the awesome cross-platform [fswatch](https://github.com/emcrisostomo/fswatch) to watch for filesystem changes, and rsync to propagate these changes.

Many other (editor built-in) alternatives use language libraries for SCP or SFTP which often ignore your SSH configuration. This script simply shells out to regular rsync, so you get the advantage of your ~/.ssh/config being used.

Rsync is called with the --delete option in order to clean up obscolete files. Doublecheck your paths so you don't accidentally delete something on your remote host!

## Installation
Just make the script executable and put it a folder in your $PATH.

## Dependencies:
- ruby
- [fswatch](https://github.com/emcrisostomo/fswatch)
- rsync

## Configuration
Add one or more sets of the following to the syncwatch.json configuration file:
- sourcePath
- remotePath
- remoteHost

Check out syncwatch.sample.json for an example.

Don't forget to add a trailing slash to the source dir when necessary! Read rsync's man page if you don't know what I mean.

## Usage
```
kenny  laptop  ⋯  work  projectx  syncwatch
• Performing initial syncs
 ‣ [1] Syncing /home/kenny/work/projectx/code/ → devapp:/var/www/foo
 ‣ [2] Syncing /home/kenny/work/projectx/config/bar/ → devproxy:/etc/bar
• Watching for changes
 Ⅱ [0] Starting new watch on syncwatch.json
 Ⅱ [1] Starting new watch on /home/kenny/work/projectx/code/foo/
 Ⅱ [2] Starting new watch on /home/kenny/work/projectx/config/bar/
 ‣ [1] Syncing /home/kenny/work/projectx/code/foo/ → devapp:/var/www/foo
 ↻ [0] Configuration changed, stopping all watches and reloading
• Performing initial syncs
 ‣ [1] Syncing /home/kenny/work/projectx/code/foo/ → devapp:/var/www/foo
 ‣ [2] Syncing /home/kenny/work/projectx/config/bar/ → devproxy:/etc/bar
 ‣ [3] Syncing /home/kenny/work/projectx/code/qux/ → devapp:/var/www/qux
• Watching for changes
 Ⅱ [0] Starting new watch on syncwatch.json
 Ⅱ [1] Starting new watch on /home/kenny/work/projectx/code/foo/
 Ⅱ [2] Starting new watch on /home/kenny/work/projectx/config/bar/
 Ⅱ [3] Starting new watch on /home/kenny/work/projectx/code/qux/
 ‣ [3] Syncing /home/kenny/work/projectx/code/qux/ → devapp:/var/www/qux
^C
Syncwatch shutting down.
```

Kill with ^C when you're done.

## License
MIT


text:
@extends('admin/app')
    @section('breadcrumb')
        {!! Breadcrumbs::render('attributes', 'Attributes') !!}
    @endsection
    @section('contentheader_title')
        Edit Attribute
    @endsection
    @section('contentheader_description')
        @include('admin.partial._content-head_btns', [$routeName = "admin::attributes::index", $createBtn = 'Back', $showFilters = false])
    @endsection
@section('main-content')

General

                {{--
Extra
--}}

                @include('admin.attributes.form', array('model' => $groupDescription))
        {{--@include('admin.users.form')--}}

@endsection


text:
#include "Parameter.h"

namespace hic {

/**
 * @details Constructs a Parameter object.
template<typename T>
Parameter<T>::Parameter(typeT type, const QString& name, const QString doc)
    : _type(type), _name(name), _doc(doc)
{
}
 */

/**
 * @details Destroys the Parameter object.
template<typename T>
Parameter<T>::~Parameter()
{
}
 */

} // namespace hic


text:
package org.jboss.portletbridge.arquillian;

import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.portletbridge.arquillian.deployment.PlutoDeploymentEnricherForJSF;

/**
 * Registers extensions to Arquillian for the Pluto Container when using JSF 2.
 *
 * @author kenfinnigan
 */
public class PlutoArchiveExtensionForJSF implements LoadableExtension {

    /**
     * @see org.jboss.arquillian.core.spi.LoadableExtension#register(org.jboss.arquillian.core.spi.LoadableExtension.ExtensionBuilder)
     */
    @Override
    public void register(ExtensionBuilder builder) {
        builder.service(ApplicationArchiveProcessor.class, PlutoDeploymentEnricherForJSF.class);
    }

}


text:
layout: post
title: "Around the World and Back Again"
date: 2017-10-29 8:00:00
tags: [events]
share: y
disqus: y
image:
    src: /images/2014-10/header.png
    desc: Whisky Tasting
---

**This event has passed. See the announcement for our [most recent event](/most-recent/)**

Do you have a sense of curiosity and a thirst for understanding? Join us at our next tasting on **November 25th @ 7pm** as we take another trip around the world of whiskies, with 8 whiskies from 8 different countries. On the itinerary we will check out whiskies from Australia, Canada, France, Japan, Netherlands, Scotland, South Africa, Sweden, and Taiwan.

If you have attended any of our previous tastings, you know it's a good time.

Tickets go on sale this **Tuesday, October 31st at 8am**, and will be available through our our [Tickets page][1]. Tickets have sold out in less than a day, so be sure to get yours.

Want get the latest on all our events? [Subscribe to our mailing list][2], [Follow us on Twitter][3], [Like us on Facebook][4], or [add us on Google+][5].

We hope to see you all there.

  [1]: /tickets/
  [2]: /subscribe/
  [3]: http://twitter.com/whiskydev
  [4]: http://www.facebook.com/whiskydev
  [5]: http://plus.google.com/+Whiskydev


text:
package nz.ac.waikato.its.dspace.app.xmlui.util;

/**
 * Created by jjung on 11/02/16.
 *
 * Utility for cocoon flow debugging
 *
 * usage.
 *   1. import in '${cocoonflow}.js'
 *      importClass(Packages.nz.ac.waikato.its.dspace.app.xmlui.util.AspectCocoonFlowDebug);
 *   2. invoke with debugging message in '${cocoonflow}.js'
 *      AspectCocoonFlowDebug.printDebugMsg(" 1. Entering the method step (1) ... ");
 *   3. Check messages from standard-out
 *
 */
public class AspectCocoonFlowDebug {
    public static void printDebugMsg(String msg){
        String output = "AspectCocoonFlowDebug] " + msg;
        System.out.println(output);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Encoding Hint: 雀の往来 -->
<project>
 <property name="jnlp.title"    value="JST Splash Screenのテスト" />
 <property name="jnlp.Name"     value="SplashScreen" />
 <property name="jnlp.name"     value="splashscreen" />
 <property name="jnlp.codebase" value="http://ateraimemo.com/swing/${jnlp.name}/" />
 <property name="jnlp.homepage" value="http://ateraimemo.com/Swing/${jnlp.Name}.html" />
</project>


text:
__image__ is the [Torch7 distribution](http://torch.ch/) package for processing
images. It contains a wide variety of functions divided into the following categories:

  * [Saving and loading](saveload.md) images as JPEG, PNG, PPM and PGM;
  * [Simple transformations](simpletransform.md) like translation, scaling and rotation;
  * [Parameterized transformations](paramtransform.md) like convolutions and warping;
  * [Graphical user interfaces](gui.md) like display and window;
  * [Color Space Conversions](colorspace.md) from and to RGB, YUV, Lab, and HSL;
  * [Tensor Constructors](tensorconstruct.md) for creating Lenna, Fabio and Gaussian and Laplacian kernels;

Note that unless speficied otherwise, this package deals with images of size
`nChannel x height x width`.

## Install

The easiest way to install this package it by following the [intructions](http://torch.ch/docs/getting-started.html)
to install [Torch7](www.torch.ch), which includes __image__.
Otherwise, to update or manually re-install it:

```bash
$ luarocks install image
```

## Usage

```lua
> require 'image'
> l = image.lena()
> image.display(l)
> f = image.fabio()
> image.display(f)
```


text:
#ifndef LINGER_RESPONSE_H_
#define LINGER_RESPONSE_H_

#define RESPONSE_PROPERTIES_INSTANCE "_instance"
#define RESPONSE_PROPERTIES_STATUS "_status"
#define RESPONSE_PROPERTIES_HEADER "_header"
#define RESPONSE_PROPERTIES_BODY "_body"

extern zend_class_entry *response_ce;

zval *linger_response_instance(zval *this);
void linger_response_send(zval *this);
int linger_response_set_body(zval *this, zval *body);
int linger_response_set_header(zval *this, zend_string *key, zval *val);
int linger_response_set_status(zval *this, zval *status);

#include "SAPI.h"

#define _404() \
	do { \
		sapi_header_line ctr = { \
			.line = "HTTP/1.1 404 Not Found", \
			.line_len = 22, \
			.response_code = 404}; \
		sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); \
	} while (0)

#endif /* LINGER_RESPONSE_H_ */


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- To clean up POMs, use:
mvn versions:display-plugin-updates
mvn versions:display-dependency-updates
mvn dependency:analyze
-->

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.inbloom.gateway</groupId>
    <artifactId>gateway-all</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>inBloom Gateway All</name>
    <description>inBloom Gateway</description>
    <url>http://www.inbloom.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.0.1.RELEASE</version>
    </parent>

    <prerequisites>
        <maven>3.1.0</maven>
    </prerequisites>

    <organization>
        <name>inBloom, Inc.</name>
        <url>http://www.inbloom.org</url>
    </organization>

    <properties>
        <bootstrap.version>3.1.1</bootstrap.version>
        <commons.codec>1.9</commons.codec>
        <commons.lang.version>3.3.1</commons.lang.version>
        <commons.logging.version>1.1.3</commons.logging.version>
        <findbugs.version>2.5.2</findbugs.version>
        <findsecbugs.version>1.2.0</findsecbugs.version>
        <java.mail.version>1.5.0-b01</java.mail.version>
        <java.validation.version>1.1.0.Final</java.validation.version>
        <jodatime.version>2.3</jodatime.version>
        <junit.version>4.11</junit.version>
        <jqbootstrapvalidation.version>1.3.6</jqbootstrapvalidation.version>
        <jquery.version>2.1.0-2</jquery.version>
        <logback.version>1.1.2</logback.version>
        <mock.javamail.version>1.9</mock.javamail.version>
        <modelmapper.version>0.6.3</modelmapper.version>
        <mysql.jdbc.version>5.1.30</mysql.jdbc.version>
        <pmd.version>3.1</pmd.version>
        <spring.version>4.0.3.RELEASE</spring.version>
        <swagger.version>0.6.5</swagger.version>
        <thymeleaf.version>2.1.2.RELEASE</thymeleaf.version>
        <unbounded.ldap.version>2.3.5</unbounded.ldap.version>
    </properties>

    <modules>
       <module>gateway-common</module>
       <module>inbloom-notifications-client</module>
       <module>gateway-boot</module>
       <module>gateway-portal</module>
    </modules>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>repo1</id>
            <name>Maven2 repo1 repository</name>
            <url>http://repo1.maven.org/maven2</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>${pmd.version}</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>${findbugs.version}</version>
                <configuration>
                    <effort>Max</effort>
                    <threshold>Low</threshold>
                    <failOnError>true</failOnError>
                    <plugins>
                        <plugin>
                            <groupId>com.h3xstream.findsecbugs</groupId>
                            <artifactId>findsecbugs-plugin</artifactId>
                            <version>${findsecbugs.version}</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <reports>
        <report>maven-pmd-plugin</report>
    </reports>

</project>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.ldc.bananamuffin.BreakfastActivity">

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/switch_text"
        android:id="@+id/activator" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/contact_top_margin">

        <EditText
            android:layout_height="fill_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:hint="@string/contact"
            android:id="@+id/contact" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="@string/select"
            android:id="@+id/select" />

    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:inputType="textMultiLine"
        android:gravity="top"
        android:id="@+id/messages"
        android:hint="@string/messages"
        android:layout_marginTop="@dimen/messages_top_margin"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="@string/notify"
            android:id="@+id/notifier" />

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:text="@string/custom_messages_save" />
    </LinearLayout>

</LinearLayout>


text:
package com.orcchg.dev.maxa.rxmusic.data.injection.local.music;

/**
 * Created by alov on 27.02.17.
 */
public class stub {
}


text:
package org.wildfly.security.permission;

import java.security.Permission;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;

import org.wildfly.security.util.EnumerationIterator;
import org.wildfly.security.util.StringEnumeration;

final class IntNameSetPermissionCollection extends NameSetPermissionCollection {

    private final AtomicInteger bitSet = new AtomicInteger();

    IntNameSetPermissionCollection(final AbstractPermission<?> sourcePermission, final StringEnumeration nameEnumeration) {
        super(sourcePermission, nameEnumeration);
    }

    private Permission permissionFor(int id) {
        return ((AbstractNamedPermission<?>)getSourcePermission()).withName(getNameEnumeration().nameOf(id));
    }

    protected void doAdd(final AbstractPermission<?> permission) {
        int setBits= getBitsForName(permission);
        final AtomicInteger bitSet = this.bitSet;
        int oldVal;
        do {
            oldVal = bitSet.get();
            if ((oldVal & setBits) == setBits) {
                return;
            }
        } while (! bitSet.compareAndSet(oldVal, oldVal | setBits));
    }

    public boolean implies(final Permission permission) {
        if (permission.getClass() != getSourcePermission().getClass()) {
            return false;
        }
        long testBits = getBitsForName(permission);
        return (bitSet.get() & testBits) == testBits;
    }

    public int size() {
        final int size = Integer.bitCount(bitSet.get());
        return size == getNameEnumeration().size() ? 1 : size;
    }

    public EnumerationIterator<Permission> iterator() {
        return new Iter(bitSet.get());
    }

    public EnumerationIterator<Permission> elements() {
        return iterator();
    }

    private int getBitsForName(final Permission permission) {
        final int bits;
        final String name = permission.getName();
        final StringEnumeration nameEnumeration = getNameEnumeration();
        if ("*".equals(name)) {
            // add all names
            bits = (1 << nameEnumeration.size()) - 1;
        } else {
            bits = 1 << nameEnumeration.indexOf(name);
        }
        return bits;
    }

    private class Iter implements EnumerationIterator<Permission> {
        private int bits;

        Iter(final int bits) {
            this.bits = bits;
        }

        public boolean hasMoreElements() {
            return bits != 0;
        }

        public Permission nextElement() {
            final int bits = this.bits;
            if (bits == 0) throw new NoSuchElementException();
            if (Integer.bitCount(bits) == getNameEnumeration().size()) {
                this.bits = 0;
                return ((AbstractNamedPermission<?>) getSourcePermission()).withName("*");
            }
            int bit = Integer.lowestOneBit(bits);
            this.bits = bits & ~bit;
            return permissionFor(Integer.numberOfTrailingZeros(bit));
        }

        public boolean hasNext() {
            return hasMoreElements();
        }

        public Permission next() {
            return nextElement();
        }
    }

}


text:
from itertools import product
from operator import eq, ne
import warnings

import numpy as np
from toolz import take

from zipline.lib.labelarray import LabelArray
from zipline.testing import check_arrays, parameter_space, ZiplineTestCase
from zipline.testing.predicates import assert_equal
from zipline.utils.compat import unicode

def rotN(l, N):
    """
    Rotate a list of elements.

    Pulls N elements off the end of the list and appends them to the front.

    >>> rotN(['a', 'b', 'c', 'd'], 2)
    ['c', 'd', 'a', 'b']
    >>> rotN(['a', 'b', 'c', 'd'], 3)
    ['d', 'a', 'b', 'c']
    """
    assert len(l) >= N, "Can't rotate list by longer than its length."
    return l[N:] + l[:N]

def all_ufuncs():
    ufunc_type = type(np.isnan)
    return (f for f in vars(np).values() if isinstance(f, ufunc_type))

class LabelArrayTestCase(ZiplineTestCase):

    @classmethod
    def init_class_fixtures(cls):
        super(LabelArrayTestCase, cls).init_class_fixtures()

        cls.rowvalues = row = ['', 'a', 'b', 'ab', 'a', '', 'b', 'ab', 'z']
        cls.strs = np.array([rotN(row, i) for i in range(3)], dtype=object)

    def test_fail_on_direct_construction(self):
        # See http://docs.scipy.org/doc/numpy-1.10.0/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray  # noqa

        with self.assertRaises(TypeError) as e:
            np.ndarray.__new__(LabelArray, (5, 5))

        self.assertEqual(
            str(e.exception),
            "Direct construction of LabelArrays is not supported."
        )

    @parameter_space(
        __fail_fast=True,
        compval=['', 'a', 'z', 'not in the array'],
        shape=[(27,), (3, 9), (3, 3, 3)],
        array_astype=(bytes, unicode, object),
        missing_value=('', 'a', 'not in the array', None),
    )
    def test_compare_to_str(self,
                            compval,
                            shape,
                            array_astype,
                            missing_value):

        strs = self.strs.reshape(shape).astype(array_astype)
        if missing_value is None:
            # As of numpy 1.9.2, object array != None returns just False
            # instead of an array, with a deprecation warning saying the
            # behavior will change in the future.  Work around that by just
            # using the ufunc.
            notmissing = np.not_equal(strs, missing_value)
        else:
            if not isinstance(missing_value, array_astype):
                missing_value = array_astype(missing_value, 'utf-8')
            notmissing = (strs != missing_value)

        arr = LabelArray(strs, missing_value=missing_value)

        if not isinstance(compval, array_astype):
            compval = array_astype(compval, 'utf-8')

        # arr.missing_value should behave like NaN.
        check_arrays(
            arr == compval,
            (strs == compval) & notmissing,
        )
        check_arrays(
            arr != compval,
            (strs != compval) & notmissing,
        )

        np_startswith = np.vectorize(lambda elem: elem.startswith(compval))
        check_arrays(
            arr.startswith(compval),
            np_startswith(strs) & notmissing,
        )

        np_endswith = np.vectorize(lambda elem: elem.endswith(compval))
        check_arrays(
            arr.endswith(compval),
            np_endswith(strs) & notmissing,
        )

        np_contains = np.vectorize(lambda elem: compval in elem)
        check_arrays(
            arr.has_substring(compval),
            np_contains(strs) & notmissing,
        )

    @parameter_space(
        __fail_fast=True,
        missing_value=('', 'a', 'not in the array', None),
    )
    def test_compare_to_str_array(self, missing_value):
        strs = self.strs
        shape = strs.shape
        arr = LabelArray(strs, missing_value=missing_value)

        if missing_value is None:
            # As of numpy 1.9.2, object array != None returns just False
            # instead of an array, with a deprecation warning saying the
            # behavior will change in the future.  Work around that by just
            # using the ufunc.
            notmissing = np.not_equal(strs, missing_value)
        else:
            notmissing = (strs != missing_value)

        check_arrays(arr.not_missing(), notmissing)
        check_arrays(arr.is_missing(), ~notmissing)

        # The arrays are equal everywhere, but comparisons against the
        # missing_value should always produce False
        check_arrays(strs == arr, notmissing)
        check_arrays(strs != arr, np.zeros_like(strs, dtype=bool))

        def broadcastable_row(value, dtype):
            return np.full((shape[0], 1), value, dtype=strs.dtype)

        def broadcastable_col(value, dtype):
            return np.full((1, shape[1]), value, dtype=strs.dtype)

        # Test comparison between arr and a like-shap 2D array, a column
        # vector, and a row vector.
        for comparator, dtype, value in product((eq, ne),
                                                (bytes, unicode, object),
                                                set(self.rowvalues)):
            check_arrays(
                comparator(arr, np.full_like(strs, value)),
                comparator(strs, value) & notmissing,
            )
            check_arrays(
                comparator(arr, broadcastable_row(value, dtype=dtype)),
                comparator(strs, value) & notmissing,
            )
            check_arrays(
                comparator(arr, broadcastable_col(value, dtype=dtype)),
                comparator(strs, value) & notmissing,
            )

    @parameter_space(
        __fail_fast=True,
        slice_=[
            0, 1, -1,
            slice(None),
            slice(0, 0),
            slice(0, 3),
            slice(1, 4),
            slice(0),
            slice(None, 1),
            slice(0, 4, 2),
            (slice(None), 1),
            (slice(None), slice(None)),
            (slice(None), slice(1, 2)),
        ]
    )
    def test_slicing_preserves_attributes(self, slice_):
        arr = LabelArray(self.strs.reshape((9, 3)), missing_value='')
        sliced = arr[slice_]
        self.assertIsInstance(sliced, LabelArray)
        self.assertIs(sliced.categories, arr.categories)
        self.assertIs(sliced.reverse_categories, arr.reverse_categories)
        self.assertIs(sliced.missing_value, arr.missing_value)

    def test_infer_categories(self):
        """
        Test that categories are inferred in sorted order if they're not
        explicitly passed.
        """
        arr1d = LabelArray(self.strs, missing_value='')
        codes1d = arr1d.as_int_array()
        self.assertEqual(arr1d.shape, self.strs.shape)
        self.assertEqual(arr1d.shape, codes1d.shape)

        categories = arr1d.categories
        unique_rowvalues = set(self.rowvalues)

        # There should be an entry in categories for each unique row value, and
        # each integer stored in the data array should be an index into
        # categories.
        self.assertEqual(list(categories), sorted(set(self.rowvalues)))
        self.assertEqual(
            set(codes1d.ravel()),
            set(range(len(unique_rowvalues)))
        )
        for idx, value in enumerate(arr1d.categories):
            check_arrays(
                self.strs == value,
                arr1d.as_int_array() == idx,
            )

        # It should be equivalent to pass the same set of categories manually.
        arr1d_explicit_categories = LabelArray(
            self.strs,
            missing_value='',
            categories=arr1d.categories,
        )
        check_arrays(arr1d, arr1d_explicit_categories)

        for shape in (9, 3), (3, 9), (3, 3, 3):
            strs2d = self.strs.reshape(shape)
            arr2d = LabelArray(strs2d, missing_value='')
            codes2d = arr2d.as_int_array()

            self.assertEqual(arr2d.shape, shape)
            check_arrays(arr2d.categories, categories)

            for idx, value in enumerate(arr2d.categories):
                check_arrays(strs2d == value, codes2d == idx)

    def test_reject_ufuncs(self):
        """
        The internal values of a LabelArray should be opaque to numpy ufuncs.

        Test that all unfuncs fail.
        """
        l = LabelArray(self.strs, '')
        ints = np.arange(len(l))

        with warnings.catch_warnings():
            # Some ufuncs return NotImplemented, but warn that they will fail
            # in the future.  Both outcomes are fine, so ignore the warnings.
            warnings.filterwarnings(
                'ignore',
                message="unorderable dtypes.*",
                category=DeprecationWarning,
            )
            warnings.filterwarnings(
                'ignore',
                message="elementwise comparison failed.*",
                category=FutureWarning,
            )
            for func in all_ufuncs():
                # Different ufuncs vary between returning NotImplemented and
                # raising a TypeError when provided with unknown dtypes.
                # This is a bit unfortunate, but still better than silently
                # accepting an int array.
                try:
                    if func.nin == 1:
                        ret = func(l)
                    elif func.nin == 2:
                        ret = func(l, ints)
                    else:
                        self.fail("Who added a ternary ufunc !?!")
                except TypeError:
                    pass
                else:
                    self.assertIs(ret, NotImplemented)

    @parameter_space(
        __fail_fast=True,
        val=['', 'a', 'not in the array', None],
        missing_value=['', 'a', 'not in the array', None],
    )
    def test_setitem_scalar(self, val, missing_value):
        arr = LabelArray(self.strs, missing_value=missing_value)

        if not arr.has_label(val):
            self.assertTrue(
                (val == 'not in the array')
                or (val is None and missing_value is not None)
            )
            for slicer in [(0, 0), (0, 1), 1]:
                with self.assertRaises(ValueError):
                    arr[slicer] = val
            return

        arr[0, 0] = val
        self.assertEqual(arr[0, 0], val)

        arr[0, 1] = val
        self.assertEqual(arr[0, 1], val)

        arr[1] = val
        if val == missing_value:
            self.assertTrue(arr.is_missing()[1].all())
        else:
            self.assertTrue((arr[1] == val).all())
            self.assertTrue((arr[1].as_string_array() == val).all())

        arr[:, -1] = val
        if val == missing_value:
            self.assertTrue(arr.is_missing()[:, -1].all())
        else:
            self.assertTrue((arr[:, -1] == val).all())
            self.assertTrue((arr[:, -1].as_string_array() == val).all())

        arr[:] = val
        if val == missing_value:
            self.assertTrue(arr.is_missing().all())
        else:
            self.assertFalse(arr.is_missing().any())
            self.assertTrue((arr == val).all())

    def test_setitem_array(self):
        arr = LabelArray(self.strs, missing_value=None)
        orig_arr = arr.copy()

        # Write a row.
        self.assertFalse(
            (arr[0] == arr[1]).all(),
            "This test doesn't test anything because rows 0"
            " and 1 are already equal!"
        )
        arr[0] = arr[1]
        for i in range(arr.shape[1]):
            self.assertEqual(arr[0, i], arr[1, i])

        # Write a column.
        self.assertFalse(
            (arr[:, 0] == arr[:, 1]).all(),
            "This test doesn't test anything because columns 0"
            " and 1 are already equal!"
        )
        arr[:, 0] = arr[:, 1]
        for i in range(arr.shape[0]):
            self.assertEqual(arr[i, 0], arr[i, 1])

        # Write the whole array.
        arr[:] = orig_arr
        check_arrays(arr, orig_arr)

    @staticmethod
    def check_roundtrip(arr):
        assert_equal(
            arr.as_string_array(),
            LabelArray(
                arr.as_string_array(),
                arr.missing_value,
            ).as_string_array(),
        )

    @staticmethod
    def create_categories(width, plus_one):
        length = int(width / 8) + plus_one
        return [
            ''.join(cs)
            for cs in take(
                2 ** width + plus_one,
                product([chr(c) for c in range(256)], repeat=length),
            )
        ]

    def test_narrow_code_storage(self):
        create_categories = self.create_categories
        check_roundtrip = self.check_roundtrip

        # uint8
        categories = create_categories(8, plus_one=False)
        arr = LabelArray(
            [],
            missing_value=categories[0],
            categories=categories,
        )
        self.assertEqual(arr.itemsize, 1)
        check_roundtrip(arr)

        # uint8 inference
        arr = LabelArray(categories, missing_value=categories[0])
        self.assertEqual(arr.itemsize, 1)
        check_roundtrip(arr)

        # just over uint8
        categories = create_categories(8, plus_one=True)
        arr = LabelArray(
            [],
            missing_value=categories[0],
            categories=categories,
        )
        self.assertEqual(arr.itemsize, 2)
        check_roundtrip(arr)

        # fits in uint16
        categories = create_categories(16, plus_one=False)
        arr = LabelArray(
            [], missing_value=categories[0],
            categories=categories,
        )
        self.assertEqual(arr.itemsize, 2)
        check_roundtrip(arr)

        # uint16 inference
        arr = LabelArray(categories, missing_value=categories[0])
        self.assertEqual(arr.itemsize, 2)
        check_roundtrip(arr)

        # just over uint16
        categories = create_categories(16, plus_one=True)
        arr = LabelArray(
            [],
            missing_value=categories[0],
            categories=categories,
        )
        self.assertEqual(arr.itemsize, 4)
        check_roundtrip(arr)

        # uint32 inference
        arr = LabelArray(categories, missing_value=categories[0])
        self.assertEqual(arr.itemsize, 4)
        check_roundtrip(arr)

        # NOTE: we could do this for 32 and 64; however, no one has enough RAM
        # or time for that.

    def test_narrow_condense_back_to_valid_size(self):
        categories = ['a'] * (2 ** 8 + 1)
        arr = LabelArray(categories, missing_value=categories[0])
        assert_equal(arr.itemsize, 1)
        self.check_roundtrip(arr)

        # longer than int16 but still fits when deduped
        categories = self.create_categories(16, plus_one=False)
        categories.append(categories[0])
        arr = LabelArray(categories, missing_value=categories[0])
        assert_equal(arr.itemsize, 2)
        self.check_roundtrip(arr)

    def manual_narrow_condense_back_to_valid_size_slow(self):
        """This test is really slow so we don't want it run by default.
        """
        # tests that we don't try to create an 'int24' (which is meaningless)
        categories = self.create_categories(24, plus_one=False)
        categories.append(categories[0])
        arr = LabelArray(categories, missing_value=categories[0])
        assert_equal(arr.itemsize, 4)
        self.check_roundtrip(arr)


text:
@implementation SMFItemForm

+ (Class)managedObjectClass
{
    return [Item class];
}

+ (NSManagedObjectContext *)managedObjectContext
{
    return ((SMFAppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
}

+ (NSArray *)fields
{
    return @[@"title", @"details", @"note"];
}

@end


text:
A [Yeoman](http://yeoman.io) generator for [AngularJS](http://angularjs.org) and [Scotty](https://github.com/scotty-web/scotty).

Scotty is a Haskell-based micro-framework.  For AngularJS integration with other micro-frameworks, see https://github.com/rayokota/MicroFrameworkRosettaStone.

## Installation

Install [Git](http://git-scm.com), [node.js](http://nodejs.org), [Haskell](http://www.haskell.org/haskellwiki/Haskell), [GHC 7.8.2](https://www.haskell.org/ghc/), and [Cabal 1.18](http://www.haskell.org/cabal/download.html).  The development mode also requires [SQLite](http://www.sqlite.org).

Install Yeoman:

    npm install -g yo

Install the Angular-Scotty generator:

    npm install -g generator-angular-scotty

The above prerequisites can be installed to a VM using the [Angular-Scotty provisioner](https://github.com/rayokota/provision-angular-scotty).

## Creating a Scotty service

In a new directory, generate the service:

    yo angular-scotty

Create the cabal sandbox and install dependencies:

    cabal sandbox init
    cabal install

Run the service:

    cabal run Main

Your service will run at [http://localhost:3000](http://localhost:3000).

## Creating a persistent entity

Generate the entity:

    yo angular-scotty:entity [myentity]

You will be asked to specify attributes for the entity, where each attribute has the following:

- a name
- a type (String, Integer, Float, Boolean, Date, Enum)
- for a String attribute, an optional minimum and maximum length
- for a numeric attribute, an optional minimum and maximum value
- for a Date attribute, an optional constraint to either past values or future values
- for an Enum attribute, a list of enumerated values
- whether the attribute is required

Files that are regenerated will appear as conflicts.  Allow the generator to overwrite these files as long as no custom changes have been made.

Run the service:

    cabal run Main

A client-side AngularJS application will now be available by running

	grunt server

The Grunt server will run at [http://localhost:9000](http://localhost:9000).  It will proxy REST requests to the Scotty service running at [http://localhost:3000](http://localhost:3000).

At this point you should be able to navigate to a page to manage your persistent entities.

The Grunt server supports hot reloading of client-side HTML/CSS/Javascript file changes.


text:
const EventEmitter = require('events');

let sessions = new Map();
let publishers = new Map();
let idlePlayers = new Set();
let nodeEvent = new EventEmitter();
let stat = {
  inbytes: 0,
  outbytes: 0,
  accepted: 0
};
module.exports = { sessions, publishers, idlePlayers, nodeEvent, stat };