text:
require File.dirname(__FILE__) + '/../../spec_helper.rb'

module Spec
  module Runner
    describe Options do
      before(:each) do
        @err = StringIO.new('')
        @out = StringIO.new('')
        @options = Options.new(@err, @out)
      end

      after(:each) do
        Spec::Expectations.differ = nil
      end

      describe "#examples" do
        it "should default to empty array" do
          @options.examples.should == []
        end
      end

      describe "#include_pattern" do
        it "should default to '**/*_spec.rb'" do
          @options.filename_pattern.should == "**/*_spec.rb"
        end
      end

      describe "#files_to_load" do

        it "should load files not following pattern if named explicitly" do
          file = File.expand_path(File.dirname(__FILE__) + "/resources/a_bar.rb")
          @options.files << file
          @options.files_to_load.should include(file)
        end

        describe "with default --pattern" do
          it "should load files named _spec.rb" do
            dir = File.expand_path(File.dirname(__FILE__) + "/resources/")
            @options.files << dir
            @options.files_to_load.should == ["#{dir}/a_spec.rb"]
          end
        end

        describe "with explicit pattern (single)" do
          before(:each) do
            @options.filename_pattern = "**/*_foo.rb"
          end

          it "should load files following pattern" do
            file = File.expand_path(File.dirname(__FILE__) + "/resources/a_foo.rb")
            @options.files << file
            @options.files_to_load.should include(file)
          end

          it "should load files in directories following pattern" do
            dir = File.expand_path(File.dirname(__FILE__) + "/resources")
            @options.files << dir
            @options.files_to_load.should include("#{dir}/a_foo.rb")
          end

          it "should not load files in directories not following pattern" do
            dir = File.expand_path(File.dirname(__FILE__) + "/resources")
            @options.files << dir
            @options.files_to_load.should_not include("#{dir}/a_bar.rb")
          end
        end

        describe "with explicit pattern (comma,separated,values)" do

          before(:each) do
            @options.filename_pattern = "**/*_foo.rb,**/*_bar.rb"
          end

          it "should support comma separated values" do
            dir = File.expand_path(File.dirname(__FILE__) + "/resources")
            @options.files << dir
            @options.files_to_load.should include("#{dir}/a_foo.rb")
            @options.files_to_load.should include("#{dir}/a_bar.rb")
          end

          it "should support comma separated values with spaces" do
            dir = File.expand_path(File.dirname(__FILE__) + "/resources")
            @options.files << dir
            @options.files_to_load.should include("#{dir}/a_foo.rb")
            @options.files_to_load.should include("#{dir}/a_bar.rb")
          end

        end

      end

      describe "#backtrace_tweaker" do
        it "should default to QuietBacktraceTweaker" do
          @options.backtrace_tweaker.class.should == QuietBacktraceTweaker
        end
      end

      describe "#dry_run" do
        it "should default to false" do
          @options.dry_run.should == false
        end
      end

      describe "#context_lines" do
        it "should default to 3" do
          @options.context_lines.should == 3
        end
      end

      describe "#parse_diff with nil" do
        before(:each) do
          @options.parse_diff nil
        end

        it "should make diff_format unified" do
          @options.diff_format.should == :unified
        end

        it "should set Spec::Expectations.differ to be a default differ" do
          Spec::Expectations.differ.class.should ==
            ::Spec::Expectations::Differs::Default
        end
      end

      describe "#parse_diff with 'unified'" do
        before(:each) do
          @options.parse_diff 'unified'
        end

        it "should make diff_format unified and uses default differ_class" do
          @options.diff_format.should == :unified
          @options.differ_class.should equal(Spec::Expectations::Differs::Default)
        end

        it "should set Spec::Expectations.differ to be a default differ" do
          Spec::Expectations.differ.class.should ==
            ::Spec::Expectations::Differs::Default
        end
      end

      describe "#parse_diff with 'context'" do
        before(:each) do
          @options.parse_diff 'context'
        end

        it "should make diff_format context and uses default differ_class" do
          @options.diff_format.should == :context
          @options.differ_class.should == Spec::Expectations::Differs::Default
        end

        it "should set Spec::Expectations.differ to be a default differ" do
          Spec::Expectations.differ.class.should ==
            ::Spec::Expectations::Differs::Default
        end
      end

      describe "#parse_diff with Custom::Differ" do
        before(:each) do
          @options.parse_diff 'Custom::Differ'
        end

        it "should use custom differ_class" do
          @options.diff_format.should == :custom
          @options.differ_class.should == Custom::Differ
          Spec::Expectations.differ.should be_instance_of(Custom::Differ)
        end

        it "should set Spec::Expectations.differ to be a default differ" do
          Spec::Expectations.differ.class.should ==
            ::Custom::Differ
        end
      end

      describe "#parse_diff with missing class name" do
        it "should raise error" do
          lambda { @options.parse_diff "Custom::MissingDiffer" }.should raise_error(NameError)
          @err.string.should match(/Couldn't find differ class Custom::MissingDiffer/n)
        end
      end

      describe "#parse_example" do
        it "with argument thats not a file path, sets argument as the example" do
          example = "something or other"
          File.file?(example).should == false
          @options.parse_example example
          @options.examples.should eql(["something or other"])
        end

        it "with argument that is a file path, sets examples to contents of the file" do
          example = "#{File.dirname(__FILE__)}/examples.txt"
          File.should_receive(:file?).with(example).and_return(true)
          file = StringIO.new("Sir, if you were my husband, I would poison your drink.\nMadam, if you were my wife, I would drink it.")
          File.should_receive(:open).with(example).and_return(file)

          @options.parse_example example
          @options.examples.should eql([
            "Sir, if you were my husband, I would poison your drink.",
              "Madam, if you were my wife, I would drink it."
          ])
        end
      end

      describe "#examples_should_not_be_run" do
        it "should cause #run_examples to return true and do nothing" do
          @options.examples_should_not_be_run
          ExampleGroupRunner.should_not_receive(:new)

          @options.run_examples.should be_true
        end
      end

      describe "#load_class" do
        it "should raise error when not class name" do
          lambda do
            @options.send(:load_class, 'foo', 'fruit', '--food')
          end.should raise_error('"foo" is not a valid class name')
        end
      end

      describe "#reporter" do
        it "returns a Reporter" do
          @options.reporter.should be_instance_of(Reporter)
          @options.reporter.options.should === @options
        end
      end

      describe "#add_example_group affecting passed in example_group" do
        it "runs all examples when options.examples is nil" do
          example_1_has_run = false
          example_2_has_run = false
          @example_group = Class.new(::Spec::Example::ExampleGroup).describe("Some Examples") do
            it "runs 1" do
              example_1_has_run = true
            end
            it "runs 2" do
              example_2_has_run = true
            end
          end

          @options.examples = nil

          @options.add_example_group @example_group
          @options.run_examples
          example_1_has_run.should be_true
          example_2_has_run.should be_true
        end

        it "keeps all example_definitions when options.examples is empty" do
          example_1_has_run = false
          example_2_has_run = false
          @example_group = Class.new(::Spec::Example::ExampleGroup).describe("Some Examples") do
            it "runs 1" do
              example_1_has_run = true
            end
            it "runs 2" do
              example_2_has_run = true
            end
          end

          @options.examples = []

          @options.add_example_group @example_group
          @options.run_examples
          example_1_has_run.should be_true
          example_2_has_run.should be_true
        end
      end

      describe "#add_example_group affecting example_group" do
        it "adds example_group when example_group has example_definitions and is not shared" do
          @example_group = Class.new(::Spec::Example::ExampleGroup).describe("Some Examples") do
            it "uses this example_group" do
            end
          end

          @options.number_of_examples.should == 0
          @options.add_example_group @example_group
          @options.number_of_examples.should == 1
          @options.example_groups.length.should == 1
        end
      end

      describe "#remove_example_group" do
        it "should remove the ExampleGroup from the list of ExampleGroups" do
          @example_group = Class.new(::Spec::Example::ExampleGroup).describe("Some Examples") do
          end
          @options.add_example_group @example_group
          @options.example_groups.should include(@example_group)

          @options.remove_example_group @example_group
          @options.example_groups.should_not include(@example_group)
        end
      end

      describe "#run_examples" do
        it "should use the standard runner by default" do
          runner = ::Spec::Runner::ExampleGroupRunner.new(@options)
          ::Spec::Runner::ExampleGroupRunner.should_receive(:new).
            with(@options).
            and_return(runner)
          @options.user_input_for_runner = nil

          @options.run_examples
        end

        it "should use a custom runner when given" do
          runner = Custom::ExampleGroupRunner.new(@options, nil)
          Custom::ExampleGroupRunner.should_receive(:new).
            with(@options, nil).
            and_return(runner)
          @options.user_input_for_runner = "Custom::ExampleGroupRunner"

          @options.run_examples
        end

        it "should use a custom runner with extra options" do
          runner = Custom::ExampleGroupRunner.new(@options, 'something')
          Custom::ExampleGroupRunner.should_receive(:new).
            with(@options, 'something').
            and_return(runner)
          @options.user_input_for_runner = "Custom::ExampleGroupRunner:something"

          @options.run_examples
        end

        describe "when there are examples" do
          before(:each) do
            @options.add_example_group Class.new(::Spec::Example::ExampleGroup)
            @options.formatters << Formatter::BaseTextFormatter.new(@options, @out)
          end

          it "runs the Examples and outputs the result" do
            @options.run_examples
            @out.string.should include("0 examples, 0 failures")
          end

          it "sets #examples_run? to true" do
            @options.examples_run?.should be_false
            @options.run_examples
            @options.examples_run?.should be_true
          end

          describe "when using heckle runner" do
            before(:each) do
              @heckle_runner_mock = mock("HeckleRunner")
              @options.heckle_runner = @heckle_runner_mock
            end

            it "should heckle" do
              @heckle_runner_mock.should_receive(:heckle_with)
              @options.run_examples
            end

            it "shouldn't heckle recursively" do
              heckled = false
              @heckle_runner_mock.should_receive(:heckle_with) {
                heckled.should == false
                heckled = true
                @options.run_examples
              }
              @options.run_examples
            end

            it "shouldn't load spec files twice" do
              example_runner = mock("ExampleGroupRunner")
              example_runner_inside_heckle = mock("ExampleGroupRunner inside Heckle")

              ExampleGroupRunner.should_receive(:new).twice.and_return(
                example_runner, example_runner_inside_heckle
              )

              example_runner.stub!(:run)
              example_runner.should_receive(:load_files)
              @heckle_runner_mock.stub!(:heckle_with).and_return { @options.run_examples }
              example_runner_inside_heckle.stub!(:run)
              example_runner_inside_heckle.should_not_receive(:load_files)

              @options.run_examples
            end
          end
        end

        describe "when there are no examples" do
          before(:each) do
            @options.formatters << Formatter::BaseTextFormatter.new(@options, @out)
          end

          it "does not run Examples and does not output a result" do
            @options.run_examples
            @out.string.should_not include("examples")
            @out.string.should_not include("failures")
          end

          it "sets #examples_run? to false" do
            @options.examples_run?.should be_false
            @options.run_examples
            @options.examples_run?.should be_false
          end
        end
      end
    end
  end
end


text:
require "edible_recipe/engine"

module EdibleRecipe
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import 'vs/text!./webview.html';
import URI from 'vs/base/common/uri';
import {TPromise} from 'vs/base/common/winjs.base';
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
import {addDisposableListener, addClass} from 'vs/base/browser/dom';
import {isLightTheme} from 'vs/platform/theme/common/themes';
import {KeybindingsRegistry} from 'vs/platform/keybinding/common/keybindingsRegistry';

declare interface WebviewElement extends HTMLElement {
	src: string;
	autoSize: 'on';
	nodeintegration: 'on';
	disablewebsecurity: 'on';

	getURL(): string;
	getTitle(): string;
	executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => any);
	send(channel: string, ...args: any[]);
	openDevTools(): any;
	closeDevTools(): any;
}

