text:
namespace ObscureWare.Console.Tests
{
    using System;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using Xunit;

    public class ColoringVisualTests
    {
        private const string TEST_ROOT = @"C:\\TestResults\\ConsoleColors\\";

        // This is obviously not possible to programmatically verify how "close" were colors matched - it's all manual testing required...
        // Therefore - help pages will be rendered for default and some customized results

        [Fact]
        public void PrintDefaultColorsTest()
        {
            string fName = "default_setup.html";
            using (var colorHelper = CloseColorFinder.GetDefault())
            {
                PrintAllNamedColorsToHtml(colorHelper, fName);
            }
        }

        [Fact]
        public void PrintCustomizedColorsBySeba()
        {
            string fName = "custom_setup_seba.html";
            using (var colorHelper = CloseColorFinder.CustomizedDefault(
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkCyan, Color.Chocolate),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Blue, Color.DodgerBlue),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Yellow, Color.Gold),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkBlue, Color.MidnightBlue)))
            {
                PrintAllNamedColorsToHtml(colorHelper, fName);
            }
        }

        [Fact]
        public void PrintCustomizedColorsByDnv()
        {
            var converter = new ColorConverter();

            string fName = "custom_setup_dnv.html";
            using (
                var colorHelper = CloseColorFinder.CustomizedDefault(
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Cyan, (Color)converter.ConvertFromString("#99d9f0")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkCyan, (Color)converter.ConvertFromString("#e98300")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Blue, (Color)converter.ConvertFromString("#009fda")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Yellow, (Color)converter.ConvertFromString("#fecb00")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkGreen, (Color)converter.ConvertFromString("#36842d")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Blue, (Color)converter.ConvertFromString("#003591")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.Magenta, (Color)converter.ConvertFromString("#635091")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkRed, (Color)converter.ConvertFromString("#c4262e")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkBlue, (Color)converter.ConvertFromString("#0f204b")),
                    new Tuple<ConsoleColor, Color>(ConsoleColor.DarkGray, (Color)converter.ConvertFromString("#988f86"))))
            {
                PrintAllNamedColorsToHtml(colorHelper, fName);
            }
        }

        private static void PrintAllNamedColorsToHtml(CloseColorFinder helper, string fName)
        {
            var props = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public)
                    .Where(p => p.PropertyType == typeof(Color));

            var colorsVersionAtt = typeof(CloseColorFinder).Assembly.GetCustomAttributes().FirstOrDefault(att => att is AssemblyFileVersionAttribute) as AssemblyFileVersionAttribute;
            string colorsVersion = colorsVersionAtt?.Version ?? "unknown";

            var dir = $"{TEST_ROOT}{colorsVersion}\\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var path = Path.Combine(dir, fName);

            using (var tw = new StreamWriter(path))
            {
                tw.WriteLine("
");
                tw.WriteLine("
ColorName	Sys Color	Console Color
");

                foreach (var propertyInfo in props)
                {
                    tw.WriteLine("
");

                    Color c = (Color)propertyInfo.GetValue(null);
                    ConsoleColor cc = helper.FindClosestColor(c);

                    Color cCol = helper.GetCurrentConsoleColor(cc);
                    var ccName = Enum.GetName(typeof(ConsoleColor), cc);

                    tw.WriteLine($"{propertyInfo.Name}	{c.Name}	{ccName}	");
                    tw.WriteLine("
");
                }

                tw.WriteLine("
");
                tw.Close();
            }
        }
    }
}


text:
package org.locationtech.geowave.core.store.adapter.annotation;

import java.lang.annotation.Inherited;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Annotation for GeoWave field annotations. This annotation provides a way to convert the annotated
 * field into a field descriptor.
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface GeoWaveFieldAnnotation {
  Class<? extends AnnotatedFieldDescriptorBuilder> fieldDescriptorBuilder();
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.polygene.sample.rental.domain;

import java.time.LocalDate;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.value.ValueComposite;

public interface Period
    extends ValueComposite
{
    Property<LocalDate> startOfPeriod();

    Property<LocalDate> endOfPeriod();
}


text:
Originally published: 2011-02-10 14:00:13
Last updated: 2011-02-10 14:00:13
Author: Jiri Zahradil

You run this script with directory as parameter (defaults to current directory) and scripts watch this directory for changes in files - creating new file, deleting some file and modification to any file. All these changes are periodically commited to subversion repository using external commands.

Not especially good for coding but great for tracking changes in your text files f.e. during essay writing etc.


text:
import sys
import json
import asyncio

from .core import Bot, run
from .utils import load_plugin

def main():
    """
    CLI entrypoint for testing.
    """
    _, config, *args = sys.argv
    with open(config, 'r') as fd:
        bot_config = json.load(fd)

    bots = []

    for config in bot_config:

        params = config.get('params') or {}
        daemons = config.get('daemons')

        bot = Bot(config.get("key"), daemons=daemons, **params)
        for plugin in config.get("plugins", []):
            bot.listen(plugin)

        bots.append(bot)

    run(*bots)

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_bar_progress_spinner"
        android:showAsAction="always"
        android:background="@null"
        android:selectableItemBackground="@null"
        android:actionLayout="@layout/action_bar_progress_spinner_layout"/>
    <item android:id="@+id/refresh"
        android:title="@string/menu_refresh"
        android:showAsAction="always"
        android:icon="@drawable/ic_menu_refresh"/>
    <item android:id="@+id/menu_plus_one"
        android:showAsAction="always"
        android:icon="@drawable/ic_menu_plus1"/>
</menu>


text:
//-----------------------------------------------------------------------
// <copyright file="GraphZipWithNSpec.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 System;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;

namespace Akka.Streams.Tests.Dsl
{
    public class GraphZipWithNSpec : TwoStreamsSetup<int>
    {
        public GraphZipWithNSpec(ITestOutputHelper helper) : base(helper)
        {
        }

        protected override Fixture CreateFixture(GraphDsl.Builder<NotUsed> builder) => new ZipWithNFixture(builder);

        private sealed class ZipWithNFixture : Fixture
        {
            public ZipWithNFixture(GraphDsl.Builder<NotUsed> builder) : base(builder)
            {
                var zip = builder.Add(new ZipWithN<int, int>(ints => ints.Sum(), 2));
                Left = zip.In(0);
                Right = zip.In(1);
                Out = zip.Out;
            }

            public override Inlet<int> Left { get; }

            public override Inlet<int> Right { get; }

            public override Outlet<int> Out { get; }
        }

        [Fact]
        public void ZipWithN_must_work_in_the_happy_case()
        {
            var probe = this.CreateManualSubscriberProbe<int>();

            RunnableGraph.FromGraph(GraphDsl.Create(b =>
            {
                var zip = b.Add(new ZipWithN<int, int>(ints => ints.Sum(), 2));

                b.From(Source.From(Enumerable.Range(1, 4))).To(zip.In(0));
                b.From(Source.From(new[] {10, 20, 30, 40})).To(zip.In(1));

                b.From(zip.Out).To(Sink.FromSubscriber(probe));
                return ClosedShape.Instance;
            })).Run(Materializer);

            var subscription = probe.ExpectSubscription();
            subscription.Request(2);
            probe.ExpectNext(11);
            probe.ExpectNext(22);

            subscription.Request(1);
            probe.ExpectNext(33);
            subscription.Request(1);
            probe.ExpectNext(44);

            probe.ExpectComplete();
        }

        [Fact]
        public void ZipWithN_must_work_in_the_sad_case()
        {
            var probe = this.CreateManualSubscriberProbe<int>();

            RunnableGraph.FromGraph(GraphDsl.Create(b =>
            {
                var zip = b.Add(new ZipWithN<int, int>(ints => ints.Aggregate(1, (i, i1) => i / i1), 2));

                b.From(Source.From(Enumerable.Range(1, 4))).To(zip.In(0));
                b.From(Source.From(Enumerable.Range(-2, 5))).To(zip.In(1));

                b.From(zip.Out).To(Sink.FromSubscriber(probe));
                return ClosedShape.Instance;
            })).Run(Materializer);

            var subscription = probe.ExpectSubscription();
            subscription.Request(2);
            probe.ExpectNext(1 / 1 / -2);
            probe.ExpectNext(1 / 2 / -1);

            EventFilter.Exception<DivideByZeroException>().ExpectOne(() => subscription.Request(2));

            probe.ExpectError().Should().BeOfType<DivideByZeroException>();
            probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
        }

        [Fact]
        public void ZipWithN_must_work_with_one_immediately_completed_and_one_nonempty_publisher()
        {
            var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
            subscriber1.ExpectSubscriptionAndComplete();

            var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>());
            subscriber2.ExpectSubscriptionAndComplete();
        }

        [Fact]
        public void ZipWithN_must_work_with_one_delayed_completed_and_one_nonempty_publisher()
        {
            var subscriber1 = Setup(SoonToCompletePublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
            subscriber1.ExpectSubscriptionAndComplete();

            var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToCompletePublisher<int>());
            subscriber2.ExpectSubscriptionAndComplete();
        }

        [Fact]
        public void ZipWithN_must_work_with_one_immediately_failed_and_one_nonempty_publisher()
        {
            var subscriber1 = Setup(FailedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
            subscriber1.ExpectSubscriptionAndError();

            var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), FailedPublisher<int>());
            subscriber2.ExpectSubscriptionAndError();
        }

        [Fact]
        public void ZipWithN_must_work_with_one_delayed_failed_and_one_nonempty_publisher()
        {
            var subscriber1 = Setup(SoonToFailPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
            subscriber1.ExpectSubscriptionAndError();

            var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToFailPublisher<int>());
            subscriber2.ExpectSubscriptionAndError();
        }

        [Fact]
        public void ZipWithN_must_work_with_3_inputs()
        {
            var probe = this.CreateManualSubscriberProbe<int>();

            RunnableGraph.FromGraph(GraphDsl.Create(b =>
            {
                var zip = b.Add(new ZipWithN<int, int>(ints => ints.Sum(), 3));

                b.From(Source.Single(1)).To(zip.In(0));
                b.From(Source.Single(2)).To(zip.In(1));
                b.From(Source.Single(3)).To(zip.In(2));

                b.From(zip.Out).To(Sink.FromSubscriber(probe));
                return ClosedShape.Instance;
            })).Run(Materializer);

            var subscription = probe.ExpectSubscription();
            subscription.Request(5);
            probe.ExpectNext(6);

            probe.ExpectComplete();
        }

        [Fact]
        public void ZipWithN_must_work_with_30_inputs()
        {
            var probe = this.CreateManualSubscriberProbe<int>();

            RunnableGraph.FromGraph(GraphDsl.Create(b =>
            {
                var zip = b.Add(new ZipWithN<int, int>(ints => ints.Sum(), 30));

                foreach (var i in Enumerable.Range(0, 30))
                    b.From(Source.Single(i)).To(zip.In(i));

                b.From(zip.Out).To(Sink.FromSubscriber(probe));
                return ClosedShape.Instance;
            })).Run(Materializer);

            var subscription = probe.ExpectSubscription();
            subscription.Request(1);
            probe.ExpectNext(Enumerable.Range(0, 30).Sum());

            probe.ExpectComplete();
        }
    }
}


text:
package com.android.server;

import com.android.server.am.ActivityManagerService;
import com.android.server.power.PowerManagerService;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.util.EventLog;
import android.util.Log;
import android.util.Slog;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

/** This class calls its monitor every minute. Killing this process if they don't return **/
public class Watchdog extends Thread {
    static final String TAG = "Watchdog";
    static final boolean localLOGV = false || false;

    // Set this to true to use debug default values.
    static final boolean DB = false;

    // Set this to true to have the watchdog record kernel thread stacks when it fires
    static final boolean RECORD_KERNEL_THREADS = true;

    static final int MONITOR = 2718;

    static final int TIME_TO_RESTART = DB ? 15*1000 : 60*1000;
    static final int TIME_TO_WAIT = TIME_TO_RESTART / 2;

    static final int MEMCHECK_DEFAULT_MIN_SCREEN_OFF = DB ? 1*60 : 5*60;   // 5 minutes
    static final int MEMCHECK_DEFAULT_MIN_ALARM = DB ? 1*60 : 3*60;        // 3 minutes
    static final int MEMCHECK_DEFAULT_RECHECK_INTERVAL = DB ? 1*60 : 5*60; // 5 minutes

    static final int REBOOT_DEFAULT_INTERVAL = DB ? 1 : 0;                 // never force reboot
    static final int REBOOT_DEFAULT_START_TIME = 3*60*60;                  // 3:00am
    static final int REBOOT_DEFAULT_WINDOW = 60*60;                        // within 1 hour

    static final String REBOOT_ACTION = "com.android.service.Watchdog.REBOOT";

    static final String[] NATIVE_STACKS_OF_INTEREST = new String[] {
        "/system/bin/mediaserver",
        "/system/bin/sdcard",
        "/system/bin/surfaceflinger"
    };

    static Watchdog sWatchdog;

    /* This handler will be used to post message back onto the main thread */
    final Handler mHandler;
    final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
    ContentResolver mResolver;
    BatteryService mBattery;
    PowerManagerService mPower;
    AlarmManagerService mAlarm;
    ActivityManagerService mActivity;
    boolean mCompleted;
    boolean mForceKillSystem;
    Monitor mCurrentMonitor;

    int mPhonePid;

    final Calendar mCalendar = Calendar.getInstance();
    int mMinScreenOff = MEMCHECK_DEFAULT_MIN_SCREEN_OFF;
    int mMinAlarm = MEMCHECK_DEFAULT_MIN_ALARM;
    boolean mNeedScheduledCheck;
    PendingIntent mCheckupIntent;
    PendingIntent mRebootIntent;

    long mBootTime;
    int mRebootInterval;

    boolean mReqRebootNoWait;     // should wait for one interval before reboot?
    int mReqRebootInterval = -1;  // >= 0 if a reboot has been requested
    int mReqRebootStartTime = -1; // >= 0 if a specific start time has been requested
    int mReqRebootWindow = -1;    // >= 0 if a specific window has been requested
    int mReqMinScreenOff = -1;    // >= 0 if a specific screen off time has been requested
    int mReqMinNextAlarm = -1;    // >= 0 if specific time to next alarm has been requested
    int mReqRecheckInterval= -1;  // >= 0 if a specific recheck interval has been requested

    /**
     * Used for scheduling monitor callbacks and checking memory usage.
     */
    final class HeartbeatHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MONITOR: {
                    // See if we should force a reboot.
                    int rebootInterval = mReqRebootInterval >= 0
                            ? mReqRebootInterval : REBOOT_DEFAULT_INTERVAL;
                    if (mRebootInterval != rebootInterval) {
                        mRebootInterval = rebootInterval;
                        // We have been running long enough that a reboot can
                        // be considered...
                        checkReboot(false);
                    }

                    final int size = mMonitors.size();
                    for (int i = 0 ; i < size ; i++) {
                        mCurrentMonitor = mMonitors.get(i);
                        mCurrentMonitor.monitor();
                    }

                    synchronized (Watchdog.this) {
                        mCompleted = true;
                        mCurrentMonitor = null;
                    }
                } break;
            }
        }
    }

    final class RebootReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context c, Intent intent) {
            if (localLOGV) Slog.v(TAG, "Alarm went off, checking reboot.");
            checkReboot(true);
        }
    }

    final class RebootRequestReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context c, Intent intent) {
            mReqRebootNoWait = intent.getIntExtra("nowait", 0) != 0;
            mReqRebootInterval = intent.getIntExtra("interval", -1);
            mReqRebootStartTime = intent.getIntExtra("startTime", -1);
            mReqRebootWindow = intent.getIntExtra("window", -1);
            mReqMinScreenOff = intent.getIntExtra("minScreenOff", -1);
            mReqMinNextAlarm = intent.getIntExtra("minNextAlarm", -1);
            mReqRecheckInterval = intent.getIntExtra("recheckInterval", -1);
            EventLog.writeEvent(EventLogTags.WATCHDOG_REQUESTED_REBOOT,
                    mReqRebootNoWait ? 1 : 0, mReqRebootInterval,
                            mReqRecheckInterval, mReqRebootStartTime,
                    mReqRebootWindow, mReqMinScreenOff, mReqMinNextAlarm);
            checkReboot(true);
        }
    }

    public interface Monitor {
        void monitor();
    }

    public static Watchdog getInstance() {
        if (sWatchdog == null) {
            sWatchdog = new Watchdog();
        }

        return sWatchdog;
    }

    private Watchdog() {
        super("watchdog");
        mHandler = new HeartbeatHandler();
    }

    public void init(Context context, BatteryService battery,
            PowerManagerService power, AlarmManagerService alarm,
            ActivityManagerService activity) {
        mResolver = context.getContentResolver();
        mBattery = battery;
        mPower = power;
        mAlarm = alarm;
        mActivity = activity;

        context.registerReceiver(new RebootReceiver(),
                new IntentFilter(REBOOT_ACTION));
        mRebootIntent = PendingIntent.getBroadcast(context,
                0, new Intent(REBOOT_ACTION), 0);

        context.registerReceiver(new RebootRequestReceiver(),
                new IntentFilter(Intent.ACTION_REBOOT),
                android.Manifest.permission.REBOOT, null);

        mBootTime = System.currentTimeMillis();
    }

    public void processStarted(String name, int pid) {
        synchronized (this) {
            if ("com.android.phone".equals(name)) {
                mPhonePid = pid;
            }
        }
    }

    public void addMonitor(Monitor monitor) {
        synchronized (this) {
            if (isAlive()) {
                throw new RuntimeException("Monitors can't be added while the Watchdog is running");
            }
            mMonitors.add(monitor);
        }
    }

    void checkReboot(boolean fromAlarm) {
        int rebootInterval = mReqRebootInterval >= 0 ? mReqRebootInterval
                : REBOOT_DEFAULT_INTERVAL;
        mRebootInterval = rebootInterval;
        if (rebootInterval <= 0) {
            // No reboot interval requested.
            if (localLOGV) Slog.v(TAG, "No need to schedule a reboot alarm!");
            mAlarm.remove(mRebootIntent);
            return;
        }

        long rebootStartTime = mReqRebootStartTime >= 0 ? mReqRebootStartTime
                : REBOOT_DEFAULT_START_TIME;
        long rebootWindowMillis = (mReqRebootWindow >= 0 ? mReqRebootWindow
                : REBOOT_DEFAULT_WINDOW) * 1000;
        long recheckInterval = (mReqRecheckInterval >= 0 ? mReqRecheckInterval
                : MEMCHECK_DEFAULT_RECHECK_INTERVAL) * 1000;

        retrieveBrutalityAmount();

        long realStartTime;
        long now;

        synchronized (this) {
            now = System.currentTimeMillis();
            realStartTime = computeCalendarTime(mCalendar, now,
                    rebootStartTime);

            long rebootIntervalMillis = rebootInterval*24*60*60*1000;
            if (DB || mReqRebootNoWait ||
                    (now-mBootTime) >= (rebootIntervalMillis-rebootWindowMillis)) {
                if (fromAlarm && rebootWindowMillis <= 0) {
                    // No reboot window -- just immediately reboot.
                    EventLog.writeEvent(EventLogTags.WATCHDOG_SCHEDULED_REBOOT, now,
                            (int)rebootIntervalMillis, (int)rebootStartTime*1000,
                            (int)rebootWindowMillis, "");
                    rebootSystem("Checkin scheduled forced");
                    return;
                }

                // Are we within the reboot window?
                if (now < realStartTime) {
                    // Schedule alarm for next check interval.
                    realStartTime = computeCalendarTime(mCalendar,
                            now, rebootStartTime);
                } else if (now < (realStartTime+rebootWindowMillis)) {
                    String doit = shouldWeBeBrutalLocked(now);
                    EventLog.writeEvent(EventLogTags.WATCHDOG_SCHEDULED_REBOOT, now,
                            (int)rebootInterval, (int)rebootStartTime*1000,
                            (int)rebootWindowMillis, doit != null ? doit : "");
                    if (doit == null) {
                        rebootSystem("Checked scheduled range");
                        return;
                    }

                    // Schedule next alarm either within the window or in the
                    // next interval.
                    if ((now+recheckInterval) >= (realStartTime+rebootWindowMillis)) {
                        realStartTime = computeCalendarTime(mCalendar,
                                now + rebootIntervalMillis, rebootStartTime);
                    } else {
                        realStartTime = now + recheckInterval;
                    }
                } else {
                    // Schedule alarm for next check interval.
                    realStartTime = computeCalendarTime(mCalendar,
                            now + rebootIntervalMillis, rebootStartTime);
                }
            }
        }

        if (localLOGV) Slog.v(TAG, "Scheduling next reboot alarm for "
                + ((realStartTime-now)/1000/60) + "m from now");
        mAlarm.remove(mRebootIntent);
        mAlarm.set(AlarmManager.RTC_WAKEUP, realStartTime, mRebootIntent);
    }

    /**
     * Perform a full reboot of the system.
     */
    void rebootSystem(String reason) {
        Slog.i(TAG, "Rebooting system because: " + reason);
        PowerManagerService pms = (PowerManagerService) ServiceManager.getService("power");
        pms.reboot(false, reason, false);
    }

    /**
     * Load the current Gservices settings for when
     * {@link #shouldWeBeBrutalLocked} will allow the brutality to happen.
     * Must not be called with the lock held.
     */
    void retrieveBrutalityAmount() {
        mMinScreenOff = (mReqMinScreenOff >= 0 ? mReqMinScreenOff
                : MEMCHECK_DEFAULT_MIN_SCREEN_OFF) * 1000;
        mMinAlarm = (mReqMinNextAlarm >= 0 ? mReqMinNextAlarm
                : MEMCHECK_DEFAULT_MIN_ALARM) * 1000;
    }

    /**
     * Determine whether it is a good time to kill, crash, or otherwise
     * plunder the current situation for the overall long-term benefit of
     * the world.
     *
     * @param curTime The current system time.
     * @return Returns null if this is a good time, else a String with the
     * text of why it is not a good time.
     */
    String shouldWeBeBrutalLocked(long curTime) {
        if (mBattery == null || !mBattery.isPowered(BatteryManager.BATTERY_PLUGGED_ANY)) {
            return "battery";
        }

        if (mMinScreenOff >= 0 && (mPower == null ||
                mPower.timeSinceScreenWasLastOn() < mMinScreenOff)) {
            return "screen";
        }

        if (mMinAlarm >= 0 && (mAlarm == null ||
                mAlarm.timeToNextAlarm() < mMinAlarm)) {
            return "alarm";
        }

        return null;
    }

    static long computeCalendarTime(Calendar c, long curTime,
            long secondsSinceMidnight) {

        // start with now
        c.setTimeInMillis(curTime);

        int val = (int)secondsSinceMidnight / (60*60);
        c.set(Calendar.HOUR_OF_DAY, val);
        secondsSinceMidnight -= val * (60*60);
        val = (int)secondsSinceMidnight / 60;
        c.set(Calendar.MINUTE, val);
        c.set(Calendar.SECOND, (int)secondsSinceMidnight - (val*60));
        c.set(Calendar.MILLISECOND, 0);

        long newTime = c.getTimeInMillis();
        if (newTime < curTime) {
            // The given time (in seconds since midnight) has already passed for today, so advance
            // by one day (due to daylight savings, etc., the delta may differ from 24 hours).
            c.add(Calendar.DAY_OF_MONTH, 1);
            newTime = c.getTimeInMillis();
        }

        return newTime;
    }

    @Override
    public void run() {
        boolean waitedHalf = false;
        while (true) {
            mCompleted = false;
            mHandler.sendEmptyMessage(MONITOR);

            synchronized (this) {
                long timeout = TIME_TO_WAIT;

                // NOTE: We use uptimeMillis() here because we do not want to increment the time we
                // wait while asleep. If the device is asleep then the thing that we are waiting
                // to timeout on is asleep as well and won't have a chance to run, causing a false
                // positive on when to kill things.
                long start = SystemClock.uptimeMillis();
                while (timeout > 0 && !mForceKillSystem) {
                    try {
                        wait(timeout);  // notifyAll() is called when mForceKillSystem is set
                    } catch (InterruptedException e) {
                        Log.wtf(TAG, e);
                    }
                    timeout = TIME_TO_WAIT - (SystemClock.uptimeMillis() - start);
                }

                if (mCompleted && !mForceKillSystem) {
                    // The monitors have returned.
                    waitedHalf = false;
                    continue;
                }

                if (!waitedHalf) {
                    // We've waited half the deadlock-detection interval.  Pull a stack
                    // trace and wait another half.
                    ArrayList<Integer> pids = new ArrayList<Integer>();
                    pids.add(Process.myPid());
                    ActivityManagerService.dumpStackTraces(true, pids, null, null,
                            NATIVE_STACKS_OF_INTEREST);
                    waitedHalf = true;
                    continue;
                }
            }

            // If we got here, that means that the system is most likely hung.
            // First collect stack traces from all threads of the system process.
            // Then kill this process so that the system will restart.

            final String name = (mCurrentMonitor != null) ?
                    mCurrentMonitor.getClass().getName() : "null";
            EventLog.writeEvent(EventLogTags.WATCHDOG, name);

            ArrayList<Integer> pids = new ArrayList<Integer>();
            pids.add(Process.myPid());
            if (mPhonePid > 0) pids.add(mPhonePid);
            // Pass !waitedHalf so that just in case we somehow wind up here without having
            // dumped the halfway stacks, we properly re-initialize the trace file.
            final File stack = ActivityManagerService.dumpStackTraces(
                    !waitedHalf, pids, null, null, NATIVE_STACKS_OF_INTEREST);

            // Give some extra time to make sure the stack traces get written.
            // The system's been hanging for a minute, another second or two won't hurt much.
            SystemClock.sleep(2000);

            // Pull our own kernel thread stacks as well if we're configured for that
            if (RECORD_KERNEL_THREADS) {
                dumpKernelStackTraces();
            }

            // Try to add the error to the dropbox, but assuming that the ActivityManager
            // itself may be deadlocked.  (which has happened, causing this statement to
            // deadlock and the watchdog as a whole to be ineffective)
            Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
                    public void run() {
                        mActivity.addErrorToDropBox(
                                "watchdog", null, "system_server", null, null,
                                name, null, stack, null);
                    }
                };
            dropboxThread.start();
            try {
                dropboxThread.join(2000);  // wait up to 2 seconds for it to return.
            } catch (InterruptedException ignored) {}

            // Only kill the process if the debugger is not attached.
            if (!Debug.isDebuggerConnected()) {
                Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + name);
                Process.killProcess(Process.myPid());
                System.exit(10);
            } else {
                Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
            }

            waitedHalf = false;
        }
    }

    private File dumpKernelStackTraces() {
        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
        if (tracesPath == null || tracesPath.length() == 0) {
            return null;
        }

        native_dumpKernelStacks(tracesPath);
        return new File(tracesPath);
    }

    private native void native_dumpKernelStacks(String tracesPath);
}


