text:
package kafka.perf.producer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

import kafka.javaapi.message.ByteBufferMessageSet;
import kafka.message.Message;
import kafka.javaapi.producer.SyncProducer;
import kafka.producer.SyncProducerConfig;

public class Producer extends Thread
{
  private final SyncProducer producer;
  private final String topic;
  private final int messageSize;
  private AtomicLong bytesSent =  new AtomicLong(0L);
  private AtomicLong messagesSent =  new AtomicLong(0L);
  private AtomicLong lastReportMessageSent = new AtomicLong(System.currentTimeMillis());
  private AtomicLong lastReportBytesSent = new AtomicLong(System.currentTimeMillis());
  private String procudername;
  private int batchSize;
  private int numParts;

  public Producer(String topic, String kafkaServerURL, int kafkaServerPort,
                  int kafkaProducerBufferSize, int connectionTimeOut, int reconnectInterval,
                  int messageSize, String name, int batchSize, int numParts)
  {
    super(name);
    Properties props = new Properties();
    props.put("host", kafkaServerURL);
    props.put("port", String.valueOf(kafkaServerPort));
    props.put("buffer.size", String.valueOf(kafkaProducerBufferSize));
    props.put("connect.timeout.ms", String.valueOf(connectionTimeOut));
    props.put("reconnect.interval", String.valueOf(reconnectInterval));
    producer = new SyncProducer(new SyncProducerConfig(props));
    this.topic = topic;

    this.messageSize = messageSize;
    procudername = name;
    this.batchSize = batchSize;
    this.numParts = numParts;
  }

  public void run() {
    Random random = new Random();
    while(true)
    {
      List<Message> messageList = new ArrayList<Message>();
      for(int i = 0; i < batchSize; i++)
      {
        Message message = new Message(new byte[messageSize]);
        messageList.add(message);
      }
      ByteBufferMessageSet set = new ByteBufferMessageSet(messageList);
      producer.send(topic, random.nextInt(numParts), set);
      bytesSent.getAndAdd(batchSize * messageSize);
      messagesSent.getAndAdd(messageList.size());
    }
  }

  public double getMessagesSentPs()
  {
    double val = (double)messagesSent.get() / (System.currentTimeMillis() - lastReportMessageSent.get());
    return val * 1000;
  }

  public String getProducerName()
  {
    return procudername;
  }

  public double getMBytesSentPs()
  {
    double val = ((double)bytesSent.get() / (System.currentTimeMillis() - lastReportBytesSent.get())) / (1024*1024);
    return val * 1000;
  }
}

redpajama_set_name: RedPajamaGithub


text:
layout: inner
title: About
permalink: /about/
---

## About me
--

I am a visual artist based in Stockholm working with live video, stage lighting and architectural lighting. My mediums are print, installation, live performance and online exhibition of media artworks.

My aesthetic inquiry is strongly associated with the tools of real-time video. Often, my works display an exploration of the vivid colors of the digital sphere, while at the same time searching for the frontier between video and plain light moving in time. My primary method is a combination of custom interfacing software, Ableton Live, GL shaders and digital visual feedback.

<p class="text-center">
{% include contact.html %}
</p>
{% include contact-modal.html %}
{% comment %}

<!-- _I am currently looking for collaborating with music festivals and artists, where I offer synchronized lighting and real-time video. Contact me with the form below if you have suggestions. Upon sending, you will get a confirmation._
 -->

<!-- ### Why?
__The workflows__ of producing visual and audible content have historically been very different. Whereas music is essentially real-time - the notion of recorded music is a relatively new one - the experimentation in film and video has been held back by the time and amount of people needed to develop the visual content. This is part of the explanation to why the field of real-time audiovisual media is so underdeveloped in comparison with the separate fields of music and video.

__Nowadays__, with the power of the graphic processing unit, video production can be instant. This opens up new possibilities for the creation of real-time audiovisual media and visual music.

__I believe__ that there is a lot of interesting discoveries to be found within visual accompaniment to _electronic music_. Electronic music, generally characterized by a relatively predictable and stable tempo, is very apt for the kind of spontaneous, conditional visual translation that I am aiming for. Mimicking the tempo in real-time, by means of beatmatching or algorithmic beattracking, enables loops to be utilised with great impact. As long as the loops are played in the same tempo of the music and the intensity of the visual content is manipulated following the music, the result will be at the very least a rhythmical pseudosynaesthetic experience.

__My inquiry__ is based on the question of _what is the most crucial element that constitutes an intuitive visual connection to music_? The answer is of course subjective, but by sufficient inquiry of the immanent, the transcendent can be approached. My method can be said to consist of three parts, _reduction, analysis and synthesis_.

__My main influences__ are the visual music pioneers, i.e. Oskar Fischinger, Viking Eggeling, Jordan Belson, John Whitney, James Whitney and Stan Brakhage. I am also influenced by artists whose work mainly involves light and perception, i.e. Robert Irwin, James Turrell and Olafur Eliasson.

This page was updated 2016-10-19. -->
{% endcomment %}


text:
#include <allegro.h>
#include <stdio.h>
#include <stddef.h>

#include "src/audio/midi.h"
#include "src/game.h"

// Whether the Allegro sound driver is initialized.
int ALLEGRO_SOUND_INITIALIZED = FALSE;

// Displayed alongside the logos when starting the game.
struct song MUSIC_LOGOS = {
    "What is this 2",
    "data\\music\\wit2.mid",
    "Chef Boyardee"
};
// Test music.
struct song MUSIC_WINTER_SONG = {
    "Winter Song",
    "data\\music\\wtsong.mid",
    "Chef Boyardee"
};
struct song MUSIC_WHOA = {
    "Whoa",
    "data\\music\\whoa.mid",
    "Chef Boyardee"
};
struct song MUSIC_IHSWSB = {
    "I_had_Sex_with_Sling_Blade",
    "data\\music\\ihswsb.mid",
    "Chef Boyardee"
};

// Complete list of all music.
struct song *ALL_MUSIC[] = {
    &MUSIC_LOGOS,
    &MUSIC_WINTER_SONG,
    &MUSIC_WHOA,
    &MUSIC_IHSWSB
};

int ALL_MUSIC_AMOUNT = sizeof(ALL_MUSIC) / sizeof(ALL_MUSIC[0]);

MIDI *curr_music;

/**
 * Installs the Allegro sound driver.
 */
int initialize_sound() {
    if (ALLEGRO_SOUND_INITIALIZED == TRUE) {
        return 0;
    }
    if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) {
        // Cannot initialize sound system.
        return ERROR_INIT_SOUND;
    }
    ALLEGRO_SOUND_INITIALIZED = TRUE;
    return 0;
}

/**
 * Initializes a midi file and begins playback.
 * Returns ERROR_INIT_SOUND or ERROR_LOADING_MUSIC on errors.
 */
int music_start(struct song *reqsong) {
    int length, pos;
    int done = 0;

    initialize_sound();

    curr_music = load_midi(reqsong->file);
    if (!curr_music) {
        // Cannot load midi file.
        return ERROR_LOADING_MUSIC;
    }
    length = get_midi_length(curr_music);

    play_midi(curr_music, TRUE);

    return 0;
}

/**
 * Stops midi playback and removes the file from memory.
 */
int music_stop() {
    destroy_midi(curr_music);
    return 0;
}


text:
{
    'name': 'Dates on Sales Order',
    'version': '1.1',
    'category': 'Sales Management',
    'description': """
Add additional date information to the sales order.
===================================================

You can add the following additional dates to a sales order:
------------------------------------------------------------
    * Requested Date (will be used as the expected date on pickings)
    * Commitment Date
    * Effective Date
""",
    'author': 'OpenERP SA',
    'website': 'https://www.odoo.com/page/crm',
    'depends': ['sale_stock'],
    'data': ['sale_order_dates_view.xml'],
    'demo': [],
    'test': ['test/requested_date.yml'],
    'installable': True,
    'auto_install': False,
}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
package org.apache.camel.maven.packaging;

import java.io.File;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.sonatype.plexus.build.incremental.BuildContext;

import static org.apache.camel.maven.packaging.PackageComponentMojo.prepareComponent;
import static org.apache.camel.maven.packaging.PackageDataFormatMojo.prepareDataFormat;
import static org.apache.camel.maven.packaging.PackageLanguageMojo.prepareLanguage;
import static org.apache.camel.maven.packaging.PackageOtherMojo.prepareOthers;

/**
 * Prepares a Camel component analyzing if the maven module contains Camel
 *

 *
components

 *
dataformats

 *
languages

 *
others

 *

 * And for each of those generates extra descriptors and schema files for easier auto-discovery in Camel and tooling.
 */
@Mojo(name = "prepare-components", threadSafe = true)
public class PrepareComponentMojo extends AbstractMojo {

    /**
     * The maven project.
     */
    @Parameter(property = "project", required = true, readonly = true)
    protected MavenProject project;

    /**
     * The output directory for generated components file
     *
     */
    @Parameter(defaultValue = "${project.build.directory}/generated/camel/components")
    protected File componentOutDir;

    /**
     * The output directory for generated dataformats file
     *
     */
    @Parameter(defaultValue = "${project.build.directory}/generated/camel/dataformats")
    protected File dataFormatOutDir;

    /**
     * The output directory for generated languages file
     *
     */
    @Parameter(defaultValue = "${project.build.directory}/generated/camel/languages")
    protected File languageOutDir;

    /**
     * The output directory for generated others file
     *
     */
    @Parameter(defaultValue = "${project.build.directory}/generated/camel/others")
    protected File otherOutDir;

    /**
     * The output directory for generated schema file
     *
     */
    @Parameter(defaultValue = "${project.build.directory}/classes")
    protected File schemaOutDir;

    /**
     * The project build directory
     *
     */
    @Parameter(defaultValue = "${project.build.directory}")
    protected File buildDir;

    /**
     * Maven ProjectHelper.
     */
    @Component
    private MavenProjectHelper projectHelper;

