text:
package it.unibz.inf.ontop.si.impl;

import it.unibz.inf.ontop.injection.OntopModelSettings;
import it.unibz.inf.ontop.injection.OntopSQLOWLAPIConfiguration;
import it.unibz.inf.ontop.si.OntopSemanticIndexLoader;
import it.unibz.inf.ontop.si.repository.impl.SIRepository;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import java.util.Properties;

/**
 * TODO: find a better name
 */
public class OntopSemanticIndexLoaderImpl implements OntopSemanticIndexLoader {

    private static final Logger LOG = LoggerFactory.getLogger(OntopSemanticIndexLoaderImpl.class);

    private final OntopSQLOWLAPIConfiguration configuration;
    private final Connection connection;

    OntopSemanticIndexLoaderImpl(SIRepository repo, Connection connection, Properties properties, Optional<OWLOntology> tbox) {
        this.connection = connection;

        Properties newProperties = new Properties();
        newProperties.putAll(properties);
        // The SI unfortunately does not provide unique constraints... and is not robust to DISTINCTs in a sub-query
        newProperties.putIfAbsent(OntopModelSettings.CARDINALITY_MODE, "LOOSE");

        OntopSQLOWLAPIConfiguration.Builder builder = OntopSQLOWLAPIConfiguration.defaultBuilder()
                .ppMapping(repo.createMappings())
                .properties(newProperties)
                .jdbcUrl(repo.getJdbcUrl())
                .jdbcUser(repo.getUser())
                .jdbcPassword(repo.getPassword())
                .jdbcDriver(repo.getJdbcDriver())
                .keepPermanentDBConnection(true);

        tbox.map(t -> {
            try {
                OutputStream out = new ByteArrayOutputStream();
                t.getOWLOntologyManager().saveOntology(t, out);
                return out.toString();
            } catch (OWLOntologyStorageException e) {
                throw new RuntimeException(e);
            }
        })
        .ifPresent(o -> builder.ontologyReader(new StringReader(o)));

        this.configuration = builder.build();
    }

    @Override
    public OntopSQLOWLAPIConfiguration getConfiguration() {
        return configuration;
    }

    @Override
    public void close() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.error("Error while closing the DB: " + e.getMessage());
        }
    }
}


text:
Tune User Guide
===============

Tune Overview
-------------

.. image:: images/tune-api.svg

Tune schedules a number of *trials* in a cluster. Each trial runs a user-defined Python function or class and is parameterized either by a *config* variation from Tune's Variant Generator or a user-specified **search algorithm**. The trials are scheduled and managed by a **trial scheduler**.

More information about Tune's `search algorithms can be found here <tune-searchalg.html>`__. More information about Tune's `trial schedulers can be found here <tune-schedulers.html>`__.

Start by installing, importing, and initializing Ray.

.. code-block:: python

    import ray
    import ray.tune as tune

    ray.init()

Experiment Configuration
------------------------

This section will cover the main steps needed to modify your code to run Tune: using the `Training API <tune-usage.html#training-api>`__ and  `executing your Tune experiment <tune-usage.html#specifying-experiments>`__.

You can checkout out our `examples page <tune-examples.html>`__ for more code examples.

Training API
~~~~~~~~~~~~

Training can be done with either the **function-based API** or **Trainable API**.

**Python functions** will need to have the following signature:

.. code-block:: python

    def trainable(config, reporter):
        """
        Args:
            config (dict): Parameters provided from the search algorithm
                or variant generation.
            reporter (Reporter): Handle to report intermediate metrics to Tune.
        """

        while True:
            # ...
            reporter(**kwargs)

The reporter will allow you to report metrics used for scheduling, search, or early stopping.

Tune will run this function on a separate thread in a Ray actor process. Note that this API is not checkpointable, since the thread will never return control back to its caller. The reporter documentation can be `found here <tune-package-ref.html#ray.tune.function_runner.StatusReporter>`__.

.. note::
    If you have a lambda function that you want to train, you will need to first register the function: ``tune.register_trainable("lambda_id", lambda x: ...)``. You can then use ``lambda_id`` in place of ``my_trainable``.

**Python classes** passed into Tune will need to subclass ``ray.tune.Trainable``. The Trainable interface `can be found here <tune-package-ref.html#ray.tune.Trainable>`__.

Both the Trainable and function-based API will have `autofilled metrics <tune-usage.html#auto-filled-results>`__ in addition to the metrics reported.

See the `experiment specification <tune-usage.html#specifying-experiments>`__ section on how to specify and execute your training.

Launching an Experiment
~~~~~~~~~~~~~~~~~~~~~~~

Tune provides a ``run`` function that generates and runs the trials.

.. autofunction:: ray.tune.run
    :noindex:

This function will report status on the command line until all Trials stop:

::

    == Status ==
    Using FIFO scheduling algorithm.
    Resources used: 4/8 CPUs, 0/0 GPUs
    Result logdir: ~/ray_results/my_experiment
     - train_func_0_lr=0.2,momentum=1:  RUNNING [pid=6778], 209 s, 20604 ts, 7.29 acc
     - train_func_1_lr=0.4,momentum=1:  RUNNING [pid=6780], 208 s, 20522 ts, 53.1 acc
     - train_func_2_lr=0.6,momentum=1:  TERMINATED [pid=6789], 21 s, 2190 ts, 100 acc
     - train_func_3_lr=0.2,momentum=2:  RUNNING [pid=6791], 208 s, 41004 ts, 8.37 acc
     - train_func_4_lr=0.4,momentum=2:  RUNNING [pid=6800], 209 s, 41204 ts, 70.1 acc
     - train_func_5_lr=0.6,momentum=2:  TERMINATED [pid=6809], 10 s, 2164 ts, 100 acc

Custom Trial Names
~~~~~~~~~~~~~~~~~~

To specify custom trial names, you can pass use the ``trial_name_creator`` argument
to `tune.run`.  This takes a function with the following signature, and
be sure to wrap it with `tune.function`:

.. code-block:: python

    def trial_name_string(trial):
        """
        Args:
            trial (Trial): A generated trial object.

        Returns:
            trial_name (str): String representation of Trial.
        """
        return str(trial)

    tune.run(
        MyTrainableClass,
        name="hyperband_test",
        num_samples=1,
        trial_name_creator=tune.function(trial_name_string)
    )