text:
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
 * \brief DTK_STKMeshEntity.cpp
 * \author Stuart R. Slattery
 * \brief STK mesh entity interface.
 */
//---------------------------------------------------------------------------//

#include "DTK_STKMeshEntity.hpp"
#include "DTK_STKMeshEntityImpl.hpp"

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Constructor.
STKMeshEntity::STKMeshEntity(
    const stk::mesh::Entity &stk_entity,
    const Teuchos::Ptr<stk::mesh::BulkData> &bulk_data )
{
    this->b_entity_impl =
        Teuchos::rcp( new STKMeshEntityImpl( stk_entity, bulk_data ) );
}

//---------------------------------------------------------------------------//

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//
// end DTK_Entity.cpp
//---------------------------------------------------------------------------//


text:
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { FlatButton } from 'material-ui';
import AppBar from 'material-ui/AppBar';
import styles from './Layout.scss';
import Icon from '../../../icons/icons';

class _Layout extends React.Component {
  render() {
    return (

          <AppBar
            title="Hugo Nasciutti App"
            iconElementRight={<FlatButton label="About" href="http://localhost:3000/about" />}
          />

          {this.props.children}

              <Icon className={styles.dribbbleLogo} glyph={Icon.GLYPHS.dribbbleLogo} />

            Hugo Nasciutti © 2017

    );
  }
}

