text:
package bt.processor.torrent;

import bt.event.EventSink;
import bt.metainfo.Torrent;
import bt.metainfo.TorrentId;
import bt.peer.IPeerRegistry;
import bt.processor.ProcessingStage;
import bt.processor.TerminateOnErrorProcessingStage;
import bt.processor.listener.ProcessingEvent;
import bt.torrent.TorrentDescriptor;
import bt.torrent.TorrentRegistry;
import bt.torrent.TrackerAnnouncer;
import bt.tracker.AnnounceKey;
import bt.tracker.ITrackerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

public class ProcessTorrentStage<C extends TorrentContext> extends TerminateOnErrorProcessingStage<C> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProcessTorrentStage.class);
    private TorrentRegistry torrentRegistry;
    private final IPeerRegistry peerRegistry;
    private ITrackerService trackerService;
    private EventSink eventSink;

    public ProcessTorrentStage(ProcessingStage<C> next,
                               TorrentRegistry torrentRegistry,
                               IPeerRegistry peerRegistry,
                               ITrackerService trackerService,
                               EventSink eventSink) {
        super(next);
        this.torrentRegistry = torrentRegistry;
        this.peerRegistry = peerRegistry;
        this.trackerService = trackerService;
        this.eventSink = eventSink;
    }

    @Override
    protected void doExecute(C context) throws InterruptedException {
        TorrentId torrentId = context.getTorrentId().get();
        TorrentDescriptor descriptor = getDescriptor(torrentId);

        Torrent torrent = context.getTorrent().get();
        Optional<AnnounceKey> announceKey = torrent.getAnnounceKey();
        if (announceKey.isPresent()) {
            TrackerAnnouncer announcer = new TrackerAnnouncer(trackerService, torrent, announceKey.get(), context.getState().get());
            context.setAnnouncer(announcer);
        }

        descriptor.start();

        eventSink.fireTorrentStarted(torrentId);

        peerRegistry.triggerPeerCollection(torrentId);
        descriptor.getDataDescriptor().waitForAllPieces();
        complete(context);
    }

    private void complete(C context) {
        try {
            context.getTorrentId().ifPresent(torrentId -> getDescriptor(torrentId).complete());
            onCompleted(context);
        } catch (Exception e) {
            LOGGER.error("Unexpected error", e);
        }
    }

    protected void onCompleted(C context) {
        context.getAnnouncer().ifPresent(TrackerAnnouncer::complete);
    }

    private TorrentDescriptor getDescriptor(TorrentId torrentId) {
        return torrentRegistry.getDescriptor(torrentId)
                .orElseThrow(() -> new IllegalStateException("No descriptor present for torrent ID: " + torrentId));
    }

    @Override
    public ProcessingEvent after() {
        return ProcessingEvent.DOWNLOAD_COMPLETE;
    }
}


text:
package org.zouzias.spark.lucenerdd.examples.linkage

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.SparkConf
import org.zouzias.spark.lucenerdd.LuceneRDD
import org.zouzias.spark.lucenerdd.logging.Logging
import org.apache.spark.sql

/**
 * Record linkage example between ACM and DBLP using [[LuceneRDD]]
 *
 * You can run this locally with, ./spark-linkage-acm.sh
 */
object LinkageACMvsDBLP extends Logging {

  def tokenizer(s: String, threshold: Int, comb: String = "OR"): String = {
    s.split(" ")
      .flatMap(_.replaceAll("[^a-zA-Z0-9]", " ").split(" "))
      .filter(_.length > threshold).mkString(s" $comb ")
  }

  def main(args: Array[String]) {

    // initialise spark context
    val conf = new SparkConf().setAppName(LinkageACMvsDBLP.getClass.getName)
    implicit val spark: SparkSession = SparkSession.builder.config(conf).getOrCreate()
    import spark.implicits._

    val start = System.currentTimeMillis()

    val acmDF = spark.read.parquet("data/linkage-papers2/linkage-papers-acm.parquet")
    logInfo(s"Loaded ${acmDF.count} ACM records")
    val dblp2DF = spark.read.parquet("data/linkage-papers2/linkage-papers-dblp2.parquet")
    logInfo(s"Loaded ${acmDF.count} DBLP records")
    val groundTruthDF = spark.read.parquet("data/linkage-papers2/linkage-papers-acm-vs-dblp2.parquet")

    val dblp2 = LuceneRDD(dblp2DF)
    dblp2.cache()

    // Link is the author tokens or title tokens match. Combine all tokens by an OR clause
    // Define a  custom linker (defines your linkage logic)
    val linker: Row => String = {row => {

      // Get title and authors fields
      val title = row.getString(row.fieldIndex("title"))
      val authors = row.getString(row.fieldIndex("authors"))

      val titleTokens = tokenizer(title, 3) // Replace 8 with 3
      val authorsTerms = tokenizer(authors, 3) // Use 3 to get 0.97 accuracy

      if (titleTokens.nonEmpty && authorsTerms.nonEmpty) {
        s"(title:(${titleTokens})) OR (authors:${authorsTerms})"
      }
      else if (titleTokens.nonEmpty){
        s"title:(${titleTokens})"
      }
      else if ( authorsTerms.nonEmpty) {
        s"(authors:${authorsTerms})"
      }
      else {
        "*:*"
      }
    }
    }

    // Perform linkage and return top-5 results
    val linkedResults = dblp2.linkDataFrame(acmDF, linker, 3).filter(_._2.nonEmpty)

    // Compute the performance of linkage (accuracy)
    val linkageResults = spark.createDataFrame(linkedResults.map{ case (acm, topDocs) =>
      (topDocs.head.getString(topDocs.head.fieldIndex("id")),
        acm.getInt(acm.fieldIndex("id")).toString)})
      .toDF("idDBLP", "idACM")

    val correctHits: Double = linkageResults
      .join(groundTruthDF, groundTruthDF.col("idDBLP").equalTo(linkageResults("idDBLP"))
        && groundTruthDF.col("idACM").equalTo(linkageResults("idACM")))
      .count().toDouble
    val total: Double = groundTruthDF.count.toDouble

    val accuracy = correctHits / total
    val end = System.currentTimeMillis()

    logInfo("=" * 40)
    logInfo(s"Elapsed time: ${(end - start) / 1000.0} seconds")
    logInfo("=" * 40)

    logInfo("********************************")
    logInfo(s"Accuracy of linkage is $accuracy")
    logInfo("********************************")

    // terminate spark context
    spark.stop()
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.openapi.util;

import org.jetbrains.annotations.NotNull;

public abstract class AtomicClearableLazyValue<T> extends ClearableLazyValue<T> {

  /** @noinspection MethodOverridesStaticMethodOfSuperclass*/
  @NotNull
  public static <T> AtomicClearableLazyValue<T> create(final Computable<? extends T> computable) {
    return new AtomicClearableLazyValue<T>() {
      @NotNull
      @Override
      protected T compute() {
        return computable.compute();
      }
    };
  }

  @NotNull
  @Override
  public final synchronized T getValue() {
    return super.getValue();
  }

  @Override
  public final synchronized void drop() {
    super.drop();
  }
}


text:
export type TagResource =
  'droplets'
  | 'images'
  | 'volumes'
  | 'volume_snapshots'
  | 'databases';


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Hocus Pocus - Excerpts from Chapter 32</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://jarcane.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//jarcane.github.io/themes/casper/assets/css/screen.css?v=1500842268825" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://jarcane.github.io/2015/07/10/Hocus-Pocus-Excerpts-from-Chapter-32.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Arcane Syntax" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Hocus Pocus - Excerpts from Chapter 32" />
    <meta property="og:description" content=""What a  clever trap your Ruling Class set for us," he went on. "First the atomic bomb. Now this." "Trap?" I echoed wonderingly. "They looted your public and corporate treasuries, and turned your industries over to nincompoops," he said. "Then they had your Government borrow so heavily from us that" />
    <meta property="og:url" content="https://jarcane.github.io/2015/07/10/Hocus-Pocus-Excerpts-from-Chapter-32.html" />
    <meta property="article:published_time" content="2015-07-10T00:00:00.000Z" />
    <meta property="article:tag" content="miscellaneous" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Hocus Pocus - Excerpts from Chapter 32" />
    <meta name="twitter:description" content=""What a  clever trap your Ruling Class set for us," he went on. "First the atomic bomb. Now this." "Trap?" I echoed wonderingly. "They looted your public and corporate treasuries, and turned your industries over to nincompoops," he said. "Then they had your Government borrow so heavily from us that" />
    <meta name="twitter:url" content="https://jarcane.github.io/2015/07/10/Hocus-Pocus-Excerpts-from-Chapter-32.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Arcane Syntax" href="https://jarcane.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

Hocus Pocus - Excerpts from Chapter 32

                <time class="post-date" datetime="2015-07-10">10 July 2015</time>  on miscellaneous

"What a  clever trap your Ruling Class set for us," he went on. "First the atomic bomb. Now this."

"Trap?" I echoed wonderingly.

"They looted your public and corporate treasuries, and turned your industries over to nincompoops," he said. "Then they had your Government borrow so heavily from us that we had no choice but to send over an Army of Occupation in business suits. Never before has the Ruling Class of a country found a way to stick other countries with all the responsibilities their wealth might imply, and still remain rich beyond the dreams of avarice! No wonder they thought the comatose Ronald Reagan was a great President!"

They had managed to convert their wealth, which had originally been in the form of factories or stores or other demanding enterprises, into a form so liquid and abstract, negotiable representations of money on paper, that there were few reminders coming from anywhere that they might be responsible for anyone outside their own circle of friends and relatives.

They didn't rage against the convicts. They were mad at the Government for not making sure that escapes from prison were impossible. The more they ran on like that, the clearer it became that it was their Government, not mine or the convicts' or the Townies'. Its first duty, moreover, was to protect them from the lower classes, not only in this country but everywhere.

If the Trustees were bad, the convicts were worse. I would be the last person to say otherwise. They were devastators of their own communities with gunfights and robberies and rapes, and the merchandising of brain-busting chemicals and on and on.

But at least they saw what they were doing, whereas people like the Trustees had a lot in common with B-52 bombardiers way up in the stratosphere. They seldom saw the devastation they caused as they moved the huge portion of this country's wealth they controlled from here to there.

Unlike my Socialist grandfather Ben Wills, who was a nobody, I have no reforms to propose. I think any form of
government, not just Capitalism, is whatever the people who have all our money, drunk or sober, sane or insane, decide to do today.

― Kurt Vonnegut, Hocus Pocus

                John Berry's Picture

John Berry

Read more posts by this author.

                    Finland
                    http://jarcane.github.com

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

Arcane Syntax © 2017

Proudly published with HubPress


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

global $CFG;
require_once "$CFG->libdir/form/select.php";

/**
 * Drop down form element to select visibility in an activity mod update form
 *
 * HTML class for a drop down element to select visibility in an activity mod update form
 *
 * @package   core_form
 * @category  form
 * @copyright 2006 Jamie Pratt <me@jamiep.org>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class MoodleQuickForm_modvisible extends MoodleQuickForm_select{

    /**
     * Class constructor
     *
     * @param string $elementName Select name attribute
     * @param mixed $elementLabel Label(s) for the select
     * @param mixed $attributes Either a typical HTML attribute string or an associative array
     * @param array $options ignored
     */
    function MoodleQuickForm_modvisible($elementName=null, $elementLabel=null, $attributes=null, $options=null)
    {
        HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes, null);
        $this->_type = 'modvisible';

    }

