text:
package com.navercorp.pinpoint.profiler.instrument;

import com.navercorp.pinpoint.bootstrap.instrument.InstrumentContext;
import com.navercorp.pinpoint.bootstrap.interceptor.Interceptor;
import com.navercorp.pinpoint.bootstrap.interceptor.annotation.Scope;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.ExecutionPolicy;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;

/**
 * @author Woonduk Kang(emeroad)
 */
public class ScopeFactory {

    public ScopeFactory() {
    }

    public ScopeInfo newScopeInfo(ClassLoader classLoader, InstrumentContext pluginContext, String interceptorClassName, InterceptorScope scope, ExecutionPolicy policy) {

        if (scope == null) {
            final Class<? extends Interceptor> interceptorClass = pluginContext.injectClass(classLoader, interceptorClassName);
            final Scope scopeAnnotation = interceptorClass.getAnnotation(Scope.class);
            if (scopeAnnotation != null) {
                return newScopeInfoByAnnotation(pluginContext, scopeAnnotation);
            }
        }
        policy = getExecutionPolicy(scope, policy);

        return new ScopeInfo(scope, policy);
    }

    private ScopeInfo newScopeInfoByAnnotation(InstrumentContext pluginContext, Scope scope) {
        final String scopeName = scope.value();
        final InterceptorScope interceptorScope = pluginContext.getInterceptorScope(scopeName);

        final ExecutionPolicy policy = scope.executionPolicy();
        return new ScopeInfo(interceptorScope, policy);
    }

    private ExecutionPolicy getExecutionPolicy(InterceptorScope scope, ExecutionPolicy policy) {
        if (scope == null) {
            policy = null;
        } else if (policy == null) {
            policy = ExecutionPolicy.BOUNDARY;
        }
        return policy;
    }

}


text:
<?php
/** Chinese (Malaysia) (中文(马来西亚))
 *
 * See MessagesQqq.php for message documentation incl. usage of parameters
 * To improve a translation please visit http://translatewiki.net
 *
 * @ingroup Language
 * @file
 *
 */

# Inherit everything for now
$fallback = 'zh-sg, zh-hans';

redpajama_set_name: RedPajamaGithub


text:
void clear(Window* w) {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
}

void swapBuffers(Window* w) {
    SDL_GL_SwapWindow(w->window);
}

void drawRect(
        Window* window,
        float* mvp,
        float* color) {
    glUniformMatrix3fv(window->shaderMvp, 1, GL_FALSE, mvp);
    glUniform1i(window->shaderMode, 0);
    glUniform4fv(window->shaderColor, 1, color);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);
}

void drawTexture(
        Window* window,
        float* mvp,
        Texture* t) {
    glUniformMatrix3fv(window->shaderMvp, 1, GL_FALSE, mvp);
    glUniform1i(window->shaderMode, 1);
    glBindTexture(GL_TEXTURE_2D, t->id);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);
}

int textureWidth(Texture* t) {
    return t->width;
}

int textureHeight(Texture* t) {
    return t->height;
}

void deleteTexture(Texture* t) {
    glDeleteTextures(1, &t->id);
    free(t);
}

Texture* surfaceToTexture(SDL_Surface* surface) {
    Texture* t = malloc(sizeof(Texture));

    glGenTextures(1, &(t->id));
    glBindTexture(GL_TEXTURE_2D, t->id);

    GLenum mode = GL_RGB;

    if(surface->format->BytesPerPixel == 4) {
        mode = GL_RGBA;
    }

    glTexImage2D(
            GL_TEXTURE_2D,
            0, mode,
            surface->w, surface->h,
            0, mode, GL_UNSIGNED_BYTE,
            surface->pixels);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    SDL_FreeSurface(surface);

    t->width = surface->w;
    t->height = surface->h;

    return t;
}


text:
module AWS
  class S3

    # Represents a collection of S3 objects.
    #
    # ## Getting an S3Object by Key
    #
    # If you know the key of the object you want, you can reference it this way:
    #
    #     # this will not make any requests against S3
    #     object = bucket.objects['foo.jpg']
    #     object.key #=> 'foo.jpg'
    #
    # ## Finding objects with a Prefix
    #
    # Given a bucket with the following keys:
    #
    #     photos/sunset.jpg
    #     photos/sunrise.jpg
    #     photos/winter.jpg
    #     videos/comedy.mpg
    #     videos/dancing.mpg
    #
    # You can list objects that share a prefix:
    #
    #     bucket.objects.with_prefix('videos').collect(&:key)
    #     #=> ['videos/comedy.mpg', 'videos/dancing.mpg']
    #
    # ## Exploring Objects with a Tree Interface
    #
    # Given a bucket with the following keys:
    #
    #     README.txt
    #     videos/wedding.mpg
    #     videos/family_reunion.mpg
    #     photos/2010/house.jpg
    #     photos/2011/fall/leaves.jpg
    #     photos/2011/summer/vacation.jpg
    #     photos/2011/summer/family.jpg
    #
    #     tree = bucket.objects.with_prefix('photos').as_tree
    #
    #     directories = tree.children.select(&:branch?).collect(&:prefix)
    #     #=> ['photos/2010', 'photos/2011']
    #
    class ObjectCollection

      include Core::Model
      include Enumerable
      include PrefixAndDelimiterCollection

      # @param [Bucket] bucket The S3 bucket this object collection belongs to.
      # @param [Hash] options
      def initialize(bucket, options = {})
        @bucket = bucket
        super
      end

      # @return [Bucket] The bucket this collection belongs to.
      attr_reader :bucket

      # Writes a new object to S3.
      #
      # The first param is the key you want to write this object to.
      # All other params/options are documented in {S3Object#write}.
      #
      # @see S3Object#write
      #
      # @param [String] key Where in S3 to write the object.
      # @return (see S3Object#write)
      def create key, *args, &block
        self[key].write(*args, &block)
      end

      # Returns an S3Object given its name.  For example:
      #
      # @example
      #
      #   object = bucket.objects['file.txt']
      #   object.class #=> S3Object
      #
      # @param [String] key The object key.
      # @return [S3Object]
      def [] key
        S3Object.new(bucket, key.to_s)
      end

      # (see PrefixedCollection#with_prefix)
      def with_prefix prefix, mode = :replace
        super(prefix, mode)
      end

      # Deletes the objects provided in as few requests as possible.
      #
      #     # delete 2 objects (by key) in a single request
      #     bucket.objects.delete('abc', 'xyz')
      #
      # You can delete objects also by passing their S3Object representation:
      #
      #     to_delete = []
      #     to_delete << buckets.objects['foo']
      #     to_delete << buckets.objects['bar']
      #
      #     bucket.objects.delete(to_delete)
      #
      # @overload delete(objects)
      #   @param [Mixed] objects One or more objects to delete.  Each object
      #     can be one of the following:
      #
      #       * An object key (string)
      #       * A hash with :key and :version_id (for versioned objects)
      #       * An {S3Object} instance
      #       * An {ObjectVersion} instance
      #
      # @overload delete(objects, options)
      #   Deletes multiple objects, with additional options. The array can
      #   contain any of the types of objects the first method invocation style
      #   accepts.
      #   @param [Array] objects One or more objects to delete.
      #   @param [Hash] options Optional headers to pass on.
      #
      # @raise [BatchDeleteError] If any of the objects failed to delete,
      #   a BatchDeleteError will be raised with a summary of the errors.
      #
      # @return [nil]
      #
      def delete *objects

        # Detect and retrieve options from the end of the splat.
        if
          objects.size == 2 and
          objects[0].is_a?(Array) and
          objects[1].is_a?(Hash)
        then
          client_opts = objects.pop
        else
          client_opts = {}
        end

        objects = objects.flatten.collect do |obj|
          case obj
          when String        then { :key => obj }
          when Hash          then obj
          when S3Object      then { :key => obj.key }
          when ObjectVersion then { :key => obj.key, :version_id => obj.version_id }
          else
            msg = "objects must be keys (strings or hashes with :key and " +
                  ":version_id), S3Objects or ObjectVersions, got " +
                  obj.class.name
            raise ArgumentError, msg
          end
        end

        batch_helper = BatchHelper.new(1000) do |batch|
          client_opts[:bucket_name] = bucket.name
          client_opts[:quiet] = true
          client_opts[:objects] = batch
          client.delete_objects(client_opts)
        end

        error_counts = {}
        batch_helper.after_batch do |response|
          response.errors.each do |error|
            error_counts[error.code] ||= 0
            error_counts[error.code] += 1
          end
        end

        objects.each do |object|
          batch_helper.add(object)
        end

        batch_helper.complete!

        raise Errors::BatchDeleteError.new(error_counts) unless
          error_counts.empty?

        nil

      end

      # Deletes each object in the collection that returns a true value
      # from block passed to this method.  Deletes are batched for efficiency.
      #
      #     # delete text files in the 2009 "folder"
      #     bucket.objects.with_prefix('2009/').delete_if {|o| o.key =~ /\.txt$/ }
      #
      # @yieldparam [S3Object] object
      #
      # @raise [BatchDeleteError] If any of the objects failed to delete,
      #   a BatchDeleteError will be raised with a summary of the errors.
      #
      def delete_if &block

        error_counts = {}

        batch_helper = BatchHelper.new(1000) do |objects|
          begin
            delete(objects)
          rescue Errors::BatchDeleteError => error
            error.error_counts.each_pair do |code,count|
              error_counts[code] ||= 0
              error_counts[code] += count
            end
          end
        end

        each do |object|
          batch_helper.add(object) if yield(object)
        end

        batch_helper.complete!

        raise Errors::BatchDeleteError.new(error_counts) unless
          error_counts.empty?

        nil

      end

      # Deletes all objects represented by this collection.
      #
      # @example Delete all objects from a bucket
      #
      #   bucket.objects.delete_all
      #
      # @example Delete objects with a given prefix
      #
      #   bucket.objects.with_prefix('2009/').delete_all
      #
      # @raise [BatchDeleteError] If any of the objects failed to delete,
      #   a BatchDeleteError will be raised with a summary of the errors.
      #
      # @return [Array] Returns an array of results
      #
      def delete_all

        error_counts = {}

        each_batch do |objects|
          begin
            delete(objects)
          rescue Errors::BatchDeleteError => error
            error.error_counts.each_pair do |code,count|
              error_counts[code] ||= 0
              error_counts[code] += count
            end
          end
        end

        raise Errors::BatchDeleteError.new(error_counts) unless
          error_counts.empty?

        nil

      end

      # Iterates the collection, yielding instances of S3Object.
      #
      # Use break or raise an exception to terminate the enumeration.
      #
      # @param [Hash] options
      # @option options [Integer] :limit (nil) The maximum number of
      #   objects to yield.
      # @option options [Integer] :batch_size (1000) The number of objects to
      #   fetch each request to S3.  Maximum is 1000 keys at time.
      # @return [nil]
      def each options = {}, &block
        super
      end

      private

      def each_member_in_page(page, &block)
        super
        page.contents.each do |content|
          content_length = content[:size].to_i if content[:size]
          etag = content[:etag]
          last_modified = content[:last_modified]
          yield(S3Object.new(bucket, content.key, { :content_length => content_length, :etag => etag, :last_modified => last_modified}))
        end
      end

      def list_request options
        client.list_objects(options)
      end

      def limit_param
        :max_keys
      end

      def next_markers page
        if page[:next_marker]
          marker = page[:next_marker]
        elsif page[:contents].size > 0
          marker = page[:contents].last[:key]
        else
          raise 'Unable to find marker in S3 list objects response'
        end

        { :marker => marker }
      end

      # processes items in batches of 1k items
      # @api private
      class BatchHelper

        def initialize batch_size, &block
          @batch_size = batch_size
          @block = block
          @batch = []
        end

        def after_batch &block
          @after_batch = block
        end

        def add item
          @batch << item
          if @batch.size == @batch_size
            process_batch
            @batch = []
          end
          item
        end

        def complete!
          process_batch unless @batch.empty?
        end

        private

        def process_batch
          response = @block.call(@batch)
          @after_batch.call(response) if @after_batch
        end

      end

    end

  end