An example can be found in `logging_example.py <https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/logging_example.py>`__.

Training Features
-----------------

Tune Search Space (Default)
~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can use ``tune.grid_search`` to specify an axis of a grid search. By default, Tune also supports sampling parameters from user-specified lambda functions, which can be used independently or in combination with grid search.

.. note::
    If you specify an explicit Search Algorithm such as any SuggestionAlgorithm, you may not be able to specify lambdas or grid search with this interface, as the search algorithm may require a different search space declaration.

The following shows grid search over two nested parameters combined with random sampling from two lambda functions, generating 9 different trials. Note that the value of ``beta`` depends on the value of ``alpha``, which is represented by referencing ``spec.config.alpha`` in the lambda function. This lets you specify conditional parameter distributions.

.. code-block:: python
   :emphasize-lines: 4-11

    tune.run(
        my_trainable,
        name="my_trainable",
        config={
            "alpha": tune.sample_from(lambda spec: np.random.uniform(100)),
            "beta": tune.sample_from(lambda spec: spec.config.alpha * np.random.normal()),
            "nn_layers": [
                tune.grid_search([16, 64, 256]),
                tune.grid_search([16, 64, 256]),
            ],
        }
    )

.. note::
    Use ``tune.sample_from(...)`` to sample from a function during trial variant generation. If you need to pass a literal function in your config, use ``tune.function(...)`` to escape it.

For more information on variant generation, see `basic_variant.py <https://github.com/ray-project/ray/blob/master/python/ray/tune/suggest/basic_variant.py>`__.

Sampling Multiple Times
~~~~~~~~~~~~~~~~~~~~~~~

By default, each random variable and grid search point is sampled once. To take multiple random samples, add ``num_samples: N`` to the experiment config. If `grid_search` is provided as an argument, the grid will be repeated `num_samples` of times.

.. code-block:: python
   :emphasize-lines: 12

    tune.run(
        my_trainable,
        name="my_trainable",
        config={
            "alpha": tune.sample_from(lambda spec: np.random.uniform(100)),
            "beta": tune.sample_from(lambda spec: spec.config.alpha * np.random.normal()),
            "nn_layers": [
                tune.grid_search([16, 64, 256]),
                tune.grid_search([16, 64, 256]),
            ],
        },
        num_samples=10
    )

E.g. in the above, ``num_samples=10`` repeats the 3x3 grid search 10 times, for a total of 90 trials, each with randomly sampled values of ``alpha`` and ``beta``.

Using GPUs (Resource Allocation)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tune will allocate the specified GPU and CPU ``resources_per_trial`` to each individual trial (defaulting to 1 CPU per trial). Under the hood, Tune runs each trial as a Ray actor, using Ray's resource handling to allocate resources and place actors. A trial will not be scheduled unless at least that amount of resources is available in the cluster, preventing the cluster from being overloaded.

Fractional values are also supported, (i.e., ``"gpu": 0.2``). You can find an example of this in the `Keras MNIST example <https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/tune_mnist_keras.py>`__.

If GPU resources are not requested, the ``CUDA_VISIBLE_DEVICES`` environment variable will be set as empty, disallowing GPU access.
Otherwise, it will be set to the GPUs in the list (this is managed by Ray).

If your trainable function / class creates further Ray actors or tasks that also consume CPU / GPU resources, you will also want to set ``extra_cpu`` or ``extra_gpu`` to reserve extra resource slots for the actors you will create. For example, if a trainable class requires 1 GPU itself, but will launch 4 actors each using another GPU, then it should set ``"gpu": 1, "extra_gpu": 4``.

.. code-block:: python
   :emphasize-lines: 4-8

    tune.run(
        my_trainable,
        name="my_trainable",
        resources_per_trial={
            "cpu": 1,
            "gpu": 1,
            "extra_gpu": 4
        }
    )

Trial Checkpointing
~~~~~~~~~~~~~~~~~~~

To enable checkpointing, you must implement a `Trainable class <tune-usage.html#training-api>`__ (Trainable functions are not checkpointable, since they never return control back to their caller). The easiest way to do this is to subclass the pre-defined ``Trainable`` class and implement its ``_train``, ``_save``, and ``_restore`` abstract methods `(example) <https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/hyperband_example.py>`__. Implementing this interface is required to support resource multiplexing in  Trial Schedulers such as HyperBand and PBT.

For TensorFlow model training, this would look something like this `(full tensorflow example) <https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/tune_mnist_ray_hyperband.py>`__:

.. code-block:: python

    class MyClass(Trainable):
        def _setup(self, config):
            self.saver = tf.train.Saver()
            self.sess = ...
            self.iteration = 0

        def _train(self):
            self.sess.run(...)
            self.iteration += 1

        def _save(self, checkpoint_dir):
            return self.saver.save(
                self.sess, checkpoint_dir + "/save",
                global_step=self.iteration)

        def _restore(self, path):
            return self.saver.restore(self.sess, path)

Additionally, checkpointing can be used to provide fault-tolerance for experiments. This can be enabled by setting ``checkpoint_freq=N`` and ``max_failures=M`` to checkpoint trials every *N* iterations and recover from up to *M* crashes per trial, e.g.:

.. code-block:: python
   :emphasize-lines: 4,5

    tune.run(
        my_trainable,
        checkpoint_freq=10,
        max_failures=5,
    )

The checkpoint_freq may not coincide with the exact end of an experiment. If you want a checkpoint to be created at the end
of a trial, you can additionally set the checkpoint_at_end to True. An example is shown below:

.. code-block:: python
   :emphasize-lines: 5

    tune.run(
        my_trainable,
        checkpoint_freq=10,
        checkpoint_at_end=True,
        max_failures=5,
    )

Recovering From Failures (Experimental)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tune automatically persists the progress of your experiments, so if an experiment crashes or is otherwise cancelled, it can be resumed with ``resume=True``. The default setting of ``resume=False`` creates a new experiment, and ``resume="prompt"`` will cause Tune to prompt you for whether you want to resume. You can always force a new experiment to be created by changing the experiment name.

Note that trials will be restored to their last checkpoint. If trial checkpointing is not enabled, unfinished trials will be restarted from scratch.

E.g.:

.. code-block:: python

    tune.run(
        my_trainable,
        checkpoint_freq=10,
        local_dir="~/path/to/results",
        resume=True
    )

