text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Diagnostics;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Threading;
using Microsoft.Reactive.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ReactiveTests.Tests
{
    [TestClass]
    public class NewThreadSchedulerTest
    {
        [TestMethod]
        public void NewThread_ArgumentChecking()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => new NewThreadScheduler(null));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.Schedule<int>(42, default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.Schedule<int>(42, DateTimeOffset.Now, default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.Schedule<int>(42, TimeSpan.Zero, default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.SchedulePeriodic<int>(42, TimeSpan.FromSeconds(1), default(Func<int, int>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.ScheduleLongRunning<int>(42, default(Action<int, ICancelable>)));
            ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => NewThreadScheduler.Default.SchedulePeriodic<int>(42, TimeSpan.FromSeconds(-1), _ => _));
        }

        [TestMethod]
        public void NewThread_Now()
        {
            var res = NewThreadScheduler.Default.Now - DateTime.Now;
            Assert.IsTrue(res.Seconds < 1);
        }

        [TestMethod]
        public void NewThread_ScheduleAction()
        {
            var id = Thread.CurrentThread.ManagedThreadId;
            var nt = NewThreadScheduler.Default;
            var evt = new ManualResetEvent(false);
            nt.Schedule(() => { Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId); evt.Set(); });
            evt.WaitOne();
        }

#if !SILVERLIGHT
        [TestMethod]
        [Ignore]
        public void NewThread_ScheduleActionDue()
        {
            var id = Thread.CurrentThread.ManagedThreadId;
            var nt = NewThreadScheduler.Default;
            var evt = new ManualResetEvent(false);
            var sw = new Stopwatch();
            sw.Start();
            nt.Schedule(TimeSpan.FromSeconds(0.2), () => { sw.Stop(); Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId); evt.Set(); });
            evt.WaitOne();
            Assert.IsTrue(sw.ElapsedMilliseconds > 180, "due " + sw.ElapsedMilliseconds);
        }
#endif

#if !NO_PERF
#if !NO_STOPWATCH
        [TestMethod]
        public void Stopwatch()
        {
            StopwatchTest.Run(NewThreadScheduler.Default);
        }
#endif
#endif

        [TestMethod]
        public void NewThread_Periodic()
        {
            var n = 0;
            var e = new ManualResetEvent(false);

            var d = NewThreadScheduler.Default.SchedulePeriodic(TimeSpan.FromMilliseconds(25), () =>
            {
                if (Interlocked.Increment(ref n) == 10)
                    e.Set();
            });

            if (!e.WaitOne(10000))
                Assert.Fail();

            d.Dispose();
        }

        [TestMethod]
        public void NewThread_Periodic_NonReentrant()
        {
            var n = 0;
            var fail = false;

            var d = NewThreadScheduler.Default.SchedulePeriodic(0, TimeSpan.FromMilliseconds(50), x =>
            {
                try
                {
                    if (Interlocked.Increment(ref n) > 1) // Without an AsyncLock this would fail.
                        fail = true;

                    Thread.Sleep(100);

                    return x + 1;
                }
                finally
                {
                    Interlocked.Decrement(ref n);
                }
            });

            Thread.Sleep(500);
            d.Dispose();

            Assert.IsFalse(fail);
        }
    }
}


text:
var MemoryGUI = (function() { // begin IIFE

//  Define specialized Backbone views...

var CardView = Backbone.View.extend({

  tagName: 'div', // create new div element for each view
  events: {
    'click': 'liftMe' // respond to clicks with tryLift method
  },

  initialize: function(opts) { //opts contains game,n, and maybe className
    // className, if included, is picked up automatically
    this.game = opts.game;
    this.n = opts.n;
    this.$el.addClass('memoryCell');
    this.$el.appendTo('#memorygrid');
  },

  liftMe: function() {
    this.game.lift(this.n); // defers to game to decide result;
                            // eventually gets replay of show, hide,or remove
  },

  // Change appearance of this card view:
  show: function(what) {
    this.$el.attr('value',what); // store what is attribute for CSS pseudo-element to read
    this.$el.addClass('faceup'); // CSS pseudo-element to show card face (what)
  },
  remove: function() {
    this.$el.addClass('missing');
  },
  hide: function() {
    this.$el.removeClass('faceup');
  },
  reset: function() {
    this.$el.removeClass('faceup').removeClass('missing');
  }
});

var  GridView = Backbone.View.extend({
	el:'#memorygrid', // div #memorygrid is created in html, so just attach view to it

	initialize: function(opts) { // opts is {game:game}
        // create personal properties:
        this.game = opts.game;
        this.cards = []; // grid's subviews

        // Generate all a subview for each card in game:
        var len = this.game.length;
		var cols = Math.ceil(Math.sqrt(len));
		for (var n=0; n<len; ++n) {
            // rebuild options object:
            opts = {game:this.game, n:n};
            if (!(n%cols))
                opts.className = 'firstCol';
            this.cards.push(new CardView(opts)); //make one subview and save it
		}
    },

    show: function(where,what) { // where is #, what is card face value (usually string)
        // Show one subview...
        this.cards[where].show(what); // delegate to card view at where
    },

    doSoon: function(locs,methodName) {// locs is an array of #s; methodName is 'hide' or 'remove'
    // In a little while, call the hide() or remove() method for each card subview in locs...
    // (This could also be split into two separate methods (hideSoon, removeSoon))

        var cards=this.cards; //retain this.cards as variable so that it's available to forEach callback below
        window.setTimeout(function () { // after a delay...
            locs.forEach(function(loc) { // for each location...
                // forEach doesn't set 'this', so needs var 'cards' from closure:
                cards[loc][methodName]();// use appropriate method of appropriate card view
            });
        }, 1000); // 1 second delay
    },

    reset: function() {
        // reset all card views...
        this.cards.forEach(function(cardview) {cardview.reset()});
    }
});

var MainView = Backbone.View.extend({
    el:'#memorygame', // div #memorygame is created in html, so just attach view to it
    events: {
        'click .resetBtn': 'resetAll' //define click for reset button
        },
    initialize: function(opts) { // opts is {game:game}
        // give mainview links to game and gridview:
        this.game = opts.game;
        this.gridview = new GridView(opts); //make subviews, passing opts downward
        // create and attach reset button:
        $('<button>Reset</button>').addClass('resetBtn').appendTo(this.$el);
    },
    resetAll: function() { //when reset button is clicked:
        this.game.reset();
        this.gridview.reset();
    }
});

function GUI(game) { //ctor
    if (arguments.length===3) //make backward compatible w. 3-arg version...
        game = {length:arguments[0], lift:arguments[1], reset:arguments[2]};

    // give GUI links to related objects: game, mainview, gridview:
    this.game = game;
    this.mainview = new MainView({game:game}); //makes all views
    this.gridview = this.mainview.gridview;

    // delegate some actions to gridview:
    this.show = function(where,what) {
        return this.gridview.show(where,what);
    }
    this.hideSoon = function(locs) {
        return this.gridview.doSoon(locs,'hide');
    }
    this.removeSoon = function(locs) {
        return this.gridview.doSoon(locs,'remove');
    }
}

return GUI;

})(); //end GUI IIFE

redpajama_set_name: RedPajamaGithub


text:
    <title>Reset password</title>

Hello,

        We have received a request to reset the password of the user with this e-mail.

        If you did not request this, simply ignore and delete this e-mail.

        To reset your password, click the following link:

        {{$domain}}/admin/login/reset/{{$token}}

This reset password request will expire in {{ $expire }} minutes.


text:
//-----------------------------------------------------------------------
// <copyright file="PNCounter.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using Akka.Cluster;
using System;
using System.Collections.Immutable;
using System.Numerics;

namespace Akka.DistributedData
{
    ///
    /// Implements a 'Increment/Decrement Counter' CRDT, also called a 'PN-Counter'.
    ///
    /// It is described in the paper
    /// A comprehensive study of Convergent and Commutative Replicated Data Types.
    ///
    /// PN-Counters allow the counter to be incremented by tracking the
    /// increments (P) separate from the decrements (N). Both P and N are represented
    /// as two internal [[GCounter]]s. Merge is handled by merging the internal P and N
    /// counters. The value of the counter is the value of the P _counter minus
    /// the value of the N counter.
    ///
    /// This class is immutable, i.e. "modifying" methods return a new instance.
    ///
    [Serializable]
    public sealed class PNCounter :
        IDeltaReplicatedData<PNCounter, PNCounter>,
        IRemovedNodePruning<PNCounter>,
        IReplicatedDataSerialization,
        IEquatable<PNCounter>,
        IReplicatedDelta
    {
        public static readonly PNCounter Empty = new PNCounter();

        public BigInteger Value => new BigInteger(Increments.Value) - new BigInteger(Decrements.Value);

        public GCounter Increments { get; }

        public GCounter Decrements { get; }

        public PNCounter() : this(GCounter.Empty, GCounter.Empty) { }

        public PNCounter(GCounter increments, GCounter decrements)
        {
            Increments = increments;
            Decrements = decrements;
        }

        ///
        /// Increment the counter with the delta specified.
        /// If the delta is negative then it will decrement instead of increment.
        ///
        public PNCounter Increment(Cluster.Cluster node, long delta = 1) => Increment(node.SelfUniqueAddress, delta);

        ///
        /// Increment the counter with the delta specified.
        /// If the delta is negative then it will decrement instead of increment.
        ///
        public PNCounter Increment(UniqueAddress address, long delta = 1) => Change(address, delta);

        ///
        /// Decrement the counter with the delta specified.
        /// If the delta is negative then it will increment instead of decrement.
        ///
        public PNCounter Decrement(Cluster.Cluster node, long delta = 1) => Decrement(node.SelfUniqueAddress, delta);

        ///
        /// Decrement the counter with the delta specified.
        /// If the delta is negative then it will increment instead of decrement.
        ///
        public PNCounter Decrement(UniqueAddress address, long delta = 1) => Change(address, -delta);

        private PNCounter Change(UniqueAddress key, long delta)
        {
            if (delta > 0) return new PNCounter(Increments.Increment(key, (ulong)delta), Decrements);
            if (delta < 0) return new PNCounter(Increments, Decrements.Increment(key, (ulong)(-delta)));

            return this;
        }

        public PNCounter Merge(PNCounter other) =>
            new PNCounter(Increments.Merge(other.Increments), Decrements.Merge(other.Decrements));

        public ImmutableHashSet<UniqueAddress> ModifiedByNodes => Increments.ModifiedByNodes.Union(Decrements.ModifiedByNodes);

        public bool NeedPruningFrom(Cluster.UniqueAddress removedNode) =>
            Increments.NeedPruningFrom(removedNode) || Decrements.NeedPruningFrom(removedNode);

        IReplicatedData IRemovedNodePruning.PruningCleanup(UniqueAddress removedNode) => PruningCleanup(removedNode);

        IReplicatedData IRemovedNodePruning.Prune(UniqueAddress removedNode, UniqueAddress collapseInto) => Prune(removedNode, collapseInto);

        public PNCounter Prune(Cluster.UniqueAddress removedNode, Cluster.UniqueAddress collapseInto) =>
            new PNCounter(Increments.Prune(removedNode, collapseInto), Decrements.Prune(removedNode, collapseInto));

        public PNCounter PruningCleanup(Cluster.UniqueAddress removedNode) =>
            new PNCounter(Increments.PruningCleanup(removedNode), Decrements.PruningCleanup(removedNode));

        /// <inheritdoc/>
        public bool Equals(PNCounter other)
        {
            if (ReferenceEquals(other, null)) return false;
            if (ReferenceEquals(this, other)) return true;

            return other.Increments.Equals(Increments) && other.Decrements.Equals(Decrements);
        }

        /// <inheritdoc/>
        public override string ToString() => $"PNCounter({Value})";

        /// <inheritdoc/>
        public override bool Equals(object obj) => obj is PNCounter && Equals((PNCounter)obj);

        /// <inheritdoc/>
        public override int GetHashCode() => Increments.GetHashCode() ^ Decrements.GetHashCode();

        public IReplicatedData Merge(IReplicatedData other) => Merge((PNCounter)other);
        IReplicatedDelta IDeltaReplicatedData.Delta => Delta;

        IReplicatedData IDeltaReplicatedData.MergeDelta(IReplicatedDelta delta) => Merge((PNCounter)delta);
        IReplicatedData IDeltaReplicatedData.ResetDelta() => ResetDelta();

        #region delta

        public PNCounter Delta => new PNCounter(Increments.Delta ?? GCounter.Empty, Decrements.Delta ?? GCounter.Empty);

        public PNCounter MergeDelta(PNCounter delta) => Merge(delta);

        public PNCounter ResetDelta()
        {
            if (Increments.Delta == null && Decrements.Delta == null)
                return this;

            return new PNCounter(Increments.ResetDelta(), Decrements.ResetDelta());
        }

        #endregion

        IDeltaReplicatedData IReplicatedDelta.Zero => PNCounter.Empty;
    }