_Layout.propTypes = {
  children: PropTypes.element.isRequired,
};

const mapStateToProps = () => ({
});

const mapActionsToProps = {
};

const Layout = connect(mapStateToProps, mapActionsToProps)(_Layout);

export default Layout;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Routing;

namespace Ceeji.FastWeb {
    /// <summary>
    /// 使用 FastWeb 引擎处理 Http 请求的 HttpHandler。
    /// </summary>
    public class FastWebHttpHandler : IHttpHandler, IRouteHandler {
        /// <summary>
        /// 创建使用 FastWeb 引擎处理 Http 请求的 HttpHandler。
        /// </summary>
        public FastWebHttpHandler(RequestProcesser func) {
            mFunc = func;
        }

        #region IHttpHandler 成员

        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context) {
            // 确保禁用输出缓存
            context.Response.Buffer = false;
            context.Response.BufferOutput = false;

            HtmlResponse r = new HtmlResponse(DefaultTitle);
            mFunc(context, r);

            r.WriteToStream(context.Response.OutputStream, HtmlOutputFormat.Zipped, 0);
            context.Response.OutputStream.Flush();
            context.Response.End();
        }

        #endregion

        #region IRouteHandler 成员

        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            return this;
        }

        #endregion

        /// <summary>
        /// 获取或设置页面的默认标题。
        /// </summary>
        public static string DefaultTitle { get; set; }

        private RequestProcesser mFunc;
    }

    /// <summary>
    /// 处理请求的委托。
    /// </summary>
    /// <param name="context"></param>
    /// <param name="response"></param>
    public delegate void RequestProcesser(HttpContext context, HtmlResponse response);
}


