text:
package com.laytonsmith.abstraction;

import com.laytonsmith.PureUtilities.DaemonManager;
import com.laytonsmith.core.events.BindableEvent;
import com.laytonsmith.core.events.Driver;
import com.laytonsmith.core.events.EventUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 *
 */
public abstract class AbstractConvertor implements Convertor{

	private final List<Runnable> shutdownHooks = new ArrayList<>();

	@Override
	public void addShutdownHook(Runnable r) {
		shutdownHooks.add(r);
	}

	@Override
	public void runShutdownHooks() {
		// Fire off the shutdown event, before we shut down all the internal hooks
		EventUtils.TriggerListener(Driver.SHUTDOWN, "shutdown", new BindableEvent() {

			@Override
			public Object _GetObject() {
				return new Object();
			}
		});
		Iterator<Runnable> iter = shutdownHooks.iterator();
		while(iter.hasNext()){
			iter.next().run();
			iter.remove();
		}
	}

	/**
	 * Runs the task either now or later. In the case of a default Convertor,
	 * it just runs the task now.
	 * @param dm
	 * @param r
	 */
	@Override
	public void runOnMainThreadLater(DaemonManager dm, Runnable r) {
		r.run();
	}

	@Override
	public <T> T runOnMainThreadAndWait(Callable<T> callable) throws Exception{
		return (T) callable.call();
	}

	@Override
	public MCWorldCreator getWorldCreator(String worldName) {
		throw new UnsupportedOperationException("Not supported.");
	}

	@Override
	public MCCommand getNewCommand(String name) {
		throw new UnsupportedOperationException("Not supported in this implementation.");
	}

	@Override
	public MCCommandSender GetCorrectSender(MCCommandSender unspecific) {
		throw new UnsupportedOperationException("Not supported in this implementation.");
	}

	private final Map<Integer, Task> tasks = new HashMap<>();
	private final AtomicInteger taskIDs = new AtomicInteger(0);

	@Override
	public void ClearAllRunnables() {
		synchronized(tasks){
			for(Task task : tasks.values()){
				task.unregister();
			}
			tasks.clear();
		}
	}

	@Override
	public void ClearFutureRunnable(int id) {
		synchronized(tasks){
			if(tasks.containsKey(id)){
				tasks.get(id).unregister();
				tasks.remove(id);
			}
		}
	}

	@Override
	public int SetFutureRepeater(DaemonManager dm, long ms, long initialDelay, final Runnable r) {
		int id = taskIDs.getAndIncrement();
		Task t = new Task(id, dm, true, initialDelay, ms, new Runnable() {

			@Override
			public void run() {
				triggerRunnable(r);
			}
		});
		synchronized(tasks){
			tasks.put(id, t);
			t.register();
		}
		return id;
	}

	@Override
	public int SetFutureRunnable(DaemonManager dm, long ms, final Runnable r) {
		int id = taskIDs.getAndIncrement();
		Task t = new Task(id, dm, false, ms, 0, new Runnable() {

			@Override
			public void run() {
				triggerRunnable(r);
			}
		});
		synchronized(tasks){
			tasks.put(id, t);
			t.register();
		}
		return id;
	}

	/**
	 * A subclass may need to do special handling for the actual trigger of a scheduled
	 * task, though not need to do anything special for the scheduling itself. In this
	 * case, subclasses may override this method, and whenever a scheduled task is
	 * intended to be run, it will be passed to this method instead. By default, the
	 * runnable is simply run.
	 * @param r
	 */
	protected synchronized void triggerRunnable(Runnable r){
		r.run();
	}

	private class Task {
		/**
		 * The task id
		 */
		private final int id;
		/**
		 * The DaemonManager
		 */
		private final DaemonManager dm;
		/**
		 * True if this is an interval, false otherwise.
		 */
		private final boolean repeater;
		/**
		 * The initial delay. For timeouts, this is just the delay.
		 */
		private final long initialDelay;
		/**
		 * The delay between triggers. For intervals, this is ignored.
		 */
		private final long interval;
		/**
		 * The task itself.
		 */
		private final Runnable task;

		private Timer timer;

		public Task(int id, DaemonManager dm, boolean repeater, long initialDelay, long interval, Runnable task){
			this.id = id;
			this.dm = dm;
			this.repeater = repeater;
			this.initialDelay = initialDelay;
			if(repeater){
				this.interval = interval;
			} else {
				this.interval = Long.MAX_VALUE;
			}
			this.task = task;
		}

		public void register(){
			timer = new Timer();
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					task.run();
					if(!repeater){
						unregister();
						synchronized(tasks){
							tasks.remove(id);
						}
					}
				}
			}, initialDelay, interval);
			if(dm != null){
				dm.activateThread(null);
			}
		}

		public void unregister(){
			timer.cancel();
			if(dm != null){
				dm.deactivateThread(null);
			}
		}

		public int getId(){
			return id;
		}
	}

}


text:
class GroupsController < Groups::ApplicationController
  include IssuesAction
  include MergeRequestsAction
  include ParamsBackwardCompatibility

  respond_to :html

  before_action :authenticate_user!, only: [:new, :create]
  before_action :group, except: [:index, :new, :create]

  # Authorize
  before_action :authorize_admin_group!, only: [:edit, :update, :destroy, :projects]
  before_action :authorize_create_group!, only: [:new, :create]

  before_action :group_projects, only: [:projects, :activity, :issues, :merge_requests]
  before_action :group_merge_requests, only: [:merge_requests]
  before_action :event_filter, only: [:activity]

  before_action :user_actions, only: [:show, :subgroups]

  layout :determine_layout

  def index
    redirect_to(current_user ? dashboard_groups_path : explore_groups_path)
  end

  def new
    @group = Group.new
  end

  def create
    @group = Groups::CreateService.new(current_user, group_params).execute

    if @group.persisted?
      notice = if @group.chat_team.present?
                 "群组 '#{@group.name}' 和它的 Mattermost 团队创建成功。"
               else
                 "群组 '#{@group.name}' 创建成功。"
               end

      redirect_to @group, notice: notice
    else
      render action: "new"
    end
  end

  def show
    setup_projects

    respond_to do |format|
      format.html

      format.json do
        render json: {
          html: view_to_html_string("dashboard/projects/_projects", locals: { projects: @projects })
        }
      end

      format.atom do
        load_events
        render layout: false
      end
    end
  end

  def subgroups
    @nested_groups = GroupsFinder.new(current_user, parent: group).execute
    @nested_groups = @nested_groups.search(params[:filter_groups]) if params[:filter_groups].present?
  end

  def activity
    respond_to do |format|
      format.html

      format.json do
        load_events
        pager_json("events/_events", @events.count)
      end
    end
  end

  def edit
  end

  def projects
    @projects = @group.projects.with_statistics.page(params[:page])
  end

  def update
    if Groups::UpdateService.new(@group, current_user, group_params).execute
      redirect_to edit_group_path(@group), notice: "群组 '#{@group.name}' 更新成功。"
    else
      @group.restore_path!

      render action: "edit"
    end
  end

  def destroy
    Groups::DestroyService.new(@group, current_user).async_execute

    redirect_to root_path, alert: "群组 '#{@group.name}' 已经被安排删除"
  end

  protected

  def setup_projects
    set_non_archived_param
    params[:sort] ||= 'latest_activity_desc'
    @sort = params[:sort]

    options = {}
    options[:only_owned] = true if params[:shared] == '0'
    options[:only_shared] = true if params[:shared] == '1'

    @projects = GroupProjectsFinder.new(params: params, group: group, options: options, current_user: current_user).execute
    @projects = @projects.includes(:namespace)
    @projects = @projects.page(params[:page]) if params[:name].blank?
  end

  def authorize_create_group!
    unless can?(current_user, :create_group)
      return render_404
    end
  end

  def determine_layout
    if [:new, :create].include?(action_name.to_sym)
      'application'
    elsif [:edit, :update, :projects].include?(action_name.to_sym)
      'group_settings'
    else
      'group'
    end
  end

  def group_params
    params.require(:group).permit(group_params_ce)
  end

  def group_params_ce
    [
      :avatar,
      :description,
      :lfs_enabled,
      :name,
      :path,
      :public,
      :request_access_enabled,
      :share_with_group_lock,
      :visibility_level,
      :parent_id,
      :create_chat_team,
      :chat_team_name,
      :require_two_factor_authentication,
      :two_factor_grace_period
    ]
  end

  def load_events
    @events = Event.in_projects(@projects)
    @events = event_filter.apply_filter(@events).with_associations
    @events = @events.limit(20).offset(params[:offset] || 0)
  end

  def user_actions
    if current_user
      @last_push = current_user.recent_push
      @notification_setting = current_user.notification_settings_for(group)
    end
  end

  def build_canonical_path(group)
    return group_path(group) if action_name == 'show' # root group path

    params[:id] = group.to_param

    url_for(params)
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Microsoft.AspNetCore.Razor.Hosting;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Language.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace FormFactory.Standalone
{
    public class MyFfHtmlHelper : FfHtmlHelper
    {
        private FfRazorProjectFileSystem fs;

        public MyFfHtmlHelper()
        {
            fs = new FfRazorProjectFileSystem();

        }

        public string Raw(string s)
        {
            return s;
        }

        public ViewData ViewData => new ViewData();

        public IViewFinder ViewFinder => new ViewFinder();

        public PropertyVm CreatePropertyVm(Type objectType, string name)
        {
            throw new NotImplementedException();
        }

        public string AntiForgeryToken() => "";

        public void RenderPartial(string partialName, object model)
        {
            throw new NotImplementedException();
        }

        public UrlHelper Url()
        {
            throw new NotImplementedException();
        }

        public string WriteTypeToString(Type type)
        {
            throw new NotImplementedException();
        }

        public string ValidationSummary(bool foo) => "";

        public MvcHtmlString Partial(string viewPath, object model)
        {
            var templateType = compiledViews.GetOrAdd(viewPath, s => new Lazy<Type>(() => GetTemplateType(s)))
                .Value;
            var template = (MyTemplate)Activator.CreateInstance(templateType);
            template.ViewData = new ViewData();
            template.Model = model;
            template.Html = this;
            template.ExecuteAsync().Wait();
            return new MvcHtmlString(template.sb.ToString());
        }
        static readonly ConcurrentDictionary<string, Lazy<Type>> compiledViews = new ConcurrentDictionary<string, Lazy<Type>>();
        private Type GetTemplateType(string viewPath)
        {
            var namespaceName = typeof(MyTemplate<>).Namespace + Guid.NewGuid().ToString().Replace("-", "");

            var engine = RazorProjectEngine.Create(RazorConfiguration.Default, fs, (builder) =>
            {
                builder.SetBaseType("FormFactory.Standalone.MyTemplate<TModel>");
                ModelDirective.Register(builder);
                InheritsDirective.Register(builder);
                builder.SetNamespace(namespaceName); // define a namespace for the Template class
            });

            var item = fs.GetItem(viewPath);

            var codeDocument = engine.Process(item);
            var cs = codeDocument.GetCSharpDocument();

            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);

            var loadedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                .Select(Assembly.Load)
                .Where(a => a.FullName == "FormFactory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
                .Select(a => MetadataReference.CreateFromFile(a.Location));
            new object[] { }.OfType<string>();
            string dllName = "hello" + Guid.NewGuid().ToString();

            var compilation = CSharpCompilation.Create(dllName, new[] {tree},
                new[]
                {
                    MetadataReference.CreateFromFile(typeof(object).Assembly.Location), // include corlib
                    MetadataReference.CreateFromFile(typeof(RazorCompiledItemAttribute).Assembly
                        .Location), // include Microsoft.AspNetCore.Razor.Runtime
                    MetadataReference.CreateFromFile(typeof(MyTemplate<>).Assembly
                        .Location), // this file (that contains the MyTemplate base class)
                    MetadataReference.CreateFromFile(typeof(System.Linq.EnumerableExecutor).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(System.Linq.Expressions.Expression).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(XElement).Assembly.Location),

                    // for some reason on .NET core, I need to add this... this is not needed with .NET framework
                    MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location),
                        "System.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location),
                        "System.Runtime.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location),
                        "System.Core.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location),
                        "System.Linq.dll")),

                    // as found out by @Isantipov, for some other reason on .NET Core for Mac and Linux, we need to add this... this is not needed with .NET framework
                    MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location),
                        "netstandard.dll"))
                }.Concat(loadedAssemblies),
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); // we want a dll

            var stream = new MemoryStream();
            var emitResult = compilation.Emit(stream);

            if (!emitResult.Success)
            {

                var errro = (viewPath + "
" +
                             string.Join("
", emitResult.Diagnostics.Select(x => x.GetMessage())));

                throw new Exception(errro);
            }

            stream.Seek(0, SeekOrigin.Begin);
            var asm = Assembly.Load(stream.ToArray());

            // the generated type is defined in our custom namespace, as we asked. "Template" is the type name that razor uses by default.
            return  asm.GetType(namespaceName + ".Template");
        }
    }
}