end


text:
import java.util.Arrays;

public class TwoValues
{
	public static boolean solve(int[] arr, int sum)
	{
		if(arr == null || arr.length == 0)
		{
			return false;
		}

		int head = 0;
		int tail = arr.length - 1;

		while(head < tail)
		{
			int val = arr[head] + arr[tail];

			if(val == sum)
			{
				return true;
			}

			if(val < sum)
			{
				head++;
			}

			if(val > sum)
			{
				tail--;
			}
		}

		return false;
	}

	public static void main(String[] args)
	{
		if(args.length < 3)
		{
			System.out.println("usage: java TwoValues s 1 2 3 .. n");
			System.out.println("Where s is a sum to check for and 1 .. n are a series of integers");
			return;
		}

		int sum = Integer.parseInt(args[0]);
		int[] values = new int[args.length - 1];

		for(int i = 1; i < args.length; i++)
		{
			values[i - 1] = Integer.parseInt(args[i]);
		}

		Arrays.sort(values);
		boolean sumExistsInArray = solve(values, sum);
		System.out.println(sum + " exists in array: " + sumExistsInArray);
	}
}


text:
namespace sw { namespace universal {

// the current shims are NON-COMPLIANT with the posit standard, which says that every function must be
// correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.

// Base-e exponential function
template<unsigned nbits, unsigned es>
posit<nbits,es> exp(posit<nbits,es> x) {
	if (isnar(x)) return x;
	posit<nbits, es> p;
	double d = std::exp(double(x));
	if (d == 0.0) {
		p.minpos();
	}
	else {
		p = d;
	}
	return p;
}

// Base-2 exponential function
template<unsigned nbits, unsigned es>
posit<nbits,es> exp2(posit<nbits,es> x) {
	if (isnar(x)) return x;
	posit<nbits, es> p;
	double d = std::exp2(double(x));
	if (d == 0.0) {
		p.minpos();
	}
	else {
		p = d;
	}
	return p;
}

// Base-10 exponential function
template<unsigned nbits, unsigned es>
posit<nbits, es> exp10(posit<nbits, es> x) {
	return posit<nbits, es>(std::pow(10.0, double(x)));
}

// Base-e exponential function exp(x)-1
template<unsigned nbits, unsigned es>
posit<nbits,es> expm1(posit<nbits,es> x) {
	return posit<nbits,es>(std::expm1(double(x)));
}

}} // namespace sw::universal


text:
/**
 *  irpipe - lirc test device.
 *
 * This is mostly an implementation of a traditional kernel fifo
 * device. Ihe purpose is to provide the same interface as the
 * kernel LIRC drivers.
 *
 * The driver creates some (default 2) devices which can be read and
 * written as a regular fifos. The udev rule can be used to let udev
 * set up the devices /dev/irpipe[0-9].
 *
 * The differences to a regular kernel fifo:
 *
 *    - A subset of the LIRC ioctl commands are supported, see
 *      irpipe_ioctl().
 *    - If the readers goes away during write(2) this fifo blocks
 *      until a reader is back instead of generating a EPIPE error.
 *    - Some extra ioctl commands for testing are in irpipe.h
 *    - No asynchronous mechanisms.
 *    - The select()/poll() support is only implemented on the
 *      reading side. Writing will always block.
 *    - The device does not report itself as a fifo when using
 *      stat().
 *    - Read buffer needs to be at least 2048 bytes (why?)
 *
 * The LIRC attributes reflected by the related ioctls are reset when
 * the device is opened for write.
 *
 * Parameters include nr of devices, buffer size and debug logging. See
 * the 'modinfo irpipe.ko' output.
 *
 * See:
 *    -  http://lwn.net/Kernel/LDD3
 *    -  fifo(7)
 */

#include <asm/ioctls.h>
#include <asm/current.h>
#include <asm-generic/ioctl.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/fcntl.h>
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/uaccess.h>

#include <media/lirc.h>

#include "irpipe.h"

/** Name of device created under /sys/class. */
#define DEVICENAME      "irpipe"

/** Default nr of created minor devices, the first being 0. */
#define NR_OF_DEVICES   2

/** Default main buffer size. */
#define DEFAULT_BUFSIZE 8196

#define MIN(a, b)       ((a) < (b) ? (a) : (b))
#define MAX(a, b)       ((a) > (b) ? (a) : (b))