text:
/*
 * 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.
 */
package com.facebook.presto.orc.metadata.statistics;

import org.apache.hive.common.util.Murmur3;
import org.testng.annotations.Test;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;

import static org.testng.Assert.assertEquals;

public class TestMurmur3
{
    private static final int SEED = 123;

    @Test
    public void testHashCodeM3_64()
    {
        byte[] origin = ("It was the best of times, it was the worst of times," +
                " it was the age of wisdom, it was the age of foolishness," +
                " it was the epoch of belief, it was the epoch of incredulity," +
                " it was the season of Light, it was the season of Darkness," +
                " it was the spring of hope, it was the winter of despair," +
                " we had everything before us, we had nothing before us," +
                " we were all going direct to Heaven," +
                " we were all going direct the other way.").getBytes(StandardCharsets.UTF_8);
        long hash = BloomFilter.Murmur3.hash64(origin, 0, origin.length);
        assertEquals(305830725663368540L, hash);
        assertEquals(hash, Murmur3.hash64(origin, 0, origin.length));

        byte[] originOffset = new byte[origin.length + 150];
        Arrays.fill(originOffset, (byte) 123);
        System.arraycopy(origin, 0, originOffset, 150, origin.length);
        hash = BloomFilter.Murmur3.hash64(originOffset, 150, origin.length);
        assertEquals(305830725663368540L, hash);
        assertEquals(hash, Murmur3.hash64(originOffset, 150, origin.length));
    }

    @Test
    public void test64()
    {
        ByteBuffer shortBuffer = ByteBuffer.allocate(Short.BYTES);
        ByteBuffer intBuffer = ByteBuffer.allocate(Integer.BYTES);
        ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES);
        Random rdm = new Random(SEED);
        for (int i = 0; i < 1_000_000; ++i) {
            long ln = rdm.nextLong();
            int in = rdm.nextInt();
            short sn = (short) (rdm.nextInt(2 * Short.MAX_VALUE - 1) - Short.MAX_VALUE);
            float fn = rdm.nextFloat();
            double dn = rdm.nextDouble();
            shortBuffer.putShort(0, sn);
            assertEquals(Murmur3.hash64(shortBuffer.array()), BloomFilter.Murmur3.hash64(shortBuffer.array()));
            intBuffer.putInt(0, in);
            assertEquals(Murmur3.hash64(intBuffer.array()), BloomFilter.Murmur3.hash64(intBuffer.array()));
            longBuffer.putLong(0, ln);
            assertEquals(Murmur3.hash64(longBuffer.array()), BloomFilter.Murmur3.hash64(longBuffer.array()));
            intBuffer.putFloat(0, fn);
            assertEquals(Murmur3.hash64(intBuffer.array()), BloomFilter.Murmur3.hash64(intBuffer.array()));
            longBuffer.putDouble(0, dn);
            assertEquals(Murmur3.hash64(longBuffer.array()), BloomFilter.Murmur3.hash64(longBuffer.array()));
        }
    }
}


text:
package com.solambda.swiffer.api.internal.decisions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

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

import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.model.Decision;
import com.amazonaws.services.simpleworkflow.model.DecisionType;
import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest;
import com.solambda.swiffer.api.Decisions;

public class DecisionExecutorImpl implements DecisionExecutor {
	private static final Logger LOGGER = LoggerFactory.getLogger(DecisionExecutorImpl.class);

	/**
	 * List of decisions that close the workflow.
	 */
	private static final List<String> CLOSE_DECISIONS = Arrays.asList(DecisionType.CancelWorkflowExecution.name(),
																	  DecisionType.CompleteWorkflowExecution.name(),
																	  DecisionType.FailWorkflowExecution.name(),
																	  DecisionType.ContinueAsNewWorkflowExecution.name());
	/**
	 * Evaluates if specified decision is the close workflow decision.
	 */
	private static final Predicate<Decision> isCloseDecision = d -> CLOSE_DECISIONS.contains(d.getDecisionType());

	/**
	 * List of decisions that could be added with close the workflow decision.
	 */
	private static final List<String> COMPATIBLE_WITH_CLOSE = Arrays.asList(DecisionType.CancelTimer.name(),
																			DecisionType.RecordMarker.name(),
																			DecisionType.StartChildWorkflowExecution.name(),
																			DecisionType.RequestCancelExternalWorkflowExecution.name());

	private AmazonSimpleWorkflow swf;

	public DecisionExecutorImpl(final AmazonSimpleWorkflow swf) {
		super();
		this.swf = swf;
	}

	@Override
	public void apply(final DecisionTaskContext context, final Decisions decisions) {
		LOGGER.debug("Receive {} decisions: {}", ((DecisionsImpl) decisions).get().size(), decisions);

		final Collection<Decision> decisionList = normalize(((DecisionsImpl) decisions).get());
		LOGGER.debug("Responding SWF with {} decisions: {}", decisionList.size(), decisionList);

		this.swf.respondDecisionTaskCompleted(new RespondDecisionTaskCompletedRequest()
													  .withDecisions(decisionList)
													  // FIXME: why and how to get it ? (appart from externally ?)
													  // .withExecutionContext(executionContext)
													  .withTaskToken(context.taskToken()));
	}

	/**
	 * Filter list of received decisions leaving only ones that could be processed without errors.
	 * Decisions could be removed from the list only if one of the close decisions is present:
	 *

	 *
remove all decisions after first close decision,

	 *
remove decisions incompatible with close.

	 *

	 *
	 * @param decisions list of decisions received after task processing
	 * @return list of decisions that could be executed without validation errors
	 * @see #CLOSE_DECISIONS
	 * @see #COMPATIBLE_WITH_CLOSE
	 */
	private List<Decision> normalize(List<Decision> decisions) {
		if (decisions.stream().anyMatch(isCloseDecision)) {
			List<Decision> normalized = new ArrayList<>();
			boolean alreadyClosed = false;
			for (Decision decision : decisions) {
				String decisionType = decision.getDecisionType();
				if (alreadyClosed) {
					LOGGER.warn("Close must be last decision in list, skip decision {}.", decision);
				} else {
					if (CLOSE_DECISIONS.contains(decisionType)) {
						normalized.add(decision);
						alreadyClosed = true;
					} else {
						if (COMPATIBLE_WITH_CLOSE.contains(decisionType)) {
							normalized.add(decision);
						} else {
							LOGGER.warn("Close decision is incompatible with this decision, skip decision {}.", decision);
						}
					}
				}
			}

			return normalized;
		}

		return new ArrayList<>(decisions);
	}
}


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

using System;

namespace Microsoft.Azure.Management.DataFactories
{
    public interface IDataFactoryManagementClient : IDisposable
    {
        /// <summary>
        /// The URI used as the base for all Service Management requests.
        /// </summary>
        Uri BaseUri { get; set; }

        /// <summary>
        /// When you create a Windows Azure subscription, it is uniquely
        /// identified by a subscription ID. The subscription ID forms part of
        /// the URI for every call that you make to the Service Management
        /// API. The Windows Azure Service ManagementAPI use mutual
        /// authentication of management certificates over SSL to ensure that
        /// a request made to the service is secure. No anonymous requests are
        /// allowed.
        /// </summary>
        SubscriptionCloudCredentials Credentials { get; set; }

        /// <summary>
        /// Operations for managing data factory ActivityTypes.
        /// </summary>
        IActivityTypeOperations ActivityTypes { get; }

        /// <summary>
        /// Operations for managing data factory ComputeTypes.
        /// </summary>
        IComputeTypeOperations ComputeTypes { get; }

        /// <summary>
        /// Operations for managing data factories.
        /// </summary>
        IDataFactoryOperations DataFactories { get; }

        /// <summary>
        /// Operations for managing data slices.
        /// </summary>
        IDataSliceOperations DataSlices { get; }

        /// <summary>
        /// Operations for managing data slice runs.
        /// </summary>
        IDataSliceRunOperations DataSliceRuns { get; }

