text:
<?php
/**
 * Enqueue scripts and stylesheets
 *
 * Enqueue stylesheets in the following order:
 * 1. /theme/assets/css/main.f33c.min.css
 *
 * Enqueue scripts in the following order:
 * 1. jquery-1.11.0.min.js via Google CDN
 * 2. /theme/assets/js/vendor/modernizr-2.7.0.min.js
 * 3. /theme/assets/js/main.min.js (in footer)
 */
function roots_scripts() {
  wp_enqueue_style('roots_main', get_template_directory_uri() . '/assets/css/main.min.css', false, '39cf815c3b5ce29cc298588405926184');
  wp_enqueue_style('web_fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700|Ultra', array(), null, false);
  // jQuery is loaded using the same method from HTML5 Boilerplate:
  // Grab Google CDN's latest jQuery with a protocol relative URL; fallback to local if offline
  // It's kept in the header instead of footer to avoid conflicts with plugins.
  if (!is_admin() && current_theme_supports('jquery-cdn')) {
    wp_deregister_script('jquery');
    wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', array(), null, true);
    add_filter('script_loader_src', 'roots_jquery_local_fallback', 10, 2);
  }

  if (is_single() && comments_open() && get_option('thread_comments')) {
    wp_enqueue_script('comment-reply');
  }

//
// Flowtype, Modernizr Register
  wp_register_script('flowtype', get_template_directory_uri() . '/assets/js/vendor/flowtype.js', array(), null, true);
  wp_register_script('modernizr', get_template_directory_uri() . '/assets/js/vendor/modernizr-2.7.0.min.js', array(), null, true);
  wp_register_script('roots_scripts', get_template_directory_uri() . '/assets/js/scripts.min.js', array(), 'e27dd583de4ac5a945b3490bfff57ffa', true);
  wp_enqueue_script('modernizr');
  wp_enqueue_script('jquery');
  wp_enqueue_script('flowtype');
  wp_enqueue_script('roots_scripts');
}
add_action('wp_enqueue_scripts', 'roots_scripts', 100);

//MapBox Scripts for Race Course Maps
wp_register_script('mapbox', '//api.tiles.mapbox.com/mapbox.js/v1.6.4/mapbox.js', array(), null, true);
wp_register_script('seattle_map', get_template_directory_uri(). '/assets/js/maps/seattle_map.js');
wp_register_script('lightboxInit', get_template_directory_uri(). '/assets/js/lightboxInit.js');

//MapBox Stylesheet for Race Course Map
wp_register_style('mapbox', '//api.tiles.mapbox.com/mapbox.js/v1.6.4/mapbox.css', array(), true, 'screen' );

//Lightbox for main homepage Stylesheet for Race Course Map
wp_register_script('lightbox', get_template_directory_uri().'/assets/js/vendor/jquery.magnific-popup.min.js', array(), null, true);

// http://wordpress.stackexchange.com/a/12450
function roots_jquery_local_fallback($src, $handle = null) {
  static $add_jquery_fallback = false;

  if ($add_jquery_fallback) {
    echo '<script>window.jQuery || document.write(\'<script src="' . get_template_directory_uri() . '/assets/js/vendor/jquery-1.11.0.min.js"><\/script>\')</script>' . "\n";
    $add_jquery_fallback = false;
  }

  if ($handle === 'jquery') {
    $add_jquery_fallback = true;
  }

  return $src;
}
add_action('wp_head', 'roots_jquery_local_fallback');

