text:
import { Table, Column, Unique, AllowNull, Model, HasMany, BelongsTo, ForeignKey, DataType } from 'sequelize-typescript';
import { Event, BlackList, WhiteList } from '../index'

@Table
export default class attendee extends Model<attendee>{
	@AllowNull(false)
	@Unique
	@Column(DataType.STRING)
	Name: string;

	@Column(DataType.STRING)
	Relation: string;

	@Unique
	@Column(DataType.STRING)
	Phone: string;

	@Column(DataType.STRING)
	Notes: string;

	@ForeignKey(() => Event)
	@Column
	EventID: number;

	@BelongsTo(() => Event)
	Event: Event;

	@HasMany(() => BlackList, 'ListerID')
	BlackList: BlackList[];

	@HasMany(() => WhiteList, 'ListerID')
	WhiteList: WhiteList[];
}


text:
package com.zelory.kace.adressbook.util;

import com.google.gson.Gson;

public class JsonParser {
    private static JsonParser INSTANCE;

    private Gson parser;

    public static JsonParser getInstance() {
        if (INSTANCE == null) {
            synchronized (JsonParser.class) {
                if (INSTANCE == null) {
                    INSTANCE = new JsonParser();
                }
            }
        }
        return INSTANCE;
    }

    private JsonParser() {
        parser = new Gson();
    }

    public Gson getParser() {
        return parser;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.management.internal.cli.commands;

import static org.assertj.core.api.Assertions.assertThat;

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

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Region;
import org.apache.geode.management.internal.i18n.CliStrings;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.assertions.CommandResultAssert;
import org.apache.geode.test.junit.assertions.TabularResultModelAssert;
import org.apache.geode.test.junit.rules.GfshCommandRule;

public class RepeatedRebalanceDUnitTest {
  private static final String PARENT_REGION = "RepeatedRebalanceTestRegion";
  private static final String COLOCATED_REGION_ONE = "RepeatedRebalanceColocatedRegionOne";
  private static final String COLOCATED_REGION_TWO = "RepeatedRebalanceColocatedRegionTwo";
  private static final String PARTITION_RESOLVER =
      "org.apache.geode.management.internal.cli.commands.RepeatedRebalancePartitionResolver";

  private static final int TOTAL_NUM_BUCKETS = 48;
  private static final int NUM_REDUNDANT_COPIES = 2;
  private static final int INITIAL_SERVERS = 4;
  private static final int NUMBER_OF_ENTRIES = 30000;

  private List<MemberVM> memberList = new ArrayList<>();
  private MemberVM locator1;

  @Rule
  public GfshCommandRule gfsh = new GfshCommandRule();

  @Rule
  public ClusterStartupRule cluster = new ClusterStartupRule();

  @Before
  public void before() throws Exception {

    locator1 = cluster.startLocatorVM(0);

    for (int i = 0; i < INITIAL_SERVERS; ++i) {
      memberList.add(cluster.startServerVM(i + 1, locator1.getPort()));
    }

    gfsh.connectAndVerify(locator1);

    gfsh.executeAndAssertThat("create region --name=" + PARENT_REGION
        + " --type=PARTITION --redundant-copies=" + NUM_REDUNDANT_COPIES
        + " --enable-statistics=true "
        + "--recovery-delay=-1 --startup-recovery-delay=-1 --total-num-buckets=" + TOTAL_NUM_BUCKETS
        + " --partition-resolver=" + PARTITION_RESOLVER)
        .statusIsSuccess();

    gfsh.executeAndAssertThat("create region --name=" + COLOCATED_REGION_ONE
        + " --type=PARTITION --redundant-copies=" + NUM_REDUNDANT_COPIES
        + " --enable-statistics=true "
        + "--recovery-delay=-1 --startup-recovery-delay=-1 --total-num-buckets=" + TOTAL_NUM_BUCKETS
        + " --partition-resolver=" + PARTITION_RESOLVER
        + " --colocated-with=" + PARENT_REGION)
        .statusIsSuccess();

    gfsh.executeAndAssertThat("create region --name=" + COLOCATED_REGION_TWO
        + " --type=PARTITION --redundant-copies=" + NUM_REDUNDANT_COPIES
        + " --enable-statistics=true "
        + "--recovery-delay=-1 --startup-recovery-delay=-1 --total-num-buckets=" + TOTAL_NUM_BUCKETS
        + " --partition-resolver=" + PARTITION_RESOLVER
        + " --colocated-with=" + COLOCATED_REGION_ONE)
        .statusIsSuccess();
  }

  @Test
  public void testSecondRebalanceIsNotNecessaryWithAddedMembers() {
    addDataToRegion(NUMBER_OF_ENTRIES);

    addOrRestartServers(2, 0);

    CommandResultAssert firstRebalance = gfsh.executeAndAssertThat("rebalance").statusIsSuccess();

    String parentRegionTableSection = "";
    for (int i = 0; i < 3; i++) {
      if (firstRebalance.hasTableSection("Table" + i).getActual().getHeader()
          .contains(PARENT_REGION)) {
        parentRegionTableSection = "Table" + i;
      }
    }

    TabularResultModelAssert parentRegionTable =
        firstRebalance.hasTableSection(parentRegionTableSection);
    assertRedundancyNotChanged(parentRegionTable);
    assertBucketsMoved(parentRegionTable);
    assertPrimariesTransfered(parentRegionTable);

    CommandResultAssert secondRebalance =
        gfsh.executeAndAssertThat("rebalance").statusIsSuccess();

    for (int i = 0; i < 3; i++) {
      if (secondRebalance.hasTableSection("Table" + i).getActual().getHeader()
          .contains(PARENT_REGION)) {
        parentRegionTableSection = "Table" + i;
      }
    }

    parentRegionTable = secondRebalance.hasTableSection(parentRegionTableSection);
    assertRedundancyNotChanged(parentRegionTable);
    assertBucketsNotMoved(parentRegionTable);
    assertPrimariesNotTransfered(parentRegionTable);
  }

  @Test
  public void testSecondRebalanceIsNotNecessaryWithAddedAndRestartedMembers() {

    addDataToRegion(NUMBER_OF_ENTRIES);

    addOrRestartServers(2, 1);

    CommandResultAssert firstRebalance = gfsh.executeAndAssertThat("rebalance").statusIsSuccess();

    String parentRegionTableSection = "";
    for (int i = 0; i < 3; i++) {
      if (firstRebalance.hasTableSection("Table" + i).getActual().getHeader()
          .contains(PARENT_REGION)) {
        parentRegionTableSection = "Table" + i;
      }
    }

    TabularResultModelAssert parentRegionTable =
        firstRebalance.hasTableSection(parentRegionTableSection);
    assertRedundancyChanged(parentRegionTable);
    assertBucketsMoved(parentRegionTable);
    assertPrimariesTransfered(parentRegionTable);

    CommandResultAssert secondRebalance =
        gfsh.executeAndAssertThat("rebalance").statusIsSuccess();

    for (int i = 0; i < 3; i++) {
      if (secondRebalance.hasTableSection("Table" + i).getActual().getHeader()
          .contains(PARENT_REGION)) {
        parentRegionTableSection = "Table" + i;
      }
    }

    parentRegionTable = secondRebalance.hasTableSection(parentRegionTableSection);
    assertRedundancyNotChanged(parentRegionTable);
    assertBucketsNotMoved(parentRegionTable);
    assertPrimariesNotTransfered(parentRegionTable);
  }

  public void addDataToRegion(int entriesToAdd) {
    memberList.get(0).invoke(() -> {
      Cache cache = ClusterStartupRule.getCache();
      assertThat(cache).isNotNull();
      Region<String, String> region = cache.getRegion(PARENT_REGION);
      Region<String, String> colocatedRegionOne = cache.getRegion(COLOCATED_REGION_ONE);
      Region<String, String> colocatedRegionTwo = cache.getRegion(COLOCATED_REGION_TWO);

      for (int i = 0; i < entriesToAdd; i++) {
        region.put("key" + i, "value" + i);
        colocatedRegionOne.put("key" + i, "value" + i);
        colocatedRegionTwo.put("key" + i, "value" + i);
      }
    });
  }

  public void addOrRestartServers(int serversToAdd, int serversToRestart) {
    for (int i = 0; i < serversToAdd; ++i) {
      memberList.add(cluster.startServerVM(INITIAL_SERVERS + i, locator1.getPort()));
    }

    for (int i = 0; i < serversToRestart; ++i) {
      if (i < INITIAL_SERVERS && i < memberList.size()) {
        memberList.get(i).stop(false);
        memberList.remove(i);
        memberList.add(i, cluster.startServerVM(i + 1, locator1.getPort()));
      }
    }
  }

  // The following methods are provided to allow easier examination of the output of the rebalance
  // command
  private void assertRedundancyChanged(TabularResultModelAssert tabularResultModelAssert) {
    tabularResultModelAssert.hasRow(0).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALBUCKETCREATEBYTES).last().isNotEqualTo("0");
    tabularResultModelAssert.hasRow(1).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALBUCKETCREATETIM).last().isNotEqualTo("0");
    tabularResultModelAssert.hasRow(2).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALBUCKETCREATESCOMPLETED).last().isNotEqualTo("0");
  }

  private void assertRedundancyNotChanged(TabularResultModelAssert tabularResultModelAssert) {
    tabularResultModelAssert.hasRow(0)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALBUCKETCREATEBYTES, "0");
    tabularResultModelAssert.hasRow(1)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALBUCKETCREATETIM, "0");
    tabularResultModelAssert.hasRow(2)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALBUCKETCREATESCOMPLETED, "0");
  }

  private void assertBucketsMoved(TabularResultModelAssert tabularResultModelAssert) {
    tabularResultModelAssert.hasRow(3).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALBUCKETTRANSFERBYTES).last().isNotEqualTo("0");
    tabularResultModelAssert.hasRow(4).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALBUCKETTRANSFERTIME).last().isNotEqualTo("0");
    tabularResultModelAssert.hasRow(5).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALBUCKETTRANSFERSCOMPLETED).last()
        .isNotEqualTo("0");
  }

  private void assertBucketsNotMoved(TabularResultModelAssert tabularResultModelAssert) {
    tabularResultModelAssert.hasRow(3)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALBUCKETTRANSFERBYTES, "0");
    tabularResultModelAssert.hasRow(4)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALBUCKETTRANSFERTIME, "0");
    tabularResultModelAssert.hasRow(5)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALBUCKETTRANSFERSCOMPLETED, "0");
  }

  private void assertPrimariesTransfered(TabularResultModelAssert tabularResultModelAssert) {
    tabularResultModelAssert.hasRow(6).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALPRIMARYTRANSFERTIME).last().isNotEqualTo("0");
    tabularResultModelAssert.hasRow(7).asList()
        .contains(CliStrings.REBALANCE__MSG__TOTALPRIMARYTRANSFERSCOMPLETED).last()
        .isNotEqualTo("0");
  }

  private void assertPrimariesNotTransfered(TabularResultModelAssert tabularResultModelAssert) {
    tabularResultModelAssert.hasRow(6)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALPRIMARYTRANSFERTIME, "0");
    tabularResultModelAssert.hasRow(7)
        .containsExactly(CliStrings.REBALANCE__MSG__TOTALPRIMARYTRANSFERSCOMPLETED, "0");
  }
}


text:
#ifndef DateTimeChooserClient_h
#define DateTimeChooserClient_h

namespace WebCore {

class DateTimeChooserClient {
public:
    virtual ~DateTimeChooserClient() { }

    // Called when user picked a value.
    virtual void didChooseValue(const String&) = 0;
    // Called when chooser has ended.
    virtual void didEndChooser() = 0;
};

} // namespace WebCore
#endif // DateTimeChooserClient_h


text:
<?php

namespace app\modules\admin\models;

use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

class Orders extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'TimeStamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['order_time'],
                    //ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ];
    }

    public function getOrderTime()
    {
        return date('d-m-Y', $this->order_time);
    }

    public function getOrderProducts()
    {
        return $this->hasMany(OrderProducts::className(), ['order_id' => 'id']);
    }

    public function getCustomer()
    {
        return $this->hasOne(Customers::className(), ['id' => 'customer_id']);
    }
}