text:
from wtforms import TextField, SelectField
from wtforms.validators import DataRequired, NumberRange
from ..base import BaseReactForm

class ReactForm(BaseReactForm):

    ''' Class that creates a Reaction form for the dashboard '''
    title = "Linode: Reboot Node Server"
    description = """
    <P>
        This reaction provides the ability to Reboot a specified Linode Node Server. This reaction simply sends a Reboot API request to Linode. A simple use case for this functionality is to reboot servers when they do not pass health checks. Using this reaction requires servers to be configured to start services automatically after reboot.
    </P>
    """
    placeholders = BaseReactForm.placeholders
    placeholders.update({
        'linode_id' : '12345',
        'api_key' : placeholders['apikey'],
    })
    descriptions=BaseReactForm.descriptions

    api_key = TextField(
        "API Key",
        description=descriptions['apikey'],
        validators=[DataRequired(message='API Key is a required field')])
    linode_id = TextField(
        "Linode ID#",
        description=descriptions['linode']['linodeID'],
        validators=[
            DataRequired(message='Linode ID# is a required field'),
            NumberRange(
                min=1, max=None,
                message="Linode ID should be a numeric ID number")
        ]
    )
    call_on = SelectField(
        "Call On",
        description=descriptions['callon'],
        choices=[('false', 'False Monitors'), ('true', 'True Monitors')],
        validators=[DataRequired(message='Call On is a required field')])

if __name__ == '__main__':
    pass


text:
require 'minitest'
require 'minitest/autorun'
require 'delve/widgets/viewport'

class ViewportWidgetTest < Minitest::Test

  def setup
    @x = 1
    @y = 1
    @width = 3
    @height = 3
    @world = mock('object')
    @display = mock('object')

    @viewport = ViewportWidget.new @x, @y, @width, @height, @world
  end

  def test_initialize_without_x_fails
    assert_raises RuntimeError do
      ViewportWidget.new nil, @y, @width, @height, @world
    end
  end

  def test_initialize_without_y_fails
    assert_raises RuntimeError do
      ViewportWidget.new @x, nil, @width, @height, @world
    end
  end

  def test_initialize_without_width_fails
    assert_raises RuntimeError do
      ViewportWidget.new @x, @y, nil, @height, @world
    end
  end

  def test_initialize_without_height_fails
    assert_raises RuntimeError do
      ViewportWidget.new @x, @y, @width, nil, @world
    end
  end

  def test_initialize_without_world_fails
    assert_raises RuntimeError do
      ViewportWidget.new @x, @y, @width, @height, nil
    end
  end

  def test_focus_west_of_0_fails
    assert_raises RuntimeError do
      @viewport.focus -1, 5
    end
  end

  def test_focus_north_of_0_fails
    assert_raises RuntimeError do
      @viewport.focus 4, -1
    end
  end

  def test_focus_east_of_width_fails
    @world.expects(:width).returns(10)
    assert_raises RuntimeError do
      @viewport.focus 10, 1
    end
  end

  def test_focus_south_off_height_fails
    @world.stubs(:width).returns(18)
    @world.expects(:height).returns(9)
    assert_raises RuntimeError do
      @viewport.focus 1, 9
    end
  end

  def test_draw_without_display_fails
    assert_raises RuntimeError do
      @viewport.draw nil
    end
  end

  def test_focus_at_5_5_renders_4_4_to_6_6
    @world.stubs(:width).returns(20)
    @world.stubs(:height).returns(100)
    expect_world 4, 4, 6, 6
    expect_draw 1, 1, 3, 3

    @viewport.focus 5, 5
    @viewport.draw @display
  end

  def test_focus_at_0_0_renders_0_0_to_2_2
    @world.stubs(:width).returns(20)
    @world.stubs(:height).returns(100)
    expect_world 0, 0, 2, 2
    expect_draw 1, 1, 3, 3

    @viewport.focus 0, 0
    @viewport.draw @display
  end

  def test_focus_at_99_99_renders_97_97_to_99_99
    @world.stubs(:width).returns(100)
    @world.stubs(:height).returns(100)
    expect_world 97, 97, 99, 99
    expect_draw 1, 1, 3, 3

    @viewport.focus 99, 99
    @viewport.draw @display
  end

  def test_focus_at_0_0_puts_top_left_at_0_0
    @world.stubs(:width).returns(100)
    @world.stubs(:height).returns(100)

    @viewport.focus 0, 0
    assert_equal 0, @viewport.top_left[:x]
    assert_equal 0, @viewport.top_left[:y]
  end

  def test_focus_at_99_99_puts_top_left_at_97_97
    @world.stubs(:width).returns(100)
    @world.stubs(:height).returns(100)

    @viewport.focus 99, 99
    assert_equal 97, @viewport.top_left[:x]
    assert_equal 97, @viewport.top_left[:y]
  end

  def test_width
    assert_equal @width, @viewport.width
  end

  def test_height
    assert_equal @height, @viewport.height
  end

  private
  def expect_world(sx, sy, ex, ey)
    (sx..ex).each do |x|
      (sy..ey).each do |y|
        @world.expects(:at).with(x, y).returns({ :char => '.', :color => :white, :walkable => true })
      end
    end
  end

  def expect_draw(sx, sy, ex, ey)
    (sx..ex).each do |x|
      (sy..ey).each do |y|
        @display.expects(:draw).with(x, y, '.', :white)
      end
    end
  end

end


text:
<!doctype html>

    <title>{{name}} Browser</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='typeaheadjs.css') }}">
    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/font-awesome.min.css') }}">

    {% block loads %}{% endblock %}

    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='theme.default.css') }}">

    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">
    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

            <button type="button" class="navbar-toggle pull-right" data-toggle="collapse" data-target="#navbar-collapse">
                Toggle navigation

            </button>
            {{name}} Browser Beta

                <form action="/awesome" class="navbar-form" role="search">

                        <input type="submit" style="display: none;"/>
                        <input id="navbar-searchbox-input" name="query" class="form-control awesomebar" type="text" placeholder="Gene, transcript, variant, or region"/>
                        <input type="submit" style="position: absolute; left: -9999px"/>

                </form>

About

Downloads

Terms

Contact

FAQ