    /**
     * Called by HTML_QuickForm whenever form event is made on this element
     *
     * @param string $event Name of event
     * @param mixed $arg event arguments
     * @param object $caller calling object
     * @return bool
     */
    function onQuickFormEvent($event, $arg, &$caller)
    {
        switch ($event) {
            case 'createElement':
                $choices=array();
                $choices[1] = get_string('show');
                $choices[0] = get_string('hide');
                $this->load($choices);
                break;

        }
        return parent::onQuickFormEvent($event, $arg, $caller);
    }
}


text:
namespace node {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Local;
using v8::MaybeLocal;
using v8::Object;
using v8::Promise;
using v8::Undefined;
using v8::Value;

namespace fs {

class FSReqBase : public ReqWrap<uv_fs_t> {
 public:
  typedef MaybeStackBuffer<char, 64> FSReqBuffer;

  FSReqBase(Environment* env, Local<Object> req, AsyncWrap::ProviderType type)
      : ReqWrap(env, req, type) {
  }

  void Init(const char* syscall,
            const char* data,
            size_t len,
            enum encoding encoding) {
    syscall_ = syscall;
    encoding_ = encoding;

    if (data != nullptr) {
      CHECK(!has_data_);
      buffer_.AllocateSufficientStorage(len + 1);
      buffer_.SetLengthAndZeroTerminate(len);
      memcpy(*buffer_, data, len);
      has_data_ = true;
    }
  }

  FSReqBuffer& Init(const char* syscall, size_t len,
                    enum encoding encoding) {
    syscall_ = syscall;
    encoding_ = encoding;

    buffer_.AllocateSufficientStorage(len + 1);
    has_data_ = false;  // so that the data does not show up in error messages
    return buffer_;
  }

  virtual void Reject(Local<Value> reject) = 0;
  virtual void Resolve(Local<Value> value) = 0;
  virtual void ResolveStat(const uv_stat_t* stat) = 0;
  virtual void SetReturnValue(const FunctionCallbackInfo<Value>& args) = 0;

  const char* syscall() const { return syscall_; }
  const char* data() const { return has_data_ ? *buffer_ : nullptr; }
  enum encoding encoding() const { return encoding_; }

  size_t self_size() const override { return sizeof(*this); }

 private:
  enum encoding encoding_ = UTF8;
  bool has_data_ = false;
  const char* syscall_ = nullptr;

  // Typically, the content of buffer_ is something like a file name, so
  // something around 64 bytes should be enough.
  FSReqBuffer buffer_;

  DISALLOW_COPY_AND_ASSIGN(FSReqBase);
};

class FSReqWrap : public FSReqBase {
 public:
  FSReqWrap(Environment* env, Local<Object> req)
      : FSReqBase(env, req, AsyncWrap::PROVIDER_FSREQWRAP) { }

  void Reject(Local<Value> reject) override;
  void Resolve(Local<Value> value) override;
  void ResolveStat(const uv_stat_t* stat) override;
  void SetReturnValue(const FunctionCallbackInfo<Value>& args) override;

 private:
  DISALLOW_COPY_AND_ASSIGN(FSReqWrap);
};

template <typename NativeT = double, typename V8T = v8::Float64Array>
class FSReqPromise : public FSReqBase {
 public:
  explicit FSReqPromise(Environment* env)
      : FSReqBase(env,
                  env->fsreqpromise_constructor_template()
                      ->NewInstance(env->context()).ToLocalChecked(),
                  AsyncWrap::PROVIDER_FSREQPROMISE),
        stats_field_array_(env->isolate(), env->kFsStatsFieldsLength) {
    auto resolver = Promise::Resolver::New(env->context()).ToLocalChecked();
    object()->Set(env->context(), env->promise_string(),
                  resolver).FromJust();
  }

  ~FSReqPromise() override {
    // Validate that the promise was explicitly resolved or rejected.
    CHECK(finished_);
  }

  void Reject(Local<Value> reject) override {
    finished_ = true;
    HandleScope scope(env()->isolate());
    InternalCallbackScope callback_scope(this);
    Local<Value> value =
        object()->Get(env()->context(),
                      env()->promise_string()).ToLocalChecked();
    Local<Promise::Resolver> resolver = value.As<Promise::Resolver>();
    resolver->Reject(env()->context(), reject).FromJust();
  }

  void Resolve(Local<Value> value) override {
    finished_ = true;
    HandleScope scope(env()->isolate());
    InternalCallbackScope callback_scope(this);
    Local<Value> val =
        object()->Get(env()->context(),
                      env()->promise_string()).ToLocalChecked();
    Local<Promise::Resolver> resolver = val.As<Promise::Resolver>();
    resolver->Resolve(env()->context(), value).FromJust();
  }

  void ResolveStat(const uv_stat_t* stat) override {
    node::FillStatsArray(&stats_field_array_, stat);
    Resolve(stats_field_array_.GetJSArray());
  }

  void SetReturnValue(const FunctionCallbackInfo<Value>& args) override {
    Local<Value> val =
        object()->Get(env()->context(),
                      env()->promise_string()).ToLocalChecked();
    Local<Promise::Resolver> resolver = val.As<Promise::Resolver>();
    args.GetReturnValue().Set(resolver->GetPromise());
  }

 private:
  bool finished_ = false;
  AliasedBuffer<NativeT, V8T> stats_field_array_;
  DISALLOW_COPY_AND_ASSIGN(FSReqPromise);
};

class FSReqAfterScope {
 public:
  FSReqAfterScope(FSReqBase* wrap, uv_fs_t* req);
  ~FSReqAfterScope();