    /**
     * build context to check changed files and mark them for refresh
     * (used for m2e compatibility)
     */
    @Component
    private BuildContext buildContext;

    /**
     * Execute goal.
     *
     * @throws org.apache.maven.plugin.MojoExecutionException execution of the main class or one of the
     *                                                        threads it generated failed.
     * @throws org.apache.maven.plugin.MojoFailureException   something bad happened...
     */
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        int count = 0;
        count += prepareComponent(getLog(), project, projectHelper, buildDir, componentOutDir, buildContext);
        count += prepareDataFormat(getLog(), project, projectHelper, dataFormatOutDir, schemaOutDir, buildContext);
        count += prepareLanguage(getLog(), project, projectHelper, buildDir, languageOutDir, schemaOutDir, buildContext);
        if (count == 0) {
            // okay its not any of the above then its other
            prepareOthers(getLog(), project, projectHelper, otherOutDir, schemaOutDir, buildContext);
        }
    }

}


text:
ReflectionClass::isIterateable()
--CREDITS--
Robin Fernandes <robinf@php.net>
Steve Seear <stevseea@php.net>
--FILE--
<?php
Interface ExtendsIterator extends Iterator {
}
Interface ExtendsIteratorAggregate extends IteratorAggregate {
}
Class IteratorImpl implements Iterator {
	public function next() {}
	public function key() {}
	public function rewind() {}
	public function current() {}
	public function valid() {}
}
Class IterarorAggregateImpl implements IteratorAggregate {
	public function getIterator() {}
}
Class ExtendsIteratorImpl extends IteratorImpl {
}
Class ExtendsIteratorAggregateImpl extends IterarorAggregateImpl {
}
Class A {
}

$classes = array('Traversable', 'Iterator', 'IteratorAggregate', 'ExtendsIterator', 'ExtendsIteratorAggregate',
	  'IteratorImpl', 'IterarorAggregateImpl', 'ExtendsIteratorImpl', 'ExtendsIteratorAggregateImpl', 'A');

foreach($classes as $class) {
	$rc = new ReflectionClass($class);
	echo "Is $class iterable? ";
	var_dump($rc->isIterateable());
}

echo "\nTest invalid params:\n";
$rc = new ReflectionClass('IteratorImpl');
var_dump($rc->isIterateable(null));
var_dump($rc->isIterateable(null, null));
var_dump($rc->isIterateable(1));
var_dump($rc->isIterateable(1.5));
var_dump($rc->isIterateable(true));
var_dump($rc->isIterateable('X'));
var_dump($rc->isIterateable(null));

echo "\nTest static invocation:\n";
ReflectionClass::isIterateable();

?>
--EXPECTF--
Is Traversable iterable? bool(false)
Is Iterator iterable? bool(false)
Is IteratorAggregate iterable? bool(false)
Is ExtendsIterator iterable? bool(false)
Is ExtendsIteratorAggregate iterable? bool(false)
Is IteratorImpl iterable? bool(true)
Is IterarorAggregateImpl iterable? bool(true)
Is ExtendsIteratorImpl iterable? bool(true)
Is ExtendsIteratorAggregateImpl iterable? bool(true)
Is A iterable? bool(false)

Test invalid params:

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 1 given in %s on line 34
NULL

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 2 given in %s on line 35
NULL

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 1 given in %s on line 36
NULL

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 1 given in %s on line 37
NULL

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 1 given in %s on line 38
NULL

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 1 given in %s on line 39
NULL

Warning: ReflectionClass::isIterateable() expects exactly 0 parameters, 1 given in %s on line 40
NULL

Test static invocation:

Fatal error: Non-static method ReflectionClass::isIterateable() cannot be called statically in %s on line 43


text:
class gui_game
{
    public:
        static void create_menu(irr::gui::IGUIEnvironment *gui);
        void create_window(irr::gui::IGUIEnvironment *gui);
};

#endif // GUI_H


text:
package kong.unirest;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class InputStreamPartTest {
    private final InputStreamPart part = new InputStreamPart("uploadFile",
            new ByteArrayInputStream(new byte[]{}),
            "application/xml",
            "foo.xml");

    @Test
    void inputStreamsAreFiles() {
        assertTrue(part.isFile());
    }

    @Test
    void inputStreamPartToString() {
        assertEquals("uploadFile=foo.xml", part.toString());
    }
}


text:
'use strict';

var handlers = require('../handlers');

var dictByName = {};
var dictById = {};
var dictByNameId = {};

module.exports = {
    config: function (server) {
        var io = require('socket.io')(server);

        io.on('connection', function (socket) {
            socket.on('chat message', function (msg) {
                io.emit('chat message', msg);
            });

            socket.on('mass message', function(msg) {
                io.emit('mass message', msg);
            });

            socket.on('moved', function (information) {
                socket.emit('moved', handlers.movement.checkMove(information));
            });

            socket.on('get map', function (userForced) {
                socket.emit('get map', handlers.map.getMapFragment(userForced, dictById));
            });

            socket.on('fight monster', function (information) {
                socket.emit('fight monster', handlers.battle.fightMonster(information));
            });

            socket.on('fight hero', function (information) {
                socket.emit('fight hero', handlers.battle.fightHero(information));
            });

            socket.on('buy troops', function(information) {
                socket.emit('buy troops', handlers.troops.buyTroops(information));
            });

            socket.on('register for events', function (userData) {
                dictByName[userData.name] = socket;
                dictById[userData.id] = socket;
                dictByNameId[socket.id] = userData;
            });

            socket.on('disconnect', function () {
                if (!dictByNameId[socket.id]) {
                    return;
                }
                dictByName[dictByNameId[socket.id].name] = undefined;
                dictById[dictByNameId[socket.id].id] = undefined;
                dictByNameId[socket.id] = undefined;
            });
        });
    },
    byName : dictByName,
    byId : dictById
};


text: Bunch of sass mixins


text:
package org.kuali.rice.krad.datadictionary.validation.constraint;

/**
 * A collection size constraint is one that implements a maximum and minimum number of elements for a collection.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 * @since 1.1
 */
public interface CollectionSizeConstraint extends Constraint {

	public Integer getMaximumNumberOfElements();

	public Integer getMinimumNumberOfElements();

}


text:
package io.gravitee.am.service.model.plugin;

/**
 * @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
 * @author GraviteeSource Team
 */
public class NotifierPlugin extends AbstractPlugin {

    private String displayName;

    private String icon;

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phoma densiuscula Sacc. & Roum.

### Remarks
null


text:
package oldapi;
import java.io.IOException;
import java.util.Iterator;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
public class AverageReducer extends MapReduceBase implements Reducer<Text, DoubleWritable, Text, DoubleWritable> {