Upon a second run, this will restore the entire experiment state from ``~/path/to/results/my_experiment_name``. Importantly, any changes to the experiment specification upon resume will be ignored.

This feature is still experimental, so any provided Trial Scheduler or Search Algorithm will not be preserved. Only ``FIFOScheduler`` and ``BasicVariantGenerator`` will be supported.

Handling Large Datasets
-----------------------

You often will want to compute a large object (e.g., training data, model weights) on the driver and use that object within each trial. Tune provides a ``pin_in_object_store`` utility function that can be used to broadcast such large objects. Objects pinned in this way will never be evicted from the Ray object store while the driver process is running, and can be efficiently retrieved from any task via ``get_pinned_object``.

.. code-block:: python

    import ray
    from ray import tune
    from ray.tune.util import pin_in_object_store, get_pinned_object

    import numpy as np

    ray.init()

    # X_id can be referenced in closures
    X_id = pin_in_object_store(np.random.random(size=100000000))

    def f(config, reporter):
        X = get_pinned_object(X_id)
        # use X

    tune.run(f)

Auto-Filled Results
-------------------

During training, Tune will automatically fill certain fields if not already provided. All of these can be used as stopping conditions or in the Scheduler/Search Algorithm specification.

.. literalinclude:: ../../python/ray/tune/result.py
   :language: python
   :start-after: __sphinx_doc_begin__
   :end-before: __sphinx_doc_end__

The following fields will automatically show up on the console output, if provided:

1. ``episode_reward_mean``
2. ``mean_loss``
3. ``mean_accuracy``
4. ``timesteps_this_iter`` (aggregated into ``timesteps_total``).

.. code-block:: bash

    Example_0:  TERMINATED [pid=68248], 179 s, 2 iter, 60000 ts, 94 rew

Logging, Analyzing, and Visualizing Results
-------------------------------------------

All results reported by the trainable will be logged locally to a unique directory per experiment, e.g. ``~/ray_results/my_experiment`` in the above example. On a cluster, incremental results will be synced to local disk on the head node.

Tune provides an ``ExperimentAnalysis`` object for analyzing results which can be used by providing the directory path as follows:

.. code-block:: python

    from ray.tune.analysis import ExperimentAnalysis

    ea = ExperimentAnalysis("~/ray_results/my_experiment")
    trials_dataframe = ea.dataframe()

You can check out `experiment_analysis.py <https://github.com/ray-project/ray/blob/master/python/ray/tune/analysis/experiment_analysis.py>`__ for more interesting analysis operations.

To visualize learning in tensorboard, install TensorFlow:

.. code-block:: bash

    $ pip install tensorflow

Then, after you run a experiment, you can visualize your experiment with TensorBoard by specifying the output directory of your results. Note that if you running Ray on a remote cluster, you can forward the tensorboard port to your local machine through SSH using ``ssh -L 6006:localhost:6006 <address>``:

.. code-block:: bash

    $ tensorboard --logdir=~/ray_results/my_experiment

.. image:: ray-tune-tensorboard.png

To use rllab's VisKit (you may have to install some dependencies), run:

.. code-block:: bash

    $ git clone https://github.com/rll/rllab.git
    $ python rllab/rllab/viskit/frontend.py ~/ray_results/my_experiment

.. image:: ray-tune-viskit.png

Custom Loggers
~~~~~~~~~~~~~~

You can pass in your own logging mechanisms to output logs in custom formats as follows:

.. code-block:: python

    from ray.tune.logger import DEFAULT_LOGGERS

    tune.run(
        MyTrainableClass
        name="experiment_name",
        loggers=DEFAULT_LOGGERS + (CustomLogger1, CustomLogger2)
    )

These loggers will be called along with the default Tune loggers. All loggers must inherit the `Logger interface <tune-package-ref.html#ray.tune.logger.Logger>`__.

Tune has default loggers for Tensorboard, CSV, and JSON formats.

You can also check out `logger.py <https://github.com/ray-project/ray/blob/master/python/ray/tune/logger.py>`__ for implementation details.

An example can be found in `logging_example.py <https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/logging_example.py>`__.

Custom Sync/Upload Commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~

If an upload directory is provided, Tune will automatically sync results to the given
directory with standard S3/gsutil commands. You can customize the upload command by
providing either a function or a string.

If a string is provided, then it must include replacement fields ``{local_dir}`` and
``{remote_dir}``, like ``"aws s3 sync {local_dir} {remote_dir}"``.

Alternatively, a function can be provided with the following signature (and must
be wrapped with ``tune.function``):

.. code-block:: python

    def custom_sync_func(local_dir, remote_dir):
        sync_cmd = "aws s3 sync {local_dir} {remote_dir}".format(
            local_dir=local_dir,
            remote_dir=remote_dir)
        sync_process = subprocess.Popen(sync_cmd, shell=True)
        sync_process.wait()

    tune.run(
        MyTrainableClass,
        name="experiment_name",
        sync_function=tune.function(custom_sync_func)
    )

Tune Client API
---------------

You can interact with an ongoing experiment with the Tune Client API. The Tune Client API is organized around REST, which includes resource-oriented URLs, accepts form-encoded requests, returns JSON-encoded responses, and uses standard HTTP protocol.

To allow Tune to receive and respond to your API calls, you have to start your experiment with ``with_server=True``:

.. code-block:: python

    tune.run(..., with_server=True, server_port=4321)

The easiest way to use the Tune Client API is with the built-in TuneClient. To use TuneClient, verify that you have the ``requests`` library installed:

.. code-block:: bash

    $ pip install requests

Then, on the client side, you can use the following class. If on a cluster, you may want to forward this port (e.g. ``ssh -L <local_port>:localhost:<remote_port> <address>``) so that you can use the Client on your local machine.

.. autoclass:: ray.tune.web_server.TuneClient
    :members:

For an example notebook for using the Client API, see the `Client API Example <https://github.com/ray-project/ray/tree/master/python/ray/tune/TuneClient.ipynb>`__.

The API also supports curl. Here are the examples for getting trials (``GET /trials/[:id]``):

.. code-block:: bash

    curl http://<address>:<port>/trials
    curl http://<address>:<port>/trials/<trial_id>

And stopping a trial (``PUT /trials/:id``):