function roots_google_analytics() { ?>
<script>
  (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
  function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
  e=o.createElement(i);r=o.getElementsByTagName(i)[0];
  e.src='//www.google-analytics.com/analytics.js';
  r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
  ga('create','<?php echo GOOGLE_ANALYTICS_ID; ?>');ga('send','pageview');
</script>

<?php }
if (GOOGLE_ANALYTICS_ID && !current_user_can('manage_options')) {
  add_action('wp_footer', 'roots_google_analytics', 20);
}


text:
import type * as ts from 'typescript';
import { Issue } from '../../issue';
declare function createIssuesFromTsDiagnostics(typescript: typeof ts, diagnostics: ts.Diagnostic[]): Issue[];
export { createIssuesFromTsDiagnostics };

redpajama_set_name: RedPajamaGithub


text:
<html>
<head>
    <script type="text/javascript">
        var dojoConfig = (function(){
            var base = "http://esri-es.github.io/Static-Maps-API-ArcGIS";
            return {
                async: true,
                isDebug: true,
                packages:[{
                    name: 'esriES', location: base + '/js', main: "staticmap"
                }]
            };
        })();
    </script>

    <link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
    <script src="http://js.arcgis.com/3.14/"></script>

    <script type="text/javascript">
        require([
            "esriES/staticmap",
            "dojo/domReady!"
        ], function(StaticMap) {
            var staticMap = new StaticMap();

            var options = {
                basemap: "satellite",
                address: "Emilio Muñoz 35, Madrid",
                markers: [{
                    latitude: 40.432508,
                    longitude: -3.627031,
                    color: "orange",
                    yoffset: 10
                }]

            };

            staticMap.getImage(options).then(function(imageURL){
                document.getElementById("staticImage").src = imageURL;
            });

        });
    </script>
</head>
<body>
<img src="" id="staticImage">
</body>
</html>


text:
using Microsoft.EntityFrameworkCore;

namespace NullDesk.Extensions.Mailer.History.EntityFramework.SqlServer.Tests.Infrastructure
{
    public class TestSqlHistoryContext : SqlHistoryContext
    {
        public TestSqlHistoryContext(DbContextOptions<HistoryContext> options) : base(options)
        {
        }

        public override void InitializeDatabase()
        {
            Database.EnsureDeleted();
            Database.EnsureCreated();
        }
    }
}


text:
namespace TaskManager
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    using TaskManager.Configuration;

    /// <summary>
    /// Manages task schedules and execution.
    /// </summary>
    internal static class TaskSupervisor
    {
        /// <summary>
        /// Maximum number of threads allowed.
        /// </summary>
        public const int TaskMaxThreads = 200;

        /// <summary>
        /// Default execution timeout, in seconds.
        /// </summary>
        public const int TaskTimeout = 60; // 60s

        /// <summary>
        /// Default wait between bursts, in seconds.
        /// </summary>
        public const int IdleTimeout = 5; // 5s

        /// <summary>
        /// List of known tasks.
        /// </summary>
        private static List<TaskWrapper> _tasks;

        /// <summary>
        /// List of tasks scheduled for execution.
        /// </summary>
        private static Queue<TaskWrapper> _taskQueue;

        /// <summary>
        /// Lock for managing task lists.
        /// </summary>
        private static object _taskLock;

        /// <summary>
        /// List of executing threads.
        /// </summary>
        private static List<TaskThread> _threads;

        /// <summary>
        /// Lock for managing the executing thread list.
        /// </summary>
        private static object _threadsLock;

        /// <summary>
        /// The SLA Thread.
        /// </summary>
        private static Thread _threadSLA;

        /// <summary>
        /// Performance counter category.
        /// </summary>
        private static PerformanceCounterCategory _performanceCounterCategory;

        /// <summary>
        /// Counter for the number of active threads.
        /// </summary>
        private static PerformanceCounter _perfCounterSpawnedThreads;

        /// <summary>
        /// Counter for the maximum number of threads.
        /// </summary>
        private static PerformanceCounter _perfCounterMaxThreads;

        /// <summary>
        /// Counter for the number of known tasks.
        /// </summary>
        private static PerformanceCounter _perfCounterTasks;

        /// <summary>
        /// Counter for the number of tasks being executed.
        /// </summary>
        private static PerformanceCounter _perfCounterTasksRunning;

        /// <summary>
        /// Counter for the average execution time.
        /// </summary>
        private static PerformanceCounter _perfCounterAverageExecutionTime;

        /// <summary>
        /// Base for the average execution time counter.
        /// </summary>
        private static PerformanceCounter _perfCounterBaseAverageExecutionTime;

        /// <summary>
        /// Counter for the number of task exceptions caught since the service started.
        /// </summary>
        private static PerformanceCounter _perfCounterTotalExceptions;

        /// <summary>
        /// Counter for the number of task timeouts occurred since the service started.
        /// </summary>
        private static PerformanceCounter _perfCounterTotalTimeouts;

        /// <summary>
        /// Counter for the number of tasks scheduled for execution in the future.
        /// </summary>
        private static PerformanceCounter _perfCounterScheduledTasks;

        /// <summary>
        /// Counter for the average time a task ready to be executed has to wait before it really starts running.
        /// </summary>
        private static PerformanceCounter _perfCounterAverageLagTime;

        /// <summary>
        /// Base for the average lag counter.
        /// </summary>
        private static PerformanceCounter _perfCounterBaseAverageLagTime;

        /// <summary>
        /// Counter for the number of task exceptions caught per second.
        /// </summary>
        private static PerformanceCounter _perfCounterErrorsPerSecond;

        /// <summary>
        /// Counter for the number of timeouts occurred per second.
        /// </summary>
        private static PerformanceCounter _perfCounterTimeoutsPerSecond;

        /// <summary>
        /// Initializes static members of the <see cref="TaskSupervisor"/> class.
        /// </summary>
        static TaskSupervisor()
        {
            _taskLock = new object();
            _threadsLock = new object();
        }

        /// <summary>
        /// Initializes the supervisor.
        /// </summary>
        public static void Initialize()
        {
            _taskQueue = new Queue<TaskWrapper>();
            _tasks = new List<TaskWrapper>();
            _threads = new List<TaskThread>();

            CreatePerformanceCounters();

            InitializePerformanceCounters();

            _perfCounterMaxThreads.RawValue = TaskMaxThreads;

            ZeroPerformanceCounters();
        }

        /// <summary>
        /// Shuts down the supervisor.
        /// </summary>
        public static void Shutdown()
        {
            if (_taskQueue == null)
            {
                throw new Exception("TaskManager failed to initialize.");
            }

            lock (_taskLock)
            {
                lock (_threadsLock)
                {
                    _threadSLA.Abort();
                    _threadSLA.Join();
                    _threadSLA = null;

                    TaskThread[] toStop = new TaskThread[_threads.Count];

                    _threads.CopyTo(toStop);

                    foreach (TaskThread thread in toStop)
                    {
                        RemoveTaskThread(thread);
                    }
                }
            }

            _perfCounterMaxThreads.RawValue = 0;

            ZeroPerformanceCounters();

            ShudownPerformanceCounters();
        }

        #region Task management

        /// <summary>
        /// Prepares and schedules a task for execution.
        /// </summary>
        /// <param name="task">The task.</param>
        public static void ScheduleTask(TaskWrapper task)
        {
            if (_taskQueue == null)
            {
                throw new Exception("TaskManager failed to initialize.");
            }

            var nextAttempt = task.NextAttempt = DateTime.Now + (task.ConfigurationData.DelayStart ?? ConfigurationHelpers.DefaultDelayStart);

            ScheduleData current = task.ConfigurationData.GetScheduleFor(task.NextAttempt);

            lock (_taskLock)
            {
                _tasks.Add(task);

                for (int index = 0, total = current.Spawn.Value; index < total; index++)
                {
                    _taskQueue.Enqueue(task);

                    _perfCounterScheduledTasks.Increment();
                    _perfCounterTasks.Increment();
                }
            }

            EnsureExecution();
        }

        /// <summary>
        /// Adds a task to the execution list.
        /// </summary>
        /// <param name="task">The task.</param>
        public static void AddTask(TaskWrapper task)
        {
            if (_taskQueue == null)
            {
                throw new Exception("TaskManager failed to initialize.");
            }

            task.NextAttempt = DateTime.Now;

            lock (_taskLock)
            {
                _tasks.Add(task);
                _taskQueue.Enqueue(task);
            }

            _perfCounterScheduledTasks.Increment();
            _perfCounterTasks.Increment();

            EnsureExecution();
        }

        /// <summary>
        /// Terminates a task and removes it from the execution list.
        /// </summary>
        /// <param name="task">The task.</param>
        public static void RemoveTask(TaskWrapper task)
        {
            if (_taskQueue == null)
            {
                throw new Exception("TaskManager failed to initialize.");
            }

            try
            {
                lock (_taskLock)
                {
                    lock (_threadsLock)
                    {
                        AbortTaskThread(task);

                        if (_taskQueue.Count > 0 && _taskQueue.Contains(task))
                        {
                            RemoveTaskFromQueue(task);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TaskManagerService.Logger.Log("Exception caught while removing task.", ex);
            }
            finally
            {
                _tasks.Remove(task);
            }
        }

        /// <summary>
        /// Terminates the task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <returns>True whether the task was being executed at the time, false otherwise.</returns>
        private static bool AbortTaskThread(TaskWrapper task)
        {
            bool found = false;

            lock (_threadsLock)
            {
                for (int i = _threads.Count - 1; i >= 0; i--)
                {
                    TaskThread tt = _threads[i];

                    if (tt.CurrentTask == task)
                    {
                        RemoveTaskThread(tt);
                        _perfCounterTasks.Decrement();
                        found = true;
                    }
                }

                SpawnTaskThread();
            }

            return found;
        }

        /// <summary>
        /// Removes a task from the execution list.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <returns>True whether the task was queued for execution, false otherwise.</returns>
        private static bool RemoveTaskFromQueue(TaskWrapper task)
        {
            bool found = false;

            lock (_taskLock)
            {
                int before, spawnCount;

                before = _taskQueue.Count;

                lock (_threadsLock)
                {
                    spawnCount = _taskQueue.Count(t => t == task) + _threads.Count(t => t.CurrentTask == task);
                }

                for (int index = 0, total = _taskQueue.Count; index < total; index++)
                {
                    TaskWrapper front = _taskQueue.Dequeue();

                    if (front != task)
                    {
                        _taskQueue.Enqueue(front);
                    }
                    else
                    {
                        _perfCounterScheduledTasks.Decrement();
                        _perfCounterTasks.Decrement();
                        found = true;
                    }
                }

                Debug.Assert(_taskQueue.Count == before - spawnCount, "Lost track of tasks.");
            }

            return found;
        }

        /// <summary>
        /// Finds a task that is ready to be executed.
        /// </summary>
        /// <param name="thread">The thread that will execute the task.</param>
        /// <returns>A task.</returns>
        /// <remarks>This call might terminate the task execution thread (removing it from the pool) if there are more threads than there are tasks ready to be executed.</remarks>
        private static TaskWrapper GetScheduledTask(TaskThread thread)
        {
            lock (_taskLock)
            {
                if (0 == _taskQueue.Count)
                {
                    return null;
                }

                lock (_threadsLock)
                {
                    if (_threads.Count(t => !t.IsRunning) > _taskQueue.Count)
                    {
                        RemoveTaskThread(thread);
                    }
                }

                for (int i = 0; i < _taskQueue.Count; i++)
                {
                    TaskWrapper task = _taskQueue.Dequeue();
                    Thread.MemoryBarrier();

                    try
                    {
                        DateTime nextAttempt = task.NextAttempt;

                        if (nextAttempt <= DateTime.Now)
                        {
                            double lag = ((double)((TimeSpan)(DateTime.Now - task.NextAttempt)).TotalSeconds) * Stopwatch.Frequency;

                            _perfCounterAverageLagTime.IncrementBy((long)lag);
                            _perfCounterBaseAverageLagTime.Increment();

                            if (task.BurstCounter == 0)
                            {
                                task.BurstStart = DateTime.Now;
                            }

                            _perfCounterScheduledTasks.Decrement();
                            Thread.MemoryBarrier();

                            return task;
                        }

                        _taskQueue.Enqueue(task);
                    }
                    catch (AppDomainUnloadedException)
                    {
                        _perfCounterScheduledTasks.Decrement();
                        Thread.MemoryBarrier();
                    }
                }

                return null;
            }
        }

        /// <summary>
        /// Reschedules a task for its next execution time.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="hasMoreWork">Boolean indicating whether the previous execution identified more work available immediately. If true, and the task is configured to allow execution bursts, it might be scheduled for execution immediately.</param>
        /// <remarks>Burst is enabled by allowing more than 1 MaxRuns in a TimeUnit.</remarks>
        private static void RescheduleTask(TaskWrapper task, bool hasMoreWork)
        {
            ScheduleData currentSchedule = task.ConfigurationData.GetScheduleFor(DateTime.Now);

            DateTime nextAttempt = DateTime.MinValue;

            task.BurstCounter++;
            int currentBurstCount = task.BurstCounter;

            if (hasMoreWork)
            {
                if (currentBurstCount < currentSchedule.MaxRuns)
                {
                    nextAttempt = DateTime.Now;
                }
                else
                {
                    task.BurstCounter = 0;
                    nextAttempt = task.BurstStart.Add(currentSchedule.TimeUnit.Value);

                    if (nextAttempt < DateTime.Now)
                    {
                        nextAttempt = DateTime.Now;
                    }
                }
            }
            else
            {
                task.BurstCounter = 0;
                nextAttempt = DateTime.Now.Add(currentSchedule.Wait.Value);
            }

            task.NextAttempt = nextAttempt;
            ScheduleData nextSchedule = task.ConfigurationData.GetScheduleFor(nextAttempt);

            lock (_taskLock)
            {
                int currentSpawnCount;

                lock (_threadsLock)
                {
                    currentSpawnCount = _taskQueue.Count(t => t == task) + _threads.Count(t => t.CurrentTask == task);
                }

                bool extraSpawn = false;

                for (int index = currentSpawnCount, total = nextSchedule.Spawn.Value; index < total; index++)
                {
                    _taskQueue.Enqueue(task);

                    _perfCounterScheduledTasks.Increment();

                    if (extraSpawn)
                    {
                        _perfCounterTasks.Increment(); // TODO: missing .Decrement() when a task is not rescheduled.
                    }

                    extraSpawn = true;
                }

                Thread.MemoryBarrier();
            }
        }

        /// <summary>
        /// Logs an unexpected task exception.
        /// </summary>
        /// <param name="message">A debug message.</param>
        /// <param name="ex">The exception.</param>
        /// <returns>True if the exception was logged.</returns>
        private static bool NotifyException(string message, Exception ex)
        {
            if (ex is ThreadAbortException)
            {
                return false;
            }

            _perfCounterTotalExceptions.Increment();
            _perfCounterErrorsPerSecond.Increment();

            TaskManagerService.Logger.Log(ex);

            return true;
        }

        /// <summary>
        /// The SLA Thread entry point.
        /// </summary>
        /// <remarks>
        /// The SLA Thread ensures that all tasks ready to be executed will start ASAP by spawning more execution threads, if possible,
        /// and that tasks whose execution time exceeds the configured execution timeout will be aborted.
        /// </remarks>
        private static void SLALoopWorker()
        {
            while (true)
            {
                bool spawnNewThread = false;
                bool hasThreadAbort = false;

                lock (_taskLock)
                {
                    lock (_threadsLock)
                    {
                        if (_taskQueue.Count > 0)
                        {
                            for (int index = 0, total = _taskQueue.Count; index < total; index++)
                            {
                                TaskWrapper task = _taskQueue.Dequeue();

                                #region Figure out if we need to spawn a new thread, if this task is late.

                                try
                                {
                                    DateTime nextAttemptDate = task.NextAttempt;

                                    ScheduleData nextSchedule = task.ConfigurationData.GetScheduleFor(nextAttemptDate);

                                    if (nextAttemptDate.AddSeconds(nextSchedule.SLA.Value.TotalSeconds) < DateTime.Now)
                                    {
                                        spawnNewThread = true;
                                    }

                                    _taskQueue.Enqueue(task);
                                }
                                catch (AppDomainUnloadedException)
                                {
                                    _perfCounterScheduledTasks.Decrement();
                                    Thread.MemoryBarrier();
                                }

                                #endregion
                            }
                        }

                        if (_tasks.Count > 0)
                        {
                            for (int index = 0, total = _tasks.Count; index < total; index++)
                            {
                                TaskWrapper task = _tasks[index];

                                #region Figure out if we need to spawn task clones, if the current schedule requires more spawned clones than there are clones currently running

                                try
                                {
                                    ScheduleData currentSchedule = task.ConfigurationData.GetScheduleFor(DateTime.Now);

                                    int currentSpawnCount = _taskQueue.Count(t => t == task) + _threads.Count(t => t.CurrentTask == task);

                                    for (int spawnIndex = currentSpawnCount, spawnTotal = currentSchedule.Spawn.Value; spawnIndex < spawnTotal; spawnIndex++)
                                    {
                                        _taskQueue.Enqueue(task);
                                        _perfCounterScheduledTasks.Increment();
                                        _perfCounterTasks.Increment();
                                    }
                                }
                                catch (AppDomainUnloadedException)
                                {
                                    // The AppDomain is gone.
                                    // May happens during module shutdown (files were updated) or service shutdown; that's ok.
                                    // The spawn a new clone check will deal with it.
                                }

                                #endregion
                            }
                        }

                        for (int i = _threads.Count - 1; i >= 0; i--)
                        {
                            TaskThread thread = _threads[i];

                            try
                            {
                                if (thread.IsRunning &&
                                    thread.StartingTime != DateTime.MinValue &&
                                    null != thread.CurrentTask &&
                                    thread.CurrentTask.HasTimedOut() &&
                                    _threads.Count > 1)
                                {
                                    TaskWrapper currentTask = thread.CurrentTask;

                                    if (null != currentTask)
                                    {
                                        RemoveTaskThread(thread);
                                        SpawnTaskThread();
                                        _perfCounterTotalTimeouts.Increment();
                                        _perfCounterTimeoutsPerSecond.Increment();
                                        Thread.MemoryBarrier();
                                        RescheduleTask(currentTask, false);
                                        hasThreadAbort = true;
                                    }
                                }
                            }
                            catch (AppDomainUnloadedException)
                            {
                                // The AppDomain is gone.
                                // May happens during module shutdown (files were updated) or service shutdown; that's ok.
                                // The spawn a new clone check will deal with it.
                            }
                        }
                    }
                }

                if (spawnNewThread && !hasThreadAbort)
                {
                    SpawnTaskThread();
                }

                Thread.Sleep(1000);
            }
        }

        #endregion

        #region Thread management

        /// <summary>
        /// Ensures that the SLA Thread is running, and that there is at least one execution thread active.
        /// </summary>
        private static void EnsureExecution()
        {
            if (_threadSLA == null)
            {
                _threadSLA = new Thread(new ThreadStart(SLALoopWorker));
                _threadSLA.Name = "SLA Thread";
                _threadSLA.Start();
            }

            lock (_threadsLock)
            {
                foreach (TaskThread thread in _threads)
                {
                    if (!thread.IsRunning)
                    {
                        return;
                    }
                }

                SpawnTaskThread();
            }
        }

        /// <summary>
        /// Starts an execution thread, adding it to the pool.
        /// </summary>
        private static void SpawnTaskThread()
        {
            lock (_threadsLock)
            {
                if (_threads.Count < TaskMaxThreads)
                {
                    TaskThread newThread = new TaskThread();
                    _threads.Add(newThread);
                    newThread.Start();
                    _perfCounterSpawnedThreads.Increment();
                }
            }
        }

        /// <summary>
        /// Stops an execution thread, removing it from the pool.
        /// </summary>
        /// <param name="thread">The task thread.</param>
        private static void RemoveTaskThread(TaskThread thread)
        {
            lock (_threadsLock)
            {
                _threads.Remove(thread);
                _perfCounterSpawnedThreads.Decrement();
            }

            thread.Stop();
        }

        /// <summary>
        /// Called by the execution thread loop to notify the supervisor that it can't find any task ready to be executed.
        /// </summary>
        /// <param name="thread">The task thread.</param>
        private static void NotifyIdleThread(TaskThread thread)
        {
            lock (_threadsLock)
            {
                if (_threads.Count > 1)
                {
                    RemoveTaskThread(thread);
                }
            }
        }

        /// <summary>
        /// Notifies the supervisor that a task has started executing.
        /// </summary>
        /// <param name="task">The task.</param>
        private static void NotifyStart(TaskWrapper task)
        {
            _perfCounterTasksRunning.Increment();
        }

        /// <summary>
        /// Notifies the supervisor that a task has finished executing.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="ticks">How long the task took to run, in system ticks.</param>
        private static void NotifyEnd(TaskWrapper task, long ticks)
        {
            if (ticks != -1)
            {
                _perfCounterAverageExecutionTime.IncrementBy(ticks);
                _perfCounterBaseAverageExecutionTime.Increment();
            }

            _perfCounterTasksRunning.Decrement();
        }

        #region Counters

        /// <summary>
        /// Initializes the performance counters.
        /// </summary>
        private static void InitializePerformanceCounters()
        {
            _perfCounterScheduledTasks = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_SCHEDULED_TASKS, false);
            _perfCounterSpawnedThreads = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_SPAWNED_THREADS, false);
            _perfCounterMaxThreads = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_MAX_THREADS, false);
            _perfCounterTasks = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_TASKS, false);
            _perfCounterTasksRunning = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_RUNNING_TASKS, false);
            _perfCounterAverageExecutionTime = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_AVERAGE_TASK_TIME, false);
            _perfCounterBaseAverageExecutionTime = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.BASE_COUNTER_AVERAGE_TASK_TIME, false);
            _perfCounterTotalExceptions = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_EXCEPTIONS, false);
            _perfCounterTotalTimeouts = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_TIMEOUTS, false);
            _perfCounterAverageLagTime = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_AVERAGE_TASK_LAG, false);
            _perfCounterBaseAverageLagTime = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.BASE_COUNTER_AVERAGE_TASK_LAG, false);
            _perfCounterErrorsPerSecond = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_EXCEPTIONS_PER_SECOND, false);
            _perfCounterTimeoutsPerSecond = new PerformanceCounter(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.COUNTER_TIMEOUTS_PER_SECOND, false);
        }

        /// <summary>
        /// Registers the performance counters with the operating system.
        /// </summary>
        private static void CreatePerformanceCounters()
        {
            CounterCreationDataCollection ccdc = new CounterCreationDataCollection();

            ccdc.AddRange(TaskManagerInstaller.COUNTERS);

            if (!PerformanceCounterCategory.Exists(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY))
            {
                _performanceCounterCategory = PerformanceCounterCategory.Create(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY, TaskManagerInstaller.PERFORMANCE_COUNTER_DESCRIPTION, PerformanceCounterCategoryType.SingleInstance, ccdc);
            }
        }

        /// <summary>
        /// Terminates the performance counters.
        /// </summary>
        private static void ShudownPerformanceCounters()
        {
            _perfCounterSpawnedThreads.Close();
            _perfCounterMaxThreads.Close();
            _perfCounterTasks.Close();
            _perfCounterTasksRunning.Close();
            _perfCounterAverageExecutionTime.Close();
            _perfCounterBaseAverageExecutionTime.Close();
            _perfCounterTotalExceptions.Close();
            _perfCounterScheduledTasks.Close();
            _perfCounterTotalTimeouts.Close();
            _perfCounterAverageLagTime.Close();
            _perfCounterBaseAverageLagTime.Close();
            _perfCounterErrorsPerSecond.Close();
            _perfCounterTimeoutsPerSecond.Close();

            if (null != _performanceCounterCategory)
            {
                PerformanceCounterCategory.Delete(TaskManagerInstaller.PERFORMANCE_COUNTER_CATEGORY);
            }
        }

        /// <summary>
        /// Zeroes performance counter values.
        /// </summary>
        private static void ZeroPerformanceCounters()
        {
            _perfCounterSpawnedThreads.RawValue = 0;
            _perfCounterTasks.RawValue = 0;
            _perfCounterTasksRunning.RawValue = 0;
            _perfCounterAverageExecutionTime.RawValue = 0;
            _perfCounterBaseAverageExecutionTime.RawValue = 0;
            _perfCounterTotalExceptions.RawValue = 0;
            _perfCounterTotalTimeouts.RawValue = 0;
            _perfCounterScheduledTasks.RawValue = 0;
            _perfCounterAverageLagTime.RawValue = 0;
            _perfCounterBaseAverageLagTime.RawValue = 0;
            _perfCounterErrorsPerSecond.RawValue = 0;
            _perfCounterTimeoutsPerSecond.RawValue = 0;
        }

        #endregion

        /// <summary>
        /// Represents an worker thread that runs tasks.
        /// </summary>
        private class TaskThread
        {
            /// <summary>
            /// A counter for the number of created threads.
            /// </summary>
            private static int _id = 0;

            /// <summary>
            /// The <see cref="T:System.Thread"/> itself.
            /// </summary>
            private Thread _thread;

            /// <summary>
            /// The task currently being executed.
            /// </summary>
            private TaskWrapper _task;

            /// <summary>
            /// An unique identifier for this execution thread.
            /// </summary>
            private int _taskThreadId;

            /// <summary>
            /// Gets a value indicating whether this thread is executing a task.
            /// </summary>
            public bool IsRunning { get; private set; }

            /// <summary>
            /// Gets a value indicating when this thread started executing the current task.
            /// </summary>
            public DateTime StartingTime { get; private set; }

            /// <summary>
            /// Gets the task currently being executed.
            /// </summary>
            public TaskWrapper CurrentTask
            {
                get
                {
                    return this._task;
                }
            }

            /// <summary>
            /// Gets the current thread id.
            /// </summary>
            public int TaskThreadId
            {
                get
                {
                    return this._taskThreadId;
                }
            }

            /// <summary>
            /// Starts the execution thread.
            /// </summary>
            public void Start()
            {
                lock (typeof(TaskThread))
                {
                    _id++;
                    if (_id == int.MaxValue)
                    {
                        _id = 0;
                    }
                }

                if (null != this._thread)
                {
                    this.Stop();
                }

                this._thread = new Thread(new ThreadStart(this.Loop));
                this._thread.Name = "Task thread #" + (this._taskThreadId = _id).ToString();
                this._thread.Start();
            }

            /// <summary>
            /// Stops the execution thread, aborting the current executing task, if any.
            /// </summary>
            public void Stop()
            {
                if (null != this._thread)
                {
                    this._thread.Abort();
                    this._thread.Join();
                }

                this._thread = null;
            }

            /// <summary>
            /// The thread loop.
            /// </summary>
            private void Loop()
            {
                DateTime lastRun = DateTime.Now;

                while (true)
                {
                    lock (TaskSupervisor._taskLock)
                    {
                        this._task = TaskSupervisor.GetScheduledTask(this);
                    }

                    System.Threading.Thread.MemoryBarrier();

                    if (null != this._task)
                    {
                        bool result = false;

                        long runTime = -1;

                        TaskSupervisor.NotifyStart(this._task);

                        this.StartingTime = lastRun = DateTime.Now;
                        this.IsRunning = true;
                        System.Threading.Thread.MemoryBarrier();

                        Stopwatch timer = Stopwatch.StartNew();

                        try
                        {
                            result = this._task.Execute();

                            runTime = timer.ElapsedTicks;
                        }
                        catch (ThreadAbortException)
                        {
                            this._task = null;
                            throw;
                        }
                        catch (AppDomainUnloadedException)
                        {
                            this._task = null;
                            throw;
                        }
                        catch (Exception ex)
                        {
                            this.IsRunning = false;
                            if (!TaskSupervisor.NotifyException("Exception caught while executing task.", ex))
                            {
                                this._task = null;
                                System.Threading.Thread.MemoryBarrier();
                                throw;
                            }
                        }
                        finally
                        {
                            lastRun = DateTime.Now;
                            this.IsRunning = false;
                            this.StartingTime = DateTime.MinValue;
                            System.Threading.Thread.MemoryBarrier();
                            TaskSupervisor.NotifyEnd(this._task, runTime);
                        }

                        lock (TaskSupervisor._taskLock)
                        {
                            try
                            {
                                TaskWrapper toReturn = this._task;
                                this._task = null;
                                TaskSupervisor.RescheduleTask(toReturn, result);
                            }
                            catch (AppDomainUnloadedException)
                            {
                            }

                            this._task = null;
                        }

                        System.Threading.Thread.MemoryBarrier();

                        Thread.Sleep(100);
                    }
                    else
                    {
                        if (lastRun.AddSeconds(IdleTimeout) <= DateTime.Now)
                        {
                            TaskSupervisor.NotifyIdleThread(this);
                        }

                        Thread.Sleep(250);
                    }
                }
            }
        }

        #endregion
    }
}