	public void reduce(Text key, Iterator<DoubleWritable> values, OutputCollector<Text, DoubleWritable> output, Reporter reporter) throws IOException {
		Double mValue = 0.0;
		int tam = 0;

		while (values.hasNext()) {
			mValue += values.next().get();
			tam++;
		}

		output.collect(key, new DoubleWritable(mValue/tam));
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Linq;

using PHP.Core.AST;
using FcnParam = System.Tuple<System.Collections.Generic.List<PHP.Core.AST.TypeRef>, System.Collections.Generic.List<PHP.Core.AST.ActualParam>, System.Collections.Generic.List<PHP.Core.AST.Expression>>;

namespace PHP.Core.Parsers
{
	#region Helpers

    /// <summary>
    /// Sink for specific language elements.
    /// Methods of this interface are called by the parser.
    /// In this way implementers are notified about declarations already during parsing,
    /// note root AST is not available at this time.
    /// </summary>
	public interface IReductionsSink
	{
		void InclusionReduced(Parser/*!*/ parser, IncludingEx/*!*/ decl);
		void FunctionDeclarationReduced(Parser/*!*/ parser, FunctionDecl/*!*/ decl);
		void TypeDeclarationReduced(Parser/*!*/ parser, TypeDecl/*!*/ decl);
		void GlobalConstantDeclarationReduced(Parser/*!*/ parser, GlobalConstantDecl/*!*/ decl);
        void NamespaceDeclReduced(Parser/*!*/ parser, NamespaceDecl/*!*/ decl);
        void LambdaFunctionReduced(Parser/*!*/ parser, LambdaFunctionExpr/*!*/ decl);
	}

    // Due to a MCS bug, it has to be in the other partial class in generated (Generated/Parser.cs)
    // .. uncomment the following once it is fixed!

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
	public partial struct SemanticValueType
	{
		public override string ToString()
		{
			if (Object != null) return Object.ToString();
			if (Offset != 0) return String.Format("[{0}-{1}]", Offset, Integer);
			if (Double != 0.0) return Double.ToString();
			return Integer.ToString();
		}
	}

	#endregion

	public partial class Parser : ICommentsSink, IScannerHandler
	{
		#region Reductions Sinks

        private sealed class NullReductionsSink : IReductionsSink
		{
			void IReductionsSink.InclusionReduced(Parser/*!*/ parser, IncludingEx/*!*/ incl)
			{
			}

			void IReductionsSink.FunctionDeclarationReduced(Parser/*!*/ parser, FunctionDecl/*!*/ decl)
			{
			}

			void IReductionsSink.TypeDeclarationReduced(Parser/*!*/ parser, TypeDecl/*!*/ decl)
			{
			}

			void IReductionsSink.GlobalConstantDeclarationReduced(Parser/*!*/ parser, GlobalConstantDecl/*!*/ decl)
			{
			}

            void IReductionsSink.NamespaceDeclReduced(Parser parser, NamespaceDecl decl)
            {
            }

            void IReductionsSink.LambdaFunctionReduced(Parser parser, LambdaFunctionExpr decl)
            {
            }
        }

		public sealed class ReductionsCounter : IReductionsSink
		{
			public int InclusionCount { get { return _inclusionCount; } }
			private int _inclusionCount = 0;

			public int FunctionCount { get { return _functionCount; } }
			private int _functionCount = 0;

			public int TypeCount { get { return _typeCount; } }
			private int _typeCount = 0;

			public int ConstantCount { get { return _constantCount; } }
			private int _constantCount = 0;

            void IReductionsSink.InclusionReduced(Parser/*!*/ parser, IncludingEx/*!*/ incl)
			{
				_inclusionCount++;
			}

			void IReductionsSink.FunctionDeclarationReduced(Parser/*!*/ parser, FunctionDecl/*!*/ decl)
			{
				_functionCount++;
			}

			void IReductionsSink.TypeDeclarationReduced(Parser/*!*/ parser, TypeDecl/*!*/ decl)
			{
				_typeCount++;
			}

			void IReductionsSink.GlobalConstantDeclarationReduced(Parser/*!*/ parser, GlobalConstantDecl/*!*/ decl)
			{
				_constantCount++;
			}

            void IReductionsSink.NamespaceDeclReduced(Parser parser, NamespaceDecl decl)
            {
            }

            void IReductionsSink.LambdaFunctionReduced(Parser parser, LambdaFunctionExpr decl)
            {
            }
		}

		#endregion

        protected sealed override int EofToken
		{
			get { return (int)Tokens.EOF; }
		}

		protected sealed override int ErrorToken
		{
			get { return (int)Tokens.ERROR; }
		}

        protected override Text.Span CombinePositions(Text.Span first, Text.Span last)
        {
            if (last.IsValid)
            {
                if (first.IsValid)
                    return Text.Span.Combine(first, last);
                else
                    return last;
            }
            else
                return first;
        }

        protected override Text.Span InvalidPosition
        {
            get
            {
                return Text.Span.Invalid;
            }
        }

		private Scanner scanner;
		private LanguageFeatures features;

		public ErrorSink ErrorSink { get { return errors; } }
		private ErrorSink errors;

		public SourceUnit SourceUnit { get { return sourceUnit; } }
		private SourceUnit sourceUnit;

		private IReductionsSink/*!*/reductionsSink;
		private bool unicodeSemantics;
		private TextReader reader;
		private Scope currentScope;

		public bool AllowGlobalCode { get { return allowGlobalCode; } set { allowGlobalCode = value; } }
		private bool allowGlobalCode;

		/// <summary>
		/// The root of AST.
		/// </summary>
		private GlobalCode astRoot;

		private const int strBufSize = 100;

        private NamespaceDecl currentNamespace;
        private bool IsInGlobalNamespace { get { return currentNamespace == null || currentNamespace.QualifiedName.Namespaces.Length == 0; } }
        private string CurrentNamespaceName { get { return IsInGlobalNamespace ? string.Empty : currentNamespace.QualifiedName.ToString(); } }

        /// <summary>
        /// Special names not namespaced. These names will not be translated using aliases and current namespace.
        /// The list is dynamically extended during parsing with generic arguments.
        /// </summary>
        private readonly HashSet<string>/*!*/reservedTypeNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
        {
            Name.SelfClassName.Value,
            Name.StaticClassName.Value,
            Name.ParentClassName.Value,
        };

		// stack of string buffers; used when processing encaps strings
        private readonly Stack<PhpStringBuilder> strBufStack = new Stack<PhpStringBuilder>(100);

		public Parser()
		{
		}

		private new bool Parse()
		{
			return false;
		}

        public GlobalCode Parse(SourceUnit/*!*/ sourceUnit,
            TextReader/*!*/ reader, ErrorSink/*!*/ errors,
			IReductionsSink reductionsSink, Lexer.LexicalStates initialLexicalState,
			LanguageFeatures features, int positionShift = 0)
		{
			Debug.Assert(reader != null && errors != null);

			// initialization:
            this.sourceUnit = sourceUnit;
            this.errors = errors;
            this.features = features;
            this.reader = reader;
            this.reductionsSink = reductionsSink ?? new NullReductionsSink();
            InitializeFields();

            this.scanner = new Scanner(reader, sourceUnit, errors, this, this, features, positionShift) { CurrentLexicalState = initialLexicalState };
            this.scanner.CurrentLexicalState = initialLexicalState;
			this.currentScope = new Scope(1); // starts assigning scopes from 2 (1 is reserved for prepended inclusion)

			this.unicodeSemantics = (features & LanguageFeatures.UnicodeSemantics) != 0;

			base.Scanner = this.scanner;
			base.Parse();

            GlobalCode result = astRoot;

			// clean and let GC collect unused AST and other stuff:
			ClearFields();

			return result;
		}

		private void InitializeFields()
		{
            InitializeCommentSink();
            strBufStack.Clear();
            condLevel = 0;

            Debug.Assert(sourceUnit != null);

            if (sourceUnit.CurrentNamespace.HasValue && sourceUnit.CurrentNamespace.Value.Namespaces.Length > 0)
            {   // J: inject current namespace from sourceUnit:
                this.currentNamespace = new AST.NamespaceDecl(default(Text.Span), sourceUnit.CurrentNamespace.Value.ToStringList(), true);

                // add aliases into the namespace:
                if (sourceUnit.Naming.Aliases != null)
                    foreach (var alias in sourceUnit.Naming.Aliases)
                        this.currentNamespace.Naming.AddAlias(alias.Key, alias.Value);
            }
            else
            {
                this.currentNamespace = null;
            }
		}

		private void ClearFields()
		{
            ClearCommentSink();

            scanner = null;
			features = 0;
			errors = null;
			sourceUnit = null;
			reductionsSink = null;
			astRoot = null;
			reader = null;
		}

        #region Conditional Code, Scope

		private int condLevel;

		private void EnterConditionalCode()
		{
			condLevel++;
		}

		private void LeaveConditionalCode()
		{
			Debug.Assert(condLevel > 0);
			condLevel--;
		}

		public bool IsCurrentCodeConditional
		{
			get
			{
				return condLevel > 0;
			}
		}

		public bool IsCurrentCodeOneLevelConditional
		{
			get
			{
				return condLevel > 1;
			}
		}

		internal Scope GetScope()
		{
			currentScope.Increment();
			return currentScope;
		}

		#endregion Conditional Code

		#region Complex Productions

        private Expression CreateConcatExOrStringLiteral(Text.Span p, List<Expression> exprs, bool trimEoln)
		{
			PhpStringBuilder encapsed_str = strBufStack.Pop();

			if (trimEoln)
                encapsed_str.TrimEoln();

			if (exprs.Count > 0)
			{
                if (encapsed_str.Length > 0)
                    exprs.Add(encapsed_str.CreateLiteral());

				return new ConcatEx(p, exprs);
			}
            else
            {
                return encapsed_str.CreateLiteral();
            }
		}

        private VariableUse CreateStaticFieldUse(Text.Span span, CompoundVarUse/*!*/ className, CompoundVarUse/*!*/ field)
        {
            return CreateStaticFieldUse(span, new IndirectTypeRef(span, className, TypeRef.EmptyList), field);
        }
        private VariableUse CreateStaticFieldUse(Text.Span span, GenericQualifiedName/*!*/ className, Text.Span classNameSpan, CompoundVarUse/*!*/ field)
        {
            return CreateStaticFieldUse(span, DirectTypeRef.FromGenericQualifiedName(classNameSpan, className), field);
        }
		private VariableUse CreateStaticFieldUse(Text.Span span, TypeRef/*!*/ typeRef, CompoundVarUse/*!*/ field)
		{
			DirectVarUse dvu;
			IndirectVarUse ivu;

			if ((dvu = field as DirectVarUse) != null)
			{
                return new DirectStFldUse(span, typeRef, dvu.VarName, field.Span);
			}
			else if ((ivu = field as IndirectVarUse) != null)
			{
                return new IndirectStFldUse(span, typeRef, ivu.VarNameEx);
			}
			else
			{
				ItemUse iu = (ItemUse)field;
                iu.Array = CreateStaticFieldUse(iu.Array.Span, typeRef, (CompoundVarUse)iu.Array);
				return iu;
			}
		}

		private ForeachStmt/*!*/ CreateForeachStmt(Text.Span pos, Expression/*!*/ enumeree, ForeachVar/*!*/ var1,
		  Text.Span pos1, ForeachVar var2, Statement/*!*/ body)
		{
			ForeachVar key, value;
			if (var2 != null)
			{
				key = var1;
				value = var2;

				if (key.Alias)
				{
					errors.Add(Errors.KeyAlias, SourceUnit, pos1);
					key.Alias = false;
				}
			}
			else
			{
				key = null;
				value = var1;
			}

			return new ForeachStmt(pos, enumeree, key, value, body);
		}

		private void CheckVariableUse(Text.Span span, object item)
		{
			if (item as VariableUse == null)
			{
                errors.Add(FatalErrors.CheckVarUseFault, SourceUnit, span);
                throw new CompilerException();
			}
		}

        private FcnParam/*!*/ CreateFcnParam(FcnParam/*!*/fcnParam, Expression/*!*/arrayDereference)
        {
            var arrayKeyList = fcnParam.Item3;
            if (arrayKeyList == null)
                arrayKeyList = new List<Expression>(1);

            arrayKeyList.Add(arrayDereference);

            return new FcnParam(fcnParam.Item1, fcnParam.Item2, arrayKeyList);
        }

        private static VarLikeConstructUse/*!*/ CreateFcnArrayDereference(Text.Span pos, VarLikeConstructUse/*!*/varUse, List<Expression> arrayKeysExpression)
        {
            if (arrayKeysExpression != null && arrayKeysExpression.Count > 0)
            {
                // wrap fcnCall into ItemUse
                foreach (var keyExpr in arrayKeysExpression)
                    varUse = new ItemUse(pos, varUse, keyExpr, true);
            }

            return varUse;
        }

        private static VarLikeConstructUse/*!*/ DereferenceFunctionArrayAccess(VarLikeConstructUse/*!*/varUse)
        {
            ItemUse itemUse;
            while ((itemUse = varUse as ItemUse) != null && itemUse.IsFunctionArrayDereferencing)
                varUse = itemUse.Array;

            return varUse;
        }

		private static VarLikeConstructUse/*!*/ CreateVariableUse(Text.Span pos, VarLikeConstructUse/*!*/ variable, VarLikeConstructUse/*!*/ property,
                                                           FcnParam parameters, VarLikeConstructUse chain)
		{
			if (parameters != null)
			{
				if (property is ItemUse)
				{
					property.IsMemberOf = variable;
                    property = new IndirectFcnCall(pos, property, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1);
				}
				else
				{
					DirectVarUse direct_use;
					if ((direct_use = property as DirectVarUse) != null)
					{
						QualifiedName method_name = new QualifiedName(new Name(direct_use.VarName.Value), Name.EmptyNames);
                        property = new DirectFcnCall(pos, method_name, null, property.Span, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1);
					}
					else
					{
						IndirectVarUse indirect_use = (IndirectVarUse)property;
                        property = new IndirectFcnCall(pos, indirect_use.VarNameEx, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1);
					}

                    property.IsMemberOf = variable;
                }

                // wrap into ItemUse
                property = CreateFcnArrayDereference(pos, property, parameters.Item3);
            }
			else
			{
				property.IsMemberOf = variable;
			}

			if (chain != null)
			{
				// finds the first variable use in the chain and connects it to the property

				VarLikeConstructUse first_in_chain = chain;
                for (;;)
                {
                    first_in_chain = DereferenceFunctionArrayAccess(first_in_chain);

                    if (first_in_chain.IsMemberOf != null)
                        first_in_chain = first_in_chain.IsMemberOf;
                    else
                        break;
                }

				first_in_chain.IsMemberOf = property;
				return chain;
			}
			else
			{
				return property;
			}
		}

        private static VarLikeConstructUse/*!*/ CreatePropertyVariable(Text.Span pos, CompoundVarUse/*!*/ property, FcnParam parameters)
		{
			if (parameters != null)
			{
				DirectVarUse direct_use;
				IndirectVarUse indirect_use;
                VarLikeConstructUse fcnCall;

				if ((direct_use = property as DirectVarUse) != null)
				{
					QualifiedName method_name = new QualifiedName(new Name(direct_use.VarName.Value), Name.EmptyNames);
                    fcnCall = new DirectFcnCall(pos, method_name, null, property.Span, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1);
				}
                else if ((indirect_use = property as IndirectVarUse) != null)
                {
                    fcnCall = new IndirectFcnCall(pos, indirect_use.VarNameEx, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1);
                }
                else
                {
                    fcnCall = new IndirectFcnCall(pos, (ItemUse)property, (List<ActualParam>)parameters.Item2, (List<TypeRef>)parameters.Item1);
                }

                // wrap fcnCall into ItemUse
                fcnCall = CreateFcnArrayDereference(pos, fcnCall, parameters.Item3);

                return fcnCall;
			}
			else
			{
				return property;
			}
		}

		private static VarLikeConstructUse/*!*/ CreatePropertyVariables(VarLikeConstructUse chain, VarLikeConstructUse/*!*/ member)
		{
            // dereference function array access:
            var element = DereferenceFunctionArrayAccess(member);

            //
            if (chain != null)
			{
                IndirectFcnCall ifc = element as IndirectFcnCall;

				if (ifc != null && ifc.NameExpr as ItemUse != null)
				{
					// we know that FcNAme is VLCU and not Expression, because chain is being parsed:
					((VarLikeConstructUse)ifc.NameExpr).IsMemberOf = chain;
				}
				else
				{
                    element.IsMemberOf = chain;
				}
			}
			else
			{
                element.IsMemberOf = null;
			}

			return member;
		}

        private DirectFcnCall/*!*/ CreateDirectFcnCall(Text.Span pos, QualifiedName qname, Text.Span qnamePosition, List<ActualParam> args, List<TypeRef> typeArgs)
        {
            QualifiedName? fallbackQName;

            TranslateFallbackQualifiedName(ref qname, out fallbackQName, this.CurrentNaming.FunctionAliases);
            return new DirectFcnCall(pos, qname, fallbackQName, qnamePosition, args, typeArgs);
        }

        private GlobalConstUse/*!*/ CreateGlobalConstUse(Text.Span pos, QualifiedName qname)
        {
            QualifiedName? fallbackQName;

            if (qname.IsSimpleName && (qname == QualifiedName.Null || qname == QualifiedName.True || qname == QualifiedName.False))
            {
                // special global consts
                fallbackQName = null;
                qname.IsFullyQualifiedName = true;
            }
            else
            {
                TranslateFallbackQualifiedName(ref qname, out fallbackQName, this.CurrentNaming.ConstantAliases);
            }

            return new GlobalConstUse(pos, qname, fallbackQName);
        }

        /// <summary>
        /// Process <paramref name="qname"/>. Ensure <paramref name="qname"/> will be fully qualified.
        /// Outputs <paramref name="fallbackQName"/> which should be used if <paramref name="qname"/> does not refer to any existing entity.
        /// </summary>
        /// <param name="qname"></param>
        /// <param name="fallbackQName"></param>
        /// <remarks>Used for handling global function call and global constant use.
        /// <param name="aliases">Optional. Dictionary of aliases for the <paramref name="qname"/>.</param>
        /// In PHP entity in current namespace is tried first, then it falls back to global namespace.</remarks>
        private void TranslateFallbackQualifiedName(ref QualifiedName qname, out QualifiedName? fallbackQName, Dictionary<string, QualifiedName> aliases)
        {
            // aliasing
            QualifiedName tmp;
            if (qname.IsSimpleName && aliases != null && aliases.TryGetValue(qname.Name.Value, out tmp))
            {
                qname = tmp;
                fallbackQName = null;
                return;
            }

            //
            qname = TranslateNamespace(qname);

            if (!qname.IsFullyQualifiedName && qname.IsSimpleName &&
                !IsInGlobalNamespace && !sourceUnit.HasImportedNamespaces &&
                !reservedTypeNames.Contains(qname.Name.Value))
            {
                // "\foo"
                fallbackQName = new QualifiedName(qname.Name) { IsFullyQualifiedName = true };

                // "namespace\foo"
                qname = new QualifiedName(qname.Name, currentNamespace.QualifiedName.Namespaces) { IsFullyQualifiedName = true };
            }
            else
            {
                fallbackQName = null;
                qname.IsFullyQualifiedName = true;  // just ensure
            }
        }

		private Expression/*!*/ CheckInitializer(Text.Span pos, Expression/*!*/ initializer)
		{
			if (initializer is ArrayEx)
			{
				errors.Add(Errors.ArrayInClassConstant, SourceUnit, pos);
				return new NullLiteral(pos);
			}

			return initializer;
		}

		private PhpMemberAttributes CheckPrivateType(Text.Span pos)
		{
			if (currentNamespace != null)
			{
				errors.Add(Errors.PrivateClassInGlobalNamespace, SourceUnit, pos);
				return PhpMemberAttributes.None;
			}

			return PhpMemberAttributes.Private;
		}

		private int CheckPartialType(Text.Span pos)
		{
			if (IsCurrentCodeConditional)
			{
				errors.Add(Errors.PartialConditionalDeclaration, SourceUnit, pos);
				return 0;
			}

			if (sourceUnit.IsTransient)
			{
				errors.Add(Errors.PartialTransientDeclaration, SourceUnit, pos);
				return 0;
			}

			if (!sourceUnit.IsPure)
			{
				errors.Add(Errors.PartialImpureDeclaration, SourceUnit, pos);
				return 0;
			}

			return 1;
		}

		private Statement/*!*/ CheckGlobalStatement(Statement/*!*/ statement)
		{
			if (sourceUnit.IsPure && !allowGlobalCode)
			{
				if (!statement.SkipInPureGlobalCode())
					errors.Add(Errors.GlobalCodeInPureUnit, SourceUnit, statement.Span);

				return EmptyStmt.Skipped;
			}

			return statement;
		}

		/// <summary>
		/// Checks whether a reserved class name is used in generic qualified name.
		/// </summary>
		private void CheckReservedNamesAbsence(Tuple<GenericQualifiedName, Text.Span> genericName)
		{
            if (genericName != null)
                CheckReservedNamesAbsence(genericName.Item1, genericName.Item2);
		}

        private void CheckReservedNamesAbsence(GenericQualifiedName genericName, Text.Span span)
        {
            if (genericName.QualifiedName.IsReservedClassName)
            {
                errors.Add(Errors.CannotUseReservedName, SourceUnit, span, genericName.QualifiedName.Name);
            }

            if (genericName.GenericParams != null)
                CheckReservedNamesAbsence(genericName.GenericParams, span);
        }

        private void CheckReservedNamesAbsence(object[] staticTypeRefs, Text.Span span)
        {
            foreach (object static_type_ref in staticTypeRefs)
                if (static_type_ref is GenericQualifiedName)
                    CheckReservedNamesAbsence((GenericQualifiedName)static_type_ref, span);
        }

        private void CheckReservedNamesAbsence(List<Tuple<GenericQualifiedName, Text.Span>> genericNames)
		{
            if (genericNames != null)
            {
                int count = genericNames.Count;
                for (int i = 0; i < count; i++)
                    CheckReservedNamesAbsence(genericNames[i].Item1, genericNames[i].Item2);
            }
		}

		private bool CheckReservedNameAbsence(Name typeName, Text.Span span)
		{
            if (typeName.IsReservedClassName)
            {
                errors.Add(Errors.CannotUseReservedName, SourceUnit, span, typeName);
                return false;
            }

            return true;
		}

        private void CheckTypeNameInUse(Name typeName, Text.Span span)
        {
            var aliases = this.CurrentNaming.Aliases;
            if (reservedTypeNames.Contains(typeName.Value) || (aliases != null && aliases.ContainsKey(typeName.Value)))
                errors.Add(FatalErrors.ClassAlreadyInUse, SourceUnit, span, CurrentNamespaceName + typeName.Value);
        }

        /// <summary>
        /// Check is given <paramref name="declarerName"/> and its <paramref name="typeParams"/> are without duplicity.
        /// </summary>
        /// <param name="typeParams">Generic type parameters.</param>
        /// <param name="declarerName">Type name.</param>
		private void CheckTypeParameterNames(List<FormalTypeParam> typeParams, string/*!*/declarerName)
		{
			if (typeParams == null) return;

            var aliases = this.CurrentNaming.Aliases;

			for (int i = 0; i < typeParams.Count; i++)
			{
				if (typeParams[i].Name.Equals(declarerName))
				{
					ErrorSink.Add(Errors.GenericParameterCollidesWithDeclarer, SourceUnit, typeParams[i].Span, declarerName);
				}
                else if (aliases != null && aliases.ContainsKey(typeParams[i].Name.Value))
                {
                    ErrorSink.Add(Errors.GenericAlreadyInUse, SourceUnit, typeParams[i].Span, typeParams[i].Name.Value);
                }
                else
                {
                    for (int j = 0; j < i; j++)
                    {
                        if (typeParams[j].Name.Equals(typeParams[i].Name))
                            errors.Add(Errors.DuplicateGenericParameter, SourceUnit, typeParams[i].Span);
                    }
                }
			}
		}

		private CustomAttribute.TargetSelectors IdentifierToTargetSelector(Text.Span span, string/*!*/ identifier)
		{
			if (identifier.EqualsOrdinalIgnoreCase("assembly"))
				return CustomAttribute.TargetSelectors.Assembly;

			if (identifier.EqualsOrdinalIgnoreCase("module"))
				return CustomAttribute.TargetSelectors.Module;

            if (identifier.EqualsOrdinalIgnoreCase("return"))
                return CustomAttribute.TargetSelectors.Return;

			errors.Add(Errors.InvalidAttributeTargetSelector, SourceUnit, span, identifier);
			return CustomAttribute.TargetSelectors.Default;
		}

		private List<CustomAttribute>/*!*/CustomAttributes(List<CustomAttribute>/*!*/ attrs, CustomAttribute.TargetSelectors targetSelector)
		{
			for (int i = 0; i < attrs.Count; i++)
				attrs[i].TargetSelector = targetSelector;

			return attrs;
		}

		#endregion

        //#region Imports

        ///// <summary>
        ///// Import of a particular type or function.
        ///// </summary>
        //public void AddImport(Position position, DeclarationKind kind, List<string>/*!*/ names, string aliasName)
        //{
        //    QualifiedName qn = new QualifiedName(names, true, true);
        //    Name alias = (aliasName != null) ? new Name(aliasName) : qn.Name;

        //    switch (kind)
        //    {
        //        case DeclarationKind.Type:
        //            if (!sourceUnit.AddTypeAlias(qn, alias))
        //                errors.Add(Errors.ConflictingTypeAliases, SourceUnit, position);
        //            break;

        //        case DeclarationKind.Function:
        //            if (!sourceUnit.AddFunctionAlias(qn, alias))
        //                errors.Add(Errors.ConflictingFunctionAliases, SourceUnit, position);
        //            break;

        //        case DeclarationKind.Constant:
        //            if (!sourceUnit.AddConstantAlias(qn, alias))
        //                errors.Add(Errors.ConflictingConstantAliases, SourceUnit, position);
        //            break;
        //    }
        //}

        ///// <summary>
        ///// Import of a namespace with a qualified name.
        ///// </summary>
        //public void AddImport(List<string>/*!*/ namespaceNames)
        //{
        //    sourceUnit.AddImportedNamespace(new QualifiedName(namespaceNames, false, true));
        //}

        ///// <summary>
        ///// Import of a namespace with a simple name.
        ///// </summary>
        //public void AddImport(string namespaceName)
        //{
        //    sourceUnit.AddImportedNamespace(new QualifiedName(Name.EmptyBaseName, new Name[] { new Name(namespaceName) }));
        //}
        public void AddImport(QualifiedName namespaceName)
        {
            if (sourceUnit.IsPure)
            {
                ErrorSink.Add(Warnings.ImportDeprecated, SourceUnit, this.yypos);   // deprecated statement

                sourceUnit.ImportedNamespaces.Add(namespaceName);
            }
            else
            {
                ErrorSink.Add(Errors.ImportOnlyInPureMode, sourceUnit, this.yypos); // does actually not happen, since T_IMPORT is not recognized outside Pure mode at all
            }
        }

        //#endregion

        #region aliases (use_statement)

        /// <summary>
        /// Dictionary of PHP aliases for the current scope.
        /// </summary>
        private NamingContext/*!*/ CurrentNaming
        {
            get
            {
                return (currentNamespace != null) ? currentNamespace.Naming : this.sourceUnit.Naming;
            }
        }

        private void AddAliases(List<KeyValuePair<string, QualifiedName>>/*!*/list)
        {
            foreach (var pair in list)
                AddAlias(pair.Value, pair.Key);
        }

        private void AddFunctionAliases(List<KeyValuePair<string, QualifiedName>>/*!*/list)
        {
            foreach (var pair in list)
                AddFunctionAlias(pair.Value, pair.Key);
        }

        private void AddConstAliases(List<KeyValuePair<string, QualifiedName>>/*!*/list)
        {
            foreach (var pair in list)
                AddConstAlias(pair.Value, pair.Key);
        }

        /// <summary>
        /// Add PHP alias (through <c>use</c> keyword).
        /// </summary>
        /// <param name="fullQualifiedName">Fully qualified aliased name.</param>
        /// <param name="alias">If not null, represents the alias name. Otherwise the last component from <paramref name="fullQualifiedName"/> is used.</param>
        private void AddAlias(QualifiedName fullQualifiedName, string alias)
        {
            Debug.Assert(!string.IsNullOrEmpty(fullQualifiedName.Name.Value));
            Debug.Assert(fullQualifiedName.IsFullyQualifiedName);

            //
            alias = alias ?? fullQualifiedName.Name.Value;

            // check if it aliases itself:
            QualifiedName qualifiedAlias = new QualifiedName(
                new Name(alias),
                (currentNamespace != null) ? currentNamespace.QualifiedName : new QualifiedName(Name.EmptyBaseName));

            if (fullQualifiedName == qualifiedAlias) return;    // ignore

            // add the alias:
            var naming = this.CurrentNaming;

            // check for alias duplicity and add the alias:
            // TODO: check if there is no conflict with some class declaration (this should be in runtime ... but this overriding looks like useful features)
            if (reservedTypeNames.Contains(alias) || !naming.AddAlias(alias, fullQualifiedName))
            {
                errors.Add(FatalErrors.AliasAlreadyInUse, this.sourceUnit, this.yypos/*TODO: position of the alias itself*/, fullQualifiedName.NamespacePhpName, alias);
            }
        }

        private void AddFunctionAlias(QualifiedName qname, string alias)
        {
            alias = alias ?? qname.Name.Value;
            if (!this.CurrentNaming.AddFunctionAlias(alias, qname))
            {
                errors.Add(FatalErrors.AliasAlreadyInUse, this.sourceUnit, this.yypos/*TODO: position of the alias itself*/, qname.NamespacePhpName, alias);
            }
        }

        private void AddConstAlias(QualifiedName qname, string alias)
        {
            alias = alias ?? qname.Name.Value;
            if (!this.CurrentNaming.AddConstantAlias(alias, qname))
            {
                errors.Add(FatalErrors.AliasAlreadyInUse, this.sourceUnit, this.yypos/*TODO: position of the alias itself*/, qname.NamespacePhpName, alias);
            }
        }

        private void ReserveTypeNames(List<FormalTypeParam> typeParams)
        {
            if (typeParams == null) return;
            foreach (var param in typeParams)
                reservedTypeNames.Add(param.Name.Value);
        }
        private void UnreserveTypeNames(List<FormalTypeParam> typeParams)
        {
            if (typeParams == null) return;
            foreach (var param in typeParams)
                reservedTypeNames.Remove(param.Name.Value);
        }

        /// <summary>
        /// Transforms each item of <paramref name="qnameList"/> using <see cref="TranslateAny(QualifiedName)"/> function.
        /// </summary>
        /// <param name="qnameList">List of qualified names.</param>
        /// <returns>Reference to <paramref name="qnameList"/>.</returns>
        private List<QualifiedName> TranslateAny(List<QualifiedName> qnameList)
        {
            for (int i = 0; i < qnameList.Count; i++)
                qnameList[i] = TranslateAny(qnameList[i]);

            return qnameList;
        }

        /// <summary>
        /// Translate the name using defined aliases. Any first part of the <see cref="QualifiedName"/> will be translated.
        /// </summary>
        /// <param name="qname">The name to translate.</param>
        /// <returns>Translated qualified name.</returns>
        /// <remarks>Fully qualified names are not translated.</remarks>
        private QualifiedName TranslateAny(QualifiedName qname)
        {
            if (qname.IsFullyQualifiedName) return qname;

            // skip special names:
            if (qname.IsSimpleName)
            {
                if (reservedTypeNames.Contains(qname.Name.Value))
                    return qname;
            }

            // return the alias if found:
            return TranslateAlias(qname);
        }

        /// <summary>
        /// Translate the name using defined aliases. Only namespace part of the <see cref="QualifiedName"/> will be translated. The <see cref="QualifiedName.Name"/> part will not.
        /// </summary>
        /// <param name="qname">The name to translate.</param>
        /// <returns>Translated qualified name.</returns>
        /// <remarks>Fully qualified names are not translated.</remarks>
        private QualifiedName TranslateNamespace(QualifiedName qname)
        {
            if (qname.IsFullyQualifiedName)
            {
                return qname;
            }

            if (qname.IsSimpleName)
            {
                // no namespace part, return not fully qualified simple name (function or constant), has to be handled during analysis:
                return qname;
            }
            else
            {
                return TranslateAlias(qname);
            }
        }

        /// <summary>
        /// Translate first part of given <paramref name="qname"/> into aliased <see cref="QualifiedName"/>.
        /// If no such alias is found, return original <paramref name="qname"/>.
        /// </summary>
        /// <param name="qname">Name which first part has tobe translated.</param>
        /// <returns>Translated <see cref="QualifiedName"/>.</returns>
        /// <remarks>Always returns fully qualified name.</remarks>
        private QualifiedName TranslateAlias(QualifiedName qname)
        {
            Debug.Assert(!qname.IsFullyQualifiedName);

            return QualifiedName.TranslateAlias(
                qname,
                this.CurrentNaming.Aliases,
                (IsInGlobalNamespace || sourceUnit.HasImportedNamespaces) ? (QualifiedName?)null : currentNamespace.QualifiedName);  // do not use current namespace, if there are imported namespace ... will be resolved later
        }

        #endregion

        #region Helpers

        private static readonly List<Tuple<GenericQualifiedName, Text.Span>> emptyGenericQualifiedNamePositionList = new List<Tuple<GenericQualifiedName, Text.Span>>();
		private static readonly List<FormalParam> emptyFormalParamListIndex = new List<FormalParam>();
		private static readonly List<ActualParam> emptyActualParamListIndex = new List<ActualParam>();
		private static readonly List<Expression> emptyExpressionListIndex = new List<Expression>();
		private static readonly List<Item> emptyItemListIndex = new List<Item>();
		private static readonly List<NamedActualParam> emptyNamedActualParamListIndex = new List<NamedActualParam>();
		private static readonly List<FormalTypeParam> emptyFormalTypeParamList = new List<FormalTypeParam>();

        private static List<T>/*!*/ListAdd<T>(object list, object item)
        {
            Debug.Assert(list is List<T>);
            //Debug.Assert(item is T);

            var tlist = (List<T>)list;

            if (item is T)
            {
                tlist.Add((T)item);
            }
            else if (item != null)
            {
                Debug.Assert(item is List<T>);
                tlist.AddRange((List<T>)item);
            }

            return tlist;
        }

        private static object/*!*/StatementListAdd(object/*!*/listObj, object itemObj)
        {
            Debug.Assert(listObj is List<Statement>);

            if (!object.ReferenceEquals(itemObj, null))
            {
                Debug.Assert(itemObj is Statement);

                var list = (List<Statement>)listObj;
                var stmt = (Statement)itemObj;

                NamespaceDecl nsitem;

                // little hack when appending statement after simple syntaxed namespace:

                // namespace A;
                // foo();   // <-- add this statement into namespace A

                if (list.Count != 0 && (nsitem = list.Last() as NamespaceDecl) != null && nsitem.IsSimpleSyntax && !(stmt is NamespaceDecl))
                {
                    // adding a statement after simple namespace declaration => add the statement into the namespace:
                    StatementListAdd(nsitem.Statements, stmt);
                    //nsitem.UpdatePosition(Text.Span.CombinePositions(nsitem.Span, ((Statement)item).Span));
                }
                else
                {
                    list.Add(stmt);
                }
            }

            //
            return listObj;
        }

        private List<Statement>/*!*/StmtList(Text.Span extentFrom, Text.Span extentTo, object/*!*/listObj)
        {
            return StmtList(CombinePositions(extentFrom, extentTo), listObj);
        }

        private List<Statement>/*!*/StmtList(Text.Span extent, object/*!*/listObj)
        {
            var list = (List<Statement>)listObj;
            _docList.Merge(extent, list);

            return list;
        }

        private T AnnotateDoc<T>(T declstmt)
        {
            _docList.Annotate((IDeclarationElement)declstmt);
            return declstmt;
        }

        private Text.Span Combine(Text.Span first, Text.Span second)
        {
            return Text.Span.Combine(first, second);
        }

        private Text.Span Combine(Text.Span start, Text.Span optEnd1, Text.Span optEnd2, Text.Span end)
        {
            if (optEnd1.IsValid) end = optEnd1;
            else if (optEnd2.IsValid) end = optEnd2;

            return Combine(start, end);
        }

        private static List<T>/*!*/NewList<T>(T item)
		{
			return new List<T>(1){ item };
        }

		private static List<T>/*!*/NewList<T>(object item)
		{
            return NewList<T>((T)item);
		}

        private static int GetHeadingEnd(Text.Span lastNonBodySymbolPosition)
        {
            return lastNonBodySymbolPosition.End;
        }

        private static int GetBodyStart(Text.Span bodyPosition)
        {
            return bodyPosition.Start;
        }

        /// <summary>
        /// Handles token that is not valid PHP class/namespace name token in PHP,
        /// but can be used from referenced C# library.
        /// </summary>
        /// <param name="span">Token position.</param>
        /// <param name="token">Token text.</param>
        /// <returns>Text of the token.</returns>
        private string CSharpNameToken(Text.Span span, string token)
        {
            // TODO: move to scanner

            // get token string:
            //string token = this.scanner.GetTokenString(position);

            if (token == null)
                throw new ArgumentNullException("token");

            // report syntax error if C# names are not allowed
            if ((this.features & LanguageFeatures.CSharpTypeNames) == 0)
            {
                this.ErrorSink.Add(FatalErrors.SyntaxError, this.SourceUnit, span, CoreResources.GetString("unexpected_token", token));
            }

            //
            return token;
        }

        /// <summary>
        /// Gets formal parameter flags.
        /// </summary>
        /// <param name="byref">Whether the parameter is prefixed with <c>&</c> character.</param>
        /// <param name="variadic">Whether the parameter is prefixed with <c>...</c>.</param>
        /// <returns>Parameter flags.</returns>
        private static FormalParam.Flags FormalParamFlags(bool byref, bool variadic)
        {
            FormalParam.Flags flags = FormalParam.Flags.Default;

            if (byref) flags |= FormalParam.Flags.IsByRef;
            if (variadic) flags |= FormalParam.Flags.IsVariadic;

            return flags;
        }

		#endregion

        #region Handling PHPDoc: ICommentsSink, IScannerHandler Members

        private ICommentsSink/*!*/_commentSink;
        private IScannerHandler/*!*/_scannerHandler;
        private DocCommentList/*!*/_docList;

        private void InitializeCommentSink()
        {
            _commentSink = ChainForwardCommentSink.ChainSinks(reductionsSink as ICommentsSink, sourceUnit as ICommentsSink);
            _scannerHandler = (sourceUnit as IScannerHandler) ?? new Scanner.NullScannerHandler();
            _docList = new DocCommentList();
        }

        private void ClearCommentSink()
        {
            _commentSink = null;
            _scannerHandler = null;
            _docList = null;
        }

        #region Nested class: ChainCommentsSink

        private abstract class ChainCommentsSink : ICommentsSink
        {
            readonly ICommentsSink/*!*/_next;

            protected ChainCommentsSink(ICommentsSink next)
            {
                _next = next ?? new Scanner.NullCommentsSink();
            }

            #region ICommentsSink Members

            public virtual void OnLineComment(Scanner scanner, Text.TextSpan span)
            {
                _next.OnLineComment(scanner, span);
            }

            public virtual void OnComment(Scanner scanner, Text.TextSpan span)
            {
                _next.OnComment(scanner, span);
            }

            public virtual void OnPhpDocComment(Scanner scanner, PHPDocBlock phpDocBlock)
            {
                _next.OnPhpDocComment(scanner, phpDocBlock);
            }

            public virtual void OnOpenTag(Scanner scanner, Text.TextSpan span)
            {
                _next.OnOpenTag(scanner, span);
            }

            public virtual void OnCloseTag(Scanner scanner, Text.TextSpan span)
            {
                _next.OnCloseTag(scanner, span);
            }

            #endregion
        }

        private sealed class ChainForwardCommentSink : ChainCommentsSink
        {
            readonly ICommentsSink/*!*/_forward;

            private ChainForwardCommentSink(ICommentsSink/*!*/forward, ICommentsSink/*!*/next)
                : base(next)
            {
                _forward = forward;
            }

            public static ICommentsSink/*!*/ChainSinks(ICommentsSink first, ICommentsSink second)
            {
                if (first != null)
                {
                    if (second != null) return new ChainForwardCommentSink(first, second);
                    else return first;
                }

                //
                return second ?? new Scanner.NullCommentsSink();
            }

            public override void OnLineComment(Scanner scanner, Text.TextSpan span)
            {
                _forward.OnLineComment(scanner, span);
                base.OnLineComment(scanner, span);
            }

            public override void OnComment(Scanner scanner, Text.TextSpan span)
            {
                _forward.OnComment(scanner, span);
                base.OnComment(scanner, span);
            }

            public override void OnPhpDocComment(Scanner scanner, PHPDocBlock phpDocBlock)
            {
                _forward.OnPhpDocComment(scanner, phpDocBlock);
                base.OnPhpDocComment(scanner, phpDocBlock);
            }

            public override void OnOpenTag(Scanner scanner, Text.TextSpan span)
            {
                _forward.OnOpenTag(scanner, span);
                base.OnOpenTag(scanner, span);
            }

            public override void OnCloseTag(Scanner scanner, Text.TextSpan span)
            {
                _forward.OnCloseTag(scanner, span);
                base.OnCloseTag(scanner, span);
            }
        }

        private sealed class HandleDocComment : IScannerHandler
        {
            readonly Parser _parser;
            readonly IScannerHandler _next;
            readonly PHPDocBlock _docComment;

            public HandleDocComment(Parser/*!*/parser, PHPDocBlock/*!*/phpDocBlock, IScannerHandler/*!*/next)
            {
                Debug.Assert(parser != null);
                Debug.Assert(phpDocBlock != null);
                Debug.Assert(next != null);

                _parser = parser;
                _docComment = phpDocBlock;
                _next = next;
            }

            #region IScannerHandler Members

            public void OnNextToken(Tokens token, char[] buffer, int tokenStart, int tokenLength)
            {
                if (token != Tokens.T_WHITESPACE)
                {
                    // now we know all the whitespace after the DOC comment
                    _parser._docList.AppendBlock(_docComment, _parser.Scanner.TokenPosition.Start);

                    // remove this handler so it is not called on every IScannerHandler.OnNextToken
                    Debug.Assert(_parser._scannerHandler == this);
                    _parser._scannerHandler = _next;
                }

                _next.OnNextToken(token, buffer, tokenStart, tokenLength);
            }

            #endregion
        }

        #endregion

        void ICommentsSink.OnLineComment(Scanner scanner, Text.TextSpan span)
        {
            _commentSink.OnLineComment(scanner, span);
        }

        void ICommentsSink.OnComment(Scanner scanner, Text.TextSpan span)
        {
            _commentSink.OnComment(scanner, span);
        }

        void ICommentsSink.OnPhpDocComment(Scanner scanner, PHPDocBlock phpDocBlock)
        {
            // handle the next non-whitespace token so we'll know span of the DOC comment including the following whitespace
            _scannerHandler = new HandleDocComment(this, phpDocBlock, _scannerHandler);

            //
            _commentSink.OnPhpDocComment(scanner, phpDocBlock);
        }

        void ICommentsSink.OnOpenTag(Scanner scanner, Text.TextSpan span)
        {
            _commentSink.OnOpenTag(scanner, span);
        }

        void ICommentsSink.OnCloseTag(Scanner scanner, Text.TextSpan span)
        {
            _commentSink.OnCloseTag(scanner, span);
        }

        void IScannerHandler.OnNextToken(Tokens token, char[] buffer, int tokenStart, int tokenLength)
        {
            _scannerHandler.OnNextToken(token, buffer, tokenStart, tokenLength);
        }

        #endregion
	}
}


text:
#ifndef cuda_profiler_H
#define cuda_profiler_H

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Profiler Output Modes
 */
/*DEVICE_BUILTIN*/
typedef enum CUoutput_mode_enum
{
    CU_OUT_KEY_VALUE_PAIR  = 0x00, /**< Output mode Key-Value pair format. */
    CU_OUT_CSV             = 0x01  /**< Output mode Comma separated values format. */
}CUoutput_mode;

/**
 * \ingroup CUDA_DRIVER
 * \defgroup CUDA_PROFILER Profiler Control
 *
 * This section describes the profiler control functions of the low-level CUDA
 * driver application programming interface.
 *
 * @{
 */

/**
 * \brief Initialize the profiling.
 *
 * Using this API user can specify the configuration file, output file and
 * output file format. This API is generally used to profile different set of
 * counters/options by looping the kernel launch. \p configFile parameter can
 * be used to select profiling options including profiler counters/options.
 * Refer the "Command Line Profiler" section in the "Compute Visual
 * Profiler User Guide" for supported profiler options and counters.
 *
 * Configurations defined initially by environment variable settings are overwritten
 * by cuProfilerInitialize().
 *
 * Limitation: Profiling APIs do not work when the application is running with
 * any profiler tool such as Compute Visual Profiler. User must handle error
 * ::CUDA_ERROR_PROFILER_DISABLED returned by profiler APIs if application is
 * likely to be used with any profiler tool.
 *
 * Typical usage of the profiling APIs is as follows:
 *
 * for each set of counters/options\n
 * {\n
 *     cuProfilerInitialize(); //Initialize profiling, set the counters or options in the config file \n
 *     ...\n
 *     cuProfilerStart(); \n
 *     // code to be profiled \n
 *     cuProfilerStop(); \n
 *     ...\n
 *     cuProfilerStart(); \n
 *     // code to be profiled \n
 *     cuProfilerStop(); \n
 *     ...\n
 * }\n
 *
 * \param configFile - Name of the config file that lists the counters/options
 * for profiling.
 * \param outputFile - Name of the outputFile where the profiling results will
 * be stored.
 * \param outputMode - outputMode, can be ::CU_OUT_KEY_VALUE_PAIR or ::CU_OUT_CSV.
 *
 * \return
 * ::CUDA_SUCCESS,
 * ::CUDA_ERROR_INVALID_VALUE,
 * ::CUDA_ERROR_PROFILER_DISABLED
 * \notefnerr
 *
 * \sa ::cuProfilerStart, ::cuProfilerStop
 */
CUresult CUDAAPI cuProfilerInitialize(const char *configFile, const char *outputFile, CUoutput_mode outputMode);

/**
 * \brief Start the profiling.
 *
 * This API starts the profiling for a context if it is not started already.
 * Profiling must be initalized using ::cuProfilerInitialize() before calling
 * this API.
 *
 * cuProfilerStart and cuProfilerStop APIs are used to programmatically control
 * the profiling granularity by allowing profiling to be done only on selective
 * pieces of code.
 *
 *
 * \return
 * ::CUDA_SUCCESS,
 * ::CUDA_ERROR_INVALID_CONTEXT,
 * ::CUDA_ERROR_PROFILER_DISABLED,
 * ::CUDA_ERROR_PROFILER_ALREADY_STARTED,
 * ::CUDA_ERROR_PROFILER_NOT_INITIALIZED
 * \notefnerr
 *
 * \sa ::cuProfilerInitialize, ::cuProfilerStop
 */
CUresult CUDAAPI cuProfilerStart(void);

/**
 * \brief Stop the profiling.
 *
 * This API stops the profiling if it is not stopped already.
 *
 * cuProfilerStart and cuProfilerStop APIs are used to programmatically control
 * the profiling granularity by allowing profiling to be done only on selective
 * pieces of code.
 *
 * \return
 * ::CUDA_SUCCESS,
 * ::CUDA_ERROR_INVALID_CONTEXT,
 * ::CUDA_ERROR_PROFILER_DISABLED,
 * ::CUDA_ERROR_PROFILER_ALREADY_STOPPED,
 * ::CUDA_ERROR_PROFILER_NOT_INITIALIZED
 * \notefnerr
 *
 * \sa ::cuProfilerInitialize, ::cuProfilerStart
 */
CUresult CUDAAPI cuProfilerStop(void);

/** @} */ /* END CUDA_PROFILER */

#ifdef __cplusplus
};
#endif

#endif


text:
using System;

namespace Telerik.Data.Core.Aggregates
{
    internal class ConstantValueAggregate : AggregateValue
    {
        private object value;
        public ConstantValueAggregate(object value)
        {
            this.value = value;
        }