#define IR_WARN(fmt, args ...) \
	pr_warn("irpipe (%d): " fmt "\n", current->pid, ## args)

#define IR_INFO(fmt, args ...) \
	pr_info("irpipe (%d): " fmt "\n", current->pid, ## args)

#define IR_DEBUG(fmt, args ...) \
	{ if (debug) \
		  IR_INFO(fmt, ## args); }

const struct file_operations fops;

/** Persistent data structure for each allocated device. */
struct ir_device {
	spinlock_t		mutex;		  /**< Fifo guard. */
	char*			fifo;		  /**< Main buffer area. */
	unsigned int		tail;		  /**< Next byte to fetch */
	unsigned int		head;		  /**< Next pos to fill */
	atomic_t		size;		  /**< Fifo size */
	wait_queue_head_t	wait_for_reader;
	wait_queue_head_t	wait_for_writer;
	atomic_t		readers;
	atomic_t		writers;
	__u32			features;	  /**< LIRC_GET_FEATURES */
	__u32			rec_mode;	  /**< LIRC_GET_REC_MODE */
	__u32			send_mode;	  /**< LIRC_GET_SEND_MODE */
	__u32			code_length;	  /**< LIRC_GET_LENGTH */
};

/** Size of internal buffer (parameter). */
static int buffsize = DEFAULT_BUFSIZE;

/** Number of allocated devices 0 < nr_of_devices <= 10 (parameter). */
static int nr_of_devices = NR_OF_DEVICES;

/** Enable/disable debug logging (parameter). */
static bool debug = 1;

/** Persistent data for each device. */
static struct ir_device* ir_devices;

static int dev_major;           /**< Allocated major device number. */
static struct cdev* ir_cdev;    /**< Opaq handle to kernel device. */
static struct class* class;     /**< /sys/class struct, set by init */

/** Get available space in fifo (unlocked). */
static inline size_t fifo_get_space(struct ir_device* d)
{
	return buffsize - atomic_read(&d->size) - 1;
}

/** True if there is some available space in fifo (unlocked). */
static bool fifo_have_space(struct ir_device* device)
{
	return fifo_get_space(device) > 0;
}

/** True if there is some data available in fifo (unlocked).*/
static bool fifo_have_data(struct ir_device* device)
{
	return atomic_read(&device->size) > 0;
}

/**
 * Put at most count bytes from src into the fifo, return bytes written.
 * Needs locked mutex
 */
static size_t fifo_put(struct ir_device* d, const char* src, size_t count)
{
	int i;

	count = MIN(count, fifo_get_space(d));
	for (i = 0; i < count; i += 1) {
		d->fifo[d->head] = *src++;
		d->head = (d->head + 1) % buffsize;
	}
	atomic_add(count, &d->size);
	return count;
}

/**
 * Get at most count bytes from fifo into dest buffer, return bytes read.
 * Needs locked mutex.
 */
static size_t fifo_get(struct ir_device* d, char* dest, size_t count)
{
	int i;

	count = MIN(count, atomic_read(&d->size));
	for (i = 0; i < count; i += 1) {
		*dest++ = d->fifo[d->tail];
		d->tail = (d->tail + 1) % buffsize;
	}
	atomic_sub(count, &d->size);
	return count;
}

/** True if opened for write (and not closed) by at least one process.  */
static bool have_writers(struct ir_device* device)
{
	return atomic_read(&device->writers) > 0;
}

/** True if opened for read (and not closed) by at least one process.  */
static bool have_readers(struct ir_device* device)
{
	return atomic_read(&device->readers) > 0;
}

/**
 * File reset when opened for write: flush fifo, reset ioctl data
 * Needs mutex lock (unless on module load).
 */
static void ir_device_reset(struct ir_device* d, int minor)
{
	IR_DEBUG("Resetting device %d", minor);
	atomic_set(&d->size, 0);
	d->head = 0;
	d->tail = 0;
	d->features = LIRC_CAN_REC_MODE2 | LIRC_CAN_SEND_PULSE;
	d->send_mode = LIRC_MODE_PULSE;
	d->rec_mode = LIRC_MODE_MODE2;
	d->code_length = 24;
}

/** Module load time initialization, return boolean success.*/
static bool ir_device_init(struct ir_device* d, int minor)
{
	memset(d, 0, sizeof(struct ir_device));
	d->fifo = kmalloc(buffsize, GFP_KERNEL);
	if (d->fifo == NULL)
		return 0;
	atomic_set(&d->readers, 0);
	atomic_set(&d->writers, 0);
	spin_lock_init(&d->mutex);
	init_waitqueue_head(&d->wait_for_reader);
	init_waitqueue_head(&d->wait_for_writer);
	ir_device_reset(d, minor);
	return 1;
}

/** Dealloc what ir_device_init() created. */
static void ir_device_destroy(struct ir_device* d)
{
	kfree(d->fifo);
}

/** Unless cond(device) is true, invoke schedule() and cleanup. */
static void cond_wait(bool			(*cond)(struct ir_device*),
		      wait_queue_head_t*	queue,
		      struct ir_device*		device)
{
	wait_queue_t my_wait;

	init_wait(&my_wait);
	prepare_to_wait(queue, &my_wait, TASK_INTERRUPTIBLE);
	if (!cond(device))
		schedule();
	finish_wait(queue, &my_wait);
}

/** Do the open() work for devices opened O_RDWR. */
static int open_read_write(struct ir_device* dev, struct file* filp, int minor)
{
	IR_DEBUG("open_read/write, size: %d", atomic_read(&dev->size));
	spin_lock(&dev->mutex);
	ir_device_reset(dev, minor);
	atomic_inc(&dev->writers);
	atomic_inc(&dev->readers);
	spin_unlock(&dev->mutex);
	wake_up_interruptible(&dev->wait_for_reader);
	return 0;
}

/** Do the open() work for devices opened O_WRONLY. */
static int open_write(struct ir_device* dev, struct file* filp, int minor)
{
	IR_DEBUG("open_write, readers: %d, size: %d",
		 atomic_read(&dev->readers),
		 atomic_read(&dev->size));
	atomic_inc(&dev->writers);
	spin_lock(&dev->mutex);
	while (!have_readers(dev)) {
		spin_unlock(&dev->mutex);
		if (filp->f_flags & O_NONBLOCK)
			return -ENXIO;
		cond_wait(have_readers, &dev->wait_for_reader, dev);
		if (signal_pending(current)) {
			IR_DEBUG("signals pending on open - ERESTARTSYS");
			return -ERESTARTSYS;
		}
		spin_lock(&dev->mutex);
	}
	ir_device_reset(dev, minor);
	spin_unlock(&dev->mutex);
	wake_up_interruptible(&dev->wait_for_writer);
	IR_DEBUG("device opened for write");
	return 0;
}

/** Do the open() work for devices opened O_RDONLY. */
static int open_read(struct ir_device* dev, struct file* filp)
{
	IR_DEBUG("open_read, writers: %d", atomic_read(&dev->writers));
	atomic_inc(&dev->readers);
	while (!have_writers(dev)) {
		if (filp->f_flags & O_NONBLOCK)
			return 0;
		cond_wait(have_writers, &dev->wait_for_writer, dev);
		if (signal_pending(current))
			return -ERESTARTSYS;
	}
	wake_up_interruptible(&dev->wait_for_reader);
	IR_DEBUG("device opened for read");
	return 0;
}

/** Kernel side of open(2). */
static int irpipe_open(struct inode* inode, struct file* filp)
{
	const int minor = iminor(inode);

	if (minor > nr_of_devices - 1)
		return -ENODEV;
	filp->private_data = &ir_devices[minor];
	if (filp->f_mode & FMODE_READ && filp->f_mode & FMODE_WRITE)
		return open_read_write(&ir_devices[minor], filp, minor);
	else if (filp->f_mode & FMODE_WRITE)
		return open_write(&ir_devices[minor], filp, minor);
	else if (filp->f_mode & FMODE_READ)
		return open_read(&ir_devices[minor], filp);
	else
		return -EINVAL;
}

/** Kernel side of close(2). */
static int irpipe_close(struct inode* inode, struct file* filp)
{
	const int minor = iminor(inode);
	struct ir_device* const dev = (struct ir_device*)filp->private_data;

	IR_DEBUG("Closing, size: %d", atomic_read(&dev->size));
	if (filp->f_mode & FMODE_WRITE) {
		atomic_dec(&dev->writers);
		wake_up_interruptible(&dev->wait_for_writer);
	}
	if (filp->f_mode & FMODE_READ) {
		atomic_dec(&dev->readers);
		wake_up_interruptible(&dev->wait_for_reader);
	}
	IR_DEBUG("%s/%s device %d closed",
		 filp->f_mode & FMODE_READ ? "read" : "-",
		 filp->f_mode & FMODE_WRITE ? "write" : "-",
		 minor);
	return 0;
}

/** kernel side of userspace read(2). */
static ssize_t
irpipe_read(struct file* filp, char* buff, size_t length, loff_t* ppos)
{
	struct ir_device* const dev = (struct ir_device*)filp->private_data;
	char kbuff[buffsize];
	int bytes;

	spin_lock(&dev->mutex);
	while (!fifo_have_data(dev) || !have_writers(dev)) {
		spin_unlock(&dev->mutex);
		if (atomic_read(&dev->writers) <= 0)
			return 0;
		if (filp->f_flags & O_NONBLOCK)
			return -EAGAIN;
		cond_wait(fifo_have_data, &dev->wait_for_writer, dev);
		if (signal_pending(current)) {
			IR_DEBUG("Signals pending on read- ERESTARTSYS");
			return -ERESTARTSYS;
		}
		spin_lock(&dev->mutex);
	}
	bytes = fifo_get(dev, kbuff, length);
	spin_unlock(&dev->mutex);
	bytes -= copy_to_user(buff, kbuff, bytes);
	wake_up_interruptible(&dev->wait_for_reader);
	return bytes;
}

/** Kernel side of userspace write(2). */
static ssize_t
irpipe_write(struct file* filp, const char* buff, size_t length, loff_t* ppos)
{
	struct ir_device* const dev = (struct ir_device*)filp->private_data;
	char kbuff[buffsize];
	unsigned int written;

	length = MIN(length, buffsize - 1);
	length -= copy_from_user(kbuff, buff, length);
	spin_lock(&dev->mutex);
	while (!fifo_have_space(dev) || !have_readers(dev)) {
		spin_unlock(&dev->mutex);
		if (!have_readers(dev)) {
			IR_DEBUG("No readers on write: blocking.");
			cond_wait(have_readers, &dev->wait_for_reader, dev);
		}
		if (filp->f_flags & O_NONBLOCK)
			return -EAGAIN;
		cond_wait(fifo_have_space, &dev->wait_for_reader, dev);
		if (signal_pending(current)) {
			IR_DEBUG("Write: signals pending on write: ERESTARTSYS.");
			return -ERESTARTSYS;
		}
		spin_lock(&dev->mutex);
	}
	written = fifo_put(dev, kbuff, length);
	spin_unlock(&dev->mutex);

	wake_up_interruptible(&dev->wait_for_writer);
	return written;
}

/** Kernel side of userspace ioctl(2). */
long irpipe_ioctl(struct file* filp, unsigned int cmd, unsigned long arg)
{
	struct ir_device* const dev = (struct ir_device*)filp->private_data;
	void __user *argp = (void __user *)arg;
	long r = 0;

	IR_DEBUG("Running ioctl cmd %u (0x%x), arg: %lu\n", cmd, cmd, arg);
	spin_lock(&dev->mutex);
	switch (cmd) {
	case FIOQSIZE:
		r = atomic_read(&dev->size);
		IR_DEBUG("Handling FIOQSIZE, size: %ld", r);
		break;
	case LIRC_GET_FEATURES:
		r = dev->features;
		IR_DEBUG("Handling LIRC_GET_FEATURES, data: 0x%lx", r);
		if (arg == 0)
			break;
		if (copy_to_user(argp, &dev->features, sizeof(__u32)) != 0)
			r = -EFAULT;
		break;
	case LIRC_GET_SEND_MODE:
		r = dev->send_mode;
		break;
	case LIRC_GET_REC_MODE:
		r = dev->rec_mode;
		break;
	case LIRC_GET_LENGTH:
		r = dev->code_length;
		break;
	case LIRC_SET_FEATURES:
		dev->features = (__u32)arg;
		r = 0;
		break;
	case LIRC_SET_SEND_MODE:
		dev->send_mode = (__u32)arg;
		r = 0;
		break;
	case LIRC_SET_REC_MODE:
		dev->rec_mode = (__u32)arg;
		r = 0;
		break;
	case LIRC_SET_LENGTH:
		dev->code_length = (__u32)arg;
		r = 0;
		break;
	default:
		r = -ENOTTY;
		break;
	}
	spin_unlock(&dev->mutex);
	return r;
}

/** Kernel side of select() and poll(). */
static unsigned int irpipe_poll(struct file *filp, poll_table *wait)
{
	int mask = 0;
	struct ir_device* const dev = (struct ir_device*)filp->private_data;

	poll_wait(filp, &dev->wait_for_writer, wait);
	if (fifo_have_data(dev))
		mask = POLLIN | POLLRDNORM;
	return mask;
}

/** Module load. */
int irpipe_init(void)
{
	dev_t dev;
	int r;
	int i;

	IR_DEBUG("start loading");
	ir_devices = kmalloc_array(nr_of_devices,
				   sizeof(struct ir_device),
				   GFP_KERNEL);
	if (ir_devices == NULL)
		return -ENOMEM;
	for (i = 0; i < nr_of_devices; i += 1) {
		if (!ir_device_init(&ir_devices[i], i)) {
			IR_WARN("Cannot allocate memory (giving up).");
			return -ENOMEM;
		}
	}
	r = alloc_chrdev_region(&dev, 0, nr_of_devices, DEVICENAME);
	if (r < 0) {
		IR_WARN("failed to allocate major number");
		return r;
	}
	dev_major = MAJOR(dev);

	class = class_create(THIS_MODULE, DEVICENAME);
	for (i = 0; i < nr_of_devices; i += 1)
		device_create(class, NULL, MKDEV(dev_major, i), NULL,
			      DEVICENAME "%d", i);
	ir_cdev = cdev_alloc();
	cdev_init(ir_cdev, &fops);
	ir_cdev->owner = THIS_MODULE;
	r = cdev_add(ir_cdev, dev, 2);
	if (r < 0) {
		IR_WARN("Cannot add kernel device\n");
		return r;
	}
	IR_INFO("Loading complete, major device nr:  %d", dev_major);
	return 0;
}

/** Module unload. */
void irpipe_exit(void)
{
	int i;

	for (i = 0; i < nr_of_devices; i += 1) {
		ir_device_destroy(&ir_devices[i]);
		device_destroy(class, MKDEV(dev_major, i));
	}
	class_destroy(class);
	cdev_del(ir_cdev);
	unregister_chrdev_region(MKDEV(dev_major, 0), nr_of_devices);
	kfree(ir_devices);
	IR_DEBUG("Unloading device %d", dev_major);
}

const struct file_operations fops = {
	.owner		= THIS_MODULE,
	.open		= irpipe_open,
	.write		= irpipe_write,
	.unlocked_ioctl = irpipe_ioctl,
	.read		= irpipe_read,
	.release	= irpipe_close,
	.poll           = irpipe_poll,
};

MODULE_AUTHOR("Alec Leamas <leamas at gmail dot com>");
MODULE_DESCRIPTION("Simple pipe supporting some lirc ioctl commands");
MODULE_LICENSE("GPL");

module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, " Enable (default off) debug logging");

module_param(buffsize, int, S_IRUGO);
MODULE_PARM_DESC(buffsize, "Internal buffer size");

module_param(nr_of_devices, int, S_IRUGO);
MODULE_PARM_DESC(nr_of_devices, "Number of minor devices");

module_init(irpipe_init);
module_exit(irpipe_exit);


text:
//
//  MutNRLockDict.h
//  VVOpenSource
//
//  Created by David Lublin on 12/22/09.
//  Copyright 2009 Vidvox. All rights reserved.
//

#if IPHONE
#import <UIKit/UIKit.h>
#else
#import <Cocoa/Cocoa.h>
#endif

#import "MutLockDict.h"
#import "ObjectHolder.h"

///	Subclass of MutLockDict; this class does NOT retain the objects in its array!
/**
\ingroup VVBasics
this class exists because i frequently find myself in situations where i want to add an instance of an object to an array/dict/[any class which retains the passed instance], but i don't actually want the item to be retained.

Instead of adding (and therefore retaining) objects to an array like my superclass, this class makes an ObjectHolder for objects which are added to it (so they don't get retained), and adds the ObjectHolder to me.  when other classes ask me for the index of an object, or ask for the object at a particular index, i'll find the relevant ObjectHolder and then return the object it's storing.
*/

@interface MutNRLockDict : MutLockDict {

}

- (void) setObject:(id)o forKey:(NSString *)s;
- (void) setValue:(id)v forKey:(NSString *)s;
- (id) objectForKey:(NSString *)k;
- (void) addEntriesFromDictionary:(id)otherDictionary;
- (NSArray *) allValues;

@end


text:
<?php
/**
 * Athene2 - Advanced Learning Resources Manager
 *
 * @author    Aeneas Rekkas (aeneas.rekkas@serlo.org)
 * @license   LGPL-3.0
 * @license   http://opensource.org/licenses/LGPL-3.0 The GNU Lesser General Public License, version 3.0
 * @link      https://github.com/serlo-org/athene2 for the canonical source repository
 */
namespace Ui\Options;

use Zend\Stdlib\AbstractOptions;

class PageHeaderHelperOptions extends AbstractOptions
{
    /**
     * @var string
     */
    protected $delimiter = ' - ';
    /**
     * @var string
     */
    protected $template = 'common/helper/page-header';

    /**
     * @return string
     */
    public function getTemplate()
    {
        return $this->template;
    }

    /**
     * @param string $template
     */
    public function setTemplate($template)
    {
        $this->template = $template;
    }

    /**
     * @return string
     */
    public function getDelimiter()
    {
        return $this->delimiter;
    }

    /**
     * @param string $delimiter
     */
    public function setDelimiter($delimiter)
    {
        $this->delimiter = $delimiter;
    }
}


text:
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef _WIN32
#include <windows.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <tgf.h>
#include <track.h>
#include <car.h>
#include <raceman.h>
#include <robottools.h>
#include <robot.h>

static tTrack	*curTrack;

static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s);
static void newrace(int index, tCarElt* car, tSituation *s);
static void drive(int index, tCarElt* car, tSituation *s);
static void endrace(int index, tCarElt *car, tSituation *s);
static void shutdown(int index);
static int  InitFuncPt(int index, void *pt);

/*
 * Module entry point
 */
extern "C" int
chenyi_AI1(tModInfo *modInfo)
{
    memset(modInfo, 0, 10*sizeof(tModInfo));

    modInfo->name    = strdup("chenyi_AI1");		/* name of the module (short) */
    modInfo->desc    = strdup("");	/* description of the module (can be long) */
    modInfo->fctInit = InitFuncPt;		/* init function */
    modInfo->gfId    = ROB_IDENT;		/* supported framework version */
    modInfo->index   = 1;

    return 0;
}

/* Module interface initialization. */
static int
InitFuncPt(int index, void *pt)
{
    tRobotItf *itf  = (tRobotItf *)pt;

    itf->rbNewTrack = initTrack; /* Give the robot the track view called */
				 /* for every track change or new race */
    itf->rbNewRace  = newrace; 	 /* Start a new race */
    itf->rbDrive    = drive;	 /* Drive during race */
    itf->rbPitCmd   = NULL;
    itf->rbEndRace  = endrace;	 /* End of the current race */
    itf->rbShutdown = shutdown;	 /* Called before the module is unloaded */
    itf->index      = index; 	 /* Index used if multiple interfaces */
    return 0;
}

/* Called for every track change or new race. */
static void
initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s)
{
    curTrack = track;
    *carParmHandle = NULL;
}

/* Start a new race. */
static void
newrace(int index, tCarElt* car, tSituation *s)
{
}

/* Compute gear. */
const float SHIFT = 0.85;         /* [-] (% of rpmredline) */
const float SHIFT_MARGIN = 4.0;  /* [m/s] */

int getGear(tCarElt *car)
{
	if (car->_gear <= 0)
		return 1;
	float gr_up = car->_gearRatio[car->_gear + car->_gearOffset];
	float omega = car->_enginerpmRedLine/gr_up;
	float wr = car->_wheelRadius(2);

	if (omega*wr*SHIFT < car->_speed_x) {
		return car->_gear + 1;
	} else {
		float gr_down = car->_gearRatio[car->_gear + car->_gearOffset - 1];
		omega = car->_enginerpmRedLine/gr_down;
		if (car->_gear > 1 && omega*wr*SHIFT > car->_speed_x + SHIFT_MARGIN) {
			return car->_gear - 1;
		}
	}
	return car->_gear;
}

/* check if the car is stuck */
const float MAX_UNSTUCK_SPEED = 5.0;   /* [m/s] */
const float MIN_UNSTUCK_DIST = 3.0;    /* [m] */
const float MAX_UNSTUCK_ANGLE = 20.0/180.0*PI;
const int MAX_UNSTUCK_COUNT = 250;
static int stuck = 0;

bool isStuck(tCarElt* car)
{
    float angle = RtTrackSideTgAngleL(&(car->_trkPos)) - car->_yaw;
    NORM_PI_PI(angle);

    if (fabs(angle) > MAX_UNSTUCK_ANGLE &&
        car->_speed_x < MAX_UNSTUCK_SPEED &&
        fabs(car->_trkPos.toMiddle) > MIN_UNSTUCK_DIST) {
        if (stuck > MAX_UNSTUCK_COUNT && car->_trkPos.toMiddle*angle < 0.0) {
            return true;
        } else {
            stuck++;
            return false;
        }
    } else {
        stuck = 0;
        return false;
    }
}

/* Drive during race. */

double desired_speed=20/3.6;
//double keepLR=-2.0;   // for two-lane
double keepLR=-4.0;   // for three-lane

//////// Yunzhu ////////
int step_count = 0;
//////// Yunzhu ////////

static void drive(int index, tCarElt* car, tSituation *s)
{
    memset(&car->ctrl, 0, sizeof(tCarCtrl));

    //////// Yunzhu /////////
    step_count++;
    if (step_count > 150)
	desired_speed = 80/3.6;
    //////// Yunzhu ////////

    if (isStuck(car)) {
        float angle = -RtTrackSideTgAngleL(&(car->_trkPos)) + car->_yaw;
        NORM_PI_PI(angle); // put the angle back in the range from -PI to PI

        car->ctrl.steer = angle / car->_steerLock;
        car->ctrl.gear = -1; // reverse gear
        car->ctrl.accelCmd = 0.3; // 30% accelerator pedal
        car->ctrl.brakeCmd = 0.0; // no brakes
    }
    else {
        float angle;
        const float SC = 1.0;

        angle = RtTrackSideTgAngleL(&(car->_trkPos)) - car->_yaw;
        NORM_PI_PI(angle); // put the angle back in the range from -PI to PI
        angle -= SC*(car->_trkPos.toMiddle+keepLR)/car->_trkPos.seg->width;

        // set up the values to return
        car->ctrl.steer = angle / car->_steerLock;
        car->ctrl.gear = getGear(car);

        if (car->_speed_x>desired_speed) {
           car->ctrl.brakeCmd=0.0;
           car->ctrl.accelCmd=0.0;
        }
        else if  (car->_speed_x<desired_speed) {
           car->ctrl.accelCmd=0.5;
           car->ctrl.brakeCmd=0.0;
        }

    }
}

/* End of the current race */
static void
endrace(int index, tCarElt *car, tSituation *s)
{
}

/* Called before the module is unloaded */
static void
shutdown(int index)
{
}


text:
#ifndef __JIN_MATRIX_H
#define __JIN_MATRIX_H
#include <math.h>
namespace jin
{
namespace util
{

    struct vertex
    {
        unsigned char r, g, b, a;
        float x, y;
        float s, t;
    };
    /**
    * This class is the basis for all transformations in LOVE. Althought not
    * really needed for 2D, it contains 4x4 elements to be compatible with
    * OpenGL without conversions.
    **/
    class Matrix
    {
    private:

        /**
        * | e0 e4 e8  e12 |
        * | e1 e5 e9  e13 |
        * | e2 e6 e10 e14 |
        * | e3 e7 e11 e15 |
        **/
        float e[16];

    public:

        /**
        * Creates a new identity matrix.
        **/
        Matrix();

        /**
        * Destructor.
        **/
        ~Matrix();

        /**
        * Multiplies this Matrix with another Matrix, changing neither.
        * @param m The Matrix to multiply with this Matrix.
        * @return The combined matrix.
        **/
        Matrix operator * (const Matrix & m) const;

        /**
        * Multiplies a Matrix into this Matrix.
        * @param m The Matrix to combine into this Matrix.
        **/
        void operator *= (const Matrix & m);

        /**
        * Gets a pointer to the 16 array elements.
        * @return The array elements.
        **/
        const float * getElements() const;

        /**
        * Resets this Matrix to the identity matrix.
        **/
        void setIdentity();

        /**
        * Resets this Matrix to a translation.
        * @param x Translation along x-axis.
        * @param y Translation along y-axis.
        **/
        void setTranslation(float x, float y);

        /**
        * Resets this Matrix to a rotation.
        * @param r The angle in radians.
        **/
        void setRotation(float r);

        /**
        * Resets this Matrix to a scale transformation.
        * @param sx Scale factor along the x-axis.
        * @param sy Scale factor along the y-axis.
        **/
        void setScale(float sx, float sy);

        /**
        * Resets this Matrix to a shear transformation.
        * @param kx Shear along x-axis.
        * @param ky Shear along y-axis.
        **/
        void setShear(float kx, float ky);

        /**
        * Creates a transformation with a certain position, orientation, scale
        * and offset. Perfect for Drawables -- what a coincidence!
        *
        * @param x The translation along the x-axis.
        * @param y The translation along the y-axis.
        * @param angle The rotation (rad) around the center with offset (ox,oy).
        * @param sx Scale along x-axis.
        * @param sy Scale along y-axis.
        * @param ox The offset for rotation along the x-axis.
        * @param oy The offset for rotation along the y-axis.
        * @param kx Shear along x-axis
        * @param ky Shear along y-axis
        **/
        void setTransformation(float x, float y, float angle, float sx, float sy, float ox, float oy);

        /**
        * Multiplies this Matrix with a translation.
        * @param x Translation along x-axis.
        * @param y Translation along y-axis.
        **/
        void translate(float x, float y);

        /**
        * Multiplies this Matrix with a rotation.
        * @param r Angle in radians.
        **/
        void rotate(float r);

        /**
        * Multiplies this Matrix with a scale transformation.
        * @param sx Scale factor along the x-axis.
        * @param sy Scale factor along the y-axis.
        **/
        void scale(float sx, float sy);

        /**
        * Multiplies this Matrix with a shear transformation.
        * @param kx Shear along the x-axis.
        * @param ky Shear along the y-axis.
        **/
        void shear(float kx, float ky);

        /**
        * Transforms an array of vertices by this Matrix. The sources and
        * destination arrays may be the same.
        *
        * @param dst Storage for the transformed vertices.
        * @param src The source vertices.
        * @param size The number of vertices.
        **/
        void transform(vertex * dst, const vertex * src, int size) const;

    };

}
}

#endif


text:
<?php

return array(
    'required'         => "Kolom ini dibutuhkan.",
    'email'            => "Email tidak valid.",
    'alpha_dash'       => "Kolom ini hanya boleh mengandung huruf, angka dan tanda penghubung.",
    'alpha'            => "Kolom ini hanya boleh mengandung huruf.",
    'last_name.min'    => "Minimal karakter untuk nama akhir adalah :min.",
    'last_name.max'    => "Karakter untuk nama akhir tidak melebihi :max.",
    'first_name.min'   => "Minimal karakter untuk nama awal adalah :min.",
    'first_name.max'   => "Karakter untuk nama awal tidak melebihi :max.",
    'username.min'     => "Minimal karakter untuk pengguna awal adalah :min.",
    'username.max'     => "Karakter untuk nama pengguna tidak melebihi :max.",
    'pass.min'         => "Minimal karakter untuk kata sandi adalah :min.",
    'pass.max'         => "Karakter untuk kata sandi tidak melebihi :max.",
    'groupname.min'    => "Minimal karakter untuk nama grup adalah :min.",
    'groupname.max'    => "Karakter untuk nama grup tidak melebihi :max.",
    'name.min'         => "Minimal karakter untuk nama adalah :min.",
    'name.max'         => "Karakter untuk nama tidak melebihi :max.",
    'value.min'        => "Minimal karakter untuk nilai adalah :min.",
    'value.max'        => "Karakter untuk nilai tidak melebihi :max.",
    'description.min'  => "Minimal karakter untuk keterangan adalah :min.",
    'description.max'  => "Karakter untuk keterangan tidak melebihi :max.",
);


text:
package cmd

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"time"

	"contrib.go.opencensus.io/exporter/jaeger"
	"contrib.go.opencensus.io/exporter/prometheus"
	"github.com/hellofresh/janus/pkg/config"
	obs "github.com/hellofresh/janus/pkg/observability"
	"github.com/hellofresh/logging-go"
	_trace "github.com/hellofresh/opencensus-go-extras/trace"
	"github.com/hellofresh/stats-go"
	"github.com/hellofresh/stats-go/bucket"
	"github.com/hellofresh/stats-go/client"
	"github.com/hellofresh/stats-go/hooks"
	log "github.com/sirupsen/logrus"
	"go.opencensus.io/stats/view"
	"go.opencensus.io/trace"
)