  bool Proceed();

  void Reject(uv_fs_t* req);

 private:
  FSReqBase* wrap_ = nullptr;
  uv_fs_t* req_ = nullptr;
  HandleScope handle_scope_;
  Context::Scope context_scope_;
};

class FileHandle;

// A request wrap specifically for uv_fs_read()s scheduled for reading
// from a FileHandle.
class FileHandleReadWrap : public ReqWrap<uv_fs_t> {
 public:
  FileHandleReadWrap(FileHandle* handle, v8::Local<v8::Object> obj);

  static inline FileHandleReadWrap* from_req(uv_fs_t* req) {
    return static_cast<FileHandleReadWrap*>(ReqWrap::from_req(req));
  }

  size_t self_size() const override { return sizeof(*this); }

 private:
  FileHandle* file_handle_;
  uv_buf_t buffer_;

  friend class FileHandle;
};

// A wrapper for a file descriptor that will automatically close the fd when
// the object is garbage collected
class FileHandle : public AsyncWrap, public StreamBase {
 public:
  FileHandle(Environment* env,
             int fd,
             v8::Local<v8::Object> obj = v8::Local<v8::Object>());
  virtual ~FileHandle();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);

  int fd() const { return fd_; }
  size_t self_size() const override { return sizeof(*this); }

  // Will asynchronously close the FD and return a Promise that will
  // be resolved once closing is complete.
  static void Close(const FunctionCallbackInfo<Value>& args);

  // Releases ownership of the FD.
  static void ReleaseFD(const FunctionCallbackInfo<Value>& args);

  // StreamBase interface:
  int ReadStart() override;
  int ReadStop() override;

  bool IsAlive() override { return !closed_; }
  bool IsClosing() override { return closing_; }
  AsyncWrap* GetAsyncWrap() override { return this; }

  // In the case of file streams, shutting down corresponds to closing.
  ShutdownWrap* CreateShutdownWrap(v8::Local<v8::Object> object) override;
  int DoShutdown(ShutdownWrap* req_wrap) override;

  int DoWrite(WriteWrap* w,
              uv_buf_t* bufs,
              size_t count,
              uv_stream_t* send_handle) override {
    return UV_ENOSYS;  // Not implemented (yet).
  }

 private:
  // Synchronous close that emits a warning
  void Close();
  void AfterClose();

  class CloseReq : public ReqWrap<uv_fs_t> {
   public:
    CloseReq(Environment* env,
             Local<Promise> promise,
             Local<Value> ref)
        : ReqWrap(env,
                  env->fdclose_constructor_template()
                      ->NewInstance(env->context()).ToLocalChecked(),
                  AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) {
      promise_.Reset(env->isolate(), promise);
      ref_.Reset(env->isolate(), ref);
    }

    ~CloseReq() {
      uv_fs_req_cleanup(req());
      promise_.Reset();
      ref_.Reset();
    }

    FileHandle* file_handle();

    size_t self_size() const override { return sizeof(*this); }

    void Resolve();

    void Reject(Local<Value> reason);

   private:
    Persistent<Promise> promise_;
    Persistent<Value> ref_;
  };

  // Asynchronous close
  inline MaybeLocal<Promise> ClosePromise();

  int fd_;
  bool closing_ = false;
  bool closed_ = false;
  int64_t read_offset_ = -1;
  int64_t read_length_ = -1;

  bool reading_ = false;
  std::unique_ptr<FileHandleReadWrap> current_read_ = nullptr;

  DISALLOW_COPY_AND_ASSIGN(FileHandle);
};

}  // namespace fs

}  // namespace node

#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

#endif  // SRC_NODE_FILE_H_


text:
<template name="voteBubble">

		{{#with user}}

					{{> avatarImage data=this online=true}}

						{{username}}

{{{../message}}}

				<button type="button" class="close">×</button>

		{{/with}}

</template>


text:
package modi;

import java.awt.Point;

import javax.swing.JPanel;

import data.Collector;
import operations.O_CompleteLayout;
import layouter.L_Random;
import layouter.Layouter;
import modi.indicators.I_RandomLayout;
import modi.indicators.Indicator;
import modi.ui.JRectLayout;

public class M_RandomLayout extends LayoutModus {

	private static final M_RandomLayout INSTANCE = new M_RandomLayout();

	private I_RandomLayout indicator;
	private JRectLayout option;
	private Point startCorner = new Point(0,0);
	private Point endCorner = new Point(0,0);

	private M_RandomLayout() {
		super();
		this.indicator = new I_RandomLayout();
		this.option = new JRectLayout(this);
	}

	@Override
	public void runPressedOperation(Point mouse) {
		Optimizer optimizer = Collector.getModi().optimizer;
		startCorner = optimizer.getOptimizedPoint(mouse);

		indicator.setStart(startCorner);
		Collector.getWindow().repaint();
	}

	@Override
	public void runDraggedOperation(Point mouse) {
		Optimizer optimizer = Collector.getModi().optimizer;
		endCorner = optimizer.getOptimizedPoint(mouse);

		indicator.setEnd(endCorner);
		Collector.getWindow().repaint();
	}

	@Override
	public void runLayout() {
		Point leftCorner = new Point(0,0);
		Point rightCorner = new Point(0,0);

		leftCorner.x = Math.min(startCorner.x, endCorner.x);
		leftCorner.y = Math.min(startCorner.y, endCorner.y);
		rightCorner.x = Math.max(startCorner.x, endCorner.x);
		rightCorner.y = Math.max(startCorner.y, endCorner.y);

		Layouter layout = new L_Random(leftCorner, rightCorner);
		new O_CompleteLayout(layout).run();
	}

	@Override
	public void updateValuesFromPanel() {

	}

	@Override
	public JPanel getOptionPanel() {
		return option;
	}

	@Override
	public Indicator getIndicator() {
		return indicator;
	}

	@Override
	public String getDescription() {
		return "Random Layout";
	}

	public static M_RandomLayout getInstance() {
		return INSTANCE;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Listener;
using Microsoft.VisualStudio.Services.WebApi;
using Moq;
using Xunit;

using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;

namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener
{
    public sealed class JobDispatcherL0
    {
        private Mock<IProcessChannel> _processChannel;
        private Mock<IProcessInvoker> _processInvoker;
        private Mock<IAgentServer> _agentServer;
        private Mock<IConfigurationStore> _configurationStore;

        public JobDispatcherL0()
        {
            _processChannel = new Mock<IProcessChannel>();
            _processInvoker = new Mock<IProcessInvoker>();
            _agentServer = new Mock<IAgentServer>();
            _configurationStore = new Mock<IConfigurationStore>();
        }

        private Pipelines.AgentJobRequestMessage CreateJobRequestMessage()
        {
            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline = null;
            JobEnvironment environment = new JobEnvironment();
            List<TaskInstance> tasks = new List<TaskInstance>();
            Guid JobId = Guid.NewGuid();
            var jobRequest = new AgentJobRequestMessage(plan, timeline, JobId, "someJob", "someJob", environment, tasks);
            return Pipelines.AgentJobRequestMessageUtil.Convert(jobRequest);
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatchesJobRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var jobDispatcher = new JobDispatcher();
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                hc.SetSingleton<IAgentServer>(_agentServer.Object);

                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);

                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                jobDispatcher.Initialize(hc);

                Pipelines.AgentJobRequestMessage message = CreateJobRequestMessage();
                string strMessage = JsonUtility.ToString(message);

                _processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<int>(56));

                _processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>(), It.IsAny<bool>()))
                    .Callback((StartProcessDelegate startDel, bool disposeClient) => { startDel("1", "2"); });
                _processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
                    .Returns(Task.CompletedTask);

                var request = new TaskAgentJobRequest();
                PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(sessionIdProperty);
                sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));

                _agentServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));

                //Actt
                jobDispatcher.Run(message);

                //Assert
                await jobDispatcher.WaitAsync(CancellationToken.None);

                Assert.False(jobDispatcher.RunOnceJobCompleted.Task.IsCompleted, "JobDispatcher should not set task complete token for regular agent.");
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatcherRenewJobRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequest));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IAgentServer>(_agentServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count == 5)
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else
                                {
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatcherRenewJobRequestStopOnJobNotFoundExceptions()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobNotFoundExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IAgentServer>(_agentServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count == 5)
                                {
                                    cancellationTokenSource.CancelAfter(10000);
                                    throw new TaskAgentJobNotFoundException("");
                                }
                                else
                                {
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                Assert.False(cancellationTokenSource.IsCancellationRequested);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IAgentServer>(_agentServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count == 5)
                                {
                                    cancellationTokenSource.CancelAfter(10000);
                                    throw new TaskAgentJobTokenExpiredException("");
                                }
                                else
                                {
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                Assert.False(cancellationTokenSource.IsCancellationRequested);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatcherRenewJobRequestRecoverFromExceptions()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestRecoverFromExceptions));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IAgentServer>(_agentServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count < 5)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count == 5 || count == 6 || count == 7)
                                {
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.Cancel();
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                Assert.True(cancellationTokenSource.IsCancellationRequested);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()), Times.Exactly(8));
                _agentServer.Verify(x => x.RefreshConnectionAsync(AgentConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
                _agentServer.Verify(x => x.SetConnectionTimeout(AgentConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Once);
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatcherRenewJobRequestFirstRenewRetrySixTimes()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestFirstRenewRetrySixTimes));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IAgentServer>(_agentServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count <= 5)
                                {
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.CancelAfter(10000);
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.False(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should failed.");
                Assert.False(cancellationTokenSource.IsCancellationRequested);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()), Times.Exactly(6));
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatcherRenewJobRequestStopOnExpiredRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnExpiredRequest));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IAgentServer>(_agentServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count == 1)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count < 5)
                                {
                                    throw new TimeoutException("");
                                }
                                else if (count == 5)
                                {
                                    lockUntilProperty.SetValue(request, DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(11)));
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.CancelAfter(10000);
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                Assert.False(cancellationTokenSource.IsCancellationRequested);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
                _agentServer.Verify(x => x.RefreshConnectionAsync(AgentConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
                _agentServer.Verify(x => x.SetConnectionTimeout(AgentConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Never);
            }
        }

        [Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Agent")]
        public async void DispatchesOneTimeJobRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var jobDispatcher = new JobDispatcher();
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                hc.SetSingleton<IAgentServer>(_agentServer.Object);

                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);

                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                jobDispatcher.Initialize(hc);

                Pipelines.AgentJobRequestMessage message = CreateJobRequestMessage();
                string strMessage = JsonUtility.ToString(message);

                _processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<int>(56));

                _processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>(), It.IsAny<bool>()))
                    .Callback((StartProcessDelegate startDel, bool disposeClient) => { startDel("1", "2"); });
                _processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
                    .Returns(Task.CompletedTask);

                var request = new TaskAgentJobRequest();
                PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(sessionIdProperty);
                sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));

                _agentServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));

                //Act
                jobDispatcher.Run(message, true);

                //Assert
                await jobDispatcher.WaitAsync(CancellationToken.None);

                Assert.True(jobDispatcher.RunOnceJobCompleted.Task.IsCompleted, "JobDispatcher should set task complete token for one time agent.");
                Assert.True(jobDispatcher.RunOnceJobCompleted.Task.Result, "JobDispatcher should set task complete token to 'TRUE' for one time agent.");
            }
        }
    }
}