        protected override object GetValueOverride()
        {
            return this.value;
        }

        protected override void AccumulateOverride(object item)
        {
            throw new NotImplementedException();
        }

        protected override void MergeOverride(AggregateValue childAggregate)
        {
            throw new NotImplementedException();
        }
    }
}


text:
Run all the unit tests of the last published versions of the core plugins against [Seneca](senecajs.org) master.

See the [travis build file](.travis.yml) for a list of the current core plugins (under `env/matrix`).

See [seneca-core-plugins-current](senecajs/seneca-core-plugins-current) for plugin master builds against the current Seneca release (`plugin` tag).


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/header_image"
            android:src="@drawable/ic_default_cover"
            android:scaleType="centerCrop"
            android:layout_width="match_parent"
            android:layout_height="300dp"/>

        <TextView
            android:textAppearance="?android:textAppearanceMedium"
            android:padding="10dp"
            android:text="@string/default_prompt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/click_counter"
            android:padding="20dp"
            android:text="@string/not_tapped"
            android:textAppearance="?android:textAppearanceLarge"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

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

            <Button
                android:id="@+id/left"
                android:text="@string/left"
                android:layout_marginRight="15dp"
                android:layout_marginLeft="15dp"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>

            <Button
                android:id="@+id/right"
                android:text="@string/right"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>
        </LinearLayout>

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