text:
export namespace Libgit2 {
    const enum OPT {
        GET_MWINDOW_SIZE = 0,
        SET_MWINDOW_SIZE = 1,
        GET_MWINDOW_MAPPED_LIMIT = 2,
        SET_MWINDOW_MAPPED_LIMIT = 3,
        GET_SEARCH_PATH = 4,
        SET_SEARCH_PATH = 5,
        SET_CACHE_OBJECT_LIMIT = 6,
        SET_CACHE_MAX_SIZE = 7,
        ENABLE_CACHING = 8,
        GET_CACHED_MEMORY = 9,
        GET_TEMPLATE_PATH = 10,
        SET_TEMPLATE_PATH = 11,
        SET_SSL_CERT_LOCATIONS = 12
    }
}

export class Libgit2 {
    static features(): number;
    static init(): number;
    static opts(option: number): number;
    static shutdown(): number;
    static version(major: number, minor: number, rev: number): void;
}


text:
@import "html_cals_table.css";

/*
=================================
    Modify the HTML defaults to reflect
    the structure of the CALS table.
    The master file is in the DITA framework.
=================================
*/

/* Because the tgroup below is having the display: table, the table element
containing the element tgroup loses its display, becoming a block.*/
table,
simpletable{
  border-color:#EEEEEE;
  border-style:solid;
  border-width:2px;
  padding:2px;
}