text:
exports.createListenerFunction = function(aListenerObject, aListenerFunction) {
    var returnFunction = function() {
        aListenerFunction.apply(aListenerObject, arguments);
    }
    return returnFunction;
};

exports.createSecureListenerFunction = function(aListenerObject, aListenerFunction) {
    var returnFunction = function() {
        try {
            aListenerFunction.apply(aListenerObject, arguments);
        } catch (theError) {
            console.log("An error occured: " + theError.message);
            // console.log(theError.stack);
        }
    }
    return returnFunction;
};

exports.createListenerFunctionWithArguments = function(aListenerObject, aListenerFunction, aArguments) {
    var returnFunction = function() {
        var argumentsArray = aArguments.concat([]); //MENOTE: can't concat arguments. It adds an object instead of all arguments.
        var currentArray = arguments;
        var currentArrayLength = currentArray.length;
        for (var i = 0; i < currentArrayLength; i++) {
            argumentsArray.push(currentArray[i]);
        }
        //console.log(arguments, arguments.length);
        //console.log(argumentsArray);
        aListenerFunction.apply(aListenerObject, argumentsArray);
    }
    return returnFunction;
};


text:
package com.datatype.BigDecimal;

import java.math.BigDecimal;

public class BigDecimalExample3 {
	public static void main(String[] args) {
        BigDecimal a = new BigDecimal("3");
        BigDecimal b = new BigDecimal("3.00");
        BigDecimal c = new BigDecimal("-2");

        System.out.println("a compared to b = "+a.compareTo(b)); //0
        System.out.println("a compared to c = "+a.compareTo(c)); //1
        System.out.println("b compared to a = "+b.compareTo(a)); //0
        System.out.println("b compared to c = "+b.compareTo(c)); //1
        System.out.println("c compared to a = "+c.compareTo(a)); //-1
        System.out.println("c compared to b = "+c.compareTo(b)); //-1
	}
}


text:
import os
from marionette import Marionette
os.system("firefox -marionette &")
cl = Marionette('localhost', port=2828)
cl.start_session()
cl.navigate("http://google.com")


text:
export default function Diff() {}

Diff.prototype = {
  diff(oldString, newString, options = {}) {
    let callback = options.callback;
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
    this.options = options;

    let self = this;

    function done(value) {
      if (callback) {
        setTimeout(function() { callback(undefined, value); }, 0);
        return true;
      } else {
        return value;
      }
    }

    // Allow subclasses to massage the input prior to running
    oldString = this.castInput(oldString);
    newString = this.castInput(newString);

    oldString = this.removeEmpty(this.tokenize(oldString));
    newString = this.removeEmpty(this.tokenize(newString));

    let newLen = newString.length, oldLen = oldString.length;
    let editLength = 1;
    let maxEditLength = newLen + oldLen;
    let bestPath = [{ newPos: -1, components: [] }];

    // Seed editLength = 0, i.e. the content starts with the same values
    let oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
    if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
      // Identity per the equality and tokenizer
      return done([{value: newString.join(''), count: newString.length}]);
    }

    // Main worker method. checks all permutations of a given edit length for acceptance.
    function execEditLength() {
      for (let diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
        let basePath;
        let addPath = bestPath[diagonalPath - 1],
            removePath = bestPath[diagonalPath + 1],
            oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
        if (addPath) {
          // No one else is going to attempt to use this value, clear it
          bestPath[diagonalPath - 1] = undefined;
        }

        let canAdd = addPath && addPath.newPos + 1 < newLen,
            canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
        if (!canAdd && !canRemove) {
          // If this path is a terminal then prune
          bestPath[diagonalPath] = undefined;
          continue;
        }

        // Select the diagonal that we want to branch from. We select the prior
        // path whose position in the new string is the farthest from the origin
        // and does not pass the bounds of the diff graph
        if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
          basePath = clonePath(removePath);
          self.pushComponent(basePath.components, undefined, true);
        } else {
          basePath = addPath;   // No need to clone, we've pulled it from the list
          basePath.newPos++;
          self.pushComponent(basePath.components, true, undefined);
        }

        oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);

        // If we have hit the end of both strings, then we are done
        if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
          return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
        } else {
          // Otherwise track this path as a potential candidate and continue.
          bestPath[diagonalPath] = basePath;
        }
      }

      editLength++;
    }

    // Performs the length of edit iteration. Is a bit fugly as this has to support the
    // sync and async mode which is never fun. Loops over execEditLength until a value
    // is produced.
    if (callback) {
      (function exec() {
        setTimeout(function() {
          // This should not happen, but we want to be safe.
          /* istanbul ignore next */
          if (editLength > maxEditLength) {
            return callback();
          }

          if (!execEditLength()) {
            exec();
          }
        }, 0);
      }());
    } else {
      while (editLength <= maxEditLength) {
        let ret = execEditLength();
        if (ret) {
          return ret;
        }
      }
    }
  },

  pushComponent(components, added, removed) {
    let last = components[components.length - 1];
    if (last && last.added === added && last.removed === removed) {
      // We need to clone here as the component clone operation is just
      // as shallow array clone
      components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
    } else {
      components.push({count: 1, added: added, removed: removed });
    }
  },
  extractCommon(basePath, newString, oldString, diagonalPath) {
    let newLen = newString.length,
        oldLen = oldString.length,
        newPos = basePath.newPos,
        oldPos = newPos - diagonalPath,

        commonCount = 0;
    while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
      newPos++;
      oldPos++;
      commonCount++;
    }

    if (commonCount) {
      basePath.components.push({count: commonCount});
    }

    basePath.newPos = newPos;
    return oldPos;
  },

  equals(left, right) {
    return left === right;
  },
  removeEmpty(array) {
    let ret = [];
    for (let i = 0; i < array.length; i++) {
      if (array[i]) {
        ret.push(array[i]);
      }
    }
    return ret;
  },
  castInput(value) {
    return value;
  },
  tokenize(value) {
    return value.split('');
  }
};

function buildValues(diff, components, newString, oldString, useLongestToken) {
  let componentPos = 0,
      componentLen = components.length,
      newPos = 0,
      oldPos = 0;

  for (; componentPos < componentLen; componentPos++) {
    let component = components[componentPos];
    if (!component.removed) {
      if (!component.added && useLongestToken) {
        let value = newString.slice(newPos, newPos + component.count);
        value = value.map(function(value, i) {
          let oldValue = oldString[oldPos + i];
          return oldValue.length > value.length ? oldValue : value;
        });

        component.value = value.join('');
      } else {
        component.value = newString.slice(newPos, newPos + component.count).join('');
      }
      newPos += component.count;

      // Common case
      if (!component.added) {
        oldPos += component.count;
      }
    } else {
      component.value = oldString.slice(oldPos, oldPos + component.count).join('');
      oldPos += component.count;

      // Reverse add and remove so removes are output first to match common convention
      // The diffing algorithm is tied to add then remove output and this is the simplest
      // route to get the desired output with minimal overhead.
      if (componentPos && components[componentPos - 1].added) {
        let tmp = components[componentPos - 1];
        components[componentPos - 1] = components[componentPos];
        components[componentPos] = tmp;
      }
    }
  }

  // Special case handle for when one terminal is ignored. For this case we merge the
  // terminal into the prior string and drop the change.
  let lastComponent = components[componentLen - 1];
  if (componentLen > 1
      && (lastComponent.added || lastComponent.removed)
      && diff.equals('', lastComponent.value)) {
    components[componentLen - 2].value += lastComponent.value;
    components.pop();
  }

  return components;
}

function clonePath(path) {
  return { newPos: path.newPos, components: path.components.slice(0) };
}


text:
"""
@brief      test log(time=40s)
"""
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder, add_missing_development_version
import ensae_teaching_cs

class TestNotebookEleves2016(unittest.TestCase):

    def setUp(self):
        add_missing_development_version(["pymyinstall", "pyensae", "pymmails", "jyquickhelper"],
                                        __file__, hide=True)

    def get_replacements(self):
        return {"https://archive.ics.uci.edu/ml/machine-learning-databases/00222/":
                "http://www.xavierdupre.fr/enseignement/complements/"}

    def test_notebook_runner_eleves(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")
        from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks
        temp = get_temp_folder(__file__, "temp_notebook_eleves_2016")
        keepnote = ls_notebooks("notebook_eleves/2016-2017")
        self.assertTrue(len(keepnote) > 0)
        execute_notebooks(temp, keepnote, (lambda i, n: True), fLOG=fLOG,
                          replacements=self.get_replacements(), dump=ensae_teaching_cs)

if __name__ == "__main__":
    unittest.main()


text:
/**
 * Gauge collections type.
 *
 * It is used ES5 declaration here, because babel
 * transpiles inheritance incorrectly in this case.
 *
 * @class Collection
 * @constructor
 */
export default function Collection () {
    Array.prototype.constructor.apply(this, arguments);
}

Collection.prototype = Object.create(Array.prototype);
Collection.prototype.constructor = Collection;

    /**
     * Returns gauge object by its identifier or index in the collection
     *
     * @param {string|number} id
     * @return {*}
     */
Collection.prototype.get = function(id) {
    if (typeof id === 'string') {
        let i = 0;
        let s = this.length;

        for (; i < s; i++) {
            let canvas = this[i].options.renderTo.tagName ?
                this[i].options.renderTo :
                /* istanbul ignore next: should be tested with e2e tests */
                document.getElementById(this[i].options.renderTo || '');

            if (canvas.getAttribute('id') === id) {
                return this[i];
            }
        }
    }

    else if (typeof id === 'number') {
        return this[id];
    }

    return null;
};

module.exports = Collection;


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* Field203.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System.IO;
using System.Linq;

using AM;
using AM.IO;
using AM.Runtime;

using CodeJam;

using JetBrains.Annotations;

#endregion

namespace ManagedIrbis.Fields
{
    /// <summary>
    /// В связи с ГОСТ 7.0.100-2018 введено 203 поле.
    /// Это поле содержит подполя: вид содержания,
    /// средства доступа, характеристика содержания.
    /// </summary>
    [PublicAPI]
    public sealed class Field203
        : IHandmadeSerializable
    {
        #region Constants

        /// <summary>
        /// Tag number.
        /// </summary>
        public const int Tag = 203;

        /// <summary>
        /// Known subfield codes.
        /// </summary>
        public const string KnownCodes = "12345678abcdefgikloptuvwxyz";

        #endregion

        #region Properties

        /// <summary>
        /// Вид содержания. Подполя A, B, D, E, F, G, I, K, L.
        /// </summary>
        [CanBeNull]
        [ItemCanBeNull]
        public string[] ContentType { get; set; }

        /// <summary>
        /// Средства доступа. Подполя C, 1, 2, 3, 4, 5, 6, 7, 8
        /// </summary>
        [CanBeNull]
        [ItemCanBeNull]
        public string[] Access { get; set; }

        /// <summary>
        /// Характеристика содержания.
        /// Подполя O, P, U, Y, T, R, W, Q, X, V, Z
        /// </summary>
        [CanBeNull]
        [ItemCanBeNull]
        public string[] ContentDescription { get; set; }

        #endregion

        #region Public methods

        /// <summary>
        /// Parse the field.
        /// </summary>
        [NotNull]
        public static Field203 Parse
            (
                [NotNull] RecordField field
            )
        {
            Code.NotNull(field, "field");

            Field203 result = new Field203
            {
                ContentType = Sequence.FromItems
                    (
                        field.GetFirstSubFieldValue('a'),
                        field.GetFirstSubFieldValue('b'),
                        field.GetFirstSubFieldValue('d'),
                        field.GetFirstSubFieldValue('e'),
                        field.GetFirstSubFieldValue('f'),
                        field.GetFirstSubFieldValue('g'),
                        field.GetFirstSubFieldValue('i'),
                        field.GetFirstSubFieldValue('k'),
                        field.GetFirstSubFieldValue('l')
                    )
                    .NonEmptyLines()
                    .ToArray(),

                Access = Sequence.FromItems
                    (
                        field.GetFirstSubFieldValue('c'),
                        field.GetFirstSubFieldValue('1'),
                        field.GetFirstSubFieldValue('2'),
                        field.GetFirstSubFieldValue('3'),
                        field.GetFirstSubFieldValue('4'),
                        field.GetFirstSubFieldValue('5'),
                        field.GetFirstSubFieldValue('6'),
                        field.GetFirstSubFieldValue('7'),
                        field.GetFirstSubFieldValue('8')
                    )
                    .NonEmptyLines()
                    .ToArray(),

                ContentDescription = Sequence.FromItems
                    (
                        field.GetFirstSubFieldValue('o'),
                        field.GetFirstSubFieldValue('p'),
                        field.GetFirstSubFieldValue('u'),
                        field.GetFirstSubFieldValue('y'),
                        field.GetFirstSubFieldValue('t'),
                        field.GetFirstSubFieldValue('r'),
                        field.GetFirstSubFieldValue('w'),
                        field.GetFirstSubFieldValue('q'),
                        field.GetFirstSubFieldValue('x'),
                        field.GetFirstSubFieldValue('v'),
                        field.GetFirstSubFieldValue('z')
                    )
                    .NonEmptyLines()
                    .ToArray()
            };

            return result;
        }

        #endregion

        #region IHandmadeSerializable members

        /// <inheritdoc cref="IHandmadeSerializable.RestoreFromStream" />
        public void RestoreFromStream
            (
                BinaryReader reader
            )
        {
            // TODO check whether this code actually works
            ContentType = reader.ReadNullableStringArray();
            Access = reader.ReadNullableStringArray();
            ContentDescription = reader.ReadNullableStringArray();
        }

        /// <inheritdoc cref="IHandmadeSerializable.SaveToStream" />
        public void SaveToStream
            (
                BinaryWriter writer
            )
        {
            writer
                .WriteNullableArray(ContentType)
                .WriteNullableArray(Access)
                .WriteNullableArray(ContentDescription);
        }

        #endregion
    }
}


text:
module Puppet::Parser::Functions
    newfunction(:latest_ant_binary, :type => :rvalue) do |args|
        versionmask=args[0]
        # We are using main mirror here because can't be sure about Apache Server config on every mirror. It could be Nginx, btw.
        %x(curl -L --stderr /dev/null 'https://downloads.apache.org/ant/binaries/?F=0&V=1' | grep -o '<li>.*href="apache-ant-#{versionmask}-bin.tar.gz"'  |  grep -o "apache-ant-#{versionmask}" | tail -1 | tr -d '\r').chomp
    end
end


text:
import { createStore, applyMiddleware, compose } from 'redux';
import promiseMiddleware from 'redux-promise-middleware';
import rootReducer from './reducers';

export default function configureStore(initializeState = {}) {
  const enhancers = [
    applyMiddleware(promiseMiddleware()),
  ];

  const store = createStore(rootReducer, initializeState, compose(...enhancers));

  // For hot reloading reducers
  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('./reducers', () => {
       // eslint-disable-line newline-after-import
      const nextReducer = require('./reducers').default;

      store.replaceReducer(nextReducer);
    });
  }

  return store;
}