            <EditText
                android:id="@+id/input_edit"
                android:lines="3"
                android:maxLines="5"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

            <CheckBox
                android:id="@+id/focus_check"
                android:layout_weight="0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>

        <TextView
            android:id="@+id/focus_text"
            android:textAppearance="?android:textAppearanceSmall"
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <EditText
            android:hint="@string/steal_focus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</ScrollView>


text:
import sys
import logging

from difflib import unified_diff

from django.test import TestCase

from xml.etree.ElementTree import fromstring, register_namespace

from metashare import test_utils
from metashare.repository.models import resourceInfoType_model, \
    SCHEMA_NAMESPACE, lingualityInfoType_model
from metashare.repository.model_utils import get_root_resources
from metashare.settings import ROOT_PATH, LOG_HANDLER
from metashare.xml_utils import to_xml_string

# Setup logging support.
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(LOG_HANDLER)

class ModelTest(TestCase):
    """
    Tests the import/export properties of the generated object model.
    """

    @classmethod
    def setUpClass(cls):
        LOGGER.info("running '{}' tests...".format(cls.__name__))
        test_utils.set_index_active(False)

    @classmethod
    def tearDownClass(cls):
        test_utils.set_index_active(True)
        LOGGER.info("finished '{}' tests".format(cls.__name__))

