text:
var Constants = require('./constants');
var req = require('request');
var debug = require('debug')('node-gcm');

function Sender(key, options) {
    if (!(this instanceof Sender)) {
        return new Sender(key, options);
    }

    this.key = key;
    this.options = options;
}

var parseAndRespond = function(resBody, callback) {
    var resBodyJSON;

    try {
        resBodyJSON = JSON.parse(resBody);
    } catch (e) {
        debug("Error parsing GCM response " + e);
        callback("Error parsing GCM response");
        return;
    }

    callback(null, resBodyJSON);
};

function extractRecipient(recipient) {
    var validKeys = ['registrationIds', 'topic', 'notificationKey'];
    var theRecipient;

    validKeys.forEach(function(key) {
        if (recipient[key]) {
            theRecipient = recipient[key];
            return;
        }
    });

    return {
        err: theRecipient ?
            null :
            'Invalid recipient key(s) ' + Object.keys(recipient) + ' (valid keys: ' + validKeys.join(', ') + ')',
        recipient: theRecipient
    };
}

Sender.prototype.sendNoRetry = function(message, recipient, callback) {
    if(!callback) {
        callback = function() {};
    }

    var body = message.toJson();

    if(typeof recipient == "string") {
        body.to = recipient;
    }
    else if (!Array.isArray(recipient) && typeof recipient == "object") {
        var o = extractRecipient(recipient);
        var theRecipient;

        if (o.err) {
            return callback(o.err);
        }
        else {
            theRecipient = o.recipient;
        }

        if (Array.isArray(theRecipient)) {
            body.registration_ids = theRecipient;
        }
        else {
            body.to = theRecipient;
        }
    }
    else {
        body.registration_ids = recipient;
    }

    var requestBody = JSON.stringify(body);

    var post_options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-length': Buffer.byteLength(requestBody, 'utf8'),
            'Authorization': 'key=' + this.key
        },
        uri: Constants.GCM_SEND_URI,
        body: requestBody
    };

    if (this.options && this.options.proxy) {
        post_options.proxy = this.options.proxy;
	post_options.tunnel = false;
    }

    if (this.options && this.options.maxSockets) {
        post_options.maxSockets = this.options.maxSockets;
    }

    var timeout = Constants.SOCKET_TIMEOUT;

    if (this.options && this.options.timeout) {
        timeout =  this.options.timeout;
    }

    post_options.timeout = timeout;

    var post_req = req(post_options, function (err, res, resBody) {
        if (err) {
            return callback(err, null);

        }
        if (!res) {
            return callback('response is null', null);

        }

        if (res.statusCode >= 500) {
            debug('GCM service is unavailable (500)');
            return callback(res.statusCode, null);
        } else if (res.statusCode === 401) {
            debug('Unauthorized (401). Check that your API token is correct.');
            return callback(res.statusCode, null);
        } else if (res.statusCode !== 200) {
            debug('Invalid request (' + res.statusCode + '): ' + resBody);
            return callback(res.statusCode, null);
        }

        parseAndRespond(resBody, callback);
    });
};

Sender.prototype.send = function(message, recipient, options, callback) {
    var backoff, retries;

    // In case of failure, will be passed to send() again for retry
    var originalRecipient = recipient;

    if(typeof options == "object") {
        retries = options.retries;
        backoff = options.backoff;

        if(typeof options.retries != "number") {
            retries = 5;
        }
        if(typeof options.backoff != "number") {
            backoff = Constants.BACKOFF_INITIAL_DELAY;
        }
    }
    else if(typeof options == "function") {
        retries = 5;
        backoff = Constants.BACKOFF_INITIAL_DELAY;
        callback = options;
    }
    else if(typeof options == "number") {
        retries = options;
        backoff = Constants.BACKOFF_INITIAL_DELAY;
    }

    if(!callback) {
        callback = function() {};
    }

    if(typeof recipient == "string") {
        recipient = [recipient];
    }
    else if (!Array.isArray(recipient) && typeof recipient == "object") {
        // For topics, passing them to sendNoRetry() as if they were registration IDs
        // will put them in the "to" value of the JSON payload, which what we want
        var o = extractRecipient(recipient);

        if (o.err) {
            return callback(o.err);
        }
        else {
            recipient = o.recipient;
        }
    }

    if (Array.isArray(recipient) && !recipient.length) {
        debug('No RegistrationIds given!');
        return process.nextTick(callback.bind(this, 'No RegistrationIds given!', null));
    }

    if(retries == 0) {
        return this.sendNoRetry(message, recipient, callback);
    }
    if (backoff > Constants.MAX_BACKOFF_DELAY) {
        backoff = Constants.MAX_BACKOFF_DELAY;
    }

    var self = this;

    this.sendNoRetry(message, recipient, function(err, result) {
        // if we err'd resend them all
        if (err) {
            return setTimeout(function() {
                self.send(message, originalRecipient, {
                    retries: retries - 1,
                    backoff: backoff * 2
                }, callback);
            }, backoff);
        }

        // check for bad ids
        var unsentRegIds = [], regIdPositionMap = [];

        // Responses for messages sent a topic just contain { message_id: '...' } or { error: '...' }
        if (result.results) {
            for (var i = 0; i < recipient.length; i++) {
                if (result.results[i].error === 'Unavailable') {
                    regIdPositionMap.push(i);
                    unsentRegIds.push(recipient[i]);
                }
            }
        }

        if (!unsentRegIds.length) {
            return callback(err, result);
        }

        debug("Results received but not all successful", result);

        setTimeout(function () {
            debug("Retrying unsent registration ids");
            self.send(message, unsentRegIds, {
                retries: retries - 1,
                backoff: backoff * 2
            }, function(err, retriedResult) {
                //If the recursive call err'd completely, our current result is the best available
                if(err) {
                    return callback(null, result);
                }

                //Map retried results onto their previous positions in the full array
                var retriedResults = retriedResult.results;
                for(var i = 0; i < result.results.length; i++) {
                    var oldIndex = regIdPositionMap[i];
                    result.results[oldIndex] = retriedResults[i];
                }

                //Update the fields on the result depending on newly returned value
                result.success += retriedResult.success;
                result.canonical_ids += retriedResult.canonical_ids;
                result.failure -= unsentRegIds.length - retriedResult.failure;

                callback(null, result);
            });
        }, backoff);
    });
};

module.exports = Sender;


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// This file tests migration from v3 to v4

function run_test()
{
  // First import the downloads.sqlite file
  importDatabaseFile("v3.sqlite");

  // ok, now it is OK to init the download manager - this will perform the
  // migration!
  var dm = Cc["@mozilla.org/download-manager;1"].
           getService(Ci.nsIDownloadManager);
  var dbConn = dm.DBConnection;
  var stmt = null;

  // check schema version
  do_check_true(dbConn.schemaVersion >= 4);

  // Check that the column exists (statement should not throw)
  stmt = dbConn.createStatement("SELECT entityID FROM moz_downloads");
  stmt.finalize();

  // now we check the entries
  stmt = dbConn.createStatement(
    "SELECT name, source, target, startTime, endTime, state, referrer, entityID " +
    "FROM moz_downloads " +
    "WHERE id = 27");
  stmt.executeStep();
  do_check_eq("Firefox 2.0.0.6.dmg", stmt.getString(0));
  do_check_eq("http://ftp-mozilla.netscape.com/pub/mozilla.org/firefox/releases/2.0.0.6/mac/en-US/Firefox%202.0.0.6.dmg",
              stmt.getUTF8String(1));
  do_check_eq("file:///Users/sdwilsh/Desktop/Firefox%202.0.0.6.dmg",
              stmt.getUTF8String(2));
  do_check_eq(1187390974170783, stmt.getInt64(3));
  do_check_eq(1187391001257446, stmt.getInt64(4));
  do_check_eq(1, stmt.getInt32(5));
  do_check_eq("http://www.mozilla.com/en-US/products/download.html?product=firefox-2.0.0.6&os=osx&lang=en-US",stmt.getUTF8String(6));
  do_check_true(stmt.getIsNull(7));
  stmt.finalize();

  cleanup();
}

redpajama_set_name: RedPajamaGithub


text:
@php
    $id = $id ?? 'bsComp_chkbx_' . incrementedInt();
@endphp

    <input
            @isset($class)
            class="custom-control-input {{$class}}"
            @else
            class="custom-control-input"
            @endisset
            type="checkbox"
            id="{{ $id }}"
            value="{{ strlen(trim($slot)) == 0 ? '1' : trim($slot) }}"
            @isset($name)
            name="{{ $name }}"
            @endisset
            @if($checked ?? false)
            checked="checked"
            @endif
            @isset($style)
            style="{{ $style }}"
            @endisset
    >
    {{ $label ?? '' }}


text:
var path = require("path"),
    PSON = require(path.join(__dirname, "dist", "PSON.js"));

module.exports = PSON;


text:
module UpsPickup
  class FaultResponse < ErrorResponse
    attr_accessor :response
    def initialize(client,response)
      fault_client = client
      fault_client.config.raise_errors = false
      @response = Savon::SOAP::Response.new(fault_client.config,response.http)

    end

  end
end


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
using System.Timers;
using D2MPMaster.Browser;
using D2MPMaster.Client;
using D2MPMaster.Database;
using D2MPMaster.LiveData;
using D2MPMaster.Model;
using D2MPMaster.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XSockets.Core.Common.Globals;
using XSockets.Core.Common.Socket;
using XSockets.Core.Common.Socket.Event.Arguments;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using PluginRange = XSockets.Plugin.Framework.PluginRange;
using Query = MongoDB.Driver.Builders.Query;
using D2MPMaster.Matchmaking;
using D2MPMaster.Party;

namespace D2MPMaster.Lobbies
{
    /// <summary>
    /// Manages the lifecycle of lobbies and the list.
    /// </summary>
    [XSocketMetadata("LobbyManager", Constants.GenericTextBufferSize, PluginRange.Internal)]
    public class LobbyManager : XSocketController, IDisposable
    {
        private static readonly ClientController ClientsController = new ClientController();
        private static readonly BrowserController Browsers = new BrowserController();
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Lobbies that should be visible in the list.
        /// </summary>
        public static ObservableCollection<Lobby> PublicLobbies = new ObservableCollection<Lobby>();