/*
  A wrapper for the main content of a table, or part of a table
 */
tgroup {
  display:table;
  border-color:black;
  border-style:solid;
  border-width:1px;
}

/*
  Mechanism for toggling on/off the visibility of the colspecs.
 */
colspec, spanspec{
    display:none;
}

tgroup:before! > colspec{
    display:block;
    text-align:left;
    font-family: sansserif, verdana, helvetica;
    font-size: 0.75em;
    color: navy;
    padding-bottom: 0.2em;
}

col, colgroup {
	display:block;
}

/*
 * The frame is displayed on tgroup
 */
table[frame] {
    border-style:none;
}

/*
   If no frame attribute value is set, use a 1px border. This is similar to the PDF output.
*/
table[frame] > tgroup {
	border-style:none;
}

table[frame = 'above'] > tgroup,
table[frame = 'top'] > tgroup {
    border-top-color:black;
    border-top-style:solid;
    border-top-width:1px;
}

table[frame = 'below'] > tgroup,
table[frame = 'bottom'] > tgroup {
    border-bottom-color:black;
    border-bottom-style:solid;
    border-bottom-width:1px;
}

table[frame = 'rhs'] > tgroup,
simpletable[frame = 'rhs'] > tgroup {
    border-right-color:black;
    border-right-style:solid;
    border-right-width:1px;
}

