text:
package net.geocentral.geometria.converter;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.geocentral.geometria.model.GLabelFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class GConverter {

    private static Logger logger = Logger.getLogger("net.geocentral.geometria");

    public Element convertFigure(Element docElement) throws Exception {
        return docElement;
    }

    public Element convertProblem(Element docElement) {
        logger.info("");
        return docElement;
    }

    public Element convertSolution(Element docElement) {
        logger.info("");
        Document doc = docElement.getOwnerDocument();
        GLabelFactory labelFactory = GLabelFactory.getInstance();
        List<String> figureNames = new ArrayList<String>();
        NodeList nodes = ((Element)docElement.getElementsByTagName("problem").item(0)).getElementsByTagName("figure");
        for (int i = 0; i < nodes.getLength(); i++) {
            String figureName = ((Element)nodes.item(i)).getElementsByTagName("name").item(0).getTextContent();
            figureNames.add(figureName);
        }
        nodes = ((Element)docElement.getElementsByTagName("log").item(0)).getElementsByTagName("action");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element actionNode = (Element)nodes.item(i);
            Element classNameNode = (Element)actionNode.getElementsByTagName("className").item(0);
            String className = classNameNode.getTextContent();
            Matcher prismMatcher = Pattern.compile("GPrism([3-6])Action").matcher(className);
            Matcher pyramidMatcher = Pattern.compile("GPyramid([3-6])Action").matcher(className);
            if (prismMatcher.matches()) {
                logger.info(String.format("Convert action %s", className));
                String sideCount = prismMatcher.group(1);
                classNameNode.setTextContent("GPrismAction");
                Element sideCountNode = doc.createElement("sideCount");
                sideCountNode.setTextContent(sideCount);
                actionNode.appendChild(sideCountNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (classNameNode.getTextContent().equals("GPrismNAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPrismAction");
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (pyramidMatcher.matches()) {
                logger.info(String.format("Convert action %s", className));
                String sideCount = pyramidMatcher.group(1);
                classNameNode.setTextContent("GPyramidAction");
                Element sideCountNode = doc.createElement("sideCount");
                sideCountNode.setTextContent(sideCount);
                actionNode.appendChild(sideCountNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GPyramidNAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPyramidAction");
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GTetrahedronAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPlatonicAction");
                Element typeNode = doc.createElement("type");
                typeNode.setTextContent("tetrahedron");
                actionNode.appendChild(typeNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GCubeAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPlatonicAction");
                Element typeNode = doc.createElement("type");
                typeNode.setTextContent("cube");
                actionNode.appendChild(typeNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GOctahedronAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPlatonicAction");
                Element typeNode = doc.createElement("type");
                typeNode.setTextContent("octahedron");
                actionNode.appendChild(typeNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GDodecahedronAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPlatonicAction");
                Element typeNode = doc.createElement("type");
                typeNode.setTextContent("dodecahedron");
                actionNode.appendChild(typeNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GIcosahedronAction")) {
                logger.info(String.format("Convert action %s", className));
                classNameNode.setTextContent("GPlatonicAction");
                Element typeNode = doc.createElement("type");
                typeNode.setTextContent("icosahedron");
                actionNode.appendChild(typeNode);
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (classNameNode.getTextContent().equals("GCloneFigureAction")) {
                logger.info(String.format("Convert action %s", className));
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GCutAction")) {
                logger.info(String.format("Convert action %s", className));
                Element figure1NameNode = doc.createElement("figure1Name");
                String figure1Name = labelFactory.newFigureName(figureNames);
                figureNames.add(figure1Name);
                figure1NameNode.setTextContent(figure1Name);
                actionNode.appendChild(figure1NameNode);
                Element figure2NameNode = doc.createElement("figure2Name");
                String figure2Name = labelFactory.newFigureName(figureNames);
                figure2NameNode.setTextContent(figure2Name);
                actionNode.appendChild(figure2NameNode);
                figureNames.add(figure2Name);
            }
            else if (className.equals("GJoinAction")) {
                logger.info(String.format("Convert action %s", className));
                String figureName = labelFactory.newFigureName(figureNames);
                figureNames.add(figureName);
            }
            else if (className.equals("GRemoveFigure")) {
                logger.info(String.format("Convert action %s", className));
                String figureName = classNameNode.getElementsByTagName("figureName").item(0).getTextContent();
                figureNames.remove(figureName);
            }
            else if (className.equals("GRenameFigure")) {
                logger.info(String.format("Convert action %s", className));
                String oldFigureName = classNameNode.getElementsByTagName("oldFigureName").item(0).getTextContent();
                String newFigureName = classNameNode.getElementsByTagName("newFigureName").item(0).getTextContent();
                figureNames.remove(oldFigureName);
                figureNames.add(newFigureName);
            }
        }
        return docElement;
    }

    public Element convertOptions(Element docElement) {
        return docElement;
    }
}


text:
class ProjectMultiselectBlob < Spinach::FeatureSteps
  include SharedAuthentication
  include SharedProject
  include SharedPaths

  class << self
    def click_line_steps(*line_numbers)
      line_numbers.each do |line_number|
        step "I click line #{line_number} in file" do
          find("#L#{line_number}").click
        end

        step "I shift-click line #{line_number} in file" do
          script = "$('#L#{line_number}').trigger($.Event('click', { shiftKey: true }));"
          page.evaluate_script(script)
        end
      end
    end

    def check_state_steps(*ranges)
      ranges.each do |range|
        fragment = range.kind_of?(Array) ? "L#{range.first}-#{range.last}" : "L#{range}"
        pluralization = range.kind_of?(Array) ? "s" : ""

        step "I should see \"#{fragment}\" as URI fragment" do
          URI.parse(current_url).fragment.should == fragment
        end

        step "I should see line#{pluralization} #{fragment[1..-1]} highlighted" do
          ids = Array(range).map { |n| "LC#{n}" }
          extra = false

          highlighted = all("#tree-content-holder .highlight .line.hll")
          highlighted.each do |element|
            extra ||= ids.delete(element[:id]).nil?
          end

          extra.should be_false and ids.should be_empty
        end
      end
    end
  end

  click_line_steps *Array(1..5)
  check_state_steps *Array(1..5), Array(1..2), Array(1..3), Array(1..4), Array(1..5), Array(3..5)

  step 'I go back in history' do
    page.evaluate_script("window.history.back()")
  end

  step 'I go forward in history' do
    page.evaluate_script("window.history.forward()")
  end

  step 'I click on "Gemfile.lock" file in repo' do
    click_link "Gemfile.lock"
  end
end

redpajama_set_name: RedPajamaGithub


text:
require 'collins_client'
require 'lib/collins_integration'

describe "Asset Update and Search" do

  before :all do
    @integration = CollinsIntegration.new('default.yaml')
    @client = @integration.collinsClient
  end

  it "should put an asset in maintenance mode" do
    assets = @client.search 'tag = "001016" AND status= unallocated'
    assets.size.should eql 1
    @client.set_status!(assets[0], "Maintenance").should eql true
    sleep(0.2)
    assets = @client.search 'tag = "001016" AND status = maintenance'
    assets.size.should eql 1
    @client.set_status!(assets[0], "Allocated")
    sleep(0.2)
    assets = @client.search 'tag = "001016" AND status = allocated'
    assets.size.should eql 1
  end

end


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ProductDescriptionPage } from './product-description';

@NgModule({
  declarations: [
    ProductDescriptionPage,
  ],
  imports: [
    IonicPageModule.forChild(ProductDescriptionPage),
  ],
  exports: [
    ProductDescriptionPage
  ]
})
export class ProductDescriptionPageModule {}


text:
var queue = require("../queue"),
    fs = require("fs"),
    vows = require("vows"),
    assert = require("assert");

var suite = vows.describe("queue");

suite.addBatch({

  "version": {
    "is semantic": function() {
      assert.isTrue(/^([0-9]+)\.([0-9]+)\.([0-9]+)/.test(queue.version));
    }
  },

  "example queue of fs.stat": {
    topic: function() {
      queue()
          .defer(fs.stat, __dirname + "/../Makefile")
          .defer(fs.stat, __dirname + "/../README.md")
          .defer(fs.stat, __dirname + "/../package.json")
          .await(this.callback);
    },
    "does not fail": function(error, one, two, three) {
      assert.isNull(error);
    },
    "successfully executes the three tasks": function(error, one, two, three) {
      assert.greater(one.size, 0);
      assert.greater(two.size, 0);
      assert.greater(three.size, 0);
    }
  },

  "queue of single synchronous task that errors": {
    topic: function() {
      queue()
          .defer(function(callback) { callback(-1); })
          .await(this.callback);
    },
    "fails": function(error, result) {
      assert.equal(error, -1);
      assert.isUndefined(result);
    }
  },

  "queue of single asynchronous task that errors": {
    topic: function() {
      queue()
          .defer(function(callback) { process.nextTick(function() { callback(-1); }); })
          .await(this.callback);
    },
    "fails": function(error, result) {
      assert.equal(error, -1);
      assert.isUndefined(result);
    }
  },

  "queue with multiple tasks that error": {
    topic: function() {
      queue()
          .defer(function(callback) { setTimeout(function() { callback(-2); }, 100); })
          .defer(function(callback) { process.nextTick(function() { callback(-1); }); })
          .defer(function(callback) { setTimeout(function() { callback(-3); }, 200); })
          .await(this.callback);
    },
    "the first error is returned": function(error, one, two, three) {
      assert.equal(error, -1);
      assert.isUndefined(one);
      assert.isUndefined(two);
      assert.isUndefined(three);
    }
  },

  "queue with multiple tasks where one errors": {
    topic: function() {
      queue()
          .defer(function(callback) { process.nextTick(function() { callback(-1); }); })
          .defer(function(callback) { process.nextTick(function() { callback(null, 'ok'); }); })
          .await(this.callback);
    },
    "the first error is returned": function(error, one, two) {
      assert.equal(error, -1);
      assert.isUndefined(one);
      assert.isUndefined(two);
    }
  },

  "queue with multiple synchronous tasks that error": {
    topic: function() {
      queue()
          .defer(function(callback) { callback(-1); })
          .defer(function(callback) { callback(-2); })
          .defer(function(callback) { throw new Error(); })
          .await(this.callback);
    },
    "the first error prevents the other tasks from running": function(error, one, two, three) {
      assert.equal(error, -1);
      assert.isUndefined(one);
      assert.isUndefined(two);
      assert.isUndefined(three);
    }
  },

  "queue of asynchronous closures, processed serially": {
    topic: function() {
      var tasks = [], task = asynchronousTask(), n = 10, q = queue(1);
      while (--n >= 0) tasks.push(task);
      tasks.forEach(function(t) { q.defer(t); });
      q.awaitAll(this.callback)
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes all tasks in series": function(error, results) {
      assert.deepEqual(results, [
        {active: 1, index: 0},
        {active: 1, index: 1},
        {active: 1, index: 2},
        {active: 1, index: 3},
        {active: 1, index: 4},
        {active: 1, index: 5},
        {active: 1, index: 6},
        {active: 1, index: 7},
        {active: 1, index: 8},
        {active: 1, index: 9}
      ]);
    }
  },

  "fully-parallel queue of ten asynchronous tasks": {
    topic: function() {
      var t = asynchronousTask();
      queue()
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .awaitAll(this.callback);
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes all tasks in parallel": function(error, results) {
      assert.deepEqual(results, [
        {active: 10, index: 0},
        {active: 9, index: 1},
        {active: 8, index: 2},
        {active: 7, index: 3},
        {active: 6, index: 4},
        {active: 5, index: 5},
        {active: 4, index: 6},
        {active: 3, index: 7},
        {active: 2, index: 8},
        {active: 1, index: 9}
      ]);
    }
  },

  "partly-parallel queue of ten asynchronous tasks": {
    topic: function() {
      var t = asynchronousTask();
      queue(3)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .awaitAll(this.callback);
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes at most three tasks in parallel": function(error, results) {
      assert.deepEqual(results, [
        {active: 3, index: 0},
        {active: 3, index: 1},
        {active: 3, index: 2},
        {active: 3, index: 3},
        {active: 3, index: 4},
        {active: 3, index: 5},
        {active: 3, index: 6},
        {active: 3, index: 7},
        {active: 2, index: 8},
        {active: 1, index: 9}
      ]);
    }
  },

  "serialized queue of ten asynchronous tasks": {
    topic: function() {
      var t = asynchronousTask();
      queue(1)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .awaitAll(this.callback);
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes all tasks in series": function(error, results) {
      assert.deepEqual(results, [
        {active: 1, index: 0},
        {active: 1, index: 1},
        {active: 1, index: 2},
        {active: 1, index: 3},
        {active: 1, index: 4},
        {active: 1, index: 5},
        {active: 1, index: 6},
        {active: 1, index: 7},
        {active: 1, index: 8},
        {active: 1, index: 9}
      ]);
    }
  },

  "serialized queue of ten deferred synchronous tasks": {
    topic: function() {
      var t = deferredSynchronousTask();
      queue(1)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .awaitAll(this.callback);
      t.finish();
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes all tasks in series, within the callback of the first task": function(error, results) {
      assert.deepEqual(results, [
        {active: 1, index: 0},
        {active: 2, index: 1},
        {active: 2, index: 2},
        {active: 2, index: 3},
        {active: 2, index: 4},
        {active: 2, index: 5},
        {active: 2, index: 6},
        {active: 2, index: 7},
        {active: 2, index: 8},
        {active: 2, index: 9}
      ]);
    }
  },

  "partly-parallel queue of ten synchronous tasks": {
    topic: function() {
      var t = synchronousTask();
      queue(3)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .awaitAll(this.callback);
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes all tasks in series": function(error, results) {
      assert.deepEqual(results, [
        {active: 1, index: 0},
        {active: 1, index: 1},
        {active: 1, index: 2},
        {active: 1, index: 3},
        {active: 1, index: 4},
        {active: 1, index: 5},
        {active: 1, index: 6},
        {active: 1, index: 7},
        {active: 1, index: 8},
        {active: 1, index: 9}
      ]);
    }
  },

  "serialized queue of ten synchronous tasks": {
    topic: function() {
      var t = synchronousTask();
      queue(1)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .defer(t)
          .awaitAll(this.callback);
    },
    "does not fail": function(error, results) {
      assert.isNull(error);
    },
    "executes all tasks in series": function(error, results) {
      assert.deepEqual(results, [
        {active: 1, index: 0},
        {active: 1, index: 1},
        {active: 1, index: 2},
        {active: 1, index: 3},
        {active: 1, index: 4},
        {active: 1, index: 5},
        {active: 1, index: 6},
        {active: 1, index: 7},
        {active: 1, index: 8},
        {active: 1, index: 9}
      ]);
    }
  }

});

suite.export(module);

function asynchronousTask(counter) {
  var active = 0;

  if (!counter) counter = {scheduled: 0};

  return function(callback) {
    var index = counter.scheduled++;
    ++active;
    process.nextTick(function() {
      try {
        callback(null, {active: active, index: index});
      } finally {
        --active;
      }
    });
  };
}

function synchronousTask(counter) {
  var active = 0;

  if (!counter) counter = {scheduled: 0};

  return function(callback) {
    try {
      callback(null, {active: ++active, index: counter.scheduled++});
    } finally {
      --active;
    }
  };
}

function deferredSynchronousTask(counter) {
  var active = 0, deferrals = [];

  if (!counter) counter = {scheduled: 0};

  function task(callback) {
    if (deferrals) return deferrals.push({callback: callback, index: counter.scheduled++});
    try {
      callback(null, {active: ++active, index: counter.scheduled++});
    } finally {
      --active;
    }
  }

  task.finish = function() {
    var deferrals_ = deferrals.slice();
    deferrals = null;
    deferrals_.forEach(function(deferral) {
      try {
        deferral.callback(null, {active: ++active, index: deferral.index});
      } finally {
        --active;
      }
    });
  };

  return task;
}


text:
using System;
using System.Collections;
using System.Linq;
using System.Text;

namespace Tharga.Toolkit.Console.Helpers
{
    internal static class ExceptionExtension
    {
        public static string ToFormattedString(this Exception exception, bool includeStackTrace, string prefix)
        {
            var data = ToFormattedString(exception, 0, includeStackTrace).TrimEnd(Environment.NewLine.ToCharArray());
            return $"{prefix}{data}";
        }

        private static string ToFormattedString(this Exception exception, int indentationLevel, bool includeStackTrace)
        {
            var sb = new StringBuilder();

            var indentation = new string(' ', indentationLevel * 2);
            sb.AppendLine($"{indentation}{exception.Message}");
            foreach (DictionaryEntry data in exception.Data)
            {
                sb.AppendLine($"{indentation}{data.Key}: {data.Value}");
            }

            var aggregateException = exception as AggregateException;
            if (aggregateException != null)
            {
                indentationLevel++;
                foreach (var exp in aggregateException.InnerExceptions)
                {
                    sb.AppendLine(exp.ToFormattedString(indentationLevel, false));
                }
            }
            else if (exception.InnerException != null)
            {
                sb.AppendLine(exception.InnerException.ToFormattedString(++indentationLevel, false));
            }

            if (includeStackTrace)
            {
                try
                {
                    //NOTE: Make it configurable if to include stacktrace or not
                    sb.AppendLine();
                    sb.AppendLine("Stack trace:");
                    var stackTrace = exception.StackTrace.Split(new[] { " at " }, StringSplitOptions.None);
                    foreach (var line in stackTrace.Where(x => !string.IsNullOrWhiteSpace(x)))
                    {
                        var pair = line.Split(new[] { " in " }, StringSplitOptions.None);
                        if (pair.Length == 2)
                        {
                            sb.AppendLine(pair[0].Trim());
                            sb.AppendLine($"  {pair[1].Trim()}");
                        }
                        else
                            sb.AppendLine(line);
                    }
                }
                catch (Exception e)
                {
                    sb.AppendLine($"Oups, internal error. {e.Message}.");
                }
            }

            var result = sb.ToString();
            return result;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <meta name="description" content="" />
        <meta name="author" content="Majdi houidi" />

        <title>Snake Game - ThreeJs</title>

        <link href="http://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css" />

        <link rel="stylesheet" type="text/css" href="assets/styles/style.css" media="all" />
        <link rel="stylesheet" type="text/css" href="assets/styles/responsive.css" media="all" />

                Snake Game
                Score : 0
                EPSI
                Recommencer

                <canvas id="snakegame"></canvas>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE WMT_MS_Capabilities SYSTEM "http://schemas.opengis.net/wms/wms/1.1.1All.xsd">
<WMT_MS_Capabilities updateSequence="0" version="1.1.1">
<Service>
<Name>OGC:WMS</Name>
<Title>MrGeo Web Map Service</Title>
<Abstract>MrGeo Web Map Service</Abstract>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
<Fees>none</Fees>
<AccessConstraints>none</AccessConstraints>
</Service>
<Capability>
<Request>
<GetCapabilities>
<Format>application/vnd.ogc.wms_xml</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
</Get>
<Post>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
</Post>
</HTTP>
</DCPType>
</GetCapabilities>
<GetMap>
<Format>image/geotif</Format>
<Format>image/geotiff</Format>
<Format>image/jpeg</Format>
<Format>image/jpg</Format>
<Format>image/png</Format>
<Format>image/tif</Format>
<Format>image/tiff</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
</Get>
<Post>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
</Post>
</HTTP>
</DCPType>
</GetMap>
<GetMosaic>
<Format>image/geotif</Format>
<Format>image/geotiff</Format>
<Format>image/jpeg</Format>
<Format>image/jpg</Format>
<Format>image/png</Format>
<Format>image/tif</Format>
<Format>image/tiff</Format>
<DCPType>
<HTTP>
<Get>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
</Get>
<Post>
<OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost:9998/wms?REQUEST=getcapabilities&SERVICE=WMS" xlink:type="simple"/>
</Post>
</HTTP>
</DCPType>
</GetMosaic>
</Request>
<Exception>
<Format>application/vnd.ogc.se_xml</Format>
<Format>application/vnd.ogc.se_inimage</Format>
<Format>application/vnd.ogc.se_blank</Format>
</Exception>
<Layer noSubsets="0" opaque="0" queryable="0">
<Title>AllLayers</Title>
<SRS>EPSG:4326</SRS>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>IslandsElevation-v2</Title>
<Name>IslandsElevation-v2</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="162.5" maxy="-10.083333333333334" minx="161.25" miny="-11.0"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>161.25</minx>
<maxx>162.5</maxx>
<miny>-11.0</miny>
<maxy>-10.083333333333334</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>IslandsElevation-v2-color-scale</Title>
<Name>IslandsElevation-v2-color-scale</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="162.5" maxy="-10.083333333333334" minx="161.25" miny="-11.0"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>161.25</minx>
<maxx>162.5</maxx>
<miny>-11.0</miny>
<maxy>-10.083333333333334</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>IslandsElevation-v2-no-pyramid</Title>
<Name>IslandsElevation-v2-no-pyramid</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="162.5" maxy="-10.083333333333334" minx="161.25" miny="-11.0"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>161.25</minx>
<maxx>162.5</maxx>
<miny>-11.0</miny>
<maxy>-10.083333333333334</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>IslandsElevation-v2-no-pyramid-extra-metadata</Title>
<Name>IslandsElevation-v2-no-pyramid-extra-metadata</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="162.5" maxy="-10.083333333333334" minx="161.25" miny="-11.0"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>161.25</minx>
<maxx>162.5</maxx>
<miny>-11.0</miny>
<maxy>-10.083333333333334</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>IslandsElevation-v2-no-stats</Title>
<Name>IslandsElevation-v2-no-stats</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="162.5" maxy="-10.083333333333334" minx="161.25" miny="-11.0"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>161.25</minx>
<maxx>162.5</maxx>
<miny>-11.0</miny>
<maxy>-10.083333333333334</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>cost-distance</Title>
<Name>cost-distance</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="69.43359375" maxy="35.068359375" minx="69.08203125" miny="34.8046875"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>69.08203125</minx>
<maxx>69.43359375</maxx>
<miny>34.8046875</miny>
<maxy>35.068359375</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>cost-distance-shift-2</Title>
<Name>cost-distance-shift-2</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="-111.4453125" maxy="36.5625" minx="-112.5" miny="35.5078125"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>-112.5</minx>
<maxx>-111.4453125</maxx>
<miny>35.5078125</miny>
<maxy>36.5625</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default Grayscale</Title>
<Abstract>3-band grayscale image, scaled from the min value (0) to max value (255).  All 3 bands contain the same 8-bit value</Abstract>
</Style>
<Style>
<Name>Default</Name>
<Title>Default</Title>
</Style>
</Layer>
<Layer cascaded="0" fixedHeight="0" fixedWidth="0" noSubsets="0" opaque="0" queryable="1">
<Title>small-3band</Title>
<Name>small-3band</Name>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox maxx="8.525390625" maxy="55.107421875" minx="8.173999786376953" miny="54.84443664550781"/>
<BoundingBox>
<SRS>EPSG:4326</SRS>
<minx>8.173999786376953</minx>
<maxx>8.525390625</maxx>
<miny>54.84443664550781</miny>
<maxy>55.107421875</maxy>
</BoundingBox>
<Style>
<Name>Default</Name>
<Title>Default RGB</Title>
<Abstract>3-band color image,  Colors are taken from bands 1, 2, & 3 respectively</Abstract>
</Style>
<Style>
<Name>BandR,G,B</Name>
<Title>Band Selection</Title>
</Style>
</Layer>
</Layer>
</Capability>
</WMT_MS_Capabilities>


text:
'use strict';

angular.
module('habitDemo').
component('habitDemo', {
    templateUrl: 'habit-demo/habit-demo.template.html',
    controller: ['ListService', function (ListService) {
            this.listService = ListService;
            var list = localStorage.getItem('list');
            if (list != null && list.length >= 0) {
                var obj = JSON.parse(list);
                for (var i = 0; i < obj.length; i++) {
                    obj[i].startDate = new Date(obj[i].startDate);
                }
                this.listService.saveList(obj);
            }
            this.addItem = function (newItem) {
                var item = {
                    name: newItem.name,
                    startDate: new Date(newItem.startDate),
                    days: newItem.days,
                    daysCompleted: 0
                };
                this.listService.addItem(item);
                this.save();
            };
            this.list = ListService.getList();
            this.refreshItem = function (item, index) {
                if (item.daysArray[index]) {
                    item.daysCompleted++;
                    this.save();
                } else {
                    item.daysCompleted--;
                    this.save();
                }
            };
            this.save = function () {
                var currentList = ListService.getList();
                localStorage.setItem('list', JSON.stringify(currentList));
            }
        }
    ]
});


text:
namespace Ui
{
	class poolTab;
}

class mainWindow;

class poolTab : public searchTab
{
	Q_OBJECT

	public:
		explicit poolTab(QMap<QString,Site*> *sites, Profile *profile, mainWindow *parent);
		~poolTab();
		Ui::poolTab *ui;
		QString tags() const;
		QList<Site*> loadSites() const override;
		void write(QJsonObject &json) const override;
		bool read(const QJsonObject &json);

	protected:
		void changeEvent(QEvent *event) override;

	public slots:
		// Zooms
		void setTags(QString);
		void setPool(int id, QString site);
		// Loading
		void load();
		bool validateImage(QSharedPointer<Image> img);
		// Batch
		void getPage();
		void getAll();
		// Others
		void closeEvent(QCloseEvent*);
		void on_buttonSearch_clicked();
		void setSite(QString);
		void focusSearch();

	private:
		int				m_id;
		TextEdit		*m_search;
		QCalendarWidget	*m_calendar;
		bool			m_sized;
};

#endif // POOL_TAB_H


text:
![Gem output](https://raw.githubusercontent.com/neurodynamic/repos_report/master/example_output.png)

# Purpose

Prints info on the status of all repos under a given directory.

    $ gem install repos_report

### How it works

To get a report on the status of repos in a directory:
```
rep2 [directory]
```

### A note on speed

This tool is optimized for directories that are populated with just repos and nothing else. I have maybe 100-200 projects in my development directory, and it scans that almost instantly. If it's somewhere with thousands of directories and subdirectories, it's not so snappy. I've found the likeliest culprit for suddenly slower behavior is if I've started a few projects in my dev folder without initializing git repos in them (thus requiring the script to search them and all their subdirectories as well in order to ensure it doesn't miss any repos).


text:
import ts from 'typescript';
import path from 'path';
import {EOL} from 'os';
import nodeREPL from 'repl';
import _ from 'lodash';
import child_process from 'child_process';
import vm from 'vm';
import fs from 'fs';

//reference: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
// and CoffeeScript

const compileOptions = {
  noEmitOnError: true,
  module: ts.ModuleKind.CommonJS,
  moduleResolution: ts.ModuleResolutionKind.NodeJs,
  experimentalDecorators: true,
  emitDecoratorMetadata: true, // ?
  newLine: process.platform === 'win32' ? ts.NewLineKind.CarriageReturnLineFeed : ts.NewLineKind.LineFeed,
  target: ts.ScriptTarget.ES5,
};

let code = `/// <reference path="${path.resolve(__dirname, './typescript/node.d.ts')}" />
`;
const replFile = `Mancy.typescript.repl.${Date.now()}.ts`;
let buildNumber = 0;
let nodeLineListener = () => {};
let promptData = '';

let langServiceHost = {
  getScriptFileNames: () => [replFile],
  getScriptVersion: (fileName) => fileName === replFile && buildNumber.toString(),
  getScriptSnapshot: (fileName) => ts.ScriptSnapshot.fromString(fileName === replFile ? code : fs.readFileSync(fileName).toString()),
  getCurrentDirectory: () => process.cwd(),
  getCompilationSettings: () => compileOptions,
  getDefaultLibFileName: (options) => path.join(__dirname, '../node_modules/typescript/lib/lib.core.es6.d.ts'),
}

let service = ts.createLanguageService(langServiceHost, ts.createDocumentRegistry())

let getDiagnostics = () => {
  let emit = service.getEmitOutput(replFile);
  let allDiagnostics = service.getCompilerOptionsDiagnostics()
    .concat(service.getSyntacticDiagnostics(replFile))
    .concat(service.getSemanticDiagnostics(replFile));
  return allDiagnostics;
};

let loadFile = (module, filename) => {
  let result = ts.transpile(fs.readFileSync(filename).toString(), compileOptions);
  return module._compile(JSON.stringify(result), filename);
};

// register extensions
let register = () => {
  if (require.extensions) {
    require.extensions['.ts'] = loadFile;
    require.extensions['.tsx'] = loadFile;
  }

  let fork = child_process.fork;
  let binary = require.resolve(path.join(__dirname, '../node_modules/typescript/bin/tsc'));
  child_process.fork = (path, args, options) => {
    if(/\.tsx?$/.test(path)) {
      if(!Array.isArray(args)) {
        options = args || {};
        args = [];
      }
      args = [path].concat(args);
      path = binary;
    }
    return fork(path, args, options);
  };
};

let transpile = (input, context, cb) => {
  let original = code;
  code += input;
  buildNumber += 1;
  let allDiagnostics = getDiagnostics();
  code = original;

  if(allDiagnostics.length) {
    let diagnostic = allDiagnostics[0];
    let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, EOL);
    if(!diagnostic.file) { return cb(message); }
    let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
    return cb(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
  }

  return cb(null, ts.transpile(input));
};

let evaluate = (input, context, filename, cb) => {
  let original = code;
  code += input;
  buildNumber += 1;
  let allDiagnostics = getDiagnostics();

  if(allDiagnostics.length) {
    let diagnostic = allDiagnostics[0];
    let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, EOL);
    if(!diagnostic.file) { return cb(message); }
    let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
    code = original;
    return cb(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
  }
  let js = ts.transpile(input);
  return cb(null, vm.runInContext(js, context, filename));
}

let addMultilineHandler = ({rli}) => {
  nodeLineListener = rli.listeners('line')[0];
  rli.removeListener('line', nodeLineListener);
  rli.on('line', (cmd) => {
    promptData += cmd + EOL;
  });
};

let completion = (repl) => {
  repl.complete = (input, cb) => {
    let original = code;
    try {
      code += input;
      let suggestions = service.getCompletionsAtPosition(replFile, code.length);
      code = original;

      if(!suggestions) { cb(null, [[],""]); }
      else {
        let lines = input.split(/\r?\n/);
        let lastLine = lines[lines.length - 1];
        let prefix = lastLine.match(/[$\w]+$/);
        let results;
        if(prefix) {
          let p = prefix[0];
          results = _.chain(suggestions.entries)
            .filter((e) => e.name.substring(0, p.length) === p)
            .map((e) => [e.name, e.kind])
            .value();
        } else {
          results = suggestions.entries.map((e) => [e.name, e.kind]);
        }
        let [names, kinds] = _.reduce(results, (o, [name, kind]) => {
          o[0].push(name);
          o[1].push(kind);
          return o;
        }, [[], []]);
        cb(null, [names, prefix ? prefix[0] : ""], kinds);
      }
    } catch(e) {
      code = original;
      cb(null, [[],""]);
    }
  };
};

let loadAction = {
  help: '?',
  action: function(file) {
    try {
      let stats = fs.statSync(file);
      if (stats && stats.isFile()) {
        let self = this;
        let data = fs.readFileSync(file, 'utf8');
        this.displayPrompt();
        nodeLineListener(data);
        promptData = '';
      } else {
        this.outputStream.write('Failed to load:' + file + ' is not a file\n');
      }
    } catch (e) {
      this.outputStream.write('Failed to load:' + file + '\n');
    }
    this.displayPrompt();
  }
};

/// export repl
export default {
  start: (options = {}) => {
    register();
    let opts = _.extend({eval: evaluate}, options);
    let repl = nodeREPL.start(opts);
    repl.on('exit', () => {
      if(!repl.rli.closed) {
        repl.outputStream.write(EOL);
      }
    });
    repl.input.on('data', (d) => {
      if(d === EOL) {
        nodeLineListener(promptData);
        promptData = '';
      }
    });
    addMultilineHandler(repl);
    completion(repl);
    repl.transpile = transpile;
    repl.defineCommand('load', loadAction);
    return repl;
  }
};


text:
using UnityEngine;
using System.Collections;

public class randomRotations : MonoBehaviour {
	public float flipDelay = 3f;
	float timer = 0f;
	Vector3 scale;
	Scriptable scriptable;

	void Start()
	{
		scale = transform.localScale;
		scriptable = GetComponent<Scriptable>();
	}

	void Update()
	{
		timer = timer + Time.deltaTime;
		if (timer < flipDelay) return;

		timer = 0;
		if (scriptable == null)
			transform.localScale = new Vector3(transform.localScale.x * (-1), scale.y, scale.z);
		else
			scriptable.Flip();
	}
}


text:
package xyz.cloudkeeper.linker;

import org.testng.Assert;
import org.testng.annotations.Test;
import xyz.cloudkeeper.linker.examples.BinarySum;
import xyz.cloudkeeper.model.ConstraintException;
import xyz.cloudkeeper.model.beans.element.module.MutableCompositeModule;
import xyz.cloudkeeper.model.beans.element.module.MutableConnection;
import xyz.cloudkeeper.model.beans.element.module.MutableInPort;
import xyz.cloudkeeper.model.beans.element.module.MutableModule;
import xyz.cloudkeeper.model.beans.element.module.MutableOutPort;
import xyz.cloudkeeper.model.beans.element.module.MutableParentInToChildInConnection;
import xyz.cloudkeeper.model.beans.element.module.MutablePort;
import xyz.cloudkeeper.model.beans.element.module.MutableProxyModule;
import xyz.cloudkeeper.model.beans.type.MutableDeclaredType;
import xyz.cloudkeeper.model.beans.type.MutableTypeMirror;
import xyz.cloudkeeper.model.immutable.Location;
import xyz.cloudkeeper.model.immutable.execution.ExecutionTrace;
import xyz.cloudkeeper.model.runtime.element.RuntimeRepository;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class RedundantApplyToAllTest {
    private static final Location ERROR_LOCATION = new Location("test", 24, 5);

    @Test
    public void test() throws Exception {
        MutableDeclaredType integerCollections = new MutableDeclaredType()
            .setDeclaration(Collection.class.getName())
            .setTypeArguments(Collections.<MutableTypeMirror<?>>singletonList(
                new MutableDeclaredType()
                    .setDeclaration(Integer.class.getName())
            ));
        MutableCompositeModule module = new MutableCompositeModule()
            .setDeclaredPorts(Arrays.<MutablePort<?>>asList(
                new MutableInPort()
                    .setSimpleName("inFirstArrayPort")
                    .setType(integerCollections),
                new MutableInPort()
                    .setSimpleName("inSecondArrayPort")
                    .setType(integerCollections),
                new MutableOutPort()
                    .setSimpleName("outPort")
                    .setType(integerCollections)
            ))
            .setModules(Collections.<MutableModule<?>>singletonList(
                new MutableProxyModule()
                    .setDeclaration(BinarySum.class.getName())
                    .setSimpleName("sum")
            ))
            .setConnections(Arrays.<MutableConnection<?>>asList(
                new MutableParentInToChildInConnection()
                    .setFromPort("inFirstArrayPort")
                    .setToModule("sum").setToPort("num1"),
                new MutableParentInToChildInConnection()
                    .setFromPort("inSecondArrayPort")
                    .setToModule("sum").setToPort("num2")
                    .setLocation(ERROR_LOCATION)
            ));

        try {
            LinkerOptions linkerOptions = LinkerOptions.nonExecutable();
            RuntimeRepository repository = Linker.createRepository(
                Collections.singletonList(Examples.simpleBundle()), linkerOptions);
            Linker.createAnnotatedExecutionTrace(ExecutionTrace.empty(), module, Collections.emptyList(), repository,
                linkerOptions);
            Assert.fail("Expected exception because of more than one apply-to-all connections.");
        } catch (ConstraintException exception) {
            Assert.assertSame(exception.getLinkerTrace().get(0).getLocation(), ERROR_LOCATION);
        }
    }
}


text:
set -ex

before_install() {
    sudo cpanm --notest Test::Nginx >build.log 2>&1 || (cat build.log && exit 1)
    mysql -uroot -e 'CREATE DATABASE IF NOT EXISTS orange;'
    mysql -uroot orange < install/orange-master.sql;
}

do_install() {
    wget -qO - https://openresty.org/package/pubkey.gpg | sudo apt-key add -
    sudo apt-get update --fix-missing
    sudo apt-get -y install software-properties-common
    sudo add-apt-repository -y "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main"
    sudo apt-get update

    sudo apt-get install -y openresty openresty-resty luarocks

    sudo luarocks make --lua-dir=/usr/local/openresty/luajit rockspec/orange-master-0.rockspec --tree=deps --only-deps --local

    cp conf/nginx.conf.example  conf/nginx.conf
    cp conf/orange.conf.example conf/orange.conf

    git clone https://github.com/sumory/lor.git lor
    cd lor
    sudo make install
    cd ..

    git clone https://github.com/iresty/test-nginx.git test-nginx

}

run_tests() {
    export OPENRESTY_PREFIX="/usr/local/openresty"
    export PATH=$OPENRESTY_PREFIX/nginx/sbin:$OPENRESTY_PREFIX/luajit/bin:$OPENRESTY_PREFIX/bin:$PATH
    prove -I test-nginx/lib -r t
}

option=$1

case ${option} in
    before_install)
        before_install
        ;;
    do_install)
        do_install
        ;;
    run_tests)
        run_tests
        ;;
    *)
        echo "$1 option is undefined."
        ;;
esac


text:
module.exports = function(grunt) {

  // Utility to load the different option files
  // based on their names
  function loadConfig(path) {
    var glob = require('glob');
    var object = {};
    var key;

    glob.sync('*', {cwd: path}).forEach(function(option) {
      key = option.replace(/\.js$/,'');
      object[key] = require(path + option);
    });

    return object;
  }

  // Initial config
  var config = {
    pkg: grunt.file.readJSON('package.json')
  }

  // Load tasks from the tasks folder
  grunt.loadTasks('tasks');

  // Load all the tasks options in tasks/options base on the name:
  // watch.js => watch{}
  grunt.util._.extend(config, loadConfig('./tasks/options/'));

  grunt.initConfig(config);

  require('load-grunt-tasks')(grunt);

  // Default Task is basically a rebuild
  grunt.registerTask('default', ['eslint', 'concat', 'uglify', 'sass', 'postcss', 'imagemin']);

};


text:
package cogx.compiler.codegenerator.opencl.hyperkernels

import cogx.cogmath.geometry.Shape
import cogx.compiler.codegenerator.opencl.fragments.{AddressingMode, HyperKernel, TensorElementAddressing}
import cogx.compiler.codegenerator.opencl.fragments.HyperKernel._
import cogx.platform.types._
import cogx.compiler.parser.op.FilterAdjointShuffleOp

/** Hyperkernel that reorders the planes of a vector field that is holding a batch
  * of multi-feature-plane images.  The input is assumed to have planes associated
  * with a given image in adjacent planes, while the output is created so that planes
  * of the same feature are adjacent.
  *
  * Input:                    Output:
  *
  * Image_0_feature_0         Image_0_feature_0
  * Image_0_feature_1         Image_1_feature_0
  * ...                       ...
  * Image_0_feature_N-1       Image_B-1_feature_0
  * Image_1_feature_0         Image_0_feature_1
  * ...                       ...
  *
  * @author Dick Carter
  *
  * @param in The virtual field register of the input field to be flipped.
  * @param operation The FilterAdjointShuffle Opcode.
  * @param resultType The FieldType of the result of this kernel.
  * @param addressMode The addressing mode of this kernel.
  */
private[cogx]
class FilterAdjointShuffleHyperKernel private (in: Array[VirtualFieldRegister],
                                        operation: FilterAdjointShuffleOp,
                                        resultType: FieldType,
                                        addressMode: AddressingMode)
        extends HyperKernel(operation, in, resultType, addressMode) {
  import operation._
  val inType = in(0).fieldType
  require(inType.tensorColumns % batchSize == 0,
    s"Internal error: Expecting VectorField tensor depth to be a multiple of $batchSize, found fieldType $inType.")
  val featuresPerImage = inType.tensorShape.points / batchSize
  val numimages = untilImage - fromImage

  val code =
    s"""|        int featureIndex = _tensorElement / $numimages;
        |        int imageIndex = $fromImage + _tensorElement % $numimages;
        |        tensorElement = imageIndex * $featuresPerImage + featureIndex;
        |${setLayerRowColumn(resultType, "_layer", "_row", "_column")}
        |        @out0 = readElementNonlocal(@in0);
        |""".stripMargin

  addCode(code)
  //debugCompile
}

/** Factory object for creating kernels of this type.
  */
private[cogx]
object FilterAdjointShuffleHyperKernel {
  /** Create a hyperkernel that flips a tensor field.
    *
    * @param in The virtual field register of the input field to be flipped.
    * @param operation The FlipOp opcode.
    * @param resultType The FieldType of the result of this kernel.
    * @return The synthesized hyperkernel.
    */
  def apply(in: Array[VirtualFieldRegister], operation: FilterAdjointShuffleOp, resultType: FieldType):
  HyperKernel =
  {
    import operation._
    require(in.length == 1, s"Expecting a single input, found ${in.length}.")
    val inType = in(0).fieldType
    val numImages = untilImage - fromImage
    require(inType.tensorColumns % batchSize == 0,
      s"Internal error: Expecting VectorField tensor depth to be a multiple of $batchSize, found fieldType $inType.")
    val featuresPerImage = inType.tensorShape.points / batchSize
    val expectedResultType = inType.resizeTensor(Shape(featuresPerImage * numImages))
    require(expectedResultType == resultType, s"Internal error: Expecting $expectedResultType == $resultType.")
    require(inType.tensorOrder == 1, s"Internal error: Expecting VectorField input, found $inType.")

    new FilterAdjointShuffleHyperKernel(in, operation, resultType, TensorElementAddressing)
  }
}


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('route:admin-antiviruses-edit', 'Unit | Route | admin antiviruses edit', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
});

test('it exists', function(assert) {
  let route = this.subject();
  assert.ok(route);
});


text:
package com.loovjo.spg.gui.machines;

import java.awt.Color;
import java.awt.Graphics2D;

import com.loovjo.spg.chem.Material;
import com.loovjo.spg.gui.Board;
import com.loovjo.spg.utils.Textures;

public class MachineBattery extends MachineContainer {

	public MachineBattery(int x, int y, double capacity, Board owner) {
		super(x, y, Material.makeFromWeight(null, 0), capacity, owner);
	}

	@Override
	public void draw(Graphics2D g, int posX, int posY, int width, int height) {

		g.setColor(content.getColor());
		int size = (int) (0.654 * height * (content.getWeight() / capacity));

		g.fillRect(posX + width / 8, posY + (int) (0.816 * width) - size, 3 * width / 4, size);
		g.drawImage(Textures.MACHINE_BATTERY.toBufferedImage(), posX, posY, width, height, null);

	}

	@Override
	public Material take(Material m, Machine mach, int port) {
		if (!m.empty() && m.mol.isEnergon()) {
			return super.take(m, mach, port);
		}
		return Material.makeFromWeight(null, 0);
	}

	@Override
	public Material recieve(Material m, Machine mach, int port) {
		if (!m.empty() && m.mol.isEnergon()) {
			return super.recieve(m, mach, port);
		}
		return m;
	}

}


text:
import { Component, Input, OnInit, Inject } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

import { Student } from '../../student/student';
import { TextboxQuestion, DropdownQuestion, ReviewQuestion, Review } from '../review';
import { ReviewService } from '../review.service';
import { CourseService } from '../../course/course.service';
import { TeacherService } from '../../teacher/teacher.service';
import { QuestionControlService } from '../question-control.service';
import { ConfirmDialogService } from '../../confirm-dialog/confirm-dialog.service';
import { ReviewComponent } from '../review.component';

@Component({
    selector: 'app-dynamic-form',
    templateUrl: './dynamic-form.component.html',
    styleUrls: ['./dynamic-form.component.css'],
    providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {

    @Input() userID;
    @Input() course_code;
    @Input() questions: ReviewQuestion<any>[] = [];
    form: FormGroup;
    userInput;
    result: any;
    reviewQuestions: ReviewQuestion<any>[] = [];

    constructor(
        private qcs: QuestionControlService,
        private reviewService: ReviewService,
        private courseService: CourseService,
        private teacherService: TeacherService,
        private router: Router,
        private dialogService: ConfirmDialogService,
        private reviewComp: ReviewComponent
    ) { }

    ngOnInit() {
        this.form = this.qcs.toFormGroup(this.questions);
    }

    onSubmit() {
        this.userInput = this.form.value;

        Object.keys(this.userInput).forEach(question => {
            const reviewQuestion = new TextboxQuestion({
                question: question,
                answer: this.userInput[question],
            });
            this.reviewQuestions.push(reviewQuestion);
        });

        this.openDialog();
    }

    public openDialog() {
        this.dialogService
            .confirm('Submit Review', 'Are you sure you want to submit the review?')
            .subscribe(res => {
                if (res) {
                    this.courseService.getCourseByCode(this.course_code)
                        .then(foundCourse => {
                            const newReview = new Review(this.userID, foundCourse.teacher_id, foundCourse._id, this.reviewQuestions);
                            this.reviewService.createReview(newReview);
                            this.reviewComp.reloadReviews();
                        })
                        .catch(err => {
                            console.error(err);
                        });
                }
            },
            error => {
                console.error(error);
            });
    }
}


text:
require 'test_helper'

class OutfitItemsHelperTest < ActionView::TestCase
end


text:
package org.redcross.openmapkit;

import android.content.Context;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by coder on 7/10/15.
 */

public class LocationXMLParser {
    public static final String FILENAME = "proximity_settings.xml";
    public static final String PROXIMITY_CHECK = "proximity_check";
    public static final String PROXIMITY_RADIUS = "proximity_radius";
    public static final String MAX_GPS_FIX_TIME = "max_gps_timer_delay";
    public static final String GPS_THRESHOLD_ACCURACY = "gps_proximity_accuracy";
    public static final double DEFAULT_PROXIMITY_RADIUS = 50d;
    public static final boolean DEFAULT_PROXIMITY_CHECK = false;
    public static final int DEFAULT_GPS_TIMER_DELAY = 0;
    public static final float DEFAULT_GPS_PROXIMITY_ACCURACY = 25f;
    public static final boolean DEFAULT_PROXIMITY_ENABLED = false;

    private static double proximityRadius = DEFAULT_PROXIMITY_RADIUS;
    private static boolean proximityCheck = DEFAULT_PROXIMITY_CHECK;
    private static boolean proximityEnabled = DEFAULT_PROXIMITY_ENABLED;
    private static int gpsTimerDelay = DEFAULT_GPS_TIMER_DELAY;
    private static float gpsProximityAccuracy = DEFAULT_GPS_PROXIMITY_ACCURACY;

    public static XmlPullParser createPullParser(Context ctx) {
        XmlPullParserFactory pullParserFactory;
        try
        {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();

            final File file = new File(ExternalStorage.getSettingsDir()+FILENAME);
            InputStream in_s = new FileInputStream(file);
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);
            return parser;

        } catch (XmlPullParserException e) {
            //e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        return null;
    }

    public static void parseXML(Context ctx) throws XmlPullParserException, IOException {

        String input;
        //Add the default settings.
        XmlPullParser parser = createPullParser(ctx);
        if (parser == null) {
            return;
        }
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name = null;
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equals(PROXIMITY_CHECK)) {
                        input = parser.nextText();
                        if (input.toLowerCase().startsWith("f") || input.toLowerCase().startsWith("n")) {
                            proximityCheck = false;
                        } else if (input.toLowerCase().startsWith("t") || input.toLowerCase().startsWith("y")) {
                            proximityCheck = true;
                        }
                    } else if (name.equals(PROXIMITY_RADIUS)) {
                        input = parser.nextText().trim();
                        try {
                            proximityRadius = Double.parseDouble(input);
                        } catch (NumberFormatException e) {
                            //e.printStackTrace();
                        }
                    } else if (name.equals(MAX_GPS_FIX_TIME)) {
                        input = parser.nextText().trim();
                        try {
                            gpsTimerDelay = Integer.parseInt(input);
                        } catch (NumberFormatException e) {
                            //e.printStackTrace();
                        }
                    } else if (name.equals(GPS_THRESHOLD_ACCURACY)) {
                        input = parser.nextText().trim();
                        try {
                            gpsProximityAccuracy = Float.parseFloat(input);
                        } catch (NumberFormatException e) {
                            //e.printStackTrace();
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    break;
            }
            eventType = parser.next();
        }
    }

    /**
     *
     * @return proximity proximityRadius around user location.
     */
    public static double getProximityRadius() {
        return proximityRadius;
    }

    /**
     *
     * @return true if GPS must be enabled to show user location.
     */
    public static boolean getProximityCheck() {
        return proximityCheck;
    }

    /**
     *
     * @param value set whether to apply proximity settings.
     */
    public static void setProximityEnabled(boolean value) {
        proximityEnabled = value;
    }

    /**
     *
     * @return true if proximity settings should be applied.
     */
    public static boolean isProximityEnabled() {
        return proximityEnabled;
    }

    public static int getGpsTimerDelay() {
        return gpsTimerDelay;
    }

    public static float getGpsProximityAccuracy() {
        return gpsProximityAccuracy;
    }
}


text:
#ifndef _SHELL_H_
#define _SHELL_H_

#include "contracted-gto.h"

/**
 * Represents the Cartesian Shell for a given cartesian number, it is
 * basically a set of ContractedGTOs.
 *
 * The shell with ang_mom 1 is this set:
 * ContractedGTO -> l,m,n = 1,0,0
 * ContractedGTO -> l,m,n = 0,1,0
 * Contractedgto -> l,m,n = 0,0,1
 *
 * In addition they must stay on the same center and they have to
 * share the same set of primitives.
 */
typedef struct  {
  /**
   * Set of ContractedGTOs
   */
  ContractedGTO **functions;
  /**
   * Set of index from the BasisSet
   *
   * The BasisSet is defined in python, this attribute is mainly an
   * hack to get the correct order of integrals
   */
  int *basis_index;
  /**
   * Angular momentum of the shell, S->0, P->1, D->2 etc...
   */
  int ang_mom;
  /**
   * Number of functions in the shell.
   * Treated as the length of functions.
   */
  int nfuncs;
  /**
   * Center of the shell
   * TODO: pending from removal, this is redundant and not so useful.
   */
  double r[3];
} Shell ;

/**
 * Instantiate the shell
 */
Shell *shell_new(void);

/**
 * Initializate the shell malloc'ing the necessary space.
 *
 * @param ang_mom : Angular momentum of the shell
 */
void shell_init(Shell *shell, int ang_mom);

/**
 * Deallocate the shell
 */
void shell_free(Shell *shell);

/**
 * Append a cgto to the shell
 *
 * @param index : this is the index from the original BasisSet. This
 * is used by python code, it can be safely set to 0.
 */
void shell_append(Shell *shell, ContractedGTO *cgto, int index);

/**
 * Compute the max number of primitives in the shell. This function is
 * redundant since in the shell the cgtos are from the same family.
 *
 * @todo pending for removal!
 */
int shell_max_num_prim(Shell *shell);

#endif /* _SHELL_H_ */


text:
public class Test {
    public static void main(String[] args) {
        Token plus = new Token(Token.PLUS,"+");
        Token one = new Token(Token.INT,"1");
        Token two = new Token(Token.INT,"2");
        ExprNode root = new AddNode(new IntNode(one), plus, new IntNode(two));
        System.out.println(root.toStringTree());
    }
}


text:
// written by Roman Dementiev
//

#include <QtGui/QApplication>
#include "widget.h"
#include "../cpucounters.h"
#include <iostream>
#include <unistd.h>
#include <signal.h>

using std::endl;
using std::cout;

#ifdef _MSC_VER
BOOL cleanup(DWORD)
{
    PCM::getInstance()->cleanup();
    return FALSE;
}
#else
void cleanup(int s)
{
    signal(s, SIG_IGN);
    PCM::getInstance()->cleanup();
    exit(0);
}
#endif

int main(int argc, char *argv[])
{
    PCM * m = PCM::getInstance();

    signal(SIGINT, cleanup);
    signal(SIGKILL, cleanup);
    signal(SIGTERM, cleanup);

    PCM::ErrorCode status = m->program();

    switch (status)
    {
    case PCM::Success:
        break;
    case PCM::MSRAccessDenied:
        cout << "Access to Intel(r) Performance Counter Monitor has denied (no MSR or PCI CFG space access)." << endl;
        return -1;
    case PCM::PMUBusy:
        cout << "Access to Intel(r) Performance Counter Monitor has denied (Performance Monitoring Unit is occupied by other application). Try to stop the application that uses PMU." << endl;
        cout << "Alternatively you can try to reset PMU configuration at your own risk. Try to reset? (y/n)" << endl;
        char yn;
        std::cin >> yn;
        if ('y' == yn)
        {
            m->resetPMU();
            cout << "PMU configuration has been reset. Try to rerun the program again." << endl;
        }
        return -1;
    default:
        cout << "Access to Intel(r) Performance Counter Monitor has denied (Unknown error)." << endl;
        return -1;
    }

    if(m->getCPUModel() != PCM::JAKETOWN || m->getNumSockets()!=2 || m->getNumCores()!=32)
    {
      std::cout << "Unsupported platform/configuration" << std::endl;
      return -1;
    }

    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}


text:
.. _android_sdk/testing:
.. include:: /partials/common.rst

Testing
=======

By default, Talkable SDK assigns a permanent ID to each device and uses it to prevent multiple registrations
from a single phone. This helps prevent fraud but can make it challenging to test the referral cycle on
real devices, requiring the developer to either flush all their Talkable campaign data, or use a new campaign
for each test run. Talkable SDK provides tools designed to help with this situation that are available
in debug mode.

The full form of `Talkable.initialize` method allows you to enable the debug mode. In debug mode Talkable SDK
will assign a new ID to the device every time it's initialized, allowing you to be registered as a new visitor each time
the app is launched.

.. code-block:: java

   String initialSiteId = null; // pass null to use the Site ID specified in your manifest
   boolean debug = true;

   Talkable.initialize(this, initialSiteId, debug, null);

You can use the last param to pass a custom device ID, allowing you to switch between user identities manually. This way
you can use a single device to pose as an Advocate or Friend and easily replicate various scenarios. The custom device ID
will be applied only if debug is set to `true`.

.. code-block:: java

   String initialSiteId = null;
   boolean debug = true;
   String customDeviceId = "qa-advocate-007";

   Talkable.initialize(this, initialSiteId, debug, customDeviceId);

.. warning::

   Debug mode must be turned off for release builds. Leaving it enabled will break the referral cycle and expose you to fraud.

.. container:: hidden

   .. toctree::


text:
namespace extensions {

// Times out on win syzyasan, http://crbug.com/166026
#if defined(SYZYASAN)
#define MAYBE_Cookies DISABLED_Cookies
#else
#define MAYBE_Cookies Cookies
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Cookies) {
  ASSERT_TRUE(RunExtensionTest("cookies/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CookiesEvents) {
  ASSERT_TRUE(RunExtensionTest("cookies/events")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CookiesEventsSpanning) {
  // We need to initialize an incognito mode window in order have an initialized
  // incognito cookie store. Otherwise, the chrome.cookies.set operation is just
  // ignored and we won't be notified about a newly set cookie for which we want
  // to test whether the storeId is set correctly.
  OpenURLOffTheRecord(browser()->profile(), GURL("chrome://newtab/"));
  ASSERT_TRUE(RunExtensionTestIncognito("cookies/events_spanning")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CookiesNoPermission) {
  ASSERT_TRUE(RunExtensionTest("cookies/no_permission")) << message_;
}

}  // namespace extensions


text:
import * as PhotoSwipeUI_Default from './dist/photoswipe-ui-default/index';
import * as PhotoSwipe from './index';

function test_defaultUI() {
    var items: PhotoSwipeUI_Default.Item[] = [
        {
            src: "path/to/image.jpg",
            w: 100,
            h: 200,
        },
        {
            src: "path/to/image2.jpg",
            w: 1000,
            h: 2000,
        }
    ];

    var options: PhotoSwipe.Options = {
        index: 3,
        getThumbBoundsFn: function(index) {
            return {x: 100, y: 100, w: 100};
        },
        showAnimationDuration: 333,
        hideAnimationDuration: 333,
        showHideOpacity: false,
        bgOpacity: 1,
        spacing: 0.12,
        allowNoPanText: true,
        maxSpreadZoom: 2,
        getDoubleTapZoom: function(isMouseClick, item) {
            if (isMouseClick) {
                return 1;
            } else {
                return item.initialZoomLevel < 0.7 ? 1 : 1.5;
            }
        },
        loop: true,
        pinchToClose: true,
        closeOnScroll: true,
        closeOnVerticalDrag: true,
        mouseUsed: false,
        escKey: true,
        arrowKeys: true,
        history: true,
        galleryUID: 3,
        errorMsg: '
The image could not be loaded.
',
        preload: [1, 1],
        mainClass: "",
        getNumItemsFn: () => { return 2; },
        focus: true,
        isClickableElement: function(el) {
            return el.tagName === 'A';
        },
        mainScrollEndFriction: 0.35,
        panEndFriction: 0.35,
        modal: true
    };

    var photoSwipe: PhotoSwipe<PhotoSwipeUI_Default.Options>;
    var uiOptions: PhotoSwipeUI_Default.Options = {
        barsSize: {top: 44, bottom: 'auto'},
        timeToIdle: 4000,
        timeToIdleOutside: 1000,
        loadingIndicatorDelay: 1000,
        addCaptionHTMLFn: function(item, captionEl, isFake) {
            if (!item.title) {
                (<HTMLElement> captionEl.children[0]).innerHTML = '';
                return false;
            }
            (<HTMLElement> captionEl.children[0]).innerHTML = item.title;
            return true;
        },
        closeEl: true,
        captionEl: true,
        fullscreenEl: true,
        zoomEl: true,
        shareEl: true,
        counterEl: true,
        arrowEl: true,
        preloaderEl: true,
        tapToClose: false,
        tapToToggleControls: true,
        clickToCloseNonZoomable: true,
        closeElClasses: ['item', 'caption', 'zoom-wrap', 'ui', 'top-bar'],
        indexIndicatorSep: ' / ',
        shareButtons: [
            {id: 'facebook', label: 'Share on Facebook', url: 'https://www.facebook.com/sharer/sharer.php?u='},
            {id: 'twitter', label: 'Tweet', url: 'https://twitter.com/intent/tweet?text=&url='},
            {id: 'pinterest', label: 'Pin it', url: 'http://www.pinterest.com/pin/create/button/?url=&media=&description='},
            {id: 'download', label: 'Download image', url: '', download: true}
        ],
        getImageURLForShare: function( shareButtonData ) {
            // `shareButtonData` - object from shareButtons array
            //
            // `pswp` is the gallery instance object,
            // you should define it by yourself
            //
            return photoSwipe.currItem.src || '';
        },
        getPageURLForShare: function( shareButtonData ) {
            return window.location.href;
        },
        getTextForShare: function( shareButtonData ) {
            return (<PhotoSwipeUI_Default.Item> photoSwipe.currItem).title || '';
        },
        parseShareButtonOut: function(shareButtonData, shareButtonOut) {
            return shareButtonOut;
        }
    };

    var pswpElement = document.getElementById("gallery");
    photoSwipe = new PhotoSwipe<PhotoSwipeUI_Default.Options>(pswpElement, PhotoSwipeUI_Default, items, uiOptions);

}

function test_photoSwipeMethods() {
    var photoSwipe: PhotoSwipe<PhotoSwipeUI_Default.Options>;

    photoSwipe.init();

    alert(photoSwipe.currItem.src);
    alert(photoSwipe.viewportSize.x);
    photoSwipe.ui.init();
    photoSwipe.bg.style.borderStyle = "1px solid red";
    photoSwipe.container.style.borderStyle = "1px solid red";
    photoSwipe.options.timeToIdle = 2000;
    alert(photoSwipe.getCurrentIndex() === 3);
    alert(photoSwipe.getZoomLevel() === 1);
    alert(photoSwipe.isDragging());

    photoSwipe.goTo(9);
    photoSwipe.next();
    photoSwipe.prev();

    photoSwipe.updateSize(true);

    photoSwipe.close();
    photoSwipe.zoomTo(2,
                      { x: 250, y: 250 },
                      2000,
                      (x) => { return x*x*(3-2*x); },
                      (zoomValue) => { console.log("zoom value is now" + zoomValue); });
    photoSwipe.applyZoomPan(1, 0, 0);

    photoSwipe.items[photoSwipe.getCurrentIndex()].src = "new/path/to/image.jpg";
    photoSwipe.invalidateCurrItems();
}

function test_photoSwipeEvents() {
    var photoSwipe: PhotoSwipe<PhotoSwipeUI_Default.Options>;

    photoSwipe.listen('beforeChange', () => {});
    photoSwipe.listen('afterChange', () => {});
    photoSwipe.listen('beforeChange', () => {});
    photoSwipe.listen('imageLoadComplete', (idx: number, item: PhotoSwipeUI_Default.Item) => {
        item.w *= 2;
    });
    photoSwipe.listen('resize', () => {});
    photoSwipe.listen('gettingData', (idx: number, item: PhotoSwipeUI_Default.Item) => {
        item.title = "abc";
    });
    photoSwipe.listen('mouseUsed', () => {});
    photoSwipe.listen('initialZoomIn', () => {});
    photoSwipe.listen('initialZoomInEnd', () => {});
    photoSwipe.listen('initialZoomOut', () => {});
    photoSwipe.listen('initialZoomOutEnd', () => {});
    photoSwipe.listen('parseVerticalMargin', (item: PhotoSwipeUI_Default.Item) => {
        item.vGap.top = 20;
        item.vGap.bottom = 40;
    });
    photoSwipe.listen('close', () => {});
    photoSwipe.listen('unbindEvents', () => {});
    photoSwipe.listen('destroy', () => {});
    photoSwipe.listen('preventDragEvent', (e: MouseEvent, isDown: boolean, preventObj: {prevent: boolean}) => {
        if (e.x > 50 && isDown) {
            preventObj.prevent = true;
        }
    });

    photoSwipe.listen('foo', (a, b, c) => {
        alert(a + b + c);
    });
    photoSwipe.shout('foo', 1, 2, 3);
}

function test_customUI() {
    var pswpElement = document.getElementById("gallery2");
    var myPhotoSwipe = new PhotoSwipe<MyUIOptions>(pswpElement, MyUI, [], {
        bgOpacity: 0,
        index: 3,
        foo: 123,
        bar: "abc"
    });
}

interface MyUIOptions extends PhotoSwipe.Options {
    foo: number;
    bar: string;
}

class MyUI implements PhotoSwipe.UI<MyUIOptions> {
    constructor(pswp: PhotoSwipe<MyUIOptions>, framework: PhotoSwipe.UIFramework) {
        // dummy
    }

    init() {
        // dummy
    }
}


text:
package com.amazonaws.services.config.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.config.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ConfigurationRecorderStatusMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ConfigurationRecorderStatusMarshaller {

    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<java.util.Date> LASTSTARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastStartTime").build();
    private static final MarshallingInfo<java.util.Date> LASTSTOPTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastStopTime").build();
    private static final MarshallingInfo<Boolean> RECORDING_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("recording").build();
    private static final MarshallingInfo<String> LASTSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastStatus").build();
    private static final MarshallingInfo<String> LASTERRORCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastErrorCode").build();
    private static final MarshallingInfo<String> LASTERRORMESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastErrorMessage").build();
    private static final MarshallingInfo<java.util.Date> LASTSTATUSCHANGETIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastStatusChangeTime").build();

    private static final ConfigurationRecorderStatusMarshaller instance = new ConfigurationRecorderStatusMarshaller();

    public static ConfigurationRecorderStatusMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ConfigurationRecorderStatus configurationRecorderStatus, ProtocolMarshaller protocolMarshaller) {

        if (configurationRecorderStatus == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(configurationRecorderStatus.getName(), NAME_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getLastStartTime(), LASTSTARTTIME_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getLastStopTime(), LASTSTOPTIME_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getRecording(), RECORDING_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getLastStatus(), LASTSTATUS_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getLastErrorCode(), LASTERRORCODE_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getLastErrorMessage(), LASTERRORMESSAGE_BINDING);
            protocolMarshaller.marshall(configurationRecorderStatus.getLastStatusChangeTime(), LASTSTATUSCHANGETIME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
cp -f gen_gdl90 /usr/bin/gen_gdl90
cp -f libdump978.so /usr/lib/libdump978.so
cp -f libimu.so /usr/lib/libimu.so

# Startup script.
RASPBIAN_VERSION=`cat /etc/debian_version`
if test "$RASPBIAN_VERSION" = "8.0" ; then
	# Install the systemd startup scripts in any case, even if they won't be used. If this is being run, then the old init.d script
	#  is still intact and we just leave it. If running Wheezy, then remove the old init.d script.
	rm -f /etc/init.d/stratux
	rm -f /etc/rc2.d/S01stratux
	rm -f /etc/rc6.d/K01stratux
fi

cp -f __lib__systemd__system__stratux.service /lib/systemd/system/stratux.service
cp -f __root__stratux-pre-start.sh /root/stratux-pre-start.sh
chmod 644 /lib/systemd/system/stratux.service
chmod 744 /root/stratux-pre-start.sh
ln -fs /lib/systemd/system/stratux.service /etc/systemd/system/multi-user.target.wants/stratux.service

#wifi config
cp -f hostapd.conf /etc/hostapd/hostapd.conf
cp -f hostapd-edimax.conf /etc/hostapd/hostapd-edimax.conf

#WiFi Hostapd ver test and hostapd.conf builder script
cp -f stratux-wifi.sh /usr/sbin/

#WiFi Config Manager
cp -f hostapd_manager.sh /usr/sbin/

#SDR Serial Script
cp -f sdr-tool.sh /usr/sbin/

#boot config
cp -f config.txt /boot/config.txt

#disable serial console
sed -i /boot/cmdline.txt -e "s/console=ttyAMA0,[0-9]\+ //"

#modprobe.d blacklist
cp -f rtl-sdr-blacklist.conf /etc/modprobe.d/

#udev config
cp -f 10-stratux.rules /etc/udev/rules.d
cp -f 99-uavionix.rules /etc/udev/rules.d

#go setup
cp -f bashrc.txt /root/.bashrc
cp -f stxAliases.txt /root/.stxAliases

# /etc/modules
cp -f modules.txt /etc/modules

#motd
cp -f motd /etc/motd

#fan control utility
cp -f fancontrol.py /usr/bin/
chmod 755 /usr/bin/fancontrol.py

cp -f dump1090 /usr/bin/

# Web files install.
cd web/ && make stratuxBuild=${stratuxBuild}

# Remove old Wi-Fi watcher script.
rm -f /usr/sbin/wifi_watch.sh
sed -i "/\bwifi_watch\b/d" /etc/rc.local


text:
cd /home/signage/online_check
nohup python -m SimpleHTTPServer 8000 &
cd /home/signage
while true; do
  chromium-browser http://localhost:8000/online_check.html --kiosk --disable-infobars --disable-session-crashed-bubble
  sleep 10s
done


text:
#region MIT License

// ExceptionUtility.cs
// Version: 0.01
// Last Modified: 2012/09/16 15:59
// Created: 2012/09/09 8:45
//
// Author: Jing-Jun Wei
// Mail: jingjunwei@outlook.com
// Homepage: http://jingjunwei.github.com/unity3d-trajectory-prototypes/
//
// MIT License
// Copyright (c) 2012 Jing-Jun Wei
// 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.

#endregion

#region Usings

using System;
using UnityEngine;
using Object = UnityEngine.Object;

#endregion

namespace KeigunGi.General
{
    /// <summary>
    /// デバッグ用例外検査・報告
    /// </summary>
    public static class ExceptionUtility
    {
        #region Check

        public static bool IsNull(object checker, string log = null)
        {
            bool isNull = checker == null;

#if UNITY_EDITOR
            if(isNull)
            {
                Null(log);
            }
#endif
            return isNull;
        }

        #endregion

        #region Exception

        public static void NotFound(string nameA, string nameB)
        {
#if UNITY_EDITOR
            if(DebugUtility.ShowLog)
            {
                var log = String.Format("Not Found: {0} on {1}", nameA, nameB);
                DebugUtility.Log(log);
            }
#endif
        }

        public static void SwitchDefault()
        {
#if UNITY_EDITOR
            DebugUtility.LogError("Switch Case Not Found!");
#endif
        }

        public static void Null(string log = "Null")
        {
#if UNITY_EDITOR
            if(DebugUtility.ShowError)
            {
                DebugUtility.LogError(log);
            }
#endif
        }

        public static void IllegalComponent(MonoBehaviour target)
        {
            DebugUtility.Log("This base class coundn't be component.");
            Object.Destroy(target);
        }

        #endregion
    }
}


text:
package org.apache.river.api.security;

import java.io.Serializable;
import java.security.Permission;
import java.security.UnresolvedPermission;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Comparator;

/**
 * A Comparator for Permission that avoids using equals and hashCode() on
 * Permission implementations.
 *
 * This comparator orders the Permission first by Class, then Name, followed
 * by Actions.
 *
 * Class is sorted by class hashcode.
 *
 * Name is sorted using Unicode character order, so wildcards "*"  will
 * preceed numbers, which will preceed letters.
 *
 * UnresolvedPermission is a special case.
 *
 * The comparator must be as fast as possible, the common case is not equal,
 * so that must be very fast.
 *
 * Note that for SocketPermissionCollection that the desired order to add to
 * SocketPermission's is in , with the most likely permissions added last.
 *
 * HINT: Use a NavigableMap to return a reverse order iterator for
 * PermissionCollection's like SocketPermissionCollection and
 * FilePermissionCollection.
 *
 *
 * @since 2.2.1
 */
public class PermissionComparator implements Comparator<Permission>, Serializable {
    private static final long serialVersionUID = 1L;
    private static final char wildcard = "*".charAt(0);

    public int compare(Permission o1, Permission o2) {
        if ( o1 == o2 ) return 0;
        if ( o1 == null ) return -1; // o1 is less
        if ( o2 == null ) return 1; // o1 is greater

        int hash1, hash2, comparison;
        // Permission not equal if Class hashCode not equal.
        Class c1 = o1.getClass();
        Class c2 = o2.getClass();
        hash1 = c1.hashCode();
        hash2 = c2.hashCode();
        if (hash1 < hash2) return -1;
        if (hash1 > hash2) return 1;
        //hashcodes equal.
        if (o1 instanceof UnresolvedPermission && o2 instanceof UnresolvedPermission){
            // Special case
            UnresolvedPermission u1 = (UnresolvedPermission) o1, u2 = (UnresolvedPermission) o2;
            String type1 = u1.getUnresolvedType(), type2 = u2.getUnresolvedType();
            if ( type1 == null ){
                if (type2 == null) return 0;
                return -1; // o1 is less
            }
            if ( type2 == null ) return 1; // o1 is greater
            comparison = type1.compareTo(type2);
            if ( comparison != 0 ) return comparison;
            // types equal.
            String name1 = u1.getUnresolvedName(), name2 = u2.getUnresolvedName();
            if ( name1 == null ){
                if (name2 == null) return 0;
                return -1; // o1 is less
            }
            if ( name2 == null ) return 1; // o1 is greater
            comparison = name1.compareTo(name2);
            if ( comparison != 0 ) return comparison;
            // names equal.
            String action1 = u1.getUnresolvedName(), action2 = u2.getUnresolvedName();
            if ( action1 == null ){
                if (action2 == null) return 0;
                return -1; // o1 is less
            }
            if ( action2 == null ) return 1; // o1 is greater
            comparison = action1.compareTo(action2);
            if ( comparison != 0 ) return comparison;
            // actions equal.
            Certificate[] cert1 = u1.getUnresolvedCerts(), cert2 = u2.getUnresolvedCerts();
            if ( cert1 == null ){
                if (cert2 == null) return 0;
                return -1; // o1 is less
            }
            if ( cert2 == null ) return 1; // o1 is greater
            int l1 = cert1.length, l2 = cert2.length;
            if (l1 < l2 ) return -1;
            if (l1 > l2 ) return 1;
            // Same length cert arrays.
            if (Arrays.asList(cert1).containsAll(Arrays.asList(cert2))) return 0;
            // compare each until they don't match don't be fussy they're not equal
            // but they're the same length.
            for (int i = 0; i < l1; i++){
                int c = cert1[i].toString().compareTo(cert2[i].toString());
                if (c != 0) return c;
            }
            return -1;
        }
        String name1 = o1.getName();
        String name2 = o2.getName();
        if ( name1 == null ){
            if (name2 == null) return 0;
            return -1; // o1 is less
        }
        if ( name2 == null ) return 1; // o1 is greater
        comparison = name1.compareTo(name2);
        if ( comparison != 0 ) return comparison;
        // names equal.
        String actions1 = o1.getActions();
        String actions2 = o2.getActions();
        if ( actions1 == null ){
            if (actions2 == null) return 0;
            return -1; // o1 is less
        }
        if ( actions2 == null ) return 1; // o1 is greater
        comparison = actions1.compareTo(actions2);
        if ( comparison != 0 ) return comparison;
        // actions equal.
        // Now we must be careful that these Permission's are truly equal.
        // Check they have same class
        if ( c1.equals(c2)) return 0;
        // if we get to here, someone might be trying to substitute
        return -1;
    }

}


text:
package org.apache.hc.client5.testing.async;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.hc.client5.testing.redirect.Redirect;
import org.apache.hc.client5.testing.redirect.RedirectResolver;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HeaderElements;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.ProtocolException;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
import org.apache.hc.core5.http.nio.CapacityChannel;
import org.apache.hc.core5.http.nio.DataStreamChannel;
import org.apache.hc.core5.http.nio.ResponseChannel;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.Args;

public class RedirectingAsyncDecorator implements AsyncServerExchangeHandler {

    private final AsyncServerExchangeHandler exchangeHandler;
    private final RedirectResolver redirectResolver;
    private final AtomicBoolean redirecting;

    public RedirectingAsyncDecorator(final AsyncServerExchangeHandler exchangeHandler,
                                     final RedirectResolver redirectResolver) {
        this.exchangeHandler = Args.notNull(exchangeHandler, "Exchange handler");
        this.redirectResolver = redirectResolver;
        this.redirecting = new AtomicBoolean();
    }

    private Redirect resolveRedirect(final HttpRequest request) throws HttpException {
        try {
            final URI requestURI = request.getUri();
            return redirectResolver != null ? redirectResolver.resolve(requestURI) : null;
        } catch (final URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    private HttpResponse createRedirectResponse(final Redirect redirect) {
        final HttpResponse response = new BasicHttpResponse(redirect.status);
        if (redirect.location != null) {
            response.addHeader(new BasicHeader(HttpHeaders.LOCATION, redirect.location));
        }
        switch (redirect.connControl) {
            case KEEP_ALIVE:
                response.addHeader(new BasicHeader(HttpHeaders.CONNECTION, HeaderElements.KEEP_ALIVE));
                break;
            case CLOSE:
                response.addHeader(new BasicHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE));
        }
        return response;
    }

    @Override
    public void handleRequest(final HttpRequest request,
                              final EntityDetails entityDetails,
                              final ResponseChannel responseChannel,
                              final HttpContext context) throws HttpException, IOException {
        final Redirect redirect = resolveRedirect(request);
        if (redirect != null) {
            responseChannel.sendResponse(createRedirectResponse(redirect), null, context);
            redirecting.set(true);
        } else {
            exchangeHandler.handleRequest(request, entityDetails, responseChannel, context);
        }
    }

    @Override
    public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
        if (!redirecting.get()) {
            exchangeHandler.updateCapacity(capacityChannel);
        } else {
            capacityChannel.update(Integer.MAX_VALUE);
        }
    }

    @Override
    public final void consume(final ByteBuffer src) throws IOException {
        if (!redirecting.get()) {
            exchangeHandler.consume(src);
        }
    }

    @Override
    public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
        if (!redirecting.get()) {
            exchangeHandler.streamEnd(trailers);
        }
    }

    @Override
    public int available() {
        if (!redirecting.get()) {
            return exchangeHandler.available();
        } else {
            return 0;
        }
    }

    @Override
    public void produce(final DataStreamChannel channel) throws IOException {
        if (!redirecting.get()) {
            exchangeHandler.produce(channel);
        }
    }

    @Override
    public void failed(final Exception cause) {
        if (!redirecting.get()) {
            exchangeHandler.failed(cause);
        }
    }

    @Override
    public void releaseResources() {
        exchangeHandler.releaseResources();
    }

}


text:
require 'joyent-provisioner'
require 'aruba-doubles'

require 'support/aruba'

RSpec.configure do |config|
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'

  config.include ArubaDoubles

  config.before(:each) do
    ArubaDoubles::Double.setup
  end

  config.after(:each) do
    ArubaDoubles::Double.teardown
    history.clear
  end
end