    public sealed class PNCounterKey : Key<PNCounter>
    {
        public PNCounterKey(string id)
            : base(id)
        { }
    }
}


text:
@if ($modelAdmin->hasTranslating())

            Language:

        currentUrl($type.'?filter='.\Request::get('filter')) }}"
           class="btn {{ \Request::get('lang', 'all') === 'all' ? 'btn-info' : 'btn-default' }} btn-flat">
            All

        @foreach($modelAdmin->languages() as $key => $language)
            currentUrl($type.'?lang='.$key.'&filter='.\Request::get('filter')) }}"
               class="btn {{ \Request::get('lang') === $key ? 'btn-info' : 'btn-default' }} btn-flat">
                {{ $language }}

        @endforeach

@endif

@if ($modelAdmin->filters())

            currentUrl($type.'?filter='.\Request::get('filter')) }}" class="btn btn-default btn-flat">
                Filter:
                @if ($filter = \Request::get('filter'))
                    {{ $modelAdmin->safeFilters()[$filter] }}
                @else
                    None
                @endif

            <button data-toggle="dropdown" class="btn btn-default btn-flat dropdown-toggle" type="button">

                Toggle Dropdown
            </button>

                    currentUrl($type) }}">
                        None

                @foreach ($modelAdmin->safeFilters() as $filterAction => $filter)

                        currentUrl($type.'?filter='.$filterAction) }}">
                           {{ $filter }}

                @endforeach

@endif


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>obter-certificado-de-aeronavegabilidade-especial-para-aeronave-leve-esportiva</id>
    <dbId>2886</dbId>
    <nome>Obter Certificado de Aeronavegabilidade Especial para Aeronave Leve Esportiva</nome>
    <sigla></sigla>
    <nomes-populares>
        <item id="2237">ALE Especial</item>
    </nomes-populares>
    <descricao>Consiste na avaliação amostral da aeronave e de seu fabricante quanto ao embasamento para declaração de cumprimento às normas consensuais para Aeronaves Leve Esportivas.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="3467">
            <tipo>Fabricantes de aeronaves</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="6714">
            <titulo>Requisistar certificado</titulo>
            <descricao>Apresentação da documentação técnica da aeronave e da empresa.</descricao>
            <documentos>
                <default>
                    <item id="8890">Documentação Técnica</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="6936" tipo="telefone">
                        <descricao>(12) 3203-6732</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="6937" tipo="e-mail">
                        <descricao>experimental@anac.gov.br</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/86144" dbId="908">
        <nomeOrgao>Agência Nacional de Aviação Civil (ANAC)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="3" idServicoSegmento="6601">Empresas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Esporte e Lazer</item>
        <item>Indústria</item>
        <item>Pesquisa e Desenvolvimento</item>
        <item>Transportes</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="12421">anac</item>
        <item id="12422">aeronave leve esportiva</item>
        <item id="12423">certificação</item>
    </palavras-chave>
</servico>


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq.Expressions;
using MonoMod.Utils;
using Mono.Cecil.Cil;
using System.Linq;
using System.Collections.ObjectModel;
using System.Threading;
#if !NET35
using System.Collections.Concurrent;
#endif

namespace MonoMod.RuntimeDetour {
    public struct DetourConfig {
        public bool ManualApply;
        public int Priority;
        public string ID;
        public IEnumerable<string> Before;
        public IEnumerable<string> After;
    }

    /// <summary>
    /// A fully managed detour.
    /// Multiple Detours for a method to detour from can exist at any given time. Detours can be layered.
    /// If you're writing your own detour manager or need to detour native functions, it's better to create instances of NativeDetour instead.
    /// </summary>
    public class Detour : ISortableDetour {
#if NET35
        private static Dictionary<MethodBase, List<Detour>> _DetourMap = new Dictionary<MethodBase, List<Detour>>(new GenericMethodInstantiationComparer());
#else
        private static ConcurrentDictionary<MethodBase, List<Detour>> _DetourMap = new ConcurrentDictionary<MethodBase, List<Detour>>(new GenericMethodInstantiationComparer());
#endif
        private static Dictionary<MethodBase, MethodInfo> _BackupMethods = new Dictionary<MethodBase, MethodInfo>();
        private static uint _GlobalIndexNext = uint.MinValue;

        private List<Detour> _DetourChain => _DetourMap.TryGetValue(Method, out List<Detour> detours) ? detours : null;

        public static Func<Detour, MethodBase, MethodBase, bool> OnDetour;
        public static Func<Detour, bool> OnUndo;
        public static Func<Detour, MethodBase, MethodBase> OnGenerateTrampoline;

        public bool IsValid => Index != -1;
        public bool IsApplied { get; private set; }
        private bool IsTop => _TopDetour != null;

        public int Index => _DetourChain?.IndexOf(this) ?? -1;
        public int MaxIndex => _DetourChain?.Count ?? -1;

        private readonly uint _GlobalIndex;
        public uint GlobalIndex => _GlobalIndex;

        private int _Priority;
        public int Priority {
            get => _Priority;
            set {
                if (_Priority == value)
                    return;
                _Priority = value;
                _RefreshChain(Method);
            }
        }

        private string _ID;
        public string ID {
            get => _ID;
            set {
                if (string.IsNullOrEmpty(value))
                    value = Target.GetID(simple: true);
                if (_ID == value)
                    return;
                _ID = value;
                _RefreshChain(Method);
            }
        }

        private List<string> _Before = new List<string>();
        private ReadOnlyCollection<string> _BeforeRO;
        public IEnumerable<string> Before {
            get => _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly());
            set {
                lock (_Before) {
                    _Before.Clear();
                    if (value != null)
                        foreach (string id in value)
                            _Before.Add(id);
                    _RefreshChain(Method);
                }
            }
        }

        private List<string> _After = new List<string>();
        private ReadOnlyCollection<string> _AfterRO;
        public IEnumerable<string> After {
            get => _AfterRO ?? (_AfterRO = _After.AsReadOnly());
            set {
                lock (_After) {
                    _After.Clear();
                    if (value != null)
                        foreach (string id in value)
                            _After.Add(id);
                    _RefreshChain(Method);
                }
            }
        }

        public readonly MethodBase Method;
        public readonly MethodBase Target;
        public readonly MethodBase TargetReal;

        // The active NativeDetour. Only present if the current Detour is on the top of the Detour chain.
        private NativeDetour _TopDetour;

        // Called by the generated trampolines, updated when the Detour chain changes.
        private MethodInfo _ChainedTrampoline;

        public Detour(MethodBase from, MethodBase to, ref DetourConfig config) {
            from = from.GetIdentifiable();
            if (from.Equals(to))
                throw new ArgumentException("Cannot detour a method to itself!");

            MMDbgLog.Log($"detour from {from.GetID()} to {to.GetID()}");

            Method = from/*.Pin()*/;
            Target = to.Pin(); // Only pin once, unpin on Free!
            TargetReal = DetourHelper.Runtime.GetDetourTarget(from, to)/*.Pin()*/;

            _GlobalIndex = _GlobalIndexNext++;

            _Priority = config.Priority;
            _ID = config.ID;
            if (config.Before != null)
                foreach (string id in config.Before)
                    _Before.Add(id);
            if (config.After != null)
                foreach (string id in config.After)
                    _After.Add(id);

            lock (_BackupMethods) {
                if ((!_BackupMethods.TryGetValue(Method, out MethodInfo backup) || backup == null) &&
                    (backup = Method.CreateILCopy()) != null)
                    _BackupMethods[Method] = backup.Pin(); // Only pin once, unpin on Free!
            }

            // Generate a "chained trampoline" DynamicMethod.
            ParameterInfo[] args = Method.GetParameters();
            Type[] argTypes;
            if (!Method.IsStatic) {
                argTypes = new Type[args.Length + 1];
                argTypes[0] = Method.GetThisParamType();
                for (int i = 0; i < args.Length; i++)
                    argTypes[i + 1] = args[i].ParameterType;
            } else {
                argTypes = new Type[args.Length];
                for (int i = 0; i < args.Length; i++)
                    argTypes[i] = args[i].ParameterType;
            }

            using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(
                $"Chain<{Method.GetID(simple: true)}>?{GetHashCode()}",
                (Method as MethodInfo)?.ReturnType ?? typeof(void), argTypes
            ))
                _ChainedTrampoline = dmd.StubCriticalDetour().Generate().Pin();