    def setUp(self):
        """
        Set up the email test
        """
        test_utils.setup_test_storage()
        _fixture = '{0}/repository/fixtures/testfixture.xml'.format(ROOT_PATH)
        _result = test_utils.import_xml(_fixture)
        self.resource_id = _result.id

    def tearDown(self):
        """
        Clean up the test
        """
        test_utils.clean_resources_db()
        test_utils.clean_storage()

    def testRollbackOnImportError(self):
        """
        Checks that a complete rollback is performed on import error.
        """
        _database = {}
        _models = [x for x in dir(sys.modules['metashare.repository.models'])
          if x.endswith('_model')]

        for _model in _models:
            if hasattr(sys.modules['metashare.repository.models'], _model):
                _inst = getattr(sys.modules['metashare.repository.models'], _model)
                _database[_model] = _inst.objects.count()

        _broken_fixture = '{0}/repository/fixtures/broken.xml'.format(ROOT_PATH)
        self.assertRaises(Exception, test_utils.import_xml, _broken_fixture)

        errors = []
        for _model in _models:
            if hasattr(sys.modules['metashare.repository.models'], _model):
                _inst = getattr(sys.modules['metashare.repository.models'], _model)
                LOGGER.info("Testing rollback for %s ...", _model)
                if _database[_model] != _inst.objects.count():
                    errors.append(_model)