        /// <summary>
        /// Operations for managing data factory gateways.
        /// </summary>
        IGatewayOperations Gateways { get; }

        /// <summary>
        /// Operations for managing hubs.
        /// </summary>
        IHubOperations Hubs { get; }

        /// <summary>
        /// Operations for managing data factory linkedServices.
        /// </summary>
        ILinkedServiceOperations LinkedServices { get; }

        /// <summary>
        /// Operations for managing pipelines.
        /// </summary>
        IPipelineOperations Pipelines { get; }

        /// <summary>
        /// Operations for managing tables.
        /// </summary>
        ITableOperations Tables { get; }
    }
}


text:
cask 'font-wire-one' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/wireone/WireOne.ttf'
  name 'Wire One'
  homepage 'http://www.google.com/fonts/specimen/Wire+One'

  font 'WireOne.ttf'
end


text:
### Concept ###

As soon as a challenge is configured into your Scoreflex account, using
challenges becomes possible. The word challenge is a generic term in the
Scoreflex world, subdivised in `ChallengeConfiguration`, `ChallengeRequest`,
`ChallengeTurn` and `ChallengeInstance`.
The object mainly manipulated by Javascript games is the `ChallengeInstance`.
When the word "challenge" is used, it often refer to a challenge instance.

A `ChallengeInstance` object is particularly useful for:
- Submitting a player's turn (a score, a move ... depending on your gameplay)
- Get details on the challenge (who are the participants, the previous turns ...)
- Display the challenge current and final state (who won the challenge?)

### Getting a ChallengeInstance object ###

The main way to get a `ChallengeInstance` is to listen for
`ScoreflexChallengeEvent`. Such an event is fired when the current player
press "Play challenge" in a Scoreflex challenge web view.

````javascript
var scoreflexEventHandler = function(event) {
  var detail = event.detail || {};
  var name = detail.name;
  if (name === "challenge") {
    var challengeInstance = detail.challenge;
  }
};
window.addEventListener("ScoreflexEvent", scoreflexEventHandler, false);
````

If you don't use the Scoreflex web view, you can still get a `ChallengeInstance`
object manually (The SDK may assist you in this task soon).

````javascript
var scoreflex = Scoreflex(/* ... */);

var getFirstInstance = function(Obj) {
  // traverse all instances and find the first one
  var type, configId, instances, i;
  for (type in data) {
    for (configId in data[type]) {
      instances = data[type][configId];
      if (instances.length > 0) {
        return scoreflex.Challenges.get(instances[0].id, configId);
      }
    }
  }
  return null;
};

var onGetAllInstances = function() {
  var data = this.reponseJSON;
  var challengeInstance = getFirstInstance(data);
  if (challengeInstance) {
    // now use the challengeInstance
  }
}

// Request all challenge instances of the current player
scoreflex.RestClient.get(
  "/challenges/instances",
  {types:["yourTurn"]},
  {onload:onGetAllInstances}
);
````

### Working with a ChallengeInstance object ###

The `ChallengeInstance` object provides methods to get details about the challenge,
such as the players and the played turns. Methods to update the challenge by
sending a new turn for the player are also available.

Read the tutoral on handlers for more details on handlers.

````javascript
/* Submit a turn */

// -- get the current player's id
var currentPlayerId = scoreflex.Players.getCurrent().getId();

// -- prepare the turn's body
var body = {};
// Set the turn score for this player
body.score = 800;
// Indicate the player ended the challenge (and cannot send new turn)
body.instance = {participants: {}};
body.instance.participants[currentPlayerId] = {status: "FINISHED"};

// -- submit the turn
challengeInstance.submitTurn(
  body,
  {},
  {onload: function() { ... }}
);
````

````javascript
/* Submit a score only */
var score = 800;
challengeInstance.submitTurnScore(
  score,
  {},
  {onload: function() { ... }}
);
````

````javascript
/* Display the challenge current state in web view */
challengeInstance.showDetails();
````


text:
namespace Contract
{
    public class MuxJob : FFmpegJob
    {
        public override JobType Type => JobType.Mux;
    }
}


text:
module TCS
  class SideViewController < UIViewController
    alias :'super_init' :'init'

    attr_accessor :sideControllerSize
    attr_reader :mainController
    attr_reader :sideController

    def initWithMainController(mainController, sideController: sideController, side: side)
      super_init.tap do
        raise ArgumentError, "Invalid value for side: #{side}" unless [:left, :right, :top, :bottom].include? side
        @mainController = mainController
        @sideController = sideController
        @side = side
        @sideControllerSize ||= @sideController.view.frame.size

        self.view.autoresizesSubviews = false

        @sideController.view.frame = sideViewRect
        @mainController.view.frame = mainViewRect

        self.addChildViewController(@sideController)
        @sideController.didMoveToParentViewController(self)
        self.addChildViewController(@mainController)
        @mainController.didMoveToParentViewController(self)

        self.view.addSubview(@sideController.view)
        self.view.addSubview(@mainController.view)
      end
    end

    def viewWillAppear(animated)
      super

      @sideController.view.frame = sideViewRect
      @mainController.view.frame = mainViewRect
    end

    def opened?
      @opened.nil? ? false : @opened
    end

    def opened=(opened)
      @opened = opened

      @sideController.view.frame = sideViewRect unless @sideController.nil?
      @mainController.view.frame = mainViewRect unless @mainController.nil?
    end

    def showSideView
      @opened = true
      UIView.animateWithDuration(
          0.25,
          animations: lambda {
            @mainController.view.frame = mainViewRect(false)
          },
          completion: lambda { |finished|
            @mainController.view.frame = mainViewRect
          })
    end

    def hideSideView
      @opened = false
      UIView.animateWithDuration(
          0.25,
          animations: lambda {
            @mainController.view.frame = mainViewRect
          })
    end

    def willAnimateRotationToInterfaceOrientation(interfaceOrientation, duration:duration)
      @sideController.view.frame = sideViewRect
      @mainController.view.frame = mainViewRect
      super
    end

    protected

    def sideViewRect

      case @side
        when :left
          CGRectMake(0, 0, @sideControllerSize.width, self.view.size.height)
        when :right
          CGRectMake(self.view.frame.size.width - @sideControllerSize.width,
                     0,
                     @sideControllerSize.width,
                     self.view.frame.size.height)
        when :top
          CGRectMake(0, 0, self.view.frame.size.width, @sideControllerSize.height)
        when :bottom
          CGRectMake(0,
                     self.view.frame.size.height - @sideControllerSize.height,
                     self.view.frame.size.width,
                     @sideControllerSize.height)
        else
          raise ArgumentError, "Invalid side #{@side}"
      end
    end

    def mainViewRect(resize = true)
      return self.view.bounds unless opened?

      sizeSelf = self.view.frame.size
      sizeMain = if resize
                   CGSizeMake(sizeSelf.width - @sideControllerSize.width,
                              sizeSelf.height - @sideControllerSize.height)
                 else
                   self.view.frame.size
                 end

      case @side
        when :left
          CGRectMake(@sideControllerSize.width, 0, sizeMain.width, sizeSelf.height)
        when :right
          CGRectMake(0, 0, sizeMain.width, sizeSelf.height)
        when :top
          CGRectMake(0, @sideControllerSize.height, sizeSelf.width, sizeMain.height)
        when :bottom
          CGRectMake(0, 0, sizeSelf.width, sizeMain.height)
        else
          raise ArgumentError, "Invalid side #{@side}"
      end
    end
  end

end


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

namespace TestingWithXUnit
{
    using Xunit;

    public class Assertions
    {
        [Fact]
        public void Asert_Examples()
        {
            Assert.Equal(1, 1);
            Assert.Equal("London", "London");

            Assert.StartsWith("Lon", "London");
            Assert.EndsWith("on", "London");

            Assert.Contains("Lon", "London");
            Assert.DoesNotContain("Bern", "London");

            Assert.Empty(new List<int>());
            Assert.NotEmpty(new List<int>(){1,2,3});

            Assert.True(1 == 1);
            Assert.False(1 == 2);

            Assert.Null(null);
            Assert.NotNull("a");

            Exception ex = Assert.Throws<ArgumentNullException>(() => MyMethod());

            Assert.InRange(5, 1, 10);
            Assert.NotInRange(-1, 0, 10);
        }

        [Fact]
        public async Task Assert_Example_Async()
        {
            await Assert.ThrowsAsync<Exception>(() => throw new Exception("name"));
        }

        private void MyMethod()
        {
            throw new ArgumentNullException(paramName: "first");
        }
    }
}


text:
export SCRIPT_NAME="pep8"
export SCRIPT_HELP="PEP8 analysis."
[[ "$GOGO_GOSH_SOURCE" -eq 1 ]] && return 0

# Normal script execution starts here.
./pep8.sh


text:
package uk.ac.surrey.xw.multichooser

import java.awt.BorderLayout.CENTER

import org.nlogo.api.LogoList
import org.nlogo.api.LogoList.toIterator
import org.nlogo.window.GUIWorkspace

import javax.swing.BorderFactory
import javax.swing.JList
import javax.swing.JScrollPane
import javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
import uk.ac.surrey.xw.api.IntegerProperty
import uk.ac.surrey.xw.api.LabeledPanelWidget
import uk.ac.surrey.xw.api.LabeledPanelWidgetKind
import uk.ac.surrey.xw.api.ListProperty
import uk.ac.surrey.xw.api.State
import uk.ac.surrey.xw.api.WidgetKey
import uk.ac.surrey.xw.api.swing.LogoObjectListCellRenderer
import uk.ac.surrey.xw.api.swing.enrichJList