KeybindingsRegistry.registerCommandDesc({
	id: '_webview.openDevTools',
	when: null,
	weight: KeybindingsRegistry.WEIGHT.workbenchContrib(0),
	primary: null,
	handler() {
		const elements = document.querySelectorAll('webview.ready');
		for (let i = 0; i < elements.length; i++) {
			try {
				(<WebviewElement>elements.item(i)).openDevTools();
			} catch (e) {
				console.error(e);
			}
		}
	}
});

export default class Webview {

	private _webview: WebviewElement;
	private _ready: TPromise<this>;
	private _disposables: IDisposable[];

	constructor(private _parent: HTMLElement, private _styleElement: Element, onDidClickLink:(uri:URI)=>any) {
		this._webview = <WebviewElement>document.createElement('webview');

		this._webview.style.width = '100%';
		this._webview.style.height = '100%';
		this._webview.autoSize = 'on';
		this._webview.nodeintegration = 'on';
		this._webview.src = require.toUrl('./webview.html');

		this._ready = new TPromise<this>(resolve => {
			const subscription = addDisposableListener(this._webview, 'ipc-message', (event) => {
				if (event.channel === 'webview-ready') {

					// console.info('[PID Webview] ' + event.args[0]);
					addClass(this._webview, 'ready'); // can be found by debug command

					subscription.dispose();
					resolve(this);
				}
			});
		});

		this._disposables = [
			addDisposableListener(this._webview, 'console-message', function (e: { level: number; message: string; line: number; sourceId: string; }) {
				console.log(`[Embedded Page] ${e.message}`);
			}),
			addDisposableListener(this._webview, 'crashed', function () {
				console.error('embedded page crashed');
			}),
			addDisposableListener(this._webview, 'ipc-message', (event) => {
				if (event.channel === 'did-click-link') {
					let [uri] = event.args;
					onDidClickLink(URI.parse(uri));
				}
			})
		];

		this._parent.appendChild(this._webview);
	}

