text:
namespace System.Web.UI.WebControls {
	public delegate void GridViewDeleteEventHandler (object sender, GridViewDeleteEventArgs e);
}
#endif

redpajama_set_name: RedPajamaGithub


text:
package org.spongepowered.lantern.world;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.MemoryDataContainer;
import org.spongepowered.api.entity.living.player.gamemode.GameMode;
import org.spongepowered.api.entity.living.player.gamemode.GameModes;
import org.spongepowered.api.world.DimensionType;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.GeneratorType;
import org.spongepowered.api.world.GeneratorTypes;
import org.spongepowered.api.world.TeleporterAgent;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.WorldBuilder;
import org.spongepowered.api.world.WorldCreationSettings;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.lantern.SpongeImpl;
import org.spongepowered.lantern.world.gen.WorldGeneratorRegistry;

import java.util.Optional;
import java.util.Random;

public class LanternWorldBuilder implements WorldBuilder {

    private String name;
    private long seed;
    private GameMode gameMode;
    private GeneratorType generatorType;
    private DimensionType dimensionType;
    private boolean mapFeaturesEnabled;
    private boolean hardcore;
    private boolean worldEnabled;
    private boolean loadOnStartup;
    private boolean keepSpawnLoaded;
    private DataContainer generatorSettings;
    private ImmutableList<WorldGeneratorModifier> generatorModifiers;
    private boolean pvp;

    public LanternWorldBuilder() {
        reset();
    }

    public LanternWorldBuilder(WorldCreationSettings settings) {
        fill(settings);
    }

    public LanternWorldBuilder(WorldProperties properties) {
        fill(properties);
    }

    @Override
    public LanternWorldBuilder fill(WorldCreationSettings settings) {
        checkNotNull(settings);
        this.name = settings.getWorldName();
        this.seed = settings.getSeed();
        this.gameMode = settings.getGameMode();
        this.generatorType = settings.getGeneratorType();
        this.dimensionType = settings.getDimensionType();
        this.mapFeaturesEnabled = settings.usesMapFeatures();
        this.hardcore = settings.isHardcore();
        this.worldEnabled = settings.isEnabled();
        this.loadOnStartup = settings.loadOnStartup();
        this.keepSpawnLoaded = settings.doesKeepSpawnLoaded();
        this.pvp = settings.isPVPEnabled();
        return this;
    }

    @Override
    public LanternWorldBuilder fill(WorldProperties properties) {
        checkNotNull(properties);
        this.name = properties.getWorldName();
        this.seed = properties.getSeed();
        this.gameMode = properties.getGameMode();
        this.generatorType = properties.getGeneratorType();
        this.dimensionType = properties.getDimensionType();
        this.mapFeaturesEnabled = properties.usesMapFeatures();
        this.hardcore = properties.isHardcore();
        this.worldEnabled = properties.isEnabled();
        this.loadOnStartup = properties.loadOnStartup();
        this.keepSpawnLoaded = properties.doesKeepSpawnLoaded();
        this.pvp = properties.isPVPEnabled();
        return this;
    }

    @Override
    public WorldBuilder name(String name) {
        this.name = name;
        return this;
    }

    @Override
    public WorldBuilder seed(long seed) {
        this.seed = seed;
        return this;
    }

    @Override
    public WorldBuilder gameMode(GameMode gameMode) {
        this.gameMode = gameMode;
        return this;
    }

    @Override
    public WorldBuilder generator(GeneratorType type) {
        this.generatorType = type;
        return this;
    }

    @Override
    public WorldBuilder dimensionType(DimensionType type) {
        this.dimensionType = type;
        return this;
    }

    @Override
    public WorldBuilder usesMapFeatures(boolean enabled) {
        this.mapFeaturesEnabled = enabled;
        return this;
    }

    @Override
    public WorldBuilder hardcore(boolean enabled) {
        this.hardcore = enabled;
        return this;
    }

    @Override
    public WorldBuilder enabled(boolean state) {
        this.worldEnabled = state;
        return this;
    }

    @Override
    public WorldBuilder loadsOnStartup(boolean state) {
        this.loadOnStartup = state;
        return this;
    }

    @Override
    public WorldBuilder keepsSpawnLoaded(boolean state) {
        this.keepSpawnLoaded = state;
        return this;
    }

    @Override
    public WorldBuilder generatorSettings(DataContainer settings) {
        this.generatorSettings = settings;
        return this;
    }

    @Override
    public WorldBuilder generatorModifiers(WorldGeneratorModifier... modifiers) {
        ImmutableList<WorldGeneratorModifier> defensiveCopy = ImmutableList.copyOf(modifiers);
        WorldGeneratorRegistry.getInstance().checkAllRegistered(defensiveCopy);
        this.generatorModifiers = defensiveCopy;
        return this;
    }

    @Override
    public WorldBuilder teleporterAgent(TeleporterAgent agent) {
        // TODO
        return null;
    }

    @Override
    public WorldBuilder pvp(boolean enabled) {
        this.pvp = enabled;
        return this;
    }

    @Override
    public Optional<World> build() throws IllegalStateException {
        final WorldCreationSettings settings = buildSettings();
        SpongeImpl.getGame().getServer().createWorld(settings);
        return SpongeImpl.getGame().getServer().loadWorld(settings.getWorldName());
    }

    @Override
    public WorldCreationSettings buildSettings() throws IllegalStateException {
        return new LanternWorldCreationSettings(this.name, this.worldEnabled, this.loadOnStartup, this.keepSpawnLoaded, this.seed,
                this.gameMode, this.generatorType, this.generatorModifiers, this.mapFeaturesEnabled, this.hardcore, this.dimensionType, this.generatorSettings, this.pvp);
    }

    @Override
    public WorldBuilder reset() {
        this.name = "spongeworld";
        this.seed = new Random().nextLong();
        this.gameMode = GameModes.SURVIVAL;
        this.generatorType = GeneratorTypes.DEFAULT;
        this.dimensionType = DimensionTypes.OVERWORLD;
        this.mapFeaturesEnabled = true;
        this.hardcore = false;
        this.worldEnabled = true;
        this.loadOnStartup = true;
        this.keepSpawnLoaded = false;
        this.generatorSettings = new MemoryDataContainer();
        this.generatorModifiers = ImmutableList.of();
        this.pvp = true;
        return this;
    }
}


text: __author__ = "Maciej Bilas"


text:
@interface Molida : Beef

@end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.planner;

import com.facebook.presto.sql.planner.iterative.IterativeOptimizer;
import com.facebook.presto.sql.planner.iterative.Rule;
import com.facebook.presto.sql.planner.iterative.RuleStats;
import org.weakref.jmx.MBeanExporter;
import org.weakref.jmx.ObjectNames;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import static java.lang.String.format;

public class StatsRecorder
{
    private final Map<Class<?>, RuleStats> stats = new HashMap<>();

    public void registerAll(Collection<Rule<?>> rules)
    {
        for (Rule<?> rule : rules) {
            checkArgument(!rule.getClass().isAnonymousClass());
            stats.put(rule.getClass(), new RuleStats());
        }
    }

    public void record(Rule<?> rule, long nanos, boolean match)
    {
        stats.get(rule.getClass()).record(nanos, match);
    }

    public void recordFailure(Rule<?> rule)
    {
        stats.get(rule.getClass()).recordFailure();
    }

    void export(MBeanExporter exporter)
    {
        for (Map.Entry<Class<?>, RuleStats> entry : stats.entrySet()) {
            verify(!entry.getKey().getSimpleName().isEmpty());
            String name = ObjectNames.builder(IterativeOptimizer.class)
                    .withProperty("rule", entry.getKey().getSimpleName())
                    .build();

            try {
                exporter.export(name, entry.getValue());
            }
            catch (RuntimeException e) {
                throw new RuntimeException(format("Failed to export MBean with name '%s'", name), e);
            }
        }
    }

    void unexport(MBeanExporter exporter)
    {
        for (Class<?> rule : stats.keySet()) {
            String name = ObjectNames.builder(IterativeOptimizer.class)
                    .withProperty("rule", rule.getSimpleName())
                    .build();

            exporter.unexport(name);
        }
    }
}


text:
var _ = require('underscore');
var parsersHelper = require('../lib/ParsersHelper');