class MultiChooserKind[W <: MultiChooser] extends LabeledPanelWidgetKind[W] {

  override val name = "MULTI-CHOOSER"
  override val newWidget = new MultiChooser(_, _, _)

  override val heightProperty = new IntegerProperty[W](
    "HEIGHT", Some(_.setHeight(_)), _.getHeight, 100)

  private def items(jl: JList) =
    (0 until jl.getModel.getSize).map(jl.getModel.getElementAt)

  val selectedItemsProperty = new ListProperty[W](
    "SELECTED-ITEMS",
    Some((w, xs) ⇒ {
      val _items = items(w.jList)
      w.jList.setSelectedIndices(
        xs.map(x ⇒ _items.indexOf(x)).filterNot(_ == -1).toArray
      )
    }),
    w ⇒ LogoList(w.jList.getSelectedValues: _*)
  )

  val itemsProperty = new ListProperty[W](
    "ITEMS",
    Some((w, xs) ⇒ {
      w.jList.setListData(xs.toVector.toArray)
    }),
    w ⇒ LogoList(items(w.jList): _*)
  )

  override def propertySet = super.propertySet ++ Set(
    selectedItemsProperty, itemsProperty
  )

  override def defaultProperty = Some(selectedItemsProperty)
}

class MultiChooser(
  val key: WidgetKey,
  val state: State,
  val ws: GUIWorkspace)
  extends LabeledPanelWidget {

  override val kind = new MultiChooserKind[this.type]

  val jList = new JList() {
    setSelectionMode(MULTIPLE_INTERVAL_SELECTION)
    setBorder(BorderFactory.createRaisedBevelBorder)
  }
  add(new JScrollPane(jList), CENTER)

  /* Use a custom renderer so Dump.logoObject is used instead of toString */
  jList.setCellRenderer(new LogoObjectListCellRenderer)

  jList.onValueChanged { event ⇒
    if (!event.getValueIsAdjusting)
      updateInState(kind.selectedItemsProperty)
  }
}


text:
package apple.coredata;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSError;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.NSURL;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * An instance of NSPersistentContainer includes all objects needed to represent a functioning Core Data stack, and
 * provides convenience methods and properties for common patterns.
 */