table[frame = 'lhs'] > tgroup,
simpletable[frame = 'lhs'] > tgroup {
    border-left-color:black;
    border-left-style:solid;
    border-left-width:1px;
}

table[frame = 'vsides'] > tgroup,
table[frame = 'sides'] > tgroup {
    border-left-color:black;
    border-left-style:solid;
    border-left-width:1px;

    border-right-color:black;
    border-right-style:solid;
    border-right-width:1px;
}

table[frame = 'hsides'] > tgroup,
table[frame = 'topbot'] > tgroup {
    border-top-color:black;
    border-top-style:solid;
    border-top-width:1px;

    border-bottom-color:black;
    border-bottom-style:solid;
    border-bottom-width:1px;
}

table[frame = 'box'] > tgroup,
table[frame = 'border'] > tgroup,
table[frame = 'all'] > tgroup {
    border-color:black;
    border-style:solid;
    border-width:1px;
}


text:
require 'xdr'

# === xdr source ============================================================
#
#   struct AllowTrustOp
#   {
#       AccountID trustor;
#       union switch (CurrencyType type)
#       {
#       // NATIVE is not allowed
#       case ISO4217:
#           opaque currencyCode[4];
#
#           // add other currency types here in the future
#       }
#       currency;
#
#       bool authorize;
#   };
#
# ===========================================================================
module Stellar
  class AllowTrustOp < XDR::Struct
    include XDR::Namespace

    autoload :Currency

    attribute :trustor,   AccountID
    attribute :currency,  Currency
    attribute :authorize, XDR::Bool
  end
end


text:
export default {
  locales: ["en"],

  messages: {

    "meta": {
      "title": "isomorphic500",
      "description": "Demo application made with React and Fluxible",
      "loadingTitle": "Loading…",
      "errorTitle": "Error displaying this page",
      "notFoundTitle": "Page not found"
    },

    "features": {
      "dashboard": "Dahsboard",
      "inbox": "Boîte de réception",
      "profile": "Mon profile",
      "account": "Mon compte",
      "popular": "Most Popular",
      "highest_rated": "Highest Rated",
      "upcoming": "Upcoming",
      "editors": "Editors picks",
      "fresh_today": "Fresh Today",
      "fresh_yesterday": "Fresh Yesterday",
      "fresh_week": "Fresh This Week"
    },

    "featured": {
      "documentTitle": "{feature} on 500px"
    },

    "home": {
      "welcome": "Welcome to Aircnc. Use our new messaging system"
    },

    "photo": {

      "documentTitle": "{name} – by {user}",
      "documentDescription": "{name} is a photo by {user} published on 500px",

      "attribution": "Photo by {userLink}",
      "rating": "Rating {rating}"
    }
  }
};


text:
/**
 * Defines means of integration between programs and data access.
 *
 * All data access is performed via system or user defined (custom) Datasets.
 */
package co.cask.cdap.api.data;


text:
using System;
using Orleans.Runtime;

namespace Orleans.Configuration
{
    public class SimpleQueueCacheOptions
    {
        public int CacheSize { get; set; } = DEFAULT_CACHE_SIZE;
        public const int DEFAULT_CACHE_SIZE = 4096;
    }

    public class SimpleQueueCacheOptionsValidator : IConfigurationValidator
    {
        private readonly SimpleQueueCacheOptions options;
        private readonly string name;

        private SimpleQueueCacheOptionsValidator(SimpleQueueCacheOptions options, string name)
        {
            this.options = options;
            this.name = name;
        }
        public void ValidateConfiguration()
        {
            if(options.CacheSize <= 0)
                throw new OrleansConfigurationException($"{nameof(SimpleQueueCacheOptions)} on stream provider {this.name} is invalid. {nameof(SimpleQueueCacheOptions.CacheSize)} must be larger than zero");
        }

        public static IConfigurationValidator Create(IServiceProvider services, string name)
        {
            SimpleQueueCacheOptions queueCacheOptions = services.GetOptionsByName<SimpleQueueCacheOptions>(name);
            return new SimpleQueueCacheOptionsValidator(queueCacheOptions, name);
        }
    }
}


text:
package com.mirantis.opendaylight;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.function.Consumer;

/**
 * A convenient container of {@code AutoCloseable} resources.
 *
 * @author Leonid Bogdanov
 */
public final class Closer implements AutoCloseable {
    private static final Logger defaultLog = LoggerFactory.getLogger(Closer.class);

    private final Logger log;
    private final Deque<AutoCloseable> closables = new ArrayDeque<>(5);

    /**
     * Creates a new instance of the {@code Closer} class.
     */
    public Closer() {
        this(defaultLog);
    }

    /**
     * Creates a new instance of the {@code Closer} class.
     *
     * @param log the {@code Logger} instance which will be used to report errors
     */
    public Closer(Logger log) {
        this.log = log;
    }

    /**
     * Registers the given {@code AutoClosable} resource in this {@code Closer} instance.
     *
     * @param autoclosable the resource
     * @return the {@code AutoCloseable} instance
     */
    public <T extends AutoCloseable> T add(T autoclosable) {
        closables.push(autoclosable);
        return autoclosable;
    }