.. code-block:: bash

    curl -X PUT http://<address>:<port>/trials/<trial_id>

Tune CLI (Experimental)
-----------------------

``tune`` has an easy-to-use command line interface (CLI) to manage and monitor your experiments on Ray. To do this, verify that you have the ``tabulate`` library installed:

.. code-block:: bash

    $ pip install tabulate

Here are a few examples of command line calls.

- ``tune list-trials``: List tabular information about trials within an experiment. Empty columns will be dropped by default. Add the ``--sort`` flag to sort the output by specific columns. Add the ``--filter`` flag to filter the output in the format ``"<column> <operator> <value>"``. Add the ``--output`` flag to write the trial information to a specific file (CSV or Pickle). Add the ``--columns`` and ``--result-columns`` flags to select specific columns to display.

.. code-block:: bash

    $ tune list-trials [EXPERIMENT_DIR] --output note.csv

    +------------------+-----------------------+------------+
    | trainable_name   | experiment_tag        | trial_id   |
    |------------------+-----------------------+------------|
    | MyTrainableClass | 0_height=40,width=37  | 87b54a1d   |
    | MyTrainableClass | 1_height=21,width=70  | 23b89036   |
    | MyTrainableClass | 2_height=99,width=90  | 518dbe95   |
    | MyTrainableClass | 3_height=54,width=21  | 7b99a28a   |
    | MyTrainableClass | 4_height=90,width=69  | ae4e02fb   |
    +------------------+-----------------------+------------+
    Dropped columns: ['status', 'last_update_time']
    Please increase your terminal size to view remaining columns.
    Output saved at: note.csv

    $ tune list-trials [EXPERIMENT_DIR] --filter "trial_id == 7b99a28a"

    +------------------+-----------------------+------------+
    | trainable_name   | experiment_tag        | trial_id   |
    |------------------+-----------------------+------------|
    | MyTrainableClass | 3_height=54,width=21  | 7b99a28a   |
    +------------------+-----------------------+------------+
    Dropped columns: ['status', 'last_update_time']
    Please increase your terminal size to view remaining columns.

- ``tune list-experiments``: List tabular information about experiments within a project. Empty columns will be dropped by default. Add the ``--sort`` flag to sort the output by specific columns. Add the ``--filter`` flag to filter the output in the format ``"<column> <operator> <value>"``. Add the ``--output`` flag to write the trial information to a specific file (CSV or Pickle). Add the ``--columns`` flag to select specific columns to display.

.. code-block:: bash

    $ tune list-experiments [PROJECT_DIR] --output note.csv

    +----------------------+----------------+------------------+---------------------+
    | name                 |   total_trials |   running_trials |   terminated_trials |
    |----------------------+----------------+------------------+---------------------|
    | pbt_test             |             10 |                0 |                   0 |
    | test                 |              1 |                0 |                   0 |
    | hyperband_test       |              1 |                0 |                   1 |
    +----------------------+----------------+------------------+---------------------+
    Dropped columns: ['error_trials', 'last_updated']
    Please increase your terminal size to view remaining columns.
    Output saved at: note.csv

    $ tune list-experiments [PROJECT_DIR] --filter "total_trials <= 1" --sort name

    +----------------------+----------------+------------------+---------------------+
    | name                 |   total_trials |   running_trials |   terminated_trials |
    |----------------------+----------------+------------------+---------------------|
    | hyperband_test       |              1 |                0 |                   1 |
    | test                 |              1 |                0 |                   0 |
    +----------------------+----------------+------------------+---------------------+
    Dropped columns: ['error_trials', 'last_updated']
    Please increase your terminal size to view remaining columns.

Further Questions or Issues?
----------------------------

You can post questions or issues or feedback through the following channels:

1. `ray-dev@googlegroups.com`_: For discussions about development or any general
   questions and feedback.
2. `StackOverflow`_: For questions about how to use Ray.
3. `GitHub Issues`_: For bug reports and feature requests.

.. _`ray-dev@googlegroups.com`: https://groups.google.com/forum/#!forum/ray-dev
.. _`StackOverflow`: https://stackoverflow.com/questions/tagged/ray
.. _`GitHub Issues`: https://github.com/ray-project/ray/issues

redpajama_set_name: RedPajamaGithub


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

using Duality;
using Duality.Input;
using Duality.Resources;
using Duality.Components;

namespace Gravity
{
    /// <summary>
    /// This component receives user input and performs actions based on the input.
    /// </summary>
    public class InputManager : Component, ICmpUpdatable
    {
        /// <summary>
        /// The prefab used to create a new Ball object.
        /// </summary>
        public ContentRef<Prefab> BallPrefab { get; set; }

        /// <summary>
        /// The prefab used to create a new Gravitator object.
        /// </summary>
        public ContentRef<Prefab> GravitatorPrefab { get; set; }

        // This function allows us to perform actions every game update.
        void ICmpUpdatable.OnUpdate()
        {
            // If the "R" key is hit, then reload the current scene.
            if (DualityApp.Keyboard.KeyHit(Key.R)) Scene.Reload();

            // If the "S" key is hit, then...
            if (DualityApp.Keyboard.KeyHit(Key.S))
            {
                // Enumerate over all Gravitators in the scene.
                foreach (Gravitator gravitator in this.GameObj.ParentScene.FindComponents<Gravitator>())
                {
                    // If the gravitator exists...
                    if (gravitator != null)
                    {
                        // If the gravitator is set to Attract mode...
                        if (gravitator.GravitationType == Gravitator.GravityType.Attract)
                            // Set it to Repel mode.
                            gravitator.GravitationType = Gravitator.GravityType.Repel;

                        // Else, if the gravitator is set to Repel mode...
                        else if (gravitator.GravitationType == Gravitator.GravityType.Repel)
                            // Set it to Attract mode.
                            gravitator.GravitationType = Gravitator.GravityType.Attract;
                    }
                }
            }

            // If the "F" key is hit...
            if (DualityApp.Keyboard.KeyHit(Key.F))
            {
                // Enumerate over all Gravitators in the scene.
                foreach (Gravitator gravitator in this.GameObj.ParentScene.FindComponents<Gravitator>())
                {
                    // If the gravitator exists, then increase it's force multiplier.
                    if (gravitator != null) gravitator.ForceMultiplier += 1f;
                }
            }

            // If the left mouse button is hit...
            if (DualityApp.Mouse.ButtonHit(MouseButton.Left))
            {
                // Get the world space position of the mouse pointer.
                Vector2 mouseWorldPos = this.GameObj.ParentScene.FindComponent<Camera>()
                                            .GetSpaceCoord(DualityApp.Mouse.Pos).Xy;

                // Create the ball at the world space mouse position.
                CreateBall(mouseWorldPos);
            }

            // If the right mouse button is hit...
            if (DualityApp.Mouse.ButtonHit(MouseButton.Right))
            {
                // Get the world space position of the mouse pointer.
                Vector2 mouseWorldPos = this.GameObj.ParentScene.FindComponent<Camera>()
                                            .GetSpaceCoord(DualityApp.Mouse.Pos).Xy;

                // Create the gravitator at the world space mouse position.
                CreateGravitator(mouseWorldPos);
            }
        }

