text:
$:.unshift File.dirname(__FILE__) + "/../lib"
require 'verneuil'

code = <<RUBY
def foo(n)
  if n>=1
    foo n-1
    p n   # prints 1, 2
  end
end

foo(2)
RUBY

program = Verneuil::Compiler.compile(code)
puts program.inspect
puts
process = Verneuil::Process.new(program, nil)
process.run


text:
package io.datarouter.storage.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;

import javax.inject.Singleton;

@Singleton
public class DaoClasses implements Supplier<List<Class<? extends Dao>>>{

	private final List<Class<? extends Dao>> classes;

	public DaoClasses(){
		this.classes = new ArrayList<>();
	}

	@SafeVarargs
	public DaoClasses(Class<? extends Dao>... daoClassVarArgs){
		this(List.of(daoClassVarArgs));
	}

	public DaoClasses(Collection<Class<? extends Dao>> daoClasses){
		this.classes = new ArrayList<>();
		daoClasses.forEach(this::add);
	}

	@Override
	public List<Class<? extends Dao>> get(){
		return classes;
	}

	public DaoClasses add(Class<? extends Dao> daoClass){
		requireUnique(daoClass);
		classes.add(daoClass);
		return this;
	}

	public DaoClasses add(List<Class<? extends Dao>> daoClasses){
		daoClasses.forEach(this::add);
		return this;
	}