    /**
     * Registers the given {@code resource} in this {@code Closer} instance provided with the {@code Consumer} instance
     * containing the actual resource clean-up logic.
     *
     * @param resource the resource
     * @param closer the {@code Consumer} which will be invoked with the resource as an input arg to perform clean-up
     * @return the {@code resource} instance
     */
    public <T> T add(T resource, Consumer<? super T> closer) {
        closables.push(() -> closer.accept(resource));
        return resource;
    }

    /**
     * Closes all {@code AutoCloseable} instances that have been added to this {@code Closer}.
     */
    @Override
    public void close() {
        for (Iterator<AutoCloseable> itr = closables.iterator(); itr.hasNext(); itr.remove()) {
            try {
                itr.next().close();
            } catch (Exception e) {
                log.warn("Couldn't close a resource", e);
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
PipeCombiner (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API)
</TITLE>

<META NAME="date" CONTENT="2011-03-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.hadoop.streaming

Class PipeCombiner

java.lang.Object
  org.apache.hadoop.streaming.PipeMapRed
      org.apache.hadoop.streaming.PipeReducer
          org.apache.hadoop.streaming.PipeCombiner

All Implemented Interfaces:
java.io.Closeable, JobConfigurable, Reducer

public class PipeCombiner
extends PipeReducer

Field Summary

Fields inherited from class org.apache.hadoop.streaming.PipeMapRed

LOG, outerrThreadsThrowable

Constructor Summary

PipeCombiner()

Method Summary

Methods inherited from class org.apache.hadoop.streaming.PipeReducer

close, configure, reduce

Methods inherited from class org.apache.hadoop.streaming.PipeMapRed

getContext, mapRedFinished

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PipeCombiner

public PipeCombiner()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

This release is based on the Facebook's version of Hadoop.
Copyright © 2009 The Apache Software Foundation.


text:
===============
Getting Started
===============

Installation
=============

Use your favorite Python package manager to install the app from PyPI, e.g.

Example::

    pip install djangobricks

Configuration
=============

Add ``djangobricks`` to the ``INSTALLED_APPS`` within your settings file
(usually ``settings.py``).

Example::

    INSTALLED_APPS = [
        [...]
        'djangobricks',
    ]


text:
//
//  AKButtonImageCoordinator.h
//  AmazeKit
//
//  Created by Jeffrey Kelley on 6/19/12.
//  Copyright (c) 2013 Detroit Labs. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <UIKit/UIKit.h>

/** The AKImageCoordinator class is a convenient way to ensure that specific image renderers will
 *  produce appropriately-sized images for displaying in a button.
 *
 *  Typically, you will have a reference to an AKButtonImageCoordinator in a UIViewController class.
 *  Then, in the -viewWillAppear: method of your view controller, you'll call -addButton: on the
 *  button coordinator, which will take care of setting the appropriate image values. Similarly, in
 *  your implementation of -viewWillDisappear:, you'll call -removeButton: with the button to
 *  absolve the button image coordinator of responsibility for rendering images for off-screen
 *  views.
 *
 *  The button image coordinator maintains a reference to two image renderers: onImageRenderer and
 *  offImageRenderer. The onImageRenderer corresponds to the button's highlighted control state, and
 *  the offImageRenderer corrsponds to the button's normal control state.
 */

@class AKImageRenderer;

@interface AKButtonImageCoordinator : NSObject

/** ----------------------------------------------
 *  @name Configuring the Button Image Coordinator
 *  ----------------------------------------------
 */

/** An image renderer for the "on" state, corresponding to the button's highlighted control state.
 */
@property (strong, nonatomic) AKImageRenderer	*onImageRenderer;

/** An image renderer for the "off" state, corresponding to the button's normal control state.
 */
@property (strong, nonatomic) AKImageRenderer	*offImageRenderer;

/** ---------------------------------
 *  @name Adding and Removing Buttons
 *  ---------------------------------
 */

/** Adds a button to the button image coordinator. When the button's frame changes, the button image
 *  coordinator will automatically re-render the images.
 *
 *  @param button The button for which the image coordinator will render images.
 */
- (void)addButton:(UIButton *)button;

/** Removes a button from the button image coordinator. This will not clear the current images in
 *  the button, but will prevent the button image coordinator from re-rendering images if the
 *  button's frame changes.
 *
 *  @param button The button for which the button image coordinator will no longer render images.
 */
- (void)removeButton:(UIButton *)button;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:gravity="center"
    android:text="Error"
    android:layout_height="match_parent">

</TextView>


text:
using Google.Apis.Calendar.v3.Data;
using StruggleApplication.api;
using StruggleApplication.framework;
using System;
using System.Collections.Generic;
using System.Text;

namespace StruggleApplication.domain
{
    class Plan
    {

        private ICalendarInstance _instance;

        private int _pomodoroTimeLearing;
        private int _pomodoroTimeBreak;
        private int _pomodoroTime;

        public Plan()
        {
            this._instance = new GoogleCalendarInstance();
            this._instance.Initialize("");
            this._pomodoroTimeBreak = 10;
            this._pomodoroTimeLearing = 50;
            this._pomodoroTime = this._pomodoroTimeLearing + this._pomodoroTimeBreak;
        }

        public void planExam(String titleOfExam, DateTime from, DateTime to,
            int effortInMinutes, int maxPomodorosPerDay)
        {

        }

        // Returns the carry over of pomodoros
        public int planPomodoroOfDay(DateTime startTimeOfDay, DateTime endTimeOfDay, List<Event> events, int numberOfPomodoros, String titleOfExam)
        {
            endTimeOfDay = endTimeOfDay.AddHours(-1);
            DateTime currentFrom = startTimeOfDay;
            DateTime currentTo = currentFrom.AddMinutes(this._pomodoroTime);
            int createdPomodoros = 0;

            if (events.Count == 0) // no events
            {
                while (currentFrom.CompareTo(endTimeOfDay) == -1)
                {
                    AddPomodoro(currentFrom, titleOfExam);
                    createdPomodoros++;
                    // next pomodoro start time
                    currentFrom = currentFrom.AddMinutes(this._pomodoroTime);
                }
            }
            else // there is a event / are more events
            {
                List<Event>.Enumerator e = events.GetEnumerator();

                while (currentFrom.CompareTo(endTimeOfDay) == -1)
                {
                    if (e.MoveNext())
                    {
                        DateTime eventFrom = e.Current.Start.DateTime.Value;
                        DateTime eventTo = e.Current.End.DateTime.Value;

                        if (currentFrom.Subtract(eventTo).TotalMinutes > 0)
                        {
                            // placeable
                            AddPomodoro(currentFrom, titleOfExam);
                            createdPomodoros++;
                            // next pomodoro start time
                            currentFrom = currentFrom.AddMinutes(this._pomodoroTime);
                        }
                        if (eventFrom.Subtract(currentFrom).TotalMinutes > this._pomodoroTime)
                        {
                            // placeable
                            AddPomodoro(currentFrom, titleOfExam);
                            createdPomodoros++;
                            // next pomodoro start time
                            currentFrom = currentFrom.AddMinutes(this._pomodoroTime);
                        }
                        else // if (eventFrom.Subtract(currentFrom).TotalMinutes < this._pomodoroTime)
                        {
                            // collision
                            currentFrom = currentFrom.AddMinutes(5);
                            continue;
                        }
                        if (eventTo.Subtract(currentFrom).TotalMinutes >= 0 &&
                            currentFrom.Subtract(eventFrom).TotalMinutes >= 0)
                        {
                            // collision
                            currentFrom = currentFrom.AddMinutes(5);
                            continue;
                        }
                    }//if move next
                    else
                    {
                        // no events anymore
                        // ...
                    }

                    if (createdPomodoros == numberOfPomodoros)
                        break;
                }//while currentFrom head is lower than end time of day
            }//else

            return numberOfPomodoros - createdPomodoros;
        }

        // E.g.: start time is 08:00 o'clock to end time 21:00 o'clock
        public TimeSpan CalculateAvailableTime(DateTime startTimeOfDay, DateTime endTimeOfDay, List<Event> events)
        {
            TimeSpan time = startTimeOfDay.Subtract(endTimeOfDay);

            // TODO: overlapping events
            // ATM: The calculation is wrong if the input events are overlapping

            foreach (Object obj in events)
            {
                Event currentEvent = (Event)obj;
                DateTime eventstart = currentEvent.Start.DateTime.Value;
                DateTime eventEnd = currentEvent.End.DateTime.Value;
                time = time.Subtract(eventEnd.Subtract(eventstart));
            }

            return time;
        }

        public int GetNumberOfDays(DateTime from, DateTime to)
        {
            double diff = to.Subtract(from).TotalDays;
            int numberOfDays = (int)Math.Ceiling(diff) + 1;

            return numberOfDays;
        }

        public int GetNumberOfWeeks(DateTime from, DateTime to)
        {
            double diff = to.AddDays(-1).Subtract(from).TotalDays;
            return (int)Math.Ceiling(diff / 7);
        }

        // Adds a learning and a break event
        public void AddPomodoro(DateTime startDateTime, String titleOfExam)
        {
            // learn
            AddEvent(startDateTime, this._pomodoroTimeLearing, "Lernen", titleOfExam);
            // break
            startDateTime = startDateTime.AddMinutes(this._pomodoroTimeLearing);
            AddEvent(startDateTime, this._pomodoroTimeBreak, "Pause", "");
        }

        // Adds an event
        private void AddEvent(DateTime startDateTime, int durationMinutes, String title, String desc)
        {
            EventDateTime eventStart = new EventDateTime();
            EventDateTime eventEnd = new EventDateTime();

            eventStart.DateTime = startDateTime;
            eventEnd.DateTime = eventStart.DateTime.Value.AddMinutes(durationMinutes);

            // create event
            this._instance.CreateEvent(title, desc, eventStart, eventEnd);
        }

    }//class
}//namespace


text:
package org.teavm.maven;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.MavenArtifactRepository;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.teavm.model.ClassHolderTransformer;
import org.teavm.tooling.*;

/**
 *
 * @author Alexey Andreev
 */
@Mojo(name = "build-javascript", requiresDependencyResolution = ResolutionScope.COMPILE,
        requiresDependencyCollection = ResolutionScope.COMPILE)
public class BuildJavascriptMojo extends AbstractMojo {
    private static Set<String> compileScopes = new HashSet<>(Arrays.asList(
            Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_SYSTEM));

    @Component
    private MavenProject project;

    @Component
    private RepositorySystem repositorySystem;

    @Parameter(required = true, readonly = true, defaultValue = "${localRepository}")
    private MavenArtifactRepository localRepository;

    @Parameter(required = true, readonly = true, defaultValue = "${project.remoteArtifactRepositories}")
    private List<MavenArtifactRepository> remoteRepositories;

    @Parameter(readonly = true, defaultValue = "${plugin.artifacts}")
    private List<Artifact> pluginArtifacts;

    @Parameter(defaultValue = "${project.build.directory}/javascript")
    private File targetDirectory;

    @Parameter(defaultValue = "${project.build.outputDirectory}")
    private File classFiles;

    @Parameter
    private String targetFileName = "classes.js";

    @Parameter
    private boolean minifying = true;

    @Parameter
    private String mainClass;

    @Parameter
    private RuntimeCopyOperation runtime = RuntimeCopyOperation.SEPARATE;

    @Parameter
    private Properties properties;

    @Parameter
    private boolean mainPageIncluded;

    @Parameter
    private boolean bytecodeLogging;

    @Parameter
    private boolean debugInformationGenerated;

    @Parameter
    private boolean sourceMapsGenerated;

    @Parameter
    private boolean sourceFilesCopied;

    @Parameter
    private boolean incremental;

    @Parameter(defaultValue = "${project.build.directory}/teavm-cache")
    private File cacheDirectory;

    @Parameter
    private String[] transformers;

    @Parameter
    private ClassAlias[] classAliases;

    @Parameter
    private MethodAlias[] methodAliases;

    @Parameter
    private boolean stopOnErrors = true;

    private TeaVMTool tool = new TeaVMTool();

    public void setProject(MavenProject project) {
        this.project = project;
    }

    public void setTargetDirectory(File targetDirectory) {
        this.targetDirectory = targetDirectory;
    }

    public void setTargetFileName(String targetFileName) {
        this.targetFileName = targetFileName;
    }

    public void setClassFiles(File classFiles) {
        this.classFiles = classFiles;
    }

    public void setMinifying(boolean minifying) {
        this.minifying = minifying;
    }

    public void setBytecodeLogging(boolean bytecodeLogging) {
        this.bytecodeLogging = bytecodeLogging;
    }

    public void setRuntimeCopy(RuntimeCopyOperation runtimeCopy) {
        this.runtime = runtimeCopy;
    }

    public void setMainPageIncluded(boolean mainPageIncluded) {
        this.mainPageIncluded = mainPageIncluded;
    }

    public String[] getTransformers() {
        return transformers;
    }

    public void setTransformers(String[] transformers) {
        this.transformers = transformers;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void setClassAliases(ClassAlias[] classAliases) {
        this.classAliases = classAliases;
    }

    public void setMethodAliases(MethodAlias[] methodAliases) {
        this.methodAliases = methodAliases;
    }

    public boolean isDebugInformationGenerated() {
        return debugInformationGenerated;
    }

    public void setDebugInformationGenerated(boolean debugInformationGenerated) {
        this.debugInformationGenerated = debugInformationGenerated;
    }

    public boolean isSourceMapsGenerated() {
        return sourceMapsGenerated;
    }

    public void setSourceMapsGenerated(boolean sourceMapsGenerated) {
        this.sourceMapsGenerated = sourceMapsGenerated;
    }

    public boolean isSourceFilesCopied() {
        return sourceFilesCopied;
    }

    public void setSourceFilesCopied(boolean sourceFilesCopied) {
        this.sourceFilesCopied = sourceFilesCopied;
    }

    public boolean isIncremental() {
        return incremental;
    }

    public void setIncremental(boolean incremental) {
        this.incremental = incremental;
    }

    public void setStopOnErrors(boolean stopOnErrors) {
        this.stopOnErrors = stopOnErrors;
    }

    public File getCacheDirectory() {
        return cacheDirectory;
    }

    public void setCacheDirectory(File cacheDirectory) {
        this.cacheDirectory = cacheDirectory;
    }

    @Override
    public void execute() throws MojoExecutionException {
        Log log = getLog();
        tool.setLog(new MavenTeaVMToolLog(log));
        try {
            ClassLoader classLoader = prepareClassLoader();
            tool.setClassLoader(classLoader);
            tool.setBytecodeLogging(bytecodeLogging);
            tool.setMainClass(mainClass);
            tool.setMainPageIncluded(mainPageIncluded);
            tool.setMinifying(minifying);
            tool.setRuntime(runtime);
            tool.setTargetDirectory(targetDirectory);
            tool.setTargetFileName(targetFileName);
            tool.getTransformers().addAll(instantiateTransformers(classLoader));
            if (sourceFilesCopied) {
                MavenSourceFileProviderLookup lookup = new MavenSourceFileProviderLookup();
                lookup.setMavenProject(project);
                lookup.setRepositorySystem(repositorySystem);
                lookup.setLocalRepository(localRepository);
                lookup.setRemoteRepositories(remoteRepositories);
                lookup.setPluginDependencies(pluginArtifacts);
                for (SourceFileProvider provider : lookup.resolve()) {
                    tool.addSourceFileProvider(provider);
                }
            }
            if (classAliases != null) {
                tool.getClassAliases().addAll(Arrays.asList(classAliases));
            }
            if (methodAliases != null) {
                tool.getMethodAliases().addAll(Arrays.asList(methodAliases));
            }
            if (properties != null) {
                tool.getProperties().putAll(properties);
            }
            tool.setCacheDirectory(cacheDirectory);
            tool.setIncremental(incremental);
            tool.setDebugInformationGenerated(debugInformationGenerated);
            tool.setSourceMapsFileGenerated(sourceMapsGenerated);
            tool.setSourceFilesCopied(sourceFilesCopied);
            tool.generate();
            if (stopOnErrors && !tool.getProblemProvider().getSevereProblems().isEmpty()) {
                throw new MojoExecutionException("Build error");
            }
        } catch (RuntimeException e) {
            throw new MojoExecutionException("Unexpected error occured", e);
        } catch (TeaVMToolException e) {
            throw new MojoExecutionException("IO error occured", e);
        }
    }

    private List<ClassHolderTransformer> instantiateTransformers(ClassLoader classLoader)
            throws MojoExecutionException {
        List<ClassHolderTransformer> transformerInstances = new ArrayList<>();
        if (transformers == null) {
            return transformerInstances;
        }
        for (String transformerName : transformers) {
            Class<?> transformerRawType;
            try {
                transformerRawType = Class.forName(transformerName, true, classLoader);
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException("Transformer not found: " + transformerName, e);
            }
            if (!ClassHolderTransformer.class.isAssignableFrom(transformerRawType)) {
                throw new MojoExecutionException("Transformer " + transformerName + " is not subtype of " +
                        ClassHolderTransformer.class.getName());
            }
            Class<? extends ClassHolderTransformer> transformerType = transformerRawType.asSubclass(
                    ClassHolderTransformer.class);
            Constructor<? extends ClassHolderTransformer> ctor;
            try {
                ctor = transformerType.getConstructor();
            } catch (NoSuchMethodException e) {
                throw new MojoExecutionException("Transformer " + transformerName + " has no default constructor");
            }
            try {
                ClassHolderTransformer transformer = ctor.newInstance();
                transformerInstances.add(transformer);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                throw new MojoExecutionException("Error instantiating transformer " + transformerName, e);
            }
        }
        return transformerInstances;
    }

    private ClassLoader prepareClassLoader() throws MojoExecutionException {
        try {
            Log log = getLog();
            log.info("Preparing classpath for JavaScript generation");
            List<URL> urls = new ArrayList<>();
            StringBuilder classpath = new StringBuilder();
            for (Artifact artifact : project.getArtifacts()) {
                if (!compileScopes.contains(artifact.getScope())) {
                    continue;
                }
                File file = artifact.getFile();
                if (classpath.length() > 0) {
                    classpath.append(':');
                }
                classpath.append(file.getPath());
                urls.add(file.toURI().toURL());
            }
            if (classpath.length() > 0) {
                classpath.append(':');
            }
            classpath.append(classFiles.getPath());
            urls.add(classFiles.toURI().toURL());
            log.info("Using the following classpath for JavaScript generation: " + classpath);
            return new URLClassLoader(urls.toArray(new URL[urls.size()]), BuildJavascriptMojo.class.getClassLoader());
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Error gathering classpath information", e);
        }
    }
}


text:
import sys
from time import time

FILEEXTENSIONLENGTH = 4
NUMBEROFINPUTS = 32 # inherent to the MADC system

dataOrder = [0,1,16,17,8,9,24,25,2,3,18,19,10,11,26,27, \
			4,5,20,21,12,13,28,29,6,7,22,23,14,15,30,31]

filename = sys.argv[1]
if len(sys.argv) == 3:
	numberColumnsKeep = int(sys.argv[2])
else:
	numberColumnsKeep = NUMBEROFINPUTS

outfilename = filename[:-FILEEXTENSIONLENGTH]+'_parsed_TEST.txt'

initialTime = time()

with open(filename) as f:
	with open(outfilename,'w') as of:
		while True:
			currLine = f.readline()
			if currLine == '':
				# print('Output file written to',outfilename)
				break
			if currLine == '4040\n': # marks end of header
				# print(previousLine) # DEBUGGING
				numData = int(previousLine.split()[0][-2:],16) - 1 # convert last 2 bits to decimal,
													   # -1 because of end-header
				# print(numData) # DEBUGGING
				batchData = [0]*NUMBEROFINPUTS
				badBatch = False
				# for i in range(numData):
				for i in range(2):
					# print(f.tell())
					dataLine = f.readline()
					dataidLine = f.readline()
					data = int(dataLine.split()[0],16)
					dataid = int(dataidLine.split()[0][-2:],16)
					if not dataid == dataOrder[i]:
						badBatch = True
						break
					batchData[dataid] = data
				if not badBatch:
					# print(batchData)
					for bd in batchData:
						of.write(str(bd)+'\t')
					of.write('\n')
			previousLine = currLine # store previous line for later reference

elapsedTime = time() - initialTime
print(round(elapsedTime,3),'seconds taken to parse.')


text:
FROM java:8-jdk-alpine

COPY javassist.jar .
COPY MemoryTest.java .

RUN javac -cp javassist.jar MemoryTest.java > /dev/null 2>&1

# Limits the maximum JVM Heap size. An OutOfMemoryException will be generated.
# Observe 'Java Heap' in jcmd output.
ENV MAX_HEAP_SIZE_MB=64

# Limits the maximum JVM Metaspace size. An OutOfMemoryException will be generated.
# Observe 'Class' in jcmd output.
ENV MAX_CLASS_SIZE_MB=64

# Limits the maximum total size of direct buffers allocated by the JVM. An OutOfMemoryException will be generated.
# Observe 'Internal' in jcmd output.
ENV MAX_DIRECT_SIZE_MB=64

# Defines the Stack size of each thread.
# There is no way to force a limit. If you create enough threads you can use all the available memory.
# Observe 'Thread' in jcmd output.
ENV THREAD_STACK_SIZE_KB=256

# Defines the period of an allocation cycle
ENV ALLOC_PERIOD_MS=1000

# MB of Heap to allocate per cycle.
# Uses: byte[]
# Observe 'Java Heap' in jcmd output.
ENV ALLOC_HEAP_MB=0

# Numer of new classes to load per cycle.
# Uses: javassist to synthetize and load new classes on the fly
# Observe 'Class' in jcmd output.
ENV ALLOC_CLASSES_COUNT=0

# MB of direct memory to allocate per cycle.
# Uses: java.nio.ByteBuffer.allocateDirect()
# Observe 'Internal' in jcmd output.
ENV ALLOC_DIRECT_MB=0

# Numer of new thread to create and start per cycle.
# Uses: new Thread(). The thread just sleeps.
# Observe 'Thread' in jcmd output.
ENV ALLOC_THREADS_COUNT=0

# MB of native memory to allocate per cycle.
# Uses: sun.misc.Unsafe.allocateMemory()
# Observe 'Internal' in jcmd output.
ENV ALLOC_NATIVE_MB=0

# Defines the period for the jcmd output
ENV LOG_PERIOD_S=1

CMD java \
     -XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=summary -XX:+PrintNMTStatistics -XX:-AutoShutdownNMT \
     -Xmx${MAX_HEAP_SIZE_MB}m -Xms1m \
     -Xss${THREAD_STACK_SIZE_KB}k \
     -XX:MaxMetaspaceSize=${MAX_CLASS_SIZE_MB}m \
     -XX:MaxDirectMemorySize=${MAX_DIRECT_SIZE_MB}m \
     -cp javassist.jar:. \
     MemoryTest $ALLOC_PERIOD_MS $ALLOC_HEAP_MB $ALLOC_NATIVE_MB $ALLOC_DIRECT_MB $ALLOC_CLASSES_COUNT $ALLOC_THREADS_COUNT \
     & PID=$! ; while [ -e /proc/$PID ] ; do jcmd $PID VM.native_memory summary scale=MB ; sleep ${LOG_PERIOD_S}s ; done


text:
| Name | Type | iOS | tvOS | watchOS | macOS |
|:--- | :--- | :---: | :---: | :---: | :---: |
| [**`replaceTitle(with image: UIImage)`**](#replacetitlewith-image-uiimage) | Method | 8+ | 9+ | - | - |

---

## `replaceTitle(with image: UIImage)`
Replace title label with an image in navigation item.

- **type**: Method.
- **parameters**:
    - **image**: UIImage to replace title with.
- **return type**: Void
- **availability**: `iOS 8+`, `tvOS 9+`.
- **unit tests**: `iOS`, `tvOS`.

Example

```swift
let navigationItem = UINavigationItem()
let image = UIImage()
navigationItem.replaceTitle(with: image)
```

---