        /// <summary>
        /// Lobbies that should have full updates sent out JUST to users in them.
        /// </summary>
        public static ObservableCollection<Lobby> PlayingLobbies = new ObservableCollection<Lobby>();

        //Test lobbies being batched together before being put into the main lobby queue
        public static List<Lobby> TestLobbyQueue = new List<Lobby>();

        public static ConcurrentDictionary<string,Lobby> LobbyID = new ConcurrentDictionary<string,Lobby>();

        public static volatile bool running = false;

        public static List<Lobby> LobbyQueue = new List<Lobby>();

        public static Queue<JObject> PublicLobbyUpdateQueue = new Queue<JObject>();

		public static System.Timers.Timer LobbyUpdateTimer;
		public static System.Timers.Timer IdleLobbyTimer;
		public static System.Timers.Timer CalculateQueueTimer;
		public static System.Timers.Timer TestLobbyTimer;

        static LobbyManager()
        {
			PublicLobbies.CollectionChanged += TransmitLobbiesChange;
			PlayingLobbies.CollectionChanged += UpdateLobbyIDDict;
        }

		public static void Start()
		{
			if (running)
				return;
			running = true;

			//Send out public lobby list updates
			LobbyUpdateTimer = new System.Timers.Timer (500);
			LobbyUpdateTimer.Elapsed += LobbyUpdateProc;
			LobbyUpdateTimer.Start ();

			//Close any idle lobbies every 20 seconds
			IdleLobbyTimer = new System.Timers.Timer (20000);
			IdleLobbyTimer.Elapsed += IdleLobbyProc;
			IdleLobbyTimer.Start ();

			//Calculate server matches for lobbies
			CalculateQueueTimer = new System.Timers.Timer (2000);
			CalculateQueueTimer.Elapsed += CalculateQueue;
			CalculateQueueTimer.Start ();

			//Group test lobbies together
			TestLobbyTimer = new System.Timers.Timer (30000);
			TestLobbyTimer.Elapsed += TestLobbyProc;
			TestLobbyTimer.Start ();
		}

		public static void Stop()
		{
			if(!running) return;
			LobbyUpdateTimer.Stop();
			LobbyUpdateTimer.Close();
			LobbyUpdateTimer.Dispose();

			IdleLobbyTimer.Stop();
			IdleLobbyTimer.Close();
			IdleLobbyTimer.Dispose();

			CalculateQueueTimer.Stop();
			CalculateQueueTimer.Close();
			CalculateQueueTimer.Dispose();

			TestLobbyTimer.Stop();
			TestLobbyTimer.Close();
			TestLobbyTimer.Dispose();
		}

		public void Dispose()
		{
		}

        private static void UpdateLobbyIDDict(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Reset)
            {
                LobbyID.Clear();
                return;
            }
            if (e.NewItems != null)
                foreach (Lobby lobby in e.NewItems)
                {
                    switch (e.Action)
                    {
                        case NotifyCollectionChangedAction.Add:
                            LobbyID[lobby.id] = lobby;
                            break;
                    }
                }
            if (e.OldItems != null)
                foreach (Lobby lobby in e.OldItems)
                {
                    switch (e.Action)
                    {
                        case NotifyCollectionChangedAction.Remove:
                            Lobby res;
                            LobbyID.TryRemove(lobby.id, out res);
                            break;
                    }
                }
        }