	private void requireUnique(Class<? extends Dao> daoClass){
		if(classes.contains(daoClass)){
			throw new IllegalArgumentException(daoClass.getCanonicalName() + " has already been registered");
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
class Admin::AmenitiesController < AdminController
  helper :all
  # before_action :check_admin_status, only: [:new, :edit, :update, :destroy]
  before_action :set_page
  before_action :set_amenity, only: [:show, :edit, :update, :destroy]

  def index
    @amenities = Amenity.all.order(:id)
  end

  def show
    @pictures = @amenity.pictures.all
    @documents = @amenity.documents.all
  end

  def new
    @amenity = Amenity.new
    @pictures = Picture.new
  end

  def edit
    @pictures = @amenity.pictures
    @documents = @amenity.documents
  end

  def create
    input = amenity_params
    @amenity = Amenity.new({name: input['name'], description: input['description']})

    respond_to do |format|
      if @amenity.save
        @amenity.pictures.create(input['picture'])
        @amenity.documents.create(input['document'])
        flash[:success] = 'Amenity was successfully created.'
        format.html do
          flash[:success] = 'Amenity was successfully created.'
          redirect_to admin_amenity_path(@amenity)
        end
      else
        flash[:error] = "There the following errors.  #{@amenity.errors.full_messages.join("")}"
        format.html { render :new }

      end
    end
  end

  def update
    input = amenity_params
    respond_to do |format|
      if @amenity.update({name: input['name'], description: input['description']})
        flash[:success] = 'Amenity was successfully updated.'
        format.html { redirect_to admin_amenity_path(@amenity)}
      else
        flash[:error] = "There the following errors.  #{@amenity.errors.full_messages.join("")}"
        format.html { render :edit }
      end
    end
  end

  def delete
    @amenity = Amenity.find(params[:amenity_id])
  end

  def destroy
    @amenities = Amenity.all.order(:id)
    @amenity.destroy
    respond_to do |format|
      format.html do
        flash[:success] = 'Amenity was successfully removed.'
        redirect_to admin_amenities_path
      end
      format.json { head :no_content }
      format.js do
        flash.now[:success] = 'Property was successfully removed.'
        render :layout => false
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_amenity
      @amenity = Amenity.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def amenity_params
      params.require(:amenity).permit(:name, :description, {picture:['image','caption']},{document:['doc','title']})
    end
    def check_admin_status
      unless is_admin?
        flash[:error] = "You must be an Admin in to access this section"
        redirect_to root_path
      end
    end
    def set_page
      @page = 'amenities'
    end

end


text:
module.exports = function(){
	var mongoose = require('mongoose');
	var Schema   = mongoose.Schema;

	var usuario = new Schema({
		nome: String,
		login: String,
		senha: String,
		data_cad: {type: Date, default: Date.now}
	});

	return mongoose.model('Usuario', usuario);
}


text:
define(['exports'], function (exports) {
  'use strict';

  Object.defineProperty(exports, '__esModule', {
    value: true
  });
  exports.fireEvent = fireEvent;
  function createEvent(name) {
    var event = document.createEvent('Event');
    event.initEvent(name, true, true);
    return event;
  }

  function fireEvent(element, name) {
    var event = createEvent(name);
    element.dispatchEvent(event);
  }
});


text:
.class Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity$1;
.super Ljava/lang/Object;

# interfaces
.implements Lcom/payu/android/sdk/internal/ng$e;

# annotations
.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic b:Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;

# direct methods
.method constructor <init>(Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;)V
    .locals 0

    .line 31
    iput-object p1, p0, Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity$1;->b:Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onDialogPositiveButtonPress(Lcom/payu/android/sdk/internal/ng$b;I)V
    .locals 1

    .line 35
    iget-object v0, p0, Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity$1;->b:Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;

    # getter for: Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;->c:Lcom/payu/android/sdk/internal/es;
    invoke-static {v0}, Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;->access$000(Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;)Lcom/payu/android/sdk/internal/es;

    move-result-object v0

    invoke-virtual {v0}, Lcom/payu/android/sdk/internal/es;->b()V

    .line 36
    iget-object v0, p0, Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity$1;->b:Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;

    # invokes: Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;->startPaymentMethodListActivity()V
    invoke-static {v0}, Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;->access$100(Lcom/payu/android/sdk/payment/ui/LocalCardCheckActivity;)V

    .line 37
    return-void
.end method


text:
#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_CACHE_H_
#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_CACHE_H_

#include "third_party/blink/public/common/web_cache/web_cache_resource_type_stats.h"
#include "third_party/blink/public/platform/web_common.h"

namespace blink {

// An interface to query and configure Blink's resource cache.
class BLINK_PLATFORM_EXPORT WebCache {
 public:
  struct UsageStats {
    size_t capacity;
    size_t size;
  };

  // Sets the capacities of the resource cache, evicting objects as necessary.
  static void SetCapacity(size_t);

  // Clears the cache (as much as possible; some resources may not be
  // cleared if they are actively referenced). Note that this method
  // only removes resources from live list, w/o releasing cache memory.
  static void Clear();

  // Gets the usage statistics from the resource cache.
  static void GetUsageStats(UsageStats*);

  // Get usage stats about the resource cache.
  static void GetResourceTypeStats(WebCacheResourceTypeStats*);

 private:
  WebCache() = delete;  // Not intended to be instanced.
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_CACHE_H_


text:
`count(predicate=None)`

Returns the number of elements in the `Enumerable` instance. This is an executing function.

**Parameters**

__predicate__ : condition to satisfy as a `lambda` function. Optional.

**Returns**

The number of elements in the `Enumerable` instance as an integer. If a predicate is given, the number of elements in the collection that have satisfied the predicate.

**Example**

from py_linq import Enumerable

collection = Enumerable([
    {'value': 1},
    {'value': 2},
    {'value': 3}
]).count()
# 3


text:
package org.sosy_lab.cpachecker.util;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;

import org.sosy_lab.common.Pair;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;

/**
 * Some utilities for generic graphs.
 */
public class GraphUtils {

  private GraphUtils() { }

  /**
   * Project a graph to a subset of "relevant" nodes.
   * The result is a SetMultimap containing the successor relationships between all relevant nodes.
   * A pair of nodes (a, b) is in the SetMultimap,
   * if there is a path through the graph from a to b which does not pass through
   * any other relevant node.
   *
   * To get the predecessor relationship, you can use {@link Multimaps#invertFrom(com.google.common.collect.Multimap, com.google.common.collect.Multimap)}.
   *
   * @param root The start of the graph to project (always considered relevant).
   * @param isRelevant The predicate determining which nodes are in the resulting relationship.
   * @param successorFunction A function giving the direct successors of any node.
   * @param <N> The node type of the graph.
   */
  public static <N> SetMultimap<N, N> projectARG(final N root,
      final Function<? super N, ? extends Iterable<N>> successorFunction,
      Predicate<? super N> isRelevant) {

    isRelevant = Predicates.or(Predicates.equalTo(root),
                               isRelevant);

    SetMultimap<N, N> successors = HashMultimap.create();

    // Our state is a stack of pairs of todo items.
    // The first item of each pair is a relevant state,
    // for which we are looking for relevant successor states.
    // The second item is a state,
    // whose children should be handled next.
    Deque<Pair<N, N>> todo = new ArrayDeque<>();
    Set<N> visited = new HashSet<>();
    todo.push(Pair.of(root, root));

    while (!todo.isEmpty()) {
      final Pair<N, N> currentPair = todo.pop();
      final N currentPredecessor = currentPair.getFirst();
      final N currentState = currentPair.getSecond();

      if (!visited.add(currentState)) {
        continue;
      }

      for (N child : successorFunction.apply(currentState)) {
        if (isRelevant.apply(child)) {
          successors.put(currentPredecessor, child);

          todo.push(Pair.of(child, child));

        } else {
          todo.push(Pair.of(currentPredecessor, child));
        }
      }
    }

    return successors;
  }
}


text:
<?php

defined('_JEXEC') or die('RESTRICTED');

class WFAggregatorExtension extends WFExtension {

    protected static $instance;

    /*
     *  @var varchar
     */
    private $extensions = array();

    /**
     * Constructor activating the default information of the class
     *
     * @access	protected
     */
    public function __construct($config = array()) {
        parent::__construct($config);
    }

    /**
     * Returns a reference to a plugin object
     *
     * This method must be invoked as:
     * 		<pre>  $advlink =AdvLink::getInstance();</pre>
     *
     * @access	public
     * @return	JCE  The editor object.
     * @since	1.5
     */
    public static function getInstance($config = array()) {
        if (!isset(self::$instance)) {
            self::$instance = new WFAggregatorExtension($config);
        }

        return self::$instance;
    }

    public function getName() {
        return $this->get('name');
    }

    public function getTitle() {
        return $this->get('title');
    }

    public function display() {
        parent::display();

        $document = WFDocument::getInstance();

        // Load javascript
        $document->addScript(array('extensions/aggregator'), 'libraries');

        $aggregators = $this->getAggregators();

        foreach ($aggregators as $aggregator) {
            $aggregator->display();

            $params = $aggregator->getParams();

            if (!empty($params)) {
                $document->addScriptDeclaration('WFExtensions.Aggregator.setParams("' . $aggregator->getName() . '",' . json_encode($params) . ');');
            }
        }
    }

    public function & getAggregators() {
        static $aggregators;

        if (!isset($aggregators)) {
            $aggregators = array();
        }

        // get the aggregator format for this instance
        $format = $this->get('format');

        if (empty($aggregators[$format])) {
            jimport('joomla.filesystem.folder');

            // get a plugin instance
            $plugin = WFEditorPlugin::getInstance();

            $aggregators[$format] = array();

            $path = WF_EDITOR_EXTENSIONS . '/aggregator';
            $files = JFolder::files($path, '\.php$', false, true);

            foreach ($files as $file) {
                require_once ($file);

                $name = basename($file, '.php');
                $classname = 'WFAggregatorExtension_' . ucfirst($name);

                // only load if enabled
                if (class_exists($classname)) {
                    $aggregator = new $classname();

                    // check if enabled
                    if ($aggregator->isEnabled()) {
                        if ($aggregator->get('format') == $format) {
                            $aggregator->set('name', $name);
                            $aggregator->set('title', 'WF_AGGREGATOR_' . strtoupper($name) . '_TITLE');
                            $aggregators[$format][] = $aggregator;
                        }
                    }
                }
            }
        }

        return $aggregators[$format];
    }

    /**
     *
     * @param object $player
     * @return
     */
    public function loadTemplate($name, $tpl = '') {
        $path = WF_EDITOR_EXTENSIONS . '/aggregator/' . $name;

        $output = '';

        $file = 'default.php';

        if ($tpl) {
            $file = 'default_' . $tpl . '.php';
        }

        if (file_exists($path . '/tmpl/' . $file)) {
            ob_start();

            include $path . '/tmpl/' . $file;

            $output .= ob_get_contents();
            ob_end_clean();
        }

        return $output;
    }

}


text:
require 'logger'
require 'rack'

require 'rack-rabbit'

module RackRabbit
  class Config

    #--------------------------------------------------------------------------

    def initialize(options = {})
      @values = {}
      options.each{|key, value| send(key, value) if respond_to?(key)}
      reload(options)
    end

    def reload(options = {})
      @rack_env = nil
      instance_eval(File.read(config_file), config_file) if config_file && File.exist?(config_file)
      validate(options) unless options[:validate] == false
    end

    #--------------------------------------------------------------------------

    def rabbit(value = :missing)
      if value == :missing
        values[:rabbit] ||= {}.merge(DEFAULT_RABBIT)
      elsif value.is_a?(Hash)
        rabbit.merge!(value)
      end
    end

    def config_file(value = :missing)
      if value == :missing
        values[:config_file]
      else
        values[:config_file] = filename(value)
      end
    end

    def rack_file(value = :missing)
      if value == :missing
        values[:rack_file] ||= filename("config.ru", File.dirname(config_file || ""))
      else
        values[:rack_file] = filename(value, File.dirname(config_file || ""))
      end
    end

    def queue(value = :missing)
      if value == :missing
        values[:queue]
      else
        values[:queue] = value
      end
    end

    def exchange(value = :missing)
      if value == :missing
        values[:exchange]
      else
        values[:exchange] = value
      end
    end

    def exchange_type(value = :missing)
      if value == :missing
        values[:exchange_type] ||= :direct
      else
        values[:exchange_type] = value.to_s.downcase.to_sym
      end
    end

    def routing_key(value = :missing)
      if value == :missing
        values[:routing_key]
      else
        values[:routing_key] = value
      end
    end

    def app_id(value = :missing)
      if value == :missing
        values[:app_id] ||= "rr-#{exchange || 'default'}-#{queue || routing_key || 'null'}"
      else
        values[:app_id] = value
      end
    end

    def workers(value = :missing)
      if value == :missing
        values[:workers] ||= 1
      else
        values[:workers] = value.to_i
      end
    end

    def min_workers(value = :missing)
      if value == :missing
        values[:min_workers] ||= 1
      else
        values[:min_workers] = value.to_i
      end
    end

    def max_workers(value = :missing)
      if value == :missing
        values[:max_workers] ||= 32
      else
        values[:max_workers] = value.to_i
      end
    end

    def ack(value = :missing)
      if value == :missing
        values[:ack]
      else
        values[:ack] = !!value
      end
    end

    def preload_app(value = :missing)
      if value == :missing
        values[:preload_app]
      else
        values[:preload_app] = !!value
      end
    end

    def daemonize(value = :missing)
      if value == :missing
        values[:daemonize]
      else
        values[:daemonize] = !!value
      end
    end

    def log_level(value = :missing)
      if value == :missing
        values[:log_level] ||= :info
      else
        values[:log_level] = symbolize(value)
      end
    end

    def logger(value = :missing)
      if value == :missing
        values[:logger] ||= build_default_logger
      else
        values[:logger] = value
      end
    end

    def logfile(value = :missing)
      if value == :missing
        values[:logfile] ||= daemonize ? "/var/log/#{app_id}.log" : nil
      else
        values[:logfile] = filename(value)
      end
    end

    def pidfile(value = :missing)
      if value == :missing
        values[:pidfile] ||= daemonize ? "/var/run/#{app_id}.pid" : nil
      else
        values[:pidfile] = filename(value)
      end
    end

    def before_fork(server=nil, &block)
      if block
        values[:before_fork] = block
      elsif values[:before_fork].respond_to?(:call)
        values[:before_fork].call(server)
      end
    end

    def after_fork(server=nil, worker=nil, &block)
      if block
        values[:after_fork] = block
      elsif values[:after_fork].respond_to?(:call)
        values[:after_fork].call(server, worker)
      end
    end

    #--------------------------------------------------------------------------

    def rack_env
      @rack_env ||= {
        'rack.version'      => Rack::VERSION,
        'rack.logger'       => logger,
        'rack.errors'       => $stderr,
        'rack.multithread'  => false,
        'rack.multiprocess' => true,
        'rack.run_once'     => false,
        'rack.url_scheme'   => 'http',
        'SERVER_NAME'       => app_id
      }
    end

    #--------------------------------------------------------------------------

    private

    attr_reader :values

    def filename(path, relative_to = nil)
      File.expand_path(path, relative_to)
    end

    def symbolize(s)
      s.to_s.downcase.to_sym
    end

    def validate(options = {})

      raise ArgumentError, "must provide EITHER a :queue OR an :exchange to subscribe to" if queue.nil? && exchange.nil?
      raise ArgumentError, "missing app_id" if app_id.to_s.empty?
      raise ArgumentError, "invalid workers" unless workers.is_a?(Integer)
      raise ArgumentError, "invalid min_workers" unless min_workers.is_a?(Integer)
      raise ArgumentError, "invalid max_workers" unless max_workers.is_a?(Integer)
      raise ArgumentError, "invalid workers < min_workers" if workers < min_workers
      raise ArgumentError, "invalid workers > max_workers" if workers > max_workers
      raise ArgumentError, "invalid min_workers > max_workers" if min_workers > max_workers
      raise ArgumentError, "invalid logger" unless [:fatal, :error, :warn, :info, :debug].all?{|method| logger.respond_to?(method)}
      raise ArgumentError, "missing pidfile - required for daemon" if daemonize && pidfile.to_s.empty?
      raise ArgumentError, "missing logfile - required for daemon" if daemonize && logfile.to_s.empty?

      unless options[:skip_filesystem_checks]
        raise ArgumentError, "missing rack config file #{rack_file}" unless File.readable?(rack_file)
        raise ArgumentError, "pidfile not writable" if pidfile && !File.writable?(File.dirname(pidfile))
        raise ArgumentError, "logfile not writable" if logfile && !File.writable?(File.dirname(logfile))
      end

    end

    def build_default_logger
      logger = Logger.new($stderr)
      class << logger
        attr_accessor :master_pid   # track the master_pid (might change if we daemonize) in order to differentiate between "SERVER" vs "worker" in log entry preamble
      end
      logger.master_pid = $$
      logger.formatter = proc do |severity, datetime, progname, msg|
        "[#{Process.pid}:#{$$ == logger.master_pid ? "SERVER" : "worker"}] #{datetime} #{msg}\n"
      end
      logger.level = case log_level.to_s.downcase.to_sym
                     when :fatal then Logger::FATAL
                     when :error then Logger::ERROR
                     when :warn  then Logger::WARN
                     when :info  then Logger::INFO
                     when :debug then Logger::DEBUG
                     else
                       Logger::INFO
                     end
      logger
    end

    #--------------------------------------------------------------------------

  end # class Config
end # module RackRabbit


text:
using namespace std;

class StringManager
{
private:
	string **StringPool;
	unsigned int PoolSize;

	inline bool EffectiveHandle(unsigned int Handle);

public:
	StringManager();
	~StringManager();

	unsigned int CreateString();
	unsigned int ToInt(unsigned int Handle);
	void PutString(unsigned int Handle, const unsigned char *Str);
	unsigned char *GetString(unsigned int Handle);
	string *QuoteString(unsigned int Handle);
	void FreeString(unsigned int Handle);
	unsigned char *StringLeft(unsigned int Handle, unsigned int Size);
	unsigned char *StringRight(unsigned int Handle, unsigned int Size);
	unsigned char *StringMid(unsigned int Handle, unsigned int Offset, unsigned int Size);
	unsigned int StringFind(unsigned int MasterHandle, unsigned int SubHandle, unsigned int Offset);
	bool StringCompare(unsigned int MasterHandle, unsigned int SlaveHandle);
	unsigned int StringLength(unsigned int Handle);
};


text:
package visual_gui_testing;

import java.awt.Robot;

public class KeyReleaseCommand extends UserInputCommand {

	private int myKeyCode;

	public KeyReleaseCommand(int keyCode) {
		myKeyCode = keyCode;
	}

	@Override
	public void execute(Robot r) {
		r.keyRelease(myKeyCode);
	}

}


text:
module Sidekiq
  class Batch
    VERSION = '0.1.9'.freeze
  end
end


text:
FROM aoehmich/cdh5.9:release-candidate
MAINTAINER Axel Oehmichen <axelfrancois.oehmichen11@imperial.ac.uk>

WORKDIR /root

ADD Cloudera_Management.py /root
ADD irkernel_install.r /root
ADD pyspark_kernel.json /root
ADD spark_kernel.json /root
ADD start_eae.sh /root

RUN echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.list \
    && apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823 \
    && apt-get update -q \
#    && apt-get upgrade -y --install-recommends \
    && apt-get install -y git wget python-numpy python-scipy python-matplotlib ipython python-pip python-scikits-learn nodejs-legacy npm zip libcurl4-openssl-dev libxml2-dev screen software-properties-common python-software-properties \
    && add-apt-repository ppa:openjdk-r/ppa \
    && apt-get update \
    && apt-get install -y openjdk-8-jdk \
    && apt-get -y install libcurl4-gnutls-dev sbt

RUN export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.1-cp27-none-linux_x86_64.whl \
    && sudo pip install --upgrade $TF_BINARY_URL \
    && pip install scimath \
    && pip install pymongo \
    && pip install cm-api \
    && chmod 777 start_eae.sh \
    && rm -f /home/eae/.ssh/*

## Setting up Jupyter notebook and we create the folder where the jupyter notebooks will run
RUN pip install setuptools pip --upgrade --user \
    && pip install ipython==5.2.1 \
    && pip install jupyter \
    && git clone https://github.com/aoehmichen/notebook.git \
    && cd notebook \
    && npm cache clean -f \
    && npm install -g n \
    && n stable \
    && pip install -e . --user \
    && cd /root \
    && jupyter-nbextension enable --py widgetsnbextension \
    && mkdir -p /home/eae/jupyter \
    && chown eae:eae /home/eae/jupyter \
    && chmod 777 /home/eae/jupyter \
    && cd /home/eae/jupyter \
    && wget https://github.com/aoehmichen/eae-files/raw/master/jupyter-examples.zip \
    && unzip jupyter-examples.zip \
    && rm jupyter-examples.zip

## Setting up R and R Kernel
RUN wget https://mran.revolutionanalytics.com/install/mro/3.3.1/microsoft-r-open-3.3.1.tar.gz \
    && tar xzf microsoft-r-open-3.3.1.tar.gz \
    && cd microsoft-r-open \
    && ./install.sh \
    && cd /root \
    && Rscript irkernel_install.r

## Setting up the Spark Kernels (Toree)
RUN ipython profile create spark \
    && git clone https://github.com/aoehmichen/incubator-toree/ \
    && cd incubator-toree \
    && make dist \
    && mkdir -p /root/.ipython/kernels/spark \
    && mkdir -p /root/.ipython/kernels/pyspark \
    && cp -r dist/toree /root/.ipython/kernels/spark/ \
    && jupyter notebook --generate-config --allow-root \
    && mv /root/spark_kernel.json /root/.ipython/kernels/spark/kernel.json \
    && mv /root/pyspark_kernel.json /root/.ipython/kernels/pyspark/kernel.json \
    && cd /root/.ipython/kernels/spark/toree/bin \
    && sed -i "/eval exec/d" run.sh \
    && echo 'exec "$SPARK_HOME"/bin/spark-submit \
        ${SPARK_OPTS} \
        --driver-class-path $PROG_HOME/lib/${KERNEL_ASSEMBLY} \
        --class org.apache.toree.Main $PROG_HOME/lib/${KERNEL_ASSEMBLY} "$@"' >> run.sh

EXPOSE 22 7180 7777 8433 8888 18088

VOLUME ["/root/jupyter/"]

ENTRYPOINT ["bash", "/root/start_eae.sh"]

## Default parameters in case the user does not provide them wih the RUN commande
CMD ["-deamon", interfaceeae, 8443, jupytereae, 22]


text:
package helloscala.common.util;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * Various reference types supported by this map.
 */
public enum ReferenceType {

    /**
     * Use {@link SoftReference}s
     */
    SOFT,

    /**
     * Use {@link WeakReference}s
     */
    WEAK
}


text:
// Copyright 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sync;

import android.accounts.Account;
import android.content.SyncStatusObserver;
import android.os.Bundle;

/**
 * Since the ContentResolver in Android has a lot of static methods, it is hard to
 * mock out for tests. This interface wraps all the sync-related methods we use from
 * the Android ContentResolver.
 */
public interface SyncContentResolverDelegate {

    Object addStatusChangeListener(int mask, SyncStatusObserver callback);

    void removeStatusChangeListener(Object handle);

    void setMasterSyncAutomatically(boolean sync);

    boolean getMasterSyncAutomatically();

    void setSyncAutomatically(Account account, String authority, boolean sync);

    boolean getSyncAutomatically(Account account, String authority);

    void setIsSyncable(Account account, String authority, int syncable);

    int getIsSyncable(Account account, String authority);

    void removePeriodicSync(Account account, String authority, Bundle extras);
}


text:
-- This originally was in 58/, but landed after 59/ was created, and so some
-- servers running develop didn't run this delta. Running it again should be
-- safe.
--
-- We first delete any in progress `rejected_events_metadata` background update,
-- to ensure that we don't conflict when trying to insert the new one. (We could
-- alternatively do an ON CONFLICT DO NOTHING, but that syntax isn't supported
-- by older SQLite versions. Plus, this should be a rare case).
DELETE FROM background_updates WHERE update_name = 'rejected_events_metadata';
INSERT INTO background_updates (ordering, update_name, progress_json) VALUES
  (5828, 'rejected_events_metadata', '{}');


text:
function processData(input) {
    var lines = input.split('\n');
    var n = parseInt(lines[0]);
    var sumLeftRight = 0;
    var sumRightLeft = 0;
    for(var i = 0; i < n; i++)
    {
        var elements = lines[i + 1].split(" ").map(function(s) {return parseInt(s)});
        sumLeftRight += elements[i];
        sumRightLeft += elements[n - i - 1];
    }
    console.log(Math.abs(sumLeftRight - sumRightLeft));
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
    processData(_input);
});


text:
const moment = require('moment')
const rssFeed = require('../models/rssFeed')
const rss = require('../models/rss')
const category = require('../models/category')

const URL_LENGTH = 60
const RSS_LIMIT = 40

const CATEGORY_LIMIT = 10
const CATEGORY_OFFSET = 0
var CATEGORY_ARRAY = [/*1, 2, 3, 4, 5, 6, 7, 8*/]
var CATEGORY_MAP = {}
category.readAll(CATEGORY_LIMIT, CATEGORY_OFFSET).then(function(categoryResult){
  categoryResult.rows.forEach(function(categoryItem){
    CATEGORY_MAP[categoryItem.id] = categoryItem.name
    CATEGORY_ARRAY.push(categoryItem.id)
  })
})

const getTimeAgo = date => (
  moment(date).fromNow()
)

const getTrimRssurl = rssfeedurl => (
  rssfeedurl.length > URL_LENGTH
  ? rssfeedurl.substring(0, URL_LENGTH - 3) + '...'
  : rssfeedurl
)

const getTrimThumbnail = thumbnail => {
  if(thumbnail && thumbnail.indexOf(',')>=0 ) {
    const thumbnailSplit = thumbnail.split(',')
    return thumbnailSplit[0]
  }

  return thumbnail
}

/**
 * GET /
 * RSS feeds page.
 */
exports.index = (req, res) => {
  category.read(req.params.categoryId).then(function(categoryResult){
    rss.read(req.params.rssId).then(function(rssResult){
      rssFeed.readByRssId(req.params.rssId, RSS_LIMIT).then(function(result){
        result.rows.forEach( item => {
          // console.log('item', item)
          const re = /[' /]+$/
          const trimThumbnailString = getTrimThumbnail(item.thumbnail)

          item.timeago = getTimeAgo(item.releasedate)
          item.trimRssurl = getTrimRssurl(item.rssfeedurl)
          item.trimThumbnail = trimThumbnailString.replace(re, '')
        })
        // console.log('result.rows', result.rows)
        res.render('rss', {
          categoryName: categoryResult.rows[0].name,
          rssName: rssResult.rows[0].rssname,
          categoryId: req.params.categoryId,
          rssId: req.params.rssId,
          categoryArray: CATEGORY_ARRAY,
          categoryMap: CATEGORY_MAP,
          result: result.rows,
        })
      })
    })
  })
}


text:
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
)

func main() {
	cpath := flag.String("config", "/etc/nginx-to-librato.conf", "Path to a configuration file")
	debug := flag.Bool("debug", false, "Turn on debugging")
	version := flag.Bool("version", false, "Prints the version and exits")

	flag.Parse()

	// Discard logging if debug is turned off.
	if *debug == false {
		log.SetOutput(ioutil.Discard)
	} else {
		log.Printf("Debugging enabled for %s", versionString())
	}

	// Print the version and exit
	if *version == true {
		fmt.Println(versionString())
		os.Exit(0)
	}

	con, errs := NewConf(*cpath)
	// Print the errors from the config and exit if there are any
	if len(errs) > 0 {
		fmt.Fprintf(os.Stderr, "Configuration errors:\n")
		for _, e := range errs {
			fmt.Fprintf(os.Stderr, "* %s\n", e.Error())
		}
		os.Exit(1)
	}

	flusher := NewMetricFlusher(con)
	// Start publishing metrics
	flusher.publishLoop()
}


text:
package Mar2021Leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class _0046Permutations {

	public static void main(String[] args) {
		System.out.println(permute(new int[] { 1, 2, 3 }));
		System.out.println(permute(new int[] { 0, 1 }));
		System.out.println(permute(new int[] { 1 }));
	}

	public static List<List<Integer>> permute(int[] nums) {
		List<List<Integer>> output = new ArrayList<List<Integer>>();
		dfs(nums, new ArrayList<Integer>(), output, new HashSet<Integer>());
		return output;
	}

	public static void dfs(int[] nums, List<Integer> list, List<List<Integer>> output, HashSet<Integer> visited) {
		if (list.size() == nums.length) {
			output.add(new ArrayList<Integer>(list));
			return;
		}

		for (int i = 0; i < nums.length; i++) {
			if (!visited.contains(i)) {
				list.add(nums[i]);
				visited.add(i);
				dfs(nums, list, output, visited);
				visited.remove(i);
				list.remove(list.size() - 1);
			}
		}
	}

}


text:
package org.apache.ignite.internal.processors.database;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheRebalanceMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;

/**
 *
 */
public class IgniteDbSingleNodeWithIndexingPutGetTest extends IgniteDbSingleNodePutGetTest {
    /** {@inheritDoc} */
    @Override protected boolean indexingEnabled() {
        return true;
    }

    /**
     */
    public void testGroupIndexes() {
        IgniteEx ig = grid(0);

        IgniteCache<Integer, Abc> cache = ig.cache("abc");

        long cnt = 50_000;

        for (int i = 0; i < cnt; i++)
            cache.put(i, new Abc(i, i % 10, i % 100));

        assertEquals(1, querySize(cache, "select count(*) from Abc"));
        assertEquals(Long.valueOf(cnt), queryOne(cache, "select count(*) from Abc"));

        assertEquals((int)cnt, querySize(cache, "select count(*) from Abc group by a"));
        assertEquals(Long.valueOf(1L), queryOne(cache, "select count(*) from Abc group by a"));
        assertEquals(Long.valueOf(1L), queryOne(cache, "select count(*) from Abc where a = 1"));

        assertEquals(10, querySize(cache, "select count(*) from Abc group by b"));
        assertEquals(Long.valueOf(cnt / 10), queryOne(cache, "select count(*) from Abc group by b"));
        assertEquals(Long.valueOf(cnt / 10), queryOne(cache, "select count(*) from Abc where b = 1"));

        assertEquals(100, querySize(cache, "select count(*) from Abc group by c"));
        assertEquals(Long.valueOf(cnt / 100), queryOne(cache, "select count(*) from Abc group by c"));
        assertEquals(Long.valueOf(cnt / 100), queryOne(cache, "select count(*) from Abc where c = 1"));
    }

    /**
     */
    public void testGroupIndexes2() {
        IgniteEx ig = grid(0);

        IgniteCache<Integer,Abc> cache = ig.cache("abc");

        long cnt = 10_000;

        Map<Integer,AtomicLong> as = new TreeMap<>();
        Map<Integer,AtomicLong> bs = new TreeMap<>();
        Map<Integer,AtomicLong> cs = new TreeMap<>();

        Random rnd = ThreadLocalRandom.current();

        for (int i = 0; i < cnt; i++) {
            Abc abc = new Abc(rnd.nextInt(2000), rnd.nextInt(100), rnd.nextInt(5));

//            X.println(">> " + i + " " + abc);

            cache.put(i, abc);

            add(as, abc.a, true);
            add(bs, abc.b, true);
            add(cs, abc.c, true);

            if (rnd.nextInt(1000) == 0) {
                switch (rnd.nextInt(3)) {
                    case 0:
                        check(as, cache, "a");

                        break;

                    case 1:
                        check(bs, cache, "b");

                        break;

                    case 2:
                        check(cs, cache, "c");

                        break;

                    default:
                        fail();
                }
            }
        }

        check(as, cache, "a");
        check(bs, cache, "b");
        check(cs, cache, "c");
    }

    /**
     * @param xs Counters.
     * @param cache Cache.
     * @param field Field name.
     */
    private static void check(Map<Integer,AtomicLong> xs, IgniteCache<Integer,Abc> cache, String field) {
        String qry = "select " + field + ", count(*) from Abc group by " + field + " order by " + field;

        List<List<?>> res = cache.query(new SqlFieldsQuery(qry)).getAll();

        assertEquals(xs.size(), res.size());

        int i = 0;

        for (Map.Entry<Integer,AtomicLong> entry : xs.entrySet()) {
//            X.println("    " + field + ": " + entry);

            int key = entry.getKey();
            long cnt = entry.getValue().get();

            assertEquals(key, res.get(i).get(0));
            assertEquals(cnt, res.get(i).get(1));

            qry = "select 1 from Abc where " + field + " = " + key;
            assertEquals(cnt, querySize(cache, qry));

            qry = "select count(*) from Abc where " + field + " = " + key;
            assertEquals(Long.valueOf(cnt), queryOne(cache, qry));

            i++;
        }
    }

    /**
     * @param xs Map.
     * @param key Key.
     * @param inc Increment.
     */
    private static void add(Map<Integer,AtomicLong> xs, int key, boolean inc) {
        AtomicLong cntr = xs.get(key);

        if (cntr == null) {
            if (!inc)
                fail("Nothing to decrement.");

            xs.put(key, cntr = new AtomicLong());
        }

        cntr.addAndGet(inc ? 1 : -1);
    }

    @SuppressWarnings("unchecked")
    private static <X> X queryOne(IgniteCache<?, ?> cache, String qry) {
        return (X)cache.query(new SqlFieldsQuery(qry)).getAll().get(0).get(0);
    }

    private static int querySize(IgniteCache<?, ?> cache, String qry) {
        return cache.query(new SqlFieldsQuery(qry)).getAll().size();
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(gridName);

        CacheConfiguration ccfg = new CacheConfiguration("abc");

        if (indexingEnabled())
            ccfg.setIndexedTypes(Integer.class, Abc.class);

        ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
        ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
        ccfg.setRebalanceMode(CacheRebalanceMode.SYNC);

        cfg.setCacheConfiguration(F.concat(cfg.getCacheConfiguration(), ccfg));

        return cfg;
    }

    static class Abc {
        /** */
        @QuerySqlField
//            (index = true)
            (orderedGroups = {
                @QuerySqlField.Group(name = "abc", order = 0),
            })
        private int a;

        /** */
        @QuerySqlField
            (index = true, orderedGroups = {
                @QuerySqlField.Group(name = "abc", order = 1),
                @QuerySqlField.Group(name = "cb", order = 1)
            })
        private int b;

        /** */
        @QuerySqlField
//            (index = true)
            (orderedGroups = {
                @QuerySqlField.Group(name = "abc", order = 2),
                @QuerySqlField.Group(name = "cb", order = 0)
            })
        private int c;

        /**
         * @param a A.
         * @param b B.
         * @param c C.
         */
        Abc(int a, int b, int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(Abc.class, this);
        }
    }
}


text:
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"text/template"
)

type Release struct {
	Meta
	Assets []Asset `json:"assets"`
}

type Meta struct {
	TagName string `json:"tag_name"`
}

type Asset struct {
	Name               string `json:"name"`
	BrowserDownloadURL string `json:"browser_download_url"`
}

type DarwinAMD64 struct {
	Meta
	Asset  Asset
	Sha256 string
}

func main() {
	res, err := http.Get("https://api.github.com/repos/minodisk/qiitactl/releases/latest")
	if err != nil {
		fmt.Sprintf("api error: %s", err)
		log.Fatal(err)
	}
	defer res.Body.Close()
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	var release Release
	err = json.Unmarshal(b, &release)
	if err != nil {
		log.Fatal(err)
	}

	darwin, err := findDarwinAMD64(release)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", darwin)

	tmpl, err := template.ParseFiles(".brew/brew.rb.tmpl")
	if err != nil {
		log.Fatal(err)
	}
	f, err := os.Create("homebrew-qiitactl/qiitactl.rb")
	defer f.Close()
	if err != nil {
		log.Fatal(err)
	}
	err = tmpl.Execute(f, darwin)
	if err != nil {
		log.Fatal(err)
	}

}

func findDarwinAMD64(release Release) (darwin DarwinAMD64, err error) {
	darwin.Meta = release.Meta
	for _, asset := range release.Assets {
		if strings.HasSuffix(asset.Name, "_darwin_amd64.zip") {
			darwin.Asset = asset
			resp, err := http.Get(asset.BrowserDownloadURL)
			if err != nil {
				fmt.Sprintf("download error: %s", err)
				return darwin, err
			}
			defer resp.Body.Close()
			hasher := sha256.New()
			_, err = io.Copy(hasher, resp.Body)
			if err != nil {
				return darwin, err
			}
			darwin.Sha256 = hex.EncodeToString(hasher.Sum(nil))
			return darwin, nil
		}
	}
	err = errors.New("not found")
	return
}


text:
Dir[File::expand_path(__FILE__ + "/../support/**/*.rb")].each{|file| require file}
Ungemmer::ungem_gemspec
# require 'spec/rails'

# module ActiveSupport
#   class TestCase
#     include ::Spec::Rails::Matchers
#     include ::Spec::Rails::Mocks
#   end
# end


text:
// Decompiled with JetBrains decompiler
// Type: System.Fabric.Management.ServiceModel.SecurityOptionsType
// Assembly: System.Fabric.Management.ServiceModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: C6D32D4D-966E-4EA3-BD3A-F4CF14D36DBC
// Assembly location: C:\Git\ServiceFabricSdkContrib\ServiceFabricSdkContrib.MsBuild\bin\Debug\netstandard2.0\publish\runtimes\win\lib\netstandard2.0\System.Fabric.Management.ServiceModel.dll

using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Xml.Serialization;

namespace System.Fabric.Management.ServiceModel
{
  [GeneratedCode("xsd", "4.0.30319.17929")]
  [DebuggerStepThrough]
  [XmlType(Namespace = "http://schemas.microsoft.com/2011/01/fabric")]
  public class SecurityOptionsType
  {
    private string valueField;

    [XmlAttribute]
    public string Value
    {
      get
      {
        return this.valueField;
      }
      set
      {
        this.valueField = value;
      }
    }
  }
}


text:
using Aurora.Framework;

namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
    public class PhysicsFrameMonitor : IMonitor, IPhysicsFrameMonitor
    {
        private float physicsFPS;

        public PhysicsFrameMonitor(IScene scene)
        {
        }

        #region Implementation of IMonitor

        public double GetValue()
        {
            return LastReportedPhysicsFPS;
        }

        public string GetName()
        {
            return "Total Physics Frame Time";
        }

        public string GetFriendlyValue()
        {
            return (int) GetValue() + "ms";
        }

        #endregion

        #region Other Methods

        #region IMonitor Members

        public void ResetStats()
        {
            physicsFPS = 0;
        }

        #endregion

        #region IPhysicsFrameMonitor Members

        public void AddFPS(int value)
        {
            physicsFPS += value;
        }

        #endregion

        #endregion

        #region IPhysicsFrameMonitor Members

        public float LastReportedPhysicsFPS { get; set; }

        public float PhysicsFPS
        {
            get { return physicsFPS; }
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">
<CSP name="confpage.csp" application="/csp/sysmon/" default="1"><![CDATA[

		<link rel="stylesheet" href="./lib/css/bootstrap.min.css">
		<title>SYSMON Configure page</title>

<csp:method name = "WriteClassChanges" Arguments="a:%Integer,b:%String">
new $namespace
set $namespace = "%SYS"
set ^SYSMONClassTemp(b) = a
</csp:method>

<csp:method name = "SaveAll">
new $namespace
set $namespace = "%SYS"
if $data(^SYSMONClassTemp)
{
	set key = $order(^SYSMONClassTemp(""))
	while (key '= "")
	{
		set value = ^SYSMONClassTemp(key)
		do ##class(%Monitor.ItemGroup).MetricsClassItemGroup(key,.id)
	 	set class=##class(%Monitor.ItemGroup).%OpenId(id)
	 	set class.Activated = value
	 	do class.%Save()
	 	set key = $order(^SYSMONClassTemp(key))
	}
	kill ^SYSMONClassTemp
	&js<alert("Settings changed")>
	&js<location.reload()>

}
</csp:method>

<csp:method name = "StopMonitor">
new $namespace
set $namespace = "%SYS"
set sc = ##class(%SYS.Monitor).Stop()
if sc=1 {
	&js< alert(" System Monitor stopped")>
} elseif sc=-1 {
	&js< alert(" System Monitor not running!")>
} else {
	 &js< alert("ERROR: "+#($ZE)#)>
}
</csp:method>

<csp:method name = "StartMonitor">
new $namespace
set $namespace = "%SYS"
set sc = ##class(%SYS.Monitor).Start()
if sc=1 {
	&js< alert("System Monitor started")>
} elseif sc =-1 {
	&js< alert("System Monitor already running!")>
} else {
	&js< alert("ERROR: "+#($ZE)#)>
}
</csp:method>

<csp:method name = "CheckMon">
new $namespace
set $namespace = "%SYS"
set sc = ##class(%SYS.Monitor).State()
if sc=0 {
	&js< document.getElementById('btnstart').disabled = false;
		 document.getElementById('btnstop').disabled = true;>
} else{
	&js< document.getElementById('btnstop').disabled = false;
		 document.getElementById('btnstart').disabled = true;>
}
</csp:method>

Sysmon Application Classes configuration:

					<form name="configform">
					<csp:while condition="Rset.Next()" counter="i">

								<input type="checkbox" name="#(i)#" value="#(Rset.GetData(1))#" #(chkd)# onclick="classChk(this.checked, this.value)">

								#(Rset.GetData(1))#

					</csp:while>

						<input style="margin-top: 2px; width: 250px;" class="btn btn-success" type="button" value="Apply" onclick="submitAll();"/>

					</form>

Control System Monitor:

					<input id="btnstart" class="btn btn-primary" type="button" value="Start SYSMON" onclick="startMon();"/>
					<input id="btnstop" class="btn btn-danger" type="button" value="Stop SYSMON" onclick="stopMon();"/>

]]></CSP>
</Export>


text: .NET E-Commerce Suite


text:
@interface JKQiNiuVM : JKViewModel

@property (nonatomic, strong) UIImage *image;

- (void)QiNiuRequestWithSuccessBlock:(ReturnSuccessBlock)successBlock withFailureBlock:(ReturnFailureBlock)failureBlock;
@end


text:
package io.digdag.guice.rs;

import java.util.Map;
import java.util.Set;
import java.io.IOException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.HandlesTypes;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@HandlesTypes(GuiceRsBootstrap.class)
public class GuiceRsServletContainerInitializer
        implements ServletContainerInitializer
{
    @Override
    @SuppressWarnings("unchecked")
    public void onStartup(Set<Class<?>> classes, ServletContext ctx)
    {
        ctx.setAttribute(GuiceRsServletContainerInitializer.class.getName(), this);

        for (Class<?> bootstrap : classes) {
            if (GuiceRsBootstrap.class.isAssignableFrom(bootstrap)) {
                processBootstrap((Class<GuiceRsBootstrap>) bootstrap, ctx);
            }
            else {
                // TODO show warnings
            }
        }
    }

    private void processBootstrap(final Class<GuiceRsBootstrap> bootstrap, final ServletContext context)
    {
        ImmutableList.Builder<Module> modules = ImmutableList.builder();
        Module module;

        module = GuiceRsServerControlModule.fromInitParameter(context);
        if (module != null) {
            modules.add(module);
        }

        modules.add((binder) -> {
            binder.bind(GuiceRsBootstrap.class).to(bootstrap).asEagerSingleton();
            binder.bind(ServletContext.class).toInstance(context);
        });

        final Injector injector = Guice.createInjector(modules.build())
            .getInstance(GuiceRsBootstrap.class)
            .initialize(context);

        if (injector instanceof AutoCloseable) {
            context.addListener(new CloseableInjectorDestroyListener((AutoCloseable) injector));
        }

        injector.findBindingsByType(TypeLiteral.get(GuiceRsServletInitializer.class))
            .stream()
            .map(binding -> binding.getProvider().get())
            .forEach(initializer -> initializer.register(injector, context));

        // return 404 Not Found if all URL patterns don't match
        context.addServlet("default", new DefaultServlet())
            .addMapping("/");
    }

    private static class DefaultServlet extends HttpServlet
    {
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
        {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private static class CloseableInjectorDestroyListener
            implements ServletContextListener
    {
        private final AutoCloseable closeable;

        public CloseableInjectorDestroyListener(AutoCloseable closeable)
        {
            this.closeable = closeable;
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce)
        {
            try {
                closeable.close();
            }
            catch (Exception exception) {
                throw new RuntimeException(exception);
            }
        }

        @Override
        public void contextInitialized(ServletContextEvent sce)
        { }
    }
}


text:
package com.expedia.echox3.internal.transport.socket;

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

import com.expedia.echox3.basics.collection.simple.ManagedSet;
import com.expedia.echox3.basics.monitoring.event.BasicLogger;

public class ComputerAddressGroup
{
	private static final BasicLogger			LOGGER					= new BasicLogger(ComputerAddressGroup.class);
	private final String						m_groupName;
	private volatile int						m_laneCount				= 0;
	private final ManagedSet<ComputerAddress>	m_addressSet			= new ManagedSet<>();

	public ComputerAddressGroup(String groupName)
	{
		m_groupName = groupName;
	}

	public static BasicLogger getLogger()
	{
		return LOGGER;
	}

	public String getGroupName()
	{
		return m_groupName;
	}

	public int getVersion()
	{
		return m_addressSet.getVersion();
	}
	public void incrementVersion()
	{
		m_addressSet.incrementVersion();
	}

	public Set<ComputerAddress> getAddressSet()
	{
		return m_addressSet;
	}

	public int getLaneCount()
	{
		return m_laneCount;
	}

	public void setAddressList(Collection<ComputerAddress> addressSet)
	{
		m_addressSet.setTo(addressSet);
		updateLaneCount();
	}
	public boolean addAddress(ComputerAddress address)
	{
		boolean		isModified		= m_addressSet.add(address);
		updateLaneCount();
		return isModified;
	}
	public boolean removeAddress(ComputerAddress address)
	{
		boolean		isModified		= m_addressSet.remove(address);
		updateLaneCount();
		return isModified;
	}
	private void updateLaneCount()
	{
		int		count		= 0;
		for (ComputerAddress address : m_addressSet)
		{
			count += address.getLaneCount();
		}
		m_laneCount = count;
	}

	public void close()
	{
		for (ComputerAddress address : m_addressSet)
		{
			removeAddress(address);
		}
	}

	/**
	 * Returns a hash code value for the object. This method is
	 * supported for the benefit of hash tables such as those provided by
	 * {@link HashMap}.
	 *

	 * The general contract of {@code hashCode} is:
	 *

	 *
Whenever it is invoked on the same object more than once during
	 * an execution of a Java application, the {@code hashCode} method
	 * must consistently return the same integer, provided no information
	 * used in {@code equals} comparisons on the object is modified.
	 * This integer need not remain consistent from one execution of an
	 * application to another execution of the same application.
	 *
If two objects are equal according to the {@code equals(Object)}
	 * method, then calling the {@code hashCode} method on each of
	 * the two objects must produce the same integer result.
	 *
It is not required that if two objects are unequal
	 * according to the {@link Object#equals(Object)}
	 * method, then calling the {@code hashCode} method on each of the
	 * two objects must produce distinct integer results.  However, the
	 * programmer should be aware that producing distinct integer results
	 * for unequal objects may improve the performance of hash tables.
	 *

	 *

	 * As much as is reasonably practical, the hashCode method defined by
	 * class {@code Object} does return distinct integers for distinct
	 * objects. (This is typically implemented by converting the internal
	 * address of the object into an integer, but this implementation
	 * technique is not required by the
	 * Java™ programming language.)
	 *
	 * @return a hash code value for this object.
	 * @see Object#equals(Object)
	 * @see System#identityHashCode
	 */
	@Override
	public int hashCode()
	{
		int		hash		= m_groupName.hashCode();
		return hash;
	}

	/**
	 * Indicates whether some other object is "equal to" this one.
	 *

	 * The {@code equals} method implements an equivalence relation
	 * on non-null object references:
	 *

	 *
It is reflexive: for any non-null reference value
	 * {@code x}, {@code x.equals(x)} should return
	 * {@code true}.
	 *
It is symmetric: for any non-null reference values
	 * {@code x} and {@code y}, {@code x.equals(y)}
	 * should return {@code true} if and only if
	 * {@code y.equals(x)} returns {@code true}.
	 *
It is transitive: for any non-null reference values
	 * {@code x}, {@code y}, and {@code z}, if
	 * {@code x.equals(y)} returns {@code true} and
	 * {@code y.equals(z)} returns {@code true}, then
	 * {@code x.equals(z)} should return {@code true}.
	 *
It is consistent: for any non-null reference values
	 * {@code x} and {@code y}, multiple invocations of
	 * {@code x.equals(y)} consistently return {@code true}
	 * or consistently return {@code false}, provided no
	 * information used in {@code equals} comparisons on the
	 * objects is modified.
	 *
For any non-null reference value {@code x},
	 * {@code x.equals(null)} should return {@code false}.
	 *

	 *

	 * The {@code equals} method for class {@code Object} implements
	 * the most discriminating possible equivalence relation on objects;
	 * that is, for any non-null reference values {@code x} and
	 * {@code y}, this method returns {@code true} if and only
	 * if {@code x} and {@code y} refer to the same object
	 * ({@code x == y} has the value {@code true}).
	 *

	 * Note that it is generally necessary to override the {@code hashCode}
	 * method whenever this method is overridden, so as to maintain the
	 * general contract for the {@code hashCode} method, which states
	 * that equal objects must have equal hash codes.
	 *
	 * @param obj the reference object with which to compare.
	 * @return {@code true} if this object is the same as the obj
	 * argument; {@code false} otherwise.
	 * @see #hashCode()
	 * @see HashMap
	 */
	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof ComputerAddressGroup)
		{
			return m_groupName.equals(((ComputerAddressGroup)obj).m_groupName);
		}
		else
		{
			return false;
		}
	}

	/**
	 * Returns a string representation of the object. In general, the
	 * {@code toString} method returns a string that
	 * "textually represents" this object. The result should
	 * be a concise but informative representation that is easy for a
	 * person to read.
	 * It is recommended that all subclasses override this method.
	 *

	 * The {@code toString} method for class {@code Object}
	 * returns a string consisting of the name of the class of which the
	 * object is an instance, the at-sign character `{@code @}', and
	 * the unsigned hexadecimal representation of the hash code of the
	 * object. In other words, this method returns a string equal to the
	 * value of:
	 *

	 *

	 * getClass().getName() + '@' + Integer.toHexString(hashCode())
	 *

	 *
	 * @return a string representation of the object.
	 */
	@Override
	public String toString()
	{
		return String.format("%s (%,d address, %,d lanes)", m_groupName, m_addressSet.size(), m_laneCount);
	}
}


text:
package com.cloudant.client.internal.views;

import com.cloudant.client.api.views.PaginatedRequestBuilder;
import com.cloudant.client.api.views.ViewRequest;

public class PaginatedRequestBuilderImpl<K, V> extends
        CommonViewRequestBuilder<K, V, PaginatedRequestBuilder<K, V>> implements
        PaginatedRequestBuilder<K, V> {

    public PaginatedRequestBuilderImpl(ViewQueryParameters<K, V> params) {
        super(params);
        //default to 20 rows per page
        viewQueryParameters.setRowsPerPage(20);
    }

    @Override
    public PaginatedRequestBuilder<K, V> returnThis() {
        return this;
    }

    @Override
    public ViewRequest<K, V> build() {
        validateQuery();
        return new ViewRequestImpl<K, V>(viewQueryParameters);
    }
}


text:
<?php namespace Modules\Core\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\Core\Foundation\Asset\Manager\AsgardAssetManager;
use Modules\Core\Foundation\Asset\Pipeline\AsgardAssetPipeline;

class AssetServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     * @return void
     */
    public function register()
    {
        $this->bindAssetClasses();
    }

    /**
     * Bind classes related to assets
     */
    private function bindAssetClasses()
    {
        $this->app->singleton('Modules\Core\Foundation\Asset\Manager\AssetManager', function () {
            return new AsgardAssetManager();
        });

        $this->app->singleton('Modules\Core\Foundation\Asset\Pipeline\AssetPipeline', function ($app) {
            return new AsgardAssetPipeline($app['Modules\Core\Foundation\Asset\Manager\AssetManager']);
        });
    }
}


text:
Dear {{talent.name}},

Per client's request, the Audition Project {{project.title}} has been cancelled. Unless further instructed, you may disregard this particular audition.

If you have any questions please email me or Debbie!

Thank you!

	{% autoescape false %}{{emailSignature}}{% endautoescape %}


text:
/**
 * @author geeksaga
 * @version 0.1
 */
package com.geeksaga.forest.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "pw_tags", catalog = "", schema = "", uniqueConstraints = { @UniqueConstraint(columnNames = "tag_name") })
public class Tag extends BaseEntity implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Column(name = "tag_name", nullable = false, columnDefinition = "VARCHAR(64)", unique = true)
    private String tagName;

    @Column(name = "hit_cnt", nullable = false, columnDefinition = "INTEGER DEFAULT 1")
    private int hitCnt;

    @Column(name = "parsing", nullable = false)
    private String parsing;

    @Transient
    private Long targetSid;

    @Transient
    private int tagCnt;

    // mappedBy 는 대상에 포함된 변수명과 일치 해야 한다.
    // @ManyToOne
    // @OneToMany(fetch = FetchType.LAZY, mappedBy = "tag", cascade = CascadeType.ALL)
    // // @MapsId("tag_sid")
    // // @MapsId("tagmap_tag_sid")
    // // @JoinColumn(name = "pk_tag_sid", insertable = false, updatable = false)
    // // // // @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    // // // // @JoinColumn(name = "tagmap_pk", referencedColumnName="sid", insertable=false, updatable=false)
    // // // // @PrimaryKeyJoinColumn
    // private List<TagMap> tagMaps = new ArrayList<TagMap>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.tag")
    private Set<TagMap> tagSet = new HashSet<TagMap>(0);

    public Set<TagMap> getTagSet()
    {
        return tagSet;
    }

    public void setTagSet(Set<TagMap> tagSet)
    {
        this.tagSet = tagSet;
    }

    // private Seed seed;
    //
    // @ManyToOne
    // @JoinColumn(name="sid", insertable=false, updatable=false)
    // public Seed getSeed()
    // {
    // return seed;
    // }

    // public List<TagMap> getTagMaps()
    // {
    // return tagMaps;
    // }
    //
    // public void setTagMaps(List<TagMap> tagMaps)
    // {
    // this.tagMaps = tagMaps;
    // }

    public Tag()
    {}

    public Tag(String tagName, String parsing)
    {
        this(0L, tagName, parsing);
    }

    public Tag(Long sid, String tagName, String parsing)
    {
        this(sid, 0L, tagName, parsing);
    }

    public Tag(Long sid, Long targetSid, String tagName, String parsing)
    {
        this.sid = sid;
        this.targetSid = targetSid;
        this.tagName = tagName;
        this.parsing = parsing;
    }

    public Long getTargetSid()
    {
        return targetSid;
    }

    public void setTargetSid(Long targetSid)
    {
        this.targetSid = targetSid;
    }

    public String getTagName()
    {
        return tagName;
    }

    public void setTagName(String tagName)
    {
        this.tagName = tagName;
    }

    public int getTagCnt()
    {
        return tagCnt;
    }

    public void setTagCnt(int tagCnt)
    {
        this.tagCnt = tagCnt;
    }

    public int getHitCnt()
    {
        return hitCnt;
    }

    public void setHitCnt(int hitCnt)
    {
        this.hitCnt = hitCnt;
    }

    public String getParsing()
    {
        return parsing;
    }

    public void setParsing(String parsing)
    {
        this.parsing = parsing;
    }

    public String toString()
    {
        return "Tag [sid = " + sid + ", tagName = " + tagName + ", parsing = " + parsing + ", hitCnt = " + hitCnt + "]";
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2014 Evolveum
  ~
  ~ 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.
  -->

<objects xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
         xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3">

    <task>
        <name>Recompute all users</name>
		<extension>
            <scext:executeScript xmlns:scext="http://midpoint.evolveum.com/xml/ns/public/model/scripting/extension-3">
                <s:search xmlns:s="http://midpoint.evolveum.com/xml/ns/public/model/scripting-3">
                    <s:type>c:UserType</s:type>
                    <s:action>
                        <s:type>recompute</s:type>
                    </s:action>
                </s:search>
            </scext:executeScript>
		</extension>
        <ownerRef oid="00000000-0000-0000-0000-000000000002"/>
        <executionStatus>runnable</executionStatus>

        <category>BulkActions</category>
        <handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/scripting/handler-3</handlerUri>
        <recurrence>single</recurrence>
    </task>

</objects>


text:
Controllers
===========

.. image:: ../diagrams/controllers.png


text:
<?php

/**
 * @file
 * Hooks provided by the Commons module.
 */

/**
 * @addtogroup hooks
 * @{
 */

/**
 * Define entity integrations.
 *
 * This hook allows modules to register entity types and/or bundles that they
 * provide for integration with Commons functionality. For example, a webform
 * module could use it to register a form entity type and its "Test", "Survey"
 * and "Suggestion" bundles.
 *
 * @return
 *   An associative array of entity integrations whose keys define the entity
 *   type for each integration and whose values contain the bundles which have
 *   been integrated. Each bundle is itself an associative array, whose keys
 *   define the type of integration to enable and whose values contain the
 *   status of the integration. TRUE = enabled, FALSE = disabled.
 *
 * For a detailed usage example, see commons_q_a.module.
 *
 * @see hook_commons_entity_integration_alter()
 */
function hook_commons_entity_integration() {
  // Register three of the webform entity's bundles for various integrations.
  return array(
    'webform' => array(
      'test' => array(
        'exclude_rate' => TRUE,
        'is_group_content' => FALSE,
      ),
      'survey' => array(
        'is_group_content' => TRUE,
        'exclude_topics' => TRUE,
      ),
      'suggestion' => array(
        'media' => TRUE,
        'is_group_content' => TRUE,
        'exclude_commons_follow' => TRUE,
      ),
    ),
    'node' => array(
      'group' => array(
        'is_group_content' => FALSE,
        'is_group' => TRUE,
        'exclude_commons_follow' => TRUE,
      ),
    ),
  );
}

/**
 * Perform alterations on entity integrations.
 *
 * @param $integrations
 *   An associative array of entity integrations whose keys define the entity
 *   type for each integration and whose values contain the bundles which have
 *   been integrated. Each bundle is itself an associative array, whose keys
 *   define the type of integration to enable and whose values contain the
 *   status of the integration. TRUE = enabled, FALSE = disabled.
 *
 * @see hook_commons_entity_integration()
 */
function hook_commons_entity_integration_alter(&$integrations) {
  // Disable Media integration for the post content type.
  $integrations['node']['post']['media'] = FALSE;
}

/**
 * @} End of "addtogroup hooks".
 */


text:
/*****************************************************************************/
/* PaygradeCreate: Event Handlers */
/*****************************************************************************/
import Ladda from 'ladda';
import _ from 'underscore'
Template.PaygradeCreate.events({
    'click #PayGradeButton': (e, tmpl) => {
        e.preventDefault();
        let l = Ladda.create(tmpl.$('#PayGradeButton')[0]);
        l.start();
        const details = {
            businessId: BusinessUnits.findOne()._id,
            code: $('[name="code"]').val(),
            description: $('[name="description"]').val(),
            positions: Core.returnSelection($('[name="positions"]')),
            payGroups: Core.returnSelection($('[name="paygroups"]')),
            leaveRequest: $('[name="leaveRequest"]').val(),
            status: $('[name="status"]').val(),
            payTypes: getPaytypes(),
            payTypePositionIds: payTypesPositionOnPayrunExport(),
            enablePensionPayments: $('#enablePensionPayments').is(":checked"),
        //    minimumHoursWorkedForPayroll: $('#minimumHoursWorkedForPayroll').val(),
        };

        let currencyCode = $('[name="currencyCode"]').val()
        details['netPayAlternativeCurrency'] = currencyCode

        function getPaytypes(){
            let paytypes =  [];
            let assigned = Template.instance().dict.get('assigned');
            //return relevant fields

            assigned.forEach((x, payTypeIndex) => {
                let payment = {};
                payment.paytype = x._id;
                payment.value = x.value;
                payment.displayInPayslip = x.displayInPayslip;

                // let payTypePositionId = $('#paySlipPaytypes > tbody > tr').eq(payTypeIndex).find('td').eq(0).find('input').eq(0).val()
                // let payTypePositionIdAsNum = parseInt(payTypePositionId)

                // if(!isNaN(payTypePositionIdAsNum)) {
                //     payment.paySlipPositionId = payTypePositionIdAsNum
                // } else {
                //     payment.paySlipPositionId = payTypeIndex
                // }
                paytypes.push(payment);
            });
            return paytypes;
        };

        function payTypesPositionOnPayrunExport() {
            let paytypes =  [];
            let payTypesPositionOnPayrunExport = Template.instance().payTypesPositionOnPayrunExport.get()

            payTypesPositionOnPayrunExport.forEach((x, payTypeIndex) => {
                let payment = {};
                payment.paytype = x._id;
                payment.value = x.value;
                payment.displayInPayslip = x.displayInPayslip;

                payment.paySlipPositionId = payTypeIndex

                paytypes.push(payment);
            });
            return paytypes;
        };

        const applyPayGradePaytypesToEmployees = $('#applyPayGradePaytypesToEmployees').is(":checked");

        if(tmpl.data){//edit action for updating tax
            const pygId = tmpl.data._id;
            const code = tmpl.data.code;
            Meteor.call("paygrade/update", pygId, details, applyPayGradePaytypesToEmployees, (err, res) => {
                l.stop();
                if(err){
                    swal("Update Failed", `Cannot Update Pay Grade ${code}`, "error");
                } else {
                    swal("Success!", `Successfully updated Pay Grade ${code}`, "success");
                    Modal.hide("PaygradeCreate");
                }
            });
        } else {
            Meteor.call('paygrade/create', details, (err, res) => {
                l.stop();
                if (res){
                    Modal.hide('PaygradeCreate');
                    swal({
                        title: "Success",
                        text: `Pay Grade Created`,
                        confirmButtonClass: "btn-success",
                        type: "success",
                        confirmButtonText: "OK"
                    });
                } else {
                    err = JSON.parse(err.details);
                    // add necessary handler on error
                    //use details from schema.key to locate html tag and error handler
                    _.each(err, (obj) => {
                        $('[name=' + obj.name +']').addClass('errorValidation');
                        $('[name=' + obj.name +']').attr("placeholder", obj.name + ' ' + obj.type);

                    })
                    swal("error", "Please check all components are entered", "error");
                }
            });
        }
    },
    'click .payment': (e, tmpl) => {
        let selected = $(e.target).is(":checked");
        let assigned = tmpl.dict.get("assigned");
        let id = $(e.target).attr('id');
        if(selected){
            //add to assigned components
            let selectedPay = PayTypes.find({_id: id}).fetch()[0];
            assigned.push(selectedPay);
            //assigned.sort();
        } else {
            let index = _.findIndex(assigned, {_id: id});
            assigned.splice(index, 1);
        }
        assigned = _.sortBy(assigned, 'derivative');
        //set the assigned dict;
        tmpl.dict.set("assigned", assigned);
    },
    'click .payslip': (e, tmpl) => {
        let selected = $(e.target).is(":checked");
        let payTypesPositionOnPayrunExport = Template.instance().payTypesPositionOnPayrunExport.get()
        let id = $(e.target).attr('id');

        let index = parseInt(id);
        payTypesPositionOnPayrunExport[index].displayInPayslip = selected;
        Template.instance().payTypesPositionOnPayrunExport.set(payTypesPositionOnPayrunExport)
    },
    'blur .calc': (e, tmpl) => {
        let index = $(e.target).closest('tr')[0].rowIndex;
        //set value of assigned index and recalculate computation
        let assigned = tmpl.dict.get('assigned');
        assigned[index-1].value = $(e.target).val().toUpperCase();
        tmpl.dict.set('assigned', assigned);
    },
    'keypress input': (e, tmpl) => {
        if (e.keyCode == 13) {
            $(e.target).blur();
        }
    }
});

/*****************************************************************************/
/* PaygradeCreate: Helpers */
/*****************************************************************************/
Template.PaygradeCreate.helpers({
    'selected': (context,val) => {
        let self = this;
        if(Template.instance().data){
            //get value of the option element
            //check and return selected if the template instce of data.context == self._id matches
            if(val){
                return Template.instance().data[context] === val ? selected="selected" : '';
            }
            return Template.instance().data[context] === self._id ? selected="selected" : '';
        }
    },
    'pensions': () => {
        return Pensions.find({}).fetch();
    },
    'taxrules': () => {
        return Tax.find({}).fetch();
    },
    "paytype": (type) => {
        return PayTypes.find({type: type}).fetch();
    },
    'assigned': () => {
        return Template.instance().dict.get('assigned');
    },
    'payTypesWithPositionOnPayrunExport': () => {
        return Template.instance().payTypesPositionOnPayrunExport.get()
    },
    'fixed': (derivative) => {
        return derivative == "Fixed";
    },
    'positions': () => {
        return EntityObjects.find();
    },
    'paygroup': () => {
        return PayGroups.find();
    },
    selectedObj: function (x) {
        let self = this;
        let selected;
        let prop = Template.instance().data[x];
        selected = _.find(prop, function(r) {
            return r ===  self._id;
        });
        if (selected){
            return "selected"
        }
    },
    selectedNetPayAlternateCurrency: function(currency) {
        if(Template.instance().data) {
            if(Template.instance().data.netPayAlternativeCurrency) {
                if(currency === Template.instance().data.netPayAlternativeCurrency) {
                    return "selected"
                }
            }
        }
    },
    'checked': (id) => {
        if(Template.instance().data){
           let index =  _.findLastIndex(Template.instance().data.payTypes, {paytype: id});
            return index !== -1? true:false;
        }

        return false;
    },
    'displayInSlip': (id) => {
        let payTypesPositionOnPayrunExport = Template.instance().payTypesPositionOnPayrunExport.get()

        if(payTypesPositionOnPayrunExport){
           let index =  _.findLastIndex(payTypesPositionOnPayrunExport, {paytype: id});
            if(index !== -1)
                return payTypesPositionOnPayrunExport[index].displayInPayslip;
        }
    },
    'action': () => {
        data = Template.instance().data;
        if(data){
            return `PAYGRADE - ${data.code} (${data.description})`
        } else {
            return 'New Pay Grade'
        }
    },
    'isInUpdateMode': () => {
        return Template.instance().data
    },
    'allCurrencies': () => {
        return [""].concat(Core.currencies());
    }
});

/*****************************************************************************/
/* PaygradeCreate: Lifecycle Hooks */
/*****************************************************************************/
Template.PaygradeCreate.onCreated(function () {
    let self = this;
    let context = Session.get('context');
    self.dict = new ReactiveDict();
    self.payTypesPositionOnPayrunExport = new ReactiveVar()
    self.payTypesPositionOnPayrunExport.set([])

    self.subscribe("PayTypes", context);
    self.subscribe("taxes", context);
    self.subscribe("pensions", context);
    self.subscribe("getPositions", context);
    self.subscribe("payGroups", context);
    self.subscribe("getbuconstants", context);
    self.subscribe("paygrades", context);

    let selectedPayGradeIdForEdit = Session.get('selectedPayGradeForEdit')
    self.currentPayGrade = new ReactiveVar()

    if(self.data) {
        //populate and map paytypes
        self.autorun(function(){
            if (Template.instance().subscriptionsReady()){
                let assignedPaytypesTemp = []
                self.data.payTypes.forEach(x=>{
                    if(Object.keys(x).length > 0) {
                        //extend all assigned paytypes with reference doc. properties
                        let ptype = PayTypes.findOne({_id: x.paytype, 'status': 'Active'});
                        if(ptype) {
                            delete ptype.paytype;
                            _.extend(x, ptype);
                            // return x;
                            assignedPaytypesTemp.push(x)
                        }
                    }
                });
                self.dict.set("assigned", assignedPaytypesTemp); //set assigned to be data
                // console.log(self.data.payTypes);
                //--
                if(selectedPayGradeIdForEdit) {
                    let currentPayGrade = PayGrades.findOne(selectedPayGradeIdForEdit)
                    self.currentPayGrade.set(currentPayGrade);

                    if(currentPayGrade) {
                        if(currentPayGrade.payTypePositionIds && currentPayGrade.payTypePositionIds.length > 0) {
                            currentPayGrade.payTypePositionIds.forEach(x=>{
                                let ptype = PayTypes.findOne({_id: x.paytype, 'status': 'Active'});
                                if(ptype) {
                                    delete ptype.paytype;
                                    _.extend(x, ptype);
                                }
                            });
                            self.data.payTypes.forEach(x => {
                                let foundPayTypeInPaygradePaytypePositions = _.find(currentPayGrade.payTypePositionIds, y => {
                                    return y._id === x._id
                                })
                                if(!foundPayTypeInPaygradePaytypePositions && Object.keys(x).length > 0) {
                                    let newX = {...x}
                                    newX.displayInPayslip = true
                                    newX.paySlipPositionId = currentPayGrade.payTypePositionIds.length

                                    currentPayGrade.payTypePositionIds.push(newX)
                                }
                            });
                            self.payTypesPositionOnPayrunExport.set(currentPayGrade.payTypePositionIds)
                        } else {
                            self.payTypesPositionOnPayrunExport.set(self.data.payTypes)
                        }
                    }
                }
            }
        });
    } else {
        self.dict.set("assigned", []);
    }
    let rules = new ruleJS('calc');
    rules.init();

    self.autorun(function(){
        //rerun computation if assigned value changes
        let assigned = self.dict.get('assigned');
        let input = $('input[type=text]');
        if(assigned){
            assigned.forEach((x,index) => {
                let formula = x.value;
                if(formula){
                    //replace all wagetypes with values
                    for (var i = 0; i < index; i++) {
                        const code = assigned[i].code? assigned[i].code.toUpperCase():assigned[i].code;
                        const regex = getPayRegex(code);
                        formula = formula.replace(regex, assigned[i].parsedValue);
                    }
                    //do the same for all contansts and replace the values
                    //will find a better way of doing this... NOTE
                    let k = Constants.find().fetch();
                    k.forEach(c => {
                        const code = c.code? c.code.toUpperCase():c.code;
                        const regex = getPayRegex(code);
                        formula = formula.replace(regex, c.value);
                    });
                    var parsed = rules.parse(formula, input);
                    if (parsed.result !== null) {
                        x.parsedValue = parsed.result.toFixed(2);  //defaulting to 2 dp ... Make configurable;
                        x.monthly = (parsed.result / 12).toFixed(2);
                    }
                    //
                    if (parsed.error) {
                        x.parsedValue = parsed.error;
                        x.monthly = ""
                    }
                } else {
                    x.parsedValue = "";
                    x.monthly = "";
                }
            });
            self.dict.set('assigned', assigned);
        }
    });
});

Template.PaygradeCreate.onRendered(function () {
    var self = this;
    var oldIndex, newIndex;

    if(Template.instance().data) {
        const payGrade = Template.instance().data

        if(!payGrade) {
            $('#enablePensionPayments').prop('checked', true);
        } else {
            if(payGrade.enablePensionPayments) {
                $('#enablePensionPayments').prop('checked', true);
            } else {
                $('#enablePensionPayments').prop('checked', false);
            }
        }
    }

    // fix a little rendering bug by clicking on step 1
    $('#step1').click();

    $('#progress-wizard-new').bootstrapWizard({
        onTabShow: function (tab, navigation, index) {
            tab.prevAll().addClass('done');
            tab.nextAll().removeClass('done');
            tab.removeClass('done');

            var $total = navigation.find('li').length;
            var $current = index + 1;

            if ($current >= $total) {
                $('#progress-wizard-new').find('.wizard .next').addClass('hide');
                $('#progress-wizard-new').find('.wizard .finish').removeClass('hide');
            } else {
                $('#progress-wizard-new').find('.wizard .next').removeClass('hide');
                $('#progress-wizard-new').find('.wizard .finish').addClass('hide');
            }

            var $percent = ($current / $total) * 100;
            $('#progress-wizard-new').find('.progress-bar').css('width', $percent + '%');
        },
        onTabClick: function (tab, navigation, index) {
            return true;
        }
    });
    //initialize rule table
    $('#derivativeTable').sortable({
        containerSelector: 'table',
        itemPath: '> tbody',
        itemSelector: 'tr',
        placeholder: '
',
        onDragStart: function ($item, container, _super) {
            oldIndex = $item.index();
            //$item.appendTo($item.parent());
            _super($item, container);
        },
        onDrop: function($item, container, _super) {
            newIndex = $item.index() ;//.attr('id'));
            //get assigned
            let assigned = self.dict.get('assigned');
            assigned.move(oldIndex, newIndex);
            self.dict.set('assigned', assigned);
            //--
            _super($item, container);
        }
    });

    //--Make paytypes in payslip sortable
    $('#paySlipPaytypes').sortable({
        containerSelector: 'table',
        itemPath: '> tbody',
        itemSelector: 'tr',
        placeholder: '
',
        onDragStart: function ($item, container, _super) {
            oldIndex = $item.index();
            //$item.appendTo($item.parent());
            _super($item, container);
        },
        onDrop: function($item, container, _super) {
            newIndex = $item.index() ;
            //--
            let payTypesPositionOnPayrunExport = self.payTypesPositionOnPayrunExport.get()
            let aPaytype = payTypesPositionOnPayrunExport[oldIndex]
            aPaytype.paySlipPositionIndex = newIndex
            payTypesPositionOnPayrunExport.move(oldIndex, newIndex);

            self.payTypesPositionOnPayrunExport.set(payTypesPositionOnPayrunExport)
            //--
            _super($item, container);
        }
    });

    $('select.dropdown').dropdown();
});

Template.PaygradeCreate.onDestroyed(function () {

});
Array.prototype.move = function (old_index, new_index) {
    while (old_index < 0) {
        old_index += this.length;
    }
    while (new_index < 0) {
        new_index += this.length;
    }
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this; // for testing purposes
};


text:
import './setup';
import './compile';

import gulp from 'gulp';

gulp.task('default', false, ['help']);


text:
package ar.edu.itba.paw.webapp.controllers.api;

import ar.edu.itba.paw.models.Patient;
import ar.edu.itba.paw.services.PatientService;
import ar.edu.itba.paw.webapp.dto.PatientDTO;
import ar.edu.itba.paw.webapp.params.PatientParams;
import ar.edu.itba.paw.webapp.utils.Pair;
import ar.edu.itba.paw.webapp.validators.PasswordValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import java.util.List;

/**
 * Created by agophurmuz on 7/19/16.
 */

@Path("api/v1/patients")
@Component
public class PatientsController extends ApiController {

  /*  private static final String USER_ALREADY_EXISTS = "El usuario ya existe";

    @Autowired
    private PatientService patientService;

    @POST
    public Response create(final PatientParams params) {
        final Patient existingPatient = patientService.findByEmail(params.email);

        if (existingPatient != null) {
            return badRequest(USER_ALREADY_EXISTS);
        } else {
            final Pair<Boolean, String> validation = PasswordValidator.validate(params.password, params.passwordConfirmation);

            if (!validation.getLeft()) {
                return badRequest(validation.getRight());
            }

            final Patient patient = patientService.create(params.firstName, params.lastName, params.email, params.password);

            if (patient.getId() == null) {
                return badRequest("Patient was not created");
            }

            return created(patient);
        }
    }

    @GET
    public Response index() {
        final List<Patient> allPatients = patientService.getAll();
        final GenericEntity<List<PatientDTO>> list = new GenericEntity<List<PatientDTO>>(PatientDTO.fromList(allPatients)) {
        };
        return ok(list);
    }

    @GET
    @Path("/{id}")
    public Response show(@PathParam("id") final Integer id) {
        final Patient patient = patientService.get(id);

        if (patient != null) {
            return ok(new PatientDTO(patient));
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }*/
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 20: 23 (1968)

#### Original name
Sphacelotheca chrysopogonis-grylli Thirum. & Pavgi

### Remarks
null


text:
class rrbroker {
private:
    typedef std::vector<boost::asio::zmq::frame> message_t;
    typedef std::shared_ptr<message_t> message_ptr;
    typedef std::shared_ptr<boost::asio::zmq::socket> socket_ptr;

    boost::asio::zmq::socket frontend_;
    boost::asio::zmq::socket backend_;
    message_t buffer_;

public:
    rrbroker(boost::asio::io_service& ios, boost::asio::zmq::context& ctx)
        : frontend_(ios, ctx, ZMQ_ROUTER), backend_(ios, ctx, ZMQ_DEALER), buffer_()
    {
        frontend_.bind("tcp://*:5559");
        backend_.bind("tcp://*:5560");

        frontend_.async_read_message(std::back_inserter(buffer_),
                                     std::bind(&rrbroker::handle_recv, this, std::placeholders::_1,
                                               std::ref(frontend_), std::ref(backend_)));

        backend_.async_read_message(std::back_inserter(buffer_),
                                    std::bind(&rrbroker::handle_recv, this, std::placeholders::_1,
                                              std::ref(backend_), std::ref(frontend_)));
    }

    void handle_recv(boost::system::error_code const& ec, boost::asio::zmq::socket& receiver,
                     boost::asio::zmq::socket& forwarder)
    {
        message_ptr tmp{new message_t};
        std::swap(*tmp, buffer_);
        forwarder.async_write_message(
            tmp->begin(), tmp->end(),
            std::bind(&rrbroker::null_handler, this, std::placeholders::_1, tmp));
        receiver.async_read_message(std::back_inserter(buffer_),
                                    std::bind(&rrbroker::handle_recv, this, std::placeholders::_1,
                                              std::ref(receiver), std::ref(forwarder)));
    }

    void null_handler(boost::system::error_code const& ec, message_ptr dummy) {}
};

int main(int argc, char* argv[])
{
    //  Prepare our context and sockets
    boost::asio::io_service ios;
    boost::asio::zmq::context ctx;
    rrbroker broker(ios, ctx);

    ios.run();

    return 0;
}


text:
<?php

namespace Gedmo\Translator;

use Doctrine\Common\Collections\Collection;

/**
 * Proxy class for Entity/Document translations.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
class TranslationProxy
{
    /**
     * @var string
     */
    protected $locale;
    /**
     * @var object
     */
    protected $translatable;
    /**
     * @var string[]
     */
    protected $properties = [];
    /**
     * @var string
     *
     * @phpstan-var class-string<TranslationInterface>
     */
    protected $class;
    /**
     * @var Collection<int, TranslationInterface>
     */
    protected $coll;

    /**
     * Initializes translations collection
     *
     * @param object $translatable object to translate
     * @param string $locale       translation name
     * @param array  $properties   object properties to translate
     * @param string $class        translation entity|document class
     *
     * @throws \InvalidArgumentException Translation class doesn't implement TranslationInterface
     *
     * @phpstan-param class-string<TranslationInterface> $class
     * @phpstan-param Collection<int, TranslationInterface> $coll
     */
    public function __construct($translatable, $locale, array $properties, $class, Collection $coll)
    {
        $this->translatable = $translatable;
        $this->locale = $locale;
        $this->properties = $properties;
        $this->class = $class;
        $this->coll = $coll;

        if (!is_subclass_of($class, TranslationInterface::class)) {
            throw new \InvalidArgumentException(sprintf('Translation class should implement %s, "%s" given', TranslationInterface::class, $class));
        }
    }

    /**
     * @param string $method
     * @param array  $arguments
     *
     * @return mixed
     */
    public function __call($method, $arguments)
    {
        $matches = [];
        if (preg_match('/^(set|get)(.*)$/', $method, $matches)) {
            $property = lcfirst($matches[2]);

            if (in_array($property, $this->properties, true)) {
                switch ($matches[1]) {
                    case 'get':
                        return $this->getTranslatedValue($property);
                    case 'set':
                        if (isset($arguments[0])) {
                            $this->setTranslatedValue($property, $arguments[0]);

                            return $this;
                        }
                }
            }
        }

        $return = call_user_func_array([$this->translatable, $method], $arguments);

        if ($this->translatable === $return) {
            return $this;
        }

        return $return;
    }

    /**
     * @param string $property
     *
     * @return mixed
     */
    public function __get($property)
    {
        if (in_array($property, $this->properties, true)) {
            if (method_exists($this, $getter = 'get'.ucfirst($property))) {
                return $this->$getter;
            }

            return $this->getTranslatedValue($property);
        }

        return $this->translatable->$property;
    }

    /**
     * @param string $property
     * @param mixed  $value
     *
     * @return self
     */
    public function __set($property, $value)
    {
        if (in_array($property, $this->properties, true)) {
            if (method_exists($this, $setter = 'set'.ucfirst($property))) {
                return $this->$setter($value);
            }

            $this->setTranslatedValue($property, $value);

            return $this;
        }

        $this->translatable->$property = $value;

        return $this;
    }

    /**
     * @param string $property
     *
     * @return bool
     */
    public function __isset($property)
    {
        return in_array($property, $this->properties, true);
    }

    /**
     * Returns locale name for the current translation proxy instance.
     *
     * @return string
     */
    public function getProxyLocale()
    {
        return $this->locale;
    }

    /**
     * Returns translated value for specific property.
     *
     * @param string $property property name
     *
     * @return mixed
     */
    public function getTranslatedValue($property)
    {
        return $this
            ->findOrCreateTranslationForProperty($property, $this->getProxyLocale())
            ->getValue();
    }

    /**
     * Sets translated value for specific property.
     *
     * @param string $property property name
     * @param string $value    value
     *
     * @return void
     */
    public function setTranslatedValue($property, $value)
    {
        $this
            ->findOrCreateTranslationForProperty($property, $this->getProxyLocale())
            ->setValue($value);
    }

    /**
     * Finds existing or creates new translation for specified property
     */
    private function findOrCreateTranslationForProperty(string $property, string $locale): TranslationInterface
    {
        foreach ($this->coll as $translation) {
            if ($locale === $translation->getLocale() && $property === $translation->getProperty()) {
                return $translation;
            }
        }

        /** @var TranslationInterface $translation */
        $translation = new $this->class();
        $translation->setTranslatable($this->translatable);
        $translation->setProperty($property);
        $translation->setLocale($locale);
        $this->coll->add($translation);

        return $translation;
    }
}