text:
let browser;
let nickname;

API.onServerEventTrigger.connect(function(eventName, args) {
    if (eventName === "startRegister") {
        const resolution = API.getScreenResolution();

        browser = API.createCefBrowser(Math.round(resolution.Width) * 0.7, Math.round(resolution.Height * 0.7), true);
        API.waitUntilCefBrowserInit(browser);

        const x = (resolution.Width * 0.3) / 2;
        const y = (resolution.Height * 0.3) / 2;

        API.setCefBrowserPosition(browser, x, y);
        API.setCefBrowserHeadless(browser, false);
        API.loadPageCefBrowser(browser, 'UI/Register_Login_Profile/Register.html', false);
        API.showCursor(true);
        API.waitUntilCefBrowserLoaded(browser);
        nickname = args[0];
    }
});

function sendMeNickname() {
    browser.call("setPlayerNickname", nickname);
}

function sendRegistration(regData) {
    API.destroyCefBrowser(browser);
    API.triggerServerEvent("onClientStartRegister", regData);
}


text:
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
    <script src="https://cdn.rawgit.com/jashkenas/coffeescript/master/extras/coffee-script.js"></script>
  </head>

  <body>

     <svg width="1000" height="1000"></svg>

<script type="text/coffeescript">
drawing = [
  { id: 1, x1: 20, y1: 20, x2: 100, y2: 400, color: '#ff0000'}
  { id: 2, x1: 120, y1: 220, x2: 500, y2: 400, color: '#00ff00'}
]

Rectangle  = Backbone.Model.extend {}
Rectangles = Backbone.Collection.extend model: Rectangle
rectangles = new Rectangles drawing

Scene  = Backbone.View.extend(

   events:
     'click rect': 'handleClick'

   handleClick: (ev)->
     id = $(ev.currentTarget).attr 'id'
     rect = @collection.get id
     rect.set 'color', getRandomColor()

   initialize: ->
     @listenTo @collection, 'change:color', @render

   render: ->
     el = @$el
     el.empty()

     @collection.each( (model)->

       rect = document.createElementNS "http://www.w3.org/2000/svg", "rect"
       rect.setAttribute 'x', model.get('x1')
       rect.setAttribute 'y', model.get('y1')
       rect.setAttribute 'width',  model.get('x2') - model.get('x1')
       rect.setAttribute 'height', model.get('y2') - model.get('y1')
       rect.setAttribute 'style', 'fill:' + model.get('color') + ';stroke:pink'
       rect.id = model.get 'id'
       el.append rect

     )

     el

 )

$(document).ready(->
  scene = new Scene el: $('svg'), collection: rectangles
  scene.render()
)

getRandomColor = ->
    letters = '0123456789ABCDEF'.split ''
    color   = '#'

    i = 0
    while i < 6
      color += letters[Math.floor(Math.random() * 16)]
      i++
    color

</script>

  </body>

</html>


text:
using namespace std;

const int kBufferSize = 1024;