        public static void TransmitLobbiesChange(object s, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Reset)
            {
                PublicLobbyUpdateQueue.Enqueue(DiffGenerator.RemoveAll("publicLobbies"));
            }
            else
            {
                if (e.NewItems != null)
                    foreach (var lobby in e.NewItems)
                    {
                        switch (e.Action)
                        {
                            case NotifyCollectionChangedAction.Add:
                                PublicLobbyUpdateQueue.Enqueue(lobby.Add("publicLobbies"));
                                break;
                        }
                    }
                if (e.OldItems != null)
                    foreach (var lobby in e.OldItems)
                    {
                        switch (e.Action)
                        {
                            case NotifyCollectionChangedAction.Remove:
                                PublicLobbyUpdateQueue.Enqueue(lobby.Remove("publicLobbies"));
                                break;
                        }
                    }
            }
        }

		public static void TestLobbyProc(object source, ElapsedEventArgs e)
        {
			lock (TestLobbyQueue) {
				lock (LobbyQueue) {
					foreach (var lobby in TestLobbyQueue) {
						LobbyQueue.Add (lobby);
						lobby.status = LobbyStatus.Queue;
						TransmitLobbyUpdate (lobby, new []{ "status" });
					}
					TestLobbyQueue.Clear ();
				}
			}
        }

		public static void LobbyUpdateProc(object source, ElapsedEventArgs e)
        {
			LobbyUpdateTimer.Stop ();
            var upd = new JObject();
            var updates = new JArray();
            while (PublicLobbyUpdateQueue.Count > 0)
            {
                var update = PublicLobbyUpdateQueue.Dequeue();
                if (update == null) continue;
                updates.Add(update);
            }
			if (updates.Count != 0) {
				upd ["msg"] = "colupd";
				upd ["ops"] = updates;
				var msg = upd.ToString (Formatting.None);
				Browsers.AsyncSendTo (m => m.user != null && m.lobby == null, new TextArgs (msg, "publicLobbies"), ar => {
				});
			}
			LobbyUpdateTimer.Start ();
        }

		public static void IdleLobbyProc(object source, ElapsedEventArgs e)
        {
            var lobbies =
                LobbyID.Values.Where(
                    m =>
                        m.status == LobbyStatus.Start &&
                        !m.hasPassword &&
					m.IdleSince < DateTime.Now.Subtract(TimeSpan.FromMinutes(3)));
            foreach (var lobby in lobbies)
            {
                CloseLobby(lobby);
                log.DebugFormat("Cleared lobby {0} for inactivity.", lobby.id);
            }
            //All playing lobbies with no server with an instance that has the lobby
            lock (PlayingLobbies) {
                lobbies =
                    LobbyID.Values.Where(
                        m => m.status==LobbyStatus.Play&&!ServerService.Servers.Find(z => z.Instances.Any(f => f.Value.lobby.id == m.id)).Any());
                foreach (var lobby in lobbies)
                {
					OnServerShutdownNoInstance(lobby);
                    log.DebugFormat("Cleared orphan lobby {0}.", lobby.id);
                }
            }
        }

        /// <summary>
        /// See if a user is already in a lobby.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static PlayerLocation FindPlayer(User user)
        {
            return PlayingLobbies.Select(lobby => FindPlayerLocation(user, lobby)).FirstOrDefault(loc => loc != null);
        }

        public static PlayerLocation FindPlayerLocationU(string userid, Lobby lobby)
        {
			if (userid == null || lobby == null)
				return null;
            User user = Mongo.Users.FindOneAs<User>(Query.EQ("_id", userid));
            if (user == null) return null;
            return FindPlayerLocation(user, lobby);
        }

        public static PlayerLocation FindPlayerLocation(User user, Lobby lobby)
        {
			if (user == null || lobby == null)
				return null;
            Player plyr;
            plyr = lobby.radiant.FirstOrDefault(player => player!=null&&player.steam == user.steam.steamid);
            if (plyr != null)
            {
                return new PlayerLocation()
                {
                    lobby = lobby,
                    goodguys = true,
                    player = plyr
                };
            }
            plyr = lobby.dire.FirstOrDefault(player => player!=null&&player.steam == user.steam.steamid);
            if (plyr != null)
            {
                return new PlayerLocation()
                {
                    lobby = lobby,
                    goodguys = true,
                    player = plyr
                };
            }
            return null;
        }

        /// <summary>
        /// Exit the lobby queue.
        /// </summary>
        /// <param name="lobby"></param>
        public static void CancelQueue(Lobby lobby)
        {
            if (lobby == null) return;
            lock (LobbyQueue)
            {
                if (!LobbyQueue.Contains(lobby)) return;
                LobbyQueue.Remove(lobby);
            }
            lobby.status = LobbyStatus.Start;
            lobby.IdleSince = DateTime.Now;
            if (lobby.isPublic)
                lock (PublicLobbies)
                    PublicLobbies.Add(lobby);
            TransmitLobbyUpdate(lobby, new[] { "status" });
        }

		private static void CalculateQueue(object source, ElapsedEventArgs e)
        {
            lock (LobbyQueue)
            {
                foreach (var lobby in LobbyQueue.ToArray())
                {
                    var server = ServerService.FindForLobby(lobby);
                    if (server == null) continue;
                    GameInstance instance = server.StartInstance(lobby);
                    lobby.status = LobbyStatus.Configure;
                    TransmitLobbyUpdate(lobby, new[] { "status" });
                    LobbyQueue.Remove(lobby);
                }
            }
        }

        /// <summary>
        /// Enter the lobby queue.
        /// </summary>
        /// <param name="lobby"></param>
        public static void StartQueue(Lobby lobby)
        {
            lock (LobbyQueue)
            {
                if (!LobbyQueue.Contains(lobby))
                {
                    lobby.status = LobbyStatus.Queue;
                    lock (PublicLobbies)
                        PublicLobbies.Remove(lobby);
                    TransmitLobbyUpdate(lobby, new[] {"status"});
                    SendLaunchDota(lobby);
                    LobbyQueue.Add(lobby);
                }
            }
        }

        public static void SetPassword(Lobby lobby, string password)
        {
            if (lobby == null) return;
            var hadPassword = lobby.hasPassword;
            if (password == null) password = "";

            if (password == "")
            {
                lobby.hasPassword = false;
                lobby.isPublic = true;
                lobby.password = "";
                lock (PublicLobbies)
                    if (!PublicLobbies.Contains(lobby)) PublicLobbies.Add(lobby);
            }
            else
            {
                lobby.hasPassword = true;
                lobby.isPublic = false;
                lobby.password = password;
                lock (PublicLobbies)
                    if (PublicLobbies.Contains(lobby)) PublicLobbies.Remove(lobby);
            }
            if (hadPassword != lobby.hasPassword)
                TransmitLobbyUpdate(lobby, new[] { "isPublic", "hasPassword" });
            lobby.IdleSince = DateTime.Now;
        }

        public static void TransmitLobbyUpdate(Lobby lobby, string[] fields)
        {
            //Generate message
            var upd = new JObject();
            upd["msg"] = "colupd";
            upd["ops"] = new JArray { lobby.Update("lobbies", fields) };
            Browsers.AsyncSendTo(m => m.lobby != null && m.lobby.id == lobby.id, new TextArgs(upd.ToString(Formatting.None), "lobby"),
                req => { });
            if (PublicLobbies.Contains(lobby))
            {
                PublicLobbyUpdateQueue.Enqueue(lobby.Update("publicLobbies", fields));
            }
        }

        public static string RemoveFromTeam(Lobby lob, string steamid)
        {
            for (int i = 0; i < lob.radiant.Length; i++)
            {
                var plyr = lob.radiant[i];
                if (plyr != null && plyr.steam == steamid)
                {
                    lob.radiant[i] = null;
                    return "radiant";
                }
            }
            for (int i = 0; i < lob.dire.Length; i++)
            {
                var plyr = lob.dire[i];
                if (plyr != null && plyr.steam == steamid)
                {
                    lob.dire[i] = null;
                    return "dire";
                }
            }
            return null;
        }

        public static void CloseLobby(Lobby lob)
        {
            foreach (var browser in Browsers.Find(m => m.user != null && m.lobby != null && m.lobby.id == lob.id))
            {
                browser.lobby = null;
            }
            lock (PublicLobbies)
                PublicLobbies.Remove(lob);
            lock(PlayingLobbies)
                PlayingLobbies.Remove(lob);
            lock (LobbyQueue)
                LobbyQueue.Remove(lob);
        }

        public static void LeaveLobby(BrowserController controller)
        {
            if (controller.lobby == null || controller.user == null) return;
            var lob = controller.lobby;
            controller.lobby = null;
            if (lob.status > LobbyStatus.Queue && !lob.allowLeave) return;
            //Find the player
            var team = RemoveFromTeam(lob, controller.user.steam.steamid);
            if (((lob.TeamCount(lob.dire) == 0 && lob.TeamCount(lob.radiant) == 0) || (lob.creatorid == controller.user.Id)) && lob.status <= LobbyStatus.Queue)
            {
                CloseLobby(lob);
                return;
            }

            if (lob.LobbyType == LobbyType.Matchmaking && lob.status <= LobbyStatus.Queue)
            {
                HandleLeaveRankedLobby(controller, lob);
                return;
            }

            if (lob.status == LobbyStatus.Queue)
            {
                CancelQueue(lob);
            }

            TransmitLobbyUpdate(lob, new[] { "radiant", "dire" });
        }

        public static void HandleLeaveRankedLobby(BrowserController controller, Lobby lob)
        {
            lock (LobbyQueue)
                LobbyQueue.Remove(lob);
            lock (PlayingLobbies)
                PlayingLobbies.Remove(lob);
            Matchmake mm1 = null;
            var mm1b = new List<BrowserController>(5);
            foreach (var player in lob.radiant.Where(player => player != null))
            {
                var browser = Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault();
                if (browser == null) continue;
                if (mm1 == null) mm1 = MatchmakeManager.CreateMatchmake(browser.user, browser.QueuedWithMods, lob.region);
                else
                {
                    mm1.Users = mm1.Users.Union(new[] { browser.user }).ToList<User>();
                }
                mm1b.Add(browser);
            }
            if (mm1 != null) mm1.UpdateRating();
            foreach (var browser in mm1b)
            {
                browser.lobby = null;
                browser.matchmake = mm1;
            }
            Matchmake mm2 = null;
            var mm2b = new List<BrowserController>(5);
            foreach (var player in lob.dire.Where(player => player != null))
            {
                var browser =
                    Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault();
                if (browser == null) continue;
                if (mm2 == null) mm2 = MatchmakeManager.CreateMatchmake(browser.user, browser.QueuedWithMods, lob.region);
                else
                {
                    mm2.Users = mm2.Users.Union(new[] { browser.user }).ToList<User>();
                }
                mm2b.Add(browser);
            }
            if (mm2 != null) mm2.UpdateRating();
            foreach (var browser in mm2b)
            {
                browser.lobby = null;
                browser.matchmake = mm2;
            }
        }

        public static void ForceLeaveLobby(BrowserController controller)
        {
            if (controller.lobby == null || controller.user == null) return;
            var lob = controller.lobby;
            controller.lobby = null;
            if (lob.status > LobbyStatus.Queue && !lob.allowLeave) return;
            if (lob.LobbyType == LobbyType.PlayerTest)
            {
                RemoveFromTeam(lob, controller.user.steam.steamid);
                if (lob.TeamCount(lob.radiant) + lob.TeamCount(lob.dire) == 0)
                {
                    lock (TestLobbyQueue)
                    {
                        lock (PlayingLobbies)
                        {
                            TestLobbyQueue.Remove(lob);
                            PlayingLobbies.Remove(lob);
                            LobbyQueue.Remove(lob);
                            return;
                        }
                    }
                }
                lock (LobbyQueue)
                {
                    if (LobbyQueue.Contains(lob))
                    {
                        LobbyQueue.Remove(lob);
                        lock(TestLobbyQueue)
                            TestLobbyQueue.Add(lob);
                        lob.status = LobbyStatus.Start;
                        TransmitLobbyUpdate(lob, new []{"status"});
                        return;
                    }
                }
            }
            //Find the player
            var team = RemoveFromTeam(lob, controller.user.steam.steamid);
            if (lob.LobbyType == LobbyType.Matchmaking)
            {
                HandleLeaveRankedLobby(controller, lob);
                return;
            }

            if (lob.status < LobbyStatus.Configure)
            {
                CancelQueue(lob);
                lob.status = LobbyStatus.Start;
                if ((lob.TeamCount(lob.dire) == 0 && lob.TeamCount(lob.radiant) == 0) || lob.creatorid == controller.user.Id)
                {
                    CloseLobby(lob);
                }
            }

            if (team != null)
                TransmitLobbyUpdate(lob, new[] { team });
        }

        public static void JoinLobby(Lobby lobby, User user, BrowserController controller, string friendId = null)
        {
            if (lobby==null || user == null || lobby.status > LobbyStatus.Start) return;
            foreach (var result in Browsers.Find(m => m.user != null && m.user.Id == user.Id && m.lobby != null))
            {
                LeaveLobby(result);
            }
            var direCount = lobby.TeamCount(lobby.dire);
            var radCount = lobby.TeamCount(lobby.radiant);
            if (direCount >= 5 && radCount >= 5) return;
            if (friendId != null)
            {
                if (radCount < 5 && lobby.radiant.Any(l => l!=null && l.steam == friendId))
                {
                    lobby.AddPlayer(lobby.radiant, Player.FromUser(user, lobby.creatorid == user.Id));
                }
                else
                {
                    lobby.AddPlayer(lobby.dire, Player.FromUser(user, lobby.creatorid == user.Id));
                }
            }
            else if (direCount < radCount || direCount == radCount)
            {
                lobby.AddPlayer(lobby.dire, Player.FromUser(user, lobby.creatorid == user.Id));
            }
            else
            {
                lobby.AddPlayer(lobby.radiant, Player.FromUser(user, lobby.creatorid == user.Id));
            }
            controller.lobby = lobby;
            Browsers.AsyncSendTo(m => m.user != null && m.user.Id == user.Id, BrowserController.LobbySnapshot(lobby),
                req => { });
            TransmitLobbyUpdate(lobby, new[] { "radiant", "dire" });
            var mod = Mods.Mods.ByID(lobby.mod);
            if (mod != null)
                ClientsController.SetMod(controller.user.steam.steamid, mod);
            ClientsController.AsyncSendTo(m => m.SteamID == user.steam.steamid, ClientController.LaunchDota(), req => { });
        }

        /// <summary>
        /// Create a new lobby.
        /// </summary>
        /// <param name="user">User creating the lobby.</param>
        /// <param name="mod">Mod.</param>
        /// <param name="name">Name of the lobby.</param>
        /// <returns></returns>
        public static Lobby CreateLobby(User user, Mod mod, string name)
        {
            /*
            foreach (var result in Browsers.Find(m => m.user != null && m.user.id == user.id && m.lobby!=null))
            {
                LeaveLobby(result);
            }
            */

            //Filter lobby name to alphanumeric only
            name = Regex.Replace(name, "^[\\w \\.\"'[]\\{\\}\\(\\)]+", "");
            //Constrain lobby name length to 40 characters
            if (name.Length > 40)
            {
                name = name.Substring(0, 40);
            }

            var lob = new Lobby()
                        {
                            creator = user.profile.name,
                            creatorid = user.Id,
                            banned = new string[0],
                            dire = new Player[5],
                            IdleSince = DateTime.Now,
                            radiant = new Player[5],
                            devMode = false,
                            enableGG = !mod.disableGG,
                            hasPassword = false,
                            id = Utils.RandomString(17),
                            mod = mod.Id,
                            region = (int)ServerRegion.UNKNOWN,
                            name = name,
                            isPublic = true,
                            password = string.Empty,
                            state = GameState.Init,
							LobbyType = LobbyType.Normal,
#if DEBUG||DEV
                            requiresFullLobby = false,
#else
                            requiresFullLobby =
                                !(user.authItems != null &&
                                 (user.authItems.Contains("developer") || user.authItems.Contains("admin") ||
                                  user.authItems.Contains("moderator"))),
#endif
							serverIP = string.Empty,
                            disablePause = !mod.enablePause,
                            allowLeave = mod.allowLeave
                        };
            lob.radiant[0] = Player.FromUser(user, true);
            lock(PublicLobbies)
                PublicLobbies.Add(lob);
            lock(PlayingLobbies)
                PlayingLobbies.Add(lob);
            Browsers.AsyncSendTo(m => m.user != null && m.user.Id == user.Id, BrowserController.LobbySnapshot(lob),
                req => { });
            ClientsController.SetMod(user.steam.steamid, mod);
            ClientsController.AsyncSendTo(m => m.SteamID == user.steam.steamid, ClientController.LaunchDota(), req => { });
            log.InfoFormat("Lobby created, User: #{0}, Name: #{1}, id: {2}", user.profile.name, name, user.Id);
            return lob;
        }

        /// <summary>
        /// Start a load test
        /// </summary>
        /// <param name="user">User creating the lobby.</param>
        /// <param name="mod">Mod.</param>
        /// <param name="name">Name of the lobby.</param>
        /// <returns></returns>
        public static Lobby CreateTestLobby(User user)
        {
            foreach (var result in Browsers.Find(m => m.user != null && m.user.Id == user.Id && m.lobby != null))
            {
                LeaveLobby(result);
            }
            var mod = Mods.Mods.ByName("checker");
            var lob = new Lobby()
            {
                creator = user.profile.name,
                creatorid = user.Id,
                banned = new string[0],
                dire = new Player[5],
                IdleSince = DateTime.Now,
                radiant = new Player[5],
                devMode = false,
                enableGG = false,
                hasPassword = false,
                id = Utils.RandomString(17),
                mod = mod.Id,
                region = (int)ServerRegion.UNKNOWN,
                name = "LOADTEST "+user.Id,
                isPublic = false,
                password = string.Empty,
                state = GameState.Init,
                LobbyType = LobbyType.PlayerTest,
                requiresFullLobby = false,
                status = LobbyStatus.Start,
                serverIP = string.Empty,
                disablePause = true
            };
            lob.radiant[0] = Player.FromUser(user, true);
            lock (PlayingLobbies)
            {
                PlayingLobbies.Add(lob);
            }
            Browsers.AsyncSendTo(m => m.user != null && m.user.Id == user.Id, BrowserController.LobbySnapshot(lob),
                req => { });
            ClientsController.SetMod(user.steam.steamid, mod);
            ClientsController.AsyncSendTo(m => m.SteamID == user.steam.steamid, ClientController.LaunchDota(), req => { });
            log.InfoFormat("Load test lobby created w/ user: #{0}", user.profile.name);
            return lob;
        }

        public static Lobby StartPlayerTest(User user)
        {
            //Find a lobby that isn't full
            lock(TestLobbyQueue){
                var lobby = TestLobbyQueue.FirstOrDefault(m=>m.LobbyType==LobbyType.PlayerTest&&m.TeamCount(m.radiant)+m.TeamCount(m.dire)<10);
                if(lobby != null){
                    var direCount = lobby.TeamCount(lobby.dire);
                    var radCount = lobby.TeamCount(lobby.radiant);
                    if (direCount < radCount || direCount == radCount)
                    {
                        lobby.AddPlayer(lobby.dire, Player.FromUser(user, false));
                    }
                    else
                    {
                        lobby.AddPlayer(lobby.radiant, Player.FromUser(user, false));
                    }
                    Browsers.AsyncSendTo(m => m.user != null && m.user.Id == user.Id, BrowserController.LobbySnapshot(lobby),
                        req => { });
                    ClientsController.SetMod(user.steam.steamid, Mods.Mods.ByName("checker"));
                    ClientsController.AsyncSendTo(m => m.SteamID == user.steam.steamid, ClientController.LaunchDota(), req => { });
					if (lobby.TeamCount (lobby.dire) + lobby.TeamCount (lobby.radiant) == 10) {
						lock (LobbyQueue) {
							TestLobbyQueue.Remove (lobby);
							LobbyQueue.Add (lobby);
							lobby.status = LobbyStatus.Queue;
							TransmitLobbyUpdate (lobby, new []{ "status" });
							log.Debug ("Test lobby " + lobby.id + " full, starting queue...");
						}
					}
                    return lobby;
                }else{
                    lobby = CreateTestLobby(user);
                    TestLobbyQueue.Add(lobby);
                    return lobby;
                }
            }
        }

        /// <summary>
        /// Create a new ranked lobby, and put directly in queue.
        /// </summary>
        /// <param name="team1">Dire team.</param>
        /// <param name="team2">Radiant team.</param>
        /// <param name="mod">Mod.</param>
        /// <param name="region">Region.</param>
        /// <returns></returns>
        public static Lobby CreateMatchedLobby(Matchmake team1, Matchmake team2, string mod, ServerRegion region)
        {
            var setMod = Mods.Mods.ByName(mod);
            var lob = new Lobby()
            {
                dire = new Player[5],
                radiant = new Player[5],
                devMode = false,
                enableGG = !setMod.disableGG,
                hasPassword = false,
                id = team1.id,
                mod = setMod.Id,
                region = region,
                name = "Ranked "+setMod.fullname+" Game",
                isPublic = false,
                password = "",
                state = GameState.Init,
                requiresFullLobby = true,
                serverIP = "",
                status = LobbyStatus.Queue,
                LobbyType = LobbyType.Matchmaking,
                disablePause = !setMod.enablePause
            };
            foreach (var user in team1.Users.ToArray())
            {
                lob.AddPlayer(lob.dire, Player.FromUser(user, false));
            }
            foreach (var user in team2.Users.ToArray())
            {
                lob.AddPlayer(lob.radiant, Player.FromUser(user, false));
            }
            PlayingLobbies.Add(lob);

            var allUsers = team1.Users.ToArray().Concat(team2.Users.ToArray());
            foreach (var user in allUsers)
            {
                Browsers.AsyncSendTo(m => m.user != null && m.user.Id == user.Id, BrowserController.LobbySnapshot(lob), req => { });
                ClientsController.SetMod(user.steam.steamid, setMod);
            }
            SendLaunchDota(lob);
            LobbyQueue.Add(lob);
            return lob;
        }

        public static void ChatMessage(Lobby lobby, string msg, string name)
        {
            string cmsg = name + ": " + msg;
            if (msg.Length == 0) return;
            if (msg.Length > 140) msg = msg.Substring(0, 140);
            Browsers.AsyncSendTo(m => m.lobby != null && m.lobby.id == lobby.id, BrowserController.ChatMessage(cmsg), req => { });
        }

        public static bool BanFromLobby(Lobby lobby, string steam)
        {
            var client =
                Browsers.Find(m => m.user != null && m.user.steam.steamid == steam && m.lobby != null && m.lobby.id == lobby.id);
            var browserClients = client as BrowserController[] ?? client.ToArray();
            if (!browserClients.Any()) return true;
            if (browserClients.First().user.authItems.Contains("admin"))
            {
                return false;
            }
            if (!lobby.banned.Contains(steam))
            {
                var arr = lobby.banned;
                Array.Resize(ref arr, lobby.banned.Length + 1);
                arr[arr.Length - 1] = steam;
                lobby.banned = arr;
                TransmitLobbyUpdate(lobby, new[] { "banned" });
            }
            LeaveLobby(browserClients.First());
            return true;
        }

        public static void SetTitle(Lobby lobby, string name)
        {
            lobby.name = name;
            TransmitLobbyUpdate(lobby, new[] { "name" });
        }

        public static void SetRegion(Lobby lobby, ServerRegion region)
        {
            lobby.region = region;
            TransmitLobbyUpdate(lobby, new[] { "region" });
        }

        public static void OnServerShutdown(GameInstance instance)
        {
            log.Info("Server shutdown: " + instance.lobby.id);
            if (!LobbyID.Values.Contains(instance.lobby) || instance.lobby.status == LobbyStatus.Start) return;
            if (instance.lobby.LobbyType == LobbyType.PlayerTest)
            {
                log.Error("No match result info for test lobby, setting all to success.");
                foreach (var browser in instance.lobby.radiant.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    BrowserController.SetTested(browser.user, true);
                }
                foreach (var browser in instance.lobby.dire.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    BrowserController.SetTested(browser.user, true);
                }
            }else if (instance.lobby.LobbyType == LobbyType.Normal)
            {
                log.Error("No match result info for regular lobby, returning to wait.");
                ReturnToWait(instance.lobby);
            }else if (instance.lobby.LobbyType == LobbyType.Matchmaking)
            {
                foreach (var browser in instance.lobby.radiant.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    browser.RespondError(null, "The server did not report the match result before closing, you will not receive/lose mmr for that game. Sorry for the inconvenience. We have recorded this failure and will examine it throughly.");
                }
                foreach (var browser in instance.lobby.dire.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    browser.RespondError(null, "The server did not report the match result before closing, you will not receive/lose mmr for that game. Sorry for the inconvenience. We have recorded this failure and will examine it throughly.");
                }
                Mongo.ResultFailures.Insert(new ResultFailure()
                {
                    creator = instance.lobby.creator,
                    creatorid = instance.lobby.creatorid,
                    enableGG = instance.lobby.enableGG,
                    hasPassword = instance.lobby.hasPassword,
                    isPublic = instance.lobby.isPublic,
                    mod = instance.lobby.mod,
                    name = instance.lobby.name,
                    password = instance.lobby.password,
                    region = (int) instance.lobby.region,
                });
                CloseLobby(instance.lobby);
            }
            else
                CloseLobby(instance.lobby);
        }

        public static void OnServerShutdownNoInstance(Lobby lobby)
        {
            log.Error("Server shutdown (NO INSTANCE): " + lobby.id);
            if (!LobbyID.Values.Contains(lobby) || lobby.status == LobbyStatus.Start) return;
            if (lobby.LobbyType == LobbyType.PlayerTest)
            {
                log.Error("No match result info for test lobby, setting all to success.");
                foreach (var browser in lobby.radiant.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    BrowserController.SetTested(browser.user, true);
                }
                foreach (var browser in lobby.dire.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    BrowserController.SetTested(browser.user, true);
                }
            }
            CloseLobby(lobby);
        }

        public static void OnServerReady(GameInstance instance)
        {
            if (!PlayingLobbies.Contains(instance.lobby)) return;
            var lobby = instance.lobby;
            lobby.serverIP = instance.Server.Address.Split(':')[0] + ":" + instance.port;
            lobby.status = LobbyStatus.Play;
            TransmitLobbyUpdate(lobby, new []{"status"});
            foreach (var player in lobby.radiant)
            {
                if (player == null) continue;
                player.failedConnect = false;
            }
            foreach (var player in lobby.dire)
            {
                if (player == null) continue;
                player.failedConnect = false;
            }
            SendLaunchDota(lobby);
            SendConnectDota(lobby);
            log.Info("Server ready " + instance.lobby.id + " " + instance.lobby.serverIP);
        }

        public static void ReturnToWait(Lobby lobby)
        {
            if (lobby == null || !LobbyID.Values.Contains(lobby)) return;
            lobby.serverIP = "";
            lobby.status = LobbyStatus.Start;
            lobby.IdleSince = DateTime.Now;
            //Check that all members are still connected
            var radiant = new List<Player>(5);
            var dire = new List<Player>(5);
            radiant.AddRange(from plyr in lobby.radiant
                where plyr != null
                let hasBrowser = Browsers.Find(m => m.user != null && m.lobby != null && m.user.steam.steamid == plyr.steam && m.lobby.id == lobby.id).Any()
                where hasBrowser
                select plyr);
            dire.AddRange(from plyr in lobby.dire
                where plyr != null
                let hasBrowser = Browsers.Find(m => m.user != null && m.lobby != null && m.user.steam.steamid == plyr.steam && m.lobby.id == lobby.id).Any()
                where hasBrowser
                select plyr);
            Player[] radiantt = new Player[5];
            Player[] diret = new Player[5];
            var i = 0;
            foreach (var player in radiant)
            {
                radiantt[i] = player;
                i++;
            }
            i = 0;
            foreach (var player in dire)
            {
                diret[i] = player;
                i++;
            }
            lobby.radiant = radiantt;
            lobby.dire = diret;
            if (FindPlayerLocationU(lobby.creatorid, lobby) == null)
            {
                CloseLobby(lobby);
            }
            else
            {
                TransmitLobbyUpdate(lobby, new[] { "status", "radiant", "dire" });
                lock (PublicLobbies)
                    if (lobby.isPublic) PublicLobbies.Add(lobby);
            }
        }

        private static void SendLaunchDota(Lobby lobby)
        {
            foreach (var plyr in lobby.radiant.Where(plyr => plyr != null))
            {
                ClientsController.AsyncSendTo(c => c.SteamID != null && c.SteamID == plyr.steam, ClientController.LaunchDota(),
                    req => { });
            }
            foreach (var plyr in lobby.dire.Where(plyr => plyr != null))
            {
                ClientsController.AsyncSendTo(c => c.SteamID != null && c.SteamID == plyr.steam, ClientController.LaunchDota(),
                    req => { });
            }
        }

        private static void SendConnectDota(Lobby lobby)
        {
            foreach (var plyr in lobby.radiant.Where(plyr => plyr != null))
            {
                ClientsController.ConnectDota(plyr.steam, lobby.serverIP);
            }
            foreach (var plyr in lobby.dire.Where(plyr => plyr != null))
            {
                ClientsController.ConnectDota(plyr.steam, lobby.serverIP);
            }
        }

        public static void LaunchAndConnect(Lobby lobby, string steamid)
        {
            ClientsController.AsyncSendTo(m => m.SteamID == steamid, ClientController.LaunchDota(), req => { });
            ClientsController.ConnectDota(steamid, lobby.serverIP);
        }

        public static void OnMatchComplete(Model.MatchData toObject)
        {
            Lobby lob;
            if (!LobbyID.TryGetValue(toObject.match_id, out lob)) return;
            log.Debug("Match completed, " + lob.id);

            if (lob.LobbyType == LobbyType.Matchmaking)
            {
                MatchmakeManager.CalculateAfterMatch(toObject);
            }

            if (lob.LobbyType != LobbyType.PlayerTest)
            {
                CloseLobby(lob);

                try
                {
                    Mongo.Results.Insert(toObject);
                }
                catch (Exception ex)
                {
                    log.Error("Failed to store match result " + lob.id, ex);
                }
            }
            else
            {
                foreach (var browser in lob.radiant.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    BrowserController.SetTested(browser.user, true);
                }
                foreach (var browser in lob.dire.Where(player => player != null).Select(player => Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault()).Where(browser => browser != null))
                {
                    BrowserController.SetTested(browser.user, true);
                }
                CloseLobby(lob);
            }
        }

        public static void OnLoadFail(string matchid, JArray failedPlayers)
        {
            Lobby lob;
            if (!LobbyID.TryGetValue(matchid, out lob)) return;
            if (lob.status != LobbyStatus.Play) return;
            var failed = new List<string>(10);
            failed.AddRange(failedPlayers.Select(player => player.Value<int>().ToSteamID64()));
            foreach(var player in lob.radiant){
                if(player == null) continue;
                player.failedConnect = failed.Contains(player.steam);
            }
            foreach(var player in lob.dire){
                if(player == null) continue;
                player.failedConnect = failed.Contains(player.steam);
            }
            if(lob.LobbyType == LobbyType.Normal)
            {
                log.Debug(matchid + " failed to load, returning to waiting stage.");
                foreach (var steam in failed)
                {
                    var browser = Browsers.Find(m => m.user != null && m.user.steam.steamid == steam).FirstOrDefault();
                    if (browser != null)
                    {
                        BrowserController.SetTested(browser.user, false);
                        log.Debug(matchid + " -> marked " + steam + " as FAIL");
                    }
                }
                ReturnToWait(lob);
            }
            else if (lob.LobbyType == LobbyType.PlayerTest)
            {
                foreach (var player in lob.getPlayers())
                {
                    if (player == null) continue;
                    var browser = Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault();
                    if (browser != null)
                    {
                        BrowserController.SetTested(browser.user, !player.failedConnect);
                    }
                }
                CloseLobby(lob);
            }
            else if (lob.LobbyType == LobbyType.Matchmaking)
            {
                var didntFail = new List<BrowserController>(10);
                var failedParties = new List<Party.Party>(4); // Parties that contains one or more players who didn't load.
                var matchedPartyIds = new List<string>(4);
                foreach (var player in lob.getPlayers())
                {
                    var browser = Browsers.Find(m => m.user != null && m.user.steam.steamid == player.steam).FirstOrDefault();
                    if (browser == null) continue;
                    if (player.failedConnect)
                    {
                        BrowserController.SetTested(browser.user, false);
                        browser.user.profile.PreventMMUntil = DateTime.UtcNow + TimeSpan.FromMinutes(5);
                        browser.SaveUser();
                        if (browser.party != null) failedParties.Add(browser.party);
                    }
                    else
                        didntFail.Add(browser);
                    browser.lobby = null;
                    browser.matchmake = null;
                }
                CloseLobby(lob);
                foreach (var browser in didntFail)
                {
                    if (browser == null) continue;

                    if (browser.party != null)
                    {
                        if (!failedParties.Contains(browser.party) && !matchedPartyIds.Contains(browser.party.id))
                        {
                            var partyBrowsers = Browsers.Find(x => x.party != null && x.user != null && x.party.id == browser.party.id);
                            var users = partyBrowsers.Select(x => x.user).ToArray();
                            var matchmake = MatchmakeManager.CreateMatchmake(users, browser.QueuedWithMods);
                            foreach (var partymemberBrowser in didntFail.Where(x=>x.party == browser.party))
                            {
                                partymemberBrowser.matchmake = matchmake;
                            }
                            matchedPartyIds.Add(browser.party.id);
                        }
                    }
                    else
                    {
                        //Requeue
                        browser.matchmake = MatchmakeManager.CreateMatchmake(browser.user, browser.QueuedWithMods);
                    }
                }
            }
        }

        public static void HandleEvent(GameEvents eventType, JToken data, Lobby lob)
        {
            switch (eventType)
            {
                case GameEvents.GameStateChange:
                    {
                        var gameState = (GameState)data.Value<int>("new_state");
                        log.Debug(lob.id + " -> entered state " + Enum.GetName(typeof(GameState), gameState));
                        lob.state = gameState;
                        TransmitLobbyUpdate(lob, new[] { "state" });
                        break;
                    }
                case GameEvents.PlayerConnect:
                    {
                        var plyr = FindPlayerLocation(new User(){steam =new SteamService(){steamid = data.Value<int>("player").ToSteamID64()}}, lob);
                        log.Debug(lob.id + " -> player connected: " + plyr.player.name);
                        if (lob.LobbyType == LobbyType.Normal && lob.state < GameState.PostGame && lob.state > GameState.WaitLoad)
                        {
                            var browser =
                                Browsers.Find(m => m.user != null && m.user.steam.steamid == plyr.player.steam)
                                    .FirstOrDefault();
                            if (browser != null)
                            {
                                BrowserController.SetTested(browser.user, true);
                            }
                            else
                            {
                                var user = Mongo.Users.FindOneAs<User>(Query.EQ("steam.steamid", plyr.player.steam));
                                if(user != null)
                                    BrowserController.SetTested(user, true);
                            }
                        }
                        break;
                    }
                case GameEvents.PlayerDisconnect:
                {
                    var plyr = FindPlayerLocation(new User() { steam = new SteamService() { steamid = data.Value<int>("player").ToSteamID64() } }, lob);
                    if (plyr != null)
                    {
                        log.Debug(lob.id + " -> player disconnected: " + plyr.player.name);
                        if (lob.LobbyType == LobbyType.Normal && lob.state < GameState.PostGame && lob.state > GameState.WaitLoad && !lob.allowLeave)
                        {
                            var browser = Browsers.Find(m => m.user != null && m.user.steam.steamid == plyr.player.steam).FirstOrDefault();
                            if (browser != null)
                            {
                                BrowserController.SetTested(browser.user, false);
                            }
                            else
                            {
                                var user = Mongo.Users.FindOneAs<User>(Query.EQ("steam.steamid", plyr.player.steam));
                                if (user != null)
                                    BrowserController.SetTested(user, false);
                            }
                        }
                    }
                    break;
                }
            }
        }

        public static void ClearPendingLobbies()
        {
            log.Info("Clearing idle lobbies!");
            try
            {
                var lobbies = LobbyID.Values.Where(m => m.status == LobbyStatus.Start);
                foreach (var lobby in lobbies)
                {
                    CloseLobby(lobby);
                }
                log.Info("Cleared " + lobbies.Count() + " lobbies.");
            }
            catch (Exception ex)
            {
                log.Error("Failed to clear idle lobbies!", ex);
            }
        }

        public static void CloseAll(Mod mod)
        {
            lock (PublicLobbies)
            {
                lock (PlayingLobbies)
                {
                    var lobbies = LobbyID.Values.Where(m => m.mod == mod.Id);
                    foreach (var lobby in lobbies)
                    {
                        log.InfoFormat("Closing lobby [{0}] for mod update.", lobby.id);
                        CloseLobby(lobby);
                    }
                }
            }
        }
    }
}