var (
	globalConfig *config.Specification
	statsClient  client.Client
)

func initLogWriterEarly() {
	switch logging.LogWriter(strings.ToLower(os.Getenv("LOG_WRITER"))) {
	case logging.StdOut:
		log.SetOutput(os.Stdout)
	case logging.Discard:
		log.SetOutput(ioutil.Discard)
	case logging.StdErr:
		fallthrough
	default:
		log.SetOutput(os.Stderr)
	}
}

func initConfig() {
	var err error
	globalConfig, err = config.Load(configFile)
	if nil != err {
		log.WithError(err).Info("Could not load configurations from file - trying environment configurations instead.")

		globalConfig, err = config.LoadEnv()
		if nil != err {
			log.WithError(err).Error("Could not load configurations from environment variables")
		}
	}
}

// initializes the basic configuration for the log wrapper
func initLog() {
	err := globalConfig.Log.Apply()
	if nil != err {
		log.WithError(err).Fatal("Could not apply logging configurations")
	}
}

func initStatsClient() {
	// FIXME: this causes application hang because we're in the locked log already
	//statsLog.SetHandler(func(msg string, fields map[string]interface{}, err error) {
	//	entry := log.WithFields(log.Fields(fields))
	//	if err == nil {
	//		entry.Warn(msg)
	//	} else {
	//		entry.WithError(err).Warn(msg)
	//	}
	//})

	sectionsTestsMap, err := bucket.ParseSectionsTestsMap(globalConfig.Stats.IDs)
	if err != nil {
		log.WithError(err).WithField("config", globalConfig.Stats.IDs).
			Error("Failed to parse stats second level IDs from env")
		sectionsTestsMap = map[bucket.PathSection]bucket.SectionTestDefinition{}
	}
	log.WithField("config", globalConfig.Stats.IDs).
		WithField("map", sectionsTestsMap.String()).
		Debug("Setting stats second level IDs")

	statsClient, err = stats.NewClient(globalConfig.Stats.DSN)
	if err != nil {
		log.WithError(err).Fatal("Error initializing stats client")
	}

	statsClient.SetHTTPMetricCallback(bucket.NewHasIDAtSecondLevelCallback(&bucket.SecondLevelIDConfig{
		HasIDAtSecondLevel:    sectionsTestsMap,
		AutoDiscoverThreshold: globalConfig.Stats.AutoDiscoverThreshold,
		AutoDiscoverWhiteList: globalConfig.Stats.AutoDiscoverWhiteList,
	}))

	host, err := os.Hostname()
	if nil != err {
		host = "-unknown-"
	}

	_, appFile := filepath.Split(os.Args[0])
	statsClient.TrackMetric("app", bucket.MetricOperation{"init", host, appFile})

	log.AddHook(hooks.NewLogrusHook(statsClient, globalConfig.Stats.ErrorsSection))
}