{#
#}
{#
#}
{#        #}
{#            {{name}} Browser (Beta)#}
{#        #}
{#        <form action="/awesome" class="navbar-form navbar-left" role="search">#}
{#
#}
{#                <input type="submit" style="display: none;"/>#}
{#                <input id="navbar-searchbox-input" name="query" class="form-control" type="text" placeholder="Gene, transcript, variant, or region"/>#}
{#                <input type="submit" style="position: absolute; left: -9999px"/>#}
{#
#}
{#        </form>#}
{#
#}
{#            Home |#}
{#            Downloads |#}
{#            Terms |#}
{#            About#}
{#
#}
{#
#}
{#
#}
{% block body %}{% endblock %}


text:
using System.Linq;
using static System.Console;

namespace BasicsofImplementation.Lib
{
    public class LittleJhoolPsychicPowers
    {
        #region Methods.

        public static void Run()
        {
            var data = ReadLine().Trim();
            var onesData = data.Replace('0', ' ').Split(' ').Select(r => r.Length >= 6).ToArray().SingleOrDefault(r => r == true);
            if (onesData)
            {
                goto Sorry_Sorry;
            }
            onesData = data.Replace('1', ' ').Split(' ').Select(r => r.Length >= 6).ToArray().SingleOrDefault(r => r == true);
            if (onesData)
            {
                goto Sorry_Sorry;
            }
            goto Good_luck;

        Good_luck:
            WriteLine("Good luck!");
            goto Exit;

        Sorry_Sorry:
            WriteLine("Sorry, sorry!");

        Exit:
            WriteLine();
        }
        #endregion
    }
}


text:
import smbus

def int_sw_swap(x):
    """Interpret integer as signed word with bytes swapped"""
	xl = x & 0xff
	xh = x >> 8
	xx = (xl << 8) + xh
    return xx - 0xffff if xx > 0x7fff else xx

class SensorITG3200(object):
    """ITG3200 digital gyroscope control class.
    Supports data polling at the moment.
    """
    def __init__(self, bus_nr, addr):
        """ Sensor class constructor
        Params:
            bus_nr .. I2C bus number
            addr   .. ITG3200 device address
        """
        self.bus = smbus.SMBus(bus_nr)
        self.addr = addr

    def sample_rate(self, lpf, div):
        """Set internal sample rate, low pass filter frequency.
        Sets device parameters DLPF_CFG and SMPLRT_DIV.
        Also sets FS_SEL to 0x03 which is required to initialize the device.
        Params:
            lpf .. (code from the list)
              code   LPF  sample rate
                 0 256Hz  8kHz
                 1 188Hz  1kHz
                 2  98Hz  1kHz
                 3  42Hz  1kHz
                 4  20Hz  1kHz
                 5  10Hz  1kHz
                 6   5Hz  1kHz
            div .. internal sample rate divider (SMPLRT_DIV will be set to div-1)
        """
        if not (lpf >= 0 and lpf <= 0x6):
            raise ValueError("Invalid low pass filter code (0-6).")
        if not (div >= 0 and div <= 0xff):
            raise ValueError("Invalid sample rate divider (0-255).")
        self.bus.write_byte_data(self.addr, 0x15, div-1)
        self.bus.write_byte_data(self.addr, 0x16, 0x18 | lpf)

    def default_init(self):
        """Initialization with default values:
        8kHz internal sample rate, 256Hz low pass filter, sample rate divider 8.
        """
        self.sample_rate(0, 8)

    def read_data(self):
        """Read and return data tuple for x, y and z axis
        as signed 16-bit integers.
        """
		gx = int_sw_swap(self.bus.read_word_data(self.addr, 0x1d))
		gy = int_sw_swap(self.bus.read_word_data(self.addr, 0x1f))
		gz = int_sw_swap(self.bus.read_word_data(self.addr, 0x21))
        return (gx, gy, gz)

if __name__ == '__main__':
    import time
    sensor = SensorITG3200(1, 0x68) # update with your bus number and address
    sensor.default_init()
    while 1:
        time.sleep(0.1)
        gx, gy, gz = sensor.read_data()
        print gx, gy, gz


text:
#import "TETTypes.h"

#ifndef TETGazeApi_TETGazeListeners_h
#define TETGazeApi_TETGazeListeners_h

/** TETGazeListener
  Callback interface with methods associated to Gaze Tracking.
  This interface should be implemented by classes that are to recieve live GazeData stream.
*/
@protocol TETGazeListener <NSObject>
@required

/** A notification call back indicating that a new GazeData frame is available.
 Implementing classes should update themselves accordingly if needed.
 Register for updates through TETGazeAPI addListener:
 @param gazeData
        Latest GazeData frame processed by Tracker Server
 */
-(void)onGazeData:(TETGazeData*)gazeData;
@end

/** TETCalibrationResultListener
  Callback interface with methods associated to the changes of calibration result.
  This interface should be implemented by classes that are to recieve only changes in calibration result
  and who are _not_ to perform the calibration process itself.
 */
@protocol TETCalibrationResultListener <NSObject>
@required

/** A notification call back indicating that state of calibration has changed.
 Implementing classes should update themselves accordingly if needed.
 Register for updates through TETGazeAPI addListener:

 @param isCalibrated
        is the Tracker Server calibrated?
 @param calibResult
        if calibrated, the currently valid gtl::CalibResult
 */

-(void)onCalibrationChanged:(BOOL)isCalibrated withResult:(TETCalibResult*)calibResult;
@end

/** TETTrackerStateListener
  Callback interface with methods associated to the state of the physical Tracker device.
  This interface should be implemented by classes that are to recieve changes if the state of Tracker
  and handle these accordingly. This could be a class in the 'View' layer telling the user that a
  Tracker has disconnected.
 */
@protocol TETTrackerStateListener <NSObject>
@required

/** A notification call back indicating that state of connected Tracker device has changed.
  Use this to detect if a tracker has been connected or disconnected.
  Implementing classes should update themselves accordingly if needed.
  Register for updates through GazeApi::add_listener(ITrackerStateListener & listener).

 @param trackerState
        the current state of the physical Tracker device
 */
-(void)onTrackerConnectionChanged:(int)trackerState;

/** A notification call back indicating that main screen index has changed.
  This is only relevant for multiscreen setups. Implementing classes should
  update themselves accordingly if needed.
  Register for updates through GazeApi::add_listener(ITrackerStateListener & listener).

 @param screen
        the new screen state
 */
-(void)onScreenStateChanged:(TETScreen*)screen;
@end

/**  TETCalibrationProcessListener
  Callback interface with methods associated to Calibration process.
 */
@protocol TETCalibrationProcessListener <NSObject>
@required

/** Called when a calibration process has been started. */
-(void)onCalibrationStarted;

/** Called every time tracking of a single calibration points has completed.
 @param progress
        'normalized' progress [0..1d]
 */
-(void)onCalibrationProgress:(double)progress;

/** Called when all calibration points have been collected and calibration processing begins. */
-(void)onCalibrationProcessing;

/** Called when processing of calibration points and calibration as a whole has completed.

 @param isCalibrated
        is the Tracker Server calibrated?
 @param calibResult
        if calibrated, the currently valid TETCalibResult
 */

-(void)onCalibrationCalibrated:(BOOL)isCalibrated withResult:(TETCalibResult*)calibResult;
@end

/** TETConnectionStateListener
  A notification callback indicating that the connection state has changed.
  Use this to detect if connection the EyeTribe Server has been lost.
  Implementing classes should update themselves accordingly if needed.
 */
@protocol TETConnectionStateListener <NSObject>
@required

/** Called when tracker received or looses connection  */
-(void)onConnectionStateChanged:(BOOL)isConnected;
@end

#endif


text:
using System;
using CoreGraphics;
using System.Linq;
using UIKit;
using Foundation;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Net;
using System.Threading;

namespace LazyTableImages {

	public partial class RootViewController : UITableViewController {

		public ObservableCollection<App> Apps { get; private set; }

		public RootViewController (string nibName, NSBundle bundle) : base (nibName, bundle)
		{
			Apps = new ObservableCollection<App> ();
			Title = NSBundle.MainBundle.LocalizedString ("Top 50 Apps", "Master");
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			TableView.Source = new DataSource (this);
		}

		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
		}

		public override void DidReceiveMemoryWarning ()
		{
			// Release all cached images. This will cause them to be redownloaded
			// later as they're displayed.
			foreach (var v in Apps)
				v.Image = null;
		}

		class DataSource : UITableViewSource {

			RootViewController Controller { get; set; }
			Task DownloadTask { get; set; }
			UIImage PlaceholderImage { get; set; }

			public DataSource (RootViewController controller)
			{
				Controller = controller;

				// Listen for changes to the Apps collection so the TableView can be updated
				Controller.Apps.CollectionChanged += HandleAppsCollectionChanged;
				// Initialise DownloadTask with an empty and complete task
				DownloadTask = Task.Factory.StartNew (() => { });
				// Load the Placeholder image so it's ready to be used immediately
				PlaceholderImage = UIImage.FromFile ("Images/Placeholder.png");

				// If either a download fails or the image we download is corrupt, ignore the problem.
				TaskScheduler.UnobservedTaskException += delegate(object sender, UnobservedTaskExceptionEventArgs e) {
					e.SetObserved ();
				};
			}

			void HandleAppsCollectionChanged (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
			{
				// Whenever the Items change, reload the data.
				Controller.TableView.ReloadData ();
			}

			public override nint NumberOfSections (UITableView tableView)
			{
				return 1;
			}

			public override nint RowsInSection (UITableView tableview, nint section)
			{
				return Controller.Apps.Count;
			}

			// Customize the appearance of table view cells.
			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				UITableViewCell cell;
				// If the list is empty, put in a 'loading' entry
				if (Controller.Apps.Count == 0 && indexPath.Row == 0) {
					cell = tableView.DequeueReusableCell ("Placeholder");
					if (cell == null) {
						cell = new UITableViewCell (UITableViewCellStyle.Subtitle, "Placeholder");
						cell.DetailTextLabel.TextAlignment = UITextAlignment.Center;
						cell.SelectionStyle = UITableViewCellSelectionStyle.None;
						cell.DetailTextLabel.Text = "Loading";
					}
					return cell;
				}

				cell = tableView.DequeueReusableCell ("Cell");
				if (cell == null) {
					cell = new UITableViewCell (UITableViewCellStyle.Subtitle, "Cell");
					cell.SelectionStyle = UITableViewCellSelectionStyle.None;
				}

				// Set the tag of each cell to the index of the App that
				// it's displaying. This allows us to directly match a cell
				// with an item when we're updating the Image
				var app = Controller.Apps [indexPath.Row];
				cell.Tag = indexPath.Row;
				cell.TextLabel.Text = app.Name;
				cell.DetailTextLabel.Text = app.Artist;

				// If the Image for this App has not been downloaded,
				// use the Placeholder image while we try to download
				// the real image from the web.
				if (app.Image == null) {
					app.Image = PlaceholderImage;
					BeginDownloadingImage (app, indexPath);
				}
				cell.ImageView.Image = app.Image;
				return cell;
			}

			void BeginDownloadingImage (App app, NSIndexPath path)
			{
				// Queue the image to be downloaded. This task will execute
				// as soon as the existing ones have finished.
				byte[] data = null;
				DownloadTask = DownloadTask.ContinueWith (prevTask => {
					try {
						UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
						using (var c = new GzipWebClient ())
							data = c.DownloadData (app.ImageUrl);
					} finally {
						UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
					}
				});

				// When the download task is finished, queue another task to update the UI.
				// Note that this task will run only if the download is successful and it
				// uses the CurrentSyncronisationContext, which on MonoTouch causes the task
				// to be run on the main UI thread. This allows us to safely access the UI.
				DownloadTask = DownloadTask.ContinueWith (t => {
					// Load the image from the byte array.
					app.Image = UIImage.LoadFromData (NSData.FromArray (data));

					// Retrieve the cell which corresponds to the current App. If the cell is null, it means the user
					// has already scrolled that app off-screen.
					var cell = Controller.TableView.VisibleCells.Where (c => c.Tag == Controller.Apps.IndexOf (app)).FirstOrDefault ();
					if (cell != null)
						cell.ImageView.Image = app.Image;
				}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext ());
			}
		}
	}
}


text:
module ScorchedEarth
  module Events
    MouseReleased = Struct.new(:x, :y)
  end
end


text:
from base64 import b64encode
from datetime import datetime, timedelta
import uuid
import time

from parknyc.exceptions import *  # noqa

try:
    from urllib.parse import urljoin
except ImportError:
    from urlparse import urljoin

import requests

API_BASE_URL = "https://parknyc.parkmobile.us/phonixxapi/"
API_BASE_PAYLOAD = {"appId": "PhonixxWeb", "appVersion": "1", "scope": "Api"}

class NYCParkingService:
    """NYC Parking service wrapper class."""

    def __init__(self, username, password):
        self.session = requests.Session()
        self.session.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36",
            "SourceAppKey": "NycMobile",
        }
        self.session.get("https://parknyc.parkmobile.us/parknyc/app/#/login")  # visit main page

        auth_header = b64encode("{username}:{password}".format(username=username, password=password).encode("utf-8")).decode('utf-8')

        self.__login(auth_header)
        self.__get_identity()

    def __login(self, auth_header):
        # get the authentication token
        response = self.session.post(urljoin(API_BASE_URL, "Token2?format=json"),
                                     json=API_BASE_PAYLOAD,
                                     headers={"Authorization": "Basic {auth_header}".format(auth_header=auth_header)})
        if response.status_code == 400:
            raise InvalidCredentialsError("Invalid credentials")

        data = response.json()
        self.session.headers.update({"PMAuthenticationToken": data['token']})

    def __get_identity(self):
        """Gets the service identity information."""
        response = self.session.get(urljoin(API_BASE_URL, "account/identify2"))
        return response.json()

    def history_sessions(self):
        """Generates history parking session data."""
        response = self.session.get(urljoin(API_BASE_URL, "parking/history"))

        if response.status_code == 404:
            raise NoDataFoundError("No historical parking sessions found")

        for session in response.json()['actions']:
            yield session

    def active_sessions(self):
        """Generates active parking session data."""
        response = self.session.get(urljoin(API_BASE_URL, "parking/active"))

        if response.status_code == 404:
            raise NoDataFoundError("No active parking sessions found")

        for session in response.json()['actions']:
            yield session

    def start_session(self, zone, duration, vehicle_idx=0):
        """
        Starts parking at the given zone for a given amount of time.
        :param zone: zone number as an integer or a string
        :param duration: parking duration as an int - number of minutes
        :param vehicle_idx: vehicle to park as an index of the vehicle array (integer)
        """
        response = self.session.get(urljoin(API_BASE_URL, "parking/zones/{zone}".format(zone=zone)))

        if response.status_code == 404:
            raise NoParkingZoneError("Zone '{zone}' is not a valid parking zone")

        # check that the given duration is supported for this zone
        zone_data = response.json()['zones'][0]
        available_durations = [
            selection['hour'] * 60 + minute_selection
            for selection in zone_data['parkInfo']['durationSelections']['hourMinuteDurationSelections']
            for minute_selection in selection['minutes']
        ]
        if duration not in available_durations:
            raise InvalidParkingSessionDuration(
                "Duration {duration} is not valid. Available options are: {available_durations}".format(duration=duration,
                                                                                available_durations=", ".join(available_durations)))
        vehicle_data = self.get_vehicles()['vehicles'][vehicle_idx]

        self.__park(zone_data, vehicle_data, duration)

    def get_vehicles(self):
        # TODO: Add pagination in case there are more than 150 vehicles
        response = self.session.get(urljoin(API_BASE_URL, "account/vehicles?page=1&pageSize=150&noCache={ts}".format(ts=int(time.time()))))
        if response.status_code == 404:
            raise NoDataFoundError("No configured vehicles found in the account")

        return response.json()

    def __park(self, zone_data, vehicle_data, duration):
        """
        Parks the car taking into account the zone, vehicle data and duration.
        Returns parking ID of the new session.
        """

        # generate temporary token
        token = str(uuid.uuid1()).replace("-", "")

        # post verification token - only 404 would mean we can proceed
        response = self.session.post(urljoin(API_BASE_URL, "parking/verification"), data={"token": token})
        if response.status_code != 404:
            raise VerificationFailedError("Could not verify parking information")

        # prepare the payload
        now = datetime.utcnow()
        start_time = now.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        end_time = (now + timedelta(minutes=duration)).strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        data = {
            "id": 0,
            "internalZoneCode": zone_data['internalZoneCode'],
            "spaceNumber": "",
            "pushToken": "",
            "device": "",
            "SourceAppKey": "NycMobile",
            "vehicleId": vehicle_data['vehicleId'],
            "vehicleVrn": vehicle_data['vrn'],
            "vehicleVrnState": vehicle_data['state'],
            "durationInMinutes": duration,
            "verification": {"isExtention": False,
                             "lpn": "",
                             "parkingActionId": 0,
                             "token": token,
                             "zoneCode": zone_data['signageCode']},
            "selectedBillingMethodId": None,
            "selectedDiscounts": "{NONE}",
            "startTimeLocal": start_time,
            "stopTimeLocal": end_time,
            "vehicleVin": "",
            "masterPassTransaction": False,
            "lon": "",
            "lat": ""
        }
        response = self.session.post(urljoin(API_BASE_URL, "parking/active"), json=data)

        if response.status_code != 201:
            raise CannotStartParkingSessionError("Cannot start new parking session")

        return response.json()['parkingActionId']


text:
function [is_good, T_initial] = sample2track(parameters_filename, initial_filename, transition_filename, varargin)
    % Copyright 2008 - 2021, MIT Lincoln Laboratory
    % SPDX-License-Identifier: BSD-2-Clause
    % See also RUN_2_sample2track, em_read

    %% Input Parser
    p = inputParser;

    % Required
    addRequired(p, 'parameters_filename');
    addRequired(p, 'initial_filename');
    addRequired(p, 'transition_filename');

    % Optional
    addParameter(p, 'num_max_tracks', 10000, @isnumeric);

    % Optional - Output Directory
    addParameter(p, 'out_dir_parent', [getenv('AEM_DIR_BAYES') filesep 'output' filesep 'tracks']);

    % Optional - Initial
    % These need to align with parameters.labels_initial
    % Note that not all models may have these variables / labels
    % These labels can be calculated via:
    % matlab.lang.makeValidName(erase(parameters.labels_initial,{'"','\'}));
    addParameter(p, 'label_initial_geographic', 'G');
    addParameter(p, 'label_initial_airspace', 'A');
    addParameter(p, 'label_initial_altitude', 'L');
    addParameter(p, 'label_initial_speed', 'v');
    addParameter(p, 'label_initial_acceleration', 'dotV');
    addParameter(p, 'label_initial_vertrate', 'dotH');
    addParameter(p, 'label_initial_turnrate', 'dotPsi');

    % Optional - Transition
    % These need to align with parameters.labels_transition
    % Note that not all models may have these variables / labels
    % These labels can be calculated via:
    % matlab.lang.makeValidName(erase(parameters.labels_transition(parameters.temporal_map(:,2)),{'"','\'}))
    addParameter(p, 'label_transition_speed', 'dotV_t_1_'); % \dot v(t+1)
    addParameter(p, 'label_transition_altitude', 'dotH_t_1_'); % \dot h(t+1)
    addParameter(p, 'label_transition_heading', 'dotPsi_t_1_'); % \dot \psi(t+1)

    % Optional - Boundaries
    addParameter(p, 'isOverwriteZeroBoundaries', false, @islogical); % If true
    addParameter(p, 'idxZeroBoundaries', [1 2 3], @isnumeric); % Index of parameters.boundaries to force to be zero / empty

    % Optional - Rejection Sampling
    addParameter(p, 'min_altitude_ft', 0, @isnumeric);

    % Optional
    addParameter(p, 'rng_seed', 42, @isnumeric); % Random seed
    addParameter(p, 'isPlot', false, @islogical);

    % Parse
    parse(p, parameters_filename, initial_filename, transition_filename, varargin{:});

    %% Set random seed
    rng(p.Results.rng_seed, 'twister');

    %% Load files
    % Parameters
    parameters = em_read(parameters_filename, 'isOverwriteZeroBoundaries', p.Results.isOverwriteZeroBoundaries, 'idxZeroBoundaries', p.Results.idxZeroBoundaries);

    labels_init = matlab.lang.makeValidName(erase(parameters.labels_initial, {'"', '\'}))';
    labels_trans = matlab.lang.makeValidName(erase(parameters.labels_transition(parameters.temporal_map(:, 2)), {'"', '\'}))';

    % Initial
    T_initial = readtable(initial_filename, 'Delimiter', ' ', 'HeaderLines', 1, 'EndOfLine', '\n');
    T_initial.Properties.VariableNames = [{'id'}; labels_init];

    % Transition
    T_transition = readtable(transition_filename, 'Delimiter', ' ', 'HeaderLines', 1, 'EndOfLine', '\n');
    T_transition.Properties.VariableNames = [{'id'}; {'t'}; labels_trans];

    %% Filter to desired number tracks
    if size(T_initial, 1) > p.Results.num_max_tracks
        T_initial = T_initial(randperm(size(T_initial, 1), p.Results.num_max_tracks), :);
    end
    num_tracks = size(T_initial, 1);

    %% Find column indicies
    % Initial
    idx_initial_geographic = find(strcmp(T_initial.Properties.VariableNames, p.Results.label_initial_geographic));
    idx_initial_airspace = find(strcmp(T_initial.Properties.VariableNames, p.Results.label_initial_airspace));
    idx_initial_altitude = find(strcmp(T_initial.Properties.VariableNames, p.Results.label_initial_altitude));
    idx_initial_speed = find(strcmp(T_initial.Properties.VariableNames, p.Results.label_initial_speed));
    idx_initial_acceleration = find(strcmp(T_initial.Properties.VariableNames, p.Results.label_initial_acceleration));
    idx_initial_vertrate = find(strcmp(T_initial.Properties.VariableNames, p.Results.label_initial_vertrate));

    % Updates / transition
    idx_update_acc = find(strcmp(T_transition.Properties.VariableNames, p.Results.label_transition_speed));
    idx_update_vertrate = find(strcmp(T_transition.Properties.VariableNames, p.Results.label_transition_altitude));
    idx_update_turnrate = find(strcmp(T_transition.Properties.VariableNames, p.Results.label_transition_heading));

    % Bounds
    idx_bound_alt = find(strcmp(labels_init, p.Results.label_initial_altitude));
    idx_bound_speed = find(strcmp(labels_init, p.Results.label_initial_speed));

    %% For rejection sampling and load balancing
    % Altitude bound
    min_alt = parameters.boundaries{idx_bound_alt}(1);
    max_alt = parameters.boundaries{idx_bound_alt}(end);

    % Airspeed bound
    min_speed = parameters.boundaries{idx_bound_speed}(1);
    max_speed = parameters.boundaries{idx_bound_speed}(end);

    %% Parse parameters_filename
    pfn = strsplit(parameters_filename, filesep);

    % Check if model is one of the many unconventional models
    is_unconv = any(strcmp(strrep(pfn{end}, '.txt', ''), {'balloon_v1p2', 'blimp_v1', 'fai1_v1', 'fai5_v1', 'glider_v1p2', 'paraglider_v1p2', 'paramotor_v1', 'skydiving_v1', 'weatherballoon_v1'}));

    %% The position output is in feet, so we need to determine the appropriate unit conversions
    if ~isempty(strfind(pfn{end}, 'uncor_')) || is_unconv
        % Uncorrelated and unconventional models
        % % https://www.ll.mit.edu/sites/default/files/publication/doc/2018-12/Edwards_2009_ATC-348_WW-18098.pdf
        ur_speed = unitsratio('ft', 'nm') / 3600; % Knots to feet per second
        ur_vertrate = unitsratio('ft', 'ft') / 60; % Feet per minute to feet per second
        ur_heading = 1; % Degrees per second to degrees per second
    else
        warning('sample2track:model', '%s has not been tested with these function, assigning default units\n', pfn{end});
        ur_speed = unitsratio('ft', 'nm') / 3600; % Knots to feet per second
        ur_vertrate = unitsratio('ft', 'ft') / 60; % Feet per minute to feet per second
        ur_heading = 1; % Degrees per second to degrees per second
    end

    %% Apply unit conversions
    % Initial
    T_initial.(idx_initial_speed) = T_initial.(idx_initial_speed) * ur_speed;
    T_initial.(idx_initial_acceleration) = T_initial.(idx_initial_acceleration) * ur_speed;
    T_initial.(idx_initial_vertrate) = T_initial.(idx_initial_vertrate) * ur_vertrate;

    % Transition
    T_transition.(idx_update_vertrate) = T_transition.(idx_update_vertrate) * ur_vertrate;
    T_transition.(idx_update_acc) = T_transition.(idx_update_acc) * ur_speed;
    T_transition.(idx_update_turnrate) = T_transition.(idx_update_turnrate) * ur_heading;

    % Bounds
    min_speed = min_speed * ur_speed;
    max_speed = max_speed * ur_speed;

    %% Determine if variable exists
    is_geographic = ~isempty(idx_initial_geographic);
    is_airspace = ~isempty(idx_initial_airspace);

    %% Create parent output directories
    % Parent
    if exist(p.Results.out_dir_parent, 'dir') ~= 7
        mkdir(p.Results.out_dir_parent);
    end

    % Determine altitude range with a step size of 100
    if mod(min_alt, 1e2) ~= 0
        L = (floor(min_alt - 50):1e2:max_alt + 2e2)';
    else
        L = (min_alt:1e2:max_alt + 2e2)';
    end
    if L(1) < 0
        L(1) = 0;
    end

    % Subdirectories
    if ~isempty(strfind(pfn{end}, 'uncor_'))
        G = unique(T_initial.(idx_initial_geographic));
        A = unique(T_initial.(idx_initial_airspace));
        GAL = allcomb(G, A, L);
        for ii = 1:1:size(GAL, 1)
            ii_dir = [p.Results.out_dir_parent filesep sprintf('G%i', GAL(ii, 1)) filesep sprintf('A%i', GAL(ii, 2)) filesep sprintf('%ift', GAL(ii, 3))];
            if exist(ii_dir, 'dir') ~= 7
                mkdir(ii_dir);
            end
        end
        fprintf('Generated %i directories\n', size(GAL, 1));
    else
        for ii = 1:1:size(L, 1)
            mkdir([p.Results.out_dir_parent filesep sprintf('%ift', L(ii, 1))]);
        end
        fprintf('Generated %i directories\n', size(L, 1));
    end

    %% Iterate
    is_good = false(num_tracks, 1);
    for ii = 1:1:num_tracks
        % Set initial position
        time_s = 0;
        x_ft = 0;
        y_ft = 0;
        z_ft = T_initial{ii, idx_initial_altitude};
        speed_fps = T_initial{ii, idx_initial_speed};
        heading_deg = 0;

        % Filter transition for the ith id
        i_updates = T_transition(T_transition.id == T_initial.id(ii), :);
        max_time_s = size(i_updates, 1);

        % Iterate over time
        pInd = length(time_s);
        cInd = 1;
        while time_s(end) < max_time_s
            cInd = pInd + 1;
            time_s(cInd) = time_s(pInd) + 1;

            % Get updates
            update_vertrate = i_updates{pInd, idx_update_vertrate};
            update_acc = i_updates{pInd, idx_update_acc};
            update_turnrate = i_updates{pInd, idx_update_turnrate};

            % Apply Updates
            z_ft(cInd) = z_ft(pInd) + update_vertrate;
            speed_fps(cInd) = speed_fps(pInd) + update_acc;
            heading_deg(cInd) = heading_deg(pInd) + update_turnrate;

            x_ft(cInd) = x_ft(pInd) + speed_fps(pInd) * cosd(heading_deg(pInd));
            y_ft(cInd) = y_ft(pInd) + speed_fps(pInd) * sind(heading_deg(pInd));

            % Update counter
            pInd = cInd;
        end

        % Plot
        if p.Results.isPlot
            figure(ii);
            plot3(x_ft, y_ft, z_ft, '-*', 'Color', 'b', 'MarkerSize', 2);
            hold on;
            plot3(x_ft(1), y_ft(1), z_ft(1), 's', 'Color', 'r', 'MarkerSize', 10);
            hold off;
            legend('Track', 'Start');
            xlabel('ft');
            ylabel('ft');
            zlabel('ft');
            grid on;
        end

        % Determine if track hits the ground
        is_cfit = false;
        if any(z_ft < 0)
            is_cfit = true;
        end

        % Rejection Sampling - Speed
        is_reject_speed = any(speed_fps <= min_speed | speed_fps >= max_speed);

        % Determine if track is good
        is_good(ii) = ~is_cfit & ~is_reject_speed;

        % Only write to file if no CFIT
        % For load balancing, create subdirectories on model variables
        if is_good(ii)
            % Create filename
            out_name = sprintf('BAYES_t%i_id%i_alt%i_speed%i.csv', max_time_s, ii, round(z_ft(1)), round(speed_fps(1)));

            % Subdirectory for geographic variable, if it exists
            out_dir_child = [];
            if is_geographic
                out_dir_child = sprintf('G%i', T_initial.(idx_initial_geographic)(ii));
            end

            % Subdirectory for airspace class variable, if it exists
            if is_airspace
                out_dir_child = [out_dir_child filesep sprintf('A%i', T_initial.(idx_initial_airspace)(ii))];
            end

            % Subdirectory for initial altitude, always use
            out_dir_alt = L(discretize(z_ft(1), L));
            if isempty(out_dir_child)
                out_dir_child = sprintf('%ift', out_dir_alt);
            else
                out_dir_child = [out_dir_child filesep sprintf('%ift', out_dir_alt)];
            end

            % Create output directory
            out_dir = [p.Results.out_dir_parent filesep out_dir_child];

            % Write to file
            fileId = fopen([out_dir filesep out_name], 'w+', 'native', 'UTF-8');
            if fileId ~= -1
                fprintf(fileId, 'time_s,x_ft,y_ft,z_ft\n');
                fprintf(fileId, '%i,%0.0f,%0.0f,%0.0f\n', [time_s; x_ft; y_ft; z_ft]);
                fclose(fileId);
            else
                warning('sample2tracK:fileid', 'Cant open %s\n', [out_dir filesep out_name]);
            end
        else
            fprintf('Reject i=%i, CFIT = %i, v = [%0.3f, %0.3f]\n', ii, is_cfit, min(speed_fps), max(speed_fps));
        end
    end


text:
package cz.metacentrum.perun.webgui.client;

import com.google.gwt.core.client.*;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import cz.metacentrum.perun.webgui.client.localization.ApplicationMessages;
import cz.metacentrum.perun.webgui.client.passwordresetresources.PasswordResetFormPage;
import cz.metacentrum.perun.webgui.client.passwordresetresources.PasswordResetLeftMenu;
import cz.metacentrum.perun.webgui.client.resources.LargeIcons;
import cz.metacentrum.perun.webgui.client.resources.SmallIcons;
import cz.metacentrum.perun.webgui.client.resources.Utils;
import cz.metacentrum.perun.webgui.json.GetGuiConfiguration;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.authzResolver.GetPerunPrincipal;
import cz.metacentrum.perun.webgui.json.registrarManager.VerifyCaptcha;
import cz.metacentrum.perun.webgui.model.BasicOverlayType;
import cz.metacentrum.perun.webgui.model.PerunError;
import cz.metacentrum.perun.webgui.model.PerunPrincipal;
import cz.metacentrum.perun.webgui.widgets.*;
import cz.metacentrum.perun.webgui.widgets.CustomButton;
import cz.metacentrum.perun.webgui.widgets.recaptcha.RecaptchaWidget;

/**
 * The main Password Reset GUI class. It's GWT Entry point.
 *
 * Loads whole GUI, makes login to RPC by calling GetPerunPrincipal
 *
 * @author Pavel Zlamal <256627@mail.muni.cz>
 */
public class PasswordResetGui implements EntryPoint {

	// web session
	private PerunWebSession session = PerunWebSession.getInstance();
	private PasswordResetLeftMenu leftMenu;

	/**
	 * Main content panel
	 */
	private ScrollPanel contentPanel = new ScrollPanel();

	/**
	 * This is ENTRY POINT method. It's called automatically when web page
	 * containing this GUI is loaded in browser.
	 */
	public void onModuleLoad() {

		ScriptInjector.fromUrl("https://www.google.com/recaptcha/api/js/recaptcha_ajax.js").setCallback(
				new Callback<Void, Exception>() {
					public void onFailure(Exception reason) {
						Window.alert("Script load failed.");
					}

					public void onSuccess(Void result) {
						loadModule();
					}
				}).setWindow(ScriptInjector.TOP_WINDOW).inject();
	}

	private void loadModule() {

		// perun web session
		session = PerunWebSession.getInstance();

		// basic settings
		session.setUiElements(new UiElements(null));

		// Get web page's BODY
		RootLayoutPanel body = RootLayoutPanel.get();
		body.setStyleName("mainPanel");

		// check RPC url
		if(session.getRpcUrl().isEmpty()){
			VerticalPanel bodyContents = new VerticalPanel();
			bodyContents.setSize("100%", "300px");
			bodyContents.add(new HTML(new Image(LargeIcons.INSTANCE.errorIcon())+"
RPC SERVER NOT FOUND !
"));
			bodyContents.setCellHorizontalAlignment(bodyContents.getWidget(0), HasHorizontalAlignment.ALIGN_CENTER);
			bodyContents.setCellVerticalAlignment(bodyContents.getWidget(0), HasVerticalAlignment.ALIGN_BOTTOM);
			body.add(bodyContents);
			return;
		}

		// WEB PAGE SPLITTER
		DockLayoutPanel bodySplitter = new DockLayoutPanel(Unit.PX);
		body.add(bodySplitter);

		// left menu
		//leftMenu = new PasswordResetLeftMenu();
		// bodySplitter.addWest(leftMenu, 240);

		// MAIN CONTENT
		contentPanel.setSize("100%", "100%");
		//contentPanel.add(leftMenu.getContent());
		bodySplitter.add(contentPanel);

		loadPerunPrincipal();

	}

	/**
	 * Performs a login into the RPC, loads user and his roles into session and enables GUI.
	 */
	private void loadPerunPrincipal() {

		// show loading box
		final PopupPanel loadingBox = session.getUiElements().perunLoadingBox();
		loadingBox.show();

		// events after getting PerunPrincipal from RPC
		final JsonCallbackEvents events = new JsonCallbackEvents() {
			@Override
			public void onFinished(JavaScriptObject jso) {

				// store perun principal into session for future use
				PerunPrincipal pp = (PerunPrincipal)jso;
				session.setPerunPrincipal(pp);

				// check if user exists
				if (session.getUser() != null && !pp.getRoles().hasAnyRole() && !session.getRpcUrl().startsWith("/non/rpc")) {
					// if not and no role, redraw page body
					RootLayoutPanel body = RootLayoutPanel.get();
					loadingBox.hide();
					body.clear();
					body.add(new NotUserOfPerunWidget());
					return;
				}

				if (session.getUser() != null && !pp.getRoles().hasAnyRole()) {

					// store users roles and editable entities into session
					session.setRoles(pp.getRoles());

					// display logged user
					session.getUiElements().setLoggedUserInfo(pp);

				}

				GetGuiConfiguration getConf = new GetGuiConfiguration(new JsonCallbackEvents(){
					@Override
					public void onFinished(JavaScriptObject jso) {

						session.setConfiguration((BasicOverlayType)jso.cast());

						// hides the loading box
						loadingBox.hide();

						if (session.getRpcUrl().startsWith("/non/rpc")) {

							// CHALLENGE WITH CAPTCHA

							FlexTable ft = new FlexTable();
							ft.setSize("100%", "500px");

							// captcha with public key
							String key = Utils.getReCaptchaPublicKey();
							if (key == null) {

								PerunError error = new JSONObject().getJavaScriptObject().cast();
								error.setErrorId("0");
								error.setName("Missing public key");
								error.setErrorInfo("Public key for Re-Captcha service is missing. Please add public key to GUIs configuration file.");
								error.setRequestURL("");
								UiElements.generateError(error, "Missing public key", "Public key for Re-Captcha service is missing.
Accessing password reset without authorization is not possible.");
								loadingBox.hide();
								return;
							}

							final RecaptchaWidget captcha = new RecaptchaWidget(key, LocaleInfo.getCurrentLocale().getLocaleName(), "clean");

							final CustomButton cb = new CustomButton();
							cb.setIcon(SmallIcons.INSTANCE.arrowRightIcon());
							cb.setText(ApplicationMessages.INSTANCE.captchaSendButton());
							cb.setImageAlign(true);

							final TextBox response = new TextBox();
							captcha.setOwnTextBox(response);

							Scheduler.get().scheduleDeferred(new Command() {
								@Override
								public void execute() {
									response.setFocus(true);
								}
							});

							response.addKeyDownHandler(new KeyDownHandler() {
								@Override
								public void onKeyDown(KeyDownEvent event) {
									if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
										cb.click();
									}
								}
							});

							cb.addClickHandler(new ClickHandler() {
								@Override
								public void onClick(ClickEvent clickEvent) {
									VerifyCaptcha req = new VerifyCaptcha(captcha.getChallenge(), captcha.getResponse(), JsonCallbackEvents.disableButtonEvents(cb, new JsonCallbackEvents() {
										public void onFinished(JavaScriptObject jso) {

											BasicOverlayType bt = jso.cast();
											if (bt.getBoolean()) {

												// OK captcha answer - load GUI

												// add menu item and load content
												contentPanel.setWidget(new PasswordResetFormPage().getContent());
												//Anchor a = leftMenu.addMenuContents("Password reset", SmallIcons.INSTANCE.keyIcon(), new PasswordResetFormPage().getContent());
												//a.fireEvent(new ClickEvent(){});

											} else {
												// wrong captcha answer
												UiElements.generateAlert(ApplicationMessages.INSTANCE.captchaErrorHeader(), ApplicationMessages.INSTANCE.captchaErrorMessage());
											}
										}
									}));
									req.retrieveData();
								}
							});

							// set layout

							int row = 0;

							ft.getFlexCellFormatter().setAlignment(row, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);
							ft.setHTML(row, 0, "
In order to continue to the password reset page, please, use CAPTCHA below.
");
							ft.setWidget(row + 1, 0, captcha);
							ft.getFlexCellFormatter().setHorizontalAlignment(row + 1, 0, HasHorizontalAlignment.ALIGN_CENTER);
							ft.getFlexCellFormatter().setVerticalAlignment(row + 1, 0, HasVerticalAlignment.ALIGN_BOTTOM);

							FlexTable sendFt = new FlexTable();
							sendFt.setStyleName("inputFormFlexTable");

							sendFt.setWidget(0, 0, response);
							sendFt.setWidget(0, 1, cb);

							ft.setWidget(row + 2, 0, sendFt);
							ft.getFlexCellFormatter().setHorizontalAlignment(row + 2, 0, HasHorizontalAlignment.ALIGN_CENTER);
							ft.getFlexCellFormatter().setVerticalAlignment(row + 2, 0, HasVerticalAlignment.ALIGN_TOP);

							ft.setHeight("100%");
							ft.getFlexCellFormatter().setHeight(row, 0, "50%");
							ft.getFlexCellFormatter().setHeight(row + 2, 0, "50%");

							// finish loading GUI
							loadingBox.hide();
							contentPanel.setWidget(ft);

						} else {

							// add menu item and load content
							contentPanel.setWidget(new PasswordResetFormPage().getContent());
							//Anchor a = leftMenu.addMenuContents("Password reset", SmallIcons.INSTANCE.keyIcon(), new PasswordResetFormPage().getContent());
							//a.fireEvent(new ClickEvent(){});

						}

					}
				@Override
				public void onError(PerunError error){
					// hides the loading box
					loadingBox.hide();

					// shows error box
					PopupPanel loadingFailedBox;
					if (error == null) {
						loadingFailedBox = session.getUiElements().perunLoadingFailedBox("Request timeout exceeded.");
					} else {
						if (error.getName().contains("UserNotExistsException")) {
							loadingFailedBox = session.getUiElements().perunLoadingFailedBox("You are not registered to any Virtual Organization.

" + error.getErrorInfo());
						} else {
							loadingFailedBox = session.getUiElements().perunLoadingFailedBox(error.getErrorInfo());
						}
					}
					loadingFailedBox.show();

					leftMenu.addItem("Password reset", SmallIcons.INSTANCE.keyIcon(), null);

				}
				});
				getConf.retrieveData();

			}
			@Override
			public void onError(PerunError error){
				// hides the loading box
				loadingBox.hide();

				// shows error box
				PopupPanel loadingFailedBox;
				if (error == null) {
					loadingFailedBox = session.getUiElements().perunLoadingFailedBox("Request timeout exceeded.");
				} else {
					if (error.getName().contains("UserNotExistsException")) {
						loadingFailedBox = session.getUiElements().perunLoadingFailedBox("You are not registered to any Virtual Organization.

" + error.getErrorInfo());
					} else {
						loadingFailedBox = session.getUiElements().perunLoadingFailedBox(error.getErrorInfo());
					}
				}
				loadingFailedBox.show();

				leftMenu.addItem("Password reset", SmallIcons.INSTANCE.keyIcon(), null);

			}
		};
		GetPerunPrincipal loggedUserRequest = new GetPerunPrincipal(events);
		loggedUserRequest.retrieveData();
	}

}


text:
<?php
/**
 * This file content the routines for install/activate  uninstall/deactivate Magic Fields
 */
class mf_install {

  function install () {
    global $wpdb;

    require_once(ABSPATH.'wp-admin/includes/upgrade.php');

		// Get collation info
		$charset_collate = "";
		if ( ! empty($wpdb->charset) )
			$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
		if ( ! empty($wpdb->collate) )
			$charset_collate .= " COLLATE $wpdb->collate";

    //checking if the table is already installed

    if($wpdb->get_var( sprintf("SHOW tables LIKE '%s'",MF_TABLE_POSTTYPES) ) != MF_TABLE_POSTTYPES) {
      $sql = "CREATE TABLE ".MF_TABLE_POSTTYPES. " (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        type varchar(20) NOT NULL,
        name varchar(50) NOT NULL,
        description text,
        arguments text,
        active tinyint(1) DEFAULT 1,
        PRIMARY KEY id (id) ) $charset_collate
      ";
      dbDelta($sql);
    }

    // Table custom taxonomy
    if($wpdb->get_var( sprintf("SHOW tables LIKE '%s'",MF_TABLE_CUSTOM_TAXONOMY) ) != MF_TABLE_CUSTOM_TAXONOMY) {
      $sql = "CREATE TABLE ".MF_TABLE_CUSTOM_TAXONOMY. " (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        type varchar(20) NOT NULL,
        name varchar(50) NOT NULL,
        description text,
        arguments text,
        active tinyint(1) DEFAULT 1,
        PRIMARY KEY id (id) ) $charset_collate
      ";
      dbDelta($sql);
    }

    // Table custom fields
    if($wpdb->get_var( sprintf("SHOW tables LIKE '%s'",MF_TABLE_CUSTOM_FIELDS) ) != MF_TABLE_CUSTOM_FIELDS) {
      $sql = "CREATE TABLE ".MF_TABLE_CUSTOM_FIELDS. " (
        id int(19) NOT NULL AUTO_INCREMENT,
        name varchar(150) NOT NULL,
        label varchar(150) NOT NULL,
        description text,
        post_type varchar(120) NOT NULL,
        custom_group_id int(19) NOT NULL,
        type varchar(100) NOT NULL,
        required_field tinyint(1),
        display_order mediumint(9) DEFAULT 0,
        duplicated tinyint(1),
        active tinyint(1) DEFAULT 1,
        options text,
        PRIMARY KEY id (id) ) $charset_collate
      ";
      dbDelta($sql);
    }

    // Table custom groups
    if($wpdb->get_var( sprintf("SHOW tables LIKE '%s'",MF_TABLE_CUSTOM_GROUPS) ) != MF_TABLE_CUSTOM_GROUPS) {
      $sql = "CREATE TABLE ".MF_TABLE_CUSTOM_GROUPS. " (
        id integer NOT NULL AUTO_INCREMENT,
        name varchar(255) NOT NULL,
        label varchar(255) NOT NULL,
        post_type varchar(255) NOT NULL,
        duplicated tinyint(1) DEFAULT 0,
        expanded tinyint(1) DEFAULT 0,
        PRIMARY KEY id (id) ) $charset_collate
      ";
      dbDelta($sql);

    }

    // Table MF Post Meta
    if( $wpdb->get_var( sprintf("SHOW tables LIKE '%s'",MF_TABLE_POST_META) ) != MF_TABLE_POST_META ) {
      $sql = "CREATE TABLE ".MF_TABLE_POST_META." (
        meta_id INT NOT NULL,
        field_name VARCHAR(255) NOT NULL,
        field_count INT NOT NULL,
        group_count  INT NOT NULL,
        post_id INT NOT NULL,
        PRIMARY KEY meta_id (meta_id),
        INDEX idx_post_field (post_id, meta_id) ) $charset_collate
				";

      dbDelta($sql);
    }

    if ( get_option( MF_DB_VERSION_KEY, FALSE ) === FALSE ) update_option(MF_DB_VERSION_KEY, MF_DB_VERSION);

    if (get_option(MF_DB_VERSION_KEY) < MF_DB_VERSION){
      self::upgrade();
      update_option(MF_DB_VERSION_KEY, MF_DB_VERSION);
    }

  }

  public function upgrade(){
    global $wpdb;

    $db_version = get_option(MF_DB_VERSION_KEY);

    if( $db_version < 2 ) {
      $sql = "ALTER TABLE ".MF_TABLE_CUSTOM_FIELDS. " CHANGE COLUMN requiered_field required_field tinyint(1)";
      $wpdb->query( $sql );
    }
    if ($db_version < 3) {
      //add index for mf post meta
      $sql = "ALTER TABLE ".MF_TABLE_POST_META. " ADD INDEX idx_post_field (post_id, meta_id)";
      $wpdb->query( $sql );
    }

    update_option(MF_DB_VERSION_KEY, MF_DB_VERSION);
  }

  public static function folders(){
    global $mf_domain;

    $dir_list = "";
    $dir_list2 = "";

    wp_mkdir_p(MF_FILES_DIR);
    wp_mkdir_p(MF_CACHE_DIR);

    if (!is_dir(MF_CACHE_DIR)){
      $dir_list2.= "
".MF_CACHE_DIR . "
";
    }elseif (!is_writable(MF_CACHE_DIR)){
      $dir_list.= "
".MF_CACHE_DIR . "
";
    }

    if (!is_dir(MF_FILES_DIR)){
      $dir_list2.= "
".MF_FILES_DIR . "
";
    }elseif (!is_writable(MF_FILES_DIR)){
      $dir_list.= "
".MF_FILES_DIR . "
";
    }

    if ($dir_list2 != ""){
      echo "

".__('Magic Fields is not ready yet.', $mf_domain)." ".__('must create the following folders (and must chmod 777):', $mf_domain)."

";
      echo $dir_list2;
      echo "

";
    }
    if ($dir_list != ""){
      echo "

".__('Magic Fields is not ready yet.', $mf_domain)." ".__('The following folders must be writable (usually chmod 777 is neccesary):', $mf_domain)."

";
      echo $dir_list;
      echo "

";
    }

  }

  //delete cache
  public function clear_cache(){
    if (is_dir(MF_CACHE_DIR)) {
      if ($dh = opendir(MF_CACHE_DIR)) {
        while (($file = readdir($dh)) !== false) {
          if(!is_dir($file) && !in_array($file,array('.','..','.DS_Store') ) ){
            @unlink(MF_CACHE_DIR.$file);
          }
        }
        closedir($dh);
      }
    }
  }

  public function delete_files(){
    if (is_dir(MF_FILES_DIR)) {
      if ($dh = opendir(MF_FILES_DIR)) {
        while (($file = readdir($dh)) !== false) {
          if(!is_dir($file) && !in_array($file,array('.','..','.DS_Store') ) ){
            @unlink(MF_FILES_DIR.$file);
          }
        }
        closedir($dh);
      }
    }
  }

  //unistall MF (delete thumbs, tables and settings)
  public function uninstall(){
    global $wpdb;

    self::clear_cache();
    self::delete_files();
    delete_option(MF_SETTINGS_KEY);
    //DB version
    delete_option(MF_DB_VERSION_KEY);

    $sql = "DELETE a.* FROM $wpdb->postmeta AS a, ".MF_TABLE_POST_META." AS b WHERE b.meta_id = a.meta_id";
    $wpdb->query($sql);

    $sql = "DROP TABLE " . MF_TABLE_POSTTYPES;
    $wpdb->query($sql);

    $sql = "DROP TABLE " . MF_TABLE_CUSTOM_TAXONOMY;
    $wpdb->query($sql);

    $sql = "DROP TABLE " . MF_TABLE_CUSTOM_FIELDS;
    $wpdb->query($sql);

    $sql = "DROP TABLE " . MF_TABLE_CUSTOM_GROUPS;
    $wpdb->query($sql);

    $sql = "DROP TABLE " . MF_TABLE_POST_META;
    $wpdb->query($sql);

    $current = get_option('active_plugins');
    $plugin = plugin_basename(MF_PATH.'/main.php');
    array_splice($current, array_search( $plugin, $current), 1 );
    do_action('deactivate_' . trim( $plugin ));
    update_option('active_plugins', $current);

    wp_redirect('options-general.php');
  }

}


text:
<!DOCTYPE html>

<title>How do I view reports for a specific site?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.sitestats.admin" name="description">
<meta content="" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/neo-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/neo-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I view reports for a specific site?

Go to Sitestats Admin.

Select the Sitestats Admin tool from the Tool Menu in the Administration Workspace.

Locate the site you want to view.

              Zoom

Enter a search term and click Search to locate the site you want to view.

All sites matching your criteria will be displayed.

Click on the title of the site.

              Zoom

The site's Statistics will display.

              Zoom

From this view, you may run any reports within the site the same way an instructor/maintain user would run reports within an individual site. See What is the Statistics tool? for more information on how to run reports.


text:
title: "ArgData: Working with Decompressed EXE files"
---

# Working with decompressed EXE files

To bring the file size (and perhaps memory usage) down, the original GP.EXE file
(just like many other old DOS games) is compressed with EXEPACK.
This means that repeating byte data is "compressed" by replacing it with a special
byte sequence which indicates which value has been compressed, and how many instances
of it that there originally was.

This is highly effective, bringing the size of the European 1.05 GP.EXE down
from 587 KB to 314 KB. However, in the case of editing Microprose Formula One Grand Prix,
this brings about some limitations.

- Helmets for drivers with number #13, #15, #36, #37, #38, #39 and #40 are forced to have the same colour for the bottom third of the helmet.
- The points system can only be edited for the top six finishers.

ArgData now has support for working with decompressed EXE files. These files work fine to run in e.g. DOSBox.

## Decompressing the EXE file

To enable/enhance various parts of F1GP, you can decompress the EXE file,
e.g. using using UNP v4.11, which can be downloaded
from unp.bencastricum.nl.

Since UNP is a 16-bit tool, it won't work out-of-the-box on 64-bit versions of Windows.
So the simplest way to run it is to put it in your F1GP folder and run the tool through DOSBox.

Run UNP by specifying your original GP.EXE and a name for the new, decompressed file (in this example GPDECOMP.EXE)

    > UNP.EXE GP.EXE GPDECOMP.EXE

This will decompress the file, and you should see some data written to the screen, like this (at least for a European 1.05 EXE file)

processing file : GP.EXE
DOS file size   : 321878
file-structure  : executable (EXE)
EXE part sizes  : header 512 bytes, image 321366 bytes, overlay 0 bytes
processed with  : LINK V3.69 /EXEPACK
action          : decompressing... done
new file size   : 600480
writing to file : GPDECOMP.EXE

The GPDECOMP.EXE file is now ready to roll!


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

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Mustache.Tests.Specs
{
    [TestClass]
    public class DelimitersTester
    {
        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void PairBehavior()
        {
            string templated = Template.Compile("{{=<% %>=}}(<%text%>)").Render(new { text = "Hey!" });
            Assert.AreEqual("(Hey!)", templated, "The equals sign (used on both sides) should permit delimiter changes");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void SpecialCharacters()
        {
            string templated = Template.Compile("({{=[ ]=}}[text])").Render(new { text = "It worked!" });
            Assert.AreEqual("(It worked!)", templated, "Characters with special meaning regexen should be valid delimiters");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void Sections()
        {
            const string template = @"
[
{{#section}}
    {{data}}
    |data|
{{/section}}

{{= | | =}}
|#section|
    {{data}}
    |data|
|/section|
]";
            const string expected = @"
[
    I got interpolated.
    |data|

    {{data}}
    I got interpolated.
]";
            string templated = Template.Compile(template).Render(new { section = true, data = "I got interpolated." });
            Assert.AreEqual(expected, templated, "Delimiters set outside sections should persist");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void InvertedSections()
        {
            const string template = @"[
{{^section}}
    {{data}}
    |data|
{{/section}}
{{= | | =}}
|^section|
    {{data}}
    |data|
|/section|
]";

            const string expected = @"[
    I got interpolated.
    |data|
    {{data}}
    I got interpolated.
]";

            string templated = Template.Compile(template).Render(new { section = false, data = "I got interpolated." });
            Assert.AreEqual(expected, templated, "Delimiters set outside inverted sections should persist");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void PartialInheritence()
        {
            const string template = @"{{<include}}.{{value}}.{{/include}}
[ {{>include}} ]
{{= | | =}}
[ |>include| ]";

            const string expected = @"[ .yes. ]
[ .yes. ]";
            string templated = Template.Compile(template).Render(new { value = "yes" });
            Assert.AreEqual(expected, templated, "Delimiters set in a parent template should not affect a partial");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void PostPartialBehavior()
        {
            const string template = @"{{<include}}.{{value}}. {{= | | =}} .|value|.|/include|
[ {{>include}} ]
[ .{{value}}.  .|value|. ]";
            const string expected = @"[ .yes.  .yes. ]
[ .yes.  .|value|. ]";

            string templated = Template.Compile(template).Render(new { value = "yes" });
            Assert.AreEqual(expected, templated, "Delimiters set in a partial should not affect the parent template");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void SurroundingWhitespace()
        {
            const string template = "| {{=@ @=}} |";
            const string expected = "|  |";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Surrounding whitespace should be left untouched");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void OutlyingWhitespaceInline()
        {
            const string template = " | {{=@ @=}}\n";
            const string expected = " | \n";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Whitespace should be left untouched");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void StandaloneTag()
        {
            const string template = @"|
Begin.
{{=@ @=}}
End.";
            const string expected = @"|
Begin.
End.";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Standalone lines should be removed from the template");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void IndentedStandaloneTag()
        {
            const string template = @"|
Begin.
    {{=@ @=}}
End.";
            const string expected = @"|
Begin.
End.";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Indented standalone lines should be removed from the template");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void StandaloneLineEndings()
        {
            const string template = "|\r\n{{= @ @ =}}\r\n|";
            const string expected = "|\r\n|";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "'\\r\\n' should be considered a newline for standalone tags");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void StandaloneWithoutPreviousLine()
        {
            const string template = "  {{=@ @=}}\n=";
            const string expected = "=";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Standalone tags should not require a newline to precede them");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void StandaloneWithoutNewline()
        {
            const string template = "=\n  {{=@ @=}}";
            const string expected = "=\n";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Standalone tags should not require a newline to follow them");
        }

        [TestMethod]
        [TestCategory("SpecsDelimiters")]
        public void PairWithPadding()
        {
            const string template = "|{{= @   @ =}}|";
            const string expected = "||";

            string templated = Template.Compile(template).Render(null);
            Assert.AreEqual(expected, templated, "Superfluous in-tag whitespace should be ignored");
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Travelling.FrameWork
{
    /// <summary>
    /// 加密
    /// </summary>
    public class AES
    {
        //默认密钥向量
        private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };

        public static string Encode(string encryptString, string encryptKey)
        {
            encryptKey = Utils.GetSubString(encryptKey, 32, "");
            encryptKey = encryptKey.PadRight(32, ' ');

            RijndaelManaged rijndaelProvider = new RijndaelManaged();
            rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
            rijndaelProvider.IV = Keys;
            ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();

            byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
            byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);

            return Convert.ToBase64String(encryptedData);
        }

        public static string Decode(string decryptString, string decryptKey)
        {
            if (decryptString == string.Empty)
            {
                return string.Empty;
            }
            try
            {
                decryptKey = Utils.GetSubString(decryptKey, 32, "");
                decryptKey = decryptKey.PadRight(32, ' ');

                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                rijndaelProvider.IV = Keys;
                ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();

                byte[] inputData = Convert.FromBase64String(decryptString);
                byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);

                return Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                return "";
            }

        }

    }

    /// <summary>
    /// 加密
    /// </summary>
    public class DES
    {
        //默认密钥向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public static string Encode(string encryptString, string encryptKey)
        {
            encryptKey = Utils.GetSubString(encryptKey, 8, "");
            encryptKey = encryptKey.PadRight(8, ' ');
            byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            byte[] rgbIV = Keys;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());

        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string Decode(string decryptString, string decryptKey)
        {
            try
            {
                decryptKey = Utils.GetSubString(decryptKey, 8, "");
                decryptKey = decryptKey.PadRight(8, ' ');
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return "";
            }
        }
    }
}


text:
package subGameByMapChangingSuper;

import java.awt.Point;

import javax.swing.Icon;

import utilities.MyPoint;

import basicConstruction.*;

public class PillarBuilding extends BuildingSolid
{
	public PillarBuilding(Icon surfaceImage, MyPoint location)
	{
		super(surfaceImage,location,100,true);

	}

	public PillarBuilding()
	{
		super();
	}

	public boolean isAccesible(MyPoint point) // ÕâÀïµÄµãÖ¸Ïà¶ÔͼƬ×óÉϽǵÄλÖ㬷´Ó³¸ø¶¨µÄÒ»µãÄܲ»ÄܽøÈë
	{
		double radius=getTotalSize().getWidth()/2.0;
		MyPoint center=new MyPoint(radius,radius);
		double distance=center.distance(point);
		if(distance<=radius)
		{
			return false;
		}
		else
		{
			return true;
		}

	}

	public boolean isAccesible(Point point) // ÕâÀïµÄµãÖ¸Ïà¶ÔͼƬ×óÉϽǵÄλÖ㬷´Ó³¸ø¶¨µÄÒ»µãÄܲ»ÄܽøÈë
	{
		double radius=getTotalSize().getWidth()/2.0;
		MyPoint center=new MyPoint(radius,radius);
		double distance=center.distance(point);
		if(distance<=radius)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	public boolean isAccesibleFromMap(MyPoint point)  //ÕâÀïµÄµãÖ¸Ïà¶Ô´óµØͼ×óÉϽǵÄλÖÃ
	{
		double distance=getDoubleCenterPoint().distance(point);
		double radius=getTotalSize().getWidth()/2.0;
		if(distance<=radius)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	public boolean isAccesibleFromMap(Point point)
	{
		double distance=getDoubleCenterPoint().distance(point);
		double radius=getTotalSize().getWidth()/2.0;
		if(distance<=radius)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>TodoMVC</title>
  <link rel="stylesheet" href="style.css"/>


text:
from sqlalchemy.ext.associationproxy import association_proxy

from octoprint_dashboard.app import db
from octoprint_dashboard.model import User

class Group(db.Model):
    """
    Instance of this class equals single record of config in database
    Class behaves like repository of Config records

    Group represent link between users and printers, single group has
    M:N users and M:N printers
    """
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    user = association_proxy("group_user", "user")

    def __init__(self, name=None):
        self.name = name

    def __repr__(self):
        return '<Group %r>' % self.name

    def editable(self, user: User):
        """Returns true if group is editable by given user else false"""
        from octoprint_dashboard.model import GroupUser
        if user.superadmin:
            return True

        role = GroupUser.query.join(User).join(Group).filter(User.id == user.id, Group.id == self.id).scalar().role
        if role == 'admin':
            return True

        return False


text:
package seedu.taskmanager.model.task;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TaskNameTest {

    // @@author A0141102H
    @Test
    public void isValidName() {
        // invalid task name
        assertFalse(TaskName.isValidName("")); // empty string
        assertFalse(TaskName.isValidName(" ")); // spaces only

        // valid task name
        assertTrue(TaskName.isValidName("eat food")); // alphabets only
        assertTrue(TaskName.isValidName("1 22 333 4444 55555")); // numbers only
        assertTrue(TaskName.isValidName("hungry b0i")); // alphanumeric
                                                        // characters
        assertTrue(TaskName.isValidName("EAT FOOD")); // with capital letters
        assertTrue(TaskName.isValidName("This is a run on sentence created" + "solely to prove a point")); // long
                                                                                // task
                                                                                // names
    }
}


text:
layout: page
title: Jason Andersen's 51st Birthday
date: 2016-05-24
author: Christopher Guzman
tags: weekly links, java
status: published
summary: In eleifend, dolor ut vehicula auctor, lacus.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 09/26/2017
  endDate: 10/01/2017
  ctyhocn: AMWHXHX
  groupCode: JA5B
published: true
---
In vitae molestie orci, a venenatis nibh. Cras dictum urna nibh, nec commodo leo vestibulum sit amet. Nunc sed lectus porttitor, consequat velit sit amet, efficitur mauris. Cras condimentum viverra porttitor. Praesent in dictum mauris, at euismod nulla. Phasellus ut cursus odio. Sed vestibulum nibh eu velit ornare ultricies. Integer malesuada, lacus nec dignissim elementum, augue quam tempus ante, in tempus dolor libero a nunc. Nunc gravida porttitor lorem eu pharetra.

* Nam vitae nunc mollis, varius felis pulvinar, pharetra orci
* Maecenas nec augue in dui mollis accumsan sed in magna.

Pellentesque aliquam varius felis. Nam placerat nunc sed massa consectetur bibendum. Suspendisse sit amet tortor at odio suscipit suscipit venenatis hendrerit nunc. Phasellus eget dictum dui. Praesent euismod enim nec ante viverra ultricies. Phasellus mattis lorem ut enim vehicula, vitae feugiat risus rutrum. Donec id porttitor urna. Aliquam cursus lacus eget porta porta. Sed ac risus ultricies, venenatis ligula id, porta ex. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi molestie malesuada odio iaculis pellentesque.
Vestibulum laoreet, mauris sed viverra sagittis, felis diam malesuada orci, sed volutpat tortor nisl quis augue. Vestibulum non consequat sem. Vestibulum vel lorem metus. Vestibulum eget euismod ligula. Ut ac auctor est. In viverra luctus tellus, quis auctor augue faucibus non. Fusce vestibulum laoreet tincidunt. Praesent et nunc euismod, porta quam viverra, dignissim sem. In non vehicula augue. Vivamus feugiat feugiat mi, id feugiat nunc facilisis at. Cras quis pharetra purus. Vivamus ultricies dui nisi, id tincidunt ipsum sodales eget. Nam vehicula nisl mi. Donec lacinia odio eu eros volutpat maximus laoreet ac erat.


text:
//
//  MMDebug.h
//  BandIt
//
//  Created by Kelly Huberty on 8/23/12.
//
//

#import <Foundation/Foundation.h>

@interface MMLogger : NSObject{

}

+(void)loadDebugMode;
+(void)setEnabled;
+(void)setDisabled;
+(BOOL)enabled;

@end

/**
 Checks whether the online file is newer than the local file.
 @param onlineURL
 The URL of the file to check.
 @param path
 The local path to check.
 @return YES if the online file is newer than the local one.
 */
void MMLog(id text, ...);

BOOL MMDebugOn();

int MMDebugCount();

void MMDebugCountReset();

void MMDebug(id text, ...);
void MMInfo(id text, ...);
void MMNotice(id text, ...);
void MMWarning(id text, ...);
void MMError(id text, ...);

enum {
    MMDebugModeSchemeNone = 0,
    MMDebugModeSchemeOff = -1,
    MMDebugModeSchemeOn = 1
};
typedef int MMDebugModeScheme;


text:
package org.apache.commons.net.examples;

import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.junit.Test;

public class MainTest {

    private static boolean hasMainMethod(String name) {
        name = name.replace(".class", "");
        try {
            final Class<?> clazz = Class.forName(name, false, MainTest.class.getClassLoader());
            clazz.getMethod("main", String[].class);
            return true;
        } catch (final ClassNotFoundException e) {
            System.out.println("Cannot find " + name);
            return false;
        } catch (final NoSuchMethodException e) {
            return false;
        } catch (final SecurityException e) {
            e.printStackTrace();
        }
        return true;
    }

    private static void processFileName(String name, final Properties p) {
        name = name.replace(File.separatorChar, '.');
        if (!name.endsWith(".class") || name.contains("$") // subclasses
                || name.endsWith("examples.Main.class") // the initial class, don't want to add that
                || !hasMainMethod(name)) {
            return;
        }
        name = name.replace(".class", "");
        final int lastSep = name.lastIndexOf('.');
        final String alias = name.substring(lastSep + 1);
        if (p.containsKey(alias)) {
            System.out.printf("Duplicate alias: %-25s %s %s %n", alias, name, p.getProperty(alias));
        } else {
            p.setProperty(alias, name);
        }
    }

    private static void scanForClasses(final int rootLength, final File current, final Properties p) {
        final File[] files = current.listFiles();
        if (files != null) {
            for (final File file : files) {
                if (file.isDirectory()) {
                    scanForClasses(rootLength, file, p);
                } else {
                    processFileName(file.getPath().substring(rootLength), p);
                }
            }
        }
    }

    @Test
    public void checkExamplesPropertiesIsComplete() throws Exception {
        final Properties cp = scanClasses();
        final Properties fp = new Properties();
        try (final InputStream inputStream = this.getClass().getResourceAsStream("examples.properties")) {
            fp.load(inputStream);
        }
        @SuppressWarnings("unchecked") // OK
        final Enumeration<String> propertyNames = (Enumeration<String>) cp.propertyNames();
        while (propertyNames.hasMoreElements()) {
            final String c = propertyNames.nextElement();
            final String fv = fp.getProperty(c);
            final String cv = cp.getProperty(c);
            if (fv == null) {
                System.out.printf("%-25s %s - missing from examples.properties%n", c, cv);
            } else if (!fv.equals(cv)) {
                System.out.printf("%-25s %s - expected value %s %n", c, fv, cv);
            }
        }
    }

    private Properties scanClasses() throws IOException {
        final CodeSource codeSource = Main.class.getProtectionDomain().getCodeSource();
        // ensure special characters are decoded OK by uing the charset
        // Use canonical path to ensure consistency with Windows
        final String sourceFile = new File(URLDecoder.decode(codeSource.getLocation().getFile(), "UTF-8")).getCanonicalPath();
        final Properties p = new Properties();
        if (sourceFile.endsWith(".jar")) {
            try (final JarFile jf = new JarFile(sourceFile)) {
                final Enumeration<JarEntry> e = jf.entries();
                while (e.hasMoreElements()) {
                    final JarEntry je = e.nextElement();
                    final String name = je.getName();
                    processFileName(name, p);
                }
            }
        } else {
            final File examples = new File(sourceFile, "org/apache/commons/net/examples"); // must match top level examples package name
            if (examples.exists()) {
                // need to add 1 to allow for path separator between root and file
                scanForClasses(sourceFile.length() + 1, examples, p);
            } else {
                fail("Could not find examples classes: " + examples.getCanonicalPath());
            }
        }
        return p;
    }
}