text:
package lithium.community.android.sdk.auth;

/**
 * Created by Lithium Technologies Inc on 7/10/17.
 * This is the interface that the app developer should implement for getting the device ID via either Firebase or GCM
 * for e.g. via Firebase it is like this: FirebaseInstanceId.getInstance().getToken()
 */
public interface LiDeviceTokenProvider {
    String getDeviceId();
}


text:
/*******************************************************************************
  OSC Peripheral Library Template Implementation

  File Name:
    osc_PBClockDivisor_PIC32_1.h

  Summary:
    OSC PLIB Template Implementation

  Description:
    This header file contains template implementations
    For Feature : PBClockDivisor
    and its Variant : PIC32_1
    For following APIs :
        PLIB_OSC_ExistsPBClockDivisor
        PLIB_OSC_PBClockDivisorGet
        PLIB_OSC_PBClockDivisorSet

*******************************************************************************/

//DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2013 released Microchip Technology Inc.  All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/

//DOM-IGNORE-END

#ifndef _OSC_PBCLOCKDIVISOR_PIC32_1_H
#define _OSC_PBCLOCKDIVISOR_PIC32_1_H

// *****************************************************************************
/* Oscillator Peripheral Bus Clock Divisor Value Type

  Summary:
    Type of the oscillator PB Clock divisor value.

  Description:
    This macro defines the type of the oscillator PB Clock divisor value.

  Remarks:
    None
*/