@Generated
@Library("CoreData")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class NSPersistentContainer extends NSObject {
    static {
        NatJ.register();
    }

    @Generated
    protected NSPersistentContainer(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native NSPersistentContainer alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native NSPersistentContainer allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("defaultDirectoryURL")
    public static native NSURL defaultDirectoryURL();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native NSPersistentContainer new_objc();

    @Generated
    @Selector("persistentContainerWithName:")
    public static native NSPersistentContainer persistentContainerWithName(String name);

    @Generated
    @Selector("persistentContainerWithName:managedObjectModel:")
    public static native NSPersistentContainer persistentContainerWithNameManagedObjectModel(String name,
            NSManagedObjectModel model);

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    @Generated
    @Selector("init")
    public native NSPersistentContainer init();

    /**
     * Creates a container using the model named `name` in the main bundle
     */
    @Generated
    @Selector("initWithName:")
    public native NSPersistentContainer initWithName(String name);

    @Generated
    @Selector("initWithName:managedObjectModel:")
    public native NSPersistentContainer initWithNameManagedObjectModel(String name, NSManagedObjectModel model);

    /**
     * Load stores from the storeDescriptions property that have not already been successfully added to the container.
     * The completion handler is called once for each store that succeeds or fails.
     */
    @Generated
    @Selector("loadPersistentStoresWithCompletionHandler:")
    public native void loadPersistentStoresWithCompletionHandler(
            @ObjCBlock(name = "call_loadPersistentStoresWithCompletionHandler") Block_loadPersistentStoresWithCompletionHandler block);

    @Generated
    @Selector("managedObjectModel")
    public native NSManagedObjectModel managedObjectModel();

    @Generated
    @Selector("name")
    public native String name();

    @Generated
    @Selector("newBackgroundContext")
    public native NSManagedObjectContext newBackgroundContext();

    @Generated
    @Selector("performBackgroundTask:")
    public native void performBackgroundTask(
            @ObjCBlock(name = "call_performBackgroundTask") Block_performBackgroundTask block);

    @Generated
    @Selector("persistentStoreCoordinator")
    public native NSPersistentStoreCoordinator persistentStoreCoordinator();

    @Generated
    @Selector("persistentStoreDescriptions")
    public native NSArray<? extends NSPersistentStoreDescription> persistentStoreDescriptions();

    @Generated
    @Selector("setPersistentStoreDescriptions:")
    public native void setPersistentStoreDescriptions(NSArray<? extends NSPersistentStoreDescription> value);

    @Generated
    @Selector("viewContext")
    public native NSManagedObjectContext viewContext();

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_loadPersistentStoresWithCompletionHandler {
        @Generated
        void call_loadPersistentStoresWithCompletionHandler(NSPersistentStoreDescription arg0, NSError arg1);
    }

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_performBackgroundTask {
        @Generated
        void call_performBackgroundTask(NSManagedObjectContext arg0);
    }
}


text:
require 'spec_helper'
require 'click/observer'

describe Click::Observer do
  it 'can be included into a class and then attached for callbacks' do
    mod = described_class
    klass = Class.new do
      include mod
    end

    expect {
      clicker = Click::Clicker.new('test')
      clicker.add_observer(klass.new)
      clicker.click!
    }.not_to raise_error
  end
end


text:
package repository

import (
	"restic"
	"sync"

	"restic/errors"

	"restic/debug"
)

// MasterIndex is a collection of indexes and IDs of chunks that are in the process of being saved.
type MasterIndex struct {
	idx      []*Index
	idxMutex sync.RWMutex
}

// NewMasterIndex creates a new master index.
func NewMasterIndex() *MasterIndex {
	return &MasterIndex{}
}

// Lookup queries all known Indexes for the ID and returns the first match.
func (mi *MasterIndex) Lookup(id restic.ID, tpe restic.BlobType) (blobs []restic.PackedBlob, err error) {
	mi.idxMutex.RLock()
	defer mi.idxMutex.RUnlock()

	debug.Log("looking up id %v, tpe %v", id.Str(), tpe)

	for _, idx := range mi.idx {
		blobs, err = idx.Lookup(id, tpe)
		if err == nil {
			debug.Log("MasterIndex.Lookup",
				"found id %v: %v", id.Str(), blobs)
			return
		}
	}

	debug.Log("id %v not found in any index", id.Str())
	return nil, errors.Errorf("id %v not found in any index", id)
}

// LookupSize queries all known Indexes for the ID and returns the first match.
func (mi *MasterIndex) LookupSize(id restic.ID, tpe restic.BlobType) (uint, error) {
	mi.idxMutex.RLock()
	defer mi.idxMutex.RUnlock()

	for _, idx := range mi.idx {
		length, err := idx.LookupSize(id, tpe)
		if err == nil {
			return length, nil
		}
	}

	return 0, errors.Errorf("id %v not found in any index", id)
}

// ListPack returns the list of blobs in a pack. The first matching index is
// returned, or nil if no index contains information about the pack id.
func (mi *MasterIndex) ListPack(id restic.ID) (list []restic.PackedBlob) {
	mi.idxMutex.RLock()
	defer mi.idxMutex.RUnlock()

	for _, idx := range mi.idx {
		list := idx.ListPack(id)
		if len(list) > 0 {
			return list
		}
	}

	return nil
}

// Has queries all known Indexes for the ID and returns the first match.
func (mi *MasterIndex) Has(id restic.ID, tpe restic.BlobType) bool {
	mi.idxMutex.RLock()
	defer mi.idxMutex.RUnlock()

	for _, idx := range mi.idx {
		if idx.Has(id, tpe) {
			return true
		}
	}

	return false
}

// Count returns the number of blobs of type t in the index.
func (mi *MasterIndex) Count(t restic.BlobType) (n uint) {
	mi.idxMutex.RLock()
	defer mi.idxMutex.RUnlock()

	var sum uint
	for _, idx := range mi.idx {
		sum += idx.Count(t)
	}

	return sum
}

// Insert adds a new index to the MasterIndex.
func (mi *MasterIndex) Insert(idx *Index) {
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	mi.idx = append(mi.idx, idx)
}

// Remove deletes an index from the MasterIndex.
func (mi *MasterIndex) Remove(index *Index) {
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	for i, idx := range mi.idx {
		if idx == index {
			mi.idx = append(mi.idx[:i], mi.idx[i+1:]...)
			return
		}
	}
}

// Store remembers the id and pack in the index.
func (mi *MasterIndex) Store(pb restic.PackedBlob) {
	mi.idxMutex.RLock()
	for _, idx := range mi.idx {
		if !idx.Final() {
			mi.idxMutex.RUnlock()
			idx.Store(pb)
			return
		}
	}

	mi.idxMutex.RUnlock()
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	newIdx := NewIndex()
	newIdx.Store(pb)
	mi.idx = append(mi.idx, newIdx)
}

// NotFinalIndexes returns all indexes that have not yet been saved.
func (mi *MasterIndex) NotFinalIndexes() []*Index {
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	var list []*Index

	for _, idx := range mi.idx {
		if !idx.Final() {
			list = append(list, idx)
		}
	}

	debug.Log("return %d indexes", len(list))
	return list
}

// FullIndexes returns all indexes that are full.
func (mi *MasterIndex) FullIndexes() []*Index {
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	var list []*Index

	debug.Log("checking %d indexes", len(mi.idx))
	for _, idx := range mi.idx {
		if idx.Final() {
			debug.Log("index %p is final", idx)
			continue
		}

		if IndexFull(idx) {
			debug.Log("index %p is full", idx)
			list = append(list, idx)
		} else {
			debug.Log("index %p not full", idx)
		}
	}

	debug.Log("return %d indexes", len(list))
	return list
}

// All returns all indexes.
func (mi *MasterIndex) All() []*Index {
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	return mi.idx
}

// RebuildIndex combines all known indexes to a new index, leaving out any
// packs whose ID is contained in packBlacklist. The new index contains the IDs
// of all known indexes in the "supersedes" field.
func (mi *MasterIndex) RebuildIndex(packBlacklist restic.IDSet) (*Index, error) {
	mi.idxMutex.Lock()
	defer mi.idxMutex.Unlock()

	debug.Log("start rebuilding index of %d indexes, pack blacklist: %v", len(mi.idx), packBlacklist)

	newIndex := NewIndex()
	done := make(chan struct{})
	defer close(done)

	for i, idx := range mi.idx {
		debug.Log("adding index %d", i)

		for pb := range idx.Each(done) {
			if packBlacklist.Has(pb.PackID) {
				continue
			}

			newIndex.Store(pb)
		}

		if !idx.Final() {
			debug.Log("index %d isn't final, don't add to supersedes field", i)
			continue
		}

		id, err := idx.ID()
		if err != nil {
			debug.Log("index %d does not have an ID: %v", err)
			return nil, err
		}

		debug.Log("adding index id %v to supersedes field", id.Str())

		err = newIndex.AddToSupersedes(id)
		if err != nil {
			return nil, err
		}
	}

	return newIndex, nil
}


text:
package org.opengroup.osdu.core.common.legal;

import org.opengroup.osdu.core.common.model.legal.InvalidTagsWithReason;
import org.opengroup.osdu.core.common.model.legal.LegalException;
import org.opengroup.osdu.core.common.model.legal.LegalTag;
import org.opengroup.osdu.core.common.model.legal.LegalTagProperties;

public interface ILegalProvider {

    LegalTag create(LegalTag lt) throws LegalException;

    void delete(String name) throws LegalException;

    LegalTag get(String name) throws LegalException;

    LegalTagProperties getLegalTagProperties() throws LegalException;

    InvalidTagsWithReason validate(String... names) throws LegalException;
}


text:
using System;
using System.IO;
using System.Timers;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;
using NLog;
using Sync.DataAccess;

namespace Sync
{
  internal class SyncJob
  {
    private static bool IsWorking { get; set; }

    public static    ChangeMainStatusDelegate ChangeMainStatusCallback;
    private readonly Logger                   _logger;
    private readonly Settings                 _settings;
    private readonly Timer                    _timer;
    private          DateTime                 _nextTriggerTime;

    public SyncJob(Settings settings)
    {
      _logger          =  LogManager.GetCurrentClassLogger();
      _timer           =  new Timer(1000);
      _settings        =  settings;
      _nextTriggerTime =  _settings.StartAt;
      _timer.Elapsed   += TimerOnElapsed;
    }

    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
      if (e.SignalTime < _nextTriggerTime || IsWorking) return;
      var result = Execute();
      _nextTriggerTime = DateTime.Now.AddMilliseconds(GetMiliseconds());
      var info = GetDescriptionWithNextTrigger($"{result}.");
      ChangeMainStatusCallback(info);
      _logger.Info($"Timer OnElapsed: {info}");
    }

    private string GetDescriptionWithNextTrigger(string description)
    {
      var nextTrigger = _nextTriggerTime.ToString("d MMMM yyyy, HH:mm:ss");
      nextTrigger = string.IsNullOrWhiteSpace(nextTrigger) ? "" : $" Next time run at: {nextTrigger}";

      return $"{description}{nextTrigger}";
    }

    private double GetMiliseconds()
    {
      switch (_settings.IntervalType)
      {
        case IntervalType.Millisecond:
          return _settings.Interval;
        case IntervalType.Second:
          return TimeSpan.FromSeconds(_settings.Interval).TotalMilliseconds;
        case IntervalType.Minute:
          return TimeSpan.FromMinutes(_settings.Interval).TotalMilliseconds;
        case IntervalType.Hour:
          return TimeSpan.FromHours(_settings.Interval).TotalMilliseconds;
        case IntervalType.Day:
          return TimeSpan.FromDays(_settings.Interval).TotalDays;
        case IntervalType.Week:
          return TimeSpan.FromDays(_settings.Interval * 7).TotalMilliseconds;
        case IntervalType.Month:
          return TimeSpan.FromDays(_settings.Interval * 30).TotalMilliseconds;
        case IntervalType.Year:
          return TimeSpan.FromDays(_settings.Interval * 365).TotalMilliseconds;
        default:
          throw new ArgumentOutOfRangeException();
      }
    }

    public void Start()
    {
      _timer.Enabled = true;
      _timer.Start();
    }

    public void Stop()
    {
      _timer.Enabled = false;
      _timer.Stop();
    }

    private string Execute()
    {
      if (_settings.IsEmpty() || IsWorking) return string.Empty;
      IsWorking = true;

      try
      {
        var info = "Start synchonization...";
        ChangeMainStatusCallback(info);
        _logger.Info(info);

        var providerA = new FileSyncProvider(_settings.ReplicaIdFolderA, _settings.FolderA);
        var providerB = new FileSyncProvider(_settings.ReplicaIdFolderB, _settings.FolderB);

        providerA.DetectChanges();
        providerB.DetectChanges();

        providerA.ApplyingChange += providerA_ApplyingChange;
        providerA.SkippedChange  += providerA_SkippedChange;
        providerA.CopyingFile    += providerA_CopyingFile;

        providerB.ApplyingChange += providerB_ApplyingChange;
        providerB.SkippedChange  += providerB_SkippedChange;
        providerB.CopyingFile    += providerB_CopyingFile;

        var syncAgent = new SyncOrchestrator
        {
          LocalProvider  = providerA,
          RemoteProvider = providerB,
          Direction = _settings.Direction == Direction.UploadAndDownload ? SyncDirectionOrder.UploadAndDownload :
            _settings.Direction == Direction.Upload                      ? SyncDirectionOrder.Upload :
                                                                           SyncDirectionOrder.Download
        };
        syncAgent.SessionProgress += syncAgent_SessionProgress;
        syncAgent.StateChanged    += syncAgent_StateChanged;
        syncAgent.Synchronize();

        return syncAgent.State.ToString();
      }
      catch (Exception ex)
      {
        _logger.Error(ex);
        return "Synchronization error!";
      }
      finally
      {
        IsWorking = false;
      }
    }

    private void providerA_CopyingFile(object sender, CopyingFileEventArgs e)
    {
      ChangeMainStatusCallback($"Copying: {e.FilePath} - {e.PercentCopied}%.");
    }

    private void providerA_SkippedChange(object sender, SkippedChangeEventArgs e)
    {
      var path = string.IsNullOrWhiteSpace(e.CurrentFilePath)
        ? e.NewFilePath
        : string.IsNullOrWhiteSpace(e.CurrentFilePath)
          ? ""
          : e.CurrentFilePath;
      var info = $"Skipped change: {path}, reason: {e.SkipReason}.";
      _logger.Info(info);

      if (e.Exception != null) _logger.Error(e);

      ChangeMainStatusCallback(info);
    }

    private void providerB_CopyingFile(object sender, CopyingFileEventArgs e)
    {
      ChangeMainStatusCallback($"Copying: {e.FilePath ?? ""} - {e.PercentCopied}%.");
    }

    private void providerB_SkippedChange(object sender, SkippedChangeEventArgs e)
    {
      var path = string.IsNullOrWhiteSpace(e.CurrentFilePath)
        ? e.NewFilePath
        : string.IsNullOrWhiteSpace(e.CurrentFilePath)
          ? ""
          : e.CurrentFilePath;
      var info = $"Skipped change: {path}. Reason: {e.SkipReason}.";
      _logger.Info(info);

      if (e.Exception != null) _logger.Error(e);

      ChangeMainStatusCallback(info);
    }

    private void providerB_ApplyingChange(object sender, ApplyingChangeEventArgs e)
    {
      if (e.ChangeType != ChangeType.Delete) return;

      e.SkipChange = _settings?.SkipDeleteInFolderB ?? false;

      if (_settings != null && !_settings.SkipDeleteInFolderB) return;

      if (_settings == null) return;

      var pathToFileB = Path.Combine(_settings.FolderB, e.CurrentFileData.RelativePath);

      if (!File.Exists(pathToFileB)) return;

      var nameWithoutExt = Path.GetFileNameWithoutExtension(e.CurrentFileData.Name);
      var nameExt        = Path.GetExtension(e.CurrentFileData.Name);
      var now            = DateTime.Now;
      var backupName     = $"{nameWithoutExt}_{now:yyyyMMdd}_{now:HHmmss}{nameExt}";
      var relativeFolder = e.CurrentFileData.RelativePath;

      relativeFolder = relativeFolder.Replace(e.CurrentFileData.Name, "");

      var relativePathToBackupFileB =
        Path.Combine(Settings.BackupFolderName, Folder.B.ToString(), relativeFolder, backupName);
      var pathToBackupFileB = Path.Combine(_settings.FolderB, relativePathToBackupFileB);

      if (!Directory.Exists(Path.GetDirectoryName(pathToBackupFileB)))
      {
        var path = Path.GetDirectoryName(pathToBackupFileB);

        if (string.IsNullOrWhiteSpace(path))
        {
          var info = $"GetDirectoryName from {pathToBackupFileB}{nameof(pathToBackupFileB)} is Null";
          ChangeMainStatusCallback(info);
          _logger.Error(info);

          return;
        }

        Directory.CreateDirectory(path);
      }

      File.Move(pathToFileB, pathToBackupFileB);

      var backup = new Backup
      {
        CreatedAt    = DateTime.Now,
        Folder       = Folder.B,
        RelativePath = relativePathToBackupFileB
      };

      SyncFactory.Get().SaveOrUpdate(backup);
    }

    private void providerA_ApplyingChange(object sender, ApplyingChangeEventArgs e)
    {
      if (e.ChangeType != ChangeType.Delete) return;

      e.SkipChange = _settings?.SkipDeleteInFolderA ?? false;

      if (_settings != null && !_settings.SkipDeleteInFolderA) return;

      if (_settings == null) return;

      var pathToFileA = Path.Combine(_settings.FolderA, e.CurrentFileData.RelativePath);

      if (!File.Exists(pathToFileA)) return;

      var nameWithoutExt = Path.GetFileNameWithoutExtension(e.CurrentFileData.Name);
      var nameExt        = Path.GetExtension(e.CurrentFileData.Name);
      var backupName     = $"{nameWithoutExt}_{DateTime.Now:yyyyMMddHHmmss}{nameExt}";
      var relativeFolder = e.CurrentFileData.RelativePath;

      relativeFolder = relativeFolder.Replace(e.CurrentFileData.Name, "");

      var relativePathToBackupFileA =
        Path.Combine(Settings.BackupFolderName, Folder.A.ToString(), relativeFolder, backupName);
      var pathToBackupFileA = Path.Combine(_settings.FolderA, relativePathToBackupFileA);

      if (!Directory.Exists(Path.GetDirectoryName(pathToBackupFileA)))
      {
        var path = Path.GetDirectoryName(pathToBackupFileA);

        if (string.IsNullOrWhiteSpace(path))
        {
          var info = $"GetDirectoryName from {pathToBackupFileA}(pathToBackupFileA) is Null";
          ChangeMainStatusCallback(info);
          _logger.Error(info);

          return;
        }

        Directory.CreateDirectory(path);
      }

      File.Move(pathToFileA, pathToBackupFileA);

      var backup = new Backup
      {
        CreatedAt    = DateTime.Now,
        Folder       = Folder.A,
        RelativePath = relativePathToBackupFileA
      };

      SyncFactory.Get().SaveOrUpdate(backup);
    }

    private void syncAgent_SessionProgress(object sender, SyncStagedProgressEventArgs e)
    {
      var info = $"Synchronization... {e.ReportingProvider}. File {e.CompletedWork:N0} of {e.TotalWork:N0}.";

      ChangeMainStatusCallback(info);
      _logger.Info(info);
    }

    private void syncAgent_StateChanged(object sender, SyncOrchestratorStateChangedEventArgs e)
    {
      string info;

      switch (e.NewState)
      {
        case SyncOrchestratorState.Uploading:
        case SyncOrchestratorState.Downloading:
        case SyncOrchestratorState.UploadingAndDownloading:
        case SyncOrchestratorState.Canceling:
          info = $"{e.NewState}...";
          break;
        case SyncOrchestratorState.Ready:
        case SyncOrchestratorState.Canceled:
          info = $"{e.NewState}.";
          break;
        default:
          info = "No information!";
          break;
      }

      ChangeMainStatusCallback(info);
      _logger.Info(info);
    }
  }
}