        self.assertEqual(errors, [])

    def assert_import_equals_export(self, _roundtrip):
        _result = test_utils.import_xml(_roundtrip)
        with open(_roundtrip) as _import_file:
            _import_xml = _import_file.read()
            register_namespace('', SCHEMA_NAMESPACE)
            _import_xml = to_xml_string(fromstring(_import_xml), encoding="utf-8")
        _export_xml = to_xml_string(_result.export_to_elementtree(), encoding="utf-8")
    # cfedermann: uncomment these lines to dump import/export XML to file.
    #
    #with open('/tmp/_import.xml', 'wb') as _out:
    #    _out.write(_import_xml.encode('utf-8'))
    #with open('/tmp/_export.xml', 'wb') as _out:
    #    _out.write(_export_xml.encode('utf-8'))
        diff = '\n'.join(unified_diff(_import_xml.split('\n'), _export_xml.split('\n')))
        self.assertEqual(_import_xml, _export_xml,
             msg='For file {0}, export differs from import:\n{1}'.format(_roundtrip, diff))

    def testImportExportRoundtrip(self):
        """
        Checks that there is no data lost when exporting an imported XML.
        """
        _roundtrip = '{0}/repository/fixtures/roundtrip.xml'.format(ROOT_PATH)
        self.assert_import_equals_export(_roundtrip)