#define OSC_PB_CLOCK_DIV_TYPE						SFR_TYPE

// *****************************************************************************
/* Oscillator Peripheral Bus count

  Summary:
    The number of Peripheral buses in available in the device.

  Description:
    This macro gives the number of Peripheral buses in available in the device.

  Remarks:
    None
*/

#define PERIPHERAL_BUSES_MAX						1

//******************************************************************************
/* Function :  OSC_ExistsPBClockDivisor_PIC32_1

  Summary:
    Implements PIC32_1 variant of PLIB_OSC_ExistsPBClockDivisor

  Description:
    This template implements the PIC32_1 variant of the PLIB_OSC_ExistsPBClockDivisor function.
*/

#define PLIB_OSC_ExistsPBClockDivisor PLIB_OSC_ExistsPBClockDivisor
PLIB_TEMPLATE bool OSC_ExistsPBClockDivisor_PIC32_1( OSC_MODULE_ID index )
{
    return true;
}

//******************************************************************************
/* Function :  OSC_PBClockDivisorGet_PIC32_1

  Summary:
    Implements PIC32_1 variant of PLIB_OSC_PBClockDivisorGet

  Description:
    This template implements the PIC32_1 variant of the PLIB_OSC_PBClockDivisorGet function.
*/

PLIB_TEMPLATE OSC_PB_CLOCK_DIV_TYPE OSC_PBClockDivisorGet_PIC32_1( OSC_MODULE_ID index , OSC_PERIPHERAL_BUS peripheralBusNumber )
{
    return (OSC_PB_CLOCK_DIV_TYPE)(0x01u << OSCCONbits.PBDIV);
}