        /// <summary>
        /// This function creates a Ball object using the Ball prefab assigned in this
        /// component, and places it at a specified position.
        /// </summary>
        /// <param name="position">The location the Ball object is to be placed at.</param>
        public void CreateBall(Vector2 position)
        {
            // Instantiate a new GameObject called "ball"
            GameObject ball = this.BallPrefab.Res.Instantiate();

            // Break the newly instantiated ball's prefab link.
            ball.BreakPrefabLink();

            // You can use alternative functions here instead; for example,
            // Transform.Pos.MoveToAbs.
            ball.Transform.Pos = new Vector3(position);

            // Actually add the ball to the scene.
            this.GameObj.ParentScene.AddObject(ball);
        }

        /// <summary>
        /// This function creates a Gravitator object using the Gravitator prefab assigned
        /// in this component, and places it at a specified position.
        /// </summary>
        /// <param name="position">The location the Gravitator object is to be placed at.</param>
        public void CreateGravitator(Vector2 position)
        {
            // Instantiate a new GameObject called "gravitator"
            GameObject gravitator = this.GravitatorPrefab.Res.Instantiate();

            // Break the newly instantiated gravitator's prefab link.
            gravitator.BreakPrefabLink();

            // You can use alternative functions here instead; for example,
            // Transform.Pos.MoveToAbs.
            gravitator.Transform.Pos = new Vector3(position);

            // Actually add the gravitator to the scene.
            this.GameObj.ParentScene.AddObject(gravitator);
        }
    }
}


text:
#ifndef _MAGICKCORE_CACHE_H
#define _MAGICKCORE_CACHE_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

#include "MagickCore/blob.h"

typedef enum
{
  UndefinedCache,
  MemoryCache,
  MapCache,
  DiskCache,
  PingCache
} CacheType;

extern MagickExport CacheType
  GetImagePixelCacheType(const Image *);

extern MagickExport const Quantum
  *GetVirtualPixels(const Image *,const ssize_t,const ssize_t,const size_t,
    const size_t,ExceptionInfo *) magick_hot_spot,
  *GetVirtualPixelQueue(const Image *) magick_hot_spot;

extern MagickExport const void
  *GetVirtualMetacontent(const Image *);

extern MagickExport MagickBooleanType
  GetOneAuthenticPixel(Image *,const ssize_t,const ssize_t,Quantum *,
    ExceptionInfo *),
  GetOneVirtualPixel(const Image *,const ssize_t,const ssize_t,Quantum *,
    ExceptionInfo *),
  GetOneVirtualPixelInfo(const Image *,const VirtualPixelMethod,
    const ssize_t,const ssize_t,PixelInfo *,ExceptionInfo *),
  PersistPixelCache(Image *,const char *,const MagickBooleanType,
    MagickOffsetType *,ExceptionInfo *),
  SyncAuthenticPixels(Image *,ExceptionInfo *) magick_hot_spot;

extern MagickExport MagickSizeType
  GetImageExtent(const Image *);

extern MagickExport Quantum
  *GetAuthenticPixels(Image *,const ssize_t,const ssize_t,const size_t,
    const size_t,ExceptionInfo *) magick_hot_spot,
  *GetAuthenticPixelQueue(const Image *) magick_hot_spot,
  *QueueAuthenticPixels(Image *,const ssize_t,const ssize_t,const size_t,
    const size_t,ExceptionInfo *) magick_hot_spot;

extern MagickExport void
  *GetAuthenticMetacontent(const Image *);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.editor.ui.factory.elements;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.gef.EditPart;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;

import com.archimatetool.editor.diagram.editparts.ArchimateElementEditPart;
import com.archimatetool.editor.diagram.figures.elements.GoalFigure;
import com.archimatetool.editor.ui.IArchiImages;
import com.archimatetool.model.IArchimatePackage;

/**
 * Goal UI Provider
 *
 * @author Phillip Beauvoir
 */
public class GoalUIProvider extends AbstractArchimateElementUIProvider {

    @Override
    public EClass providerFor() {
        return IArchimatePackage.eINSTANCE.getGoal();
    }

    @Override
    public EditPart createEditPart() {
        return new ArchimateElementEditPart(GoalFigure.class);
    }

    @Override
    public String getDefaultName() {
        return Messages.GoalUIProvider_0;
    }

    @Override
    public Image getImage() {
        return IArchiImages.ImageFactory.getImage(IArchiImages.ICON_GOAL);
    }

    @Override
    public ImageDescriptor getImageDescriptor() {
        return IArchiImages.ImageFactory.getImageDescriptor(IArchiImages.ICON_GOAL);
    }

    @Override
    public Color getDefaultColor() {
        return defaultMotivationColor;
    }

    @Override
    protected Dimension getDefaultSizeForFigureType(int figureType) {
        return super.getDefaultSizeForFigureType(figureType);
        //return figureType == 1 ? getDefaultSquareSize() : super.getDefaultSizeForFigureType(figureType);
    }
}


text:
<?php

namespace Doctrine\DBAL\Event\Listeners;

use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
use Doctrine\Common\EventSubscriber;