text:
using System;

namespace Brick.FluentNHibernate.Conventions.Conventions.Attributes
{
    public class NotNullAttribute : Attribute
    {
    }
}


text:
SuperResolution
===============

Implementation of different Super Resolution algorithms:

1. S. Farsiu , D. Robinson, M. Elad, P. Milanfar. Fast and robust multiframe super resolution.
2. Dennis Mitzel, Thomas Pock, Thomas Schoenemann, Daniel Cremers. Video Super Resolution using Duality Based TV-L1 Optical Flow.


text:
/**
* Name        : Logic.cpp
* Description : C++ program for implementation of the logic of the program
*
*/

#include "Logic.hpp"

Logic::Logic(){
	setAlgorithmsNumber();
	setSelectedAlgorithms();
	setVectorsNumber();
	setSelectedVectors();
	setInitialVectorSize();
	setInterval();
	setIterations();
	openFiles();
}

/**
* A method that is responsible for setting the number of sorting
* algorithms used in the program.
*
*/

void Logic::setAlgorithmsNumber(){
	mAlgorithmsNumber = mSetter.setAlgorithmsNumber();
}

/**
* A method that is responsible for selecting of sorting algorithms
* used in the program and validating user's input.
*
*/

void Logic::setSelectedAlgorithms(){
	mSelectedAlgorithms = new unsigned int[mAlgorithmsNumber];
	int alreadySelectedAlgorithms=0;
	bool newAlgorithm;
	if (mAlgorithmsNumber < 7) {
		for (int i = 0; i < mAlgorithmsNumber; ++i){
			newAlgorithm = true;
			mSelectedAlgorithms[i] = mSetter.setAlgorithmType(i);
			for(int k = 0; k<alreadySelectedAlgorithms; ++k){
				if(mSelectedAlgorithms[i]==mSelectedAlgorithms[k]){
					std::cout<<"Algorithm already selected. Please select another algorithm"<<std::endl;
					--i;
					newAlgorithm = false;
					break;
				}
			}
			if(newAlgorithm){
			++alreadySelectedAlgorithms;
			}
		}
	} else {
		mAlgorithmsNumber = 7;
		for (int i = 0; i < mAlgorithmsNumber; ++i){
			mSelectedAlgorithms[i] = i + 1;
		}
	}
}

/**
* A method that is responsible for setting the number of vectors
* used in the program.
*
*/

void  Logic::setVectorsNumber(){
	mVectorsNumber = mSetter.setVectorsNumber();
}

/**
* A method that is responsible for selecting of vectors used in
* the program and validating user's input.
*
*/

void  Logic::setSelectedVectors(){
	mSelectedVectors = new unsigned int[mVectorsNumber];
	int alreadySelectedVectors=0;
	bool newVector;
	if (mVectorsNumber < 5) {
		for (int i = 0; i < mVectorsNumber; ++i){
			mSelectedVectors[i] = mSetter.setVectorType(i);
			newVector= true;
			for(int k = 0; k<alreadySelectedVectors; ++k){
				if(mSelectedVectors[i]==mSelectedVectors[k]){
					std::cout<<"Vector already selected. Please select another vector"<<std::endl;
					--i;
					newVector = false;
					break;
				}
			}
				if(newVector){
				++alreadySelectedVectors;
				}
		}
	} else {
		mVectorsNumber = 5;
		for (int i = 0; i < mVectorsNumber; ++i){
			mSelectedVectors[i] = i + 1;
		}
	}
}

/**
* A method that is responsible for setting the interval used to
* increase vector.
*
*/

void Logic::setInterval(){
	mInterval = mSetter.setInterval();
}

/**
* A method that is responsible for setting the number of
* iterations in which vector is increased.
*
*/

void Logic::setIterations(){
	mIterations = mSetter.setIterations();
}

/**
* A method that is responsible for setting the initial size of the
* vector.
*
*/

void Logic::setInitialVectorSize(){
	mVectorSize = mSetter.setVectorSize();
	mVectorToSort.resize(mVectorSize);
}

/**
* A method that is responsible for filling the vector with integers.
*
*/

void Logic::fillVector(int n){
	switch (mSelectedVectors[n]) {
	case 1:
		mGenerator.createSortedSet(mVectorToSort);
		break;
	case 2:
		mGenerator.createRandomSet(mVectorToSort);
		break;
	case 3:
		mGenerator.createBackwardSortedSet(mVectorToSort);
		break;
	case 4:
		mGenerator.createSortedSetWithFirstRandomValue(mVectorToSort);
		break;
	case 5:
		mGenerator.createBackwardSortedSetWithLastRandomValue(mVectorToSort);
		break;
	default:
		std::cout << "Vector filling failed!" << std::endl;
		break;
	}
}

/**
* A method that is responsible for opening files.
*
*/

void Logic::openFiles(){
	for (int i = 0; i < mAlgorithmsNumber; i++) {
			mLogger.openFile(mSelectedAlgorithms[i]);
	}
}

/**
* A method that is responsible for logging names of selected vectors.
*
*/

void Logic::logVectorTypes(int n){
	for (int i = 0; i < mAlgorithmsNumber; i++) {
		mLogger.logVectorType(mSelectedVectors[n],mSelectedAlgorithms[i]);
	}
}

/**
 * A method that is responsible for printing information regarding
 * sorting process being in progress to the console.
 *
 */

void Logic::printSortingInProgress(int algorithmNumber, int vectorNumber){
	std::string algorithmType, vectorType;

	switch (vectorNumber) {
		case 1:
			vectorType = "Sorted set";
			break;
		case 2:
			vectorType = "Random set";
			break;
		case 3:
			vectorType = "Backward sorted set";
			break;
		case 4:
			vectorType = "Sorted set with first random value";
			break;
		case 5:
			vectorType = "Backward sorted set with last random value";
			break;
		default:
			std::cout << "Unknown vector type" << std::endl;
			break;
		}

	switch (algorithmNumber) {
		case 1:
			algorithmType = "Bubble sort";
			break;
		case 2:
			algorithmType = "Quick sort";
			break;
		case 3:
			algorithmType = "Insertion sort";
			break;
		case 4:
			algorithmType = "Merge sort";
			break;
		case 5:
			algorithmType = "Counting sort";
			break;
		case 6:
			algorithmType = "Heap sort";
			break;
		case 7:
			algorithmType = "Shell sort";
			break;
		default:
			std::cout << "Unknown vector type" << std::endl;
			break;
		}

	std::cout<<"Sorting in progress: "<<algorithmType<<" on "<<vectorType<<std::endl;
}

/**
* A method that is responsible for extension of the vector and
* filling it with integers.
*
*/

void Logic::extendVector(int n){
	switch (mSelectedVectors[n]) {
		case 1:
			mGenerator.extendSortedSet(mVectorToSort, mInterval);
			break;
		case 2:
			mGenerator.extendRandomSet(mVectorToSort, mInterval);
			break;
		case 3:
			mGenerator.extendBackwardSortedSet(mVectorToSort, mInterval);
			break;
		case 4:
			mGenerator.extendSortedSetWithFirstRandomValue(mVectorToSort, mInterval);
			break;
		case 5:
			mGenerator.extendBackwardSortedSetWithLastRandomValue(mVectorToSort, mInterval);
			break;
		default:
			std::cout << "Vector extension failed!" << std::endl;
			break;
		}
}

/**
* A method that is responsible for logging sorting results into a CSV file.
*
*/

void Logic::logSortingToFile(int algorithmIndex, int iteration){
	mLogger.logSortingResults(mVectorSize + (iteration * mInterval), mSortingAlgorithm->getTime(), mSortingAlgorithm->getTransitions(),mSelectedAlgorithms[algorithmIndex]);
}

/**
* A method that is responsible for filling vector, sorting it and calling logging method.
*
*/

void Logic::sort(){
	for(int k=0; k<mVectorsNumber; ++k){
		fillVector(k);
		logVectorTypes(k);
		for(unsigned int i = 0; i <= mIterations; i++) {
			if (i) {
				extendVector(k);
			}
			for (int j = 0; j < mAlgorithmsNumber; j++) {
				mSortingAlgorithm = mAlgorithmSetter.setSortingAlgorithm(mSelectedAlgorithms[j]);
				printSortingInProgress(mSelectedAlgorithms[j], mSelectedVectors[k]);
				mSortingAlgorithm->sort(mVectorToSort);
				logSortingToFile(j,i);
			}
		}
		mVectorToSort.resize(mVectorSize);
	}
}

/**
* A dectructor that is responsible for deletion of dynamically
* allocated variables/arrays.
*
*/