text:
<!DOCTYPE HTML>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/bootstrap-grid.css">

Cam's Pizzeria

                <form action="#randomPizzas">
                  <input type="submit" value="Menu">
                </form>
                <form action="#ingredients">
                  <input type="submit" value="Our Ingredients">
                </form>
                <form action="#locations">
                  <input type="submit" value="Locations">
                </form>
                <form action="#" onsubmit="alert('Thanks for clicking! This button doesn\'t do anything because this is a fake pizzeria :\)')">
                  <input type="submit" value="Contact Us">
                </form>

We Have Hundreds of Pizza Recipes!

At Cam's Pizzeria, we know you want options. Pepperoni? Boring. Cheese? No way! Sausage? C'mon, let's get creative.

We have every pizza ingredient imaginable in our kitchen because we know you take choice seriously. Take a look through our menu of hundreds of pizza options and we know that you'll find something you love.

            <form action="#randomPizzas">
              <input type="submit" value="Pick a Pizza Now!">
            </form>

Ingredients!

We've scoured the planet for the best pizza ingredients. Our crack team of ingredient specialists are on constant lookout for new and interesting pizza ingredients.

We have classic meats like pepperoni, sausage, and barbecue chicken. But you can find even more fun meats like coppa, kielbasa and soylent green on our menu too.

Not interested in meat? No problem! We love our veggies too :) We have everything from arugula to zucchini.

Locations!

Pizza Road

1800 Pizza Road
San Francisco, CA
01010
555-555-5555

Classic Pie Way

999 Classic Pie Way
New York, NY
00100
555-555-5555

Our Pizzas!

            What size pizza would you like? Use the slider below to change pizza sizes.

Medium

            <input id="sizeSlider" type="range" min="1" max="3" value="2" step="1" onchange="resizePizzas(this.value)"></input>

The Udacity Special

Turkey

Tofu

Cauliflower

Sun Dried Tomatoes

Velveeta Cheese

Red Sauce

Whole Wheat Crust

The Cameron Special

Chicken

Hot Sauce

White Crust

Thanks for visiting! © 2014 Udacity


text:
package eu.qualimaster.families.imp;

import eu.qualimaster.families.inf.*;
import eu.qualimaster.observables.IObservable;
import eu.qualimaster.dataManagement.serialization.SerializerRegistry;

/**
 * The implementation for the algorithm family "IFTweetClassifier" (GEN).
 */
public class FTweetClassifier implements IFTweetClassifier {

    /**
     * Provides a default implementation of the data input for the {@link IFTweetClassifierModifiedTwitterStreamInput} algorithm.
     * Actual execution system code may also directly wrap the respective tuple concept.
     */
    public static class IFTweetClassifierModifiedTwitterStreamInput implements IIFTweetClassifierModifiedTwitterStreamInput {

        private Object status;

        @Override
        public Object getStatus(){
            return status;
        }

        @Override
        public void setStatus(Object status){
            this.status = status;
        }
        static {
            SerializerRegistry.register("IFTweetClassifierModifiedTwitterStreamInput", FTweetClassifierSerializers.IFTweetClassifierModifiedTwitterStreamInputSerializer.class);
        }
    }

    /**
     * Provides a default implementation of the data input for the {@link IFTweetClassifierKeywordStreamInput} algorithm.
     * Actual execution system code may also directly wrap the respective tuple concept.
     */
    public static class IFTweetClassifierKeywordStreamInput implements IIFTweetClassifierKeywordStreamInput {

        private Object keywords;

        @Override
        public Object getKeywords(){
            return keywords;
        }

        @Override
        public void setKeywords(Object keywords){
            this.keywords = keywords;
        }
        static {
            SerializerRegistry.register("IFTweetClassifierKeywordStreamInput", FTweetClassifierSerializers.IFTweetClassifierKeywordStreamInputSerializer.class);
        }
    }

    /**
     * Provides a default implementation of the data output for the {@link IFTweetClassifierModifiedTwitterStreamOutput} algorithm.
     * Actual execution system code may also directly wrap the respective tuple concept.
     */
    public static class IFTweetClassifierModifiedTwitterStreamOutput extends eu.qualimaster.base.algorithm.AbstractOutputItem<IIFTweetClassifierModifiedTwitterStreamOutput> implements IIFTweetClassifierModifiedTwitterStreamOutput {

        /**
         * Creates the item.
         */
        public IFTweetClassifierModifiedTwitterStreamOutput() {
            this(true);
        }

        /**
         * Creates a sub-item.
         *
         * @param topLevel whether it is a top-level item
         */
        private IFTweetClassifierModifiedTwitterStreamOutput(boolean topLevel) {
            super(topLevel);
            setParent(this);
        }

        @Override
        protected IFTweetClassifierModifiedTwitterStreamOutput createItem() {
            return new IFTweetClassifierModifiedTwitterStreamOutput(false);
        }
        private Object tweet;
        private Object stocks;

        @Override
        public Object getTweet(){
            return tweet;
        }

        @Override
        public void setTweet(Object tweet){
            this.tweet = tweet;
        }
        @Override
        public Object getStocks(){
            return stocks;
        }

        @Override
        public void setStocks(Object stocks){
            this.stocks = stocks;
        }
        static {
            SerializerRegistry.register("IFTweetClassifierModifiedTwitterStreamOutput", FTweetClassifierSerializers.IFTweetClassifierModifiedTwitterStreamOutputSerializer.class);
        }
    }

    /**
     * Calculates the actual result for input.
     *
     * @param input the algorithm input taken from the input stream
     * @param result the result calculated by the algorithm
     */
    @Override
    public void calculate(IIFTweetClassifierModifiedTwitterStreamInput input, IIFTweetClassifierModifiedTwitterStreamOutput result){
    }

    /**
     * Calculates the actual result for input.
     *
     * @param input the algorithm input taken from the input stream
     * @param result the result calculated by the algorithm
     */
    @Override
    public void calculate(IIFTweetClassifierKeywordStreamInput input, IIFTweetClassifierModifiedTwitterStreamOutput result){
    }

    @Override
    public void switchState(State arg0) {
    }

    @Override
    public Double getMeasurement(IObservable arg0) {
	    return null;
    }
}