var regexImports = /require\(['|"](.+)['|"]\)/;

var foundName = function foundName(nodeName, filepath, isImport) {

  //lib like `mongoose`
  if(nodeName.charAt(0) !== '.' && isImport === true) {
    return nodeName;
  }

  var path = filepath.split('/');
  path = _.initial(path);
  var names = nodeName.split('/');
  var newNames = _.map(names, function(n) {
    if(n === '..') {
      path = _.initial(path);
      return '';
    } else if(n === '.') {
      return '';
    } else {
      return n;
    }
  });
  return path.join('/') + '/' + _.filter(newNames, function(n) {
    return n !== '';
  }).join('/');
};

var foundImports = function foundImports(regexImports, nodes, src, filepath, options) {
  var temp = src;
  var matches = temp.match(regexImports);
  var count = 0;
  var imports = [];
  while(matches !== null) {
    var name = foundName(matches[1], filepath, true);//.split('/');
    //name = name[name.length-1];
    imports.push(name);

    if(nodes[name] === undefined) {
      nodes[name] = parsersHelper.buildNode(name, options);
    }
    count = count + 1;//kill infinite recursion
    if(count < 1000) {
      temp = temp.substr(matches.index + matches[0].length);
      matches = temp.match(regexImports);
    } else {
      matches = null;
    }
  }

  return imports;
};

module.exports = {
  foundNode: function(nodes, src, filepath, options) {
    var name = filepath.split('/');
    name = name[name.length-1].split('.')[0];
    name = foundName(name, filepath);
    var nodeType = 'nodejs';
    imports = foundImports(regexImports, nodes, src, filepath, options);
    nodes[name] = parsersHelper.buildNode(name, options, filepath, src.length, imports, nodeType, src);
    return nodes;
  },
  callbackAfter: function(nodes, options) {
    return nodes;
  }
}


text:
/**
 * Module dependencies
 */
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var syntax = require('./syntax');
var template = require('./templates/build/templates');
var file = require('../../libraries/file');
var log = require('../../libraries/_log');
var minimatch = require('minimatch');
var mkdirp = require('mkdirp');
var MessageFormat = require('../../libraries/MessageFormat');
var digits = require('./digits');
var defer = require('q').defer;
var LDML = { AST: require('../../libraries/LDML/AST') };
var timezones = require('../../IANA/latest');

/**
 * Clean up time zones
 */
var temporaryTimezones = {};
var hasTimezone = true;
for(var i in project.timezones) {
  var timezone = project.timezones[i];
  temporaryTimezones[timezone] = timezones[timezone];
}
timezones = temporaryTimezones;
if(typeof project.timezones === 'undefined' || project.timezones.length === 0) {
  hasTimezone = false;
}

/**
 * Add terminal colors
 */
require('terminal-colors');

/**
 * Compiler
 *
 * @constructor Compiler
 */
var Compiler = function() {
  // default namespace
  this.namespace = 'it';
  // new line
  this.linefeed = '\n';
  // quote
  this.quote = '\'';
  // dot
  this.dot = '.';
  // comma
  this.comma = ',';
  // add
  this.add = ' + ';
  // space
  this.space = ' ';
  // and
  this.and = ' && ';
  // append string
  this.appendString = 'string += ';
};

/**
 * Compile task
 *
 * @return {void}
 * @api public
 */
Compiler.prototype.run = function() {
  var _this = this;

  return this._getLocalizationMap()
    .then(function(localizationsMap) {
      var languagesCount = 0;
      var languagesLength = Object.keys(localizationsMap).length
      var allLocalizations = '';

      if(project.outputFile) {
        throw new TypeError('`outputFile` is no longer in use, please use just `output`.');
      }

      if(!project.output) {
        throw new TypeError('You must define an output in your l10ns.json file.');
      }

      for(var language in localizationsMap) {
        var stringMap = template['LocalizationsMap']({
          localizations: _this._indentSpaces(2, localizationsMap[language])
        });

        var content = template['JavascriptWrapper']({
          hasTimezone: hasTimezone,
          timezones: _this._indentSpaces(2, template['DateTimeZones']({
            timezones: JSON.stringify(timezones)
          })),
          getTimezoneOffsetFunction: _this._indentSpaces(2, template['DateGetTimezoneOffset']()),
          getLongLocalizedGMTFunction: _this._indentSpaces(2, template['DateGetLongLocalizedGMT']()),
          roundUpFunction: _this._indentSpaces(2, template['RoundToFunction']()),
          formatNumberFunction: _this._indentSpaces(2, template['FormatNumberFunction']()),
          functionName: language.GET_LOCALIZATION_STRING_FUNCTION_NAME,
          localizationMap: _this._indentSpaces(2, stringMap),
          functionBlock: _this._indentSpaces(2, template['LocalizationGetter']({
            language: language
          })),
          moduleExportBlock: _this._indentSpaces(2, template['ModuleExportBlock']({
            variableName: 'l'
          }))
        });

        var filePath = project.output + '/' + language + '.js';
        mkdirp.sync(path.dirname(filePath));
        fs.writeFileSync(filePath, content);

        allLocalizations += localizationsMap[language];

        if(languagesCount !== languagesLength - 1) {
          allLocalizations += _this.comma;
          allLocalizations += _this.linefeed;
        }

        languagesCount++;
      }

      var stringMap = template['LocalizationsMap']({
        localizations: _this._indentSpaces(2, allLocalizations)
      });

      var content = template['JavascriptWrapper']({
        hasTimezone: hasTimezone,
        timezones: _this._indentSpaces(2, template['DateTimeZones']({
          timezones: JSON.stringify(timezones)
        })),
        getTimezoneOffsetFunction: _this._indentSpaces(2, template['DateGetTimezoneOffset']()),
        getLongLocalizedGMTFunction: _this._indentSpaces(2, template['DateGetLongLocalizedGMT']()),
        roundUpFunction: _this._indentSpaces(2, template['RoundToFunction']()),
        formatNumberFunction: _this._indentSpaces(2, template['FormatNumberFunction']()),
        functionName: language.GET_LOCALIZATION_STRING_FUNCTION_NAME,
        localizationMap: _this._indentSpaces(2, stringMap),
        functionBlock: _this._indentSpaces(2, template['RequireLocalizations']()),
        moduleExportBlock: _this._indentSpaces(2, template['ModuleExportBlock']({
          variableName: 'requireLocalizations'
        }))
      });

      var filePath = project.output + '/all.js';
      mkdirp.sync(path.dirname(filePath));
      fs.writeFileSync(filePath, content);
    });
};

/**
 * Indent spaces
 *
 * @param {Number} spaces
 * @param {String} string
 * @return {String}
 * @api public
 */

Compiler.prototype._indentSpaces = function(spaces, string) {
  for(var i = 0; i<spaces; i++) {
    string = string.replace(/\n/g, '\n ');
  }
  if(/^[^\s]$/.test(string.charAt(0))) {
    for(var i = 0; i<spaces; i++) {
      string = ' ' + string;
    }
  }

  string = string.replace(/\n\s+\n/g, '\n\n');

  return string;
};

/**
 * Get localization map string.
 *
 * @param {String} language
 * @return {Promise}
 * @resolves {String} String representing a localization map
 * @api private
 */

Compiler.prototype._getLocalizationMap = function() {
  var _this = this, deferred = defer();
  file.readLocalizations()
    .then(function(localizations) {
      var localizationsMap = {};
      var languagesLength = Object.keys(localizations).length;
      var languagesCount = 0;

      if (process.argv.indexOf('--clientOnly') !== -1) {
        var glob = process.argv[process.argv.indexOf('--clientOnly') + 1];
        Object.getOwnPropertyNames(localizations).forEach(function(langIndex) {
          Object.getOwnPropertyNames(localizations[langIndex]).forEach(function(key) {
            var item = localizations[langIndex][key];
            var canDelete = (item.files.filter(function(file) { return minimatch(file, glob); }).length <= 0);
            if (canDelete) {
              delete localizations[langIndex][key];
            }
          });
        });
      }

      for(var language in localizations) {
        var localizationMap = '';
        var localizationsLength = Object.keys(localizations[language]).length;
        var localizationsCount = 0;
        var messageFormat = new MessageFormat(language);

        localizationMap += template['LocalizationKeyValue']({
          key: '__getPluralKeyword',
          value: _this._getPluralGetterFunctionString(messageFormat) + _this.linefeed
        });

        localizationMap += template['LocalizationKeyValue']({
          key: '__getOrdinalKeyword',
          value: _this._getOrdinalGetterFunctionString(messageFormat) + _this.linefeed
        });

        localizationMap += template['LocalizationKeyValue']({
          key: '__numberSymbols',
          value: JSON.stringify(messageFormat.numberSymbols, null, 2).replace(/\'/g, '\\\'').replace(/"/g, '\'') + _this.comma + _this.linefeed
        });

        if(project.currencies) {
          localizationMap += template['LocalizationKeyValue']({
            key: '__currencies',
            value: JSON.stringify(messageFormat.currencies, null, 2).replace(/"/g, '\'') + _this.comma + _this.linefeed
          });

          localizationMap += template['LocalizationKeyValue']({
            key: '__currencyUnitPattern',
            value: JSON.stringify(messageFormat.currencyUnitPattern, null, 2).replace(/"/g, '\'') + _this.comma + _this.linefeed
          });
        }

        if(project.timezones) {
          localizationMap += template['LocalizationKeyValue']({
            key: '__timezones',
            value: JSON.stringify(messageFormat.timezones, null, 2).replace(/"/g, '\'') + _this.comma + _this.linefeed
          });
        }

        for(var numberSystem in messageFormat.decimalPatterns) {
          var pattern = MessageFormat.AST.NumberFormatPattern.parse(messageFormat.decimalPatterns[numberSystem]).positive;
          var metaData = _this._getMetaDataFromDecimalPattern(pattern);
          localizationMap += template['LocalizationKeyValue']({
            key: '__formatStandardNumber__' + numberSystem,
            value: template['FormatStandardNumber']({
              type: metaData.type,
              prefix: pattern.prefix,
              suffix: pattern.suffix,
              roundTo: pattern.rounding,
              percentage: pattern.percentage,
              permille: pattern.permille,
              currency: pattern.currency,
              minimumIntegerDigits: metaData.minimumIntegerDigits,
              maximumIntegerDigits: metaData.maximumIntegerDigits,
              minimumFractionDigits: metaData.minimumFractionDigits,
              maximumFractionDigits: metaData.maximumFractionDigits,
              minimumSignificantDigits: metaData.minimumSignificantDigits,
              maximumSignificantDigits: metaData.maximumSignificantDigits,
              groupSize: pattern.groupSize,
              numberSystem: numberSystem,
              exponent: !pattern.exponent ? null : {
                digits: pattern.exponent.nonAbsentNumbers,
                plusSign: pattern.exponent.showPositiveCharacter
              },
              patternLength: pattern.patternLength,
              paddingCharacter: pattern.paddingCharacter
            })
          }) + _this.comma + _this.linefeed;
        }

        for(var numberSystem in messageFormat.shortFormats) {
          localizationMap += template['LocalizationKeyValue']({
            key: '__shortFormats__' + numberSystem,
            value: JSON.stringify(messageFormat.shortFormats[numberSystem])
          }) + _this.comma + _this.linefeed;
        }

        for(var numberSystem in messageFormat.shortFormatDecimalPatterns) {
          for(var decimalPattern in messageFormat.shortFormatDecimalPatterns[numberSystem]) {
            var pattern = messageFormat.shortFormatDecimalPatterns[numberSystem][decimalPattern];
            var metaData = _this._getMetaDataFromDecimalPattern(pattern);

            localizationMap += template['LocalizationKeyValue']({
              key: '__short__' + numberSystem + '__' + decimalPattern,
              value: template['FormatNumberHelper']({
                roundTo: pattern.rounding,
                minimumIntegerDigits: metaData.minimumIntegerDigits,
                maximumIntegerDigits: metaData.maximumIntegerDigits,
                groupSize: pattern.groupSize,
                language: language,
                numberSystem: numberSystem,
                patternLength: pattern.patternLength,
              })
            }) + _this.comma + _this.linefeed;
          }
        }

        for(var numberSystem in messageFormat.longFormats) {
          localizationMap += template['LocalizationKeyValue']({
            key: '__longFormats__' + numberSystem,
            value: JSON.stringify(messageFormat.longFormats[numberSystem])
          }) + _this.comma + _this.linefeed;
        }

        for(var numberSystem in messageFormat.longFormatDecimalPatterns) {
          for(var decimalPattern in messageFormat.longFormatDecimalPatterns[numberSystem]) {
            var pattern = messageFormat.longFormatDecimalPatterns[numberSystem][decimalPattern];
            var metaData = _this._getMetaDataFromDecimalPattern(pattern);

            localizationMap += template['LocalizationKeyValue']({
              key: '__long__' + numberSystem + '__' + decimalPattern,
              value: template['FormatNumberHelper']({
                roundTo: pattern.rounding,
                minimumIntegerDigits: metaData.minimumIntegerDigits,
                maximumIntegerDigits: metaData.maximumIntegerDigits,
                groupSize: pattern.groupSize,
                numberSystem: numberSystem,
                patternLength: pattern.patternLength,
              })
            }) + _this.comma + _this.linefeed;
          }
        }

        var localizationsCount = 0;
        for(var key in localizations[language]) {
          messageFormat.parse(localizations[language][key].value);
          var _function = template['Function']({
            functionBody: _this._indentSpaces(
              2,
              _this._getFunctionBody(messageFormat.messageAST, language)
            )
          });

          localizationMap += template['LocalizationKeyValue']({
            key: key,
            value: _function
          });

          if(localizationsCount !== localizationsLength - 1) {
            localizationMap += _this.comma;
            localizationMap += _this.linefeed;
          }

          localizationsCount++;
        }

        localizationsMap[language] = template['LocalizationMap']({
          language: language,
          map: _this._indentSpaces(2, localizationMap)
        });
      }

      deferred.resolve(localizationsMap);
    })
    .fail(function(error) {
      deferred.reject(error);
    });

  return deferred.promise;
};

/**
 * Get function body
 *
 * @param {Array} messageAST
 * @return {String} A string representing a function body
 * @api private
 */

Compiler.prototype._getFunctionBody = function(messageAST, language) {
  var result = '';

  for(var index = 0; index < messageAST.length; index++) {
    if(messageAST[index] instanceof MessageFormat.AST.Sentence) {
      result += template['Sentence']({
        sentence: messageAST[index].string
          .replace(/'/g, '\\\'')
          .replace(/\n/g, '\\n')
        });
    }
    else if(messageAST[index] instanceof MessageFormat.AST.Variable) {
      result += template['Variable']({ variableName: messageAST[index].name });
    }
    else if(messageAST[index] instanceof MessageFormat.AST.Remaining) {
      result += this._compileRemaining(messageAST[index], language);
    }
    else if(messageAST[index] instanceof MessageFormat.AST.NumberFormat) {
      result += this._compileNumberFormat(messageAST[index]);
    }
    else if(messageAST[index] instanceof MessageFormat.AST.date.DateFormat) {
      result += this._compileDateFormat(messageAST[index]);
    }
    else if(messageAST[index] instanceof MessageFormat.AST.CurrencyFormat) {
      result += this._compileCurrencyFormat(messageAST[index]);
    }
    else if(messageAST[index] instanceof MessageFormat.AST.PluralFormat) {
      result += this._compilePluralFormat(messageAST[index], language);
    }
    else if(messageAST[index] instanceof MessageFormat.AST.SelectFormat) {
      result += this._compileSelectFormat(messageAST[index]);
    }
    else if(messageAST[index] instanceof MessageFormat.AST.SelectordinalFormat) {
      result += this._compileSelectordinalFormat(messageAST[index], language);
    }

    if(index !== messageAST.length - 1) {
      result += this.linefeed;
    }
  }

  return result;
};

/**
 * Compile remaining
 *
 * @param {AST.Remaining} remaining
 * @param {String} language
 * @return {String}
 * @api private
 */

Compiler.prototype._compileRemaining = function(remaining, language) {
  var pattern = remaining.pattern;
  var minimumIntegerDigits = 0;
  var maximumIntegerDigits = 0;
  var minimumFractionDigits = 0;
  var maximumFractionDigits = 0;
  var minimumSignificantDigits = 0;
  var maximumSignificantDigits = 0;
  var type = 'floating';

  if(pattern instanceof MessageFormat.AST.NumberFormatPattern._SignificantNumberFormat) {
    type = 'significant';
  }

  if(type === 'floating') {
    if(pattern.fraction &&
       typeof pattern.fraction.nonAbsentNumbers === 'number' &&
       typeof pattern.fraction.rightAbsentNumbers === 'number') {
      minimumFractionDigits = pattern.fraction.nonAbsentNumbers;
      maximumFractionDigits = minimumFractionDigits + pattern.fraction.rightAbsentNumbers;
    }
    if(pattern.integer &&
       typeof pattern.integer.nonAbsentNumbers === 'number' &&
       typeof pattern.integer.leftAbsentNumbers === 'number') {
      minimumIntegerDigits = pattern.integer.nonAbsentNumbers;
      maximumIntegerDigits = pattern.integer.nonAbsentNumbers + pattern.integer.leftAbsentNumbers;
    }
  }
  else if(type === 'significant') {
    minimumSignificantDigits = pattern.nonAbsentNumbers;
    maximumSignificantDigits = minimumSignificantDigits + pattern.rightAbsentNumbers;
  }

  result = template['Remaining']({
    variableName: remaining.variable.name,
    type: type,
    offset: remaining.offset,
    prefix: pattern.prefix,
    suffix: pattern.suffix,
    roundTo: pattern.rounding,
    percentage: pattern.percentage,
    permille: pattern.permille,
    currency: false,
    minimumIntegerDigits: minimumIntegerDigits,
    maximumIntegerDigits: maximumIntegerDigits,
    minimumFractionDigits: minimumFractionDigits,
    maximumFractionDigits: maximumFractionDigits,
    minimumSignificantDigits: minimumSignificantDigits,
    maximumSignificantDigits: maximumSignificantDigits,
    groupSize: pattern.groupSize,
    language: language,
    numberSystem: remaining.numberSystem,
    exponent: !pattern.exponent ? null : {
      digits: pattern.exponent.nonAbsentNumbers,
      plusSign: pattern.exponent.plusSign
    },
    patternLength: pattern.patternLength,
    paddingCharacter: pattern.paddingCharacter
  });

  if(remaining.numberSystem !== 'latn') {
    result += this.linefeed + template['ReplaceDigitBlock']({
      variableName: 'string',
      digits: digits[remaining.numberSystem]
    })
  }

  return result;
};

/**
 * Compile number format
 *
 * @param {AST.NumberFormat} numberFormat
 * @return {String}
 * @api private
 */

Compiler.prototype._compileNumberFormat = function(numberFormat) {
  var _this = this;
  var result = '';
  var signs = ['positive', 'negative'];
  var _case = {};

  var Type = MessageFormat.AST.NumberFormat.Type;
  if (numberFormat.type !== Type.DECIMAL) {
    result += 'var numberString = \'\';\n';
    if (numberFormat.type === Type.SHORT) {
      result += template['FormatShortLongNumberFormat']({
        variableName: numberFormat.variable.name,
        type: 'short',
        numberSystem: numberFormat.numberSystem,
        minDigits: numberFormat.minDigits,
      });
    }
    else {
      result += template['FormatShortLongNumberFormat']({
        variableName: numberFormat.variable.name,
        type: 'long',
        numberSystem: numberFormat.numberSystem,
        minDigits: numberFormat.minDigits,
      });
    }

    result += this.linefeed + 'string += numberString;';
    return result;
  }

  signs.forEach(function(sign) {
    var pattern = numberFormat.pattern[sign];
    if(sign === 'negative' && pattern === null) {
      pattern = Object.create(numberFormat.pattern['positive']);
      pattern.prefix = pattern.prefix + '-';
    }
    _case[sign] = _this._getFormatNumberExpressionString(pattern, numberFormat, sign);
  });

  result += 'var numberString = \'\';\n';

  if(numberFormat.pattern['positive'].currency) {
    result += template['SetCurrencyUnitBlock']({
      variableName: numberFormat.variable.name,
      language: numberFormat.language,
      currency: {
        type: numberFormat.pattern['positive'].currency.type,
        context: numberFormat.pattern['positive'].currency.context
      }
    }) + this.linefeed;

    result += template['FormatCurrencyCondition']({
      variableName: numberFormat.variable.name,
      positive: this._indentSpaces(2, _case['positive']),
      negative: this._indentSpaces(2, _case['negative'])
    });
  }
  else {
    result += template['FormatNumberCondition']({
      variableName: numberFormat.variable.name,
      positive: this._indentSpaces(2, _case['positive']),
      negative: this._indentSpaces(2, _case['negative'])
    });
  }

  if(numberFormat.numberSystem !== 'latn') {
    result += this.linefeed + template['ReplaceDigitBlock']({
      variableName: 'numberString',
      digits: digits[numberFormat.numberSystem]
    });
  }

  result += this.linefeed + 'string += numberString;';

  return result;
};

Compiler.prototype._getMetaDataFromDecimalPattern = function(pattern) {
  var minimumIntegerDigits = 0;
  var maximumIntegerDigits = 0;
  var minimumFractionDigits = 0;
  var maximumFractionDigits = 0;
  var minimumSignificantDigits = 0;
  var maximumSignificantDigits = 0;
  var type = 'floating';

  if(pattern instanceof MessageFormat.AST.NumberFormatPattern._SignificantNumberFormat) {
    type = 'significant';
  }

  if(type === 'floating') {
    if(pattern.fraction &&
        typeof pattern.fraction.nonAbsentNumbers === 'number' &&
        typeof pattern.fraction.rightAbsentNumbers === 'number') {
      minimumFractionDigits = pattern.fraction.nonAbsentNumbers;
      maximumFractionDigits = minimumFractionDigits + pattern.fraction.rightAbsentNumbers;
    }
    if(pattern.integer &&
        typeof pattern.integer.nonAbsentNumbers === 'number' &&
        typeof pattern.integer.leftAbsentNumbers === 'number') {
      minimumIntegerDigits = pattern.integer.nonAbsentNumbers;
      maximumIntegerDigits = pattern.integer.nonAbsentNumbers + pattern.integer.leftAbsentNumbers;
    }
  }
  else if(type === 'significant') {
    minimumSignificantDigits = pattern.nonAbsentNumbers;
    maximumSignificantDigits = pattern.nonAbsentNumbers + pattern.rightAbsentNumbers;
  }

  return {
    type: type,
    minimumIntegerDigits: minimumIntegerDigits,
    maximumIntegerDigits: maximumIntegerDigits,
    minimumFractionDigits: minimumFractionDigits,
    maximumFractionDigits: maximumFractionDigits,
    minimumSignificantDigits: minimumSignificantDigits,
    maximumSignificantDigits: maximumSignificantDigits,
  }
}

Compiler.prototype._getFormatNumberExpressionString = function(pattern, numberFormat, sign) {
  var metaData = this._getMetaDataFromDecimalPattern(pattern);
  return 'numberString += ' + template['FormatNumber']({
    variableName: numberFormat.variable.name,
    type: metaData.type,
    prefix: ((sign === 'negative') && (pattern.prefix.indexOf('-') > 0)) ? pattern.prefix.replace('-', ' -') : pattern.prefix,
    suffix: pattern.suffix,
    roundTo: pattern.rounding,
    percentage: pattern.percentage,
    permille: pattern.permille,
    currency: pattern.currency,
    minimumIntegerDigits: metaData.minimumIntegerDigits,
    maximumIntegerDigits: metaData.maximumIntegerDigits,
    minimumFractionDigits: metaData.minimumFractionDigits,
    maximumFractionDigits: metaData.maximumFractionDigits,
    minimumSignificantDigits: metaData.minimumSignificantDigits,
    maximumSignificantDigits: metaData.maximumSignificantDigits,
    groupSize: pattern.groupSize,
    numberSystem: numberFormat.numberSystem,
    exponent: !pattern.exponent ? null : {
      digits: pattern.exponent.nonAbsentNumbers,
      plusSign: pattern.exponent.showPositiveCharacter
    },
    patternLength: pattern.patternLength,
    paddingCharacter: pattern.paddingCharacter
  });
}

/**
 * Compile currency format
 *
 * @param {AST.CurrencyFormat} currencyFormat
 * @return {void}
 * @api private
 */

Compiler.prototype._compileCurrencyFormat = function(currencyFormat) {
  var result = '';
  var signs = ['positive', 'negative'];
  var _case = {};

  signs.forEach(function(sign) {
    var pattern = currencyFormat.pattern[sign];
    if(sign === 'negative' && (pattern === null || currencyFormat.type === 'text')) {
      pattern = Object.create(currencyFormat.pattern['positive']);
      pattern.prefix = pattern.prefix + '-';
      pattern.patternLength++;
    }

    var minimumIntegerDigits = 0;
    var maximumIntegerDigits = 0;
    var minimumFractionDigits = 0;
    var maximumFractionDigits = 0;
    var minimumSignificantDigits = 0;
    var maximumSignificantDigits = 0;
    var type = 'floating';

    if(pattern instanceof MessageFormat.AST.NumberFormatPattern._SignificantNumberFormat) {
      type = 'significant';
    }

    if(type === 'floating') {
      if(pattern.fraction &&
         typeof pattern.fraction.nonAbsentNumbers === 'number' &&
         typeof pattern.fraction.rightAbsentNumbers === 'number') {
        minimumFractionDigits = pattern.fraction.nonAbsentNumbers;
        maximumFractionDigits = minimumFractionDigits + pattern.fraction.rightAbsentNumbers;
      }
      if(pattern.integer &&
         typeof pattern.integer.nonAbsentNumbers === 'number' &&
         typeof pattern.integer.leftAbsentNumbers === 'number') {
        minimumIntegerDigits = pattern.integer.nonAbsentNumbers;
        maximumIntegerDigits = pattern.integer.nonAbsentNumbers + pattern.integer.leftAbsentNumbers;
      }
    }
    else if(type === 'significant') {
      minimumSignificantDigits = pattern.nonAbsentNumbers;
      maximumSignificantDigits = pattern.nonAbsentNumbers + pattern.rightAbsentNumbers;
    }

    if(currencyFormat.type === 'text') {
      pattern.prefix = pattern.prefix.replace(/¤/g, '');
      pattern.suffix = pattern.suffix.replace(/¤/g, '');
    }

    _case[sign] = template['FormatCurrency']({
      variableName: currencyFormat.variable.name,
      type: type,
      prefix: ((sign === 'negative') && (pattern.prefix.indexOf('-') > 0)) ? pattern.prefix.replace('-', ' -') : pattern.prefix,
      suffix: pattern.suffix,
      roundTo: pattern.rounding,
      percentage: pattern.percentage,
      permille: pattern.permille,
      currency: currencyFormat.type,
      minimumIntegerDigits: minimumIntegerDigits,
      maximumIntegerDigits: maximumIntegerDigits,
      minimumFractionDigits: minimumFractionDigits,
      maximumFractionDigits: maximumFractionDigits,
      minimumSignificantDigits: minimumSignificantDigits,
      maximumSignificantDigits: maximumSignificantDigits,
      groupSize: pattern.groupSize,
      language: currencyFormat.language,
      numberSystem: currencyFormat.numberSystem,
      exponent: !pattern.exponent ? null : {
        digits: pattern.exponent.nonAbsentNumbers,
        plusSign: pattern.exponent.showPositiveCharacter
      },
      patternLength: pattern.patternLength,
      paddingCharacter: pattern.paddingCharacter
    });
  });

  result += 'var currencyString = \'\';\n';

  result += template['SetCurrencyUnitBlock']({
    variableName: currencyFormat.variable.name,
    language: currencyFormat.language,
    currency: {
      type: currencyFormat.type,
      context: currencyFormat.context
    }
  }) + this.linefeed;

  if(currencyFormat.type === 'symbol') {
    result += template['FormatCurrencyCondition']({
      variableName: currencyFormat.variable.name,
      positive: this._indentSpaces(2, 'currencyString += ' + _case['positive']),
      negative: this._indentSpaces(2, 'currencyString += ' + _case['negative'])
    });
  }
  else {
    result += template['FormatCurrencyTextCondition']({
      variableName: currencyFormat.variable.name,
      positive: this._indentSpaces(4, _case['positive']),
      negative: this._indentSpaces(4, _case['negative']),
      language: currencyFormat.language,
      currency: {
        type: currencyFormat.type,
        context: currencyFormat.context
      }
    });
  }

  if(currencyFormat.numberSystem !== 'latn') {
    result += this.linefeed + template['ReplaceDigitBlock']({
      variableName: 'currencyString',
      digits: digits[currencyFormat.numberSystem]
    })
  }

  result += this.linefeed + 'string += currencyString;';

  return result;
};

/**
 * Compile date format
 *
 * @param {AST.DateFormat} dateFormat
 * @return {void}
 * @api private
 */

Compiler.prototype._compileDateFormat = function(dateFormat) {
  var _this = this;

  var result = template['SetDateBlock']({
    variableName: dateFormat.variable.name
  });

  result += this.linefeed;

  dateFormat.AST.forEach(function(component) {
    if(component instanceof MessageFormat.AST.date.Sentence) {
      result += template['DateSentence']({
        sentence: component.sentence
      });
    }
    else if(component instanceof MessageFormat.AST.date.Era) {
      var eraFormat;
      switch(component.format) {
        case MessageFormat.AST.date.Era.Formats.ABBREVIATED:
          eraFormat = 'abbreviated';
          break;
        case MessageFormat.AST.date.Era.Formats.WIDE:
          eraFormat = 'full';
          break;
        case MessageFormat.AST.date.Era.Formats.NARROW:
          eraFormat = 'narrow';
          break;
      }
      result += template['DateEra']({
        AD: dateFormat.CLDR.era[eraFormat].AD,
        BC: dateFormat.CLDR.era[eraFormat].BC
      });
    }
    else if(component instanceof MessageFormat.AST.date.year.CalendarYear) {
      result += template['SetYear']() + _this.linefeed;
      result += template['FormatYear']({
        length: component.length
      });
    }
    else if(component instanceof MessageFormat.AST.date.year.WeekBasedYear) {
      result += template['DateWeekBasedYear']({
        startOfWeek: component.startOfWeek
      }) + _this.linefeed;
      result += template['FormatYear']({
        length: component.length
      });
    }
    else if(component instanceof MessageFormat.AST.date.Quarter) {
      var quarterContext;
      var quarterFormat;
      var quarterStrings;

      switch(component.context) {
        case MessageFormat.AST.date.Quarter.Contexts.FORMATED:
          quarterContext = 'formated';
          break;
        case MessageFormat.AST.date.Quarter.Contexts.STAND_ALONE:
          quarterContext = 'standalone';
          break;
      }
      switch(component.format) {
        case MessageFormat.AST.date.Quarter.Formats.NUMERIC:
          quarterStrings = {
            Q1: '1',
            Q2: '2',
            Q3: '3',
            Q4: '4'
          };
          break;
        case MessageFormat.AST.date.Quarter.Formats.NUMERIC_WITH_PADDING:
          quarterStrings = {
            Q1: '01',
            Q2: '02',
            Q3: '03',
            Q4: '04'
          };
          break;
        case MessageFormat.AST.date.Quarter.Formats.ABBREVIATED:
          quarterStrings = dateFormat.CLDR.quarter[quarterContext]['abbreviated'];
          break;
        case MessageFormat.AST.date.Quarter.Formats.WIDE:
          quarterStrings = dateFormat.CLDR.quarter[quarterContext]['wide'];
          break;
      }

      result += template['DateQuarter'](quarterStrings);
    }
    else if(component instanceof MessageFormat.AST.date.Month) {
      var monthContext;
      var monthFormat;
      var monthStrings;

      switch(component.context) {
        case MessageFormat.AST.date.Month.Contexts.FORMATED:
          monthContext = 'formated';
          break;
        case MessageFormat.AST.date.Month.Contexts.STAND_ALONE:
          monthContext = 'standalone';
          break;
      }

      switch(component.format) {
        case MessageFormat.AST.date.Month.Formats.NUMERIC:
          monthStrings = {
            '1': '1',
            '2': '2',
            '3': '3',
            '4': '4',
            '5': '5',
            '6': '6',
            '7': '7',
            '8': '8',
            '9': '9',
            '10': '10',
            '11': '11',
            '12': '12'
          };
          break;
        case MessageFormat.AST.date.Month.Formats.NUMERIC_WITH_PADDING:
          monthStrings = {
            '1': '01',
            '2': '02',
            '3': '03',
            '4': '04',
            '5': '05',
            '6': '06',
            '7': '07',
            '8': '08',
            '9': '09',
            '10': '10',
            '11': '11',
            '12': '12'
          };
          break;
        case MessageFormat.AST.date.Month.Formats.SHORT:
          monthStrings = dateFormat.CLDR.month[monthContext]['abbreviated'];
          break;
        case MessageFormat.AST.date.Month.Formats.WIDE:
          monthStrings = dateFormat.CLDR.month[monthContext]['wide'];
          break;
        case MessageFormat.AST.date.Month.Formats.NARROW:
          monthStrings = dateFormat.CLDR.month[monthContext]['narrow'];
          break;
      }

      result += template['DateMonth']({ monthStrings: monthStrings });
    }
    else if(component instanceof MessageFormat.AST.date.Week) {
      if(component.type === MessageFormat.AST.date.Week.Types.WEEK_OF_YEAR) {
        if(component.format === MessageFormat.AST.date.Week.Formats.NUMERIC) {
          result += template['DateWeekOfYear']({
            startOfWeek: component.startOfWeek,
            padding: false
          });
        }
        else {
          result += template['DateWeekOfYear']({
            startOfWeek: component.startOfWeek,
            padding: true
          });
        }
      }
      else {
        result += template['DateWeekOfMonth']({
          startOfWeek: component.startOfWeek
        });
      }
    }
    else if(component instanceof MessageFormat.AST.date.day.DayOfMonth) {
      if(component.format === MessageFormat.AST.date.day.DayOfMonth.Formats.NUMERIC) {
        result += template['DateDayOfMonth']({});
      }
      else {
        result += template['DateDayOfMonth']({
          padding: true
        });
      }
    }
    else if(component instanceof MessageFormat.AST.date.day.DayOfYear) {
      var dayOfYearLength;
      var dayOfYearPadding;

      if(component.length > 1) {
        dayOfYearPadding = template['DatePadding']({
          minimum: component.length,
          variableName: 'day'
        });
      }

      result += template['DateDayOfYear']({
        padding: dayOfYearPadding
      });
    }
    else if(component instanceof MessageFormat.AST.date.day.DayOfWeekInMonth) {
      result += template['DateDayOfWeekInMonth']();
    }
    else if(component instanceof MessageFormat.AST.date.weekDay.DayOfWeek) {
      var localDayOfWeekStrings;
      var localDayOfWeekContext;
      var localDayOfWeekPadding;

      if(component.context === MessageFormat.AST.date.weekDay.DayOfWeek.Contexts.FORMATED) {
        localDayOfWeekContext = 'formated';
      }
      else {
        localDayOfWeekContext = 'standalone';
      }

      switch(component.format) {
        case MessageFormat.AST.date.weekDay.DayOfWeek.Formats.NUMERIC_WITH_PADDING:
          localDayOfWeekPadding = true;
        case MessageFormat.AST.date.weekDay.DayOfWeek.Formats.NUMERIC:
          return result += template['DateLocalDayOfWeekDigit']({
            padding: localDayOfWeekPadding
          }) + _this.linefeed;
        case MessageFormat.AST.date.weekDay.DayOfWeek.Formats.ABBREVIATED:
          localDayOfWeekStrings = dateFormat.CLDR.day[localDayOfWeekContext]['abbreviated'];
          break;
        case MessageFormat.AST.date.weekDay.DayOfWeek.Formats.WIDE:
          localDayOfWeekStrings = dateFormat.CLDR.day[localDayOfWeekContext]['wide'];
          break;
        case MessageFormat.AST.date.weekDay.DayOfWeek.Formats.NARROW:
          localDayOfWeekStrings = dateFormat.CLDR.day[localDayOfWeekContext]['narrow'];
          break;
        default:
          localDayOfWeekStrings = dateFormat.CLDR.day[localDayOfWeekContext]['short'];
          break;
      }

      result += template['DateDayOfWeek']({
        days: localDayOfWeekStrings
      });
    }
    else if(component instanceof MessageFormat.AST.date.time.Period) {
      var periodFormat;

      switch(component.format) {
        case MessageFormat.AST.date.time.Period.Formats.ABBREVIATED:
          periodFormat = 'abbreviated';
          break;
        case MessageFormat.AST.date.time.Period.Formats.NARROW:
          periodFormat = 'narrow';
          break;
        case MessageFormat.AST.date.time.Period.Formats.WIDE:
          periodFormat = 'wide';
          break;
      }

      result += template['DatePeriod']({
        period: dateFormat.CLDR.period[periodFormat]
      });
    }
    else if(component instanceof MessageFormat.AST.date.time.Hour) {
      var startHour;
      var hourLength;
      var hourPadding;

      switch(component.type) {
        case MessageFormat.AST.date.time.Hour.Types.TWELVE_HOURS_STARTING_AT_ZERO:
          startHour = 0;
          hourLength = 12;
          break;
        case MessageFormat.AST.date.time.Hour.Types.TWELVE_HOURS_STARTING_AT_ONE:
          startHour = 1;
          hourLength = 12;
          break;
        case MessageFormat.AST.date.time.Hour.Types.TWENTY_FOUR_HOURS_STARTING_AT_ZERO:
          startHour = 0;
          hourLength = 24;
          break;
        default:
          startHour = 1;
          hourLength = 24;
          break;
      }

      if(component.format === MessageFormat.AST.date.time.Hour.Formats.NUMERIC_WITH_PADDING) {
        hourPadding = true;
      }

      result += template['DateHour']({
        start: startHour,
        length: hourLength,
        padding: hourPadding
      });
    }
    else if(component instanceof MessageFormat.AST.date.time.Minute) {
      var minutePadding;
      if(component.format === MessageFormat.AST.date.time.Minute.Formats.NUMERIC_WITH_PADDING) {
        minutePadding = true;
      }

      result += template['DateMinute']({
        padding: minutePadding
      });
    }
    else if(component instanceof MessageFormat.AST.date.time.second.Second) {
      var secondPadding;

      if(component.format === MessageFormat.AST.date.time.second.Second.Formats.NUMERIC_WITH_PADDING) {
        secondPadding = true;
      }

      result += template['DateSecond']({
        padding: secondPadding
      });
    }
    else if(component instanceof MessageFormat.AST.date.time.second.FractionalSecond) {
      result += template['DateFractionalSeconds']({
        length: component.length
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.SpecificNonLocationTimezone) {
      result += template['DateSpecificNonLocationTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.RegularTimezone) {
      result += template['DateRegularTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.LocalizedGMTTimezone) {
      result += template['DateLocalizedGMTTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.GenericNonLocationTimezone) {
      result += template['DateGenericNonLocationTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.GenericLocationTimezone) {
      result += template['DateGenericLocationTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.ISO8601WithZTimezone) {
      result += template['DateISO8601WithZTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }
    else if(component instanceof MessageFormat.AST.date.timezone.ISO8601WithoutZTimezone) {
      result += template['DateISO8601WithoutZTimezone']({
        format: component.format,
        variableName: dateFormat.variable.name
      });
    }

    result += _this.linefeed;
  });

  if(dateFormat.numberSystem !== 'latn') {
    result += this.linefeed + template['ReplaceDigitBlock']({
      variableName: 'dateString',
      digits: digits[dateFormat.numberSystem]
    });
  }

  result += this.linefeed + 'string += dateString;';

  return result;
};

/**
 * Compile select format
 *
 * @param {AST.PluralFormat} pluralFormat
 * @return {String}
 * @api private
 */

Compiler.prototype._compileSelectFormat = function(selectFormat) {
  var switchBody = '';

  for(var _case in selectFormat.values) {
    var caseBody = this._getFunctionBody(selectFormat.values[_case]);
    if(_case !== 'other') {
      switchBody += template['Case']({
        case: _case,
        caseBody: this._indentSpaces(2, caseBody)
      });
    }
    else {
      switchBody += template['OtherCase']({
        caseBody: this._indentSpaces(2, caseBody)
      });
    }

    switchBody += this.linefeed;
  }

  switchBody = this._indentSpaces(2, switchBody.substring(0, switchBody.length - 1));

  return template['SelectSwitchStatement']({
    variableName: selectFormat.variable.name,
    switchBody: switchBody
  });
};

/**
 * Compile plural format
 *
 * @param {AST.PluralFormat} pluralFormat
 * @return {String}
 * @api private
 */

Compiler.prototype._compilePluralFormat = function(pluralFormat, language) {
  var switchBody = '';
  var setCaseStatement = '';
  var exactCases = [];
  var conditionOrder = 'if';

  for(var _case in pluralFormat.values) {
    var caseBody = this._getFunctionBody(pluralFormat.values[_case], language);
    if(_case !== 'other') {
      switchBody += template['Case']({
        case: _case.replace('infinity', 'Infinity'),
        caseBody: this._indentSpaces(2, caseBody)
      });
    }
    else {
      switchBody += template['OtherCase']({
        caseBody: this._indentSpaces(2, caseBody)
      });
    }

    switchBody += this.linefeed;
    if(/^=\-?(\d+(\.\d+)|Infinity|infinity)?/.test(_case)) {
      exactCases.push(_case);
    }
  }

  if(exactCases.length > 0) {
    for(var exactCaseIndex = 0; exactCaseIndex < exactCases.length; exactCaseIndex++) {
      if(exactCaseIndex !== 0) {
        conditionOrder = 'else if';
      }
      setCaseStatement += template['SetPluralConditionCase']({
        statementType: conditionOrder,
        variableName: pluralFormat.variable.name,
        value: exactCases[exactCaseIndex].replace('=', '').replace('infinity', 'Infinity')
      });
    }
    setCaseStatement += this.linefeed;
    setCaseStatement += template['SetPluralElseCase']({
      language: pluralFormat.language,
      variableName: pluralFormat.variable.name
    });
  }
  else {
    setCaseStatement += template['SetPluralCase']({
      language: pluralFormat.language,
      variableName: pluralFormat.variable.name
    });
  }

  switchBody = this._indentSpaces(2, switchBody.substring(0, switchBody.length - 1));

  return template['PluralSwitchStatement']({
    setCaseStatement: setCaseStatement,
    variableName: pluralFormat.variable.name,
    switchBody: switchBody
  });
};

/**
 * Compile selectordinal format
 *
 * @param {AST.Selectordinal} selectordinalFormat
 * @return {String}
 * @api private
 */

Compiler.prototype._compileSelectordinalFormat = function(selectordinalFormat, language) {
  var switchBody = '';
  var setCaseStatement = '';
  var exactCases = [];
  var conditionOrder = 'if';

  for(var _case in selectordinalFormat.values) {
    var caseBody = this._getFunctionBody(selectordinalFormat.values[_case], language);
    if(_case !== 'other') {
      switchBody += template['Case']({
        case: _case,
        caseBody: this._indentSpaces(2, caseBody)
      });
    }
    else {
      switchBody += template['OtherCase']({
        caseBody: this._indentSpaces(2, caseBody)
      });
    }

    switchBody += this.linefeed;
    if(/^=\d+$/.test(_case)) {
      exactCases.push(_case);
    }
  }

  if(exactCases.length > 0) {
    for(var exactCaseIndex = 0; exactCaseIndex < exactCases.length; exactCaseIndex++) {
      if(exactCaseIndex !== 0) {
        conditionOrder = 'else if';
      }
      setCaseStatement += template['SetOrdinalConditionCase']({
        statementType: conditionOrder,
        variableName: selectordinalFormat.variable.name,
        value: exactCases[exactCaseIndex].replace('=', '')
      });
    }
    setCaseStatement += this.linefeed;
    setCaseStatement += template['SetOrdinalElseCase']({
      language: selectordinalFormat.language,
      variableName: selectordinalFormat.variable.name
    });
  }
  else {
    setCaseStatement += template['SetOrdinalCase']({
      language: selectordinalFormat.language,
      variableName: selectordinalFormat.variable.name
    });
  }

  switchBody = this._indentSpaces(2, switchBody.substring(0, switchBody.length - 1));

  return template['OrdinalSwitchStatement']({
    setCaseStatement: setCaseStatement,
    switchBody: switchBody
  });
};

/**
 * Get plural getter function string
 *
 * @return {void}
 * @api private
 */

Compiler.prototype._getPluralGetterFunctionString = function(messageFormat) {
  var result = this.linefeed, index = 0, conditionOrder = 'if';

  for(var _case in messageFormat.pluralRules) {
    if(_case === 'other') {
      continue;
    }

    if(index > 0) {
      conditionOrder = 'else if';
    }

    result += this._indentSpaces(2, template['ConditionStatement']({
      order: conditionOrder,
      condition: this._getPluralComparisonString(messageFormat.pluralRules[_case]),
      body: this._indentSpaces(2, 'return \'' + _case + '\';')
    }));

    result += this.linefeed;

    index++;
  }

  if(index === 0) {
    result = result.substring(1);
  }
  result += this._indentSpaces(2, template['ReturnOtherStringStatement']());

  return template['GetPluralKeyword']({
    functionBody: result
  });
};

/**
 * Get ordinal getter function string
 *
 * @return {void}
 * @api private
 */

Compiler.prototype._getOrdinalGetterFunctionString = function(messageFormat) {
  var result = this.linefeed, index = 0, conditionOrder = 'if';

  for(var _case in messageFormat.ordinalRules) {
    if(_case === 'other') {
      continue;
    }

    if(index > 0) {
      conditionOrder = 'else if';
    }

    result += this._indentSpaces(2, template['ConditionStatement']({
      order: conditionOrder,
      condition: this._getPluralComparisonString(messageFormat.ordinalRules[_case]),
      body: this._indentSpaces(2, 'return \'' + _case + '\';')
    }));

    result += this.linefeed;

    index++;
  }

  if(index === 0) {
    result = result.substring(1);
  }
  result += this._indentSpaces(2, template['ReturnOtherStringStatement']());

  return template['GetPluralKeyword']({
    functionBody: result
  });
};

/**
 * Get javascript number comparison group type
 *
 * @param {String} type (and|or)
 * @return {String} (&&|||)
 * @api private
 */

Compiler.prototype._getNumberComparisonGroupType = function(type) {
  if(type === 'and') {
    return '&&';
  }

  return '||';
};

/**
 * Get plural comparison string
 *
 * @param {String} _case
 * @param {LMDLPlural.AST.NumberComparisonGroup|LMDLPlural.AST.NumberComparison} comparison
 * @return {String}
 * @api private
 */

Compiler.prototype._getPluralComparisonString = function(comparison) {
  if(comparison instanceof LDML.AST.NumberComparisonGroup) {
    var LHSString = this._getPluralComparisonString(comparison.LHS);
    var RHSString = this._getPluralComparisonString(comparison.RHS);

    return LHSString + this.space + this._getNumberComparisonGroupType(comparison.type) + this.space + RHSString;
  }
  else if(comparison instanceof LDML.AST.NumberComparison) {
    var result = ''
      , values = comparison.RHS.values;

    for(var index = 0; index < values.length; index++) {
      if(index !== 0) {
        result += this.and;
      }
      if(values[index] instanceof LDML.AST.Value) {
        result += template['NumberComparison']({
          variableName: comparison.LHS.variable,
          modulus: comparison.LHS.modulus,
          comparator: comparison.comparator === '=' ? '===' : '!==',
          value: values[index].value
        });
      }
      else if(values[index] instanceof LDML.AST.Range) {
        result += template['RangeNumberComparison']({
          variableName: comparison.LHS.variable,
          from: values[index].from,
          to: values[index].to
        });
      }
    }

    return result;
  }
};

/**
 * Export instance
 */

module.exports = new Compiler;

/**
 * Export constructor
 */

module.exports.Constructor = Compiler;


text:
const tracks: string[] = ['chapter1.mp3', 'chapter2.mp3', 'chapter3.mp3'];
let trackId = 0;

const audio: HTMLAudioElement = document.createElement('audio');
audio.src = tracks[trackId];

function updatePlayingMedia(): void {
  audio.src = tracks[trackId];
}

if ('mediaSession' in navigator && navigator.mediaSession) {
  navigator.mediaSession.setActionHandler('previoustrack', (): void => {
    trackId = (trackId + tracks.length - 1) % tracks.length;
    updatePlayingMedia();
  });

  navigator.mediaSession.setActionHandler('nexttrack', (): void => {
    trackId = (trackId + 1) % tracks.length;
    updatePlayingMedia();
  });

  navigator.mediaSession.metadata = new MediaMetadata({
    title: 'Episode Title',
    artist: 'Podcast Host',
    album: 'Podcast Title',
    artwork: [
      {src: 'podcast.jpg', sizes: '128x128', type: 'image/jpeg'},
      {src: 'podcast_hd.jpg', sizes: '256x256'},
      {src: 'podcast_xhd.jpg', sizes: '1024x1024', type: 'image/jpeg'},
      {src: 'podcast.png', sizes: '128x128', type: 'image/png'},
      {src: 'podcast_hd.png', sizes: '256x256', type: 'image/png'},
      {src: 'podcast.ico', sizes: '128x128 256x256', type: 'image/x-icon'}
    ]
  });
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Symb. bot. upsal. 16(no. 1): 104 (1958)

#### Original name
Peniophora hastata Litsch., 1928

### Remarks
null


text:
//  Copyright 2017 Twitter. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
package com.twitter.heron.apiserver.resources;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

import javax.activation.MimetypesFileTypeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.twitter.heron.apiserver.utils.FileHelper;
import com.twitter.heron.apiserver.utils.Logging;
import com.twitter.heron.apiserver.utils.Utils;
import com.twitter.heron.spi.common.Config;
import com.twitter.heron.spi.common.Key;

/**
 * Endpoints that allows the API server to become a file server
 */
@Path("/file")
public class FileResource extends HeronResource {
  private static final Logger LOG = LoggerFactory.getLogger(FileResource.class);

  private static final String FILE_SYSTEM_DIRECTORY
      = "heron.apiserver.http.file.system.directory";

  private static final String DOWNLOAD_HOSTNAME_OVERRIDE
      = "heron.apiserver.http.download.hostname";

  private static InetAddress ip;
  private static String hostname;

  static {
    try {
      ip = InetAddress.getLocalHost();
      hostname = ip.getHostName();
    } catch (UnknownHostException e) {
      LOG.info("Failed to resolve IP address of localhost");
    }
  }

/**
 * Endpoints for artifacts upload
 */
  @POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail) {

    Config config = createConfig();

    if (uploadedInputStream == null) {
      String msg = "input stream is null";
      LOG.error(msg);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(msg)).build();
    }
    if (fileDetail == null) {
      String msg = "form data content disposition is null";
      LOG.error(msg);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(msg)).build();
    }

    String uploadDir = config.getStringValue(FILE_SYSTEM_DIRECTORY);

    final String fileName = UUID.randomUUID() + "-" + fileDetail.getFileName();

    final String uploadedFileLocation
        = uploadDir + "/" + fileName;

    // save it
    try {
      FileHelper.writeToFile(uploadedInputStream, uploadedFileLocation);
    } catch (IOException e) {
      LOG.error("error uploading file {}", fileDetail.getFileName(), e);
      return Response.serverError()
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(e.getMessage()))
          .build();
    }

    String uri = String.format("http://%s:%s/api/v1/file/download/%s",
        getHostNameOrIP(), getPort(), fileName);

    return Response.status(Response.Status.OK).entity(uri).build();
  }

/**
 * Endpoints for artifacts download
 */
  @GET
  @Path("/download/{file}")
  public Response downloadFile(final @PathParam("file") String file) {
    Config config = createConfig();
    String uploadDir = config.getStringValue(FILE_SYSTEM_DIRECTORY);
    String filePath = uploadDir + "/" + file;
    return getResponseByFile(filePath);
  }

  /**
   * Endpoint for downloading Heron Core
   */
  @GET
  @Path("/download/core")
  public Response downloadHeronCore() {
    String corePath = getHeronCorePackagePath();
    return getResponseByFile(corePath);
  }

  private Response getResponseByFile(String filePath) {

    File file = new File(filePath);
    if (!file.exists()) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }
    String mimeType = new MimetypesFileTypeMap().getContentType(file);
    Response.ResponseBuilder rb = Response.ok(file, mimeType);
    rb.header("content-disposition", "attachment; filename = "
        + file.getName());
    return rb.build();

  }

  private Config createConfig() {
    final Config.Builder builder = Config.newBuilder().putAll(getBaseConfiguration());
    builder.put(Key.VERBOSE, Logging.isVerbose());
    return Config.toLocalMode(builder.build());
  }

  private String getHostNameOrIP() {
    // Override hostname if provided in flags
    if (Utils.isNotEmpty(getDownloadHostName())) {
      return getDownloadHostName();
    } else if (Utils.isNotEmpty(hostname)) {
      return hostname;
    } else if (ip != null && !ip.toString().isEmpty()) {
      return ip.toString();
    }
    return "";
  }

}


text:
from twython import Twython

from easy_twitter.models import Settings

def get_tweets(account):
    feed_account = Settings.objects.get(display_name=account)
    twitter = Twython(feed_account.consumer_key, feed_account.consumer_secret, feed_account.access_token, feed_account.access_token_secret)
    time_line = twitter.get_user_timeline(display_name=feed_account.display_name, include_rts=feed_account.show_retweets, count=feed_account.count_limit, exclude_replies=feed_account.exclude_replies)
    return time_line

def show_tweets(account):
    tweets = get_tweets(account)
    return tweets


text:
MQTT::MQTT() {
    this->ip = NULL;
    this->buffer = NULL;
}

MQTT::MQTT(char* domain, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int)) {
    this->initialize(domain, NULL, port, MQTT_DEFAULT_KEEPALIVE, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(char* domain, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), int maxpacketsize) {
    this->initialize(domain, NULL, port, MQTT_DEFAULT_KEEPALIVE, callback, maxpacketsize);
}

MQTT::MQTT(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int)) {
    this->initialize(NULL, ip, port, MQTT_DEFAULT_KEEPALIVE, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), int maxpacketsize) {
    this->initialize(NULL, ip, port, MQTT_DEFAULT_KEEPALIVE, callback, maxpacketsize);
}

MQTT::MQTT(char* domain, uint16_t port, int keepalive, void (*callback)(char*,uint8_t*,unsigned int)) {
    this->initialize(domain, NULL, port, keepalive, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(char* domain, uint16_t port, int keepalive, void (*callback)(char*,uint8_t*,unsigned int), int maxpacketsize) {
    this->initialize(domain, NULL, port, keepalive, callback, maxpacketsize);
}

MQTT::MQTT(uint8_t *ip, uint16_t port, int keepalive, void (*callback)(char*,uint8_t*,unsigned int)) {
    this->initialize(NULL, ip, port, keepalive, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(uint8_t *ip, uint16_t port, int keepalive, void (*callback)(char*,uint8_t*,unsigned int), int maxpacketsize) {
    this->initialize(NULL, ip, port, keepalive, callback, maxpacketsize);
}

MQTT::~MQTT() {
    if (isConnected()) {
        disconnect();
    }

    if (buffer != NULL)
      delete[] buffer;
}

void MQTT::initialize(char* domain, uint8_t *ip, uint16_t port, int keepalive, void (*callback)(char*,uint8_t*,unsigned int), int maxpacketsize) {
    this->callback = callback;
    this->qoscallback = NULL;
    if (ip != NULL)
        this->ip = ip;
    if (domain != NULL)
        this->domain = domain;
    this->port = port;
    this->keepalive = keepalive;

    // if maxpacketsize is over MQTT_MAX_PACKET_SIZE.
    this->maxpacketsize = (maxpacketsize <= MQTT_MAX_PACKET_SIZE ? MQTT_MAX_PACKET_SIZE : maxpacketsize);
    if (buffer != NULL)
      delete[] buffer;
    buffer = new uint8_t[this->maxpacketsize];
}

void MQTT::setBroker(char* domain, uint16_t port) {
    if(isConnected()) {
        disconnect();
    }
    this->domain = domain;
    this->ip = NULL;
    this->port = port;
}

void MQTT::setBroker(uint8_t *ip, uint16_t port) {
    if(isConnected()) {
        disconnect();
    }
    this->domain = "";
    this->ip = ip;
    this->port = port;
}

void MQTT::addQosCallback(void (*qoscallback)(unsigned int)) {
    this->qoscallback = qoscallback;
}

bool MQTT::connect(const char *id) {
    return connect(id, NULL, NULL, 0, QOS0, 0, 0, true);
}

bool MQTT::connect(const char *id, const char *user, const char *pass) {
    return connect(id, user, pass, 0, QOS0, 0, 0, true);
}

bool MQTT::connect(const char *id, const char *user, const char *pass, const char* willTopic, EMQTT_QOS willQos, uint8_t willRetain, const char* willMessage, bool cleanSession) {
    if (!isConnected()) {
        int result = 0;
        if (ip == NULL)
            result = _client.connect(this->domain.c_str(), this->port);
        else
            result = _client.connect(this->ip, this->port);

        if (result) {
            nextMsgId = 1;
            uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p',MQTTPROTOCOLVERSION};
            // Leave room in the buffer for header and variable length field
            uint16_t length = 5;
            unsigned int j;
            for (j = 0;j<9;j++) {
                buffer[length++] = d[j];
            }

            uint8_t v;
            if (willTopic) {
                v = 0x06|(willQos<<3)|(willRetain<<5);
            } else {
                v = 0x02;
            }

            if (!cleanSession) {
              v = v&0xfd;
            }

            if(user != NULL) {
                v = v|0x80;

                if(pass != NULL) {
                    v = v|(0x80>>1);
                }
            }

            buffer[length++] = v;

            buffer[length++] = ((this->keepalive) >> 8);
            buffer[length++] = ((this->keepalive) & 0xFF);
            length = writeString(id, buffer, length);
            if (willTopic) {
                length = writeString(willTopic, buffer, length);
                length = writeString(willMessage, buffer, length);
            }

            if(user != NULL) {
                length = writeString(user,buffer,length);
                if(pass != NULL) {
                    length = writeString(pass,buffer,length);
                }
            }

            write(MQTTCONNECT, buffer, length-5);
            lastInActivity = lastOutActivity = millis();

            while (!_client.available()) {
                unsigned long t = millis();
                if (t-lastInActivity > this->keepalive*1000UL) {
                    _client.stop();
                    return false;
                }
            }
            uint8_t llen;
            uint16_t len = readPacket(&llen);

            if (len == 4) {
                if (buffer[3] == CONN_ACCEPT) {
                    lastInActivity = millis();
                    pingOutstanding = false;
                    debug_print(" Connect success\n");
                    return true;
                } else {
                    // check EMQTT_CONNACK_RESPONSE code.
                    debug_print(" Connect fail. code = [%d]\n", buffer[3]);
                }
            }
        }
        _client.stop();
    }
    return false;
}

uint8_t MQTT::readByte() {
    while(!_client.available()) {}
    return _client.read();
}

uint16_t MQTT::readPacket(uint8_t* lengthLength) {
    uint16_t len = 0;
    buffer[len++] = readByte();
    bool isPublish = (buffer[0]&0xF0) == MQTTPUBLISH;
    uint32_t multiplier = 1;
    uint16_t length = 0;
    uint8_t digit = 0;
    uint16_t skip = 0;
    uint8_t start = 0;

    do {
        digit = readByte();
        buffer[len++] = digit;
        length += (digit & 127) * multiplier;
        multiplier *= 128;
    } while ((digit & 128) != 0);
    *lengthLength = len-1;

    if (isPublish) {
        // Read in topic length to calculate bytes to skip over for Stream writing
        buffer[len++] = readByte();
        buffer[len++] = readByte();
        skip = (buffer[*lengthLength+1]<<8)+buffer[*lengthLength+2];
        start = 2;
        if (buffer[0] & MQTTQOS1_HEADER_MASK) {
            // skip message id
            skip += 2;
        }
    }

    for (uint16_t i = start;i<length;i++) {
        digit = readByte();
        if (len < this->maxpacketsize) {
            buffer[len] = digit;
        }
        len++;
    }

    if (len > this->maxpacketsize) {
        len = 0; // This will cause the packet to be ignored.
    }

    return len;
}

bool MQTT::loop() {
    if (isConnected()) {
        unsigned long t = millis();
        if ((t - lastInActivity > this->keepalive*1000UL) || (t - lastOutActivity > this->keepalive*1000UL)) {
            if (pingOutstanding) {
                _client.stop();
                return false;
            } else {
                buffer[0] = MQTTPINGREQ;
                buffer[1] = 0;
                _client.write(buffer,2);
                lastOutActivity = t;
                lastInActivity = t;
                pingOutstanding = true;
            }
        }
        if (_client.available()) {
            uint8_t llen;
            uint16_t len = readPacket(&llen);
            uint16_t msgId = 0;
            uint8_t *payload;
            if (len > 0) {
                lastInActivity = t;
                uint8_t type = buffer[0]&0xF0;
                if (type == MQTTPUBLISH) {
                    if (callback) {
                        uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2];
                        char topic[tl+1];
                        for (uint16_t i=0;i<tl;i++) {
                            topic[i] = buffer[llen+3+i];
                        }
                        topic[tl] = 0;
                        // msgId only present for QOS>0
                        if ((buffer[0]&0x06) == MQTTQOS1_HEADER_MASK) {
                            msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1];
                            payload = buffer+llen+3+tl+2;
                            callback(topic,payload,len-llen-3-tl-2);

                            buffer[0] = MQTTPUBACK;
                            buffer[1] = 2;
                            buffer[2] = (msgId >> 8);
                            buffer[3] = (msgId & 0xFF);
                            _client.write(buffer,4);
                            lastOutActivity = t;
                        } else {
                            payload = buffer+llen+3+tl;
                            callback(topic,payload,len-llen-3-tl);
                        }
                    }
                } else if (type == MQTTPUBACK || type == MQTTPUBREC) {
                    if (qoscallback) {
                        // msgId only present for QOS==0
                        if (len == 4 && (buffer[0]&0x06) == MQTTQOS0_HEADER_MASK) {
                            msgId = (buffer[2]<<8)+buffer[3];
                            this->qoscallback(msgId);
                        }
                    }
                } else if (type == MQTTPUBCOMP) {
                    // TODO:if something...
                } else if (type == MQTTSUBACK) {
                    // if something...
                } else if (type == MQTTPINGREQ) {
                    buffer[0] = MQTTPINGRESP;
                    buffer[1] = 0;
                    _client.write(buffer,2);
                } else if (type == MQTTPINGRESP) {
                    pingOutstanding = false;
                }
            }
        }
        return true;
    }
    return false;
}

bool MQTT::publish(const char* topic, const char* payload) {
    return publish(topic, (uint8_t*)payload, strlen(payload), false, QOS0, NULL);
}

bool MQTT::publish(const char * topic, const char* payload, EMQTT_QOS qos, bool dup, uint16_t *messageid) {
    return publish(topic, (uint8_t*)payload, strlen(payload), false, qos, dup, messageid);
}

bool MQTT::publish(const char * topic, const char* payload, EMQTT_QOS qos, uint16_t *messageid) {
    return publish(topic, (uint8_t*)payload, strlen(payload), false, qos, messageid);
}

bool MQTT::publish(const char* topic, const uint8_t* payload, unsigned int plength) {
    return publish(topic, payload, plength, false, QOS0, NULL);
}

bool MQTT::publish(const char* topic, const uint8_t* payload, unsigned int plength, EMQTT_QOS qos, bool dup, uint16_t *messageid) {
    return publish(topic, payload, plength, false, qos, dup, messageid);
}

bool MQTT::publish(const char* topic, const uint8_t* payload, unsigned int plength, EMQTT_QOS qos, uint16_t *messageid) {
    return publish(topic, payload, plength, false, qos, messageid);
}

bool MQTT::publish(const char* topic, const uint8_t* payload, unsigned int plength, bool retain) {
    return publish(topic, payload, plength, retain, QOS0, NULL);
}

bool MQTT::publish(const char* topic, const uint8_t* payload, unsigned int plength, bool retain, EMQTT_QOS qos, uint16_t *messageid) {
    return publish(topic, payload, plength, retain, qos, false, messageid);
}

bool MQTT::publish(const char* topic, const uint8_t* payload, unsigned int plength, bool retain, EMQTT_QOS qos, bool dup, uint16_t *messageid) {
    if (isConnected()) {
        // Leave room in the buffer for header and variable length field
        uint16_t length = 5;
        memset(buffer, 0, this->maxpacketsize);

        length = writeString(topic, buffer, length);

        if (qos == QOS2 || qos == QOS1) {
            nextMsgId += 1;
            buffer[length++] = (nextMsgId >> 8);
            buffer[length++] = (nextMsgId & 0xFF);
            if (messageid != NULL)
                *messageid = nextMsgId++;
        }

        for (uint16_t i=0; i < plength && length < this->maxpacketsize; i++) {
            buffer[length++] = payload[i];
        }

        uint8_t header = MQTTPUBLISH;
        if (retain) {
            header |= 1;
        }

        if (dup) {
            header |= DUP_FLAG_ON_MASK;
        }

        if (qos == QOS2)
            header |= MQTTQOS2_HEADER_MASK;
        else if (qos == QOS1)
            header |= MQTTQOS1_HEADER_MASK;
        else
            header |= MQTTQOS0_HEADER_MASK;

        return write(header, buffer, length-5);
    }
    return false;
}

bool MQTT::publishRelease(uint16_t messageid) {
    if (isConnected()) {
        uint16_t length = 0;
        buffer[length++] = MQTTPUBREL | MQTTQOS1_HEADER_MASK;
        buffer[length++] = 2;
        buffer[length++] = (messageid >> 8);
        buffer[length++] = (messageid & 0xFF);
        return _client.write(buffer, length);
    }
    return false;
}

bool MQTT::write(uint8_t header, uint8_t* buf, uint16_t length) {
    uint8_t lenBuf[4];
    uint8_t llen = 0;
    uint8_t digit;
    uint8_t pos = 0;
    uint16_t rc;
    uint16_t len = length;
    do {
        digit = len % 128;
        len = len / 128;
        if (len > 0) {
            digit |= 0x80;
        }
        lenBuf[pos++] = digit;
        llen++;
    } while(len > 0);

    buf[4-llen] = header;
    for (int i = 0; i < llen; i++) {
        buf[5-llen+i] = lenBuf[i];
    }
    rc = _client.write(buf+(4-llen), length+1+llen);

    lastOutActivity = millis();
    return (rc == 1+llen+length);
}

bool MQTT::subscribe(const char* topic) {
    return subscribe(topic, QOS0);
}

bool MQTT::subscribe(const char* topic, EMQTT_QOS qos) {
    if (qos < 0 || qos > 1)
        return false;

    if (isConnected()) {
        // Leave room in the buffer for header and variable length field
        uint16_t length = 5;
        nextMsgId++;
        if (nextMsgId == 0) {
            nextMsgId = 1;
        }
        buffer[length++] = (nextMsgId >> 8);
        buffer[length++] = (nextMsgId & 0xFF);
        length = writeString(topic, buffer,length);
        buffer[length++] = qos;
        return write(MQTTSUBSCRIBE | MQTTQOS1_HEADER_MASK,buffer,length-5);
    }
    return false;
}

bool MQTT::unsubscribe(const char* topic) {
    if (isConnected()) {
        uint16_t length = 5;
        nextMsgId++;
        if (nextMsgId == 0) {
            nextMsgId = 1;
        }
        buffer[length++] = (nextMsgId >> 8);
        buffer[length++] = (nextMsgId & 0xFF);
        length = writeString(topic, buffer,length);
        return write(MQTTUNSUBSCRIBE | MQTTQOS1_HEADER_MASK,buffer,length-5);
    }
    return false;
}

void MQTT::disconnect() {
    buffer[0] = MQTTDISCONNECT;
    buffer[1] = 0;
    _client.write(buffer,2);
    _client.stop();
    lastInActivity = lastOutActivity = millis();
}

uint16_t MQTT::writeString(const char* string, uint8_t* buf, uint16_t pos) {
    const char* idp = string;
    uint16_t i = 0;
    pos += 2;
    while (*idp && pos < this->maxpacketsize) {
        buf[pos++] = *idp++;
        i++;
    }
    buf[pos-i-2] = (i >> 8);
    buf[pos-i-1] = (i & 0xFF);
    return pos;
}

bool MQTT::isConnected() {
    bool rc = (int)_client.connected();
    if (!rc) _client.stop();
    return rc;
}

void MQTT::clear() {
  _client.stop();
  lastInActivity = lastOutActivity = millis();
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Joda-Time -
  Java date and time API - Home</title>

    <link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
      <meta name="author" content="Stephen Colebourne" />
      <meta name="author" content="Al Major" />
    <meta name="Date-Revision-yyyymmdd" content="20100914" />
    <meta http-equiv="Content-Language" content="en" />

                Joda.org

                Joda-Time

        Version: 1.6.2

                    Joda-Time
            |
                        JSP tags
            |
                        Hibernate
            |
                        I18N

Joda Time

            Overview

                          Quick start guide

                          User guide

                          FAQ

                          Related projects

                          Javadoc (Release)

                          License

                          Download

Key concepts

                          Instant

                          Partial

                          Interval

                          Duration

                          Period

                          Chronology

Chronologies

                          ISO8601

                          Buddhist

                          Coptic

                          Ethiopic

                          Gregorian

                          GregorianJulian

                          Islamic

                          Julian

Development

                          Sourceforge

                          Test results

                          Mailing lists

                          Tasks

                          Subversion

                          Javadoc (Development)

Joda

                          Joda home

                          Beans

                          Convert

                          Money

                          Primitives

Project Documentation

                          Project Information

            About

                          Dependencies

                          Issue Tracking

                          Mailing Lists

                          Project License

                          Project Summary

                          Project Team

                          Source Repository

                          Project Reports

Website

                          Privacy

        Last Published: 2010-09-14

Joda Time - Java date and time API

Joda-Time provides a quality replacement for the Java date
and time classes. The design allows for multiple calendar
systems, while still providing a simple API.
The 'default' calendar is the ISO8601 standard which
is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems
are also included, and we welcome further additions. Supporting classes include
time zone, duration, format and parsing.

As a flavour of Joda-Time, here's some example code:

public boolean isAfterPayDay(DateTime datetime) {
  if (datetime.getMonthOfYear() == 2) {   // February is month 2!!
    return datetime.getDayOfMonth() > 26;
  }
  return datetime.getDayOfMonth() > 28;
}

public Days daysToNewYear(LocalDate fromDate) {
  LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
  return Days.daysBetween(fromDate, newYear);
}

public boolean isRentalOverdue(DateTime datetimeRented) {
  Period rentalPeriod = new Period().withDays(2).withHours(12);
  return datetimeRented.plus(rentalPeriod).isBeforeNow();
}

public String getBirthMonthText(LocalDate dateOfBirth) {
  return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
}

Version 1.6.2 was released on 2010-09-14 -
Download now

Why Joda Time?

Joda-Time has been created to radically change date and time handling in Java.
The JDK classes Date and Calendar are very badly designed, have had numerous bugs
and have odd performance effects.
Here are some of our reasons for developing and using Joda-Time:

Easy to Use.
Calendar makes accessing 'normal' dates difficult, due to the lack of simple methods.
Joda-Time has straightforward field accessors such as
<tt>getYear()</tt> or <tt>getDayOfWeek()</tt>.

Easy to Extend.
The JDK supports multiple calendar systems via subclasses of <tt>Calendar</tt>.
This is clunky, and in practice it is very difficult to write another calendar system.
Joda-Time supports multiple calendar systems via a pluggable system based on the
<tt>Chronology</tt> class.

Comprehensive Feature Set.
The library is intended to provide all the functionality that is required for date-time
calculations. It already provides out-of-the-box features, such as support for oddball
date formats, which are difficult to replicate with the JDK.

Up-to-date Time Zone calculations.
The time zone implementation is based on
the public tz database, which is
updated several times a year. New Joda-Time releases incorporate all changes
made to this database. Should the changes be needed earlier,
manually updating the zone data is easy.

Calendar support.
The library currently provides 8 calendar systems. More will be added in the future.

Easy interoperability.
The library internally uses a millisecond instant which is identical to the JDK and similar
to other common time representations. This makes interoperability easy, and Joda-Time comes
with out-of-the-box JDK interoperability.

Better Performance Characteristics.
Calendar has strange performance characteristics as it recalculates fields at unexpected moments.
Joda-Time does only the minimal calculation for the field that is being accessed.

Good Test Coverage.
Joda-Time has a comprehensive set of developer tests, providing assurance of the library's quality.

Complete Documentation.
There is a full User Guide which provides an overview and covers
common usage scenarios. The javadoc
is extremely detailed and covers the rest of the API.

Maturity.
The library has been under active development since 2002.
Although it continues to be improved with the addition of new features and
bug-fixes, it is a mature and reliable code base.
A number of related projects are now available.

Open Source.
Joda-Time is licenced under the business friendly Apache License Version 2.0.

Documentation

Various documentation is available:

Two user guides - quick and full

The key concepts and chronology documents in the left navigation area

The javadoc for the current release

The javadoc for the latest code in development

A FAQ list

Information on downloading and installing Joda-Time

The Subversion repository

Releases

Release 1.6.2
is the current latest release.
This release is considered stable and worthy of the 1.x tag.
It has extensive testing suites and has been used in production.
We now recommend JDK 1.4 or later, and have performed no testing on earlier JDKs.

We will support the 1.x product line using standard Java mechanisms.
The main public API will remain backwards compatible for both source and binary.
The version number will change to 2.0 to indicate a change in compatibility.

Support

Support on bugs, library usage or enhancement requests is available via:

the joda-interest mailing list. Due to spam, you must be subscribed to post to the mailing list.

the joda-time sourceforge forum.

Alternatively, you can contact the project lead, Stephen Colebourne via scolebourne.at.users.sourceforge.net.

Copyright ©                    2002-2010
                        Joda.org.
            All Rights Reserved.


text:
<?php

namespace Sodium\Contract\Component\Export;

interface ExportInterface
{
    public function export();
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Linq;
using System.Windows.Forms;
using Palaso.Extensions;
using Palaso.WritingSystems;

namespace Palaso.UI.WindowsForms.WritingSystems
{
	public partial class LookupISOControl : UserControl
	{
		private LookupIsoCodeModel _model;
		private string _lastSearchedForText;
		private string _unlistedLanguageName;
		private string _incomingDesiredName;
		private LanguageInfo _incomingLanguageInfo;
		public event EventHandler ReadinessChanged;

		/// <summary>Force the dialog to return 3 letter iso codes even if a 2 letter code is available</summary>
		public bool Force3LetterCodes
		{
			get { return _model.Force3LetterCodes; }
			set { _model.Force3LetterCodes = value; }
		}

		public void UpdateReadiness()
		{
			EventHandler handler = ReadinessChanged;
			if (handler != null) handler(this, null);
		}

		public event EventHandler DoubleClicked;

		public LookupISOControl()
		{
			InitializeComponent();
			ShowDesiredLanguageNameField = true;
			_model = new LookupIsoCodeModel();
			_unlistedLanguageName = L10NSharp.LocalizationManager.GetString("LanguageLookup.UnlistedLanguage", "Unlisted Language");
		}

		public bool ShowDesiredLanguageNameField
		{
			set { _desiredLanguageDisplayName.Visible = _desiredLanguageLabel.Visible= value; }
		}

		public LanguageInfo LanguageInfo
		{
			get { return _model.LanguageInfo; }
			set { _model.LanguageInfo = value; }
		}

		public bool HaveSufficientInformation
		{
			get
			{
				return LanguageInfo != null &&
				_desiredLanguageDisplayName.Text != _unlistedLanguageName &&
					_desiredLanguageDisplayName.Text.Trim().Length > 0;
			}
		}

		public string ISOCode
		{
			get { return _model.ISOCode; }
			set { _searchText.Text  = value; }
		}

		private void OnLoad(object sender, EventArgs e)
		{
			if (DesignMode)
				return;
			if (_model.LanguageInfo != null)
			{
				_searchText.Text = _model.LanguageInfo.Code;
				if (!string.IsNullOrEmpty(_model.LanguageInfo.DesiredName))
				{
					_incomingLanguageInfo = _model.LanguageInfo;
					_desiredLanguageDisplayName.Text = _model.LanguageInfo.DesiredName;
				}
			}
			if (_desiredLanguageDisplayName.Visible)
				AdjustDesiredLanguageNameFieldLocations();
			AdjustCannotFindLanguageLocation();

			UpdateReadiness();
			_searchTimer.Start();
		}

		/// <summary>
		/// The label and textbox controls overlap on Linux/Mono.  Adjust them to not overlap.
		/// </summary>
		private void AdjustDesiredLanguageNameFieldLocations()
		{
			var labelLocation = _desiredLanguageLabel.Location;
			var labelWidth = _desiredLanguageLabel.Width;
			var nameLocation = _desiredLanguageDisplayName.Location;
			if (labelLocation.X + labelWidth + 5 >= nameLocation.X)
			{
				var newLabelLoc = new System.Drawing.Point(_listView.Location.X, labelLocation.Y);
				_desiredLanguageLabel.Location = newLabelLoc;
				if (newLabelLoc.X + labelWidth + 5 >= nameLocation.X)
				{
					var newNameLoc = new System.Drawing.Point(newLabelLoc.X + labelWidth + 6, nameLocation.Y);
					_desiredLanguageDisplayName.Location = newNameLoc;
				}
			}
		}

		/// <summary>
		/// The link label for "Cannot find language?" is truncated on Linux/Mono.
		/// Adjust the location to allow it to display properly.
		/// </summary>
		private void AdjustCannotFindLanguageLocation()
		{
			//_cannotFindLanguageLink
			var labelLocation = _cannotFindLanguageLink.Location;
			var labelWidth = _cannotFindLanguageLink.Width;
			var shortage = labelLocation.X + labelWidth - this.Width;
			if (shortage > 0)
			{
				var newLoc = new System.Drawing.Point(labelLocation.X - shortage, labelLocation.Y);
				_cannotFindLanguageLink.Location = newLoc;
			}
		}

		private new bool DesignMode
		{
			get
			{
				return (base.DesignMode || GetService(typeof(IDesignerHost)) != null) ||
					(LicenseManager.UsageMode == LicenseUsageMode.Designtime);
			}
		}
		private void OnSelectedIndexChanged(object sender, EventArgs e)
		{
			var oldIso = _model.ISOCode;
			if (_listView.SelectedIndices != null && _listView.SelectedIndices.Count > 0)
			{
				ListViewItem item = _listView.Items[_listView.SelectedIndices[0]];
				_model.LanguageInfo = item.Tag as LanguageInfo;

				if (_incomingLanguageInfo != null && _incomingLanguageInfo.Code == _model.LanguageInfo.Code && !string.IsNullOrEmpty(_incomingLanguageInfo.DesiredName))
				{
					_desiredLanguageDisplayName.Text = _incomingLanguageInfo.DesiredName;
				}
				else
				{
					_desiredLanguageDisplayName.Text = _model.LanguageInfo.Names[0];
					//now if they were typing another form, well then that form makes a better default "Desired Name" than the official primary name
					foreach (var name in _model.LanguageInfo.Names)
					{
						if (name.ToLowerInvariant().StartsWith(_searchText.Text.ToLowerInvariant()))
						{
							_desiredLanguageDisplayName.Text = name;
							break;
						}
					}
				}
			}
			if (_model.ISOCode != oldIso)
				UpdateReadiness();
		}

		/// <summary>
		/// ideally, people dispose of controls properly, so that this isn't needed
		/// But if you're a dialog using and you can't rely on your caller disposing
		/// of you, just call this when you're done with this controll
		/// </summary>
		public void StopTimer()
		{
			_searchTimer.Stop();
		}

		private void _searchTimer_Tick(object sender, EventArgs e)
		{
			var oldIso = _model.ISOCode;
			var typedText = _searchText.Text.Trim();
			if (typedText == _lastSearchedForText)
			{
				return;
			}
			_lastSearchedForText = typedText;
			_listView.SuspendLayout();

			_listView.Items.Clear();
			_listView.SelectedIndices.Clear();
			var toShow = new List<ListViewItem>();

			if (_searchText.Text == "?")
			{
				var description = L10NSharp.LocalizationManager.GetString("LanguageLookup.UnlistedLanguage", "Unlisted Language");
				List<string> names = new List<string>(new string[] {description});
				LanguageInfo unlistedLanguage = new LanguageInfo() {Code = "qaa", Country = "", Names = names};
				ListViewItem item = new ListViewItem(description);
				item.SubItems.Add("qaa");
				item.Tag = unlistedLanguage;
				item.Selected = true;
				_listView.Items.Add(item);

			}
			else
			{
				var itemSelected = false;
				foreach (LanguageInfo lang in _model.GetMatchingLanguages(typedText))
				{
					ListViewItem item = new ListViewItem(lang.Names[0]);
					item.SubItems.Add(lang.Code);
					item.SubItems.Add(lang.Country);
					item.SubItems.Add(string.Join(", ", lang.Names.Skip(1)));
					item.SubItems.Add(lang.Country);
					item.Tag = lang;
					toShow.Add(item);

//					if (!itemSelected && typedText.Length > 1 &&
//					    (lang.Code.ToLower() == typedText || lang.Names[0].ToLower().StartsWith(typedText.ToLower())))
					if (!itemSelected)
					{
						item.Selected = true;
						itemSelected = true; //we only want to select the first one
					}
				}
				if (!itemSelected)
				{
					_model.LanguageInfo = null;
					//_desiredLanguageDisplayName.Text = _searchText.Text;
				}
				_desiredLanguageDisplayName.Enabled = itemSelected;
				_listView.Items.AddRange(toShow.ToArray());

			}
			_listView.ResumeLayout();
			//            if (_listView.Items.Count > 0)
			//            {
			//                _listView.SelectedIndices.Add(0);
			//            }			if(_model.ISOCode != oldIso)
			UpdateReadiness();
		}

		private void listView1_DoubleClick(object sender, EventArgs e)
		{
			if (DoubleClicked != null)
			{
				DoubleClicked(this, null);
			}
		}

		private void _cannotFindLanguageLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			using (var dlg = new CannotFindMyLanguageDialog())
			{
				dlg.ShowDialog();

				_desiredLanguageDisplayName.Text = _searchText.Text.ToUpperFirstLetter();
				_searchText.Text = "?";
				if (_desiredLanguageDisplayName.Visible)
				{
					_desiredLanguageDisplayName.Select();
					_desiredLanguageDisplayName.Enabled = true;
				}
			}
		}

		private void _desiredLanguageDisplayName_TextChanged(object sender, EventArgs e)
		{
			if(_model.LanguageInfo!=null)
				_model.LanguageInfo.DesiredName = _desiredLanguageDisplayName.Text;
			UpdateReadiness();
		}
	}
}


text:
using Tavis;

namespace GitHubLib
{
    public class GitHubHelper
    {
        public static void RegisterGitHubLinks(LinkFactory linkFactory)
        {
            linkFactory.AddLinkType<HomeLink>();
            linkFactory.AddLinkType<UserLink>();
            linkFactory.AddLinkType<CodeSearchLink>();
            linkFactory.AddLinkType<EmojisLink>();
            linkFactory.AddLinkType<FollowingLink>();
            linkFactory.AddLinkType<FollowersLink>();
            linkFactory.AddLinkType<GistsLink>();
        }
    }
}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_FLASH_H_INCLUDED
#define CONF_FLASH_H_INCLUDED

/*! \name Configuration
 */
/* ! @{ */

/* ! @} */
#endif /* CONF_FLASH_H_INCLUDED */