Logic::~Logic(){
	delete mSortingAlgorithm;
	delete[] mSelectedAlgorithms;
	delete[] mSelectedVectors;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
  prefer="public">

  <public publicId="urn:pubid:dita4publishers.org:doctypes:dita:division"
    uri="division.dtd"
  />
  <system systemId="urn:pubid:dita4publishers.org:doctypes:dita:division.dtd"
    uri="division.dtd"
  />

  <public publicId="urn:pubid:dita4publishers.org:modules:division"
    uri="division.mod"
  />
  <system systemId="urn:pubid:dita4publishers.org:modules:division.mod"
    uri="division.mod"
  />

</catalog>


text:
package dao

import (
	"context"
	"go-common/app/interface/live/push-live/model"
	"go-common/library/log"
)

const (
	_getPushConfig   = "SELECT `type` FROM ap_push_config WHERE value=? ORDER BY `order` ASC" // 获取推送选项配置
	_getPushInterval = "SELECT `order` FROM ap_push_config WHERE type=?"                      // 获取推送间隔时间
)

// GetPushConfig 从DB中获取推送配置
func (d *Dao) GetPushConfig(c context.Context) (types []string, err error) {
	var t string
	types = make([]string, 0)
	rows, err := d.db.Query(c, _getPushConfig, model.LivePushConfigOn)
	if err != nil {
		log.Error("[dao.config|GetPushConfig] db.Query() error(%v)", err)
		return
	}
	for rows.Next() {
		if err = rows.Scan(&t); err != nil {
			log.Error("[dao.config|GetPushConfig] rows.Scan() error(%v)", err)
			return
		}
		types = append(types, t)
	}
	return
}

// GetPushInterval 获取推送时间间隔
func (d *Dao) GetPushInterval(c context.Context) (interval int32, err error) {
	var i int32
	row := d.db.QueryRow(c, _getPushInterval, model.PushIntervalKey)
	if err = row.Scan(&i); err != nil {
		log.Error("[dao.config|GetPushInterval] row.Scan() error(%v)", err)
		return
	}
	interval = i * 60 // min to sec
	return
}


text:
@interface PodsDummy_Pods_3DGridViewController_3DGridViewController : NSObject
@end
@implementation PodsDummy_Pods_3DGridViewController_3DGridViewController
@end


text:
class Postgresql < Formula
  desc "Object-relational database system"
  homepage "https://www.postgresql.org/"
  url "https://ftp.postgresql.org/pub/source/v13.3/postgresql-13.3.tar.bz2"
  sha256 "3cd9454fa8c7a6255b6743b767700925ead1b9ab0d7a0f9dcb1151010f8eb4a1"
  license "PostgreSQL"
  head "https://github.com/postgres/postgres.git"

  livecheck do
    url "https://ftp.postgresql.org/pub/source/"
    regex(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i)
  end

  bottle do
    sha256 arm64_big_sur: "7c0e1b76d60b428facd521c729323221712d7f6d9954e21da389aeeb2c62348e"
    sha256 big_sur:       "eaf28965ead970ecfb327b121ec6a07f0a4e39865797a1a0383605a17e5911e3"
    sha256 catalina:      "74e946503c73cd0efc55ad4b373efbd8f4fb8a9e26a670b878c6db25794aea4a"
    sha256 mojave:        "36c7bde4788571e5b66ffe05b6174b62c69781d61c53c3ebcd9d278e8f148197"
  end

  depends_on "pkg-config" => :build
  depends_on "icu4c"
  # GSSAPI provided by Kerberos.framework crashes when forked.
  # See https://github.com/Homebrew/homebrew-core/issues/47494.
  depends_on "krb5"
  depends_on "openssl@1.1"
  depends_on "readline"

  uses_from_macos "libxml2"
  uses_from_macos "libxslt"
  uses_from_macos "openldap"
  uses_from_macos "perl"

  on_linux do
    depends_on "linux-pam"
    depends_on "util-linux"
  end

  def install
    ENV.prepend "LDFLAGS", "-L#{Formula["openssl@1.1"].opt_lib} -L#{Formula["readline"].opt_lib}"
    ENV.prepend "CPPFLAGS", "-I#{Formula["openssl@1.1"].opt_include} -I#{Formula["readline"].opt_include}"

    args = %W[
      --disable-debug
      --prefix=#{prefix}
      --datadir=#{HOMEBREW_PREFIX}/share/postgresql
      --libdir=#{HOMEBREW_PREFIX}/lib
      --includedir=#{HOMEBREW_PREFIX}/include
      --sysconfdir=#{etc}
      --docdir=#{doc}
      --enable-thread-safety
      --with-gssapi
      --with-icu
      --with-ldap
      --with-libxml
      --with-libxslt
      --with-openssl
      --with-pam
      --with-perl
      --with-uuid=e2fs
    ]
    on_macos do
      args += %w[
        --with-bonjour
        --with-tcl
      ]
    end

    # PostgreSQL by default uses xcodebuild internally to determine this,
    # which does not work on CLT-only installs.
    args << "PG_SYSROOT=#{MacOS.sdk_path}" if MacOS.sdk_root_needed?

    system "./configure", *args
    system "make"
    system "make", "install-world", "datadir=#{pkgshare}",
                                    "libdir=#{lib}",
                                    "pkglibdir=#{lib}/postgresql",
                                    "includedir=#{include}",
                                    "pkgincludedir=#{include}/postgresql",
                                    "includedir_server=#{include}/postgresql/server",
                                    "includedir_internal=#{include}/postgresql/internal"

    on_linux do
      inreplace lib/"postgresql/pgxs/src/Makefile.global",
                "LD = #{HOMEBREW_PREFIX}/Homebrew/Library/Homebrew/shims/linux/super/ld",
                "LD = #{HOMEBREW_PREFIX}/bin/ld"
    end
  end

  def post_install
    (var/"log").mkpath
    postgresql_datadir.mkpath

    # Don't initialize database, it clashes when testing other PostgreSQL versions.
    return if ENV["HOMEBREW_GITHUB_ACTIONS"]

    system "#{bin}/initdb", "--locale=C", "-E", "UTF-8", postgresql_datadir unless pg_version_exists?
  end

  def postgresql_datadir
    var/"postgres"
  end

  def postgresql_log_path
    var/"log/postgres.log"
  end

  def pg_version_exists?
    (postgresql_datadir/"PG_VERSION").exist?
  end

  def caveats
    <<~EOS
      To migrate existing data from a previous major version of PostgreSQL run:
        brew postgresql-upgrade-database

      This formula has created a default database cluster with:
        initdb --locale=C -E UTF-8 #{postgresql_datadir}
      For more details, read:
        https://www.postgresql.org/docs/#{version.major}/app-initdb.html
    EOS
  end

  plist_options manual: "pg_ctl -D #{HOMEBREW_PREFIX}/var/postgres start"

  def plist
    <<~EOS
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>KeepAlive</key>
        <true/>
        <key>Label</key>
        <string>#{plist_name}</string>
        <key>ProgramArguments</key>
        <array>
          <string>#{opt_bin}/postgres</string>
          <string>-D</string>
          <string>#{postgresql_datadir}</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>WorkingDirectory</key>
        <string>#{HOMEBREW_PREFIX}</string>
        <key>StandardOutPath</key>
        <string>#{postgresql_log_path}</string>
        <key>StandardErrorPath</key>
        <string>#{postgresql_log_path}</string>
      </dict>
      </plist>
    EOS
  end

  test do
    system "#{bin}/initdb", testpath/"test" unless ENV["HOMEBREW_GITHUB_ACTIONS"]
    assert_equal "#{HOMEBREW_PREFIX}/share/postgresql", shell_output("#{bin}/pg_config --sharedir").chomp
    assert_equal "#{HOMEBREW_PREFIX}/lib", shell_output("#{bin}/pg_config --libdir").chomp
    assert_equal "#{HOMEBREW_PREFIX}/lib/postgresql", shell_output("#{bin}/pg_config --pkglibdir").chomp
  end
end


text:
use serde::Serialize;
use serde::Deserialize;

use serde_json;

use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::thread;
use std::time::*;

pub enum Algorithm {
    MCTS,
    MTDF,
    PVS,
    BNS,
}

fn mcts_rounds() -> isize{-1}
fn solve_depth() -> u8 {21}

#[derive(Serialize, Deserialize, Debug)]
pub struct CoinCfg {
    // mode : Algorithm,
    pub model_file : String,
    pub heuristic_directory : String,
    #[serde(default = "solve_depth")]
    pub solve_depth : u8,
    #[serde(default = "mcts_rounds")]
    pub mcts_rounds : isize,
}

impl CoinCfg {
    pub fn from_bytes(buf : &[u8]) -> CoinCfg {
        let config : CoinCfg = serde_json::from_slice(buf).unwrap();

        config
    }
    pub fn from_path(path : &Path) -> CoinCfg {
        let mut buf = vec![];

        while let Err(_) = File::open(path).map(|mut fd| fd.read_to_end(&mut buf)) {
            thread::sleep(Duration::from_millis(100));
        };

        let config : CoinCfg = serde_json::from_slice(&buf).unwrap();

        config
    }
}


text:
if [[ $TRAVIS_BRANCH == 'master' ]]
then
	cp ./keys/pubring.gpg $HOME/.gnupg/pubring.gpg && cp ./keys/secring.gpg $HOME/.gnupg/secring.gpg && cp ./keys/trustdb.gpg $HOME/.gnupg/trustdb.gpg && mvn -s ./.travis.settings.xml deploy -DskipTests && mvn site;
fi


text:
class City < ActiveRecord::Base
  belongs_to :state

  validates :state_id, :presence => true
  validates :name, :presence => true
  validates :longitude, :presence => true
  validates :latitude, :presence => true

  def name_state_abbreviation
    [name, state.abbreviation].join(' - ')
  end

  def state_name
    state.name
  end
end


text:
void NetworkLobbyStage::Begin()
{
}

void NetworkLobbyStage::Pause()
{
}

void NetworkLobbyStage::Resume()
{
}

void NetworkLobbyStage::Finish()
{
}

void NetworkLobbyStage::Event( FwEvent* e )
{
	if( e->Type == EVENT_KEY_DOWN || e->Type == EVENT_JOYSTICK_BUTTON_DOWN )
	{
		delete Framework::SystemFramework->ProgramStages->Pop();
	}
}

void NetworkLobbyStage::Update()
{
}

void NetworkLobbyStage::Render()
{
	ALLEGRO_FONT* optionFont = Framework::SystemFramework->GetFontManager()->GetFont( "resource/falsepos.ttf", Framework::SystemFramework->GetDisplayHeight() / 12, 0 );
	int opFntH = al_get_font_line_height( optionFont );
	int qtrX = Framework::SystemFramework->GetDisplayWidth() / 4;
	int qtrY = Framework::SystemFramework->GetDisplayHeight() / 3;

	Framework::SystemFramework->ProgramStages->Previous( this )->Render();

	al_draw_filled_rectangle( 0, 0, qtrX * 4, qtrY * 3, al_map_rgba( 0, 0, 0, 128 ) );

	al_draw_filled_rounded_rectangle( qtrX, qtrY, qtrX * 3, qtrY * 2, 8, 8, al_map_rgb( 0, 0, 0 ) );

	al_draw_text( optionFont, al_map_rgb( 255, 255, 255 ), (qtrX * 2) - (al_get_text_width( optionFont, "Under Development" ) / 2), (Framework::SystemFramework->GetDisplayHeight() / 2) - (opFntH * 1.5), 0, "Under Development" );
	al_draw_text( optionFont, al_map_rgb( 255, 255, 255 ), (qtrX * 2) - (al_get_text_width( optionFont, "Press Any Key" ) / 2), (Framework::SystemFramework->GetDisplayHeight() / 2) + (opFntH / 2), 0, "Press Any Key" );
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Xml.Linq;

namespace TiledSharp
{
    public class TmxObjectGroup : ITmxElement
    {
        public string Name {get; private set;}
        public TmxColor Color {get; private set;}
        public DrawOrderType DrawOrder {get; private set;}
        public double Opacity {get; private set;}
        public bool Visible {get; private set;}

        public TmxList<TmxObject> Objects {get; private set;}
        public PropertyDict Properties {get; private set;}

        public TmxObjectGroup(XElement xObjectGroup)
        {
            Name = (string)xObjectGroup.Attribute("name") ?? String.Empty;
            Color = new TmxColor(xObjectGroup.Attribute("color"));
            Opacity = (double?)xObjectGroup.Attribute("opacity") ?? 1.0;
            Visible = (bool?)xObjectGroup.Attribute("visible") ?? true;

            var drawOrderDict = new Dictionary<string, DrawOrderType> {
                {"unknown", DrawOrderType.UnknownOrder},
                {"topdown", DrawOrderType.IndexOrder},
                {"index", DrawOrderType.TopDown}
            };

            var drawOrderValue = (string) xObjectGroup.Attribute("draworder");
            if (drawOrderValue != null)
                DrawOrder = drawOrderDict[drawOrderValue];

            Objects = new TmxList<TmxObject>();
            foreach (var e in xObjectGroup.Elements("object"))
                Objects.Add(new TmxObject(e));

            Properties = new PropertyDict(xObjectGroup.Element("properties"));
        }
    }

    public class TmxObject : ITmxElement
    {
        // Many TmxObjectTypes are distinguished by null values in fields
        // It might be smart to subclass TmxObject
        public int Id { get; private set; }
        public string Name {get; private set;}
        public TmxObjectType ObjectType {get; private set;}
        public string Type {get; private set;}
        public double X {get; private set;}
        public double Y {get; private set;}
        public double Width {get; private set;}
        public double Height {get; private set;}
        public double Rotation {get; private set;}
        public TmxLayerTile Tile {get; private set;}
        public bool Visible {get; private set;}

        public Collection<TmxObjectPoint> Points {get; private set;}
        public PropertyDict Properties {get; private set;}

        public TmxObject(XElement xObject)
        {
            Id = (int)xObject.Attribute("id");
            Name = (string)xObject.Attribute("name") ?? String.Empty;
            X = (double)xObject.Attribute("x");
            Y = (double)xObject.Attribute("y");
            Width = (double?)xObject.Attribute("width") ?? 0.0;
            Height = (double?)xObject.Attribute("height") ?? 0.0;
            Type = (string)xObject.Attribute("type") ?? String.Empty;
            Visible = (bool?)xObject.Attribute("visible") ?? true;
            Rotation = (double?)xObject.Attribute("rotation") ?? 0.0;

            // Assess object type and assign appropriate content
            var xGid = xObject.Attribute("gid");
            var xEllipse = xObject.Element("ellipse");
            var xPolygon = xObject.Element("polygon");
            var xPolyline = xObject.Element("polyline");

            if (xGid != null)
            {
                Tile = new TmxLayerTile((uint)xGid,
                    Convert.ToInt32(Math.Round(X)),
                    Convert.ToInt32(Math.Round(X)));
                ObjectType = TmxObjectType.Tile;
            }
            else if (xEllipse != null)
            {
                ObjectType = TmxObjectType.Ellipse;
            }
            else if (xPolygon != null)
            {
                Points = ParsePoints(xPolygon);
                ObjectType = TmxObjectType.Polygon;
            }
            else if (xPolyline != null)
            {
                Points = ParsePoints(xPolyline);
                ObjectType = TmxObjectType.Polyline;
            }
            else ObjectType = TmxObjectType.Basic;

            Properties = new PropertyDict(xObject.Element("properties"));
        }

        public Collection<TmxObjectPoint> ParsePoints(XElement xPoints)
        {
            var points = new Collection<TmxObjectPoint>();

            var pointString = (string)xPoints.Attribute("points");
            var pointStringPair = pointString.Split(' ');
            foreach (var s in pointStringPair)
            {
                var pt = new TmxObjectPoint(s);
                points.Add(pt);
            }
            return points;
        }
    }

    public class TmxObjectPoint
    {
        public double X {get; private set;}
        public double Y {get; private set;}

        public TmxObjectPoint(double x, double y)
        {
            X = x;
            Y = y;
        }

        public TmxObjectPoint(string s)
        {
            var pt = s.Split(',');
            X = double.Parse(pt[0]);
            Y = double.Parse(pt[1]);
        }
    }

    public enum TmxObjectType
    {
        Basic,
        Tile,
        Ellipse,
        Polygon,
        Polyline
    }

    public enum DrawOrderType
    {
        UnknownOrder = -1,
        TopDown,
        IndexOrder
    }
}


text:
package org.apache.spark.mllib.linalg

import scala.util.Random

import org.scalatest.BeforeAndAfterAll
import org.scalatest.FunSuite

import org.jblas.{DoubleMatrix, Singular, MatrixFunctions}

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.RDD

import org.jblas._

class SVDSuite extends FunSuite with BeforeAndAfterAll {
  @transient private var sc: SparkContext = _

  override def beforeAll() {
    sc = new SparkContext("local", "test")
  }

  override def afterAll() {
    sc.stop()
    System.clearProperty("spark.driver.port")
  }

  val EPSILON = 1e-4

  // Return jblas matrix from sparse matrix RDD
  def getDenseMatrix(matrix: SparseMatrix) : DoubleMatrix = {
    val data = matrix.data
    val m = matrix.m
    val n = matrix.n
    val ret = DoubleMatrix.zeros(m, n)
    matrix.data.toArray.map(x => ret.put(x.i, x.j, x.mval))
    ret
  }

  def assertMatrixEquals(a: DoubleMatrix, b: DoubleMatrix) {
    assert(a.rows == b.rows && a.columns == b.columns, "dimension mismatch")
    val diff = DoubleMatrix.zeros(a.rows, a.columns)
    Array.tabulate(a.rows, a.columns){(i, j) =>
      diff.put(i, j,
          Math.min(Math.abs(a.get(i, j) - b.get(i, j)),
          Math.abs(a.get(i, j) + b.get(i, j))))  }
    assert(diff.norm1 < EPSILON, "matrix mismatch: " + diff.norm1)
  }

  test("full rank matrix svd") {
    val m = 10
    val n = 3
    val data = sc.makeRDD(Array.tabulate(m,n){ (a, b) =>
      MatrixEntry(a, b, (a + 2).toDouble * (b + 1) / (1 + a + b)) }.flatten )

    val a = SparseMatrix(data, m, n)

    val decomposed = SVD.sparseSVD(a, n)
    val u = decomposed.U
    val v = decomposed.V
    val s = decomposed.S

    val densea = getDenseMatrix(a)
    val svd = Singular.sparseSVD(densea)

    val retu = getDenseMatrix(u)
    val rets = getDenseMatrix(s)
    val retv = getDenseMatrix(v)

    // check individual decomposition
    assertMatrixEquals(retu, svd(0))
    assertMatrixEquals(rets, DoubleMatrix.diag(svd(1)))
    assertMatrixEquals(retv, svd(2))

    // check multiplication guarantee
    assertMatrixEquals(retu.mmul(rets).mmul(retv.transpose), densea)
  }

 test("rank one matrix svd") {
    val m = 10
    val n = 3
    val data = sc.makeRDD(Array.tabulate(m, n){ (a,b) =>
      MatrixEntry(a, b, 1.0) }.flatten )
    val k = 1

    val a = SparseMatrix(data, m, n)

    val decomposed = SVD.sparseSVD(a, k)
    val u = decomposed.U
    val s = decomposed.S
    val v = decomposed.V
    val retrank = s.data.toArray.length

    assert(retrank == 1, "rank returned not one")

    val densea = getDenseMatrix(a)
    val svd = Singular.sparseSVD(densea)

    val retu = getDenseMatrix(u)
    val rets = getDenseMatrix(s)
    val retv = getDenseMatrix(v)

    // check individual decomposition
    assertMatrixEquals(retu, svd(0).getColumn(0))
    assertMatrixEquals(rets, DoubleMatrix.diag(svd(1).getRow(0)))
    assertMatrixEquals(retv, svd(2).getColumn(0))

     // check multiplication guarantee
    assertMatrixEquals(retu.mmul(rets).mmul(retv.transpose), densea)
  }

 test("truncated with k") {
    val m = 10
    val n = 3
    val data = sc.makeRDD(Array.tabulate(m,n){ (a, b) =>
      MatrixEntry(a, b, (a + 2).toDouble * (b + 1)/(1 + a + b)) }.flatten )
    val a = SparseMatrix(data, m, n)

    val k = 1 // only one svalue above this

    val decomposed = SVD.sparseSVD(a, k)
    val u = decomposed.U
    val s = decomposed.S
    val v = decomposed.V
    val retrank = s.data.toArray.length

    val densea = getDenseMatrix(a)
    val svd = Singular.sparseSVD(densea)

    val retu = getDenseMatrix(u)
    val rets = getDenseMatrix(s)
    val retv = getDenseMatrix(v)

    assert(retrank == 1, "rank returned not one")

    // check individual decomposition
    assertMatrixEquals(retu, svd(0).getColumn(0))
    assertMatrixEquals(rets, DoubleMatrix.diag(svd(1).getRow(0)))
    assertMatrixEquals(retv, svd(2).getColumn(0))
  }
}


text:
package ubic.gemma.model.genome.gene;

public class Multifunctionality implements java.io.Serializable {

    private static final long serialVersionUID = 1842256912459855071L;
    private Double score;
    private Double rank;
    private Integer numGoTerms;
    private Long id;

    /**
     * No-arg constructor added to satisfy javabean contract
     *
     * @author Paul
     */
    @SuppressWarnings("WeakerAccess") // Required by spring
    public Multifunctionality() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId( Long id ) {
        this.id = id;
    }

    /**
     * @return The number of GO terms the gene has, after propagation, but excluding the roots
     */
    public Integer getNumGoTerms() {
        return this.numGoTerms;
    }

    public void setNumGoTerms( Integer numGoTerms ) {
        this.numGoTerms = numGoTerms;
    }

    /**
     * @return The relative rank of the gene among other genes in the taxon, based on the multifunctionality score (not the
     * number of GO terms, though that would generally give a similar result). A rank of 1 means the
     * "most multifunctional", while 0 is assigned to the least multifunctional gene.
     */
    public Double getRank() {
        return this.rank;
    }

    public void setRank( Double rank ) {
        this.rank = rank;
    }

    /**
     * @return The multifunctionality of the gene, as scored using the "optimal ranking" method of Gillis and Pavlidis (2011).
     * It is a value from 0 to 1, where 1 is the highest multifunctionality. Note that this score is not very useful by
     * itself as it really only makes sense as a relative measure among genes. Thus the rank should be used for display.
     */
    public Double getScore() {
        return this.score;
    }

    public void setScore( Double score ) {
        this.score = score;
    }

    @Override
    public int hashCode() {
        int hashCode = 0;
        hashCode = 29 * hashCode + ( id == null ? 0 : id.hashCode() );

        return hashCode;
    }

    @Override
    public boolean equals( Object object ) {
        if ( this == object ) {
            return true;
        }
        if ( !( object instanceof Multifunctionality ) ) {
            return false;
        }
        final Multifunctionality that = ( Multifunctionality ) object;
        return this.id != null && that.getId() != null && this.id.equals( that.getId() );
    }

    @Override
    public String toString() {
        return String.format( "terms=%d score=%.2f rank=%.3f", this.numGoTerms, this.score, this.rank );
    }

    public static final class Factory {
        public static Multifunctionality newInstance() {
            return new Multifunctionality();
        }
    }

}


text:
package com.oprisnik.semdroid.feature.instance.method;

import com.oprisnik.semdroid.app.DexMethod;
import com.oprisnik.semdroid.app.LocalVariable;
import com.oprisnik.semdroid.app.MethodCall;
import com.oprisnik.semdroid.feature.instance.MethodInstanceGenerator;
import com.oprisnik.semdroid.utils.DexUtils;

import java.util.HashSet;
import java.util.Set;

import at.tuflowgraphy.semantic.base.domain.data.InstanceDataElement;

/**
 * Method instance generator for SMS plugins.
 */
public class SmsMIG2 extends MethodInstanceGenerator {

    private static final String TAG = "SmsMIG2";

    @Override
    protected void getMethodInstance(DexMethod method,
                                     InstanceDataElement results) {
//        double[] histogram = getOpcodeHistogram(method, true);
//        results.addValue(getDistanceBasedFeatureDataElement("opcodes",
//                histogram));

        Set<String> localVarSet = new HashSet<String>();
        Set<String> invokesSet = new HashSet<String>();

        for (LocalVariable l : method.getLocalVariables(getMethodCallInclusionDepth())) {
            String type = l.getType();
            if (type != null
                    && (DexUtils.isBasicDataType(type) || DexUtils
                    .dataTypeStartsWith(type, "android.telephony"))) {
                localVarSet.add(type);
            }
        }
        for (MethodCall mc : method.getMethodCalls(getMethodCallInclusionDepth())) {
            if (mc.getClassName().startsWith("android.telephony")) {
                invokesSet.add(mc.getName());
            }
        }

        for (String classname : invokesSet) {
            results.addValue(getSymbolicFeatureDataElement("invokes", classname));
//            Log.v(TAG, "invokes: " + classname);
        }
        for (String type : localVarSet) {
            results.addValue(getSymbolicFeatureDataElement("localVar", type));
//            Log.v(TAG, "LocalVar: " + type);
        }

    }

}


text:
"""Copyright 2008 Orbitz WorldWide
   Copyright 2011 Chris Davis

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."""

from graphite.logger import log
import time
try:
  from hashlib import md5
except ImportError:
  from md5 import md5
import bisect

def hashRequest(request):
  # Normalize the request parameters so ensure we're deterministic
  queryParams = ["%s=%s" % (key, '&'.join(values))
                 for (key,values) in request.GET.lists()
                 if not key.startswith('_')]

  normalizedParams = ','.join( sorted(queryParams) ) or 'noParam'
  myHash = stripControlChars(normalizedParams) #memcached doesn't like unprintable characters in its keys

  if len(myHash) > 249: #memcached key size limitation
    return compactHash(myHash)
  else:
    return myHash

def hashData(targets, startTime, endTime):
  targetsString = ','.join(targets)
  startTimeString = startTime.strftime("%Y%m%d_%H%M")
  endTimeString = endTime.strftime("%Y%m%d_%H%M")
  myHash = targetsString + '@' + startTimeString + ':' + endTimeString
  myHash = stripControlChars(myHash)
  if len(myHash) > 249:
    return compactHash(myHash)
  else:
    return myHash

def stripControlChars(string):
  return filter(lambda char: ord(char) >= 33, string)

def compactHash(string):
  hash = md5()
  hash.update(string)
  return hash.hexdigest()

class ConsistentHashRing:
  def __init__(self, nodes, replica_count=100):
    self.ring = []
    self.replica_count = replica_count
    for node in nodes:
      self.add_node(node)

  def compute_ring_position(self, key):
    big_hash = md5( str(key) ).hexdigest()
    small_hash = int(big_hash[:4], 16)
    return small_hash

  def add_node(self, key):
    for i in range(self.replica_count):
      replica_key = "%s:%d" % (key, i)
      position = self.compute_ring_position(replica_key)
      entry = (position, key)
      bisect.insort(self.ring, entry)

  def remove_node(self, key):
    self.ring = [entry for entry in self.ring if entry[1] != key]

  def get_node(self, key):
    position = self.compute_ring_position(key)
    search_entry = (position, None)
    index = bisect.bisect_left(self.ring, search_entry)
    index %= len(self.ring)
    entry = self.ring[index]
    return entry[1]


text:
'''
To retrieve and parse application setting and resources file
'''

from liaar.lib import path, parser, exception, logger, setting
import re
import os

# to hold all applications' configuration in memory
apps = {}

def add_app(app_name, version, setting):
    '''
    Add a new application to in-memory dictionary
    '''
    apps[app_name] = {}
    apps[app_name][version] = {}
    apps[app_name][version]['resources'] = {}
    apps[app_name][version]['setting'] = setting
    # add log
    logger.info('Adding application `%s`' % app_name)

def add_resource(app_name, version, resource_name):
    '''
    Add a new resource to in-memory dictionary
    '''
    if not apps.has_key(app_name):
        exception.handle('Undefined `app_name`, call `add_app` before `add_resource`')

    if not apps[app_name].has_key(version):
        exception.handle('Undefined app version')

    apps[app_name][version]['resources'][resource_name] = {}

    # add log
    logger.info('Adding resource `%s` to application `%s`' % (resource_name, app_name))

def add_method(app_name, version, resource_name, method_name, method_setting):
    '''
    Add a new method to in-memory dictionary
    '''
    if not apps.has_key(app_name):
        exception.handle('Undefined `app_name`, call `add_app` before `add_resource`')

    if not apps[app_name].has_key(version):
        exception.handle('Undefined app version')

    if not apps[app_name][version]['resources'].has_key(resource_name):
        exception.handle('Undefined resource name')

    apps[app_name][version]['resources'][resource_name][method_name] = method_setting

    # add log
    logger.info('Adding method `%s` to resource `%s`' % (method_name, resource_name))

def get_method(app_name, version, resource_name, method_name):
    '''
    Get method's setting
    '''
    try:
        return apps[app_name][version]['resources'][resource_name][method_name]
    except KeyError:
        exception.handle('No method found')

def get_apps():
    '''
    To get all available applications
    '''

    apps_list = []

    apps_path = os.path.abspath(setting.APPS_DIRECTORY)

    for app_item in os.listdir(apps_path):
        # check if it's a directory
        app_abs_path = os.path.join(apps_path, app_item)
        if os.path.isdir(app_abs_path):
            apps_list.append(app_item)

    return apps_list

def get_resources(app_name):
    '''
    Get the list of resource directories
    '''
    resources_list = []

    resources_path = path.get_resources_abs_path(app_name)

    # get all files and folders from resource directory
    for resource in os.listdir(resources_path):
        # check if it's a directory
        resource_abs_path = os.path.abspath(os.path.join(resources_path,
                                                         resource))
        if os.path.isdir(resource_abs_path):
            resources_list.append(resource)

    return resources_list

def get_methods(app_name, resource_name):
    '''
    Get all methods of given resource name
    '''
    methods_list = []

    resource_abs_path = path.get_resource_abs_path(app_name, resource_name)

    for method_name in os.listdir(resource_abs_path):
        name_re = re.match('^(.+)\.json$', method_name)
        if name_re:
            methods_list.append(name_re.group(1))

    return methods_list

def get_app_setting(app_name):
    '''
    Get application's setting
    '''
    parsed_file = parser.load_and_parse(path.get_app_setting_filename(app_name))
    # add application name to setting dictionary
    parsed_file['name'] = app_name
    return parsed_file


text:
package fr.imie.training.cdi13.dav.tptests.bank;

public class BankAccountFTO extends BankAccount {

}


text:
-- =============================================
-- Author:		Stephen Mooney
-- Create date: 04/04/11
-- Description:	retrieves properties for all customer types from h3giAccChangeCustomerTypeProperties
-- =============================================
CREATE PROCEDURE [dbo].[h3giAccChangeGetCustomerTypeProperties]
AS
BEGIN

	SELECT * FROM h3giAccChangeCustomerTypeProperties

END

GRANT EXECUTE ON h3giAccChangeGetCustomerTypeProperties TO b4nuser
GO


text:
@font-face {font-family: "iconfont";
  src: url('iconfont.eot'); /* IE9*/
  src: url('iconfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
  url('iconfont.woff') format('woff'), /* chrome、firefox */
  url('iconfont.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
  url('iconfont.svg#iconfont') format('svg'); /* iOS 4.1- */
}

.iconfont {
  font-family:"iconfont" !important;
  font-size:16px;
  margin-right:5px;
  font-style:normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}
.icon-hebing:before { content: "\f0002"; }
.icon-category:before { content: "\e699"; }
.icon-shangyouquan:before { content: "\e604"; }
.icon-shengyijing:before { content: "\e605"; }
.icon-wodeali:before { content: "\e606"; }
.icon-xiangce:before { content: "\e608"; }
.icon-renmai:before { content: "\e609"; }
.icon-zanxiangao:before { content: "\e619"; }
.icon-yonghuxiangao:before { content: "\e617"; }
.icon-xiaoxixiangao:before { content: "\e614"; }
.icon-wodezhuye:before { content: "\e625"; }
.icon-gerenziliao:before { content: "\e624"; }
.icon-kantazhuanlan:before { content: "\e626"; }
.icon-faxiaoxi:before { content: "\e62b"; }
.icon-huida:before { content: "\e62c"; }
.icon-lianxi:before { content: "\e62d"; }
.icon-shanchu:before { content: "\e62e"; }
.icon-shezhi:before { content: "\e62f"; }
.icon-shuaxin:before { content: "\e630"; }
.icon-sousuo:before { content: "\e631"; }
.icon-xinxi:before { content: "\e633"; }
.icon-yingyong:before { content: "\e634"; }
.icon-shijian:before { content: "\e635"; }
.icon-yonghu:before { content: "\e638"; }
.icon-baocun:before { content: "\e63c"; }
.icon-gengduo:before { content: "\e642"; }
.icon-jisuanqi:before { content: "\e644"; }
.icon-queding:before { content: "\e64a"; }
.icon-shoucang:before { content: "\e64b"; }
.icon-huifu:before { content: "\e655"; }
.icon-luntanquan:before { content: "\e65b"; }
.icon-jiantouyou:before { content: "\e66f"; }
.icon-jiantouzuo:before { content: "\e670"; }
.icon-huifu1:before { content: "\e671"; }
.icon-liebiao:before { content: "\e648"; }
.icon-more:before { content: "\e6a7"; }
.icon-moreunfold:before { content: "\e6a6"; }
.icon-less:before { content: "\e6a5"; }
.icon-selected:before { content: "\e6ad"; }
.icon-refresh:before { content: "\e6aa"; }
.icon-qrcode:before { content: "\e6a9"; }
.icon-all:before { content: "\e696"; }
.icon-back:before { content: "\e697"; }
.icon-close:before { content: "\e69a"; }
.icon-add:before { content: "\e6b9"; }
.icon-locationfill:before { content: "\e650"; }
.icon-like:before { content: "\e669"; }
.icon-notificationfill:before { content: "\e66a"; }
.icon-notification:before { content: "\e66b"; }
.icon-samefill:before { content: "\e66d"; }
.icon-same:before { content: "\e66e"; }
.icon-friendfill:before { content: "\e726"; }
.icon-new:before { content: "\e71e"; }
.icon-pullleft:before { content: "\e71f"; }
.icon-pullright:before { content: "\e720"; }
.icon-rank:before { content: "\e722"; }
.icon-rankfill:before { content: "\e721"; }
.icon-apps:before { content: "\e729"; }
.icon-down:before { content: "\e703"; }
.icon-forward:before { content: "\e6eb"; }
.icon-forwardfill:before { content: "\e6ea"; }
.icon-appreciatefill:before { content: "\e6e3"; }
.icon-infofill:before { content: "\e6e4"; }
.icon-info:before { content: "\e6e5"; }
.icon-homefill:before { content: "\e6bb"; }
.icon-message:before { content: "\e6bc"; }
.icon-home:before { content: "\e6b8"; }
.icon-delete:before { content: "\e6b4"; }
.icon-cartfill:before { content: "\e6b9"; }
.icon-cart:before { content: "\e6af"; }
.icon-qrcode1:before { content: "\e6b0"; }
.icon-pulldown:before { content: "\e69f"; }
.icon-myfill:before { content: "\e685"; }
.icon-more1:before { content: "\e684"; }
.icon-cascades:before { content: "\e67c"; }
.icon-tag:before { content: "\e670"; }
.icon-friendaddfill:before { content: "\e6c9"; }
.icon-friendadd:before { content: "\e6ca"; }
.icon-friendfamous:before { content: "\e6cb"; }
.icon-friend:before { content: "\e6cc"; }
.icon-squarecheckfill:before { content: "\e6d4"; }
.icon-squarecheck:before { content: "\e6d6"; }
.icon-roundaddfill:before { content: "\e6d8"; }
.icon-roundadd:before { content: "\e6d9"; }
.icon-add:before { content: "\e6da"; }
.icon-info:before { content: "\e6e5"; }
.icon-forward:before { content: "\e6eb"; }
.icon-forwardfill:before { content: "\e6ea"; }
.icon-friendfill:before { content: "\e726"; }
.icon-newfill:before { content: "\e71d"; }
.icon-new:before { content: "\e71e"; }
.icon-pullleft:before { content: "\e71f"; }
.icon-pullright:before { content: "\e720"; }
.icon-refresharrow:before { content: "\e72d"; }


text:
package genetic.gui;

import genetic.data.Parameter;

import java.awt.BorderLayout;
import java.util.Hashtable;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * {@link JPanel} displaying the simulation's {@link Parameter}.
 *
 * @author Tim Wiederhake
 */
public class JParameterPane extends JPanel implements ChangeListener {
    /** Not meant to be serialized. */
    private static final long serialVersionUID = 1L;

    /** The parameter this Panel represents. */
    private final Parameter parameter;

    /** Label displaying the current value. */
    private final JLabel label;

    /**
     * Create a new JParameterPane.
     *
     * @param parameter this pane's parameter
     */
    public JParameterPane(final Parameter parameter) {
        this(parameter, false);
    }

    /**
     * Create a new JParameterPane that might be allowed to adjust an parameter
     * even though it is not mutable. TODO This method should be removed.
     *
     * @param parameter this pane's parameter
     * @param adjust if this pane is allowed to change that parameter
     */
    public JParameterPane(final Parameter parameter, final boolean adjust) {
        this.parameter = parameter;
        parameter.addChangeListener(this);

        final Hashtable<Integer, JLabel> labelTable =
            new Hashtable<Integer, JLabel>();

        labelTable.put(
            parameter.getMinimum(),
            new JLabel(String.valueOf(parameter.getMinimum())));
        labelTable.put(
            parameter.getMaximum(),
            new JLabel(String.valueOf(parameter.getMaximum())));

        final JSlider slider = new JSlider(parameter);
        slider.setPaintTicks(true);
        slider.setSnapToTicks(true);
        slider.setPaintLabels(true);
        slider.setMinorTickSpacing(1);
        slider.setLabelTable(labelTable);

        if (parameter.isMutable() || adjust) {
            slider.addChangeListener(this);
        } else {
            slider.setEnabled(false);
        }

        label = new JLabel();
        label.setText(String.valueOf(parameter.getValue()));

        setLayout(new BorderLayout());
        setBorder(new TitledBorder(
            null,
            parameter.getTitle(),
            TitledBorder.LEADING,
            TitledBorder.TOP,
            null,
            null));
        add(slider, BorderLayout.CENTER);
        add(label, BorderLayout.LINE_END);
    }

    @Override
    protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    @Override
    public final void stateChanged(final ChangeEvent e) {
        label.setText(String.valueOf(parameter.getValue()));
    }
}


text:
define(['fixitup'], function (fixitup) {

    'use strict';

    var errMsg = 'you have given all your money to the fix it up chappie';

    function Sneetch(starOnThars) {
        this.star = starOnThars;
    }

    Sneetch.prototype.money = 100;

    Sneetch.prototype.star = false;

    Sneetch.prototype.starOn = function () {
        if (this.money >= MONEY.on) {
            this.money -= MONEY.on;
            fixitup.on(this, MONEY.on);
        } else {
            throw errMsg;
        }
    };

    Sneetch.prototype.starOff = function () {
        if (this.money >= MONEY.off) {
            this.money -= MONEY.off;
            fixitup.off(this, MONEY.off);
        } else {
            throw errMsg;
        }
    };

    return Sneetch;

});


text:
(shopt -s igncr) 2>/dev/null && shopt -s igncr; # Workaround Cygwin line-ending issue

# This batch file runs the Multiverse sever processes on Linux in bash shell or on Windows/Cygwin
# You must have installed Java, a database, JDBC driver, and the Multiverse servers
# Thanks to Judd-MGT for contributions.

# Optional: Set MV_HOME env. variable to be able to run this script from an arbitrary directory.
# Otherwise, this script assumes it is being run from MV_HOME/bin working directory
# NOTE: Doesn't work if you set MV_HOME.
export MV_HOME=${MV_HOME:-".."}

# Optional: Set DEFAULT_MV_PROPERTYFILE env. variable to set the default property file, otherwise use multiverse.properties
# when no property file is specified as final argument on command line.
DEFAULT_MV_PROPERTYFILE=${DEFAULT_MV_PROPERTYFILE:-"multiverse.properties"}

### Set to true to enable JMX management and monitoring (either here or in env. variable.
ENABLE_MGMT=${ENABLE_MGMT:-"false"}

function kill_process () {
    if [ $verbose -gt 0 ]; then
        echo -en "stopping $1 "
    fi
    kill $2 > /dev/null 2>&1
    result=$?
    if [ $verbose -gt 0 ]; then
        if [ $result = 0 ]; then
            echo STOPPED
        else
            echo NOT RUNNING
        fi
    fi
}

function check_process () {
    ps -e ho pid | grep $1 > /dev/null 2>&1
    result=$?
    if [ $result = 1 ]; then
        echo FAILED
    else
        echo SUCCESS
    fi
}

function status_process () {
    if [ x$2 == x ]; then
	return 0
    fi
    ps -e ho pid | grep $2 > /dev/null 2>&1
    result=$?
    if [ $result = 0 ]; then
        echo -e "$1" RUNNING
    else
        echo -e "$1" NOT RUNNING
    fi
    return $result
}

function alloc_domain_name () {

    type=$1
    name=$2

    if [ $(uname -o) == "Cygwin" ]; then
	CMD_CLASSPATH="$MV_JAR;$GETOPT;$LOG4J;$BCEL;."
    else
	CMD_CLASSPATH="${MV_JAR}:${GETOPT}:${LOG4J}:${BCEL}:."
    fi

    # not currently using CMD_CLASSPATH

    java -client ${JAVA_FLAGS} \
	    -Dmultiverse.disable_logs=true \
	    -Dmultiverse.log_level=3 \
	    multiverse.msgsys.DomainCommand \
	    $CMDLINE_PROPS \
        -t "${MV_COMMON}"/typenumbers.txt \
	    -n ${type},${name}

    if [ $? -ne 0 ]; then
	echo "alloc_domain_name failed" 1>&2
	exit 1
    fi
}

function start_world_manager () {

    AGENT_TYPE=wmgr
    AGENT_NAME=$(alloc_domain_name AGENT ${AGENT_TYPE}_# )

    if [ $verbose -gt 0 ]; then
        echo -en "Starting $AGENT_NAME ...     \t"
    fi

    java \
        $JAVA_FLAGS \
	$JMX_FLAGS \
        -Dmultiverse.agenttype=${AGENT_TYPE} \
        -Dmultiverse.loggername=${AGENT_NAME} \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_BIN}"/wmgr_local1.py \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
		"${MV_COMMON}"/global_props.py \
        "${MV_WORLD}"/global_props.py \
        "${MV_COMMON}"/world_mgr1.py \
        "${MV_WORLD}"/extensions_wmgr.py \
        &

    PID=$!
    echo $PID > "${MV_RUN}"/${AGENT_NAME}.pid

    if [ $verbose -gt 0 ]; then
        check_process $PID
    fi
}

function start_proxy () {

    AGENT_TYPE=proxy
    AGENT_NAME=$(alloc_domain_name AGENT ${AGENT_TYPE}_# )

    if [ $verbose -gt 0 ]; then
        echo -en "Starting $AGENT_NAME ...     \t"
    fi

    java  \
        $JAVA_FLAGS \
	$JMX_FLAGS \
        -Dmultiverse.agenttype=$AGENT_TYPE \
        -Dmultiverse.loggername=$AGENT_NAME \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_BIN}"/proxy.py \
        -i "${MV_COMMON}"/events.py \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_COMMON}"/proxy.py \
        "${MV_COMMON}"/global_props.py \
        "${MV_WORLD}"/global_props.py \
        "${MV_WORLD}"/extensions_proxy.py \
        &

    PID=$!
    echo $PID > "${MV_RUN}"/${AGENT_NAME}.pid

    if [ $verbose -gt 0 ]; then
        check_process $PID
    fi
}

function archive_log_dir () {
    rm -rf "${MV_LOGS}.old"/*
    mkdir -p "${MV_LOGS}".old
    mv "${MV_LOGS}"/* "${MV_LOGS}".old
}

function start_server () {

    if [ X$ARCHIVE_LOG_DIR = X"true" ]; then
	if [ -d "${MV_LOGS}" ]; then
	    archive_log_dir
	fi
    fi

    # Do marshalling code injection if USE_CLASS_FILES is true
    if [ X$USE_CLASS_FILES = X"true" ]; then
        ./performinjection.sh $MV_WORLDNAME
    fi

    # Use these flags for profiling
    HPROF_FLAGS="-agentlib:hprof=heap=sites,depth=8"
    GCDETAILS_FLAGS="-XX:+PrintGC -XX:+PrintGCDetails"

    # Linux: Use strace with the following flags to monitor one of the
    # multiverse server processes.
    #    strace -f -e trace=\!futex,gettimeofday,clock_gettime java \

    echo "*** Starting world $MV_WORLDNAME ***"
    if [ ! -d "${MV_RUN}" ]
        then
        mkdir -p "${MV_RUN}"
    fi

    if [ ! -d "${MV_LOGS}" ]
        then
        mkdir -p "${MV_LOGS}"
    fi

    rm -f ${MV_RUN}/*.pid

    if [ X$DELETE_LOGS_ON_STARTUP = X"true" ]; then
        rm "${MV_LOGS}"/*.out*
    fi

    if [ X$ENABLE_MGMT = X"true" ]; then
        echo "Enabling JMX mgmt & monitoring"
        JAVA_FLAGS="${JAVA_FLAGS} $JMX_FLAGS"
    fi

    if [ $verbose -gt 0 ]; then
        echo MV_HOME is $MV_HOME
        if [ X$USE_CLASS_FILES = X"true" ]; then
            echo "Using .class files from the /build hierarchy"
        else
            echo "Using .jar files from the /dist hierarchy"
        fi
        echo Using property file $MV_PROPERTYFILE
        echo Using world file $MVW_FILENAME
        echo Using world script directory $MV_WORLD
        echo Using log directory $MV_LOGS
        echo Using common directory $MV_COMMON, bin directory $MV_BIN
        echo "JAVA_FLAGS=\"${JAVA_FLAGS}\""
    fi

    # Increase the file descriptor limit up to the hard limit
    # Linux: Use /etc/security/limits.conf to set the hard limit
    ulimit -n hard

    AGENT_NAMES="-a combat -a wmgr_1 -a mobserver -a objmgr -a login_manager -a proxy_1 -a instance -a voiceserver"
    PLUGIN_TYPES="-p Login,1 -p Proxy,1 -p ObjectManager,1 -p WorldManager,1 -p Inventory,1 -p MobManager,1 -p Quest,1 -p Instance,1 -p Voice,1 -p Trainer,1 -p Group,1 -p Combat,1 -p ClassAbility,1 -p Domain,1"

    if [ $verbose -gt 0 ]; then
        echo -en "Starting domain server: \t"
    fi

    java ${JAVA_FLAGS} \
        -Dmultiverse.loggername=domain \
        multiverse.msgsys.DomainServer \
	$CMDLINE_PROPS \
        -t "${MV_COMMON}"/typenumbers.txt \
        ${AGENT_NAMES} ${PLUGIN_TYPES} \
        &

    echo $! > "${MV_RUN}"/domain.pid

    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/domain.pid)
    fi

    start_world_manager

    if [ $verbose -gt 0 ]; then
        echo -en "Starting combat server: \t"
    fi
    java \
        $JAVA_FLAGS \
        -Dmultiverse.loggername=combat \
        multiverse.server.engine.Engine \
	    $CMDLINE_PROPS \
        -i "${MV_BIN}"/wmgr_local1.py \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_COMMON}"/global_props.py \
        "${MV_WORLD}"/global_props.py \
        "${MV_COMMON}"/skill_db.py \
        "${MV_WORLD}"/skill_db.py \
        "${MV_COMMON}"/ability_db.py \
        "${MV_WORLD}"/ability_db.py \
        "${MV_WORLD}"/classabilityplugin.py \
        "${MV_WORLD}"/combat.py \
        "${MV_WORLD}"/extensions_combat.py \
        "${MV_COMMON}"/profession_db.py \
        "${MV_WORLD}"/profession_db.py \
        "${MV_COMMON}"/groupplugin.py \
        "${MV_WORLD}"/group.py \
        &

    echo $! > "${MV_RUN}"/combat.pid

    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/combat.pid)
        echo -en "Starting instance server: \t"
    fi
    java \
        $JAVA_FLAGS \
        -Dmultiverse.loggername=instance \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_COMMON}"/global_props.py \
        "${MV_WORLD}"/global_props.py \
        "${MV_COMMON}"/instance.py \
        "${MV_WORLD}"/startup_instance.py \
        &

    echo $! > "${MV_RUN}"/instance.pid

    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/instance.pid)
        echo -en "Starting object manager: \t"
    fi
    java \
        ${JAVA_FLAGS} \
        -Dmultiverse.loggername=objmgr \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_COMMON}"/global_props.py \
        "${MV_WORLD}"/global_props.py \
        "${MV_WORLD}"/templates.py \
        "${MV_COMMON}"/obj_manager.py \
        "${MV_WORLD}"/mobs_db.py \
        "${MV_WORLD}"/items_db.py \
        "${MV_WORLD}"/extensions_objmgr.py \
        &

    echo $! > "${MV_RUN}"/objmgr.pid

    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/objmgr.pid)
        echo -en "Starting login manager: \t"
    fi

    java \
        ${JAVA_FLAGS} \
        -Dmultiverse.loggername=login_manager \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_BIN}"/login_manager.py \
        "${MV_COMMON}"/login_manager.py \
        "${MV_COMMON}"/character_factory.py \
        "${MV_WORLD}"/character_factory.py \
        "${MV_WORLD}"/extensions_login.py \
        &

    echo $! > "${MV_RUN}"/login_manager.pid

    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/login_manager.pid)
    fi

    start_proxy

    if [ $verbose -gt 0 ]; then
        echo -en "Starting mob server:    \t"
    fi

    java \
        ${JAVA_FLAGS} \
        -Dmultiverse.loggername=mobserver \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_BIN}"/mobserver_local.py \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_COMMON}"/global_props.py \
        "${MV_WORLD}"/global_props.py \
        "${MV_COMMON}"/mobserver_init.py \
        "${MV_WORLD}"/mobserver_init.py \
        "${MV_COMMON}"/questplugin.py \
        "${MV_COMMON}"/trainerplugin.py \
        "${MV_COMMON}"/mobserver.py \
        "${MV_WORLD}"/mobserver.py \
        "${MV_WORLD}"/extensions_mobserver.py \
        &

    echo $! > ${MV_RUN}/mobserver.pid
    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/mobserver.pid)
        echo -en "Starting voice server:    \t"
    fi

    java \
        ${JAVA_FLAGS} \
        -Dmultiverse.loggername=voiceserver \
        multiverse.server.engine.Engine \
	$CMDLINE_PROPS \
        -i "${MV_COMMON}"/mvmessages.py \
        -i "${MV_WORLD}"/worldmessages.py \
        -t "${MV_COMMON}"/typenumbers.txt \
        "${MV_COMMON}"/voice.py \
        "${MV_WORLD}"/voice.py \
        &

    echo $! > ${MV_RUN}/voiceserver.pid
    if [ $verbose -gt 0 ]; then
        check_process $(cat "${MV_RUN}"/voiceserver.pid)
    fi

    echo "Wait for finished initializing msg... "
}

function stop_server () {
    echo "*** Stopping world $MV_WORLDNAME ***"
    kill_process "login server   " $(cat "${MV_RUN}"/login_manager.pid)
    kill_process "combat server  " $(cat "${MV_RUN}"/combat.pid)
    kill_process "instance       " $(cat "${MV_RUN}"/instance.pid)
    kill_process "object manager " $(cat "${MV_RUN}"/objmgr.pid)
    kill_process "world manager  " $(cat "${MV_RUN}"/wmgr_1.pid)
    kill_process "proxy server   " $(cat "${MV_RUN}"/proxy_1.pid)
    kill_process "mob server     " $(cat "${MV_RUN}"/mobserver.pid)
    kill_process "voice server   " $(cat "${MV_RUN}"/voiceserver.pid)
    kill_process "domain server  " $(cat "${MV_RUN}"/domain.pid)
}

function status_server () {
    down=0
    status_process "domain server  " $(cat "${MV_RUN}"/domain.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "login server   " $(cat "${MV_RUN}"/login_manager.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "combat server  " $(cat "${MV_RUN}"/combat.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "instance       " $(cat "${MV_RUN}"/instance.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "object manager " $(cat "${MV_RUN}"/objmgr.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "world manager  " $(cat "${MV_RUN}"/wmgr_1.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "proxy server   " $(cat "${MV_RUN}"/proxy_1.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "mob server     " $(cat "${MV_RUN}"/mobserver.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    status_process "voice server   " $(cat "${MV_RUN}"/voiceserver.pid)
    if [ $? -ne 0 ]; then down=1 ; fi
    exit ${down}
}

function test_server () {
    if [ $verbose -gt 0 ]; then
        java $JAVA_FLAGS multiverse.simpleclient.SimpleClient -e ${MV_COMMON}/simpleclient.props -s $MV_COMMON/simpleclient.py --exit-after-login
    else
        java $JAVA_FLAGS multiverse.simpleclient.SimpleClient -e ${MV_COMMON}/simpleclient.props -s ${MV_COMMON}/simpleclient.py --exit-after-login > /dev/null 2>&1
    fi
    result=$?
    if [ $verbose -gt 0 ]; then
        if [ $result == 0 ]; then
            echo "login test: PASS"
        else
            echo "login test: FAIL"
        fi
    fi
    exit ${result}
}

function import_property_file () {
    for file
    do
        if [ -f $file ]; then
            files="$files $file"
        fi
    done
    if [ -n "$files" ]; then
        awk -f "$MV_BIN/prop2sh.awk" $files > "$MV_BIN/_javaprops_"
        . "$MV_BIN/_javaprops_"
        rm -f "$MV_BIN/_javaprops_"
    fi
}

verbose=0
rm -f _cmdline_props_
while getopts "hvw:p:CMP:Aa" arg; do
    case "$arg" in
        h)
            echo "$0: usage: $0 [-hvCM] [-w worldname] [-p propertyfilename] (start|stop|status|test)"
            ;;
        v)
            let verbose++
            ;;
	w)
	    MV_WORLDNAME=$OPTARG
	    ;;
	p)
	    if [ -z $MV_PROPERTYFILE ]; then
		MV_PROPERTYFILE=$OPTARG
	    else
		CMDLINE_PROPS="$CMDLINE_PROPS -p $OPTARG"
		PROPERTY_FILES="$PROPERTY_FILES $OPTARG"
	    fi
	    ;;
	C)
	    JVM_FLAG=-client
	    ;;
	M)
	    ENABLE_MGMT=true
	    JMX_FLAGS="-Dcom.sun.management.jmxremote"
	    ;;
	P)
	    CMDLINE_PROPS="$CMDLINE_PROPS -P$OPTARG"
	    echo $OPTARG >> _cmdline_props_
	    ;;
	A)
	    AGGRESIVE="-XX:CompileThreshold=200 -Xnoclassgc -XX:+RelaxAccessControlCheck"
	    ;;
	a)
	    ARCHIVE_LOG_DIR=true
	    ;;
	esac
done
shift $((OPTIND-1))

if [ $(uname -o) = "Cygwin" ]; then
    MV_HOME_UNIX=$(cygpath -u "${MV_HOME}")
else
    MV_HOME_UNIX="$MV_HOME"
fi

# where the local startup configs are stored, such as the port number
# and log level
MV_BIN=${MV_BIN:-"${MV_HOME}/bin"}

# where common config files are stored, such as plugin logic
MV_COMMON=${MV_COMMON:-"${MV_HOME}/config/common"}

if [ -n $MV_WORLDNAME ]; then
    JAVA_FLAGS="$JAVA_FLAGS -Dmultiverse.worldname=$MV_WORLDNAME"
    CMDLINE_PROPS="$CMDLINE_PROPS -Pmultiverse.worldname=$MV_WORLDNAME"
fi

MV_PROPERTYFILE=${MV_PROPERTYFILE:-"${MV_BIN}/${DEFAULT_MV_PROPERTYFILE}"}

import_property_file $MV_PROPERTYFILE
if [ -n "$MV_WORLDNAME" ] ; then
    multiverse_worldname=$MV_WORLDNAME
fi
import_property_file "$MV_HOME/config/$multiverse_worldname/world.properties" $PROPERTY_FILES _cmdline_props_
rm -f _cmdline_props_

if [ -z "$ARCHIVE_LOG_DIR" -a -n "$multiverse_archive_logs_on_startup" ] ; then
    ARCHIVE_LOG_DIR=$multiverse_archive_logs_on_startup
fi

# Determine if we should use .class files from the build hierarchy,
# or .jar files from the dist hierarchy.  To run the property getter
# before MV_JAR is set, we always use the dist version of the property
# getter.
USE_CLASS_FILES=${USE_CLASS_FILES:-$multiverse_use_class_files}

RHINO=${RHINO:-"${MV_HOME}/other/rhino1_5R5/js.jar"}
GETOPT=${GETOPT:-"${MV_HOME}/other/java-getopt-1.0.11.jar"}
JYTHON=${JYTHON:-"${MV_HOME}/other/jython.jar"}
LOG4J=${LOG4J:-"${MV_HOME}/other/log4j-1.2.14.jar"}
BCEL=${BCEL:-"${MV_HOME}/other/bcel-5.2.jar"}

if  [ X$USE_CLASS_FILES = X"true" ]; then
    MV_JAR=${MV_JAR:-"${MV_HOME}/build"}
    MARS_JAR=${MARS_JAR:-"${MV_HOME}/build"}
    INJECTED_JAR=${INJECTED_JAR:-"${MV_HOME}/inject"}
else
    MV_JAR=${MV_JAR:-"${MV_HOME}/dist/lib/multiverse.jar"}
    MARS_JAR=${MARS_JAR:-"${MV_HOME}/dist/lib/mars.jar"}
    INJECTED_JAR=${INJECTED_JAR:-"${MV_HOME}/dist/lib/injected.jar"}
fi

EXT_JAR=${EXT_JAR:="${MV_HOME}/dist/lib/${MV_WORLDNAME}.jar"}
JDBC=${JDBC:-$multiverse_jdbcJarPath}

if [ $(uname -o) == "Cygwin" ]; then
    export PATH=$(cygpath "$JAVA_HOME"/bin):.:$PATH
    MV_CLASSPATH="$RHINO;$JDBC;$INJECTED_JAR;$MV_JAR;$MARS_JAR;$EXT_JAR;$GETOPT;$JYTHON;$LOG4J;$BCEL;."
else
    MV_CLASSPATH="${RHINO}:${JDBC}:${INJECTED_JAR}:${MV_JAR}:${MARS_JAR}:${EXT_JAR}:${GETOPT}:${JYTHON}:${LOG4J}:${BCEL}:."
fi

# HotSpot tracking flags: -XX:+PrintCompilation -XX:+CITime
JVM_FLAG="${JVM_FLAG:-"-server"} $AGGRESIVE"
JAVA_FLAGS="-cp ${MV_CLASSPATH} -Dmultiverse.propertyfile=${MV_PROPERTYFILE} ${JAVA_FLAGS}"
JAVA_FLAGS="${JVM_FLAG} ${JAVA_FLAGS}"

#Get world name from properties file, and construct path to world script dir if not set from env var.
MV_WORLDNAME=${MV_WORLDNAME:-$multiverse_worldname}
MV_WORLD=${MV_WORLD:-"$MV_HOME/config/$MV_WORLDNAME"}

# Get path to mvw file if set explicitly in multiverse.mvwfile, otherwise, construct path to mvwfile.
MVW_FILENAME=${MVW_FILENAME:-$multiverse_mvwfile}

if [ "$MVW_FILENAME" = "null" ]; then
    MVW_FILENAME=$MV_HOME/config/$MV_WORLDNAME/$MV_WORLDNAME.mvw
fi

if [ X"$MV_HOSTNAME" != "X" ]; then
    CMDLINE_PROPS="$CMDLINE_PROPS -Pmultiverse.hostname=${MV_HOSTNAME}"
    JAVA_FLAGS="$JAVA_FLAGS -Dmultiverse.hostname=${MV_HOSTNAME}"
fi

# This is in local OS format
MV_LOGS=${MV_LOGS:-"${MV_HOME}/logs/${MV_WORLDNAME}"}
DELETE_LOGS_ON_STARTUP=${DELETE_LOGS_ON_STARTUP:-$multiverse_delete_logs_on_startup}

# This should always be in "unix" format
if [ $(uname -o) = "Cygwin" ]; then
    MV_RUN=${MV_RUN:-$(cygpath -w ${MV_BIN}/run/${MV_WORLDNAME})}
else
    MV_RUN=${MV_RUN:-${MV_BIN}/run/${MV_WORLDNAME}}
fi

JAVA_FLAGS="${JAVA_FLAGS} -Dmultiverse.logs=${MV_LOGS}"

case "$1" in

    start)
        start_server
        ;;

    stop)
        stop_server
        ;;

    status)
        status_server
        ;;

    restart)
        stop_server
        start_server
        ;;

    proxy)
        start_proxy
        ;;

    wmgr)
        start_world_manager
        ;;

    test)
        test_server
        ;;
esac