    def testImportExportRoundtrip0(self):
        """
        Checks that there is no data lost when exporting an imported XML.
        """
        _roundtrip = '{0}/repository/fixtures/ILSP10.xml'.format(ROOT_PATH)
        self.assert_import_equals_export(_roundtrip)

    def test_delete_deep(self):
        resource = resourceInfoType_model.objects.get(pk=self.resource_id)
        num_before = lingualityInfoType_model.objects.all().count()
        resource.delete_deep()
        num_after = lingualityInfoType_model.objects.all().count()
        self.assertEquals(num_before - 1, num_after)

    def testImportExportRoundtrip1(self):
        """
        Checks that there is no data lost when exporting an imported XML.
        """
        _roundtrip = '{0}/repository/test_fixtures/ingested-corpus-AudioVideo-French.xml'.format(ROOT_PATH)
        self.assert_import_equals_export(_roundtrip)

    def testImportExportRoundtrip2(self):
        """
        Checks that there is no data lost when exporting an imported XML.
        """
        _roundtrip = '{0}/repository/test_fixtures/internal-lexConcept-Text-Eng.xml'.format(ROOT_PATH)
        self.assert_import_equals_export(_roundtrip)

    def testImportExportRoundtrip3(self):
        """
        Checks that there is no data lost when exporting an imported XML.
        """
        _roundtrip = '{0}/repository/test_fixtures/published-corpus-AudioVideo-English.xml'.format(ROOT_PATH)
        self.assert_import_equals_export(_roundtrip)

    def testImportExportRoundtrip4(self):
        """
        Checks that there is no data lost when exporting an imported XML.
        """
        _roundtrip = '{0}/repository/test_fixtures/published-lexConcept-Audio-EnglishGerman.xml'.format(ROOT_PATH)
        self.assert_import_equals_export(_roundtrip)

class ModelUtilsTest(TestCase):
    """
    Tests for model_utils.py.
    """
    @classmethod
    def setUpClass(cls):
        LOGGER.info("running '{}' tests...".format(cls.__name__))
        test_utils.set_index_active(False)

    @classmethod
    def tearDownClass(cls):
        test_utils.set_index_active(True)
        LOGGER.info("finished '{}' tests".format(cls.__name__))

    def setUp(self):
        """
        Imports a few test resources.
        """
        test_utils.setup_test_storage()
        self.test_res_1 = test_utils.import_xml(
            '{0}/repository/fixtures/testfixture.xml'.format(ROOT_PATH))
        self.test_res_2 = test_utils.import_xml(
            '{0}/repository/fixtures/ILSP10.xml'.format(ROOT_PATH))

    def tearDown(self):
        """
        Cleans the database after a test.
        """
        test_utils.clean_resources_db()
        test_utils.clean_storage()

    def test_get_root_resources(self):
        """
        Tests the `get_root_resources` method.
        """
        # test with no arguments
        self.assertSetEqual(set(), get_root_resources())
        # test with a resource argument
        self.assertSetEqual(set((self.test_res_1,)),
            get_root_resources(self.test_res_1))
        # test with nested model instance
        self.assertSetEqual(set((self.test_res_1,)),
            get_root_resources(self.test_res_1.identificationInfo))
        # test with a more deeply nested model instance
        self.assertSetEqual(set((self.test_res_1,)),
            get_root_resources(*self.test_res_1.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all()))
        # test with twice the same more deeply nested model instance
        self.assertSetEqual(set((self.test_res_1,)),
            get_root_resources(*(list(self.test_res_1.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all())
                + list(self.test_res_1.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all()))))
        # test with two different nested model instances of the same resource
        self.assertSetEqual(set((self.test_res_1,)),
            get_root_resources(*(list(self.test_res_1.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all())
                + list(self.test_res_1.metadataInfo.metadataCreator.all()))))
        # test with two nested model instances of different resources
        self.assertSetEqual(set((self.test_res_1, self.test_res_2)),
            get_root_resources(*(list(self.test_res_1.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all())
                + list(self.test_res_2.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all()))))
        # test with multiple nested model instances of different resources
        self.assertSetEqual(set((self.test_res_1, self.test_res_2)),
            get_root_resources(*(list(self.test_res_1.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all())
                + list(self.test_res_2.resourceComponentType \
                    .as_subclass().corpusMediaType \
                    .corpustextinfotype_model_set.all())
                + list(self.test_res_1.metadataInfo.metadataCreator.all())
                + list(self.test_res_2.contactPerson.all())
                + [self.test_res_1.identificationInfo,
                   self.test_res_2.identificationInfo])))


text:
<?php namespace Tsi\Lutetium\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class BuilderTableUpdateTsiLutetiumPlan extends Migration
{
    public function up()
    {
        Schema::table('tsi_lutetium_plan', function($table)
        {
            $table->string('account_code')->nullable();
            $table->increments('id')->unsigned(false)->change();
        });
    }

    public function down()
    {
        Schema::table('tsi_lutetium_plan', function($table)
        {
            $table->dropColumn('account_code');
            $table->increments('id')->unsigned()->change();
        });
    }
}


text:
/**
 * \file
 * \brief Registering for handler functions to manage cores
 */
/*
 * Copyright (c) 2013, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <coreboot.h>
#include <barrelfish_kpi/types.h>
#include <barrelfish_kpi/cpu.h>

static coreboot_start_fn_t spawn_core_handlers[CPU_TYPE_NUM];

/**
 * Register spawn core handler function for specific cpu type.
 *
 * \param type CPU type
 * \param handler Handler functions
 */
void coreboot_set_spawn_handler(enum cpu_type type, coreboot_start_fn_t handler)
{
    if (type < CPU_TYPE_NUM) {
        spawn_core_handlers[type] = handler;
    }
}

/**
 * \param  cpu_type Get handler for specific cpu type
 * \return Core boot handler function or NULL in case none was registered
 * for that type
 */
coreboot_start_fn_t coreboot_get_spawn_handler(enum cpu_type type) {
    assert(type < CPU_TYPE_NUM);

    if (type >= CPU_TYPE_NUM) {
        return NULL;
    }
    return spawn_core_handlers[type];
}


text:
echo -n "Enter your username: "
read -r username
if [ "$username" = "$USER" ]
then
  echo "Hello $username. How do you feel today?"
else
  echo "You are not $USER! Who are you?"
fi


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Business.Entities
{

    class Subject : BusinessEntity
    {
        private string _Description;
        private int _HoursPerWeek;
        private int _TotalHours;
        private int _PlanID;

        public int PlanID
        {
            get { return _PlanID; }
            set { _PlanID = value; }
        }

        public int TotalHours
        {
            get { return _TotalHours; }
            set { _TotalHours = value; }
        }

        public int HoursPerWeek
        {
            get { return _HoursPerWeek; }
            set { _HoursPerWeek = value; }
        }

        public string Description
        {
            get { return _Description; }
            set { _Description = value; }
        }

    }
}


text:
from __future__ import absolute_import

import datetime
import time
from typing import Any

from django.http import HttpRequest, HttpResponse
from django.utils import timezone
from django.utils.translation import ugettext as _

from zerver.decorator import authenticated_json_post_view
from zerver.lib.actions import get_status_dict, update_user_presence
from zerver.lib.request import has_request_variables, REQ, JsonableError
from zerver.lib.response import json_success, json_error
from zerver.lib.validator import check_bool
from zerver.models import UserActivity, UserPresence, UserProfile

def get_status_list(requesting_user_profile):
    # type: (UserProfile) -> Dict[str, Any]
    return {'presences': get_status_dict(requesting_user_profile),
            'server_timestamp': time.time()}

@has_request_variables
def update_active_status_backend(request, user_profile, status=REQ(),
                                 new_user_input=REQ(validator=check_bool, default=False)):
    # type: (HttpRequest, UserProfile, str, bool) -> HttpResponse
    status_val = UserPresence.status_from_string(status)
    if status_val is None:
        raise JsonableError(_("Invalid status: %s") % (status,))
    else:
        update_user_presence(user_profile, request.client, timezone.now(),
                             status_val, new_user_input)

    ret = get_status_list(user_profile)
    if user_profile.realm.is_zephyr_mirror_realm:
        # In zephyr mirroring realms, users can't see the presence of other
        # users, but each user **is** interested in whether their mirror bot
        # (running as their user) has been active.
        try:
            activity = UserActivity.objects.get(user_profile = user_profile,
                                                query="get_events_backend",
                                                client__name="zephyr_mirror")

            ret['zephyr_mirror_active'] = \
                (activity.last_visit > timezone.now() - datetime.timedelta(minutes=5))
        except UserActivity.DoesNotExist:
            ret['zephyr_mirror_active'] = False

    return json_success(ret)