	dispose(): void {
		this._disposables = dispose(this._disposables);
		this._webview.parentElement.removeChild(this._webview);
	}

	private _send(channel: string, ...args: any[]): void {
		this._ready
			.then(() => this._webview.send(channel, ...args))
			.done(void 0, console.error);
	}

	set contents(value: string[]) {
		this._send('content', value);
	}

	set baseUrl(value: string) {
		this._send('baseUrl', value);
	}

	focus(): void {
		this._webview.focus();
		this._send('focus');
	}

	style(themeId: string): void {
		const {color, backgroundColor, fontFamily, fontSize} = window.getComputedStyle(this._styleElement);

		let value = `
		:root {
			--background-color: ${backgroundColor};
			--color: ${color};
			--font-family: ${fontFamily};
			--font-size: ${fontSize};
		}
		body {
			margin: 0;
			background-color: var(--background-color);
			color: var(--color);
			font-family: var(--font-family);
			font-size: var(--font-size);
		}
		img {
			max-width: 100%;
			max-height: 100%;
		}
		a:focus,
		input:focus,
		select:focus,
		textarea:focus {
			outline: 1px solid -webkit-focus-ring-color;
			outline-offset: -1px;
		}
		::-webkit-scrollbar {
			width: 14px;
			height: 10px;
		}
		::-webkit-scrollbar-thumb:hover {
			background-color: rgba(100, 100, 100, 0.7);
		}`;

		if (isLightTheme(themeId)) {
			value += `
			::-webkit-scrollbar-thumb {
				background-color: rgba(100, 100, 100, 0.4);
			}
			::-webkit-scrollbar-thumb:active {
				background-color: rgba(0, 0, 0, 0.6);
			}`;
		} else {
			value += `
			::-webkit-scrollbar-thumb {
				background-color: rgba(121, 121, 121, 0.4);
			}
			::-webkit-scrollbar-thumb:active {
				background-color: rgba(85, 85, 85, 0.8);
			}`;
		}

		this._send('styles', value);
	}
}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/hair/zabrak/shared_hair_zabrak_female_s07.iff"
	result.attribute_template_id = -1
	result.stfName("hair_name","hair")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