/**
 * Session init listener for executing a single SQL statement right after a connection is opened.
 *
 * @link    www.doctrine-project.org
 * @since   2.2
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class SQLSessionInit implements EventSubscriber
{
    /**
     * @var string
     */
    protected $sql;

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

    /**
     * @param \Doctrine\DBAL\Event\ConnectionEventArgs $args
     *
     * @return void
     */
    public function postConnect(ConnectionEventArgs $args)
    {
        $conn = $args->getConnection();
        $conn->exec($this->sql);
    }

    /**
     * {@inheritdoc}
     */
    public function getSubscribedEvents()
    {
        return [Events::postConnect];
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Xml;
using Microsoft.Win32;

namespace LESs
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        const string IntendedVersion = "0.0.1.94";

        private readonly BackgroundWorker worker = new BackgroundWorker();
        private bool wasPatched = true;

        public MainWindow()
        {
            InitializeComponent();
            FindButton.AddHandler(MouseDownEvent, new RoutedEventHandler(FindButton_MouseDown), true);
            LeagueVersionLabel.Content = IntendedVersion;
            if (File.Exists("debug.log"))
            {
                File.Delete("debug.log");
            }

            File.Create("debug.log");

            if (Directory.Exists("temp"))
            {
                Directory.Delete("temp", true);
            }

            if (Directory.Exists(Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "wm")))
            {
                MessageBox.Show(
                    "You may have malware on your system due to getting this application from an unknown source. Please delete C:/wm/ and the file inside it and then download this application from http://da.viddiaz.com/LESs");
            }

            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            if (!Debugger.IsAttached)
            {
                AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            }
        }

        void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine);
            this.wasPatched = false;
        }

        private void MainGrid_Loaded(object sender, RoutedEventArgs e)
        {
            if (!Directory.Exists("mods"))
            {
                MessageBox.Show("Missing mods directory. Ensure that all files were extracted properly.", "Missing files");
            }

            var modList = Directory.GetDirectories("mods");

            foreach (string mod in modList)
            {
                var check = new CheckBox();
                check.IsChecked = true;
                check.Content = mod.Replace("mods\\", string.Empty);
                if (File.Exists(Path.Combine(mod, "disabled")))
                {
                    check.IsChecked = false;
                }

                ModsListBox.Items.Add(check);
            }
        }

        private void ModsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var box = (CheckBox)ModsListBox.SelectedItem;

            if (box == null)
            {
                return;
            }

            var selectedMod = (string)box.Content;
            using (XmlReader reader = XmlReader.Create(Path.Combine("mods", selectedMod, "info.xml")))
            {
                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {
                        switch (reader.Name)
                        {
                            case "name":
                                reader.Read();
                                ModNameLabel.Content = reader.Value;
                                break;
                            case "description":
                                reader.Read();
                                ModDescriptionBox.Text = reader.Value;
                                break;
                        }
                    }
                }
            }
        }

        private void FindButton_MouseDown(object sender, RoutedEventArgs e)
        {
            PatchButton.IsEnabled = false;
            var findLeagueDialog = new OpenFileDialog();

            findLeagueDialog.InitialDirectory = !Directory.Exists(Path.Combine("C:\\", "Riot Games", "League of Legends")) ? Path.Combine("C:\\", "Program Files (x86)", "GarenaLoL", "GameData", "Apps", "LoL") : Path.Combine("C:\\", "Riot Games", "League of Legends");
            findLeagueDialog.DefaultExt = ".exe";
            findLeagueDialog.Filter = "League of Legends Launcher|lol.launcher*.exe|Garena Launcher|lol.exe";

            bool? result = findLeagueDialog.ShowDialog();

            if (result == true)
            {
                File.AppendAllText("debug.log", findLeagueDialog.FileName + Environment.NewLine);
                string filename = findLeagueDialog.FileName.Replace("lol.launcher.exe", string.Empty).Replace("lol.launcher.admin.exe", string.Empty);
                if (filename.Contains("lol.exe"))
                {
                    // Ga ga ga garena
                    PatchButton.IsEnabled = true;
                    RemoveButton.IsEnabled = false; // Can't automatically remove on garena installations!

                    filename = filename.Replace("lol.exe", string.Empty);

                    LocationTextbox.Text = Path.Combine(filename, "Air");
                }
                else
                {
                    string radLocation = Path.Combine(filename, "RADS", "projects", "lol_air_client", "releases");

                    File.AppendAllText("debug.log", filename + Environment.NewLine + radLocation + Environment.NewLine);

                    var versionDirectories = Directory.GetDirectories(radLocation);
                    string finalDirectory = string.Empty;
                    string version = string.Empty;
                    int versionCompare = 0;
                    foreach (string x in versionDirectories)
                    {
                        string compare1 = x.Substring(x.IndexOf("releases\\")).Replace("releases\\", string.Empty);
                        int compareVersion;
                        try
                        {
                            compareVersion = Convert.ToInt32(compare1.Substring(0, 8).Replace(".", string.Empty));
                        }
                        catch (ArgumentOutOfRangeException) // fix for version numbers < 0.0.1.10
                        {
                            // Ignore
                            compareVersion = 0;
                        }

                        if (compareVersion > versionCompare)
                        {
                            versionCompare = compareVersion;
                            version = x.Replace(radLocation + "\\", string.Empty);
                            finalDirectory = x;
                        }

                        File.AppendAllText("debug.log", x + Environment.NewLine + compareVersion + Environment.NewLine);
                    }

                    if (version != IntendedVersion)
                    {
                        MessageBoxResult versionMismatchResult = MessageBox.Show("This version of LESs is intended for " + IntendedVersion + ". Your current version of League of Legends is " + version + ". Continue? This could harm your installation.", "Invalid Version", MessageBoxButton.YesNo);
                        if (versionMismatchResult == MessageBoxResult.No)
                            return;
                    }

                    PatchButton.IsEnabled = true;
                    RemoveButton.IsEnabled = true;

                    LocationTextbox.Text = Path.Combine(finalDirectory, "deploy");
                }

                Directory.CreateDirectory(Path.Combine(LocationTextbox.Text, "LESsBackup"));
                Directory.CreateDirectory(Path.Combine(LocationTextbox.Text, "LESsBackup", IntendedVersion));
            }
        }

        private void PatchButton_Click(object sender, RoutedEventArgs e)
        {
            PatchButton.IsEnabled = false;

            File.AppendAllText("debug.log", "Starting patch" + Environment.NewLine); // ToDo: Localize

            worker.RunWorkerAsync();
        }

        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(Path.Combine(LocationTextbox.Text.Substring(0, LocationTextbox.Text.Length - 7), "S_OK")))
            {
                File.Delete(Path.Combine(LocationTextbox.Text.Substring(0, LocationTextbox.Text.Length - 7), "S_OK"));
                MessageBox.Show("LESs will be removed next time League of Legends launches!");
                StatusLabel.Content = "Removed LESs";
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            ItemCollection modCollection = null;
            Dispatcher.BeginInvoke(
                DispatcherPriority.Input,
                new ThreadStart(() => { modCollection = ModsListBox.Items; }));

            // Wait for UI thread to respond...
            while (modCollection == null)
            {
                ;
            }

            foreach (var x in modCollection)
            {
                var box = (CheckBox)x;
                bool? isBoxChecked = null;
                string boxName = string.Empty;
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Input,
                    new ThreadStart(
                        () =>
                            {
                                if (box.IsChecked != null && (bool)box.IsChecked)
                                {
                                    isBoxChecked = true;
                                    boxName = (string)box.Content;
                                }
                                else
                                {
                                    isBoxChecked = false;
                                    boxName = "blah";
                                }
                            }));

                // Wait for UI thread to respond...
                while (isBoxChecked == null || String.IsNullOrEmpty(boxName))
                {
                    ;
                }

                if ((bool)isBoxChecked)
                {
                    int amountOfPatches = 1;

                    using (XmlReader reader = XmlReader.Create(Path.Combine("mods", boxName, "info.xml")))
                    {
                        while (reader.Read())
                        {
                            if (reader.IsStartElement())
                            {
                                switch (reader.Name)
                                {
                                    case "files":
                                        reader.Read();
                                        amountOfPatches = Convert.ToInt32(reader.Value);
                                        break;
                                }
                            }
                        }
                    }

                    for (int i = 0; i < amountOfPatches; i++)
                    {
                        Directory.CreateDirectory("temp");
                        Patcher(boxName, i);
                        DeletePathWithLongFileNames(Path.GetFullPath("temp"));
                    }
                }
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show(
                this.wasPatched
                    ? "LESs has been successfully patched into League of Legends!"
                    : "LESs encountered errors during patching. However, some patches may still be applied.");
            PatchButton.IsEnabled = true;
            StatusLabel.Content = "Done patching!";
        }

        private void Patcher(string modName, int amountOfPatches)
        {
            string patchNumber = string.Empty;
            if (amountOfPatches >= 1)
            {
                patchNumber = amountOfPatches.ToString();
            }

            string[] modDetails = File.ReadAllLines(Path.Combine("mods", modName, "patch" + patchNumber + ".txt"));
            string fileLocation = "null";
            string tryFindClass = "null";
            string traitToModify = "null";
            bool isNewTrait = false;
            foreach (string s in modDetails)
            {
                if (s.StartsWith("#"))
                {
                    tryFindClass = s.Substring(1);
                }
                else if (s.StartsWith("@@@"))
                {
                    traitToModify = s.Substring(3);
                }
                else if (s.StartsWith("@+@"))
                {
                    // Insert the new trait above this one
                    traitToModify = s.Substring(3);
                    isNewTrait = true;
                }
                else if (s.StartsWith("~"))
                {
                    fileLocation = s.Substring(1);
                }
            }

            File.AppendAllText("debug.log", "Patching " + modName + patchNumber + Environment.NewLine); // ToDo: Localize

            string[] filePart = fileLocation.Split('/');
            string fileName = filePart[filePart.Length - 1];

            string locationText = string.Empty;
            Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                locationText = LocationTextbox.Text;
            }));

            //Wait for UI thread to respond...
            while (String.IsNullOrEmpty(locationText))
                ;

            string n = string.Empty;
            foreach (string s in filePart.Take(filePart.Length - 1))
            {
                n = Path.Combine(n, s);
                if (!Directory.Exists(Path.Combine(locationText, "LESsBackup", IntendedVersion, n)))
                {
                    Directory.CreateDirectory(Path.Combine(locationText, "LESsBackup", IntendedVersion, n));
                }
            }
            if (!File.Exists(Path.Combine(locationText, "LESsBackup", IntendedVersion, fileLocation)))
            {
                File.Copy(Path.Combine(locationText, fileLocation), Path.Combine(locationText, "LESsBackup", IntendedVersion, fileLocation));
            }

            File.Copy(Path.Combine(locationText, fileLocation), Path.Combine("temp", fileName));

            Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                StatusLabel.Content = "Exporting patch " + modName;
            }));

            File.AppendAllText("debug.log", "Running abcexport" + Environment.NewLine); // ToDo: Localize

            var export = new ProcessStartInfo();
            export.FileName = "abcexport.exe";
            export.Arguments = Path.Combine("temp", fileName);
            var ExportProc = Process.Start(export);
            if (ExportProc != null)
            {
                ExportProc.WaitForExit();
            }

            Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                StatusLabel.Content = "Disassembling patch (" + modName + ")";
            }));

            string[] abcFiles = Directory.GetFiles("temp", "*.abc");

            File.AppendAllText("debug.log", "Got " + abcFiles.Length + " files" + Environment.NewLine); // ToDo: Localize

            foreach (string s in abcFiles)
            {
                var disassemble = new ProcessStartInfo();
                disassemble.FileName = "rabcdasm.exe";
                disassemble.Arguments = s;
                disassemble.UseShellExecute = false;
                disassemble.CreateNoWindow = true;
                var disasmProc = Process.Start(disassemble);
                if (disasmProc != null)
                {
                    disasmProc.WaitForExit();
                }
            }

            if (tryFindClass.IndexOf(':') == 0)
            {
                File.AppendAllText("debug.log", "INVALID MOD!!!" + Environment.NewLine); // ToDo: Localize
                throw new Exception("Invalid mod " + modName);
            }

            List<string> directories = Directory.GetDirectories("temp", "*", SearchOption.AllDirectories).ToList();

            //Get all directories that match the requested class to modify
            string searchFor = tryFindClass.Substring(0, tryFindClass.IndexOf(':'));
            var foundDirectories = new List<string>();
            foreach (string s in directories)
            {
                if (!s.Contains("com"))
                    continue;

                string tempS = s;
                tempS = tempS.Substring(tempS.IndexOf("com"));
                tempS = tempS.Replace("\\", ".");
                if (tempS == searchFor)
                {
                    foundDirectories.Add(s);
                }
            }

            if (foundDirectories.Count == 0)
            {
                File.AppendAllText("debug.log", "No class matching " + searchFor + " for mod " + modName + Environment.NewLine); // ToDo: Localize
                throw new Exception("No class matching " + searchFor + " for mod " + modName);
            }

            string finalDirectory = string.Empty;
            string Class = tryFindClass.Substring(tryFindClass.IndexOf(':')).Replace(":", string.Empty);
            //Find the directory that has the requested class
            foreach (string s in foundDirectories)
            {
                string[] m = Directory.GetFiles(s);
                string x = Path.Combine(s, Class + ".class.asasm");
                if (m.Contains(x))
                {
                    finalDirectory = s;
                }
            }

            string[] ClassModifier = File.ReadAllLines(Path.Combine(finalDirectory, Class + ".class.asasm"));

            //return if the new trait already exists
            if (isNewTrait)
            {
                foreach (string l in ClassModifier)
                {
                    if (l == modDetails[3])
                        return;
                }
            }

            int traitStartPosition = 0;
            int traitEndLocation = 0;

            // Get location of trait
            for (int i = 0; i < ClassModifier.Length; i++)
            {
                if (ClassModifier[i] == traitToModify)
                {
                    traitStartPosition = i;
                    break;
                }
            }

            if (traitStartPosition == 0)
            {
                File.AppendAllText("debug.log", "Trait start location was not found! Corrupt mod?"); // ToDo: Localize
                throw new Exception("Trait start location was not found! Corrupt mod?");
            }

            if (!isNewTrait)
            {
                // Get end location of trait
                for (int i = traitStartPosition; i < ClassModifier.Length; i++)
                {
                    if (ClassModifier[i].Trim() == "end ; method")
                    {
                        if (ClassModifier[i + 1].Trim() == "end ; trait")
                        {
                            traitEndLocation = i + 2;
                        }
                        else
                        {
                            traitEndLocation = i + 1;
                        }
                        break;
                    }
                }

                if (traitEndLocation < traitStartPosition)
                {
                    File.AppendAllText("debug.log", "Trait end location was smaller than trait start location! " + traitEndLocation + ", " + traitStartPosition); // ToDo: Localize
                    throw new Exception("Trait end location was smaller than trait start location! " + traitEndLocation + ", " + traitStartPosition);
                }

                var startTrait = new string[traitStartPosition];
                Array.Copy(ClassModifier, startTrait, traitStartPosition);
                var afterTrait = new string[ClassModifier.Length - traitEndLocation];
                Array.Copy(ClassModifier, traitEndLocation, afterTrait, 0, ClassModifier.Length - traitEndLocation);

                var finalClass = new string[startTrait.Length + (modDetails.Length - 3) + afterTrait.Length];
                Array.Copy(startTrait, finalClass, traitStartPosition);
                Array.Copy(modDetails, 3, finalClass, traitStartPosition, modDetails.Length - 3);
                Array.Copy(afterTrait, 0, finalClass, traitStartPosition + (modDetails.Length - 3), afterTrait.Length);

                File.Delete(Path.Combine(finalDirectory, Class + ".class.asasm"));
                File.WriteAllLines(Path.Combine(finalDirectory, Class + ".class.asasm"), finalClass);
            }
            else
            {
                var finalClass = new string[ClassModifier.Length + (modDetails.Length - 3)];
                Array.Copy(ClassModifier, 0, finalClass, 0, traitStartPosition);
                Array.Copy(modDetails, 3, finalClass, traitStartPosition, modDetails.Length - 3);
                Array.Copy(ClassModifier, traitStartPosition, finalClass, traitStartPosition + modDetails.Length - 3, ClassModifier.Length - traitStartPosition);

                File.Delete(Path.Combine(finalDirectory, Class + ".class.asasm"));
                File.WriteAllLines(Path.Combine(finalDirectory, Class + ".class.asasm"), finalClass);

            }

            var reAssembleLocation = finalDirectory.Substring(0, finalDirectory.IndexOf("com")).Replace("temp\\", string.Empty);
            string abcNumber = reAssembleLocation.Substring(reAssembleLocation.IndexOf('-')).Replace("-", string.Empty).Replace("\\", string.Empty);

            Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                StatusLabel.Content = "Repackaging " + modName;
            }));

            var reAsm = new ProcessStartInfo();
            reAsm.FileName = "rabcasm.exe";
            reAsm.RedirectStandardError = true;
            reAsm.UseShellExecute = false;
            reAsm.Arguments = Path.Combine("temp", reAssembleLocation, reAssembleLocation.Replace("\\", string.Empty) + ".main.asasm");
            var reAsmProc = Process.Start(reAsm);
            while (reAsmProc != null && !reAsmProc.StandardError.EndOfStream)
            {
                string line = reAsmProc.StandardError.ReadLine();
                File.AppendAllText("debug.log", line + Environment.NewLine);
            }
            if (reAsmProc != null)
            {
                reAsmProc.WaitForExit();
            }

            Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                StatusLabel.Content = "Finishing touches for " + modName;
            }));

            var doPatch = new ProcessStartInfo();
            doPatch.FileName = "abcreplace.exe";
            doPatch.RedirectStandardError = true;
            doPatch.UseShellExecute = false;
            doPatch.Arguments = Path.Combine("temp", fileName) + " " + abcNumber + " " + Path.Combine("temp", reAssembleLocation, reAssembleLocation.Replace("\\", string.Empty) + ".main.abc");
            var finalPatchProc = Process.Start(doPatch);
            while (finalPatchProc != null && !finalPatchProc.StandardError.EndOfStream)
            {
                string line = finalPatchProc.StandardError.ReadLine();
                File.AppendAllText("debug.log", line + Environment.NewLine);
            }
            if (finalPatchProc != null)
            {
                finalPatchProc.WaitForExit();
            }

            Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
            {
                StatusLabel.Content = "Done patching " + modName + "!";
            }));

            File.Copy(Path.Combine("temp", fileName), Path.Combine(locationText, fileLocation), true);
        }

        private static void DeletePathWithLongFileNames(string path)
        {
            var tmpPath = @"\\?\" + path;
            var fso = new Scripting.FileSystemObject();
            fso.DeleteFolder(tmpPath, true);
        }
    }
}