//******************************************************************************
/* Function :  OSC_PBClockDivisorSet_PIC32_1

  Summary:
    Implements PIC32_1 variant of PLIB_OSC_PBClockDivisorSet

  Description:
    This template implements the PIC32_1 variant of the PLIB_OSC_PBClockDivisorSet function.
*/

PLIB_TEMPLATE void OSC_PBClockDivisorSet_PIC32_1( OSC_MODULE_ID index , OSC_PERIPHERAL_BUS peripheralBusNumber , OSC_PB_CLOCK_DIV_TYPE peripheralBusClkDiv )
{
    uint8_t regValue;

    for (regValue = 0u; regValue < 4u; regValue++)
    {
        if ( peripheralBusClkDiv == ( 0x01u << regValue ) )
        {
            OSCCONbits.PBDIV = regValue;
            return;
        }
    }
    PLIB_ASSERT(false, "Given PB Divisor value is not supported for the selected device");
}

#endif /*_OSC_PBCLOCKDIVISOR_PIC32_1_H*/

/******************************************************************************
 End of File
*/


text:
namespace switches {

const char kDisableBrowserTaskScheduler[] = "disable-browser-task-scheduler";
const char kEnableBrowserTaskScheduler[] = "enable-browser-task-scheduler";

}  // namespace switches


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MovieDetailsComponent } from './movie-details/movie-details.component';
import { MoviesComponent } from './movies/movies.component';
import { SingleMovieResolver } from './service/resolvers/single-movie.resolver';
import { MovieSerachComponent } from './movie-serach/movie-serach.component';

const routes: Routes = [{
  path: '',
  pathMatch: 'full',
  redirectTo: 'movies'
}, {
  path: 'movies/search',
  component: MovieSerachComponent
}, {
  path: 'movies',
  component: MoviesComponent
}, {
  path: 'movies/:id',
  component: MovieDetailsComponent,
  resolve: { singleMovie: SingleMovieResolver }
}];