int main()
{
	char buffer[kBufferSize];
	cin.getline(buffer, kBufferSize);

	cout << "***" << buffer << "***" << endl;

	string myString;
	std::getline(cin, myString);

	cout << "***" << myString << "***" << endl;

	return 0;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

  <title>Jasmine Spec Runner</title>

  <link href="thirdparty/bootstrap2/css/bootstrap.min.css" rel="stylesheet">
  <link href="thirdparty/bootstrap2/css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="BootstrapReporterView.css" rel="stylesheet">

          Brackets Tests

All

Unit

Integration

Performance

Extensions

Reload

Show Developer Tools


text:
package net.sourceforge.arbaro.params;

public class ParamException extends RuntimeException {
	private static final long serialVersionUID = 1L;

    public ParamException(String msg) {
	super(msg);
    }
};


text:
package framian
package csv

/**
 * A single row in a CSV file.
 */
final class CsvRow(val cells: Vector[CsvCell]) extends AnyVal {
  def text(format: CsvFormat): Vector[String] = cells.map(_ render format)

  def render(format: CsvFormat): String =
    cells.iterator map (_ render format) mkString format.separator

  override def toString: String =
    cells.mkString("CsvRow(", ", ", ")")
}

object CsvRow extends (Vector[CsvCell] => CsvRow) {
  def apply(cells: Vector[CsvCell]): CsvRow = new CsvRow(cells)

  implicit def csvRowExtractor[Col]: RowExtractor[CsvRow, Col, Variable] = {
    import CsvCell.CsvCellColumnTyper // TODO: WHY IS THIS NEEDED! ARGH!
    RowExtractor.collectionOf[Vector, CsvCell, Col].map { cells =>
      CsvRow(cells.map(_.fold[CsvCell](CsvCell.Empty, CsvCell.Invalid)(cell => cell)))
    }
  }
}


text:
define([
    'amber/devel',
    './deploy',
    // --- packages used only during development begin here ---

    'tide_lib/devel',
    'shoreline/ShoreLine-Dev',
    'shoreline/ShoreLine-Tests',
    // 'shoreline/ShoreLine-Examples'
    // 'amber/legacy/Benchfib',
    // 'amber/legacy/Examples',
    'amber/legacy/IDE',

    // --- packages used only during development end here ---
], function (amber) {
    return amber;
});


text:
mklab-framework-common
=============================

This project contains the main class and interface declarations to be used by other projects.


text:
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using Sb.Web.Generated;
namespace Sb.Web.Controllers
{
    public partial class ResultsController
    {
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected ResultsController(Dummy d) { }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoute(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult)
        {
            return RedirectToAction(taskResult.Result);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult)
        {
            return RedirectToActionPermanent(taskResult.Result);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ResultsController Actions { get { return MVC.Results; } }
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Area = "";
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Name = "Results";
        [GeneratedCode("T4MVC", "2.0")]
        public const string NameConst = "Results";
        [GeneratedCode("T4MVC", "2.0")]
        static readonly ActionNamesClass s_actions = new ActionNamesClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionNamesClass ActionNames { get { return s_actions; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNamesClass
        {
            public readonly string Hobby = "Hobby";
            public readonly string Business = "Business";
            public readonly string Unsure = "Unsure";
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNameConstants
        {
            public const string Hobby = "Hobby";
            public const string Business = "Business";
            public const string Unsure = "Unsure";
        }

        static readonly ViewsClass s_views = new ViewsClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ViewsClass Views { get { return s_views; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ViewsClass
        {
            static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass();
            public _ViewNamesClass ViewNames { get { return s_ViewNames; } }
            public class _ViewNamesClass
            {
                public readonly string _Answers = "_Answers";
                public readonly string _IfThingsChange = "_IfThingsChange";
                public readonly string _MandatoryObligations = "_MandatoryObligations";
                public readonly string _OptionalObligations = "_OptionalObligations";
                public readonly string _RateThis = "_RateThis";
                public readonly string _WhatAreYou = "_WhatAreYou";
                public readonly string Index = "Index";
            }
            public readonly string _Answers = "~/Views/Results/_Answers.cshtml";
            public readonly string _IfThingsChange = "~/Views/Results/_IfThingsChange.cshtml";
            public readonly string _MandatoryObligations = "~/Views/Results/_MandatoryObligations.cshtml";
            public readonly string _OptionalObligations = "~/Views/Results/_OptionalObligations.cshtml";
            public readonly string _RateThis = "~/Views/Results/_RateThis.cshtml";
            public readonly string _WhatAreYou = "~/Views/Results/_WhatAreYou.cshtml";
            public readonly string Index = "~/Views/Results/Index.cshtml";
        }
    }

    [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
    public partial class T4MVC_ResultsController : Sb.Web.Controllers.ResultsController
    {
        public T4MVC_ResultsController() : base(Dummy.Instance) { }

        [NonAction]
        partial void HobbyOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Hobby()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Hobby);
            HobbyOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void BusinessOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Business()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Business);
            BusinessOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void UnsureOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Unsure()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Unsure);
            UnsureOverride(callInfo);
            return callInfo;
        }

    }
}

#endregion T4MVC
#pragma warning restore 1591, 3008, 3009, 0108, 0114


text:
using NRules.IntegrationTests.TestAssets;

namespace NRules.IntegrationTests.TestRules
{
    public class ThreeFactTwoNotRule : BaseRule
    {
        public override void Define()
        {
            FactType1 fact1 = null;

            When()
                .Match<FactType1>(() => fact1, f => f.TestProperty.StartsWith("Valid"))
                .Not<FactType2>(f => f.TestProperty.StartsWith("Valid"), f => f.JoinProperty == fact1.TestProperty)
                .Not<FactType3>(f => f.TestProperty.StartsWith("Valid"), f => f.JoinProperty == fact1.TestProperty);
            Then()
                .Do(ctx => Action());
        }
    }
}


text:
<?php

class AcTasksController extends AcBaseController
{

    /**
     * Parent resource AcProject Repository
     *
     * @var AcProject
     */
    protected $acProjectModel;

    /**
     * AcTask Repository
     *
     * @var AcTask
     */
    protected $acTaskModel;

    /**
     * Parent resource AcProject instance
     *
     * @var AcProject
     */
    protected $acProject;

    /**
     * current AcTask instance
     *
     * @var AcTask
     */
    protected $acTask;

    /**
     * AcTask collection
     *
     * @var Illuminate\Database\Eloquent\Collection
     */
    protected $acTasks;

    public function __construct(AcProject $acProjectModel, AcTask $acTaskModel)
    {
        $this->acProjectModel = $acProjectModel;
        $this->acTaskModel = $acTaskModel;
        $this->loadAndAuthorizeResource('ac_project');
        $this->loadAndAuthorizeResource('ac_task', ['through' => 'ac_project']);
    }

    /**
     * Display a listing of the resource.
     *
     * @param  int  $acProjectId
     * @return Response
     */
    public function index($acProjectId)
    {
        // $this->acTasks = $this->acTaskModel->get();

        return view('ac_tasks.index', compact_property($this, 'acProject', 'acTasks'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @param  int  $acProjectId
     * @return Response
     */
    public function create($acProjectId)
    {
        return view('ac_tasks.create', compact_property($this, 'acProject'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  int  $acProjectId
     * @return Response
     */
    public function store($acProjectId)
    {
        // $this->acTask = app('AcTask');

        $this->acTask->fill(request()->except('_method', '_token'));
        $this->acTask->ac_project_id = $acProjectId;
        try {
            $this->acTask->save();
            return redirect()->route('ac_projects.ac_tasks.index', $acProjectId);
        } catch (Exception $e) {
            return redirect()->route('ac_projects.ac_tasks.create', $acProjectId)
                ->withErrors($this->acTask->errors())
                ->with('message', 'There were validation errors.');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $acProjectId
     * @param  int  $id
     * @return Response
     */
    public function show($acProjectId, $id)
    {
        // $this->acTask = $this->acTaskModel->findOrFail($id);

        return view('ac_tasks.show', compact_property($this, 'acTask'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $acProjectId
     * @param  int  $id
     * @return Response
     */
    public function edit($acProjectId, $id)
    {
        // $this->acTask = $this->acTaskModel->find($id);

        if (is_null($this->acTask)) {
            return redirect()->route('ac_projects.ac_tasks.index', $acProjectId);
        }

        return view('ac_tasks.edit', compact_property($this, 'acTask'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $acProjectId
     * @param  int  $id
     * @return Response
     */
    public function update($acProjectId, $id)
    {
        // $this->acTask = $this->acTaskModel->find($id);

        $this->acTask->fill(request()->except('_method', '_token'));
        try {
            $this->acTask->save();
            return redirect()->route('ac_projects.ac_tasks.show', [$acProjectId, $id]);
        } catch (Exception $e) {
            return redirect()->route('ac_projects.ac_tasks.edit', $id)
                ->withErrors($this->acTask->errors())
                ->with('message', 'There were validation errors.');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $acProjectId
     * @param  int  $id
     * @return Response
     */
    public function destroy($acProjectId, $id)
    {
        // $this->acTaskModel->find($id)->delete();

        $this->acTask->delete();

        return redirect()->route('ac_projects.ac_tasks.index', $acProjectId);
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**genre** | [**BroadcastRelations_genre**](BroadcastRelations_genre.md) |  | [optional] [default to null]
**items** | [**BroadcastRelations_items**](BroadcastRelations_items.md) |  | [optional] [default to null]
**blocks** | [**BroadcastRelations_blocks**](BroadcastRelations_blocks.md) |  | [optional] [default to null]
**program** | [**BlockRelations_program**](BlockRelations_program.md) |  | [optional] [default to null]
**tags** | [**BroadcastRelations_tags**](BroadcastRelations_tags.md) |  | [optional] [default to null]
**presenters** | [**BroadcastRelations_presenters**](BroadcastRelations_presenters.md) |  | [optional] [default to null]
**model_type** | [**BroadcastRelations_model_type**](BroadcastRelations_model_type.md) |  | [optional] [default to null]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

var classCallCheck = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var WorkerWrapper = function () {
  function WorkerWrapper(worker) {
    var _this = this;

    classCallCheck(this, WorkerWrapper);

    this.worker = worker;
    this.listeners = [];
    this.nextId = 0;

    this.worker.addEventListener('message', function (event) {
      var id = event.data.id;
      var error = event.data.error;
      var result = event.data.result;

      _this.listeners[id](error, result);
      delete _this.listeners[id];
    });
  }

  createClass(WorkerWrapper, [{
    key: 'render',
    value: function render(src, options) {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        var id = _this2.nextId++;

        _this2.listeners[id] = function (error, result) {
          if (error) {
            reject(new Error(error.message, error.fileName, error.lineNumber));
            return;
          }
          resolve(result);
        };

        _this2.worker.postMessage({ id: id, src: src, options: options });
      });
    }
  }]);
  return WorkerWrapper;
}();

var ModuleWrapper = function ModuleWrapper(module, render) {
  classCallCheck(this, ModuleWrapper);

  var instance = module();
  this.render = function (src, options) {
    return new Promise(function (resolve, reject) {
      try {
        resolve(render(instance, src, options));
      } catch (error) {
        reject(error);
      }
    });
  };
};

// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

function b64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
    return String.fromCharCode('0x' + p1);
  }));
}

function defaultScale() {
  if ('devicePixelRatio' in window && window.devicePixelRatio > 1) {
    return window.devicePixelRatio;
  } else {
    return 1;
  }
}

function svgXmlToImageElement(svgXml) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$scale = _ref.scale,
      scale = _ref$scale === undefined ? defaultScale() : _ref$scale,
      _ref$mimeType = _ref.mimeType,
      mimeType = _ref$mimeType === undefined ? "image/png" : _ref$mimeType,
      _ref$quality = _ref.quality,
      quality = _ref$quality === undefined ? 1 : _ref$quality;

  return new Promise(function (resolve, reject) {
    var svgImage = new Image();

    svgImage.onload = function () {
      var canvas = document.createElement('canvas');
      canvas.width = svgImage.width * scale;
      canvas.height = svgImage.height * scale;

      var context = canvas.getContext("2d");
      context.drawImage(svgImage, 0, 0, canvas.width, canvas.height);

      canvas.toBlob(function (blob) {
        var image = new Image();
        image.src = URL.createObjectURL(blob);
        image.width = svgImage.width;
        image.height = svgImage.height;

        resolve(image);
      }, mimeType, quality);
    };

    svgImage.onerror = function (e) {
      var error;

      if ('error' in e) {
        error = e.error;
      } else {
        error = new Error('Error loading SVG');
      }

      reject(error);
    };

    svgImage.src = 'data:image/svg+xml;base64,' + b64EncodeUnicode(svgXml);
  });
}

function svgXmlToImageElementFabric(svgXml) {
  var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref2$scale = _ref2.scale,
      scale = _ref2$scale === undefined ? defaultScale() : _ref2$scale,
      _ref2$mimeType = _ref2.mimeType,
      mimeType = _ref2$mimeType === undefined ? 'image/png' : _ref2$mimeType,
      _ref2$quality = _ref2.quality,
      quality = _ref2$quality === undefined ? 1 : _ref2$quality;

  var multiplier = scale;

  var format = void 0;
  if (mimeType == 'image/jpeg') {
    format = 'jpeg';
  } else if (mimeType == 'image/png') {
    format = 'png';
  }

  return new Promise(function (resolve, reject) {
    fabric.loadSVGFromString(svgXml, function (objects, options) {
      // If there's something wrong with the SVG, Fabric may return an empty array of objects. Graphviz appears to give us at least one <g> element back even given an empty graph, so we will assume an error in this case.
      if (objects.length == 0) {
        reject(new Error('Error loading SVG with Fabric'));
      }

      var element = document.createElement("canvas");
      element.width = options.width;
      element.height = options.height;

      var canvas = new fabric.Canvas(element, { enableRetinaScaling: false });
      var obj = fabric.util.groupSVGElements(objects, options);
      canvas.add(obj).renderAll();

      var image = new Image();
      image.src = canvas.toDataURL({ format: format, multiplier: multiplier, quality: quality });
      image.width = options.width;
      image.height = options.height;

      resolve(image);
    });
  });
}

var Viz = function () {
  function Viz() {
    var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        workerURL = _ref3.workerURL,
        worker = _ref3.worker,
        Module = _ref3.Module,
        render = _ref3.render;

    classCallCheck(this, Viz);

    if (typeof workerURL !== 'undefined') {
      this.wrapper = new WorkerWrapper(new Worker(workerURL));
    } else if (typeof worker !== 'undefined') {
      this.wrapper = new WorkerWrapper(worker);
    } else if (typeof Module !== 'undefined' && typeof render !== 'undefined') {
      this.wrapper = new ModuleWrapper(Module, render);
    } else if (typeof Viz.Module !== 'undefined' && typeof Viz.render !== 'undefined') {
      this.wrapper = new ModuleWrapper(Viz.Module, Viz.render);
    } else {
      throw new Error('Must specify workerURL or worker option, Module and render options, or include one of full.js.opaque or lite.js.opaque after viz.js.');
    }
  }

  createClass(Viz, [{
    key: 'renderString',
    value: function renderString(src) {
      var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
          _ref4$format = _ref4.format,
          format = _ref4$format === undefined ? 'svg' : _ref4$format,
          _ref4$engine = _ref4.engine,
          engine = _ref4$engine === undefined ? 'dot' : _ref4$engine,
          _ref4$files = _ref4.files,
          files = _ref4$files === undefined ? [] : _ref4$files,
          _ref4$images = _ref4.images,
          images = _ref4$images === undefined ? [] : _ref4$images,
          _ref4$yInvert = _ref4.yInvert,
          yInvert = _ref4$yInvert === undefined ? false : _ref4$yInvert;

      for (var i = 0; i < images.length; i++) {
        files.push({
          path: images[i].path,
          data: '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n<svg width="' + images[i].width + '" height="' + images[i].height + '"></svg>'
        });
      }

      return this.wrapper.render(src, { format: format, engine: engine, files: files, images: images, yInvert: yInvert });
    }
  }, {
    key: 'renderSVGElement',
    value: function renderSVGElement(src) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      return this.renderString(src, _extends({}, options, { format: 'svg' })).then(function (str) {
        var parser = new DOMParser();
        return parser.parseFromString(str, 'image/svg+xml').documentElement;
      });
    }
  }, {
    key: 'renderImageElement',
    value: function renderImageElement(src) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var scale = options.scale,
          mimeType = options.mimeType,
          quality = options.quality;

      return this.renderString(src, _extends({}, options, { format: 'svg' })).then(function (str) {
        if ((typeof fabric === 'undefined' ? 'undefined' : _typeof(fabric)) === "object" && fabric.loadSVGFromString) {
          return svgXmlToImageElementFabric(str, { scale: scale, mimeType: mimeType, quality: quality });
        } else {
          return svgXmlToImageElement(str, { scale: scale, mimeType: mimeType, quality: quality });
        }
      });
    }
  }, {
    key: 'renderJSONObject',
    value: function renderJSONObject(src) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var format = options.format;

      if (format !== 'json' || format !== 'json0') {
        format = 'json';
      }

      return this.renderString(src, _extends({}, options, { format: format })).then(function (str) {
        return JSON.parse(str);
      });
    }
  }]);
  return Viz;
}();

export default Viz;


text:
var EventEmitter = require('events').EventEmitter;
var log = require('./logging');
var util = require('util');
var dispatcher = require('../dispatcher/dispatcher');

function FlickrStore() {
	EventEmitter.call(this);
}

util.inherits(FlickrStore, EventEmitter);

FlickrStore.prototype.actionHandler = function (action) {
	var retval = null;
	log.log("FlickrStore got an action: " + action.type);
	switch (action.type) {
		case dispatcher.action.FLICKR_VIEW:
			retval = getFlickrImages();
			break;

		case dispatcher.action.MOVE_VIEW:
			retval = getFlickrImages();
			break;
	}
	return retval;
};

function getFlickrImages() {
	_store.emit('reset');
	//ajaxGet("https://api.flickr.com/services/feeds/photos_public.gne?format=json");
	//ajaxGet("https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=landscape,sky");
	ajaxGet("https://api.flickr.com/services/feeds/photos_public.gne?format=json&id=135040308@N08");
}

function ajaxGet(req_url) {
	log.log("GET Request to " + req_url);
	$.ajax({
		method: "GET",
		dataType: "jsonp",
		url: req_url,
	});
}

// Deal with the callback of the jsonp request
window["jsonFlickrFeed"] = function (data) {
	var array = data.items;
	array.forEach(function(item){
		var title = item.title;
		var url = item.media.m;

		var newItem = {title: title, url: url};

		_store.emit('new_image', newItem);
	});
}

var _store = new FlickrStore();
module.exports = _store;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<type>
    <display-name>Media</display-name>
    <is-abstract>false</is-abstract>
    <is-final>false</is-final>
    <is-built-in>true</is-built-in>
    <allow-child-content>false</allow-child-content>
    <form/>
</type>


text:
namespace hobbes { namespace stream {

typedef std::vector<uint8_t> RawData;

template < typename Char = char, typename Traits = std::char_traits<Char> >
  class raw_ostream_buffer : public std::basic_streambuf<Char, Traits> {
  public:
    typedef std::basic_streambuf<Char, Traits> BaseT;
    typedef typename BaseT::int_type  int_type;
    typedef typename BaseT::char_type char_type;

    raw_ostream_buffer(RawData* d) : d(d) {
    }
  private:
    RawData* d;

    int_type overflow(int_type c) {
      if (c != Traits::eof()) {
        d->push_back((uint8_t)Traits::to_char_type(c));
      }
      return Traits::not_eof(c);
    }
  };

template < typename Char = char, typename Traits = std::char_traits<Char> >
  class raw_ostream : public std::basic_ostream<Char, Traits> {
  public:
    raw_ostream(RawData* d) : std::basic_ostream<Char, Traits>(&buffer), buffer(d) {
    }
  private:
    raw_ostream_buffer<Char, Traits> buffer;

    raw_ostream();
    raw_ostream(const raw_ostream<Char, Traits>&);
    raw_ostream<Char, Traits>& operator=(const raw_ostream<Char,Traits>&);
  };

template < typename Char = char, typename Traits = std::char_traits<Char> >
  class raw_istream_buffer : public std::basic_streambuf<Char, Traits> {
  public:
    typedef std::basic_streambuf<Char, Traits> BaseT;

    raw_istream_buffer(const RawData& d) {
      if (d.size() == 0) {
        BaseT::setg(0,0,0);
      } else {
        BaseT::setg((Char*)&d[0], (Char*)&d[0], (Char*)(&d[0] + d.size()));
      }
    }
  };

template < typename Char = char, typename Traits = std::char_traits<Char> >
  class raw_istream : public std::basic_istream<Char, Traits> {
  public:
    raw_istream(const RawData& d) : std::basic_istream<Char, Traits>(&buffer), buffer(d) {
    }
  private:
    raw_istream_buffer<Char, Traits> buffer;

    raw_istream();
    raw_istream(const raw_istream<Char, Traits>&);
    raw_istream<Char, Traits>& operator=(const raw_istream<Char,Traits>&);
  };

}}

#endif


text:
var NwBuilder = require('node-webkit-builder');
var gulp = require('gulp');
var gutil = require('gulp-util');
var install = require("gulp-install");
var del = require('del');

// Build package
gulp.task('nw', function () {
	var nw = new NwBuilder({
		version: '0.12.1', // Current Node Version
		files: ['./src/**'],
		platforms: ['osx64', 'win64'], // Available options ['osx', 'osx32', 'osx64', 'win', 'win32', 'win64']
		macZip: true
		//,
		//macIcns: "/path/to/your/icon.icns",
		//winIco: "/path/to/your/icon.ico"
	});
	// Log stuff you want
	nw.on('log', function (msg) {
		gutil.log('node-webkit-builder', msg);
	});
	// Build returns a promise, return it so the task isn't called in parallel
	return nw.build().catch(function (err) {
		gutil.log('node-webkit-builder', err);
	});
});

// Clean .git folder
gulp.task('clean:git', function (cb) {
	del([
		'test/',
		'.git'
	], cb);
});

// Install `src` folder dependencies
gulp.task('src:install', function () {
	gulp.src(['./src/bower.json', './src/package.json']).pipe(install());
});

// Init
gulp.task('init', ['clean:git', 'src:install']);


text:
//
// 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.
//
/**
 * Namespace: System.Web.UI.WebControls
 * Class:     UnitConverter
 *
 * Author:  Gaurav Vaish
 * Maintainer: gvaish@iitk.ac.in
 * Contact: <my_scripts2001@yahoo.com>, <gvaish@iitk.ac.in>
 * Implementation: yes
 * Status:  100%
 *
 * (C) Gaurav Vaish (2002)
 */

using System;
using System.Globalization;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.ComponentModel.Design.Serialization;
using System.Reflection;

namespace System.Web.UI.WebControls
{
	public class UnitConverter : TypeConverter
	{
		public UnitConverter(): base()
		{
		}

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if(sourceType == typeof(string))
				return true;
			return CanConvertFrom(context, sourceType);
		}

#if NET_2_0
		public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == typeof (string))
				return true;

			if (destinationType == typeof (InstanceDescriptor))
				return true;

			return base.CanConvertTo (context, destinationType);
		}
#endif

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if(value == null)
				return null;
			if(value is string)
			{
				string val = ((string)value).Trim();
				if(val.Length == 0)
				{
					return Unit.Empty;
				}
				return (culture == null ? Unit.Parse(val) : Unit.Parse(val, culture));
			}
			return ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if(destinationType == typeof(string))
			{
				Unit val = (Unit)value;
				if(val == Unit.Empty)
				{
					return String.Empty;
				}
				return val.ToString(culture);
			}

#if NET_2_0
			if (destinationType == typeof (InstanceDescriptor) && value is Unit) {
				Unit s = (Unit) value;
				ConstructorInfo ci = typeof(Unit).GetConstructor (new Type[] { typeof(double), typeof(UnitType) });
				return new InstanceDescriptor (ci, new object[] { s.Value, s.Type });
			}

			if (destinationType == typeof (InstanceDescriptor) && value is string) {
				Unit s = Unit.Parse ((string)value, CultureInfo.InvariantCulture);
				ConstructorInfo ci = typeof(Unit).GetConstructor (new Type[] { typeof(double), typeof(UnitType) });
				return new InstanceDescriptor (ci, new object[] { s.Value, s.Type });
			}
#endif

			return ConvertTo(context, culture, value, destinationType);
		}
	}
}


text:
#if !defined __X86INTRIN_H && !defined __IMMINTRIN_H
#error "Never use <movdirintrin.h> directly; include <x86intrin.h> instead."
#endif

#ifndef _MOVDIRINTRIN_H
#define _MOVDIRINTRIN_H

/* Move doubleword as direct store */
static __inline__ void
__attribute__((__always_inline__, __nodebug__,  __target__("movdiri")))
_directstoreu_u32 (void *__dst, unsigned int  __value)
{
  __builtin_ia32_directstore_u32((unsigned int *)__dst, (unsigned int)__value);
}

#ifdef __x86_64__

/* Move quadword as direct store */
static __inline__ void
__attribute__((__always_inline__, __nodebug__,  __target__("movdiri")))
_directstoreu_u64 (void *__dst, unsigned long __value)
{
  __builtin_ia32_directstore_u64((unsigned long *)__dst, __value);
}

#endif /* __x86_64__ */

/*
 * movdir64b - Move 64 bytes as direct store.
 * The destination must be 64 byte aligned, and the store is atomic.
 * The source address has no alignment requirement, and the load from
 * the source address is not atomic.
 */
static __inline__ void
__attribute__((__always_inline__, __nodebug__,  __target__("movdir64b")))
_movdir64b (void *__dst __attribute__((align_value(64))), const void *__src)
{
  __builtin_ia32_movdir64b(__dst, __src);
}

#endif /* _MOVDIRINTRIN_H */


text:
<?xml version="1.0" encoding="UTF-8"?>
<solver>
  <!--<environmentMode>FAST_ASSERT</environmentMode>-->

  <!-- Domain model configuration -->
  <scanAnnotatedClasses>
    <packageInclude>org.optaplanner.examples.cloudbalancing</packageInclude>
  </scanAnnotatedClasses>

  <!-- Score configuration -->
  <scoreDirectorFactory>
    <!--<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.optional.score.CloudBalancingEasyScoreCalculator</easyScoreCalculatorClass>-->
    <!--<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.optional.score.CloudBalancingMapBasedEasyScoreCalculator</easyScoreCalculatorClass>-->
    <!--<incrementalScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.optional.score.CloudBalancingIncrementalScoreCalculator</incrementalScoreCalculatorClass>-->
    <scoreDrl>org/optaplanner/examples/cloudbalancing/solver/cloudBalancingScoreRules.drl</scoreDrl>
    <initializingScoreTrend>ONLY_DOWN</initializingScoreTrend>
    <!--<assertionScoreDirectorFactory>-->
      <!--<easyScoreCalculatorClass>org.optaplanner.examples.cloudbalancing.optional.score.CloudBalancingMapBasedEasyScoreCalculator</easyScoreCalculatorClass>-->
    <!--</assertionScoreDirectorFactory>-->
  </scoreDirectorFactory>

  <!-- Optimization algorithms configuration -->
  <termination>
    <secondsSpentLimit>120</secondsSpentLimit>
  </termination>

  <!-- Power tweaked optimization algorithms configuration -->
  <!--<constructionHeuristic>-->
    <!--<constructionHeuristicType>FIRST_FIT_DECREASING</constructionHeuristicType>-->
  <!--</constructionHeuristic>-->
  <!--<localSearch>-->
    <!--<unionMoveSelector>-->
      <!--<changeMoveSelector/>-->
      <!--<swapMoveSelector/>-->
      <!--<pillarChangeMoveSelector/>-->
      <!--<pillarSwapMoveSelector/>-->
    <!--</unionMoveSelector>-->
    <!--<acceptor>-->
      <!--<entityTabuSize>7</entityTabuSize>-->
    <!--</acceptor>-->
    <!--<forager>-->
      <!--<acceptedCountLimit>1000</acceptedCountLimit>-->
    <!--</forager>-->
  <!--</localSearch>-->

  <!-- Alternative power tweaked optimization algorithms configuration -->
  <!--<partitionedSearch>-->
    <!--<solutionPartitionerClass>org.optaplanner.examples.cloudbalancing.optional.partitioner.CloudBalancePartitioner</solutionPartitionerClass>-->
    <!--<solutionPartitionerCustomProperties>-->
      <!--<partCount>4</partCount>-->
      <!--<minimumProcessListSize>300</minimumProcessListSize>-->
    <!--</solutionPartitionerCustomProperties>-->
  <!--</partitionedSearch>-->
</solver>


text:
package com.dss886.nForumSDK.service;

import java.io.IOException;

import com.dss886.nForumSDK.util.ParamOption;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;

import com.dss886.nForumSDK.http.GetMethod;
import com.dss886.nForumSDK.http.NForumException;
import com.dss886.nForumSDK.http.PostMethod;
import com.dss886.nForumSDK.model.Vote;

/**
 * 该类封装了投票接口,
 * 见https://github.com/xw2423/nForum/wiki/nForum-API
 * @author dss886
 * @since 2014-9-7
 */
public class VoteService {

    public static final String CATEGORY_ME = "me";
    public static final String CATEGORY_JOIN = "join";
    public static final String CATEGORY_LIST = "list";
    public static final String CATEGORY_NEW = "new";
    public static final String CATEGORY_HOT = "hot";
    public static final String CATEGORY_ALL = "all";

	private DefaultHttpClient httpClient;
	private String host;
	private String returnFormat;
	private String appkey;
	private String auth;

	public VoteService(DefaultHttpClient httpClient, String host,
			String returnFormat, String appkey, String auth){
		this.httpClient = httpClient;
		this.host = host;
		this.returnFormat = returnFormat;
		this.appkey = appkey;
		this.auth = auth;
	}

	/**
	 * 获取投票信息
	 * @param vid 投票vid
	 * @return 投票元数据
	 * @throws JSONException
	 * @throws NForumException
	 * @throws IOException
	 */
	public Vote getVote(int vid) throws JSONException,
		NForumException, IOException {
		String url = host + "vote/" + vid + returnFormat + appkey;
		GetMethod getMethod = new GetMethod(httpClient, auth, url);
        return Vote.parse(getMethod.getJSON());
	}

    /**
     * 投票操作(单选)
     *
     * @param vid  投票vid
     * @param viid 所提交的投票选项
     * @return 投票元数据
     * @throws JSONException
     * @throws NForumException
     * @throws IOException
     */
    public Vote vote(int vid, int viid) throws
            JSONException, NForumException, IOException {
        String url = host + "vote/" + vid + returnFormat + appkey;
        ParamOption params = new ParamOption()
                .addParams("vote", viid);
        PostMethod postMethod = new PostMethod(httpClient, auth, url, params);
        return Vote.parse(postMethod.postJSON());
    }

    /**
     * 投票操作(多选)
     *
     * @param vid   投票vid
     * @param viids 所有提交的投票选项项的viid集合
     * @return 投票元数据
     * @throws JSONException
     * @throws NForumException
     * @throws IOException
     */
    public Vote vote(int vid, int[] viids) throws
            JSONException, NForumException, IOException {
        String url = host + "vote/" + vid + returnFormat + appkey;
        ParamOption params = new ParamOption();
        for (int i = 0; i < viids.length; i++) {
            params.addParams("vote[" + i + "]", viids[i]);
        }
        PostMethod postMethod = new PostMethod(httpClient, auth, url, params);
        return Vote.parse(postMethod.postJSON());
    }

    /**
	 * 获取投票列表
	 * @param category 投票列表类型,取值为me|join|list|new|hot|all,
	 *		建议使用VoteService.CATEGORY_*常量
	 * @return 投票元数据
	 * @throws JSONException
	 * @throws NForumException
	 * @throws IOException
	 */
	public Vote getVoteList(String category, ParamOption params) throws JSONException,
		NForumException, IOException {
		String url = host + "vote/category/" + category + returnFormat + appkey + params;
		GetMethod getMethod = new GetMethod(httpClient, auth, url);
		return Vote.parse(getMethod.getJSON());
	}

}


text:
package extension;

import java.util.Scanner;

import client.Evenement;
import client.interfaces.IEntreeUtilisateur;

public class EntreeConsole implements IEntreeUtilisateur {

	Scanner reader = new Scanner(System.in);

	@Override
	public Evenement lireEntree() {
		System.out.println("Saisissez un déplacement : z = haut, s = bas, q = gauche, d = droite ");
		String choix = reader.nextLine();

		switch(choix){
		case "z" :
			return new Evenement(Evenement.HAUT);
		case "s" :
			return new Evenement(Evenement.BAS);
		case "q" :
			return new Evenement(Evenement.GAUCHE);
		case "d" :
			return new Evenement(Evenement.DROITE);
		default:
			break;
		}

		return null;

	}

}


text:
Texture const * Texture::g_current_texture[Texture::MAX_TEXTURE_UNITS] =
{
  0, 0
};
unsigned Texture::g_active_texture_unit = 0;

Texture::Texture(unsigned width, unsigned height, unsigned channels, void * data, bool clamp) :
  m_id(0),
  m_width(width),
  m_height(height)
{
  dnload_glGenTextures(1, &m_id);

#if defined(USE_LD)
  const Texture* prev_texture = g_current_texture[g_active_texture_unit];
  this->bind(g_active_texture_unit);
#endif

  static GLenum const formats[] =
  {
    0,
    GL_LUMINANCE,
    GL_LUMINANCE_ALPHA,
    GL_RGB,
    GL_RGBA
  };
  GLenum const format = formats[channels];
  GLint const wrap_mode = clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT;

  dnload_glBindTexture(GL_TEXTURE_2D, m_id);
  dnload_glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(format), static_cast<GLsizei>(width),
      static_cast<GLsizei>(height), 0, format, GL_UNSIGNED_BYTE, data);

  dnload_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  dnload_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  dnload_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_mode);
  dnload_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_mode);

#if defined(USE_LD)
  glGenerateMipmap(GL_TEXTURE_2D);

  if(prev_texture)
  {
    prev_texture->bind(g_active_texture_unit);
  }
#endif
}

#ifdef USE_LD
Texture::~Texture()
{
  for(unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  {
    if(g_current_texture[i] && g_current_texture[i]->m_id == m_id)
    {
      dnload_glActiveTexture(GL_TEXTURE0 + i);
      dnload_glBindTexture(GL_TEXTURE_2D, 0);
      g_current_texture[i] = NULL;
    }
  }

  dnload_glActiveTexture(GL_TEXTURE0 + g_active_texture_unit);

  if(m_id)
  {
    glDeleteTextures(1, &m_id);
  }
}
#endif

void Texture::bind(unsigned texture_unit) const
{
  if(g_current_texture[texture_unit] != this)
  {
    dnload_glActiveTexture(GL_TEXTURE0 + texture_unit);
    dnload_glBindTexture(GL_TEXTURE_2D, m_id);
    g_active_texture_unit = texture_unit;
    g_current_texture[texture_unit] = this;
  }
}


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

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.chimesdkmeetings.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * StopMeetingTranscriptionResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StopMeetingTranscriptionResultJsonUnmarshaller implements Unmarshaller<StopMeetingTranscriptionResult, JsonUnmarshallerContext> {

    public StopMeetingTranscriptionResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        StopMeetingTranscriptionResult stopMeetingTranscriptionResult = new StopMeetingTranscriptionResult();

        return stopMeetingTranscriptionResult;
    }

    private static StopMeetingTranscriptionResultJsonUnmarshaller instance;

    public static StopMeetingTranscriptionResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new StopMeetingTranscriptionResultJsonUnmarshaller();
        return instance;
    }
}