            // Add the detour to the detour map.
            List<Detour> detours;
#if NET35
            lock (_DetourMap) {
                if (!_DetourMap.TryGetValue(Method, out detours))
                    _DetourMap[Method] = detours = new List<Detour>();
            }
#else
            detours = _DetourMap.GetOrAdd(Method, m => new List<Detour>());
#endif
            lock (detours) {
                detours.Add(this);
                // The chain gets refreshed when the detour is applied.
            }

            if (!config.ManualApply)
                Apply();
        }
        public Detour(MethodBase from, MethodBase to, DetourConfig config)
            : this(from, to, ref config) {
        }
        public Detour(MethodBase from, MethodBase to)
            : this(from, to, DetourContext.Current?.DetourConfig ?? default) {
        }

        public Detour(MethodBase method, IntPtr to, ref DetourConfig config)
            : this(method, DetourHelper.GenerateNativeProxy(to, method), ref config) {
        }
        public Detour(MethodBase method, IntPtr to, DetourConfig config)
            : this(method, DetourHelper.GenerateNativeProxy(to, method), ref config) {
        }
        public Detour(MethodBase method, IntPtr to)
            : this(method, DetourHelper.GenerateNativeProxy(to, method)) {
        }

        public Detour(Delegate from, IntPtr to, ref DetourConfig config)
            : this(from.Method, to, ref config) {
        }
        public Detour(Delegate from, IntPtr to, DetourConfig config)
            : this(from.Method, to, ref config) {
        }
        public Detour(Delegate from, IntPtr to)
            : this(from.Method, to) {
        }
        public Detour(Delegate from, Delegate to, ref DetourConfig config)
            : this(from.Method, to.Method, ref config) {
        }
        public Detour(Delegate from, Delegate to, DetourConfig config)
            : this(from.Method, to.Method, ref config) {
        }
        public Detour(Delegate from, Delegate to)
            : this(from.Method, to.Method) {
        }

        public Detour(Expression from, IntPtr to, ref DetourConfig config)
            : this(((MethodCallExpression) from).Method, to, ref config) {
        }
        public Detour(Expression from, IntPtr to, DetourConfig config)
            : this(((MethodCallExpression) from).Method, to, ref config) {
        }
        public Detour(Expression from, IntPtr to)
            : this(((MethodCallExpression) from).Method, to) {
        }
        public Detour(Expression from, Expression to, ref DetourConfig config)
            : this(((MethodCallExpression) from).Method, ((MethodCallExpression) to).Method, ref config) {
        }
        public Detour(Expression from, Expression to, DetourConfig config)
            : this(((MethodCallExpression) from).Method, ((MethodCallExpression) to).Method, ref config) {
        }
        public Detour(Expression from, Expression to)
            : this(((MethodCallExpression) from).Method, ((MethodCallExpression) to).Method) {
        }

        public Detour(Expression<Action> from, IntPtr to, ref DetourConfig config)
            : this(from.Body, to, ref config) {
        }
        public Detour(Expression<Action> from, IntPtr to, DetourConfig config)
            : this(from.Body, to, ref config) {
        }
        public Detour(Expression<Action> from, IntPtr to)
            : this(from.Body, to) {
        }
        public Detour(Expression<Action> from, Expression<Action> to, ref DetourConfig config)
            : this(from.Body, to.Body, ref config) {
        }
        public Detour(Expression<Action> from, Expression<Action> to, DetourConfig config)
            : this(from.Body, to.Body, ref config) {
        }
        public Detour(Expression<Action> from, Expression<Action> to)
            : this(from.Body, to.Body) {
        }

        /// <summary>
        /// Mark the detour as applied in the detour chain. This can be done automatically when creating an instance.
        /// </summary>
        public void Apply() {
            if (!IsValid)
                throw new ObjectDisposedException(nameof(Detour));

            if (IsApplied)
                return;

            if (!(OnDetour?.InvokeWhileTrue(this, Method, Target) ?? true))
                return;

            IsApplied = true;
            _RefreshChain(Method);
        }

        /// <summary>
        /// Undo the detour without freeing it, allowing you to reapply it later.
        /// </summary>
        public void Undo() {
            if (!IsValid)
                throw new ObjectDisposedException(nameof(Detour));

            if (!IsApplied)
                return;

            if (!(OnUndo?.InvokeWhileTrue(this) ?? true))
                return;

            IsApplied = false;
            _RefreshChain(Method);
        }

        /// <summary>
        /// Free the detour, while also permanently undoing it. This makes any further operations on this detour invalid.
        /// </summary>
        public void Free() {
            // NativeDetour allows freeing without undoing, but Detours are fully managed.
            // Freeing a Detour without undoing it would leave a hole open in the detour chain.
            if (!IsValid)
                return;

            Undo();

            List<Detour> detours = _DetourChain;
            lock (detours) {
                detours.Remove(this);
                if (detours.Count == 0) {
                    lock (_BackupMethods) {
                        if (_BackupMethods.TryGetValue(Method, out MethodInfo backup)) {
                            backup.Unpin();
                            _BackupMethods.Remove(Method);
                        }
                    }
#if NET35
                    lock (_DetourMap) {
                        _DetourMap.Remove(Method);
                    }
#else
                    _DetourMap.TryRemove(Method, out _);
#endif
                }
            }

            _ChainedTrampoline.Unpin();
            Target.Unpin();
        }

        /// <summary>
        /// Undo and free this temporary detour.
        /// </summary>
        public void Dispose() {
            if (!IsValid)
                return;

            Undo();
            Free();
        }

        /// <summary>
        /// Generate a new DynamicMethod with which you can invoke the previous state.
        /// </summary>
        public MethodBase GenerateTrampoline(MethodBase signature = null) {
            MethodBase remoteTrampoline = OnGenerateTrampoline?.InvokeWhileNull<MethodBase>(this, signature);
            if (remoteTrampoline != null)
                return remoteTrampoline;

            if (signature == null)
                signature = Target;

            // Note: It'd be more performant to skip this step and just return the "chained trampoline."
            // Unfortunately, it'd allow a third party to break the Detour trampoline chain, among other things.
            // Instead, we create and return a DynamicMethod calling the "chained trampoline."

            Type returnType = (signature as MethodInfo)?.ReturnType ?? typeof(void);

            ParameterInfo[] args = signature.GetParameters();
            Type[] argTypes = new Type[args.Length];
            for (int i = 0; i < args.Length; i++)
                argTypes[i] = args[i].ParameterType;

            using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(
                $"Trampoline<{Method.GetID(simple: true)}>?{GetHashCode()}",
                returnType, argTypes
            )) {
                ILProcessor il = dmd.GetILProcessor();

                for (int i = 0; i < 32; i++) {
                    // Prevent mono from inlining the DynamicMethod.
                    il.Emit(OpCodes.Nop);
                }

                // Jmp and older versions of mono don't work well together.
                // il.Emit(OpCodes.Jmp, _ChainedTrampoline);

                // Manually call the target method instead.
                for (int i = 0; i < argTypes.Length; i++)
                    il.Emit(OpCodes.Ldarg, i);
                il.Emit(OpCodes.Call, _ChainedTrampoline);
                il.Emit(OpCodes.Ret);

                return dmd.Generate();
            }
        }

        /// <summary>
        /// Generate a new DynamicMethod with which you can invoke the previous state.
        /// </summary>
        public T GenerateTrampoline<T>() where T : Delegate {
            if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
                throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");

            return GenerateTrampoline(typeof(T).GetMethod("Invoke")).CreateDelegate(typeof(T)) as T;
        }

        private void _TopUndo() {
            if (_TopDetour == null)
                return;

            _TopDetour.Undo();
            _TopDetour.Free();
            _TopDetour = null;

            Method.Unpin();
            TargetReal.Unpin();
        }

        private void _TopApply() {
            if (_TopDetour != null)
                return;

            // GetNativeStart to avoid repins and managed copies.
            _TopDetour = new NativeDetour(Method.Pin().GetNativeStart(), TargetReal.Pin().GetNativeStart());
        }

        private static int compileMethodSubscribed = 0;
        private static void _OnCompileMethod(MethodBase method, IntPtr codeStart, ulong codeLen) {
            if (method == null)
                return;

            MMDbgLog.Log("compiling: " + method.GetID());
            if (_DetourMap.TryGetValue(method, out List<Detour> detours)) {
                Detour top = detours.FindLast(d => d.IsTop);
                /*top?._TopUndo();
                top?._TopApply();*/
                top?._TopDetour?.ChangeSource(codeStart);
            }
        }

        private static void _RefreshChain(MethodBase method) {
            // ensure we're subscribed to the event before doing anything
            if (Interlocked.CompareExchange(ref compileMethodSubscribed, 1, 0) == 0) {
                DetourHelper.Runtime.OnMethodCompiled += _OnCompileMethod;
            }

            MMDbgLog.Log($"detours applying for {method.GetID()}");

            List<Detour> detours = _DetourMap[method];
            lock (detours) {
                DetourSorter<Detour>.Sort(detours);

                Detour topOld = detours.FindLast(d => d.IsTop);
                Detour topNew = detours.FindLast(d => d.IsApplied);

                if (topOld != topNew)
                    topOld?._TopUndo();

                if (detours.Count == 0)
                    return;

                MethodBase prev = _BackupMethods[method];
                foreach (Detour detour in detours) {
                    if (!detour.IsApplied)
                        continue;

                    MethodBase next = detour._ChainedTrampoline;

                    using (NativeDetour link = new NativeDetour(
                        detour._ChainedTrampoline.GetNativeStart(),
                        prev.GetNativeStart()
                    )) {
                        // This link detour is applied permanently.
                        link.Free(); // Dispose will no longer undo.
                    }

                    prev = detour.Target;
                }

                if (topOld != topNew)
                    topNew?._TopApply();
            }
        }
    }

    public class Detour<T> : Detour where T : Delegate {
        public Detour(T from, IntPtr to, ref DetourConfig config)
            : base(from, to, ref config) {
        }
        public Detour(T from, IntPtr to, DetourConfig config)
            : base(from, to, ref config) {
        }
        public Detour(T from, IntPtr to)
            : base(from, to) {
        }
        public Detour(T from, T to, ref DetourConfig config)
            : base(from, to, ref config) {
        }
        public Detour(T from, T to, DetourConfig config)
            : base(from, to, ref config) {
        }
        public Detour(T from, T to)
            : base(from, to) {
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    internal sealed class SourceUserDefinedConversionSymbol : SourceUserDefinedOperatorSymbolBase
    {
        public static SourceUserDefinedConversionSymbol CreateUserDefinedConversionSymbol(
            SourceMemberContainerTypeSymbol containingType,
            ConversionOperatorDeclarationSyntax syntax,
            DiagnosticBag diagnostics)
        {
            // Dev11 includes the explicit/implicit keyword, but we don't have a good way to include
            // Narrowing/Widening in VB and we want the languages to be consistent.
            var location = syntax.Type.Location;
            string name = syntax.ImplicitOrExplicitKeyword.IsKind(SyntaxKind.ImplicitKeyword)
                ? WellKnownMemberNames.ImplicitConversionName
                : WellKnownMemberNames.ExplicitConversionName;

            return new SourceUserDefinedConversionSymbol(
                containingType, name, location, syntax, diagnostics);
        }

        // NOTE: no need to call WithUnsafeRegionIfNecessary, since the signature
        // is bound lazily using binders from a BinderFactory (which will already include an
        // UnsafeBinder, if necessary).
        private SourceUserDefinedConversionSymbol(
            SourceMemberContainerTypeSymbol containingType,
            string name,
            Location location,
            ConversionOperatorDeclarationSyntax syntax,
            DiagnosticBag diagnostics) :
            base(
                MethodKind.Conversion,
                name,
                containingType,
                location,
                syntax,
                diagnostics)
        {
            CheckForBlockAndExpressionBody(
                syntax.Body, syntax.ExpressionBody, syntax, diagnostics);

            if (syntax.ParameterList.Parameters.Count != 1)
            {
                diagnostics.Add(ErrorCode.ERR_OvlUnaryOperatorExpected, syntax.ParameterList.GetLocation());
            }
        }

        internal new ConversionOperatorDeclarationSyntax GetSyntax()
        {
            Debug.Assert(syntaxReferenceOpt != null);
            return (ConversionOperatorDeclarationSyntax)syntaxReferenceOpt.GetSyntax();
        }

        protected override ParameterListSyntax ParameterListSyntax
        {
            get
            {
                return GetSyntax().ParameterList;
            }
        }

        protected override TypeSyntax ReturnTypeSyntax
        {
            get
            {
                return GetSyntax().Type;
            }
        }

        internal override bool GenerateDebugInfo
        {
            get { return true; }
        }
    }
}


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class CreateGist(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the CreateGist Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(CreateGist, self).__init__(temboo_session, '/Library/GitHub/GistsAPI/Gists/CreateGist')

    def new_input_set(self):
        return CreateGistInputSet()

    def _make_result_set(self, result, path):
        return CreateGistResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return CreateGistChoreographyExecution(session, exec_id, path)

class CreateGistInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the CreateGist
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_AccessToken(self, value):
        """
        Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
        """
        super(CreateGistInputSet, self)._set_input('AccessToken', value)
    def set_Description(self, value):
        """
        Set the value of the Description input for this Choreo. ((optional, string) The description for this gist.)
        """
        super(CreateGistInputSet, self)._set_input('Description', value)
    def set_FileContents(self, value):
        """
        Set the value of the FileContents input for this Choreo. ((required, string) The file contents of the gist.)
        """
        super(CreateGistInputSet, self)._set_input('FileContents', value)
    def set_FileName(self, value):
        """
        Set the value of the FileName input for this Choreo. ((required, string) The file name of the gist (i.e. myProject.py).)
        """
        super(CreateGistInputSet, self)._set_input('FileName', value)
    def set_Public(self, value):
        """
        Set the value of the Public input for this Choreo. ((required, boolean) Indicates whether or not the gist is public or private.)
        """
        super(CreateGistInputSet, self)._set_input('Public', value)
    def set_User(self, value):
        """
        Set the value of the User input for this Choreo. ((required, string) Deprecated (retained for backward compatibility only).)
        """
        super(CreateGistInputSet, self)._set_input('User', value)

class CreateGistResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the CreateGist Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from GitHub.)
        """
        return self._output.get('Response', None)
    def get_Limit(self):
        """
        Retrieve the value for the "Limit" output from this Choreo execution. ((integer) The available rate limit for your account. This is returned in the GitHub response header.)
        """
        return self._output.get('Limit', None)
    def get_Remaining(self):
        """
        Retrieve the value for the "Remaining" output from this Choreo execution. ((integer) The remaining number of API requests available to you. This is returned in the GitHub response header.)
        """
        return self._output.get('Remaining', None)

class CreateGistChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return CreateGistResultSet(response, path)


text:
const int PUL = 6;
const int DIR = 7;
int value = 0;
int testState = true;

#define trigPin 48                                    // Pin 12 trigger output
#define echoPin 21                                     // Pin 2 Echo input
#define onBoardLED 13                                 // Pin 13 onboard LED
#define echo_int 2                                    // Interrupt id for echo pulse

#define TIMER_US 50                                   // 50 uS timer duration
#define TICK_COUNTS 4000                              // 200 mS worth of timer ticks

volatile long echo_start = 0;                         // Records start of echo pulse
volatile long echo_end = 0;                           // Records end of echo pulse
volatile long echo_duration = 0;                      // Duration - difference between end and start
volatile int trigger_time_count = 0;                  // Count down counter to trigger pulse time
volatile long range_flasher_counter = 0;              // Count down counter for flashing distance LED

// sd data string
String SDData;

const int led = 13;
const int throttle = 8;
const int switchPin = 9;

String inputString = "";
boolean stringComplete = false;

const int sdCS = 53;

const char *file = "datalog20140427.txt";

//GPS relate
float gpslat, gpslon;
String gpsdate, gpstime;
unsigned long date, time;
TinyGPS gps;
static void gpsdump(TinyGPS &gps);
static bool feedgps();
static void print_float(float val, float invalid, int len, int prec);
static void print_date(TinyGPS &gps);

// tn901 data
TN901 tn;
float objectT, envirT;

int soil1 = A0;
int soil2 = A1;
int soil3 = A2;
int soil4 = A8;
// soil data
float soil11, soil22, soil33, soil44;

// display settings
U8GLIB_ST7920_128X64_1X dis(49,46,47);
int row = 10;
int column = 30;

// dht22
#define DHTPIN 32
#define DHTTYPE DHT11   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
float dht_h, dht_t;


text:
using DertInfo.WEB.Core;
using DertInfo.WEB.Models;
using DertInfo.WEB.ViewModels.Base;
using DertInfo.WEB.ViewModels.TeamVMs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DertInfo.WEB.ViewModels.CompetitionVMs
{
    public class CompetitionDetailsViewModel : DertViewModelBase_Accessible
    {
        #region Constructors

        //Constructors
        public CompetitionDetailsViewModel(Models.Competition competition)
            : base(competition.AccessToken)
        {
            this.ToView(competition);
        }

        //private void VariablesConstructor()
        //{

        //    // todo - clean up - moved from system setting to event settings.
        //    //this.PaymentDueDate = DertInfo.WEB.BLL.BLLSystemSettings.GetDateSetting("PAYMENTDUEDATE");
        //    //this.RegistrationOpenDate = DertInfo.WEB.BLL.BLLSystemSettings.GetDateSetting("REGISTRATIONOPENDATE");
        //    //this.RegistrationCloseDate = DertInfo.WEB.BLL.BLLSystemSettings.GetDateSetting("REGISTRATIONCLOSEDATE");
        //    //this.ResultsPublic = DertInfo.WEB.BLL.BLLSystemSettings.GetBooleanSetting("RESULTSPUBLISHED");
        //}

        #endregion

        #region Properties

        //Static Properties
        //public DateTime PaymentDueDate { get; set; }
        //public DateTime RegistrationOpenDate { get; set; }
        //public DateTime RegistrationCloseDate { get; set; }
        //public bool ResultsPublic { get; set; }

        //Variable Properties
        public CompetitionViewModel CompetitionVM { get; set; }
        public CompetitionEntryAttributeVMs.CompetitionEntryAttribute_Listing_ByCompetition_ViewModel CompetitionEntryAttribute_Listing_ByCompetition_VM { get; set; }
        public CompetitionEntryVMs.CompetitionEntry_Listing_ByCompetition_ViewModel CompetitionEntry_Listing_ByCompetition_VM { get; set; }

        public VenueVMs.Venue_Listing_ByCompetition_ViewModel Venue_Listing_ByCompetition_VM { get; set; }
        public ScoreSetVMs.ScoreSet_Listing_ByCompetition_ViewModel ScoreSet_Listing_ByCompetition_VM { get; set; }
        public DanceVMs.DanceSummaryViewModel DanceSummaryVM { get; set; }

        //public List<RegistrationVMs.RegistrationViewModel> PreviousRegistrationVMs { get; set; }
        //public List<RegistrationVMs.RegistrationViewModel> CurrentRegistrationVMs { get; set; }
        //public List<Models.CompetitionImage> CompetitionImages { get; set; }
        //public ImageVMs.ImageAjaxSingleSelectionViewModel ImageAjaxSingleSelectionVM { get; set; }
        //public TeamVMs.TeamGalleryViewModel TeamGalleryVM { get; set; }
        //public EventVMs.Event_SelectionListing_ByCompetition_ViewModel Event_SelectionListing_ByCompetition_VM { get; set; }
        //public CompetitionMemberVMs.CompetitionMember_Listing_ByCompetition_ViewModel CompetitionMember_Listing_ByCompetition_VM { get; set; }
        //public List<InvoiceVMs.InvoiceViewModel> InvoiceVMs { get; set; }

        #endregion

        #region ToView / ToModel methods

        private void ToView(Models.Competition competition)
        {
            FillBasic(competition);
            FillCompetitionEntryAttributes(competition);
            FillCompetitionEntries(competition);

            FillVenues(competition);
            FillScoreSets(competition);
            FillDanceSummary(competition);

            //FillCompetitionImages(competition.Id);
            //FillCompetitionRegistrations(competition.Id);
            //FillTeams(competition.Id);
            //FillEventSelection(competition.Id);
            //FillCompetitionMembers(competition.Id);
            //FillInvoice(competition.Id);
        }

        private void FillBasic(Models.Competition competition)
        {
            CompetitionViewModel competitionVM = new CompetitionViewModel(competition);
            this.CompetitionVM = competitionVM;
        }

        private void FillCompetitionEntryAttributes(Models.Competition competition)
        {
            ICompetitionEntryAttributeRepository competitionEntryAttributeRepo = new CompetitionEntryAttributeRepository();
            List<Models.CompetitionEntryAttribute> competitionMembers = competitionEntryAttributeRepo.AllByCompetitionId(competition.Id).ToList();

            this.CompetitionEntryAttribute_Listing_ByCompetition_VM = new CompetitionEntryAttributeVMs.CompetitionEntryAttribute_Listing_ByCompetition_ViewModel(competition.Id, competitionMembers);
        }

        private void FillCompetitionEntries(Competition competition)
        {
            ICompetitionEntryRepository competitionEntryRepo = new CompetitionEntryRepository();
            List<Models.CompetitionEntry> competitionEntries = competitionEntryRepo.AllByCompetitionId(competition.Id).Where(ce => ce.AttendingTeam.Registration.FlowState == Enumerations.RegistrationState.Confirmed || ce.AttendingTeam.Registration.FlowState == Enumerations.RegistrationState.Closed).ToList();

            this.CompetitionEntry_Listing_ByCompetition_VM = new CompetitionEntryVMs.CompetitionEntry_Listing_ByCompetition_ViewModel(competition.Id, competitionEntries);
        }

        private void FillVenues(Competition competition)
        {
            IVenueRepository venueRepo = new VenueRepository();
            List<Models.Venue> venues = venueRepo.AllByCompetitionId(competition.Id).ToList();

            this.Venue_Listing_ByCompetition_VM = new VenueVMs.Venue_Listing_ByCompetition_ViewModel(competition, venues);
        }

        private void FillScoreSets(Competition competition)
        {
            IScoreSetRepository scoreSetRepo = new ScoreSetRepository();
            List<Models.ScoreSet> scoreSets = scoreSetRepo.AllByCompetitionId(competition.Id).ToList();

            this.ScoreSet_Listing_ByCompetition_VM = new ScoreSetVMs.ScoreSet_Listing_ByCompetition_ViewModel(competition.Id, scoreSets);
        }

        private void FillDanceSummary(Competition competition)
        {
            this.DanceSummaryVM = new DanceVMs.DanceSummaryViewModel(competition);
        }

        //private void FillCompetitionImages(int competitionId)
        //{
        //    Models.IImageRepository imageRepo = new Models.ImageRepository();
        //    Models.ICompetitionImageRepository competitionImageRepo = new Models.CompetitionImageRepository();

        //    int selectedId = competitionImageRepo.GetPrimaryImageId(competitionId);
        //    //List<Models.Image> selectedTeamImages = imageRepo.AllByTeamId(teamId).ToList();
        //    List<Models.Image> selectionSetImages = imageRepo.AllByCompetitionId(competitionId).ToList();

        //    this.ImageAjaxSingleSelectionVM = new ImageVMs.ImageAjaxSingleSelectionViewModel(competitionId, "JsonSetCompetitionPrimary", "Image", selectionSetImages, selectedId);

        //    //ICompetitionImageRepository competitionImageRepo = new CompetitionImageRepository();
        //    //this.CompetitionImages = competitionImageRepo.AllByCompetitionIdIncluding(competitionId,gi => gi.Image).ToList();

        //    ////Models.CompetitionImage competitionImage = new Models.CompetitionImage();
        //    ////competitionImage.ListByCompetition(competitionId);

        //    //this.CompetitionImageGalleryVM = new ImageVMs.CompetitionImageGalleryViewModel(competitionId, this.CompetitionImages);
        //}

        //private void FillCompetitionRegistrations(int competitionId)
        //{
        //    IRegistrationRepository registrationRepo = new RegistrationRepository();
        //    IQueryable<Models.Registration> registrations = registrationRepo.AllByCompetitionIdIncluding(competitionId,g => g.Event,g=>g.Competition);

        //   foreach(Models.Registration competitionRegistration in registrations.Where(r=>r.FlowState != Core.Enumerations.RegistrationState.Closed))
        //   {
        //       RegistrationVMs.RegistrationViewModel competitionRegistrationVM = new RegistrationVMs.RegistrationViewModel(competitionRegistration);
        //       this.CurrentRegistrationVMs.Add(competitionRegistrationVM);
        //   }

        //   foreach (Models.Registration competitionRegistration in registrations.Where(r => r.FlowState == Core.Enumerations.RegistrationState.Closed))
        //   {
        //       RegistrationVMs.RegistrationViewModel competitionRegistrationVM = new RegistrationVMs.RegistrationViewModel(competitionRegistration);
        //       this.PreviousRegistrationVMs.Add(competitionRegistrationVM);
        //   }

        //}

        //private void FillTeams(int competitionId)
        //{
        //    ITeamRepository teamRepo = new TeamRepository();

        //    List<Models.Team> teams = teamRepo.AllByCompetitionId(competitionId).ToList();

        //    this.TeamGalleryVM = new TeamGalleryViewModel(competitionId, teams);
        //}

        //private void FillEventSelection(int competitionId)
        //{
        //    IEventRepository eventRepo = new EventRepository();

        //    List<Models.Event> openEvents = eventRepo.AllByRegistrationOpen(DateTime.Now).ToList();

        //    //todo - push down into business logic
        //    List<Models.Event> openForCompetitionEvents = new List<Event>();

        //    foreach (Models.Event myEvent in openEvents)
        //    {
        //        if (!this.CurrentRegistrationVMs.Where(rvm => rvm.EventId == myEvent.Id).Any())
        //        {
        //            //Business Logic - If the competition is not already registered for the event
        //            openForCompetitionEvents.Add(myEvent);
        //        }
        //    }

        //    this.Event_SelectionListing_ByCompetition_VM = new EventVMs.Event_SelectionListing_ByCompetition_ViewModel(competitionId, openForCompetitionEvents);
        //}

        //private void FillCompetitionMembers(int competitionId)
        //{
        //    ICompetitionMemberRepository competitionMemberRepo = new CompetitionMemberRepository();
        //    List<Models.CompetitionMember> competitionMembers = competitionMemberRepo.AllByCompetitionId(competitionId).ToList();

        //    this.CompetitionMember_Listing_ByCompetition_VM = new CompetitionMemberVMs.CompetitionMember_Listing_ByCompetition_ViewModel(competitionId, competitionMembers);
        //}

        //private void FillInvoice(int competitionId)
        //{
        //    IInvoiceRepository invoiceRepo = new InvoiceRepository();
        //    List<Models.Invoice> invoices = invoiceRepo.AllByCompetitionId(competitionId).ToList();

        //    foreach (var invoice in invoices)
        //    {
        //        InvoiceVMs.InvoiceViewModel invoiceVM = new InvoiceVMs.InvoiceViewModel(invoice);
        //        this.InvoiceVMs.Add(invoiceVM);
        //    }
        //}

        #endregion
    }
}


text:
package ru.stqa.training.selenium;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import test.utils.Url;

import java.net.MalformedURLException;
import java.net.URL;

import static org.openqa.selenium.Platform.MAC;
import static org.openqa.selenium.Platform.WINDOWS;

/**
 * Created by ilya on 17/02/2017.
 */
public class SeleniumServerGrid {
    WebDriver driver1;
    WebDriver driver2;

    @Before
    public void before() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setBrowserName("chrome");

        capabilities.setPlatform(MAC);
        driver1 = new RemoteWebDriver(new URL("http://192.168.1.68:4444/wd/hub"), capabilities);

        capabilities.setPlatform(WINDOWS);
        driver2 = new RemoteWebDriver(new URL("http://192.168.1.68:4444/wd/hub"), capabilities);
    }

    @Test
    public void tryRemoteWebDriver(){
        driver1.get(Url.MAIN.toString());
        driver2.get(Url.MAIN.toString());
    }

    @After
    public void after(){
        driver1.quit();
        driver1 = null;
        driver2.quit();
        driver2 = null;
    }

}


text:
{% extends "site_base.html" %}

{% load url from future %}
{% load i18n %}
{% load bootstrap %}

{% block head_title %}{% trans "Set your new password" %}{% endblock %}

{% block search %}
{% endblock search %}

{% block body %}

Set your new password

                    <form method="POST" action="{% url "account_password_reset_token" uidb36=uidb36 token=token %}">
                        <fieldset>
                            {% csrf_token %}
                            {{ form|bootstrap }}
                            <button type="submit" class="button large bold">{% trans "Save" %}</button>
                        </fieldset>
                    </form>

{% endblock %}


text:
JDON FRAMEWORK
===================================
JdonFramework is a java reactive framework that you can use to build your Domain Driven Design + CQRS + EventSourcing  applications with asynchronous concurrency and higher throughput.

JdonFramework = DDD + Event Sourcing + CQRS + asynchronous + concurrency + higher throughput.

JdonFramework = Ioc/DI/AOP + reactive Actors model

Why Reactive?
===================================

Reactive Programming is a hot topic , especially with such things as the [Reactive Manifesto](http://www.reactivemanifesto.org/).
Reactive architecture allows developers to build systems that are event-driven(EDA), scalable, resilient and responsive: delivering highly responsive user experiences with a real-time feel, backed by a scalable and resilient application stack, ready to be deployed on multicore and cloud computing architectures.
a reactive application is non-blocking that is under heavy load can thus have lower latency and higher throughput than a traditional application based on blocking synchronization and communication primitives.

Why DDD?
===================================
Domain-driven design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts,

DDD's servral concepts are the Heart and Soul of OOD:

		Entities and Identity, Value Objects
		Aggregate Root
		Bounded context

Why CQRS?
===================================
CQRS: Command-query Responsibility Segregation, at its heart is a simple notion that you can use a different model to update information than the model you use to read information.

Why Jdon?
===================================
Jdon introduces reactive and event-driven into domain, using jdon, a aggregate root can act as a mailbox(like scala's Actors) that is a asynchronous and non-blocking event-sending and event-recipient metaphor.
Event is a better interactive way for aggregate root with each other, instead of directly exposing behavior and hold references to others.
and it can better protect root entity's internal state not expose. and can safely update root's state in non-blocking way [Single Writer Principle](http://www.javacodegeeks.com/2012/08/single-writer-principle.html).

Jdon moves mutable state from database to memory, and uses Aggregate Root to guard it, traditional database's data operations (by SQL or JPA/ORM) not need any more, only need send a Command or Event to drive Aggregate Root to change its mutable state by its behaviours

	@Model
	public class AggregateRootA {

		private int state = 100;

		@OnCommand("CommandtoEventA")
		public Object save(ParameterVO parameterVO) {

			//update root's state in non-blocking single thread way (Single Writer)
			this.state = parameterVO.getValue() + state;

		}

	}

Jdonframework work mode is Producer/Consumer, A producer emits to its Consumer by a asynchronous and non-blocking queue made by LMAX Disruptor's RingBuffer.
such as:

@Send("CommandtoEventA") ---> @OnCommand("CommandtoEventA")

There are two kinds of Consumer in jdon:

	@Send --> @OnCommand  (1:1 Queue)
	@Send --> @OnEvent    (1:N topic)

Difference between 'OnCommand' and 'OnEvent' is:

When a event happend otherwhere comes in a aggregate root we regard this event
as a command, and it will action a method annotated with @OnCommand,
and in this method some events will happen. and they will action those methods annotated with @OnEvent.

full example: [click here](https://github.com/banq/jdonframework/blob/master/src/test/java/com/jdon/sample/test/cqrs/a/AggregateRootA.java)

GETTING STARTED
===================================
online documents :
	English: http://en.jdon.com/
	Chinese: http://www.jdon.com/jdonframework/

In the "doc\english" directory there are all documents about how to use.

In the "doc\chinese" directory there are chinese documents about how to use.

In the "example" directory there are serveral examples that show how to use jdon, in these examples directory run 'mvn package' to get war file.

In the "JdonAccessory" directory there are struts1.x MVC and jdbc templates.

DEMO
------------------
online: http://www.jdon.com/testWeb/

RELEASE NOTES
===================================

6.8 version.

add command of CQRS:
UI ---Command---> a aggregate root ---DomainEvents---> another aggregate root/Component

A aggregate root in Jdon acts like Actors of AKKA or Erlang.

stable version download:
http://sourceforge.net/projects/jdon/files/JdonFramework/6.X_DDD/

DISTRIBUTION JAR FILES
===================================

apply jdonframework.jar to your project:
  MAVEN:

		<dependency>
			<groupId>org.jdon</groupId>
			<artifactId>jdonframework</artifactId>
			<version>6.8</version>
		</dependency>

Communication
------------------
twiiter: [@jdonframework](http://twitter.com/jdonframework)

Bugs and Feedback
------------------
For bugs, questions and discussions please use the [Github Issues](https://github.com/banq/jdonframework/issues).

LICENSE
------------------
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


text:
package org.jenkinsci.plugins.vb6.DAO;

import java.util.ArrayList;

public class CheckModificationExcludes {
	private ArrayList<String> checkModificationExclude = new ArrayList<String>();

	public ArrayList<String> getCheckModificationExclude() {
		return checkModificationExclude;
	}

	public void setCheckModificationExclude(ArrayList<String> checkModificationExclude) {
		this.checkModificationExclude = checkModificationExclude;
	}
}


text:
package com.google.javascript.jscomp.bundle;

import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.Immutable;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CompilerOptions.InstrumentOption;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.VariableRenamingPolicy;
import java.util.Optional;

/**
 * A source transformer for instrmenting code for coverage data collection.
 */
@GwtIncompatible
@Immutable
public class CoverageInstrumenter extends CompilerBasedTransformer {

  public CoverageInstrumenter(CompilerBasedTransformer.CompilerSupplier compilerSupplier) {
    super(compilerSupplier);
  }
  /**
   * Supply options for coverage.
   */
  public static class CompilerSupplier extends CompilerBasedTransformer.CompilerSupplier {
    @Override
    protected void setOptions(CompilerOptions options) {
      options.coalesceVariableNames = false;
      options.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5);
      options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_NEXT);
      options.setStrictModeInput(false);
      // Setting the path to any non-null value will trigger source map generation.
      // CompilerBasedTransformer attachs the sourcemap to the result.
      options.setSourceMapOutputPath("/dev/null");
      options.setVariableRenaming(VariableRenamingPolicy.OFF);
      options.setInstrumentForCoverageOption(InstrumentOption.LINE_ONLY);
      options.setInstrumentForCoverageOnly(true);
    }

    @Override
    public boolean transformed(Result result) {
      return true;
    }
  }

  @Override
  public Optional<String> getRuntime() {
    return Optional.empty();
  }

  @Override
  public String getTranformationName() {
    return "Coverage Instrumentation";
  }

  public static CoverageInstrumenter.CompilerSupplier compilerSupplier() {
    return new CoverageInstrumenter.CompilerSupplier();
  }

  public static final CoverageInstrumenter INSTRUMENTER =
      new CoverageInstrumenter(CoverageInstrumenter.compilerSupplier());
}


text:
package main

import (
	"context"

	managedidentities "cloud.google.com/go/managedidentities/apiv1"
	managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1"
)

func main() {
	ctx := context.Background()
	c, err := managedidentities.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &managedidentitiespb.ReconfigureTrustRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/managedidentities/v1#ReconfigureTrustRequest.
	}
	op, err := c.ReconfigureTrust(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

// [END managedidentities_v1_generated_ManagedIdentitiesService_ReconfigureTrust_sync]


text:
package dockershim

import (
	"fmt"

	dockertypes "github.com/docker/engine-api/types"
	dockercontainer "github.com/docker/engine-api/types/container"
	dockerfilters "github.com/docker/engine-api/types/filters"

	runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
)

const (
	defaultSandboxImage = "gcr.io/google_containers/pause-amd64:3.0"

	// Various default sandbox resources requests/limits.
	defaultSandboxCPUshares int64 = 2
	defaultSandboxOOMScore  int   = -999

	// Termination grace period
	defaultSandboxGracePeriod int = 10
)

// CreatePodSandbox creates a pod-level sandbox.
// The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899
// For docker, PodSandbox is implemented by a container holding the network
// namespace for the pod.
// Note: docker doesn't use LogDirectory (yet).
func (ds *dockerService) CreatePodSandbox(config *runtimeApi.PodSandboxConfig) (string, error) {
	// Step 1: Pull the image for the sandbox.
	// TODO: How should we handle pulling custom pod infra container image
	// (with credentials)?
	image := defaultSandboxImage
	if err := ds.client.PullImage(image, dockertypes.AuthConfig{}, dockertypes.ImagePullOptions{}); err != nil {
		return "", fmt.Errorf("unable to pull image for the sandbox container: %v", err)
	}

	// Step 2: Create the sandbox container.
	createConfig := makeSandboxDockerConfig(config, image)
	createResp, err := ds.client.CreateContainer(*createConfig)
	if err != nil || createResp == nil {
		return "", fmt.Errorf("failed to create a sandbox for pod %q: %v", config.GetName(), err)
	}

	// Step 3: Start the sandbox container.
	// Assume kubelet's garbage collector would remove the sandbox later, if
	// startContainer failed.
	err = ds.StartContainer(createResp.ID)
	return createResp.ID, err
}

// StopPodSandbox stops the sandbox. If there are any running containers in the
// sandbox, they should be force terminated.
func (ds *dockerService) StopPodSandbox(podSandboxID string) error {
	return ds.client.StopContainer(podSandboxID, defaultSandboxGracePeriod)
	// TODO: Stop all running containers in the sandbox.
}

// RemovePodSandbox removes the sandbox. If there are running containers in the
// sandbox, they should be forcibly removed.
func (ds *dockerService) RemovePodSandbox(podSandboxID string) error {
	return ds.client.RemoveContainer(podSandboxID, dockertypes.ContainerRemoveOptions{RemoveVolumes: true})
	// TODO: remove all containers in the sandbox.
}

// PodSandboxStatus returns the status of the PodSandbox.
func (ds *dockerService) PodSandboxStatus(podSandboxID string) (*runtimeApi.PodSandboxStatus, error) {
	// Inspect the container.
	r, err := ds.client.InspectContainer(podSandboxID)
	if err != nil {
		return nil, err
	}

	// Parse the timstamps.
	createdAt, _, _, err := getContainerTimestamps(r)
	if err != nil {
		return nil, fmt.Errorf("failed to parse timestamp for container %q: %v", podSandboxID, err)
	}
	ct := createdAt.Unix()

	// Translate container to sandbox state.
	state := runtimeApi.PodSandBoxState_NOTREADY
	if r.State.Running {
		state = runtimeApi.PodSandBoxState_READY
	}

	// TODO: We can't really get the IP address from the network plugin, which
	// is handled by kubelet as of now. Should we amend the interface? How is
	// this handled in the new remote runtime integration?
	// See DockerManager.determineContainerIP() for more details.
	// For now, just assume that there is no network plugin.
	// Related issue: https://github.com/kubernetes/kubernetes/issues/28667
	var IP string
	if r.NetworkSettings != nil {
		IP = r.NetworkSettings.IPAddress
		// Fall back to IPv6 address if no IPv4 address is present
		if IP == "" {
			IP = r.NetworkSettings.GlobalIPv6Address
		}
	}
	network := &runtimeApi.PodSandboxNetworkStatus{Ip: &IP}
	netNS := getNetworkNamespace(r)

	return &runtimeApi.PodSandboxStatus{
		Id:        &r.ID,
		Name:      &r.Name,
		State:     &state,
		CreatedAt: &ct,
		// TODO: We write annotations as labels on the docker containers. All
		// these annotations will be read back as labels. Need to fix this.
		// Also filter out labels only relevant to this shim.
		Labels:  r.Config.Labels,
		Network: network,
		Linux:   &runtimeApi.LinuxPodSandboxStatus{Namespaces: &runtimeApi.Namespace{Network: &netNS}},
	}, nil
}

// ListPodSandbox returns a list of Sandbox.
func (ds *dockerService) ListPodSandbox(filter *runtimeApi.PodSandboxFilter) ([]*runtimeApi.PodSandbox, error) {
	// By default, list all containers whether they are running or not.
	opts := dockertypes.ContainerListOptions{All: true}
	filterOutReadySandboxes := false

	opts.Filter = dockerfilters.NewArgs()
	f := newDockerFilter(&opts.Filter)
	if filter != nil {
		if filter.Name != nil {
			f.Add("name", filter.GetName())
		}
		if filter.Id != nil {
			f.Add("id", filter.GetId())
		}
		if filter.State != nil {
			if filter.GetState() == runtimeApi.PodSandBoxState_READY {
				// Only list running containers.
				opts.All = false
			} else {
				// runtimeApi.PodSandBoxState_NOTREADY can mean the
				// container is in any of the non-running state (e.g., created,
				// exited). We can't tell docker to filter out running
				// containers directly, so we'll need to filter them out
				// ourselves after getting the results.
				filterOutReadySandboxes = true
			}
		}

		if filter.LabelSelector != nil {
			for k, v := range filter.LabelSelector {
				f.AddLabel(k, v)
			}
		}
		// Filter out sandbox containers.
		f.AddLabel(containerTypeLabelKey, containerTypeLabelSandbox)
	}
	containers, err := ds.client.ListContainers(opts)
	if err != nil {
		return nil, err
	}

	// Convert docker containers to runtime api sandboxes.
	result := []*runtimeApi.PodSandbox{}
	for _, c := range containers {
		s := toRuntimeAPISandbox(&c)
		if filterOutReadySandboxes && s.GetState() == runtimeApi.PodSandBoxState_READY {
			continue
		}
		result = append(result, s)
	}
	return result, nil
}

func makeSandboxDockerConfig(c *runtimeApi.PodSandboxConfig, image string) *dockertypes.ContainerCreateConfig {
	// Merge annotations and labels because docker supports only labels.
	labels := makeLabels(c.GetLabels(), c.GetAnnotations())
	// Apply a label to distinguish sandboxes from regular containers.
	labels[containerTypeLabelKey] = containerTypeLabelSandbox

	hc := &dockercontainer.HostConfig{}
	createConfig := &dockertypes.ContainerCreateConfig{
		Name: c.GetName(),
		Config: &dockercontainer.Config{
			Hostname: c.GetHostname(),
			// TODO: Handle environment variables.
			Image:  image,
			Labels: labels,
		},
		HostConfig: hc,
	}

	// Apply linux-specific options.
	if lc := c.GetLinux(); lc != nil {
		// Apply Cgroup options.
		// TODO: Check if this works with per-pod cgroups.
		hc.CgroupParent = lc.GetCgroupParent()

		// Apply namespace options.
		hc.NetworkMode, hc.UTSMode, hc.PidMode = "", "", ""
		nsOpts := lc.GetNamespaceOptions()
		if nsOpts != nil {
			if nsOpts.GetHostNetwork() {
				hc.NetworkMode = namespaceModeHost
			} else {
				// Assume kubelet uses either the cni or the kubenet plugin.
				// TODO: support docker networking.
				hc.NetworkMode = "none"
			}
			if nsOpts.GetHostIpc() {
				hc.IpcMode = namespaceModeHost
			}
			if nsOpts.GetHostPid() {
				hc.PidMode = namespaceModeHost
			}
		}
	}
	// Set port mappings.
	exposedPorts, portBindings := makePortsAndBindings(c.GetPortMappings())
	createConfig.Config.ExposedPorts = exposedPorts
	hc.PortBindings = portBindings

	// Set DNS options.
	if dnsOpts := c.GetDnsOptions(); dnsOpts != nil {
		hc.DNS = dnsOpts.GetServers()
		hc.DNSSearch = dnsOpts.GetSearches()
	}

	// Apply resource options.
	setSandboxResources(c.GetResources(), hc)

	// Set security options.
	hc.SecurityOpt = []string{getSeccompOpts()}

	return createConfig
}

func setSandboxResources(_ *runtimeApi.PodSandboxResources, hc *dockercontainer.HostConfig) {
	// Ignore the resource requests and limits for now and just use the docker
	// defaults.
	// TODO: apply resource limits based on the configuration.
	hc.Resources = dockercontainer.Resources{
		MemorySwap: -1, // Always disable memory swap.
		CPUShares:  defaultSandboxCPUshares,
		// Use docker's default cpu quota/period.
	}
	hc.OomScoreAdj = defaultSandboxOOMScore
}


text:
package org.lodder.subtools.sublibrary.data.tvdb;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

import org.lodder.subtools.sublibrary.Language;
import org.lodder.subtools.sublibrary.Manager;
import org.lodder.subtools.sublibrary.data.tvdb.exception.TheTvdbException;
import org.lodder.subtools.sublibrary.data.tvdb.model.TheTvdbEpisode;
import org.lodder.subtools.sublibrary.data.tvdb.model.TheTvdbSerie;
import org.lodder.subtools.sublibrary.util.OptionalExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uwetrottmann.thetvdb.TheTvdb;
import com.uwetrottmann.thetvdb.entities.Episode;
import com.uwetrottmann.thetvdb.entities.EpisodesResponse;
import com.uwetrottmann.thetvdb.entities.Series;
import com.uwetrottmann.thetvdb.entities.SeriesResponse;
import com.uwetrottmann.thetvdb.entities.SeriesResultsResponse;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.experimental.ExtensionMethod;
import retrofit2.Response;

@ExtensionMethod({ OptionalExtension.class })
public class TheTvdbApi {

    private static final Logger LOGGER = LoggerFactory.getLogger(TheTvdbApi.class);
    @Getter(value = AccessLevel.PRIVATE)
    private final Manager manager;
    private final TheTvdb theTvdb;

    public TheTvdbApi(Manager manager, String apikey) {
        this.manager = manager;
        this.theTvdb = new TheTvdb(apikey);
    }

    public List<TheTvdbSerie> getSeries(String seriename, Language language) throws TheTvdbException {
        return getManager().valueBuilder()
                .memoryCache()
                .key("%s-series-%s-%s".formatted("TVDB", seriename, language))
                .collectionSupplier(TheTvdbSerie.class, () -> {
                    String encodedSerieName = URLEncoder.encode(seriename.toLowerCase().replace(" ", "-"), StandardCharsets.UTF_8);
                    try {
                        Response<SeriesResultsResponse> response =
                                theTvdb.search().series(encodedSerieName, null, null, null, language == null ? null : language.getLangCode())
                                        .execute();
                        if (response.isSuccessful()) {
                            return response.body().data.stream().map(series -> seriesToTVDBSerie(series, language)).toList();
                        }
                        return List.of();
                    } catch (IOException e) {
                        throw new TheTvdbException(e);
                    }
                }).getCollection();
    }

    public Optional<TheTvdbSerie> getSerie(int tvdbId, Language language) throws TheTvdbException {
        try {
            Response<SeriesResponse> response =
                    theTvdb.series()
                            .series(tvdbId, language == null ? null : language.getLangCode())
                            .execute();
            if (response.isSuccessful()) {
                return Optional.of(seriesToTVDBSerie(response.body().data, language));
            }
            return Optional.empty();
        } catch (IOException e) {
            throw new TheTvdbException(e);
        }
    }

    public Optional<TheTvdbEpisode> getEpisode(int tvdbId, int season, int episode, Language language) throws TheTvdbException {
        return getManager().valueBuilder()
                .memoryCache()
                .key("%s-episode-%s-%s-%s-%s".formatted("TVDB", tvdbId, season, episode, language))
                .optionalSupplier(() -> {
                    try {
                        Response<EpisodesResponse> response =
                                theTvdb.series().episodesQuery(tvdbId, null, season, episode, null, null, null, null, null,
                                        language == null ? null : language.getLangCode()).execute();
                        if (response.isSuccessful()) {
                            return response.body().data.stream().map(serie -> episodeToTVDBEpisode(serie, language)).findFirst();
                        }
                        throw new TheTvdbException(response.errorBody().string());
                    } catch (IOException e) {
                        throw new TheTvdbException(e);
                    }
                }).getOptional();
    }

    private TheTvdbSerie seriesToTVDBSerie(Series serie, Language lang) {
        TheTvdbSerie TheTVDBSerie = new TheTvdbSerie();

        TheTVDBSerie.setId(serie.id);
        TheTVDBSerie.setAirsDayOfWeek(serie.airsDayOfWeek);
        TheTVDBSerie.setAirsTime(serie.airsTime);
        TheTVDBSerie.setContentRating(serie.rating);
        TheTVDBSerie.setFirstAired(serie.firstAired);
        TheTVDBSerie.setGenres(serie.genre);
        TheTVDBSerie.setImdbId(serie.imdbId);
        TheTVDBSerie.setLanguage(lang);
        TheTVDBSerie.setNetwork(serie.network);
        // TheTVDBSerie.setOverview(serie.overview);
        TheTVDBSerie.setRating(serie.rating);
        TheTVDBSerie.setRuntime(serie.runtime);
        // TheTVDBSerie.setSerieId(toString(serie.id));
        TheTVDBSerie.setSerieName(serie.seriesName);
        TheTVDBSerie.setStatus(serie.status);

        return TheTVDBSerie;
    }

    private TheTvdbEpisode episodeToTVDBEpisode(Episode episode, Language lang) {
        TheTvdbEpisode tvdbEpisode = new TheTvdbEpisode();

        tvdbEpisode.setId(toString(episode.id));
        tvdbEpisode.setDvdEpisodeNumber(toString(episode.dvdEpisodeNumber));
        tvdbEpisode.setDvdSeason(toString(episode.dvdSeason));
        tvdbEpisode.setEpisodeName(episode.episodeName);
        tvdbEpisode.setEpisodeNumber(episode.airedEpisodeNumber);
        tvdbEpisode.setFirstAired(episode.firstAired);
        tvdbEpisode.setLanguage(lang);
        // tvdbEpisode.setOverview(episode.language.overview);
        tvdbEpisode.setSeasonNumber(episode.airedSeason);
        tvdbEpisode.setAbsoluteNumber(toString(episode.absoluteNumber));
        tvdbEpisode.setLastUpdated(toString(episode.lastUpdated));
        tvdbEpisode.setSeasonId(toString(episode.airedSeasonID));
        tvdbEpisode.setAirsAfterSeason(0);
        tvdbEpisode.setAirsBeforeEpisode(0);

        return tvdbEpisode;
    }

    private String toString(Object value) {
        return value != null ? value.toString() : null;
    }

}


text:
package trends;

import java.util.Comparator;

public class MeanComparator implements Comparator<Graph> {

	  public int compare(Graph g1, Graph g2) {
	    return g2.getMean().compareTo(g1.getMean());
	  }

	}


text:
module Luchadeer
  class Error < StandardError

    # http://www.giantbomb.com/api/documentation#toc-0-0
    module Codes
      OK                     = 1
      INVALID_API_KEY        = 100
      OBJECT_NOT_FOUND       = 101
      URL_FORMAT_ERROR       = 102
      FILTER_ERROR           = 104
      SUBSCRIBER_ONLY        = 105
    end

    # Used for bespoke status codes returned in the response body
    def self.api_errors
      {
        Codes::INVALID_API_KEY  => Luchadeer::Error::InvalidAPIKey,
        Codes::OBJECT_NOT_FOUND => Luchadeer::Error::NotFound,
        Codes::URL_FORMAT_ERROR => Luchadeer::Error::URLFormatError,
        Codes::FILTER_ERROR     => Luchadeer::Error::FilterError,
        Codes::SUBSCRIBER_ONLY  => Luchadeer::Error::SubscriberOnly
      }
    end

    # Used for HTTP status codes
    def self.http_errors
      {
        400 => Luchadeer::Error::BadRequest,
        404 => Luchadeer::Error::NotFound,
        500 => Luchadeer::Error::InternalServerError,
        502 => Luchadeer::Error::InternalServerError, # unconfirmed
        503 => Luchadeer::Error::InternalServerError, # unconfirmed
        504 => Luchadeer::Error::InternalServerError, # unconfirmed
      }
    end

    %w[RedirectLimitReached RequestTimeout InvalidAPIKey URLFormatError FilterError
    SubscriberOnly BadRequest NotFound InternalServerError ].each do |e|
      const_set e, Class.new(Luchadeer::Error)
    end

  end
end


text:
package instagram

import (
	"fmt"
	"net/http"
	"reflect"
	"testing"
)

func TestLikesService_MediaLikes(t *testing.T) {
	setup()
	defer teardown()

	mux.HandleFunc("/media/1/likes", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		fmt.Fprint(w, `{"data": [{"id":"1"}]}`)
	})

	users, err := client.Likes.MediaLikes("1")
	if err != nil {
		t.Errorf("Likes.MediaLikes returned error: %v", err)
	}

	want := []User{User{ID: "1"}}
	if !reflect.DeepEqual(users, want) {
		t.Errorf("Likes.MediaLikes returned %+v, want %+v", users, want)
	}
}

func TestLikesService_Like(t *testing.T) {
	setup()
	defer teardown()

	mux.HandleFunc("/media/1/likes", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "POST")
		fmt.Fprint(w, `{"meta": {"code": 200}, "data": null}`)
	})

	err := client.Likes.Like("1")
	if err != nil {
		t.Errorf("Likes.Like returned error: %v", err)
	}
}

func TestLikesService_Unlike(t *testing.T) {
	setup()
	defer teardown()

	mux.HandleFunc("/media/1/likes", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "DELETE")
		fmt.Fprint(w, `{"meta": {"code": 200}, "data": null}`)
	})

	err := client.Likes.Unlike("1")
	if err != nil {
		t.Errorf("Likes.Unlike returned error: %v", err)
	}
}


text:
using namespace std;

Game* Game::instance = 0;

Game::~Game()
{
	gameObjects.clear();
}

bool Game::init(const char* title, int xPos, int yPos, int width, int height, int flags)
{
	if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
	{
		cout << "SDL_Init: success\n";

		window = SDL_CreateWindow(title, xPos, yPos, width, height, flags);

		this->_WINDOW_WIDTH = width;
		this->_WINDOW_HEIGHT = height;

		if (window != 0)
		{
			cout << "SDL_CreateWindow: success\n";
			renderer = SDL_CreateRenderer(window, -1, 0);

			if (renderer != 0)
			{
				cout << "SDL_CreateRenderer: success\n";
				//SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);

				initGameObjects();
			}
			else
			{
				cout << "SDL_CreateRenderer: fail\n";
				return false;
			}
		}
		else
		{
			cout << "SDL_CreateWindow: fail\n";
			return false;
		}
	}
	else
	{
		cout << "SDL_Init: fail\n";
		return false;
	}

	running = true;

	return true;
}

void Game::initGameObjects()
{
	// Here you would load all of the game objects and add them to the gameObjects vector
	gameObjects[enumUtility::Main_Menu] = new MainMenu(new LoaderParameters(0, 0, 600, 600, 0, 0, "mainMenu"));
	gameObjects[enumUtility::Character_Editor] = new CharacterEditor(new LoaderParameters(0, 0, 600, 600, 0, 0, "characterEditor"));
	gameObjects[enumUtility::Map_Editor] = new MapEditor(new LoaderParameters(0, 0, 600, 600, 0, 0, "mapEditor"));
	gameObjects[enumUtility::Game_Main] = new GameEngine(new LoaderParameters(0, 0, 600, 600, 0, 0, "gameEngine"));
}

void Game::render()
{
	SDL_RenderClear(renderer);
	switch(currentView){
		case enumUtility::Main_Menu:
			// If the view is main menu, then we display it.
			((MainMenu*)gameObjects[enumUtility::Main_Menu])->draw();
			break;
		case enumUtility::Character_Editor:
			// If the view is main menu, then we display it.
			((CharacterEditor*)gameObjects[enumUtility::Character_Editor])->draw();
			break;
		case enumUtility::Map_Editor:
			// If the current view is the map editor, then we display it.
			((MapEditor*)gameObjects[enumUtility::Map_Editor])->draw();
			break;
		case enumUtility::Game_Main:
			// If the current view is the map editor, then we display it.
			((GameEngine*)gameObjects[enumUtility::Game_Main])->draw();
			break;
	}
	SDL_RenderPresent(renderer);
}

void Game::handleEvents()
{
	InputHandler::getInstance()->update();

	switch(currentView){
		case enumUtility::Main_Menu:
			// If the current view is the main menu, then we update it / handle events.
			((MainMenu*)gameObjects[enumUtility::Main_Menu])->handleEvents();
			break;
		case enumUtility::Character_Editor:
			// If the current view is the main menu, then we update it / handle events.
			((CharacterEditor*)gameObjects[enumUtility::Character_Editor])->handleEvents();
			break;
		case enumUtility::Map_Editor:
			// If the current view is the map editor, then we display it.
			((MapEditor*)gameObjects[enumUtility::Map_Editor])->handleEvents();
			break;
		case enumUtility::Game_Main:
			// If the current view is the map editor, then we display it.
			((GameEngine*)gameObjects[enumUtility::Game_Main])->handleEvents();
			break;
	}

	InputHandler::getInstance()->reset();
}

void Game::clean()
{
	cout << "Cleaning the game\n";
	SDL_DestroyWindow(window);
	SDL_DestroyRenderer(renderer);
	TTF_Quit();
	SDL_Quit();
}

void Game::quit()
{
	running = false;
}

bool Game::isRunning()
{
	return running;
}

SDL_Renderer* Game::getRenderer() const
{
	return renderer;
}

Game* Game::getInstance()
{
	if (instance == nullptr)
	{
		instance = new Game();
	}
	return instance;
}
void Game::setCurrentView(enumUtility::gameView currentView)
{
	this->currentView = currentView;
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: grpc/instrumentation/v1alpha/monitoring.proto

package io.grpc.instrumentation.v1alpha;

public interface StatsResponseOrBuilder extends
    // @@protoc_insertion_point(interface_extends:grpc.instrumentation.v1alpha.StatsResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * A StatsResponse can optionally contain the MeasurementDescriptor and
   * ViewDescriptor for the View. These will be sent in the first WatchStats
   * response, or all GetStats and GetCanonicalRpcStats responses. These will
   * not be set for {Get,Watch}Stats if
   * dont_include_descriptors_in_first_response is set to true in the
   * StatsRequest.
   *

   *
   * .google.instrumentation.MeasurementDescriptor measurement_descriptor = 1;
   */
  boolean hasMeasurementDescriptor();
  /**
   *

   * A StatsResponse can optionally contain the MeasurementDescriptor and
   * ViewDescriptor for the View. These will be sent in the first WatchStats
   * response, or all GetStats and GetCanonicalRpcStats responses. These will
   * not be set for {Get,Watch}Stats if
   * dont_include_descriptors_in_first_response is set to true in the
   * StatsRequest.
   *

   *
   * .google.instrumentation.MeasurementDescriptor measurement_descriptor = 1;
   */
  com.google.instrumentation.stats.proto.CensusProto.MeasurementDescriptor getMeasurementDescriptor();
  /**
   *

   * A StatsResponse can optionally contain the MeasurementDescriptor and
   * ViewDescriptor for the View. These will be sent in the first WatchStats
   * response, or all GetStats and GetCanonicalRpcStats responses. These will
   * not be set for {Get,Watch}Stats if
   * dont_include_descriptors_in_first_response is set to true in the
   * StatsRequest.
   *

   *
   * .google.instrumentation.MeasurementDescriptor measurement_descriptor = 1;
   */
  com.google.instrumentation.stats.proto.CensusProto.MeasurementDescriptorOrBuilder getMeasurementDescriptorOrBuilder();

  /**
   * .google.instrumentation.ViewDescriptor view_descriptor = 2;
   */
  boolean hasViewDescriptor();
  /**
   * .google.instrumentation.ViewDescriptor view_descriptor = 2;
   */
  com.google.instrumentation.stats.proto.CensusProto.ViewDescriptor getViewDescriptor();
  /**
   * .google.instrumentation.ViewDescriptor view_descriptor = 2;
   */
  com.google.instrumentation.stats.proto.CensusProto.ViewDescriptorOrBuilder getViewDescriptorOrBuilder();

  /**
   *

   * The View data.
   *

   *
   * .google.instrumentation.View view = 3;
   */
  boolean hasView();
  /**
   *

   * The View data.
   *

   *
   * .google.instrumentation.View view = 3;
   */
  com.google.instrumentation.stats.proto.CensusProto.View getView();
  /**
   *

   * The View data.
   *

   *
   * .google.instrumentation.View view = 3;
   */
  com.google.instrumentation.stats.proto.CensusProto.ViewOrBuilder getViewOrBuilder();
}


text:
// Generated by LiveScript 1.4.0

(function(){
  Polymer({
    'is': 'cs-system-admin-languages',
    behaviors: [cs.Polymer.behaviors.Language('system_admin_languages_'), cs.Polymer.behaviors.admin.System.settings],
    properties: {
      settings_api_url: 'api/System/admin/languages'
    }
  });
}).call(this);


text:
using System;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Sql.Models;

namespace Microsoft.WindowsAzure.Management.Sql.Models
{
    /// <summary>
    /// Contains the response to the Create Recover Database Operation request.
    /// </summary>
    public partial class RecoverDatabaseOperationCreateResponse : OperationResponse
    {
        private RecoverDatabaseOperation _operation;

        /// <summary>
        /// Optional. Gets or sets the operation that has been returned from a
        /// Create Recover Database Operation request.
        /// </summary>
        public RecoverDatabaseOperation Operation
        {
            get { return this._operation; }
            set { this._operation = value; }
        }

        /// <summary>
        /// Initializes a new instance of the
        /// RecoverDatabaseOperationCreateResponse class.
        /// </summary>
        public RecoverDatabaseOperationCreateResponse()
        {
        }
    }
}


text:
<!-- Please fill in the below table to describe your issue -->

| Title               | Description
| --------------------|------------
| Version             | <!-- Version of bolt in which issue is detected , not required for feature request -->
| Type                | <!-- Is this a feature Request or Issue -->
| node                | <!-- Version of node, please see contributing guide to know the recommended node version -->
| Operating System    | <!-- Please mention the OS in which issue is observed, not required for feature request -->
| Short Description   | <!-- short desciption of the issue or feature Request -->
| Detailed description| <!-- Detailed description of the issue or feature Request -->


text:
class CreateConfigurations < ActiveRecord::Migration
  def self.up
    create_table :configurations do |t|
      t.string :config_key
      t.string :config_value
    end
    create_default
  end

  def self.down
    drop_table :configurations
  end

  def self.create_default
    Configuration.create :config_key => "SchoolCollegeName", :config_value => ""
    Configuration.create :config_key => "StudentAttendanceType", :config_value => "Daily"
    Configuration.create :config_key => "AcademicYearID", :config_value => "1"
    Configuration.create :config_key => "CurrencyType", :config_value =>""
  end

end


text:
raspberrypi-sandbox
===================

Simple sandbox for testing functionality on the RaspberryPI.


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.quickblox.ui.kit.chatmessage.adapter">

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true">

        <meta-data
            android:name="com.quickblox.ui.kit.chatmessage.adapter.media.video.thumbnails.VideoThumbnailModule"
            android:value="GlideModule" />
    </application>

</manifest>