@NgModule({
  declarations: [],
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


text:
<component name="ArtifactManager">
  <artifact type="jar" name="ScorpUtils:jar0.5.0">
    <output-path>$PROJECT_DIR$/out/artifacts/ScorpUtils_jar0_5_0</output-path>
    <root id="archive" name="ScorpUtils-0.5.0.jar">
      <element id="module-output" name="ScorpUtils" />
      <element id="dir-copy" path="$PROJECT_DIR$/src" />
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/META-INF/MANIFEST.MF" />
      </element>
    </root>
  </artifact>
</component>


text:
'use strict';

/* Services */
var services = angular.module('passeiDiretoApp.services', ['ngResource']);

services.factory('Album', ['$resource',
  function($resource) {
    return $resource('api/albums/:albumId', {albumId:'@id'}, {
      query: {method:'GET', isArray:true},
      update: {method: "PUT"},
      delete: { method: 'DELETE'}
    });
}]);


text:
/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2016, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
package it.geosolutions.jaiext.classbreaks;

import javax.media.jai.ROI;
import java.awt.image.RenderedImage;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;

/**
 * Classification op for the natural breaks method.
 */
public class NaturalBreaksOpImage extends ClassBreaksOpImage {

    public NaturalBreaksOpImage(
            RenderedImage image,
            Integer numClasses,
            Double[][] extrema,
            ROI roi,
            Integer[] bands,
            Integer xStart,
            Integer yStart,
            Integer xPeriod,
            Integer yPeriod,
            Double noData,
            Boolean percentages) {
        super(image, numClasses, extrema, roi, bands, xStart, yStart, xPeriod, yPeriod, noData, percentages);
    }

    @Override
    protected Classification createClassification() {
        return new NaturalClassification(bands.length);
    }

    @Override
    protected void handleValue(double d, Classification c, int band) {
        if (extrema != null) {
            double min = extrema[0][band];
            double max = extrema[1][band];

            if (d < min || d > max) {
                return;
            }
        }
        ((NaturalClassification) c).count(d, band);
    }

    @Override
    protected void postCalculate(Classification c, int band) {
        NaturalClassification nc = (NaturalClassification) c;

        List<Double> data = nc.getValues(band);
        Collections.sort(data);

        final int k = numClasses;
        final int m = data.size();

        if (k >= m) {
            Double[] breaks = data.toArray(new Double[data.size()]);
            // just return all the values
            c.setBreaks(band, breaks);
            setPercentages(data, breaks, m, k, c);
            return;
        }

        int[][] iwork = new int[m + 1][k + 1];
        double[][] work = new double[m + 1][k + 1];

        for (int j = 1; j <= k; j++) {
            // the first item is always in the first class!
            iwork[0][j] = 1;
            iwork[1][j] = 1;
            // initialize work matirix
            work[1][j] = 0;
            for (int i = 2; i <= m; i++) {
                work[i][j] = Double.MAX_VALUE;
            }
        }

        // calculate the class for each data item
        for (int i = 1; i <= m; i++) {
            // sum of data values
            double s1 = 0;
            // sum of squares of data values
            double s2 = 0;

            double var = 0.0;
            // consider all the previous values
            for (int ii = 1; ii <= i; ii++) {
                // index in to sorted data array
                int i3 = i - ii + 1;
                // remember to allow for 0 index
                double val = data.get(i3 - 1);
                // update running totals
                s2 = s2 + (val * val);
                s1 += val;
                double s0 = (double) ii;
                // calculate (square of) the variance
                // (http://secure.wikimedia.org/wikipedia/en/wiki/Standard_deviation#Rapid_calculation_methods)
                var = s2 - ((s1 * s1) / s0);
                // System.out.println(s0+" "+s1+" "+s2);
                // System.out.println(i+","+ii+" var "+var);
                int ik = i3 - 1;
                if (ik != 0) {
                    // not the last value
                    for (int j = 2; j <= k; j++) {
                        // for each class compare current value to var + previous value
                        // System.out.println("\tis "+work[i][j]+" >= "+(var + work[ik][j - 1]));
                        if (work[i][j] >= (var + work[ik][j - 1])) {
                            // if it is greater or equal update classification
                            iwork[i][j] = i3 - 1;
                            // System.out.println("\t\tiwork["+i+"]["+j+"] = "+i3);
                            work[i][j] = var + work[ik][j - 1];
                        }
                    }
                }
            }
            // store the latest variance!
            iwork[i][1] = 1;
            work[i][1] = var;
        }

        TreeSet<Double> breaks = new TreeSet<>();

        // go through matrix and extract class breaks
        int ik = m - 1;
        breaks.add(data.get(ik));
        for (int j = k; j >= 2; j--) {
            int id = (int) iwork[ik][j] - 1; // subtract one as we want inclusive breaks on the
            // left?
            breaks.add(data.get(id));
            ik = (int) iwork[ik][j] - 1;
        }
        breaks.add(data.get(0));
        Double[] arrBreaks = breaks.toArray(new Double[breaks.size()]);
        nc.setBreaks(band, arrBreaks);
        setPercentages(data, arrBreaks, m, k, nc);
    }

    private void setPercentages(List<Double> data, Double[] breaks, int m, int k, Classification nc) {
        if (percentages.booleanValue()) {
            ClassPercentagesManager percentagesManager = new ClassPercentagesManager();
            int actualClassNumber = k > breaks.length ? breaks.length - 1 : k;
            double[] percentages = percentagesManager.getPercentages(data, breaks, m, actualClassNumber);
            nc.setPercentages(percentages);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (c) 1997, 2019 Oracle and/or its affiliates. All rights reserved.

    This program and the accompanying materials are made available under the
    terms of the Eclipse Distribution License v. 1.0, which is available at
    http://www.eclipse.org/org/documents/edl-v10.php.

    SPDX-License-Identifier: BSD-3-Clause

-->

<descriptor since="2.0" >
  <description>stax parser</description>

</descriptor>


text:
module 'mock_edit'

-- CLASS: ProtoManager ()

-- function ProtoManager:__init()
-- 	connectGlobalSignalFunc( 'scene.post_deserialize', self, 'postSceneDeserialize' )
-- 	connectGlobalSignalFunc( 'scene.post_serialize',   self, 'postSceneSerialize' )

-- end

-- function ProtoManager:extractProtoData( info, scnData )

-- end

-- function ProtoManager:postSceneDeserialize( scn, scnData, objMap )
-- 	local instanceOverrideTable = {}
-- 	scn.__instanceOverrided = instanceOverrideTable

-- end

-- function ProtoManager:preSceneSerialize( scn, scnData )
-- 	--extract proto scnData and
-- 	self:extractAllProtoData( scnData )
-- end

-- local _protoManager = ProtoManager()
-- function ProtoManager.get()
-- 	return _protoManager
-- end


text:
struct fooalign {char x; double d;};
union fooround {long x; double d;};

int
foo ()
{
  int extra = 4;
  if (extra < sizeof (union fooround))
    extra = sizeof (union fooround);
  return extra;
}


text:
define([
    'underscore',
    'contrail-model',
], function (_, ContrailModel) {

    var alarmsModel = ContrailModel.extend({
        ackAlarms: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            var alarmsList = [];

            $.each(checkedRows, function (checkedRowsKey, checkedRowsValue) {
                alarmsList.push({"table":checkedRowsValue.table,
                    "name":checkedRowsValue.name,
                    "type":checkedRowsValue.type,
                    "token":checkedRowsValue.token});
            });

            ajaxConfig.type = "POST";
            ajaxConfig.data = JSON.stringify(alarmsList);

            ajaxConfig.url = '/api/tenant/monitoring/ackalarms';
            contrail.ajaxHandler(ajaxConfig, function () {
                if (contrail.checkIfFunction(callbackObj.init)) {
                    callbackObj.init();
                }
            }, function (response) {
                if (contrail.checkIfFunction(callbackObj.success)) {
                    callbackObj.success();
                }
            }, function (error) {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(error);
                }
            });
        },
    });

    return alarmsModel;
});


text:
/**
 * Date utility extention, adding format. (based on PHP's date function)
 * @see http://php.net/manual/en/function.date.php
 * @author Rob Taylor [manix84@gmail.com]
 *
 * @exports date
 *
 * @requires date/beatTime
 * @requires date/daylightSavings
 * @requires date/dayName
 * @requires date/dayOrdinal
 * @requires date/gmtOffset
 * @requires date/meridiem
 * @requires date/monthName
 * @requires date/twelveHourTime
 * @requires date/yearShort
 * @requires date/convert/toDate
 * @requires date/convert/toIso8601
 * @requires date/convert/toRFC2822
 * @requires date/convert/toTimestamp
 */
define('date', [
    'date/beatTime',
    'date/daylightSavings',
    'date/dayName',
    'date/dayOrdinal',
    'date/gmtOffset',
    'date/meridiem',
    'date/monthName',
    'date/twelveHourTime',
    'date/yearShort',
    'date/convert/toDate',
    'date/convert/toIso8601',
    'date/convert/toRFC2822',
    'date/convert/toTimestamp'
], function (
    beatTime,
    daylightSavings,
    dayName,
    dayOrdinal,
    gmtOffset,
    meridiem,
    monthName,
    twelveHourTime,
    yearShort,
    convertToDate,
    convertToIso8601,
    convertToRFC2822,
    convertToTimestamp
) {
    /**
     * Is an attempt to duplicate the PHP Date function.  Some characters have been omitted.
     * @see http://php.net/manual/en/function.date.php
     * @param {dateFormatMask|string} mask The format of the outputted date string. (EG: 'D, d M Y H:i:s' would produce 'Mon, 31 Oct 2001 15:05:02')
     * @param {date object} [dateValue] Date class.  If not set, it assumes you mean 'now'.
     * @example format('D, d M Y H:i:s'); // RETURNS: 'Mon, 31 Oct 2001 15:05:02'
     * @returns {string} Formatted date, using "mask" (EG: 'Mon, 31 Oct 2001 15:05:02')
     */
    var pad = function (input) {
        input = String(input);

        while (input.length < 2) {
            input = "0" + input;
        }
        return input;
    },
    date = function (mask, dateValue) {
        var maskArray = '',
            no_support = function (character) {
                if (!!window.console && 'warn' in window.console) {
                    window.console.warn('Date.Format: "' + character + '", is currently not a supported format.');
                }
            },
            o = '',
            i = 0;

        dateValue = convertToDate(dateValue);

        maskArray = mask.split('');

        for (i in maskArray) {
            if (maskArray.hasOwnProperty(i)) {
                switch (maskArray[i]) {

                // ------- DAY -------

                /*
                 * Character: "d"
                 * Description: Day of the month, 2 digits with leading zeros
                 * Example: 01 to 31
                 */
                case 'd':
                    o += pad(dateValue.getDate());
                    break;

                /*
                 * Character: "D"
                 * Description: A textual representation of a day, three letters
                 * Example: Mon through Sun
                 */
                case 'D':
                    o += dayName(dateValue, true);
                    break;

                /*
                 * Character: "j"
                 * Description: Day of the month without leading zeros
                 * Example: 1 to 31
                 */
                case 'j':
                    o += dateValue.getDate();
                    break;

                /*
                 * Character: "l" (lowercase 'L')
                 * Description: A full textual representation of the day of the week
                 * Example: Sunday through Saturday
                 */
                case 'l':
                    o += dayName(dateValue);
                    break;

                /*
                 * Character: "N"
                 * Description: ISO-8601 numeric representation of the day of the week
                 * Example: 1 (for Monday) through 7 (for Sunday)
                 */
                case 'N':
                    o += dateValue.getDay() + 1;
                    break;

                /*
                 * Character: "S"
                 * Description: English ordinal suffix for the day of the month, 2 characters
                 * Example: st, nd, rd or th. Works well with "j"
                 */
                case 'S':
                    o += dayOrdinal(dateValue);
                    break;

                /*
                 * Character: "w"
                 * Description: Numeric representation of the day of the week
                 * Example: 0 (for Sunday) through 6 (for Saturday)
                 */
                case 'w':
                    o += dateValue.getDay();
                    break;

                /*
                 * Character: "z"
                 * Description: The day of the year (starting from 0)
                 * Example: 0 through 365
                 */
                case 'z':
                    o += Math.floor((dateValue - new Date(dateValue.getFullYear(), 0, 1)) / 86400000);
                    break;

                // ------- WEEK -------

                /*
                 * Character: "W"
                 * Description: Week number of year
                 * Example: 42 (the 42nd week in the year)
                 */
                case 'W':
                    o += Math.floor((dateValue - new Date(dateValue.getFullYear(), 0, 1)) / 604800000);
                    break;

                // ------- MONTH -------

                /*
                 * Character: "F"
                 * Description: A full textual representation of a month, such as January or March
                 * Example: January through December
                 */
                case 'F':
                    o += monthName(dateValue);
                    break;

                /*
                 * Character: "m"
                 * Description: Numeric representation of a month, with leading zeros
                 * Example: 01 through 12
                 */
                case 'm':
                    o += pad(dateValue.getMonth() + 1);
                    break;

                /*
                 * Character: "M"
                 * Description: A short textual representation of a month, three letters
                 * Example: Jan through Dec
                 */
                case 'M':
                    o += monthName(dateValue);
                    break;

                /*
                 * Character: "n"
                 * Description: Numeric representation of a month, without leading zeros
                 * Example: 1 through 12
                 */
                case 'n':
                    o += pad(dateValue.getMonth() + 1);
                    break;

                /*
                 * Character: "t"
                 * Description: Number of days in the given month
                 * Example: 28 through 31
                 * TODO: Add Number of days in the given month to format
                 */
                case 't':
                    no_support('t', 'Number of days in the given month');
                    break;

                // ------- YEAR -------

                /*
                 * Character: "L"
                 * Description: Whether it's a leap year
                 * Example: 1 if it is a leap year, 0 otherwise.
                 */
                case 'L':
                    o += (dateValue.getFullYear() % 4 === 0) ? 1 : 0;
                    break;

                /*
                 * Character: "Y" / "o"
                 * Description: A full numeric representation of a year, 4 digits
                 * Example: 1999 or 2003
                 */
                case 'Y':
                case 'o':
                    o += dateValue.getFullYear();
                    break;

                /*
                 * Character: "y"
                 * Description: A two digit representation of a year
                 * Example: 99 or 03
                 */
                case 'y':
                    o += yearShort(dateValue);
                    break;

                // ------- TIME -------

                /*
                 * Character: "a"
                 * Description: Lowercase Ante meridiem and Post meridiem
                 * Example: am or pm
                 */
                case 'a':
                    o += meridiem(dateValue);
                    break;

                /*
                 * Character: "A"
                 * Description: Uppercase Ante meridiem and Post meridiem
                 * Example: AM or PM
                 */
                case 'A':
                    o += meridiem(dateValue, true);
                    break;

                /*
                 * Character: "B"
                 * Description: Swatch Internet time
                 * Example: 000 through 999
                 */
                case 'B':
                    o += Math.floor(beatTime(dateValue));
                    break;

                /*
                 * Character: "g"
                 * Description: 12-hour format of an hour without leading zeros
                 * Example: 1 through 12
                 */
                case 'g':
                    o += twelveHourTime(dateValue);
                    break;

                /*
                 * Character: "G"
                 * Description: 24-hour format of an hour without leading zeros
                 * Example: 0 through 23
                 */
                case 'G':
                    o += dateValue.getHours();
                    break;

                /*
                 * Character: "h"
                 * Description: 12-hour format of an hour with leading zeros
                 * Example: 01 through 12
                 */
                case 'h':
                    o += pad(twelveHourTime(dateValue));
                    break;

                /*
                 * Character: "H"
                 * Description: 24-hour format of an hour with leading zeros
                 * Example: 00 through 23
                 */
                case 'H':
                    o += pad(dateValue.getHours());
                    break;

                /*
                 * Character: "i"
                 * Description: Minutes with leading zeros
                 * Example: 00 to 59
                 */
                case 'i':
                    o += pad(dateValue.getMinutes());
                    break;

                /*
                 * Character: "s"
                 * Description: Seconds, with leading zeros
                 * Example: 00 through 59
                 */
                case 's':
                    o += pad(dateValue.getSeconds());
                    break;

                /*
                 * Character: "u"
                 * Description: Microseconds
                 * Example: 321
                 */
                case 'u':
                    o += pad(dateValue.getMilliseconds(), 3);
                    break;

                /*
                 * Character: "e"
                 * Description: Timezone identifier
                 * Example: UTC, GMT, Atlantic/Azores
                 */
                case 'e':
                    no_support('e', 'Timezone identifier');
                    break;

                /*
                 * Character: "I" (capital i)
                 * Description: Whether or not the date is in daylight saving time
                 * Example: 1 if Daylight Saving Time, 0 otherwise.
                 */
                case 'I':
                    o += daylightSavings(dateValue);
                    break;

                /*
                 * Character: "O"
                 * Description: Difference to Greenwich time (GMT) in hours and minutes
                 * Example: +0200
                 */
                case 'O':
                    o += gmtOffset(dateValue, false);
                    break;

                /*
                 * Character: "P"
                 * Description: Difference to Greenwich time (GMT) with colon between hours and minutes
                 * Example: +02:00
                 */
                case 'P':
                    o += gmtOffset(dateValue, true);
                    break;

                /*
                 * Character: "T"
                 * Description: Timezone abbreviation
                 * Example: EST, MDT ...
                 */
                case 'T':
                    no_support('T', 'Timezone abbreviation');
                    break;

                /*
                 * Character: "c"
                 * Description: ISO 8601 date
                 * Example: 2004-02-12T15:19:21+00:00
                 * TODO: Add this ISO 8601 date to format.
                 */
                case 'c':
                    o += convertToIso8601(dateValue);
                    break;

                /*
                 * Character: "r"
                 * Description: RFC 2822
                 * Example: Thu, 21 Dec 2000 16:01:07 +0200
                 * TODO: Add this RFC 2822 to format.
                 */
                case 'r':
                    o += convertToRFC2822(dateValue);
                    break;

                /*
                 * Character: "U"
                 * Description: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
                 * Example: 12345678910
                 * TODO: Add this Unix Epoch to format.
                 */
                case 'U':
                    o += convertToTimestamp(dateValue);
                    break;

                /*
                 * Any other characters get passed through.
                 */
                default:
                    o += maskArray[i];
                    break;
                }
            }
        }
        return o;
    };

    return date;
});


text:
//
// ClientException.cs
//
// Author:
//       Zach Deibert <zachdeibert@gmail.com>
//
// Copyright (c) 2017 Zach Deibert
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Com.Latipium.Daemon.Api.Model;

namespace Com.Latipium.Daemon {
    public class ClientException : Exception {
        public Error Error;

        public ClientException(string message) : base(message) {
            Error = new Error() {
                Message = message,
                Side = Side.Client
            };
        }
    }
}


text:
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.encoding import force_text, smart_text
from django.utils.functional import SimpleLazyObject
from django.utils.translation import gettext_lazy

@ignore_warnings(category=RemovedInDjango40Warning)
class TestDeprecatedEncodingUtils(SimpleTestCase):

    def test_force_text(self):
        s = SimpleLazyObject(lambda: 'x')
        self.assertIs(type(force_text(s)), str)

    def test_smart_text(self):
        class Test:
            def __str__(self):
                return 'ŠĐĆŽćžšđ'

        lazy_func = gettext_lazy('x')
        self.assertIs(smart_text(lazy_func), lazy_func)
        self.assertEqual(smart_text(Test()), '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
        self.assertEqual(smart_text(1), '1')
        self.assertEqual(smart_text('foo'), 'foo')


text: docker push $DOCKER_REGISTRY/quickstart/java-simple-mainclass:2.0-SNAPSHOT


text:
import java.net.URI;
import java.net.URISyntaxException;

public class CLI {
    public static void main(String[] args) {
        String roombaHost = System.getProperty("roomba-host");
        String channel = System.getProperty("channel");

        System.out.println("Using roomba host: " + roombaHost);
        System.out.println("Using channel: " + channel);

        try {
            URI uri = new URI("ws://" + roombaHost + "/socket/websocket?vsn=1.0.0");
            Roombot roombot = new Roombot(uri, channel);

            System.out.println("Initializing connection.");
            roombot.connect();

            System.out.println("Setting up heartbeat back to host.");
            roombot.setupHeartbeat();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}


text:
"""
Key bindings for extra page navigation: bindings for up/down scrolling through
long pages, like in Emacs or Vi.
"""
from __future__ import unicode_literals
from prompt_toolkit.filters import emacs_mode, buffer_has_focus
from .scroll import scroll_forward, scroll_backward, scroll_half_page_up, scroll_half_page_down, scroll_one_line_up, scroll_one_line_down, scroll_page_up, scroll_page_down
from prompt_toolkit.filters import vi_mode
from prompt_toolkit.key_binding.key_bindings import KeyBindings, ConditionalKeyBindings, merge_key_bindings

__all__ = [
    'load_page_navigation_bindings',
    'load_emacs_page_navigation_bindings',
    'load_vi_page_navigation_bindings',
]

def load_page_navigation_bindings():
    """
    Load both the Vi and Emacs bindings for page navigation.
    """
    # Only enable when a `Buffer` is focused, otherwise, we would catch keys
    # when another widget is focused (like for instance `c-d` in a
    # ptterm.Terminal).
    return ConditionalKeyBindings(
        merge_key_bindings([
            load_emacs_page_navigation_bindings(),
            load_vi_page_navigation_bindings(),
        ]), buffer_has_focus)

def load_emacs_page_navigation_bindings():
    """
    Key bindings, for scrolling up and down through pages.
    This are separate bindings, because GNU readline doesn't have them.
    """
    key_bindings = KeyBindings()
    handle = key_bindings.add

    handle('c-v')(scroll_page_down)
    handle('pagedown')(scroll_page_down)
    handle('escape', 'v')(scroll_page_up)
    handle('pageup')(scroll_page_up)

    return ConditionalKeyBindings(key_bindings, emacs_mode)

def load_vi_page_navigation_bindings():
    """
    Key bindings, for scrolling up and down through pages.
    This are separate bindings, because GNU readline doesn't have them.
    """
    key_bindings = KeyBindings()
    handle = key_bindings.add

    handle('c-f')(scroll_forward)
    handle('c-b')(scroll_backward)
    handle('c-d')(scroll_half_page_down)
    handle('c-u')(scroll_half_page_up)
    handle('c-e')(scroll_one_line_down)
    handle('c-y')(scroll_one_line_up)
    handle('pagedown')(scroll_page_down)
    handle('pageup')(scroll_page_up)

    return ConditionalKeyBindings(key_bindings, vi_mode)


text:
package net.ontrack.extension.github.service;

import net.ontrack.core.model.ProjectSummary;
import net.ontrack.extension.git.client.GitCommit;
import net.ontrack.extension.github.model.GitHubIssue;
import net.ontrack.extension.github.model.GitHubIssueInfo;

import java.util.Collection;
import java.util.List;
import java.util.Locale;

public interface GitHubService {

    List<GitHubIssue> getGitHubIssues(int branchId, List<GitCommit> commits);

    Collection<ProjectSummary> getProjectsWithIssue(int issue);

    GitHubIssueInfo getIssueInfo(Locale locale, int projectId, int issue);
}


text:
#pragma once

#include "CollectorOutput.h"
#include "cpptest.h"

#include <ostream>

namespace Test
{

	/*!
	 * Prints a HTML-statistics to the output-stream
	 */
	class HTMLOutput : public CollectorOutput
	{
	public:
		HTMLOutput() = default;
		HTMLOutput(const HTMLOutput&) = delete;
		HTMLOutput(HTMLOutput&&) = default; //RPi cross-compiler throws on noexcept here
		~HTMLOutput() noexcept override = default;

		HTMLOutput& operator=(const HTMLOutput&) = delete;
		HTMLOutput& operator=(HTMLOutput&&) = default; //RPi cross-compiler throws on noexcept here

		/*!
		 * Generates a HTML page with a <table> listing the result of the tests
		 *
		 * \param stream The stream to generate the HTML-table to
		 * \param includePassed Whether to include passed test-methods (methods without any error)
		 * \param title The title of the result-page
		 */
		void generate(std::ostream& stream, bool includePassed = true, const std::string& title = "Test-Results");

	private:
		void generateHeader(std::ostream& stream, const std::string& title);
		void generateSuitesTable(std::ostream& stream, bool includePassed);
		void generateTestsTable(std::ostream& stream, const SuiteInfo& suite, bool includePassed);
	};

} // namespace Test


text:
<?php

namespace vSymfo\Payment\BlockchainBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader;
use vSymfo\Core\ExtensionAbstract;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 *
 * @author Rafał Mikołajun <rafal@vision-web.pl>
 * @package vSymfoPaymentBlockchainBundle
 */
class vSymfoPaymentBlockchainExtension extends ExtensionAbstract
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration($this->getAlias());
        $config = $this->processConfiguration($configuration, $configs);
        $this->setParameterAll($container, $config);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'vsymfo_payment_blockchain';
    }
}


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

namespace LOCCounter.Domain.Attributes
{
    public class ReaderAttribute : Attribute
    {
        public string Extension { get; private set; }

        public ReaderAttribute(string extension)
        {
            this.Extension = extension;
        }
    }
}