func initStatsExporter() {
	var err error
	logger := log.WithField("stats.exporter", globalConfig.Stats.Exporter)

	// Register stats exporter according to config
	switch globalConfig.Stats.Exporter {
	case obs.Datadog:
		fallthrough
	case obs.Stackdriver:
		logger.Warn("Not implemented!")
		return
	case obs.Prometheus:
		err = initPrometheusExporter()
	default:
		logger.Info("Invalid or no stats exporter was specified")
		return
	}

	if err != nil {
		logger.WithError(err).Error("Failed initialising stats exporter")
		return
	}

	// Configure/Register stats views
	view.SetReportingPeriod(time.Second)

	vv := append(obs.AllViews)

	if err := view.Register(vv...); err != nil {
		log.WithError(err).Warn("Failed to register server views")
	}
}

func initPrometheusExporter() (err error) {
	obs.PrometheusExporter, err = prometheus.NewExporter(prometheus.Options{})
	if err != nil {
		log.WithError(err).Warn("Failed to create prometheus exporter")
	} else {
		view.RegisterExporter(obs.PrometheusExporter)
	}
	return err
}

func initTracingExporter() {
	var err error
	logger := log.WithField("tracing.exporter", globalConfig.Tracing.Exporter)

	switch globalConfig.Tracing.Exporter {
	case obs.AzureMonitor:
		fallthrough
	case obs.Datadog:
		fallthrough
	case obs.Stackdriver:
		fallthrough
	case obs.Zipkin:
		logger.Warn("Not implemented!")
	case obs.Jaeger:
		err = initJaegerExporter()
	default:
		logger.Info("Invalid or no tracing exporter was specified")
		return
	}

	if err != nil {
		logger.WithError(err).Error("Failed initialising tracing exporter")
		return
	}

	var traceConfig trace.Config
	var sampler trace.Sampler
	logger = logger.WithField("tracing.samplingStrategy", globalConfig.Tracing.SamplingStrategy)

	switch globalConfig.Tracing.SamplingStrategy {
	case "always":
		sampler = trace.AlwaysSample()
	case "never":
		sampler = trace.NeverSample()
	case "probabilistic":
		sampler = trace.ProbabilitySampler(globalConfig.Tracing.SamplingParam)
	default:
		logger.Warn("Invalid tracing sampling strategy specified")
		return
	}

	if !globalConfig.Tracing.IsPublicEndpoint {
		sampler = _trace.RespectParentSampler(sampler)
	}

	traceConfig.DefaultSampler = sampler
	trace.ApplyConfig(traceConfig)
}

func initJaegerExporter() (err error) {
	jaegerURL := globalConfig.Tracing.JaegerTracing.SamplingServerURL
	if jaegerURL == "" {
		jaegerURL = fmt.Sprintf("%s:%s", globalConfig.Tracing.JaegerTracing.SamplingServerHost, globalConfig.Tracing.JaegerTracing.SamplingServerPort)
	}

	jaegerExporter, err := jaeger.NewExporter(jaeger.Options{
		AgentEndpoint: jaegerURL,
		ServiceName:   globalConfig.Tracing.ServiceName,
	})
	if err != nil {
		log.WithError(err).Warn("Failed to create jaeger exporter")
	} else {
		trace.RegisterExporter(jaegerExporter)
	}
	return err
}


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.salesforce;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
@SuppressWarnings("unchecked")
public class SalesforceEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {

    @Override
    public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
        SalesforceEndpoint target = (SalesforceEndpoint) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "apexmethod":
        case "apexMethod": target.getConfiguration().setApexMethod(property(camelContext, java.lang.String.class, value)); return true;
        case "apexqueryparams":
        case "apexQueryParams": target.getConfiguration().setApexQueryParams(property(camelContext, java.util.Map.class, value)); return true;
        case "apexurl":
        case "apexUrl": target.getConfiguration().setApexUrl(property(camelContext, java.lang.String.class, value)); return true;
        case "apiversion":
        case "apiVersion": target.getConfiguration().setApiVersion(property(camelContext, java.lang.String.class, value)); return true;
        case "backoffincrement":
        case "backoffIncrement": target.getConfiguration().setBackoffIncrement(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
        case "batchid":
        case "batchId": target.getConfiguration().setBatchId(property(camelContext, java.lang.String.class, value)); return true;
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
        case "contenttype":
        case "contentType": target.getConfiguration().setContentType(property(camelContext, org.apache.camel.component.salesforce.api.dto.bulk.ContentType.class, value)); return true;
        case "defaultreplayid":
        case "defaultReplayId": target.getConfiguration().setDefaultReplayId(property(camelContext, java.lang.Long.class, value)); return true;
        case "exceptionhandler":
        case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
        case "exchangepattern":
        case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
        case "format": target.getConfiguration().setFormat(property(camelContext, org.apache.camel.component.salesforce.internal.PayloadFormat.class, value)); return true;
        case "httpclient":
        case "httpClient": target.getConfiguration().setHttpClient(property(camelContext, org.apache.camel.component.salesforce.SalesforceHttpClient.class, value)); return true;
        case "includedetails":
        case "includeDetails": target.getConfiguration().setIncludeDetails(property(camelContext, java.lang.Boolean.class, value)); return true;
        case "initialreplayidmap":
        case "initialReplayIdMap": target.getConfiguration().setInitialReplayIdMap(property(camelContext, java.util.Map.class, value)); return true;
        case "instanceid":
        case "instanceId": target.getConfiguration().setInstanceId(property(camelContext, java.lang.String.class, value)); return true;
        case "jobid":
        case "jobId": target.getConfiguration().setJobId(property(camelContext, java.lang.String.class, value)); return true;
        case "lazystartproducer":
        case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
        case "limit": target.getConfiguration().setLimit(property(camelContext, java.lang.Integer.class, value)); return true;
        case "maxbackoff":
        case "maxBackoff": target.getConfiguration().setMaxBackoff(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
        case "notfoundbehaviour":
        case "notFoundBehaviour": target.getConfiguration().setNotFoundBehaviour(property(camelContext, org.apache.camel.component.salesforce.NotFoundBehaviour.class, value)); return true;
        case "notifyforfields":
        case "notifyForFields": target.getConfiguration().setNotifyForFields(property(camelContext, org.apache.camel.component.salesforce.internal.dto.NotifyForFieldsEnum.class, value)); return true;
        case "notifyforoperationcreate":
        case "notifyForOperationCreate": target.getConfiguration().setNotifyForOperationCreate(property(camelContext, java.lang.Boolean.class, value)); return true;
        case "notifyforoperationdelete":
        case "notifyForOperationDelete": target.getConfiguration().setNotifyForOperationDelete(property(camelContext, java.lang.Boolean.class, value)); return true;
        case "notifyforoperationundelete":
        case "notifyForOperationUndelete": target.getConfiguration().setNotifyForOperationUndelete(property(camelContext, java.lang.Boolean.class, value)); return true;
        case "notifyforoperationupdate":
        case "notifyForOperationUpdate": target.getConfiguration().setNotifyForOperationUpdate(property(camelContext, java.lang.Boolean.class, value)); return true;
        case "notifyforoperations":
        case "notifyForOperations": target.getConfiguration().setNotifyForOperations(property(camelContext, org.apache.camel.component.salesforce.internal.dto.NotifyForOperationsEnum.class, value)); return true;
        case "objectmapper":
        case "objectMapper": target.getConfiguration().setObjectMapper(property(camelContext, com.fasterxml.jackson.databind.ObjectMapper.class, value)); return true;
        case "rawpayload":
        case "rawPayload": target.getConfiguration().setRawPayload(property(camelContext, boolean.class, value)); return true;
        case "replayid":
        case "replayId": target.setReplayId(property(camelContext, java.lang.Long.class, value)); return true;
        case "reportid":
        case "reportId": target.getConfiguration().setReportId(property(camelContext, java.lang.String.class, value)); return true;
        case "reportmetadata":
        case "reportMetadata": target.getConfiguration().setReportMetadata(property(camelContext, org.apache.camel.component.salesforce.api.dto.analytics.reports.ReportMetadata.class, value)); return true;
        case "resultid":
        case "resultId": target.getConfiguration().setResultId(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectblobfieldname":
        case "sObjectBlobFieldName": target.getConfiguration().setSObjectBlobFieldName(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectclass":
        case "sObjectClass": target.getConfiguration().setSObjectClass(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectfields":
        case "sObjectFields": target.getConfiguration().setSObjectFields(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectid":
        case "sObjectId": target.getConfiguration().setSObjectId(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectidname":
        case "sObjectIdName": target.getConfiguration().setSObjectIdName(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectidvalue":
        case "sObjectIdValue": target.getConfiguration().setSObjectIdValue(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectname":
        case "sObjectName": target.getConfiguration().setSObjectName(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectquery":
        case "sObjectQuery": target.getConfiguration().setSObjectQuery(property(camelContext, java.lang.String.class, value)); return true;
        case "sobjectsearch":
        case "sObjectSearch": target.getConfiguration().setSObjectSearch(property(camelContext, java.lang.String.class, value)); return true;
        case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
        case "updatetopic":
        case "updateTopic": target.getConfiguration().setUpdateTopic(property(camelContext, boolean.class, value)); return true;
        default: return false;
        }
    }

    @Override
    public Class<?> getOptionType(String name, boolean ignoreCase) {
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "apexmethod":
        case "apexMethod": return java.lang.String.class;
        case "apexqueryparams":
        case "apexQueryParams": return java.util.Map.class;
        case "apexurl":
        case "apexUrl": return java.lang.String.class;
        case "apiversion":
        case "apiVersion": return java.lang.String.class;
        case "backoffincrement":
        case "backoffIncrement": return long.class;
        case "batchid":
        case "batchId": return java.lang.String.class;
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": return boolean.class;
        case "contenttype":
        case "contentType": return org.apache.camel.component.salesforce.api.dto.bulk.ContentType.class;
        case "defaultreplayid":
        case "defaultReplayId": return java.lang.Long.class;
        case "exceptionhandler":
        case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
        case "exchangepattern":
        case "exchangePattern": return org.apache.camel.ExchangePattern.class;
        case "format": return org.apache.camel.component.salesforce.internal.PayloadFormat.class;
        case "httpclient":
        case "httpClient": return org.apache.camel.component.salesforce.SalesforceHttpClient.class;
        case "includedetails":
        case "includeDetails": return java.lang.Boolean.class;
        case "initialreplayidmap":
        case "initialReplayIdMap": return java.util.Map.class;
        case "instanceid":
        case "instanceId": return java.lang.String.class;
        case "jobid":
        case "jobId": return java.lang.String.class;
        case "lazystartproducer":
        case "lazyStartProducer": return boolean.class;
        case "limit": return java.lang.Integer.class;
        case "maxbackoff":
        case "maxBackoff": return long.class;
        case "notfoundbehaviour":
        case "notFoundBehaviour": return org.apache.camel.component.salesforce.NotFoundBehaviour.class;
        case "notifyforfields":
        case "notifyForFields": return org.apache.camel.component.salesforce.internal.dto.NotifyForFieldsEnum.class;
        case "notifyforoperationcreate":
        case "notifyForOperationCreate": return java.lang.Boolean.class;
        case "notifyforoperationdelete":
        case "notifyForOperationDelete": return java.lang.Boolean.class;
        case "notifyforoperationundelete":
        case "notifyForOperationUndelete": return java.lang.Boolean.class;
        case "notifyforoperationupdate":
        case "notifyForOperationUpdate": return java.lang.Boolean.class;
        case "notifyforoperations":
        case "notifyForOperations": return org.apache.camel.component.salesforce.internal.dto.NotifyForOperationsEnum.class;
        case "objectmapper":
        case "objectMapper": return com.fasterxml.jackson.databind.ObjectMapper.class;
        case "rawpayload":
        case "rawPayload": return boolean.class;
        case "replayid":
        case "replayId": return java.lang.Long.class;
        case "reportid":
        case "reportId": return java.lang.String.class;
        case "reportmetadata":
        case "reportMetadata": return org.apache.camel.component.salesforce.api.dto.analytics.reports.ReportMetadata.class;
        case "resultid":
        case "resultId": return java.lang.String.class;
        case "sobjectblobfieldname":
        case "sObjectBlobFieldName": return java.lang.String.class;
        case "sobjectclass":
        case "sObjectClass": return java.lang.String.class;
        case "sobjectfields":
        case "sObjectFields": return java.lang.String.class;
        case "sobjectid":
        case "sObjectId": return java.lang.String.class;
        case "sobjectidname":
        case "sObjectIdName": return java.lang.String.class;
        case "sobjectidvalue":
        case "sObjectIdValue": return java.lang.String.class;
        case "sobjectname":
        case "sObjectName": return java.lang.String.class;
        case "sobjectquery":
        case "sObjectQuery": return java.lang.String.class;
        case "sobjectsearch":
        case "sObjectSearch": return java.lang.String.class;
        case "synchronous": return boolean.class;
        case "updatetopic":
        case "updateTopic": return boolean.class;
        default: return null;
        }
    }

    @Override
    public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
        SalesforceEndpoint target = (SalesforceEndpoint) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "apexmethod":
        case "apexMethod": return target.getConfiguration().getApexMethod();
        case "apexqueryparams":
        case "apexQueryParams": return target.getConfiguration().getApexQueryParams();
        case "apexurl":
        case "apexUrl": return target.getConfiguration().getApexUrl();
        case "apiversion":
        case "apiVersion": return target.getConfiguration().getApiVersion();
        case "backoffincrement":
        case "backoffIncrement": return target.getConfiguration().getBackoffIncrement();
        case "batchid":
        case "batchId": return target.getConfiguration().getBatchId();
        case "bridgeerrorhandler":
        case "bridgeErrorHandler": return target.isBridgeErrorHandler();
        case "contenttype":
        case "contentType": return target.getConfiguration().getContentType();
        case "defaultreplayid":
        case "defaultReplayId": return target.getConfiguration().getDefaultReplayId();
        case "exceptionhandler":
        case "exceptionHandler": return target.getExceptionHandler();
        case "exchangepattern":
        case "exchangePattern": return target.getExchangePattern();
        case "format": return target.getConfiguration().getFormat();
        case "httpclient":
        case "httpClient": return target.getConfiguration().getHttpClient();
        case "includedetails":
        case "includeDetails": return target.getConfiguration().getIncludeDetails();
        case "initialreplayidmap":
        case "initialReplayIdMap": return target.getConfiguration().getInitialReplayIdMap();
        case "instanceid":
        case "instanceId": return target.getConfiguration().getInstanceId();
        case "jobid":
        case "jobId": return target.getConfiguration().getJobId();
        case "lazystartproducer":
        case "lazyStartProducer": return target.isLazyStartProducer();
        case "limit": return target.getConfiguration().getLimit();
        case "maxbackoff":
        case "maxBackoff": return target.getConfiguration().getMaxBackoff();
        case "notfoundbehaviour":
        case "notFoundBehaviour": return target.getConfiguration().getNotFoundBehaviour();
        case "notifyforfields":
        case "notifyForFields": return target.getConfiguration().getNotifyForFields();
        case "notifyforoperationcreate":
        case "notifyForOperationCreate": return target.getConfiguration().getNotifyForOperationCreate();
        case "notifyforoperationdelete":
        case "notifyForOperationDelete": return target.getConfiguration().getNotifyForOperationDelete();
        case "notifyforoperationundelete":
        case "notifyForOperationUndelete": return target.getConfiguration().getNotifyForOperationUndelete();
        case "notifyforoperationupdate":
        case "notifyForOperationUpdate": return target.getConfiguration().getNotifyForOperationUpdate();
        case "notifyforoperations":
        case "notifyForOperations": return target.getConfiguration().getNotifyForOperations();
        case "objectmapper":
        case "objectMapper": return target.getConfiguration().getObjectMapper();
        case "rawpayload":
        case "rawPayload": return target.getConfiguration().isRawPayload();
        case "replayid":
        case "replayId": return target.getReplayId();
        case "reportid":
        case "reportId": return target.getConfiguration().getReportId();
        case "reportmetadata":
        case "reportMetadata": return target.getConfiguration().getReportMetadata();
        case "resultid":
        case "resultId": return target.getConfiguration().getResultId();
        case "sobjectblobfieldname":
        case "sObjectBlobFieldName": return target.getConfiguration().getSObjectBlobFieldName();
        case "sobjectclass":
        case "sObjectClass": return target.getConfiguration().getSObjectClass();
        case "sobjectfields":
        case "sObjectFields": return target.getConfiguration().getSObjectFields();
        case "sobjectid":
        case "sObjectId": return target.getConfiguration().getSObjectId();
        case "sobjectidname":
        case "sObjectIdName": return target.getConfiguration().getSObjectIdName();
        case "sobjectidvalue":
        case "sObjectIdValue": return target.getConfiguration().getSObjectIdValue();
        case "sobjectname":
        case "sObjectName": return target.getConfiguration().getSObjectName();
        case "sobjectquery":
        case "sObjectQuery": return target.getConfiguration().getSObjectQuery();
        case "sobjectsearch":
        case "sObjectSearch": return target.getConfiguration().getSObjectSearch();
        case "synchronous": return target.isSynchronous();
        case "updatetopic":
        case "updateTopic": return target.getConfiguration().isUpdateTopic();
        default: return null;
        }
    }
}


text: Dir[ File.dirname(__FILE__) + "/core_ext/*.rb" ].each { |file| require(file) }


text:
<?php
	// Start session
	session_start();

	// Unset the variables stored in session
	unset($_SESSION['user']);
	unset($_SESSION['user_id']);
	unset($_SESSION['user_first_name']);
	unset($_SESSION['user_last_name']);

	// Write session
	$_SESSION['logged_out'] = true;
	session_write_close();
	header("location: login.php");
	exit();
?>


text:
package com.blazebit.persistence.view.impl.entity;

import com.blazebit.persistence.CriteriaBuilder;
import com.blazebit.persistence.CriteriaBuilderFactory;
import com.blazebit.persistence.parser.EntityMetamodel;
import com.blazebit.persistence.parser.util.JpaMetamodelUtils;
import com.blazebit.persistence.view.impl.EntityViewManagerImpl;
import com.blazebit.persistence.view.impl.update.UpdateContext;
import com.blazebit.persistence.view.metamodel.Attribute;
import com.blazebit.persistence.view.metamodel.ManagedViewType;
import com.blazebit.persistence.view.metamodel.MappingAttribute;
import com.blazebit.persistence.view.metamodel.MethodAttribute;
import com.blazebit.persistence.view.metamodel.PluralAttribute;
import com.blazebit.persistence.view.metamodel.SingularAttribute;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.metamodel.EntityType;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author Christian Beikov
 * @since 1.2.0
 */
public class FullEntityLoader extends AbstractEntityLoader {

    private final String queryString;
    private final String queryStringMultiple;

    public FullEntityLoader(EntityViewManagerImpl evm, ManagedViewType<?> subviewType) {
        // ViewIdMapper is not necessary because this will always be invoked with a null id
        super(evm, subviewType.getEntityClass(), jpaIdOf(evm, subviewType), viewIdMappingOf(evm, subviewType), null, evm.getEntityIdAccessor());
        this.queryString = createQueryString(evm, subviewType, false);
        this.queryStringMultiple = createQueryString(evm, subviewType, true);
    }

    private String createQueryString(EntityViewManagerImpl evm, ManagedViewType<?> subviewType, boolean multiple) {
        EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
        EntityType<?> entityType = entityMetamodel.getEntity(entityClass);

        // We can't query embeddables
        if (entityType == null) {
            return null;
        }

        Set<String> fetchJoinableRelations = new HashSet<>(subviewType.getAttributes().size());

        addFetchJoinableRelations(fetchJoinableRelations, "", subviewType);

        CriteriaBuilderFactory cbf = evm.getCriteriaBuilderFactory();
        if (fetchJoinableRelations.isEmpty()) {
            return null;
        } else {
            CriteriaBuilder<?> criteriaBuilder = cbf.create(null, entityClass).fetch(fetchJoinableRelations.toArray(new String[fetchJoinableRelations.size()]));
            if (multiple) {
                criteriaBuilder.where(JpaMetamodelUtils.getSingleIdAttribute(entityType).getName()).inExpressions(":entityIds");
            } else {
                criteriaBuilder.where(JpaMetamodelUtils.getSingleIdAttribute(entityType).getName()).eqExpression(":id");
            }
            return criteriaBuilder.getQueryString();
        }
    }

    private void addFetchJoinableRelations(Set<String> fetchJoinableRelations, String prefix, ManagedViewType<?> subviewType) {
        @SuppressWarnings("unchecked")
        Set<MethodAttribute<?, ?>> attributes = (Set<MethodAttribute<?, ?>>) (Set) subviewType.getAttributes();
        for (MethodAttribute<?, ?> attribute : attributes) {
            if (attribute.getMappingType() == Attribute.MappingType.BASIC) {
                if (attribute.isUpdatable()) {
                    String mapping = getMapping(prefix, attribute);
                    fetchJoinableRelations.add(mapping);
                }
                if (attribute.isMutable() && attribute.isSubview()) {
                    String mapping = getMapping(prefix, attribute);
                    fetchJoinableRelations.add(mapping);
                    ManagedViewType<?> type;
                    if (attribute instanceof SingularAttribute<?, ?>) {
                        type = (ManagedViewType<?>) ((SingularAttribute<?, ?>) attribute).getType();
                    } else if (attribute instanceof PluralAttribute<?, ?, ?>) {
                        type = (ManagedViewType<?>) ((PluralAttribute<?, ?, ?>) attribute).getElementType();
                    } else {
                        throw new RuntimeException("Unknown attribute type: " + attribute);
                    }
                    addFetchJoinableRelations(fetchJoinableRelations, mapping + ".", type);
                }
            }
        }
    }

    private String getMapping(String prefix, MethodAttribute<?, ?> attribute) {
        // Remove all array expressions
        String mapping = ((MappingAttribute<?, ?>) attribute).getMapping();
        return prefix + mapping.replaceAll("\\[[^\\]]\\]", "");
    }

    @Override
    public Object toEntity(UpdateContext context, Object view, Object id) {
        if (id == null || entityIdAccessor == null) {
            return createEntity();
        }

        return getReferenceOrLoad(context, view, id);
    }

    @Override
    public void toEntities(UpdateContext context, List<Object> views, List<Object> ids) {
        if (entityIdAccessor == null) {
            for (int i = 0; i < views.size(); i++) {
                views.set(i, createEntity());
            }
        } else {
            getReferencesLoadOrCreate(context, views, ids);
        }
    }

    @Override
    protected Object queryEntity(EntityManager em, Object id) {
        if (queryString == null) {
            return em.find(entityClass, id);
        }

        @SuppressWarnings("unchecked")
        List<Object> list = em.createQuery(queryString)
                .setParameter("id", id)
                .getResultList();
        if (list.isEmpty()) {
            throw new EntityNotFoundException("Required entity '" + entityClass.getName() + "' with id '" + id + "' couldn't be found!");
        }

        return list.get(0);
    }

    @Override
    protected List<Object> queryEntities(EntityManager em, List<Object> ids) {
        List<Object> list = em.createQuery(queryStringMultiple)
            .setParameter("entityIds", ids)
            .getResultList();
        if (list.size() != ids.size()) {
            throw new EntityNotFoundException("Required entities '" + entityClass.getName() + "' with ids '" + ids + "' couldn't all be found!");
        }

        return list;
    }
}


text:
var gulp = require('gulp');
var gutil = require('gulp-util');
var notify = require('gulp-notify');
var beml = require('gulp-beml');
var tarsConfig = require('../../../tars-config');
var replace = require('gulp-replace-task');
var notifier = require('../../helpers/notifier');
var fs = require('fs');

var handlebarsOptions = {
    batch: ['./markup/modules'],
    helpers: require('../../helpers/handlebars-helpers')
};

/**
 * Handlebars compilation of pages templates.
 * Templates with _ prefix won't be compiled
 * @param  {Object} buildOptions
 */
module.exports = function (buildOptions) {

    var patterns = [];
    if (!gutil.env.ie8) {
        patterns.push(
            {
                match: '<link href="%=staticPrefix=%/css/main_ie8%=hash=%%=min=%.css" rel="stylesheet" type="text/css">',
                replacement: ''
            }
        );
    }

    if (gutil.env.min || gutil.env.release) {
        patterns.push(
            {
                match: '%=min=%',
                replacement: '.min'
            }
        );
    } else {
        patterns.push(
            {
                match: '%=min=%',
                replacement: ''
            }
        );
    }

    if (gutil.env.release) {
        patterns.push(
            {
                match: '%=hash=%',
                replacement: buildOptions.hash
            }
        );
    } else {
        patterns.push(
            {
                match: '%=hash=%',
                replacement: ''
            }
        );
    }

    patterns.push(
        {
            match: '%=staticPrefix=%',
            replacement: tarsConfig.staticPrefixForPhp
        }
    );

    return gulp.task('html:compile-pages-for-php', function (cb) {

        return gulp.src([
            './markup/pages/**/*.html',
            '!./markup/pages/**/_*.html',
        ])
            .pipe(replace({
                patterns: patterns,
                usePrefix: false
            }))
            .on('error', notify.onError(function (error) {
                return '\nAn error occurred while replacing placeholdres.\nLook in the console for details.\n' + error;
            }))
            .pipe(beml())
            .on('error', notify.onError(function (error) {
                return '\nAn error occurred while beml html-files.\nLook in the console for details.\n' + error;
            }))
            .pipe(gulp.dest('./dev/pages/'))
            .pipe(
            notifier('Templates pages\'ve been compiled')
        );
    });
};


text:
function loadTxt()
	{
    var txtLang = document.getElementsByName("txtLang");
    txtLang[0].innerHTML = "Zoeken";
    txtLang[1].innerHTML = "Vervangen";
    txtLang[2].innerHTML = "Ident. hoofd/kleine lett.";
    txtLang[3].innerHTML = "Heel woord";

    document.getElementById("btnSearch").value = "zoek volgende";;
    document.getElementById("btnReplace").value = "vervangen";
    document.getElementById("btnReplaceAll").value = "alles vervangen";
    document.getElementById("btnClose").value = "sluiten";
	}
function getTxt(s)
    {
    switch(s)
        {
        case "Finished searching": return "Het doorzoeken van het document is voltooid.\nOpnieuw zoeken vanaf het begin?";
        default: return "";
        }
    }
function writeTitle()
	{
	document.write("<title>Zoeken & Vervangen</title>")
	}


text:
<?php

namespace Frontend\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Controller\AppController;

class DienstleistungenController extends AppController
{
    public function aenderungsabnahmeAction()
    {
        return new ViewModel();
    }
    public function hauptuntersuchungAction()
    {
        return new ViewModel();
    }
    public function schadengutachtenAction()
    {
        return new ViewModel();
    }
    public function sicherheitspruefungAction()
    {
        return new ViewModel();
    }
    public function oldtimergutachtenAction()
    {
        return new ViewModel();
    }
}


text:
<?php
namespace Code4\View;

use Code4\View\Interfaces\UserInterface;
use Code4\View\Traits\JsTraits;
use Illuminate\Http\Request;

/**
 * @method static array  jsRedirect(\string $redirectUrl) Redirect page
 * @method static array  dismissModal(\string $modalSelector) Close modal
 * @method static array  execScript(\string $function) Execute script or function
 * @method static array  successReload() Reload page
 * @method static array  refreshNotifications() Refresh notifications
 */
class ViewHelper {

    use JsTraits;

    protected $modal = [];

    /**
     * Generuje avatar. Jeżeli ma być użyty gravatar - $text = $email
     * @param string $text initials
     * @param string $email email
     * @param string $size micro|small|medium|large|huge
     * @param string $color color-0|color-1|color-2|color-3|color-4|color-5|color-6|color-7
     * @param string $class use 'reversed' for inverted colors
     * @param bool $gravatar
     * @return string
     */
    public function avatar($text, $email, $size, $color, $class = '', $gravatar = false) {

        if ($gravatar)
        {
            $gravatar_src = \Gravatar::src($email, 100);
            $temp = '
';
            $temp .= '
';
            $temp .= '';
            $temp .= '
';
            $temp .= '
';
            return $temp;
        } else {
            $temp = '
';
            $temp .= '
';
            $temp .= ''.$text.'';
            $temp .= '
';
            $temp .= '
';
            return $temp;
        }

    }

    /**
     * Używając interfejsu UserInterface pobieramy dane do generacji awatara
     * @param UserInterface $user
     * @param string $size
     * @param string $class
     * @return string
     */
    public function userAvatar(UserInterface $user, $size = 'medium', $class = '') {
        $gravatar = $user->getSetting('general_useGravatar', '1');
        $email = $user->getEmail();
        $initials = $user->getInitials();
        $color = $user->getSetting('userColor', 'color-0');

        return $this->avatar($initials, $email, $size, $color, $class, $gravatar);
    }

    /**
     * Tworzy i zwraca nowy obiekt modal
     * @param null|string $name
     * @return Elements\Modal
     */
    public function modal($name = null) {
        if (!$name) {
            return new Elements\Modal();
        } else {
            if (array_key_exists($name, $this->modal)) {
                return $this->modal[$name];
            } else {
                $this->modal[$name] = new Elements\Modal();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="表副問合せ" />
<meta content="TableSubquery" name="DC.subject" />
<meta content="TableSubquery" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefqueries.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rreftablesubquery" name="DC.Identifier" />
<meta content="ja" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>表副問合せ</title>

表副問合せ

表副問合せは複数の行を返す副問合せです。

スカラー副問合せとは異なり、表副問合せは以下の文脈にてのみ可能です。

FROM 節の表式

EXISTSやIN、量の比較

FROM 節の表式にて使われた場合、複数の列を返すことができます。

EXISTSでは、*を使う場合のみ複数の列を返すことができます。

INや限定条件では、単列のみ返すことができます。

構文

(問合せ)

例

-- FROM節の表式として、副問合せを使う。
SELECT VirtualFlightTable.flight_ID
FROM
    (SELECT flight_ID, orig_airport, dest_airport
    FROM Flights
    WHERE (orig_airport = 'SFO' OR dest_airport = 'SCL') )
AS VirtualFlightTable
-- FROM節の表式として、副問合せ(values式)を使う。
SELECT mycol1
FROM
    (VALUES (1, 2), (3, 4))
AS mytable (mycol1, mycol2)
-- EXISTSにて副問合せを使う
SELECT *
FROM Flights
WHERE EXISTS
    (SELECT * FROM Flights WHERE dest_airport = 'SFO'
    AND orig_airport = 'GRU')
-- INにて副問合せを使う
SELECT flight_id, segment_number
FROM Flights
WHERE flight_id IN
    (SELECT flight_ID
    FROM Flights WHERE orig_airport = 'SFO'
    OR dest_airport = 'SCL')
-- 定量比較にて副問合せを使う
SELECT NAME, COMM
FROM STAFF
WHERE COMM >
(SELECT AVG(BONUS + 800)
     FROM EMPLOYEE
     WHERE COMM < 5000)

親トピック: SQL 問い合わせ


text:
from .common import *

def get_argparser_min_cov(parser):
    parser.add_argument(
        "target_fn",
        help="Filename of the target sequence file or directory."
        )

    parser.add_argument(
        "jellyfish_fn",
        help="Filename of the jellyfish database.",
        nargs='*')


text:
package htmltest;

import java.io.File;

import common.Util;
import us.codecraft.webmagic.selector.Html;

public abstract class HtmlParseFromLocalFile {

	// private static volatile HtmlPaserFromLocalFile INSTANCE = null;
	//
	// private HtmlPaserFromLocalFile() {
	// }
	//
	// public static HtmlPaserFromLocalFile getInstance() {
	// if (INSTANCE == null) {
	// synchronized (HtmlPaserFromLocalFile.class) {
	// if (INSTANCE == null) {
	// INSTANCE = new HtmlPaserFromLocalFile();
	// }
	// }
	// }
	// return INSTANCE;
	// }

	public Object doSomething(final Html html) {
		throw new IllegalArgumentException();
	}

	public Object readFile() {

		final String content = Util.loadFromFile(new File("D://robot//test.html"));

		final Html html = new Html(content);

		return doSomething(html);
	}

	public Object readFile2() {

		final String content = Util.loadFromFile(new File("D://robot//test.html"));

		return doSomething(content);
	}

	public Object doSomething(final String pageContent) {
		throw new IllegalArgumentException();
	}

	public static void main(final String[] args) {

	}

}


text:
"use strict";

const

    net = require("net"),

    server = net.createServer(function(connection) {

        console.log('Subscriber connected...');

        // send the first chunk immediately
        connection.write(
            '{"type":"changed", "file":"targ'
        );

        // after a one sec delay, send the other chunk
        let timer = setTimeout(function() {
            connection.write('et.txt","timestamp":1358175758495}' + "\n");
            connection.end();
        }, 1000);

        connection.on('end', function() {
            clearTimeout(timer);
            console.log('Subscriber disconnected...');
        });
    });

server.listen(5432, function() {
    console.log("Test server listneing for subscribers...");
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BB.Poker.Common;

namespace BB.Poker.Logic
{
    public partial class TexasHoldemTable
    {
        protected abstract class TexasHoldemRoutine : BaseGameRoutine
        {
            public new TexasHoldemTable Table { get; protected set; }

            public TexasHoldemRoutine(TexasHoldemTable table, TableState newState)
                : base(table, newState)
            {
                Table = table;
            }
        }
    }
}


text:
import * as bluebird from "bluebird";
import * as _ from "lodash";
import { UnknownState } from "../errors";
import { IVoxaIntentEvent } from "../VoxaEvent";
import { IVoxaReply } from "../VoxaReply";
import { State } from "./State";
import { ITransition, SystemTransition } from "./transitions";

export type IStateMachineCb = (
  event: IVoxaIntentEvent,
  reply: IVoxaReply,
  transition: ITransition,
) => Promise<ITransition>;

export type IUnhandledStateCb = (
  event: IVoxaIntentEvent,
  stateName: string,
) => Promise<ITransition>;

export type IOnBeforeStateChangedCB = (
  event: IVoxaIntentEvent,
  reply: IVoxaReply,
  state: State,
) => Promise<void>;

export interface IStateMachineConfig {
  states: State[];
  onBeforeStateChanged?: IOnBeforeStateChangedCB[];
  onAfterStateChanged?: IStateMachineCb[];
  onUnhandledState?: IUnhandledStateCb;
}
export class StateMachine {
  public states: State[];
  public currentState!: State;
  public onBeforeStateChangedCallbacks: IOnBeforeStateChangedCB[];
  public onAfterStateChangeCallbacks: IStateMachineCb[];
  public onUnhandledStateCallback?: IUnhandledStateCb;

  constructor(config: IStateMachineConfig) {
    this.states = _.cloneDeep(config.states);
    this.onBeforeStateChangedCallbacks = config.onBeforeStateChanged || [];
    this.onAfterStateChangeCallbacks = config.onAfterStateChanged || [];
    this.onUnhandledStateCallback = config.onUnhandledState;

    this.states.push(new State("die", { flow: "terminate" }));
  }

  public async runTransition(
    fromState: string,
    voxaEvent: IVoxaIntentEvent,
    reply: IVoxaReply,
    recursions: number = 0,
  ): Promise<SystemTransition> {
    if (recursions > 10) {
      throw new Error("State Machine Recursion Error");
    }

    const transition = await this.stateTransition(
      fromState,
      voxaEvent,
      reply,
      recursions,
    );

    let sysTransition = await this.checkOnUnhandledState(
      voxaEvent,
      reply,
      transition,
    );

    sysTransition = await this.onAfterStateChanged(
      voxaEvent,
      reply,
      sysTransition,
    );

    if (sysTransition.shouldTerminate) {
      reply.terminate();
    }

    if (sysTransition.shouldContinue) {
      return this.runTransition(
        sysTransition.to,
        voxaEvent,
        reply,
        recursions + 1,
      );
    }

    return sysTransition;
  }

  private async stateTransition(
    fromState: string,
    voxaEvent: IVoxaIntentEvent,
    reply: IVoxaReply,
    recursions: number,
  ): Promise<ITransition> {
    try {
      if (fromState === "entry") {
        this.currentState = this.getCurrentState(
          voxaEvent.intent.name,
          voxaEvent.intent.name,
          voxaEvent.platform.name,
        );
      } else {
        this.currentState = this.getCurrentState(
          fromState,
          voxaEvent.intent.name,
          voxaEvent.platform.name,
        );
      }
    } catch (error) {
      /*
       * Returning to the global handler here only makes sense if we didn't already made that,
       * meaning that it could only be done in the first recursion. There's tests covering this scenario
       * in tests/States.spec.ts
       */
      if (fromState !== "entry" && recursions < 1) {
        return this.stateTransition("entry", voxaEvent, reply, recursions);
      }

      if (error instanceof UnknownState) {
        if (!this.onUnhandledStateCallback) {
          throw new Error(`${voxaEvent.intent.name} went unhandled`);
        }

        return this.onUnhandledStateCallback(voxaEvent, voxaEvent.intent.name);
      }

      throw error;
    }

    await this.runOnBeforeStateChanged(voxaEvent, reply);

    let transition: ITransition = await this.currentState.handle(voxaEvent);

    voxaEvent.log.debug(`${this.currentState.name} transition resulted in`, {
      transition,
    });

    try {
      if (!transition && fromState !== "entry") {
        this.currentState = this.getCurrentState(
          voxaEvent.intent.name,
          voxaEvent.intent.name,
          voxaEvent.platform.name,
        );

        transition = await this.currentState.handle(voxaEvent);
      }
    } catch (error) {
      if (error instanceof UnknownState) {
        return transition;
      }

      throw error;
    }

    return transition;
  }

  private async onAfterStateChanged(
    voxaEvent: IVoxaIntentEvent,
    reply: IVoxaReply,
    transition: SystemTransition,
  ): Promise<SystemTransition> {
    voxaEvent.log.debug("Running onAfterStateChangeCallbacks");
    await bluebird.mapSeries(this.onAfterStateChangeCallbacks, (fn) => {
      return fn(voxaEvent, reply, transition);
    });

    voxaEvent.log.debug("Transition is now", { transition });
    return transition;
  }

  private async checkOnUnhandledState(
    voxaEvent: IVoxaIntentEvent,
    reply: IVoxaReply,
    transition: ITransition,
  ): Promise<SystemTransition> {
    if (!_.isEmpty(transition) || transition) {
      return new SystemTransition(transition);
    }

    if (!this.onUnhandledStateCallback) {
      throw new Error(`${voxaEvent.intent.name} went unhandled`);
    }

    const tr = await this.onUnhandledStateCallback(
      voxaEvent,
      this.currentState.name,
    );

    return new SystemTransition(tr);
  }

  private async runOnBeforeStateChanged(
    voxaEvent: IVoxaIntentEvent,
    reply: IVoxaReply,
  ) {
    const onBeforeState = this.onBeforeStateChangedCallbacks;
    voxaEvent.log.debug("Running onBeforeStateChanged");

    await bluebird.mapSeries(onBeforeState, (fn: IOnBeforeStateChangedCB) => {
      return fn(voxaEvent, reply, this.currentState);
    });
  }

  private getCurrentState(
    currentStateName: string,
    intentName: string,
    platform: string,
  ): State {
    const states: State[] = _(this.states)
      .filter({ name: currentStateName })
      .filter((s: State) => {
        return s.platform === platform || s.platform === "core";
      })
      // Sometimes a user might have defined more than one controller for the same state,
      // in that case we want to get the one for the current intent
      .filter((s: State) => {
        return s.intents.length === 0 || _.includes(s.intents, intentName);
      })
      .value();

    if (states.length === 0) {
      throw new UnknownState(currentStateName);
    }

    return states[0];
  }
}


text:
export default class TextureManager {
    constructor(gl, textureConfig) {
        this.gl = gl;
        this.config = textureConfig;
        this.textures = {};
    }

    async initialize() {
        let loaded = await Promise.all(Object.keys(this.config).map(n => this.loadTexture(n, this.config[n])));

        for (let t of loaded) {
            this.textures[t.name] = t.texture;
        }
    }

    async loadTexture(name, path) {
        return new Promise((resolve, reject) => {
            let texture = this.gl.createTexture();
            texture.image = new Image();
            texture.image.onload = () => {
                this.onLoadTexture(texture);
                resolve({ name, texture });
            };

            texture.image.src = path;
        });
    }

    getTexture(name) {
        return this.textures[name];
    }

    /**
     * Configures the freshly loaded texture.
     * http://learningwebgl.com/blog/?p=507
     * @param {object} texture Texture data.
     */
    onLoadTexture(texture) {
        this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, true);
        this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
        this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, texture.image);
        this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.NEAREST);
        this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.NEAREST);
        this.gl.bindTexture(this.gl.TEXTURE_2D, null);
    }
}