This is a simple logging module. It can be used to generate pretty/colorized logs or plain text logs suitable for a syslog environment. This was created as a simple npm demo for the [Bleeding Edge Web Meetup](http://www.meetup.com/bleeding-edge-web/) ([slide deck](http://edgeatx.github.io/slides/2015/03-mar/#slide-32)).

## Usage

Creating a custom logger is straightforward. There are two configuration options that can be passed to a logger: `prefix` and `colorize`. By default, there is no prefix and `colorize` defaults to `true`.

```js
var CustomLogger = require('../'),
    log = new CustomLogger({
      prefix: 'Test Server'
    }),
    log2 = new CustomLogger({
      colorize: false
    });

log.log('Basic text.');
log.info('Important information.');
log.warn('Watch out!');
log.error('Uh oh! Something is awry.');

console.log('\n===========================\n');

log2.log('Basic text.');
log2.info('Important information.');
log2.warn('Watch out!');
log2.error('Uh oh! Something is awry.');
```

The code above produces:

![Screenshot](https://raw.githubusercontent.com/coreybutler/demomodule/master/demo.png)

## Installation

Download node at [nodejs.org](http://nodejs.org) and install it, if you haven't already.

```sh
npm install edgeatx-npm-demo --save
```

## Tests

**NOTICE:** You must `git clone https://github.com/edgeatx/npm-demo.git` this module to obtain tests.

```sh
npm install
npm test
```

## Dependencies

- [chalk](https://github.com/sindresorhus/chalk): Terminal string styling done right. Much color.

## Dev Dependencies

- [mocha](https://github.com/mochajs/mocha): simple, flexible, fun test framework

## License

MIT

_Generated by [package-json-to-readme](https://github.com/zeke/package-json-to-readme)_


text:
package ly.stealth.mesos.kafka

import net.elodina.mesos.util.{Strings, Period, Version, Repr}
import java.util.concurrent.ConcurrentHashMap
import org.apache.mesos.Protos._
import org.apache.mesos.{MesosSchedulerDriver, SchedulerDriver}
import java.util
import com.google.protobuf.ByteString
import java.util.{Collections, Date}
import scala.collection.JavaConversions._
import org.apache.log4j._
import scala.Some
import org.apache.mesos.Protos.Environment.Variable
import scala.collection.mutable

object Scheduler extends org.apache.mesos.Scheduler {
  private val logger: Logger = Logger.getLogger(this.getClass)
  val version: Version = new Version("0.9.5.1")

  val cluster: Cluster = new Cluster()
  private var driver: SchedulerDriver = null

  val logs = new ConcurrentHashMap[Long, Option[String]]()

  private[kafka] def newExecutor(broker: Broker): ExecutorInfo = {
    var cmd = "java -cp " + HttpServer.jar.getName
    cmd += " -Xmx" + broker.heap + "m"
    if (broker.jvmOptions != null) cmd += " " + broker.jvmOptions.replace("$id", broker.id)

    if (Config.debug) cmd += " -Ddebug"
    cmd += " ly.stealth.mesos.kafka.Executor"

    val commandBuilder = CommandInfo.newBuilder
    if (Config.jre != null) {
      commandBuilder.addUris(CommandInfo.URI.newBuilder().setValue(Config.api + "/jre/" + Config.jre.getName))
      cmd = "jre/bin/" + cmd
    }

    val env = new mutable.HashMap[String, String]()
    env("MESOS_SYSLOG_TAG") = Config.frameworkName + "-" + broker.id
    if (broker.syslog) env("MESOS_SYSLOG") = "true"

    val envBuilder = Environment.newBuilder()
    for ((name, value) <- env)
      envBuilder.addVariables(Variable.newBuilder().setName(name).setValue(value))
    commandBuilder.setEnvironment(envBuilder)

    commandBuilder
      .addUris(CommandInfo.URI.newBuilder().setValue(Config.api + "/jar/" + HttpServer.jar.getName).setExtract(false))
      .addUris(CommandInfo.URI.newBuilder().setValue(Config.api + "/kafka/" + HttpServer.kafkaDist.getName))
      .setValue(cmd)

    ExecutorInfo.newBuilder()
      .setExecutorId(ExecutorID.newBuilder.setValue(Broker.nextExecutorId(broker)))
      .setCommand(commandBuilder)
      .setName("broker-" + broker.id)
      .build()
  }

  private[kafka] def newTask(broker: Broker, offer: Offer, reservation: Broker.Reservation): TaskInfo = {
    def taskData: ByteString = {
      var defaults: Map[String, String] = Map(
        "broker.id" -> broker.id,
        "port" -> ("" + reservation.port),
        "log.dirs" -> "kafka-logs",
        "log.retention.bytes" -> ("" + 10l * 1024 * 1024 * 1024),

        "zookeeper.connect" -> Config.zk,
        "host.name" -> offer.getHostname
      )

      if (HttpServer.kafkaVersion.compareTo(new Version("0.9")) >= 0)
        defaults += ("listeners" -> s"PLAINTEXT://:${reservation.port}")

      if (reservation.volume != null)
        defaults += ("log.dirs" -> "data/kafka-logs")

      val data = new util.HashMap[String, String]()
      data.put("broker", "" + broker.toJson(false))
      data.put("defaults", Strings.formatMap(defaults))
      ByteString.copyFromUtf8(Strings.formatMap(data))
    }

    val taskBuilder: TaskInfo.Builder = TaskInfo.newBuilder
      .setName(Config.frameworkName + "-" + broker.id)
      .setTaskId(TaskID.newBuilder.setValue(Broker.nextTaskId(broker)).build)
      .setSlaveId(offer.getSlaveId)
      .setData(taskData)
      .setExecutor(newExecutor(broker))

    taskBuilder.addAllResources(reservation.toResources)
    taskBuilder.build
  }

  def registered(driver: SchedulerDriver, id: FrameworkID, master: MasterInfo): Unit = {
    logger.info("[registered] framework:" + Repr.id(id.getValue) + " master:" + Repr.master(master))

    cluster.frameworkId = id.getValue
    cluster.save()

    this.driver = driver
    checkMesosVersion(master)
    reconcileTasksIfRequired(force = true)
  }

  def reregistered(driver: SchedulerDriver, master: MasterInfo): Unit = {
    logger.info("[reregistered] master:" + Repr.master(master))
    this.driver = driver
    reconcileTasksIfRequired(force = true)
  }

  def resourceOffers(driver: SchedulerDriver, offers: util.List[Offer]): Unit = {
    logger.debug("[resourceOffers]\n" + Repr.offers(offers))
    syncBrokers(offers)
  }

  def offerRescinded(driver: SchedulerDriver, id: OfferID): Unit = {
    logger.info("[offerRescinded] " + Repr.id(id.getValue))
  }

  def statusUpdate(driver: SchedulerDriver, status: TaskStatus): Unit = {
    logger.info("[statusUpdate] " + Repr.status(status))
    onBrokerStatus(status)
  }

  def frameworkMessage(driver: SchedulerDriver, executorId: ExecutorID, slaveId: SlaveID, data: Array[Byte]): Unit = {
    logger.debug("[frameworkMessage] executor:" + Repr.id(executorId.getValue) + " slave:" + Repr.id(slaveId.getValue) + " data: " + new String(data))

    val broker = cluster.getBroker(Broker.idFromExecutorId(executorId.getValue))

    try {
      val node: Map[String, Object] = Util.parseJson(new String(data))
      if (node.contains("metrics")) {
        if (broker != null && broker.active) {
          val metricsNode = node("metrics").asInstanceOf[Map[String, Object]]
          val metrics = new Broker.Metrics()
          metrics.fromJson(metricsNode)

          broker.metrics = metrics
        }
      }

      if (node.contains("log")) {
        if (broker != null && broker.active && broker.task != null && broker.task.running) {
          val logResponse = LogResponse.fromJson(node)
          if (logs.containsKey(logResponse.requestId)) {
            logs.put(logResponse.requestId, Some(logResponse.content))
          }
        }
      }
    } catch {
      case e: IllegalArgumentException =>
        logger.warn("Unable to parse framework message as JSON", e)
    }
  }

  def disconnected(driver: SchedulerDriver): Unit = {
    logger.info("[disconnected]")
    this.driver = null
  }

  def slaveLost(driver: SchedulerDriver, id: SlaveID): Unit = {
    logger.info("[slaveLost] " + Repr.id(id.getValue))
  }

  def executorLost(driver: SchedulerDriver, executorId: ExecutorID, slaveId: SlaveID, status: Int): Unit = {
    logger.info("[executorLost] executor:" + Repr.id(executorId.getValue) + " slave:" + Repr.id(slaveId.getValue) + " status:" + status)
  }

  def error(driver: SchedulerDriver, message: String): Unit = {
    logger.info("[error] " + message)
  }

  private[kafka] def syncBrokers(offers: util.List[Offer]): Unit = {
    val declineReasons = new util.ArrayList[String]()
    var didSomething = false
    for (offer <- offers) {
      val declineReason = acceptOffer(offer)

      if (declineReason != null) {
        driver.declineOffer(offer.getId)
        if (!declineReason.isEmpty) declineReasons.add(offer.getHostname + Repr.id(offer.getId.getValue) + " - " + declineReason)
      } else {
        didSomething = true
      }
    }

    if (!declineReasons.isEmpty) logger.info("Declined offers:\n" + declineReasons.mkString("\n"))

    for (broker <- cluster.getBrokers) {
      if (broker.shouldStop) {
        logger.info(s"Stopping broker ${broker.id}: killing task ${broker.task.id}")
        driver.killTask(TaskID.newBuilder.setValue(broker.task.id).build)
        broker.task.state = Broker.State.STOPPING
        didSomething = true
      }
    }

    didSomething |= reconcileTasksIfRequired()
    if (didSomething) {
      cluster.save()
      logger.info("Saving cluster state")
    }
  }

  private[kafka] def acceptOffer(offer: Offer): String = {
    if (isReconciling) return "reconciling"
    val now = new Date()

    var reason = ""
    for (broker <- cluster.getBrokers.filter(_.shouldStart(offer.getHostname))) {
      val diff = broker.matches(offer, now, otherTasksAttributes)

      if (diff == null) {
        launchTask(broker, offer)
        return null
      } else {
        if (!reason.isEmpty) reason += ", "
        reason += s"broker ${broker.id}: $diff"
      }
    }

    reason
  }

  private[kafka] def onBrokerStatus(status: TaskStatus): Unit = {
    val broker = cluster.getBroker(Broker.idFromTaskId(status.getTaskId.getValue))

    status.getState match {
      case TaskState.TASK_RUNNING =>
        onBrokerStarted(broker, status)
      case TaskState.TASK_LOST | TaskState.TASK_FINISHED |
           TaskState.TASK_FAILED | TaskState.TASK_KILLED |
           TaskState.TASK_ERROR =>
        onBrokerStopped(broker, status)
      case _ => logger.warn("Got unexpected task state: " + status.getState)
    }

    cluster.save()
  }

  private[kafka] def onBrokerStarted(broker: Broker, status: TaskStatus): Unit = {
    if (broker == null || broker.task == null || broker.task.id != status.getTaskId.getValue) {
      logger.info(s"Got ${status.getState} for unknown/stopped broker, killing task ${status.getTaskId}")
      driver.killTask(status.getTaskId)
      return
    }

    if (broker.task.reconciling)
      logger.info(s"Finished reconciling of broker ${broker.id}, task ${broker.task.id}")

    broker.task.state = Broker.State.RUNNING
    if (status.getData.size() > 0) broker.task.endpoint = new Broker.Endpoint(status.getData.toStringUtf8)
    broker.registerStart(broker.task.hostname)
  }

  private[kafka] def onBrokerStopped(broker: Broker, status: TaskStatus, now: Date = new Date()): Unit = {
    if (broker == null) {
      logger.info(s"Got ${status.getState} for unknown broker, ignoring it")
      return
    }

    broker.task = null
    val failed = broker.active && status.getState != TaskState.TASK_FINISHED && status.getState != TaskState.TASK_KILLED
    broker.registerStop(now, failed)

    if (failed) {
      var msg = s"Broker ${broker.id} failed ${broker.failover.failures}"
      if (broker.failover.maxTries != null) msg += "/" + broker.failover.maxTries

      if (!broker.failover.isMaxTriesExceeded) {
        msg += ", waiting " + broker.failover.currentDelay
        msg += ", next start ~ " + Repr.dateTime(broker.failover.delayExpires)
      } else {
        broker.active = false
        msg += ", failure limit exceeded"
        msg += ", deactivating broker"
      }

      logger.info(msg)
    }

    broker.metrics = null
    broker.needsRestart = false
  }

  private def isReconciling: Boolean = cluster.getBrokers.exists(b => b.task != null && b.task.reconciling)

  private[kafka] def launchTask(broker: Broker, offer: Offer): Unit = {
    broker.needsRestart = false

    val reservation = broker.getReservation(offer)
    val task_ = newTask(broker, offer, reservation)
    val id = task_.getTaskId.getValue

    val attributes = new util.LinkedHashMap[String, String]()
    for (attribute <- offer.getAttributesList)
      if (attribute.hasText) attributes.put(attribute.getName, attribute.getText.getValue)

    driver.launchTasks(util.Arrays.asList(offer.getId), util.Arrays.asList(task_))
    broker.task = new Broker.Task(id, task_.getSlaveId.getValue, task_.getExecutor.getExecutorId.getValue, offer.getHostname, attributes)

    logger.info(s"Starting broker ${broker.id}: launching task $id by offer ${offer.getHostname + Repr.id(offer.getId.getValue)}\n ${Repr.task(task_)}")
  }

  def forciblyStopBroker(broker: Broker): Unit = {
    if (driver != null && broker.task != null) {
      logger.info(s"Stopping broker ${broker.id} forcibly: sending 'stop' message")

      driver.sendFrameworkMessage(
        ExecutorID.newBuilder().setValue(broker.task.executorId).build(),
        SlaveID.newBuilder().setValue(broker.task.slaveId).build(),
        "stop".getBytes
      )
    }
  }

  private[kafka] val RECONCILE_DELAY = new Period("10s")
  private[kafka] val RECONCILE_MAX_TRIES = 3

  private[kafka] var reconciles: Int = 0
  private[kafka] var reconcileTime: Date = null

  private[kafka] def reconcileTasksIfRequired(force: Boolean = false, now: Date = new Date()): Boolean = {
    var didSomething = false
    if (reconcileTime != null && now.getTime - reconcileTime.getTime < RECONCILE_DELAY.ms)
      return false

    if (!isReconciling) reconciles = 0
    reconciles += 1
    reconcileTime = now

    if (reconciles > RECONCILE_MAX_TRIES) {
      for (broker <- cluster.getBrokers.filter(b => b.task != null && b.task.reconciling)) {
        logger.info(s"Reconciling exceeded $RECONCILE_MAX_TRIES tries for broker ${broker.id}, sending killTask for task ${broker.task.id}")
        driver.killTask(TaskID.newBuilder().setValue(broker.task.id).build())
        broker.task = null
        didSomething = true
      }

      return didSomething
    }

    val statuses = new util.ArrayList[TaskStatus]

    for (broker <- cluster.getBrokers.filter(_.task != null))
      if (force || broker.task.reconciling) {
        broker.task.state = Broker.State.RECONCILING
        logger.info(s"Reconciling $reconciles/$RECONCILE_MAX_TRIES state of broker ${broker.id}, task ${broker.task.id}")

        statuses.add(TaskStatus.newBuilder()
          .setTaskId(TaskID.newBuilder().setValue(broker.task.id))
          .setState(TaskState.TASK_STAGING)
          .build()
        )
        didSomething = true
      }

    if (force || !statuses.isEmpty)
      driver.reconcileTasks(if (force) Collections.emptyList() else statuses)

    didSomething
  }

  private def checkMesosVersion(master: MasterInfo): Unit = {
    if (master == null) return

    val minVersion: Version = new Version("0.23.0")
    var version: Version = if (master.getVersion != null) new Version(master.getVersion) else null

    if (version == null || version.compareTo(minVersion) < 0) {
      val versionStr: String = if (version == null) "?(<0.23.0)" else "" + version
      logger.fatal("Unsupported Mesos version " + versionStr + ", expected version " + minVersion + "+")
      driver.stop
    }
  }

  private[kafka] def otherTasksAttributes(name: String): util.Collection[String] = {
    def value(task: Broker.Task, name: String): String = {
      if (name == "hostname") return task.hostname
      task.attributes.get(name)
    }

    val values = new util.ArrayList[String]()
    for (broker <- cluster.getBrokers)
      if (broker.task != null) {
        val v = value(broker.task, name)
        if (v != null) values.add(v)
      }

    values
  }

  def start() {
    initLogging()
    logger.info(s"Starting ${getClass.getSimpleName}:\n$Config")

    cluster.load()
    HttpServer.start()

    val frameworkBuilder = FrameworkInfo.newBuilder()
    frameworkBuilder.setUser(if (Config.user != null) Config.user else "")
    if (cluster.frameworkId != null) frameworkBuilder.setId(FrameworkID.newBuilder().setValue(cluster.frameworkId))
    frameworkBuilder.setRole(Config.frameworkRole)

    frameworkBuilder.setName(Config.frameworkName)
    frameworkBuilder.setFailoverTimeout(Config.frameworkTimeout.ms / 1000)
    frameworkBuilder.setCheckpoint(true)

    var credsBuilder: Credential.Builder = null
    if (Config.principal != null && Config.secret != null) {
      frameworkBuilder.setPrincipal(Config.principal)

      credsBuilder = Credential.newBuilder()
      credsBuilder.setPrincipal(Config.principal)
      credsBuilder.setSecret(Config.secret)
    }

    val driver =
      if (credsBuilder != null) new MesosSchedulerDriver(Scheduler, frameworkBuilder.build, Config.master, credsBuilder.build)
      else new MesosSchedulerDriver(Scheduler, frameworkBuilder.build, Config.master)

    Runtime.getRuntime.addShutdownHook(new Thread() {
      override def run() = HttpServer.stop()
    })

    val status = if (driver.run eq Status.DRIVER_STOPPED) 0 else 1
    System.exit(status)
  }

  def stop(): Unit = {
    if (driver != null) {
      // Warning: stop(false) and stop() are dangerous, calling them will destroy the framework
      // and kill all running tasks / executors.
      driver.stop(true)
    }
  }

  def kill(): Unit = {
    System.exit(1)
  }

  private def initLogging() {
    HttpServer.initLogging()
    BasicConfigurator.resetConfiguration()

    val root = Logger.getRootLogger
    root.setLevel(Level.INFO)

    Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN)
    Logger.getLogger("org.I0Itec.zkclient").setLevel(Level.WARN)

    val logger = Logger.getLogger(Scheduler.getClass)
    logger.setLevel(if (Config.debug) Level.DEBUG else Level.INFO)

    val layout = new PatternLayout("%d [%t] %-5p %c %x - %m%n")

    var appender: Appender = null
    if (Config.log == null) appender = new ConsoleAppender(layout)
    else appender = new DailyRollingFileAppender(layout, Config.log.getPath, "'.'yyyy-MM-dd")

    root.addAppender(appender)
  }

  def requestBrokerLog(broker: Broker, name: String, lines: Int): Long = {
    var requestId: Long = -1
    if (driver != null) {
      requestId = System.currentTimeMillis()
      logs.put(requestId, None)
      val executorId = ExecutorID.newBuilder().setValue(broker.task.executorId).build()
      val slaveId = SlaveID.newBuilder().setValue(broker.task.slaveId).build()

      driver.sendFrameworkMessage(executorId, slaveId, LogRequest(requestId, lines, name).toString.getBytes)
    }
    requestId
  }

  def receivedLog(requestId: Long): Boolean = logs.get(requestId).isDefined

  def logContent(requestId: Long): String = logs.get(requestId).get

  def removeLog(requestId: Long): Option[String] = logs.remove(requestId)
}


text:
namespace tsimd {
  namespace traits {

    // Type is same (for SFINAE) //////////////////////////////////////////////

    template <typename T1, typename T2>
    using is_same_t = enable_if_t<std::is_same<T1, T2>::value>;

    template <typename T1, typename T2>
    using is_not_same_t = enable_if_t<!std::is_same<T1, T2>::value>;

  }  // namespace traits
}  // namespace tsimd


text:
<?php
declare(strict_types=1);

namespace Remp\Mailer\Models\PageMeta\Content;

use GuzzleHttp\Exception\RequestException;
use Remp\MailerModule\Models\PageMeta\Content\ContentInterface;
use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException;
use Remp\MailerModule\Models\PageMeta\Meta;
use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface;

class TyzdenContent implements ContentInterface
{
    private $transport;

    public function __construct(TransportInterface $transport)
    {
        $this->transport = $transport;
    }

    public function fetchUrlMeta(string $url): ?Meta
    {
        $url = preg_replace('/\\?ref=(.*)/', '', $url);
        try {
            $content = $this->transport->getContent($url);
            if ($content === null) {
                return null;
            }
            $meta = $this->parseMeta($content);
            if (!$meta) {
                return null;
            }
        } catch (RequestException $e) {
            throw new InvalidUrlException("Invalid URL: {$url}", 0, $e);
        }
        return $meta;
    }

    public function parseMeta(string $content): Meta
    {
        // author
        $authors = [];
        $matches = [];
        preg_match_all('/<meta name=\"author\" content=\"(.+)\">/U', $content, $matches);
        if ($matches) {
            foreach ($matches[1] as $author) {
                $authors[] = $author;
            }
        }

        // title
        $title = null;
        $matches = [];
        preg_match('/<meta property=\"og:title\" content=\"(.+)\">/U', $content, $matches);
        if ($matches) {
            $title = $matches[1];
        }

        // description
        $description = null;
        $matches = [];
        preg_match('/<meta property=\"og:description\" content=\"(.+)\">/Us', $content, $matches);
        if ($matches) {
            $description = $matches[1];
        }

        // image
        $image = null;
        $matches = [];
        preg_match('/<meta property=\"og:image\" content=\"(.+)\">/U', $content, $matches);
        if ($matches) {
            $image = $matches[1];
        }

        return new Meta($title, $description, $image, $authors);
    }
}


text:
lego_loader_with_local:
	node skottie-wasm-perf.js --canvaskit_js ../../out/canvaskit_wasm/canvaskit.js \
	--canvaskit_wasm ../../out/canvaskit_wasm/canvaskit.wasm --use_gpu \
	--input ../../modules/canvaskit/perf/assets/lego_loader.json \
	--output lego_loader_perf.json


text:
package com.yourname.flixelgame.examples.userinterface;

import org.flixel.FlxText;
import org.flixel.ui.FlxRadioButton;
import org.flixel.ui.FlxRadioButtonGroup;
import org.flixel.ui.FlxUIGroup;
import org.flixel.ui.event.IFlxRadioButtonGroup;

/**
 *
 * @author Ka Wing Chin
 */
public class RadioButtonState extends Test
{
	@Override
	public void create()
	{
		super.create();

		// The choice you picked.
		final FlxText text = new FlxText(10, 300, 200)
		.setFormat(FntRobotoRegular, 30, 0x0099CC);
		add(text);

		// Just to vertical align the buttons.
		FlxUIGroup radioButtonGroup;
		add(radioButtonGroup = new FlxUIGroup(10, 20, "RADIOBUTTONS"));
		radioButtonGroup.label.setFormat(FntRobotoRegular, 14, 0x0099CC);

		// Radiobutton group. It's mandatory.
		final FlxRadioButtonGroup radioGroup = new FlxRadioButtonGroup();
		// Fire a callback when a radiobutton changes status.
		radioGroup.onChange = new IFlxRadioButtonGroup()
		{
			@Override
			public void callback()
			{
				text.setText(radioGroup.getSelectedLabel());
			}
		};

		// Create a bunch of radios. Default will be Linux.
		radioButtonGroup.add(new FlxRadioButton(0, 0, "A", radioGroup, null, "Android"));
		radioButtonGroup.add(new FlxRadioButton(0, 0, "B", radioGroup, null, "HTML5"));
		radioButtonGroup.add(new FlxRadioButton(0, 0, "C", radioGroup, null, "iOS"));
		radioButtonGroup.add(new FlxRadioButton(0, 0, "D", radioGroup, null, "Linux"));
		radioButtonGroup.add(new FlxRadioButton(0, 0, "E", radioGroup, null, "Windows"));
		radioGroup.setCheck(3);
	}
}


text:
    Neighborhood

              Note: Race and the racial composition of the neighborhood are not appraisal factors.

              Neighborhood Characteristics

Location

                        <input type="radio" id="urban" name="NBChk1" value="urban"/>

Urban

                        <input type="radio" id="suburban" name="NBChk1" value="suburban"/>

Suburban

                        <input type="radio" id="rural" name="NBChk1" value="rural"/>

Rural

Built-Up

                        <input type="radio" name="NBChkBU" id="Over75" value="Over75" />

Over75%

                        <input type="radio" name="NBChkBU" id="25-75" value="25-75" />

25% - 75%

                        <input type="radio" name="NBChkBU" id="Under25" value="Under25" />

Under 25%

Growth

                        <input type="radio" name="NBChkGrowth" id="Rapid" value="Rapid" />

Rapid

                        <input type="radio" name="NBChkGrowth" id="Stable" value="Stable" />

Stable

                        <input type="radio" name="NBChkGrowth" id="Slow" value="Slow" />

Slow

            One-Unit Housing Trends

Property Values

                        <input type="radio" name="NBChkPTV" value="Increasing" />

Increasing

                        <input type="radio" name="NBChkPTV" value="Stable" />

Stable

                        <input type="radio" name="NBChkPTV" value="Declining" />

Declining

Demand/Supply

                        <input type="radio" name="NBChkDS" value="Shortage" />

Shortage

                        <input type="radio" name="NBChkDS" value="InBalance" />

In Balance

                        <input type="radio" name="NBChkDS" value="OverSupply" />

Over Supply

Marketing Time

                        <input type="radio" name="NBChkMT" value="Under3months" onClick="clearOUHTPMT(this);"/>

Under 3 Months

                        <input type="radio" name="NBChkMT" value="3To6Months" onClick="clearOUHTPMT(this);"	/>

3-6 Months

                        <input type="radio" name="NBChkMT" value="Over6Months" onClick="clearOUHTPMT(this);"	/>

Over 6 Months

              One-Unit Housing

Price

                    <input type="text" placeholder="$$$" id="nbPrice" />

Age

                    <input type="text" placeholder="(yrs)" id="nbYears"/>

                      <input type="radio" name="NBChkOu" value="Low" />

Low

                      <input type="radio" name="NBChkOu" value="High" />

High

                      <input type="radio" name="NBChkOu" value="Pred" />

Pred.

              Present Land Use %

                  One-Unit

                  <input type="text"  id="nbOneUnit" />

                  %

                  2-4 Unit

                  <input type="text"  id="nb2to4Unit" />

                  %

                  Multi-Family

                  <input type="text"  id="nbMultiFamily" />

                  %

                  Commercial

                  <input type="text"  id="nbCommercial" />

                  %

                  Other

                  <input type="text"  id="nbOther" />

                  %

Neighborhood Description

                <textarea id="nbDescription" placeholder="Description"></textarea>

Market Conditions (including support for the above conclusions)

                <textarea id="nbMConditions" placeholder="Description"></textarea>


text:
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace System.Html.Media.Graphics.SVG {
	[IgnoreNamespace, Imported(ObeysTypeSystem = true)]
	public partial class SVGPathSegList {
		internal SVGPathSegList() {
		}

		[IndexerName("__Item"), IntrinsicProperty]
		public SVGPathSeg this[int index] {
			get {
				return default(SVGPathSeg);
			}
		}

		public SVGPathSeg AppendItem(SVGPathSeg newItem) {
			return default(SVGPathSeg);
		}

		public void Clear() {
		}

		[EnumerateAsArray, InlineCode("new {$System.ArrayEnumerator}({this})")]
		public IEnumerator<SVGPathSeg> GetEnumerator() {
			return null;
		}

		public SVGPathSeg GetItem(int index) {
			return default(SVGPathSeg);
		}

		public SVGPathSeg Initialize(SVGPathSeg newItem) {
			return default(SVGPathSeg);
		}

		public SVGPathSeg InsertItemBefore(SVGPathSeg newItem, int index) {
			return default(SVGPathSeg);
		}

		[IntrinsicProperty]
		public int Length {
			get {
				return 0;
			}
		}

		[IntrinsicProperty]
		public int NumberOfItems {
			get {
				return 0;
			}
		}

		public SVGPathSeg RemoveItem(int index) {
			return default(SVGPathSeg);
		}

		public SVGPathSeg ReplaceItem(SVGPathSeg newItem, int index) {
			return default(SVGPathSeg);
		}
	}
}


text:
Oct11-Kata
==========

October 11, 2013 Code Kata

To Run
------

checkout

npm install

mocha test.js threeMiddleDigits.js