text:
package com.hannobraun.piccoinput

import scala.collection.immutable.HashMap
import scala.collection.immutable.Map

import org.specs.Specification
import org.specs.mock.Mockito
import org.specs.runner.JUnit4

class KeyMapTest extends JUnit4( KeyMapSpec )

object KeyMapSpec extends Specification {

	object TestPlayer extends Player

	object Key1 extends Key
	object Key2 extends Key

	val keyCode1 = 5
	val keyCode2 = 10

	"KeyMap" should {
		"have no mappings initially." in {
			val keyMap = new KeyMap

			keyMap.mappings.isEmpty must beTrue
		}

		"add a new mapping to the provided map." in {
			val keyMap = ( new KeyMap ).addMapping( TestPlayer, Key1, keyCode1 )

			val mapping = keyMap.mappings( TestPlayer )
			mapping( Key1 ) must beEqualTo( keyCode1 )
		}

		"add a new mapping to the provided map, even if there already is a mapping." in {
			val keyMap = ( new KeyMap )
					.addMapping( TestPlayer, Key1, keyCode1 )
					.addMapping( TestPlayer, Key2, keyCode2 )

			val mapping = keyMap.mappings( TestPlayer )
			mapping( Key2 ) must beEqualTo( keyCode2 )
		}

		"not overwrite the first mapping if a second one is added." in {
			val keyMap = ( new KeyMap )
					.addMapping( TestPlayer, Key1, keyCode1 )
					.addMapping( TestPlayer, Key2, keyCode2 )

			val mapping = keyMap.mappings( TestPlayer )
			mapping( Key1 ) must beEqualTo( keyCode1 )
		}
	}
}


text:
Dashboards

Power Consumption Information

Overall Performance

Total Power

{{total_power_consumption}} KWh

Cost

{{(total_power_consumption * price_per_kwh).toFixed(2)}} LKR

Device Performance

        <md-input-container>
        Devices
        <md-select data-ng-model="devices">
          <md-option ng-repeat="sm in deviceList" value="{{sm._id}}">
            {{sm.name}}
          </md-option>
        </md-select>
      </md-input-container>

   <button class="form-control btn btn-info" ng-click="getTotalPowerConsumedPerDevice(devices)">Calculate</button>

Total Power

{{power_per_device}} KWh

Cost

{{(power_per_device* price_per_kwh).toFixed(2)}} LKR

Smart Plug Performance

      <md-input-container>
        Smart Plugs
        <md-select data-ng-model="smartplugs">
          <md-option ng-repeat="sm in smartplugList" value="{{sm._id}}">
            {{sm.name}}
          </md-option>
        </md-select>
      </md-input-container>

   <button class="form-control btn btn-info" ng-click="getTotalPowerConsumedPerSmartPlug(smartplugs)">Calculate</button>

Total Power

{{power_per_smartplug}} KWh

Cost

{{(power_per_smartplug* price_per_kwh).toFixed(2)}} LKR

Search

<datepicker date-format="yyyy-MM-dd">
<input type="datetime" placeholder="Start Date" class="form-control" min-view="date" auto-close="true" date-time ng-model="start_date" view="date">
</datepicker>

     <datepicker date-format="yyyy-MM-dd">
        <input type="datetime" placeholder="End Date" class="form-control" min-view="date" auto-close="true" date-time ng-model="end_date" view="date">
        </datepicker>

        <input class="form-control" placeholder="Start Time" ui-timepicker  ng-model="start_time">

         <input class="form-control" placeholder="End Time" ui-timepicker  ng-model="end_time">

 <button class="form-control btn btn-info" type="button"
        ng-dialog="firstDialogId"
        ng-dialog-controller="DashboardsController"
        ng-dialog-data="{{jsonData1}}"
        ng-dialog-class="ngdialog-theme-default"
        ng-dialog-show-close="false">Get More Info</button>

    <button class="form-control btn btn-warning" ng-click=" getTotalPowerConsumptionFromEachDeviceByDayRange(start_date,end_date)">Filter</button>

Consumption : {{total_power_consumption_per_date_range}}

             <button class="form-control btn btn-info" type="button"
        ng-dialog="firstDialogId2"
        ng-dialog-controller="DashboardsController"
        ng-dialog-data="{{jsonData1}}"
        ng-dialog-class="ngdialog-theme-default"
        ng-dialog-show-close="false">More Info</button>

               <button class="form-control btn btn-success" type="button"
        ng-dialog="firstDialogId4"
        ng-dialog-controller="DashboardsController"

        ng-dialog-class="ngdialog-theme-default"
        ng-dialog-show-close="false">Percentage</button>

              <button class="form-control btn btn-warning" type="button"
        ng-dialog="firstDialogId5"
        ng-dialog-controller="DashboardsController"

        ng-dialog-class="ngdialog-theme-default"
        ng-dialog-show-close="false">Gauge Meter</button>

      <md-input-container>
        Devices
        <md-select data-ng-model="devices_for_time">
          <md-option ng-repeat="sm in deviceList" value="{{sm._id}}">
            {{sm.name}}
          </md-option>
        </md-select>
      </md-input-container>

<button class="form-control btn btn-info" ng-click="getActivatedTimeOfDevice(devices_for_time)">Activate Time</button>
             <button class="form-control btn btn-danger" type="button"
        ng-dialog="firstDialogId6"
        ng-dialog-controller="DashboardsController"
        ng-dialog-data="{{jsonData4}}"
        ng-dialog-class="ngdialog-theme-default"
        ng-dialog-show-close="false">Get Activation Info</button>

        <button class="form-control btn btn-success" type="button"
        ng-dialog="firstDialogId7"
        ng-dialog-controller="DashboardsController"
        ng-dialog-data="{{jsonData5}}"
        ng-dialog-class="ngdialog-theme-default"
        ng-dialog-show-close="false">Summary</button>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace AppBundle\Exception;

/**
 * Class OAuthResourceOwnerNotFoundException
 * @package AppBundle\Exception
 */
class OAuthUserResponseHandlerNotFoundException extends \Exception
{

}


text:
package designpattern.strategy;

import javakara.JavaKaraProgram;

import java.io.IOException;

public class StrategyExample extends JavaKaraProgram {
	public static void main(String[] args) throws IOException, InterruptedException {
		StrategyExample program = new StrategyExample();
		program.run("src/main/resources/world2.world");

		Strategy strat = new SnakeStrategy(program.kara);

		int c;
		while ((c = System.in.read()) != -1) {
			strat.explore();
		}
	}
}


text:
package com.mozilla.fhr.pig.eval;

import java.io.IOException;
import java.util.Map;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;

public class FingerprintTuples extends EvalFunc<DataBag> {

    private static final String APPSESSIONS_FIELD = "org.mozilla.appSessions.previous";
    private static final String PROCESS_INIT_TIME_FIELD = "main";
    private static final String FIRST_PAINT_TIME_FIELD = "firstPaint";
    private static final String SESSION_RESTORE_TIME_FIELD = "sessionRestored";

    private static final String PLACES_FIELD = "org.mozilla.places.places";
    private static final String PLACES_BOOKMARKS_FIELD = "bookmarks";
    private static final String PLACES_VISITS_FIELD = "pages";

    private static BagFactory bagFactory = BagFactory.getInstance();
    private static TupleFactory tupleFactory = TupleFactory.getInstance();

    private static int getSafeInt(Object o) {
        if (o == null) {
            return 0;
        }

        return ((Number)o).intValue();
    }

    @SuppressWarnings("unchecked")
    @Override
    public DataBag exec(Tuple input) throws IOException {

        DataBag dbag = null;

        if (input == null || input.size() == 0) {
            return null;
        }

        try {

            dbag = bagFactory.newDefaultBag();
            Map<String, Object> dataPoints = (Map<String, Object>) input.get(0);
            for (Map.Entry<String, Object> dayEntry : dataPoints.entrySet()) {

                String dayStr = dayEntry.getKey();
                Map<String, Object> dayMap = (Map<String, Object>) dayEntry.getValue();

                if (dayMap.containsKey(APPSESSIONS_FIELD) || dayMap.containsKey(PLACES_FIELD)) {

                    int bookmarkCount = 0;
                    int pagesVisitCount = 0;
                    int processInitTime = 0;
                    int startupTime = 0;
                    int sessionRestoreTime = 0;

                    // places info
                    Map<String, Object> placesMap = (Map<String, Object>) dayMap.get(PLACES_FIELD);
                    if (placesMap != null) {
                        bookmarkCount = getSafeInt(placesMap.get(PLACES_BOOKMARKS_FIELD));
                        pagesVisitCount = getSafeInt(placesMap.get(PLACES_VISITS_FIELD));
                    }

                    // sessions info
                    Map<String, Object> sessionsMap = (Map<String, Object>) dayMap.get(APPSESSIONS_FIELD);
                    if (sessionsMap != null) {
                        DataBag processInitTimesBag = (DataBag) sessionsMap.get(PROCESS_INIT_TIME_FIELD);
                        DataBag startupTimesBag = (DataBag) sessionsMap.get(FIRST_PAINT_TIME_FIELD);
                        DataBag sessionRestoreTimesBag = (DataBag) sessionsMap.get(SESSION_RESTORE_TIME_FIELD);

                        Tuple processInitTimesTuple = processInitTimesBag.iterator().next();
                        Tuple startupTimesTuple = startupTimesBag.iterator().next();
                        Tuple sessionRestoreTimesTuple = sessionRestoreTimesBag.iterator().next();

                        int startupRecordsInCurrentDay = (int) startupTimesTuple.size();

                        for (int i = 0; i < startupRecordsInCurrentDay; i++) {
                            processInitTime += ((Number) processInitTimesTuple.get(i)).intValue();
                            startupTime += ((Number) startupTimesTuple.get(i)).intValue();
                            sessionRestoreTime += ((Number) sessionRestoreTimesTuple.get(i)).intValue();
                        }
                    }

                    Tuple t = tupleFactory.newTuple(6);
                    t.set(0, dayStr);
                    t.set(1, bookmarkCount);
                    t.set(2, pagesVisitCount);
                    t.set(3, processInitTime);
                    t.set(4, startupTime);
                    t.set(5, sessionRestoreTime);
                    dbag.add(t);
                }
            }

        } catch (Exception e) {
            // ignore
        }

        return dbag;
    }
}


text:
post_title: Log Management with Splunk
menu_order: 3
---
You can pipe system and application logs from a DC/OS cluster to your existing Splunk server. This document describes how to configure a Splunk universal forwarder to send output from each node to a Splunk installation. This document does not explain how to set up and configure a Splunk server.

These instructions are based on CoreOS and might differ substantially from other Linux distributions.

**Prerequisites**

*   An existing Splunk installation that can ingest data for indexing.
*   All DC/OS nodes must be able to connect to your Splunk indexer via HTTP or HTTPS.
*   The `ulimit` of open files must be set to `unlimited` for your user with root access.

# Step 1: All nodes

For all nodes in your DC/OS cluster:

1.  Install Splunk's [universal forwarder][2].
2.  Make sure the forwarder has the credentials it needs to send data to the indexer.
3.  Start the forwarder.

# Step 2: Master nodes

For each master node in your DC/OS cluster:

1.  Create a script `$SPLUNK_HOME/bin/scripts/journald-master.sh` that will obtain the Mesos master logs from `journald`.

      **Tip:** This script can be used with DC/OS and Enterprise DC/OS. Log entries that do not apply are ignored.

        #!/bin/sh

        exec journalctl --since=now -f     \
        -u dcos-diagnostics.service        \
        -u dcos-diagnostics.socket         \
        -u dcos-adminrouter-reload.service \
        -u dcos-adminrouter-reload.timer   \
        -u dcos-adminrouter.service        \
        -u dcos-bouncer.service            \
        -u dcos-ca.service                 \
        -u dcos-cfn-signal.service         \
        -u dcos-cosmos.service             \
        -u dcos-download.service           \
        -u dcos-epmd.service               \
        -u dcos-exhibitor.service          \
        -u dcos-gen-resolvconf.service     \
        -u dcos-gen-resolvconf.timer       \
        -u dcos-history.service            \
        -u dcos-link-env.service           \
        -u dcos-logrotate-master.timer     \
        -u dcos-marathon.service           \
        -u dcos-mesos-dns.service          \
        -u dcos-mesos-master.service       \
        -u dcos-metronome.service          \
        -u dcos-minuteman.service          \
        -u dcos-navstar.service            \
        -u dcos-networking_api.service     \
        -u dcos-secrets.service            \
        -u dcos-setup.service              \
        -u dcos-signal.service             \
        -u dcos-signal.timer               \
        -u dcos-spartan-watchdog.service   \
        -u dcos-spartan-watchdog.timer     \
        -u dcos-spartan.service            \
        -u dcos-vault.service              \
        -u dcos-logrotate-master.service

2.  Make the script executable:

        chmod +x "$SPLUNK_HOME/bin/scripts/journald-master.sh"

3.  Add the script as an input to the forwarder:

        "$SPLUNK_HOME/bin/splunk" add exec \
            -source "$SPLUNK_HOME/bin/scripts/journald-master.sh" \
            -interval 0

# Step 3: Agent nodes

For each agent node in your DC/OS cluster:

1.  Create a script `$SPLUNK_HOME/bin/scripts/journald-agent.sh` that will obtain the Mesos agent logs from `journald`.

    **Tip:** This script can be used with DC/OS and Enterprise DC/OS. Log entries that do not apply are ignored.

        #!/bin/sh

            journalctl --since="now" -f              \
            -u dcos-diagnostics.service              \
            -u dcos-logrotate-agent.timer            \
            -u dcos-diagnostics.socket               \
            -u dcos-mesos-slave.service              \
            -u dcos-adminrouter-agent.service        \
            -u dcos-minuteman.service                \
            -u dcos-adminrouter-reload.service       \
            -u dcos-navstar.service                  \
            -u dcos-adminrouter-reload.timer         \
            -u dcos-rexray.service                   \
            -u dcos-cfn-signal.service               \
            -u dcos-setup.service                    \
            -u dcos-download.service                 \
            -u dcos-signal.timer                     \
            -u dcos-epmd.service                     \
            -u dcos-spartan-watchdog.service         \
            -u dcos-gen-resolvconf.service           \
            -u dcos-spartan-watchdog.timer           \
            -u dcos-gen-resolvconf.timer             \
            -u dcos-spartan.service                  \
            -u dcos-link-env.service                 \
            -u dcos-vol-discovery-priv-agent.service \
            -u dcos-logrotate-agent.service

2.  Make the script executable:

        chmod +x "$SPLUNK_HOME/bin/scripts/journald-agent.sh"

3.  Add the script as an input to the forwarder:

        "$SPLUNK_HOME/bin/splunk" add exec \
            -source "$SPLUNK_HOME/bin/scripts/journald-agent.sh" \
            -interval 0

4.  Add the task logs as inputs to the forwarder:

        "$SPLUNK_HOME/bin/splunk" add monitor '/var/lib/mesos/slave' \
            -whitelist '/stdout$|/stderr$'

# Known issue

*   The agent node Splunk forwarder configuration expects tasks to write logs to `stdout` and `stderr`. Some DC/OS services, including Cassandra and Kafka, do not write logs to `stdout` and `stderr`. If you want to log these services, you must customize your agent node Splunk forwarder configuration.

# What's next

For details on how to filter your logs with Splunk, see [Filtering logs with Splunk][3].

 [2]: http://www.splunk.com/en_us/download/universal-forwarder.html
 [3]: ../filter-splunk/


text:
layout: page
title: Packages
permalink: /packages/
showHeader: true
---

These posts will teach you how to use some of the most popular Clockwork packages:

  {% for post in site.posts %}
  {% if post.categories contains "packages" %}

            {{ post.title }}

          {{ post.date | date: "%b %-d, %Y" }}

              Tags:
                {% for category in post.categories %}
                   {{ category }}
                {% endfor %}

  {% endif %}
  {% endfor %}


text:
module Data.SBV.Examples.Uninterpreted.Shannon where

import Data.SBV

-----------------------------------------------------------------------------
-- * Boolean functions
-----------------------------------------------------------------------------

-- | A ternary boolean function
type Ternary = SBool -> SBool -> SBool -> SBool

-- | A binary boolean function
type Binary = SBool -> SBool-> SBool

-----------------------------------------------------------------------------
-- * Shannon cofactors
-----------------------------------------------------------------------------

-- | Positive Shannon cofactor of a boolean function, with
-- respect to its first argument
pos :: (SBool -> a) -> a
pos f = f true

-- | Negative Shannon cofactor of a boolean function, with
-- respect to its first argument
neg :: (SBool -> a) -> a
neg f = f false

-----------------------------------------------------------------------------
-- * Shannon expansion theorem
-----------------------------------------------------------------------------

-- | Shannon's expansion over the first argument of a function. We have:
--
-- >>> shannon
-- Q.E.D.
shannon :: IO ThmResult
shannon = prove $ \x y z -> f x y z .== (x &&& pos f y z ||| bnot x &&& neg f y z)
 where f :: Ternary
       f = uninterpret "f"

-- | Alternative form of Shannon's expansion over the first argument of a function. We have:
--
-- >>> shannon2
-- Q.E.D.
shannon2 :: IO ThmResult
shannon2 = prove $ \x y z -> f x y z .== ((x ||| neg f y z) &&& (bnot x ||| pos f y z))
 where f :: Ternary
       f = uninterpret "f"

-----------------------------------------------------------------------------
-- * Derivatives
-----------------------------------------------------------------------------

-- | Computing the derivative of a boolean function (boolean difference).
-- Defined as exclusive-or of Shannon cofactors with respect to that
-- variable.
derivative :: Ternary -> Binary
derivative f y z = pos f y z <+> neg f y z

-- | The no-wiggle theorem: If the derivative of a function with respect to
-- a variable is constant False, then that variable does not "wiggle" the
-- function; i.e., any changes to it won't affect the result of the function.
-- In fact, we have an equivalence: The variable only changes the
-- result of the function iff the derivative with respect to it is not False:
--
-- >>> noWiggle
-- Q.E.D.
noWiggle :: IO ThmResult
noWiggle = prove $ \y z -> bnot (f' y z) <=> pos f y z .== neg f y z
  where f :: Ternary
        f  = uninterpret "f"
        f' = derivative f

-----------------------------------------------------------------------------
-- * Universal quantification
-----------------------------------------------------------------------------

-- | Universal quantification of a boolean function with respect to a variable.
-- Simply defined as the conjunction of the Shannon cofactors.
universal :: Ternary -> Binary
universal f y z = pos f y z &&& neg f y z

-- | Show that universal quantification is really meaningful: That is, if the universal
-- quantification with respect to a variable is True, then both cofactors are true for
-- those arguments. Of course, this is a trivial theorem if you think about it for a
-- moment, or you can just let SBV prove it for you:
--
-- >>> univOK
-- Q.E.D.
univOK :: IO ThmResult
univOK = prove $ \y z -> f' y z ==> pos f y z &&& neg f y z
  where f :: Ternary
        f  = uninterpret "f"
        f' = universal f

-----------------------------------------------------------------------------
-- * Existential quantification
-----------------------------------------------------------------------------

-- | Existential quantification of a boolean function with respect to a variable.
-- Simply defined as the conjunction of the Shannon cofactors.
existential :: Ternary -> Binary
existential f y z = pos f y z ||| neg f y z

-- | Show that existential quantification is really meaningful: That is, if the existential
-- quantification with respect to a variable is True, then one of the cofactors must be true for
-- those arguments. Again, this is a trivial theorem if you think about it for a moment, but
-- we will just let SBV prove it:
--
-- >>> existsOK
-- Q.E.D.
existsOK :: IO ThmResult
existsOK = prove $ \y z -> f' y z ==> pos f y z ||| neg f y z
  where f :: Ternary
        f  = uninterpret "f"
        f' = existential f


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

import java.util.Map;
import java.util.Map.Entry;

import javax.xml.stream.events.XMLEvent;

import com.amazonaws.services.elasticbeanstalk.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * ConfigurationSettingsDescription StAX Unmarshaller
 */
public class ConfigurationSettingsDescriptionStaxUnmarshaller implements
        Unmarshaller<ConfigurationSettingsDescription, StaxUnmarshallerContext> {

    public ConfigurationSettingsDescription unmarshall(
            StaxUnmarshallerContext context) throws Exception {
        ConfigurationSettingsDescription configurationSettingsDescription = new ConfigurationSettingsDescription();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return configurationSettingsDescription;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("SolutionStackName", targetDepth)) {
                    configurationSettingsDescription
                            .setSolutionStackName(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("ApplicationName", targetDepth)) {
                    configurationSettingsDescription
                            .setApplicationName(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("TemplateName", targetDepth)) {
                    configurationSettingsDescription
                            .setTemplateName(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("Description", targetDepth)) {
                    configurationSettingsDescription
                            .setDescription(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("EnvironmentName", targetDepth)) {
                    configurationSettingsDescription
                            .setEnvironmentName(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DeploymentStatus", targetDepth)) {
                    configurationSettingsDescription
                            .setDeploymentStatus(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DateCreated", targetDepth)) {
                    configurationSettingsDescription
                            .setDateCreated(DateStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context.testExpression("DateUpdated", targetDepth)) {
                    configurationSettingsDescription
                            .setDateUpdated(DateStaxUnmarshaller.getInstance()
                                    .unmarshall(context));
                    continue;
                }

                if (context
                        .testExpression("OptionSettings/member", targetDepth)) {
                    configurationSettingsDescription.getOptionSettings().add(
                            ConfigurationOptionSettingStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return configurationSettingsDescription;
                }
            }
        }
    }

    private static ConfigurationSettingsDescriptionStaxUnmarshaller instance;

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


text:
<?php

class UrlTest extends TestCaseBase
{
    public function urlsParserProvider()
    {
        return [
            ['http://vimeo.com//69912181?', 'http://vimeo.com/69912181'],
            ['http://vimeo.com//69912181', 'http://vimeo.com/69912181'],
            ['http://vimeo.com/69912181', 'http://vimeo.com/69912181'],
            ['http://vimeo.com/69912181/', 'http://vimeo.com/69912181/'],
            ['https://www.tumblr.com/oembed/1.0', 'https://www.tumblr.com/oembed/1.0'],
            ['https://www.tumblr.com/oembed/1.0/', 'https://www.tumblr.com/oembed/1.0/'],
            ['https://www.tumblr.com/oembed//1.0//', 'https://www.tumblr.com/oembed/1.0/'],
            ['https://animoto.com/oembeds/create.xml?automated=true&options=start_hq', 'https://animoto.com/oembeds/create.xml?automated=true&options=start_hq'],
            ['http://static2.politico.com/dims4/default/28fb355/2147483647/resize/1160x%3E/quality/90/?url=http%3A%2F%2Fs3-origin-images.politico.com%2F2013%2F12%2F18%2F131218_george_w_bush_barack_obama_ap_60', 'http://static2.politico.com/dims4/default/28fb355/2147483647/resize/1160x%3E/quality/90/?url=http%3A%2F%2Fs3-origin-images.politico.com%2F2013%2F12%2F18%2F131218_george_w_bush_barack_obama_ap_60'],
            ['https://plus.google.com/+carlsenverlag/posts/2hibgWrmhp1', 'https://plus.google.com/+carlsenverlag/posts/2hibgWrmhp1'],
        ];
    }

    /**
     * @dataProvider urlsParserProvider
     */
    public function testParser($url, $expected_url)
    {
        $parsed_url = new Embed\Url($url);

        $this->assertSame($expected_url, $parsed_url->getUrl());
    }

    public function testDirectoryPosition()
    {
        $url = new Embed\Url('http://domain.com/first//second/third');

        $this->assertSame('first', $url->getDirectoryPosition(0));
        $this->assertSame('second', $url->getDirectoryPosition(1));
        $this->assertSame('third', $url->getDirectoryPosition(2));
        $this->assertNull($url->getDirectoryPosition(3));

        $url = $url->withDirectoryPosition(0, 'one')->withDirectoryPosition(2, 'four');

        $this->assertSame('one', $url->getDirectoryPosition(0));
        $this->assertSame('four', $url->getDirectoryPosition(2));
        $this->assertNull($url->getDirectoryPosition(3));

        $this->assertSame('http://domain.com/one/second/four', $url->getUrl());
    }

    public function testDomain()
    {
        $url = new Embed\Url('http://www.domain.com');

        $this->assertSame('domain', $url->getDomain());
        $this->assertSame('domain.com', $url->getDomain(1));

        $url = new Embed\Url('http://www.domain.co.uk');

        $this->assertSame('domain', $url->getDomain());
        $this->assertSame('domain.co.uk', $url->getDomain(1));

        $url = new Embed\Url('http://www.domain.com.au');

        $this->assertSame('domain', $url->getDomain());
        $this->assertSame('domain.com.au', $url->getDomain(1));
    }

    public function testPathsWithDots()
    {
        $url = new Embed\Url('https://en.wikipedia.org/wiki/Supernatural_(U.S._TV_series)');
        $this->assertNull($url->getExtension());
        $this->assertSame('/wiki/Supernatural_(U.S._TV_series)', $url->getPath());
        $this->assertSame('Supernatural_(U.S._TV_series)', $url->getDirectoryPosition(1));
    }
}


text:
/** @jsx React.DOM */

var assert = require('chai').assert;
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var Header = require('../../src/components/Header');

describe('Header', function () {
	before('render and locate element', function () {
		this.header = TestUtils.renderIntoDocument(<Header />);
	});

	it('should contain logo', function () {
		var logo = TestUtils.findRenderedDOMComponentWithClass(this.header, 'foo-logo');
		assert.isDefined(logo, 'logo is defined');
		assert.equal(logo.getDOMNode().textContent, 'Foobar');
	});
});


text:
package ru.maximkulikov.goodgame.api;

import java.util.EnumMap;
import java.util.Map;
import ru.maximkulikov.goodgame.api.realization.*;

/**
 * Класс, реализующий библиотеку
 *
 * @author Maxim Kulikov
 * @since 25.12.2017
 */
public class GoodGameImplementation {

    private GoodGame gg;

    private Map<GoodGame.Resources, Object> realization;

    public GoodGameImplementation(GoodGame gg) {
        this.gg = gg;
        this.realization = new EnumMap<>(GoodGame.Resources.class);
        this.realization.put(GoodGame.Resources.OAUTH, new OauthRealization(gg));
        this.realization.put(GoodGame.Resources.PLAYER, new PlayerRealization(gg));
        this.realization.put(GoodGame.Resources.STREAMS, new StreamsRealization(gg));
        this.realization.put(GoodGame.Resources.CHANNELS, new ChannelsRealization(gg));
        this.realization.put(GoodGame.Resources.CHAT, new ChatRealization(gg));
        this.realization.put(GoodGame.Resources.GAMES, new GamesRealization(gg));
        this.realization.put(GoodGame.Resources.INFO, new InfoRealization(gg));
        this.realization.put(GoodGame.Resources.SMILES, new SmilesRealization(gg));
        this.realization.put(GoodGame.Resources.GITHUBAPI, new GithubRealization(gg));
        this.realization.put(GoodGame.Resources.AJAX, new AjaxRealization(gg));
    }

    public final AjaxRealization ajax() {
        return (AjaxRealization) realization.get(GoodGame.Resources.AJAX);
    }

    public final ChannelsRealization channels() {
        return (ChannelsRealization) realization.get(GoodGame.Resources.CHANNELS);
    }

    public final ChatRealization chat() {
        return (ChatRealization) realization.get(GoodGame.Resources.CHAT);
    }

    public final GamesRealization games() {
        return (GamesRealization) realization.get(GoodGame.Resources.GAMES);
    }

    public final GithubRealization github() {
        return (GithubRealization) realization.get(GoodGame.Resources.GITHUBAPI);
    }

    public final InfoRealization info() {
        return (InfoRealization) realization.get(GoodGame.Resources.INFO);
    }

    public final OauthRealization oauth() {
        return (OauthRealization) realization.get(GoodGame.Resources.OAUTH);
    }

    public final PlayerRealization player() {
        return (PlayerRealization) realization.get(GoodGame.Resources.PLAYER);
    }

    public final SmilesRealization smiles() {
        return (SmilesRealization) realization.get(GoodGame.Resources.SMILES);
    }

    public final StreamsRealization streams() {
        return (StreamsRealization) realization.get(GoodGame.Resources.STREAMS);
    }
}


text:
<?php

use DI\ContainerBuilder;

echo call_user_func(require 'vendor/autoload.php', function(SplFileInfo $file, ContainerBuilder $builder) {
    return get_class($builder);
});


text:
package middleware

import (
	"net/http"

	"github.com/m3db/m3/src/x/instrument"
	"github.com/m3db/m3/src/x/net/http/cors"

	"github.com/gorilla/mux"
	"github.com/jonboulle/clockwork"
	"github.com/opentracing/opentracing-go"
	"github.com/prometheus/prometheus/util/httputil"
)

// Register is a func to build the set of middleware functions.
type Register func(opts Options) []mux.MiddlewareFunc

// Options is the set of parameters passed to the Register function.
type Options struct {
	// Common options for all middleware functions.
	InstrumentOpts instrument.Options
	Clock          clockwork.Clock
	Route          *mux.Route

	// Specific options for middleware functions.
	Logging                LoggingOptions
	Metrics                MetricsOptions
	Source                 SourceOptions
	PrometheusRangeRewrite PrometheusRangeRewriteOptions
}

// OverrideOptions is a function that returns new Options from the provided Options.
type OverrideOptions func(opts Options) Options

// Default is the default list of middleware functions applied if no middleware functions are set in the
// HandlerOptions.
func Default(opts Options) []mux.MiddlewareFunc {
	// The order of middleware is important. Be very careful when reordering existing middleware.
	return []mux.MiddlewareFunc{
		Cors(),
		// install tracing before logging so the trace_id is available for response logging.
		Tracing(opentracing.GlobalTracer(), opts.InstrumentOpts),
		// install source before logging so the source is available for response logging.
		Source(opts),
		RequestID(opts.InstrumentOpts),
		PrometheusRangeRewrite(opts),
		ResponseLogging(opts),
		ResponseMetrics(opts),
		// install panic handler after any middleware that adds extra useful information to the context logger.
		Panic(opts.InstrumentOpts),
		Compression(),
	}
}

// Cors adds CORS headers will be added to all responses.
func Cors() mux.MiddlewareFunc {
	return func(base http.Handler) http.Handler {
		return &cors.Handler{
			Handler: base,
			Info: &cors.Info{
				"*": true,
			},
		}
	}
}

// Compression adds suitable response compression based on the client's Accept-Encoding headers.
func Compression() mux.MiddlewareFunc {
	return func(base http.Handler) http.Handler {
		return httputil.CompressionHandler{
			Handler: base,
		}
	}
}


text:
from setuptools import setup

NAME = 'kfp-arena'
VERSION = '0.6'

REQUIRES = ['kfp >= 0.1']

setup(
    name=NAME,
    version=VERSION,
    description='KubeFlow Pipelines Extended Arena SDK',
    author='cheyang',
    author_email="cheyang@163.com",
    install_requires=REQUIRES,
    packages=[
      'arena',
    ],
    classifiers=[
      'Intended Audience :: Developers',
      'Intended Audience :: Education',
      'Intended Audience :: Science/Research',
      'License :: OSI Approved :: Apache Software License',
      'Programming Language :: Python :: 3',
      'Programming Language :: Python :: 3.5',
      'Programming Language :: Python :: 3.6',
      'Programming Language :: Python :: 3.7',
      'Topic :: Scientific/Engineering',
      'Topic :: Scientific/Engineering :: Artificial Intelligence',
      'Topic :: Software Development',
      'Topic :: Software Development :: Libraries',
      'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    python_requires='>=3.5.3',
    include_package_data=True
)


text:
package lib.folderpicker;

import java.util.Comparator;

/**
 * Created by Kashif on 4/7/2018.
 */

public class FilePojo {

    private String name;
    private boolean folder;

    public FilePojo(String name, boolean folder){
        this.name = name;
        this.folder = folder;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isFolder() {
        return folder;
    }

    public void setFolder(boolean folder) {
        this.folder = folder;
    }

}


text:
namespace Microsoft.CodeDom
{
    using System.Diagnostics;
    using System;
    using Microsoft.Win32;
    using System.Collections;
    using System.Runtime.InteropServices;

    /// <devdoc>
    ///    <para> Represents a comment.</para>
    /// </devdoc>
    [
        //  ClassInterface(ClassInterfaceType.AutoDispatch),
        ComVisible(true),
    // Serializable,
    ]
    public class CodeCommentStatement : CodeStatement
    {
        private CodeComment _comment;

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='Microsoft.CodeDom.CodeCommentStatement'/>.
        ///    </para>
        /// </devdoc>
        public CodeCommentStatement()
        {
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public CodeCommentStatement(CodeComment comment)
        {
            _comment = comment;
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='Microsoft.CodeDom.CodeCommentStatement'/> with the specified text as
        ///       contents.
        ///    </para>
        /// </devdoc>
        public CodeCommentStatement(string text)
        {
            _comment = new CodeComment(text);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public CodeCommentStatement(string text, bool docComment)
        {
            _comment = new CodeComment(text, docComment);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public CodeComment Comment
        {
            get
            {
                return _comment;
            }
            set
            {
                _comment = value;
            }
        }
    }
}


text:
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using nClam;

class Program
{
  static async Task Main(string[] args)
  {
    Console.WriteLine("nClam Test Application");
    Console.WriteLine();

    Console.Write("\t* Testing connectivity: ");

    var clam = new ClamClient("localhost", 3310);
    var pingResult = await clam.TryPingAsync();

    if (!pingResult)
    {
      Console.WriteLine("test failed. Exiting.");
      return;
    }

    Console.WriteLine("connected.");

    Console.Write("\t* Scanning file: ");
    var scanResult = await clam.ScanFileOnServerAsync("C:\\test.txt");  //any file you would like!

    switch (scanResult.Result)
    {
      case ClamScanResults.Clean:
        Console.WriteLine("The file is clean!");
        break;
      case ClamScanResults.VirusDetected:
        Console.WriteLine("Virus Found!");
        Console.WriteLine("Virus name: {0}", scanResult.InfectedFiles.First().VirusName);
        break;
      case ClamScanResults.Error:
        Console.WriteLine("Woah an error occured! Error: {0}", scanResult.RawResult);
        break;
    }

  }
}


text:
module ROM
  class ClassBuilder
    include Options

    option :name, type: String, reader: true
    option :parent, type: Class, reader: true, parent: Object

    def call
      klass = Class.new(parent)

      klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
        def self.name
          #{name.inspect}
        end

        def self.inspect
          name
        end

        def self.to_s
          name
        end
      RUBY

      yield(klass) if block_given?

      klass
    end
  end
end


text:
package reborncore.common.fluid.container;

import net.minecraft.fluid.Fluid;
import net.minecraft.item.ItemStack;
import reborncore.common.fluid.FluidValue;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/*

	* Based of Slilk's API but with some breaking changes

	* Direction has been replaced with a generic type, this allows for things like ItemStack to be easily passed along
	* Some methods such as getCapacity have been tweaked to also provide the type
	* Some methods have got default implementations making it a lot easier to implement without the worry for bugs
	* The multiple fluids thing has gone, it is still possible to one fluid per side if wanted as the type is passed around everywhere
	* A lot of the "helper" methods have been removed, these should really go in boilerplate classes and not the in raw api
	* removed the docs as cba to write them

 */
public interface GenericFluidContainer<T> {

	@Nullable
	static GenericFluidContainer<ItemStack> fromStack(@Nonnull ItemStack itemStack){
		if(itemStack.getItem() instanceof GenericFluidContainer){
			//noinspection unchecked
			return (GenericFluidContainer<ItemStack>) itemStack.getItem();
		}
		return null;
	}

	void setFluid(T type, @Nonnull FluidInstance instance);

	@Nonnull
	FluidInstance getFluidInstance(T type);

	FluidValue getCapacity(T type);

	default boolean canHold(T type, Fluid fluid){
		return true;
	}

	default FluidValue getCurrentFluidAmount(T type) {
		return getFluidInstance(type).getAmount();
	}

	default boolean canInsertFluid(T type, @Nonnull Fluid fluid, FluidValue amount){
		if(!canHold(type, fluid)){
			return false;
		}
		FluidInstance currentFluid = getFluidInstance(type);
		return currentFluid.isEmpty() || currentFluid.getFluid() == fluid && currentFluid.getAmount().add(amount).lessThan(getCapacity(type));
	}

	default boolean canExtractFluid(T type, @Nonnull Fluid fluid, FluidValue amount){
		return getFluidInstance(type).getFluid() == fluid && amount.lessThanOrEqual(getFluidInstance(type).getAmount());
	}

	default void insertFluid(T type, @Nonnull Fluid fluid, FluidValue amount){
		if(canInsertFluid(type, fluid, amount)){
			setFluid(type, getFluidInstance(type).addAmount(amount));
		}
	}

	default void extractFluid(T type, @Nonnull Fluid fluid, FluidValue amount){
		if(canExtractFluid(type, fluid, amount)){
			setFluid(type, getFluidInstance(type).subtractAmount(amount));
		}
	}

}


text:
<?php
/**
 *
 * Fixes for aliasing to legacy syntaxes.
 *
 */
namespace CssCrush;

class PostAliasFix
{
    public static $functions = [];

    public static function add($alias_type, $key, $callback)
    {
        if ($alias_type === 'function') {
            self::$functions[$key] = $callback;
        }
    }

    public static function remove($alias_type, $key)
    {
        if ($alias_type === 'function') {
            unset(self::$functions[$key]);
        }
    }
}


text:
package org.pmiops.workbench.notebooks;

import static com.google.common.truth.Truth.assertThat;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public class NotebookLockingUtilsTest {
  private static Stream<Arguments> notebookLockingCases() {
    return Stream.of(
        Arguments.of(
            "fc-bucket-id-1",
            "user@aou",
            "dc5acd54f734a2e2350f2adcb0a25a4d1978b45013b76d6bc0a2d37d035292fe"),
        Arguments.of(
            "fc-bucket-id-1",
            "another-user@aou",
            "bc90f9f740702e5e0408f2ea13fed9457a7ee9c01117820f5c541067064468c3"),
        Arguments.of(
            "fc-bucket-id-2",
            "user@aou",
            "a759e5aef091fd22bbf40bf8ee7cfde4988c668541c18633bd79ab84b274d622"),
        // catches an edge case where the hash has a leading 0
        Arguments.of(
            "fc-5ac6bde3-f225-44ca-ad4d-92eed68df7db",
            "brubenst2@fake-research-aou.org",
            "060c0b2ef2385804b7b69a4b4477dd9661be35db270c940525c2282d081aef56"));
  }

  @ParameterizedTest
  @MethodSource("notebookLockingCases")
  public void testNotebookLockingEmailHash(String bucket, String email, String hash) {
    assertThat(NotebookLockingUtils.notebookLockingEmailHash(bucket, email)).isEqualTo(hash);
  }
}


text:
namespace atom {

using JavaScriptHandler =
    base::Callback<void(const net::URLRequest*, v8::Local<v8::Value>)>;

namespace internal {

using BeforeStartCallback =
    base::Callback<void(v8::Isolate*, v8::Local<v8::Value>)>;
using ResponseCallback =
    base::Callback<void(bool, std::unique_ptr<base::Value> options)>;

// Ask handler for options in UI thread.
void AskForOptions(v8::Isolate* isolate,
                   const JavaScriptHandler& handler,
                   net::URLRequest* request,
                   const BeforeStartCallback& before_start,
                   const ResponseCallback& callback);

// Test whether the |options| means an error.
bool IsErrorOptions(base::Value* value, int* error);

}  // namespace internal

template<typename RequestJob>
class JsAsker : public RequestJob {
 public:
  JsAsker(net::URLRequest* request, net::NetworkDelegate* network_delegate)
      : RequestJob(request, network_delegate), weak_factory_(this) {}

  // Called by |CustomProtocolHandler| to store handler related information.
  void SetHandlerInfo(
      v8::Isolate* isolate,
      net::URLRequestContextGetter* request_context_getter,
      const JavaScriptHandler& handler) {
    isolate_ = isolate;
    request_context_getter_ = request_context_getter;
    handler_ = handler;
  }

  // Subclass should do initailze work here.
  virtual void BeforeStartInUI(v8::Isolate*, v8::Local<v8::Value>) {}
  virtual void StartAsync(std::unique_ptr<base::Value> options) = 0;

  net::URLRequestContextGetter* request_context_getter() const {
    return request_context_getter_;
  }

 private:
  // RequestJob:
  void Start() override {
    content::BrowserThread::PostTask(
        content::BrowserThread::UI, FROM_HERE,
        base::Bind(&internal::AskForOptions,
                   isolate_,
                   handler_,
                   RequestJob::request(),
                   base::Bind(&JsAsker::BeforeStartInUI,
                              weak_factory_.GetWeakPtr()),
                   base::Bind(&JsAsker::OnResponse,
                              weak_factory_.GetWeakPtr())));
  }
  void GetResponseInfo(net::HttpResponseInfo* info) override {
    info->headers = new net::HttpResponseHeaders("");
  }

  // Called when the JS handler has sent the response, we need to decide whether
  // to start, or fail the job.
  void OnResponse(bool success, std::unique_ptr<base::Value> value) {
    int error = net::ERR_NOT_IMPLEMENTED;
    if (success && value && !internal::IsErrorOptions(value.get(), &error)) {
      StartAsync(std::move(value));
    } else {
      RequestJob::NotifyStartError(
          net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
    }
  }

  v8::Isolate* isolate_;
  net::URLRequestContextGetter* request_context_getter_;
  JavaScriptHandler handler_;

  base::WeakPtrFactory<JsAsker> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(JsAsker);
};

}  // namespace atom

#endif  // ATOM_BROWSER_NET_JS_ASKER_H_


text:
$(function(){

  // home page signup button
  $('#signup-btn').on('click', function(e){
    e.preventDefault();

    // store the signup data
    var newUserData = $('#signup-form');

    if (validateForm(newUserData.val()) !== true) {
        $("#err").modal("show");
        $('#err .modal-body').text('Please enter a valid email address.');
    } else {

      $.ajax({
        type: "POST",
        dataType: "json",
        url: $SCRIPT_ROOT + '/create',
        data: newUserData.serialize()
      }).done(function(data) {
          if(data.errors) {
              $("#err").modal("show");
              $("#err .modal-body").text(data["errors"]);
          } else {
            $("#intro").modal("show");
            $('#intro .modal-body').text(data["email"] + " has been signed up for InboxNuke. Once the request is processed, this email address will start receiving extremely large amounts of email newsletters.");
          }

      });
    }
  });

  function validateForm(email) {
    console.log(email);
    var atpos=email.indexOf("@");
    var dotpos=email.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
      return false;
    } else {
      return true;
    }
  }

});


text:
'use strict'
const Router = require('koa-router')

const { blogListController } = require('../controllers')

module.exports = prefix => {

  /**
   * blog article list
   */
  const api = new Router({ prefix })

  api.get('/blog/list', blogListController.getArticleList)

  /**
   * restful API format
   */
  api.use(require('../middlewares/middlewares.restfulAPI.response.js')())

  return api

}


text:
require_relative "cartmans_essay.md"

# 1. What is the line number where the error occurs?
#    155
# 2. What is the type of error message?
#    LoadError
# 3. What additional information does the interpreter provide about this type of error?
#    cannot load such file
# 4. Where is the error in the code?
#    The require relative method
# 5. Why did the interpreter give you this error?
#    The relative file cannot be found because it doesnt exist.

# --- REFLECTION -------------------------------------------------------
# Write your reflection below as a comment.

# Which error was the most difficult to read?
#   The first error threw me off because it referneced line 170 which was nowhere near the code itself.

# How did you figure out what the issue with the error was?
#   The expecting keyword_end clued me in to the fact that Ruby was trying to find an "end" to the method which was why it searched all the way to the end of the file.

# Were you able to determine why each error message happened based on the code?
#   Yes, the error types and messages are helpful in indicating what to look for and where.

# When you encounter errors in your future code, what process will you follow to help you debug?
#   First, I will look to the line that is indicated and if applicable, the ^ symbol which shows exactly where the error occured. Next, I will refer to the error type and the message to try and find what the problem is. If none of those works, I can google the particular error to see if I can find exactly why it happened.


text:
"""Defines the models.

The base of the network is a vision model that embeds an
RGB image to a flat vector which serves as a visual description.

The head of the network turns the visual description into a pose.  It must have
a method to compute the loss and to predict a pose given a visual description
vector.  For the implicit function based approach, the random sampling is all
contained within the class definition.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import re

from absl import logging
import numpy as np
import tensorflow as tf
import tensorflow_graphics.geometry.transformation as tfg

tfkl = tf.keras.layers
eps = 1e-9

def create_vision_model(image_dims=(224, 224, 3), weights='imagenet'):
  """Loads a pre-trained resnet for the vision model.

  Args:
    image_dims: The input shape.
    weights: Source of weights to be loaded.

  Returns:
    The vision model and the length of the visual description vector.
  """
  base_model = tf.keras.applications.ResNet50V2(
      weights=weights, include_top=False, input_shape=image_dims)
  inp = tf.keras.layers.Input(shape=image_dims)
  x = base_model(inp)
  x = tfkl.GlobalAveragePooling2D()(x)
  len_visual_description = x.shape[-1]
  vision_model = tf.keras.Model(inp, x)
  return vision_model, len_visual_description

class ImplicitSO3(tfkl.Layer):
  """Represents a distribution over SO(3) as an implicit function.

  Specifically, this is a fully connected network which takes as input
  a visual description vector and a query rotation, and outputs
  a single scalar which can be converted to a log likelihood via normalization.
  By querying many values we can build up a probability distribution over SO(3).

  The query format is a 3x3 rotation matrix, flattened and then positionally
  encoded in each component with multiple frequencies of sinusoids.

  Init args:
    len_visual_description: The length of the visual description vector, which
      is returned with the vision model at creation.
    number_fourier_components: The number of positional encoding frequencies for
      the rotation query.  If zero, positional encoding is not used.
    mlp_layer_sizes: A list of the number of units in each layer of the MLP.
    so3_sampling_mode: 'random' or 'grid'.  This is only efficacious during
     training, and determines how the normalization is computed.  'random'
     corresponds to sampling uniformly over the space of rotations, which is
     simple and less constrained but results in inexact normalization.  'grid'
     uses equivolumetric grids generated using healpix as a starting point.
     These grids are stored so each size only needs to be computed once per run.
    number_train_queries: The number of queries to use during training, which
      populate SO(3) to approximate the normalization of the likelihoods.  If
      so3_sampling_mode is 'grid', the nearest grid size in log space is used.
    number_eval_queries: The number of queries to use during evaluation, which
      is always a grid sampling (for proper normalization).

  """

  def __init__(self, len_visual_description,
               number_fourier_components, mlp_layer_sizes,
               so3_sampling_mode, number_train_queries,
               number_eval_queries, **kwargs):
    super().__init__(**kwargs)
    self.len_visual_description = len_visual_description
    # Rotations are represented as flattened 3x3 orthonormal matrices.
    self.len_rotation = 9
    self.number_fourier_components = number_fourier_components
    self.frequencies = tf.range(number_fourier_components, dtype=tf.float32)
    self.frequencies = tf.math.pow(2., self.frequencies)
    self.so3_sampling_mode = so3_sampling_mode
    self.number_train_queries = number_train_queries
    self.number_eval_queries = number_eval_queries
    if number_fourier_components == 0:
      self.len_query = self.len_rotation
    else:
      self.len_query = self.len_rotation * number_fourier_components * 2

    self.grids = {}

    # The grids will be populated on-demand.
    if self.so3_sampling_mode == 'grid':
      self.get_closest_available_grid(self.number_train_queries)
    self.get_closest_available_grid(self.number_eval_queries)

    input_visual = tfkl.Input(shape=(len_visual_description,))
    visual_embedding = tfkl.Dense(mlp_layer_sizes[0])(input_visual)
    input_query = tfkl.Input(shape=(None, self.len_query,))
    query_embedding = tfkl.Dense(mlp_layer_sizes[0])(input_query)

    # Broadcast sum to combine inputs.
    output = visual_embedding[:, tf.newaxis] + query_embedding

    output = tfkl.ReLU()(output)

    for num_units in mlp_layer_sizes[1:]:
      output = tfkl.Dense(num_units, 'relu')(output)
    output = tfkl.Dense(1)(output)
    self.implicit_model = tf.keras.models.Model(
        inputs=[input_visual, input_query],
        outputs=output)
    self.mlp_layer_sizes = mlp_layer_sizes

  def get_config(self):
    """For saving purposes."""
    config = super().get_config().copy()
    config.update({
        'len_visual_description': self.len_visual_description,
        'number_fourier_components': self.number_fourier_components,
        'mlp_layer_sizes': self.mlp_layer_sizes,
        'so3_sampling_mode': self.so3_sampling_mode,
        'number_train_queries': self.number_train_queries,
        'number_eval_queries': self.number_eval_queries,
    })
    return config

  def call(self, inp):
    return self.implicit_model(inp)

  def predict_probability(self, vision_description, rotation_matrix,
                          training=False):
    """Predict the probability of the rotation, given the vision description.

    Rotate the grids to make sure they contain the rotation matrix. It requires
    different queries per element in the batch, increasing the # of ops in the
    first MLP layer.

    Args:
      vision_description: The feature vectors of the batch of images.
      rotation_matrix: The query rotation matrices.
      training: True or False; determines how many queries to use for
        normalization and whether to use an equivolumetric grid.

    Returns:
      The probability density at the rotation given by rotation_matrix.
    """
    if training:
      query_rotations = self.generate_queries(
          self.number_train_queries, mode=self.so3_sampling_mode)
    else:
      query_rotations = self.generate_queries(
          self.number_eval_queries, mode='grid')
    delta_rot = tf.transpose(query_rotations[-1]) @ rotation_matrix
    query_rotations = tf.einsum('aij,bjk->baik', query_rotations, delta_rot)
    shape = query_rotations.shape
    query_rotations = tf.reshape(query_rotations,
                                 [shape[0], shape[1], self.len_rotation])
    query_rotations = self.positional_encoding(query_rotations)
    logits = self.implicit_model([vision_description, query_rotations],
                                 training=training)[Ellipsis, 0]

    probabilities = tf.nn.softmax(logits, axis=-1)
    # Scale by the volume per grid point.
    probabilities *= query_rotations.shape[1] / np.pi**2
    # The final query rotation is the rotation we care about.
    return probabilities[:, -1]

  def predict_rotation(self, vision_descriptions, gradient_ascent=False):
    """Returns a predicted rotation given the vision description.

    The mode of the distribution is approximated, found either as the argmax
    over a set of samples, or by running gradient ascent on the probability with
    the sample argmax as the starting point.

    Args:
      vision_descriptions: The feature vectors for the images on which to run
        pose estimation.
      gradient_ascent: True or False; whether to perform gradient ascent after
        finding the argmax over the sample rotations, to squeeze out a little
        more performance.

    Returns:
      A tensor of rotations, shape [N, 3, 3] where N is the number of vision
      descriptions.
    """
    query_rotations = self.generate_queries(self.number_eval_queries,
                                            mode='grid')
    query_rotations_inp = tf.reshape(query_rotations, [-1, self.len_rotation])
    query_rotations_inp = self.positional_encoding(query_rotations_inp)
    logits = self.implicit_model([vision_descriptions, query_rotations_inp],
                                 training=False)[Ellipsis, 0]

    max_inds = tf.argmax(logits, axis=-1)
    max_rotations = tf.gather(query_rotations, max_inds)

    if not gradient_ascent:
      max_rotations = tf.reshape(max_rotations, [-1, 3, 3])
      return max_rotations

    # Perform gradient ascent, using the argmax rotations as starting seeds.
    # These parameters were found to work well for the scenarios tested, but
    # other cases may benefit from tuning these.
    update_step_size = 1e-4
    number_optimization_steps = 100
    # Convert to quaternions to enforce normalization.
    query_quaternions = tfg.quaternion.from_rotation_matrix(max_rotations)
    query_quaternions = tf.Variable(query_quaternions, trainable=True)

    @tf.function
    def gradient_ascent_step(query_quaternions):
      with tf.GradientTape() as tape:
        query_rotations_inp = tfg.rotation_matrix_3d.from_quaternion(
            query_quaternions)
        query_rotations_inp = tf.reshape(query_rotations_inp,
                                         [-1, self.len_rotation])
        query_rotations_inp = self.positional_encoding(query_rotations_inp)
        logits = self.implicit_model([vision_descriptions, query_rotations_inp],
                                     training=False)
        logits = tf.linalg.diag_part(logits[Ellipsis, 0])
        # Maximize the network output without caring about normalization
        loss = -tf.reduce_mean(logits)
      grads = tape.gradient(loss, query_quaternions)
      query_quaternions.assign_add(-grads * update_step_size)
      query_quaternions.assign(tfg.quaternion.normalize(query_quaternions))
      return

    for _ in range(number_optimization_steps):
      gradient_ascent_step(query_quaternions)
    max_rotations = tfg.rotation_matrix_3d.from_quaternion(query_quaternions)
    return max_rotations

  def compute_loss(self, vision_description, rotation_matrix_gt):
    """Return the negative log likelihood of the ground truth rotation matrix.

    Args:
      vision_description: The vector representations of a batch of images.
      rotation_matrix_gt: The ground truth rotation matrices associated with the
        batch of images.

    Returns:
      A scalar, the loss of the batch.
    """
    probs = self.predict_probability(
        vision_description, rotation_matrix_gt, training=True)
    loss = -tf.reduce_mean(tf.math.log(probs))
    return loss

  def get_closest_available_grid(self, number_queries=None):
    if not number_queries:
      number_queries = self.number_eval_queries
    # HEALPix-SO(3) is defined only on 72 * 8^N points; we find the closest
    # valid grid size (in log space) to the requested size.
    # The largest grid size we consider has 19M points.
    grid_sizes = 72*8**np.arange(7)
    size = grid_sizes[
        np.argmin(np.abs(np.log(number_queries) - np.log(grid_sizes)))
        ]
    if self.grids.get(size) is not None:
      return self.grids[size]
    else:
      logging.info('Using grid of size %d. Requested was %d.', size,
                   number_queries)
      grid_created = False

      if not grid_created:
        self.grids[size] = np.float32(generate_healpix_grid(size=size))

      return self.grids[size]

  def generate_queries(self, number_queries, mode='random'):
    """Generate query rotations from SO(3).

    Args:
      number_queries: The number of queries.
      mode: 'random' or 'grid'; determines whether to generate rotations from
        the uniform distribution over SO(3), or use an equivolumetric grid.

    Returns:
      A tensor of rotation matrices, shape [num_queries, 3, 3].
    """
    if mode == 'random':
      return self.generate_queries_random(number_queries)
    elif mode == 'grid':
      return self.get_closest_available_grid(number_queries)

  def generate_queries_random(self, number_queries):
    """Generate rotation matrices from SO(3) uniformly at random.

    Args:
      number_queries: The number of queries.
    Returns:
      A tensor of shape [number_queries, 3, 3].
    """
    random_quaternions = tfg.quaternion.normalized_random_uniform(
        (number_queries,))
    random_rotations = tfg.rotation_matrix_3d.from_quaternion(
        random_quaternions)
    random_rotations = tf.cast(random_rotations, tf.float32)
    return random_rotations

  def positional_encoding(self, query_rotations):
    """This handles the positional encoding.

    Args:
      query_rotations: tensor of shape [N, len_rotation] or
        [bs, N, len_rotation].

    Returns:
      Tensor of shape [N, len_query] or [bs, N, len_query].
    """
    if self.frequencies.shape[0] == 0:
      return query_rotations

    def _enc(freq):
      return tf.concat(
          [tf.math.sin(query_rotations * freq),
           tf.math.cos(query_rotations * freq)], -1)
    query_rotations = tf.map_fn(_enc, self.frequencies)
    query_shape = tf.shape(query_rotations)
    if len(query_shape) == 4:
      query_rotations = tf.transpose(query_rotations, [1, 2, 0, 3])
      shape = tf.concat([query_shape[1:3], [self.len_query]], axis=0)
      query_rotations = tf.reshape(query_rotations, shape)
    else:
      query_rotations = tf.transpose(query_rotations, [1, 0, 2])
      query_rotations = tf.reshape(query_rotations, [-1, self.len_query])
    return query_rotations

  def output_pdf(self, vision_description, num_queries=None,
                 query_rotations=None):
    """Returns a normalized distribution over pose, given a vision description.

    Args:
      vision_description: A batch of feature vectors, representing the images on
        which to estimate the pose.
      num_queries: The number of queries to evaluate the probability for.
      query_rotations: If supplied, these rotations will be used to evaluate the
        distribution and normalize it, instead using the kwarg num_queries.
    Returns:
      Both the rotations and their corresponding probabilities.
    """

    if num_queries is None:
      num_queries = self.number_eval_queries
    if query_rotations is None:
      query_rotations = self.get_closest_available_grid(num_queries)

    query_rotations_enc = tf.reshape(query_rotations, [-1, self.len_rotation])
    query_rotations_enc = self.positional_encoding(query_rotations_enc)
    log_probabilities = self.implicit_model(
        [vision_description, query_rotations_enc], training=False)[Ellipsis, 0]
    probabilities = tf.nn.softmax(log_probabilities, axis=-1)
    return query_rotations, probabilities

def generate_healpix_grid(recursion_level=None, size=None):
  """Generates an equivolumetric grid on SO(3) following Yershova et al. (2010).

  Uses a Healpix grid on the 2-sphere as a starting point and then tiles it
  along the 'tilt' direction 6*2**recursion_level times over 2pi.

  Args:
    recursion_level: An integer which determines the level of resolution of the
      grid.  The final number of points will be 72*8**recursion_level.  A
      recursion_level of 2 (4k points) was used for training and 5 (2.4M points)
      for evaluation.
    size: A number of rotations to be included in the grid.  The nearest grid
      size in log space is returned.

  Returns:
    (N, 3, 3) array of rotation matrices, where N=72*8**recursion_level.
  """
  import healpy as hp  # pylint: disable=g-import-not-at-top

  assert not(recursion_level is None and size is None)
  if size:
    recursion_level = max(int(np.round(np.log(size/72.)/np.log(8.))), 0)
  number_per_side = 2**recursion_level
  number_pix = hp.nside2npix(number_per_side)
  s2_points = hp.pix2vec(number_per_side, np.arange(number_pix))
  s2_points = np.stack([*s2_points], 1)

  # Take these points on the sphere and
  azimuths = np.arctan2(s2_points[:, 1], s2_points[:, 0])
  tilts = np.linspace(0, 2*np.pi, 6*2**recursion_level, endpoint=False)
  polars = np.arccos(s2_points[:, 2])
  grid_rots_mats = []
  for tilt in tilts:
    # Build up the rotations from Euler angles, zyz format
    rot_mats = tfg.rotation_matrix_3d.from_euler(
        np.stack([azimuths,
                  np.zeros(number_pix),
                  np.zeros(number_pix)], 1))
    rot_mats = rot_mats @ tfg.rotation_matrix_3d.from_euler(
        np.stack([np.zeros(number_pix),
                  np.zeros(number_pix),
                  polars], 1))
    rot_mats = rot_mats @ tf.expand_dims(
        tfg.rotation_matrix_3d.from_euler([tilt, 0., 0.]), 0)
    grid_rots_mats.append(rot_mats)

  grid_rots_mats = np.concatenate(grid_rots_mats, 0)
  return grid_rots_mats


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

    (c) 2004 Scorpio Software
        19 Wittama Drive
        Glenmore Park
        Sydney NSW 2745
        Australia

-----------------------------------------------------------------------------

    $Workfile::                                                           $
    $Revision::                                                           $
        $Date::                                                           $
      $Author::                                                           $

---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#ifndef ZXVic20HiresPaletteH
#define ZXVic20HiresPaletteH
//---------------------------------------------------------------------------
#include "..\ZXPalette.h"
#include "..\ZXImage.h"
//---------------------------------------------------------------------------
namespace Scorpio
{
    //using namespace Imaging;
    namespace Vic20HiresPalette
    {
        //---------------------------------------------------------------------------
        class ZXVic20HiresPalette : public ZXPalette
        {
        private:
                    unsigned char       m_iInk;
                    unsigned char       m_iPaper;

                    void    __fastcall  Initialize(void);
                    void    __fastcall  SetPixel(int iX, int iY, unsigned char iInk, bool bSet, ZXImage& Image);
                    void    __fastcall  SetPixel(int iX, int iY, unsigned char PixelByte, ZXImage* Image);
                    void    __fastcall  SetAttribute(int iX, int iY, unsigned char Attribute, ZXImage* Image);
            unsigned char   __fastcall  GetAttribute(int iX, int iY, ZXImage& Image);
                    void    __fastcall  SetInk   (unsigned char iInk);
                    void    __fastcall  SetPaper (unsigned char iPaper);
                    bool    __fastcall  Convert(ZXImage* Image, Graphics::TBitmap* Bitmap);
                    int     __fastcall  FindPaperColor(Graphics::TBitmap* Bitmap);
                    void    __fastcall  FindInkColor(Graphics::TBitmap* Bitmap, int iX, int iY, unsigned char& Ink, unsigned char Paper);
                    void    __fastcall  SetColors(ZXImage* Image, Graphics::TBitmap* Bitmap, int iX, int iY, unsigned char Ink, unsigned char Paper);
            unsigned char   __fastcall  GetColorIndex(TColor Color);
                    String  __fastcall  GetName(void);
                    TColor  __fastcall  GetClosestColor(TColor SrcColor, unsigned char* ColorIndex);

        public:
                            __fastcall  ZXVic20HiresPalette();
                    void    __fastcall  Write(int X, int Y, bool bSet, ZXImage& Image);
                    void    __fastcall  Draw(ZXImage& Image, Graphics::TBitmap* Bitmap);
                    void    __fastcall  SetColorAt(ZXImage& Image, int X, int Y);
                    void    __fastcall  GetColorAt(ZXImage& Image, int X, int Y);
                    String  __fastcall  GetColorAsString(ZXImage& Image, int X, int Y);
                    void    __fastcall  Invert(ZXImage& Image, int X, int Y);

            __property  unsigned char   Ink             = { read = m_iInk           , write = SetInk            };
            __property  unsigned char   Paper           = { read = m_iPaper         , write = SetPaper          };
        };
        //---------------------------------------------------------------------------
    }
}
//---------------------------------------------------------------------------
#endif


text:
NS_ASSUME_NONNULL_BEGIN

@interface JSContact (CoreDataProperties)

+ (NSFetchRequest<JSContact *> *)fetchRequest;

@property (nullable, nonatomic, copy) NSString *contactId;
@property (nullable, nonatomic, copy) NSString *contactIdntifier;
@property (nullable, nonatomic, copy) NSString *familyName;
@property (nullable, nonatomic, copy) NSString *givenName;
@property (nullable, nonatomic, copy) NSString *displayName;
@property (nullable, nonatomic, retain) NSSet<JSPhoneNumber *> *has_phone_numbers;

@end

@interface JSContact (CoreDataGeneratedAccessors)

- (void)addHas_phone_numbersObject:(JSPhoneNumber *)value;
- (void)removeHas_phone_numbersObject:(JSPhoneNumber *)value;
- (void)addHas_phone_numbers:(NSSet<JSPhoneNumber *> *)values;
- (void)removeHas_phone_numbers:(NSSet<JSPhoneNumber *> *)values;

@end

NS_ASSUME_NONNULL_END


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

import org.activiti.engine.impl.persistence.deploy.DeploymentCache;
import org.activiti.engine.impl.persistence.deploy.ProcessDefinitionCacheEntry;
import org.activiti.engine.repository.ProcessDefinition;

/**
 * Very simplistic cache implementation that only caches one process definition.
 *
 * @author Joram Barrez
 */
public class CustomDeploymentCache implements DeploymentCache<ProcessDefinitionCacheEntry> {

  protected String id;
  protected ProcessDefinitionCacheEntry entry;

  @Override
  public ProcessDefinitionCacheEntry get(String id) {
    if (id.equals(this.id)) {
      return entry;
    }
    return null;
  }

  @Override
  public void add(String id, ProcessDefinitionCacheEntry object) {
    this.id = id;
    this.entry = object;
  }

  @Override
  public void remove(String id) {
    if (id.equals(this.id)) {
      this.id = null;
      this.entry = null;
    }
  }

  @Override
  public void clear() {
    this.id = null;
    this.entry = null;
  }

  @Override
  public boolean contains(String id) {
    return id.equals(this.id);
  }

  // For testing purposes only
  public ProcessDefinition getCachedProcessDefinition() {
    if (entry == null) {
      return null;
    }
    return entry.getProcessDefinition();
  }

}


text:
<?php

namespace Magento\Integration\Model;

use Magento\Integration\Model\Cache\TypeConsolidated;

/**
 * ConsolidatedConfig to deliver information for config-based integrations that use integration.xml
 */
class ConsolidatedConfig
{
    const CACHE_ID = 'integration-consolidated';

    /**
     * @var \Magento\Framework\App\Cache\Type\Config
     */
    protected $configCacheType;

    /**
     * @var \Magento\Integration\Model\Config\Consolidated\Reader
     */
    protected $configReader;

    /**
     * Array of integrations
     *
     * @var array
     */
    protected $integrations;

    /**
     * @param Cache\TypeConsolidated $configCacheType
     * @param Config\Consolidated\Reader $configReader
     */
    public function __construct(Cache\TypeConsolidated $configCacheType, Config\Consolidated\Reader $configReader)
    {
        $this->configCacheType = $configCacheType;
        $this->configReader = $configReader;
    }

    /**
     * Return integrations loaded from cache if enabled or from files merged previously
     *
     * @return array
     */
    public function getIntegrations()
    {
        if (null === $this->integrations) {
            $integrations = $this->configCacheType->load(self::CACHE_ID);
            if ($integrations && is_string($integrations)) {
                $this->integrations = unserialize($integrations);
            } else {
                $this->integrations = $this->configReader->read();
                $this->configCacheType->save(
                    serialize($this->integrations),
                    self::CACHE_ID,
                    [TypeConsolidated::CACHE_TAG]
                );
            }
        }
        return $this->integrations;
    }
}


text:
using UnityEngine;

public class Variables : MonoBehaviour
{
    public string myName = "Unity3D";
    public float speed = 5.5f;
    public bool isCool = true;
    public int health = 100;

    private int myAge = 26;
    private int maxAmmoCount = 100;
}


text:
extern "Java"
{
  namespace javax
  {
    namespace swing
    {
      namespace text
      {
        namespace html
        {
            class HTML$Attribute;
        }
      }
    }
  }
}

class javax::swing::text::html::HTML$Attribute : public ::java::lang::Object
{

  HTML$Attribute(::java::lang::String *);
public:
  ::java::lang::String * toString();
public: // actually package-private
  static JArray< ::javax::swing::text::html::HTML$Attribute * > * getAllAttributes();
public:
  static ::javax::swing::text::html::HTML$Attribute * ACTION;
  static ::javax::swing::text::html::HTML$Attribute * ALIGN;
  static ::javax::swing::text::html::HTML$Attribute * ALINK;
  static ::javax::swing::text::html::HTML$Attribute * ALT;
  static ::javax::swing::text::html::HTML$Attribute * ARCHIVE;
  static ::javax::swing::text::html::HTML$Attribute * BACKGROUND;
  static ::javax::swing::text::html::HTML$Attribute * BGCOLOR;
  static ::javax::swing::text::html::HTML$Attribute * BORDER;
  static ::javax::swing::text::html::HTML$Attribute * CELLPADDING;
  static ::javax::swing::text::html::HTML$Attribute * CELLSPACING;
  static ::javax::swing::text::html::HTML$Attribute * CHECKED;
  static ::javax::swing::text::html::HTML$Attribute * CLASS;
  static ::javax::swing::text::html::HTML$Attribute * CLASSID;
  static ::javax::swing::text::html::HTML$Attribute * CLEAR;
  static ::javax::swing::text::html::HTML$Attribute * CODE;
  static ::javax::swing::text::html::HTML$Attribute * CODEBASE;
  static ::javax::swing::text::html::HTML$Attribute * CODETYPE;
  static ::javax::swing::text::html::HTML$Attribute * COLOR;
  static ::javax::swing::text::html::HTML$Attribute * COLS;
  static ::javax::swing::text::html::HTML$Attribute * COLSPAN;
  static ::javax::swing::text::html::HTML$Attribute * COMMENT;
  static ::javax::swing::text::html::HTML$Attribute * COMPACT;
  static ::javax::swing::text::html::HTML$Attribute * CONTENT;
  static ::javax::swing::text::html::HTML$Attribute * COORDS;
  static ::javax::swing::text::html::HTML$Attribute * DATA;
  static ::javax::swing::text::html::HTML$Attribute * DECLARE;
  static ::javax::swing::text::html::HTML$Attribute * DIR;
  static ::javax::swing::text::html::HTML$Attribute * DUMMY;
  static ::javax::swing::text::html::HTML$Attribute * ENCTYPE;
  static ::javax::swing::text::html::HTML$Attribute * ENDTAG;
  static ::javax::swing::text::html::HTML$Attribute * FACE;
  static ::javax::swing::text::html::HTML$Attribute * FRAMEBORDER;
  static ::javax::swing::text::html::HTML$Attribute * HALIGN;
  static ::javax::swing::text::html::HTML$Attribute * HEIGHT;
  static ::javax::swing::text::html::HTML$Attribute * HREF;
  static ::javax::swing::text::html::HTML$Attribute * HSPACE;
  static ::javax::swing::text::html::HTML$Attribute * HTTPEQUIV;
  static ::javax::swing::text::html::HTML$Attribute * ID;
  static ::javax::swing::text::html::HTML$Attribute * ISMAP;
  static ::javax::swing::text::html::HTML$Attribute * LANG;
  static ::javax::swing::text::html::HTML$Attribute * LANGUAGE;
  static ::javax::swing::text::html::HTML$Attribute * LINK;
  static ::javax::swing::text::html::HTML$Attribute * LOWSRC;
  static ::javax::swing::text::html::HTML$Attribute * MARGINHEIGHT;
  static ::javax::swing::text::html::HTML$Attribute * MARGINWIDTH;
  static ::javax::swing::text::html::HTML$Attribute * MAXLENGTH;
public: // actually package-private
  static ::javax::swing::text::html::HTML$Attribute * MEDIA;
public:
  static ::javax::swing::text::html::HTML$Attribute * METHOD;
  static ::javax::swing::text::html::HTML$Attribute * MULTIPLE;
  static ::javax::swing::text::html::HTML$Attribute * N;
  static ::javax::swing::text::html::HTML$Attribute * NAME;
  static ::javax::swing::text::html::HTML$Attribute * NOHREF;
  static ::javax::swing::text::html::HTML$Attribute * NORESIZE;
  static ::javax::swing::text::html::HTML$Attribute * NOSHADE;
  static ::javax::swing::text::html::HTML$Attribute * NOWRAP;
  static ::javax::swing::text::html::HTML$Attribute * PROMPT;
  static ::javax::swing::text::html::HTML$Attribute * REL;
  static ::javax::swing::text::html::HTML$Attribute * REV;
  static ::javax::swing::text::html::HTML$Attribute * ROWS;
  static ::javax::swing::text::html::HTML$Attribute * ROWSPAN;
  static ::javax::swing::text::html::HTML$Attribute * SCROLLING;
  static ::javax::swing::text::html::HTML$Attribute * SELECTED;
  static ::javax::swing::text::html::HTML$Attribute * SHAPE;
  static ::javax::swing::text::html::HTML$Attribute * SHAPES;
  static ::javax::swing::text::html::HTML$Attribute * SIZE;
  static ::javax::swing::text::html::HTML$Attribute * SRC;
  static ::javax::swing::text::html::HTML$Attribute * STANDBY;
  static ::javax::swing::text::html::HTML$Attribute * START;
  static ::javax::swing::text::html::HTML$Attribute * STYLE;
  static ::javax::swing::text::html::HTML$Attribute * TARGET;
  static ::javax::swing::text::html::HTML$Attribute * TEXT;
  static ::javax::swing::text::html::HTML$Attribute * TITLE;
  static ::javax::swing::text::html::HTML$Attribute * TYPE;
  static ::javax::swing::text::html::HTML$Attribute * USEMAP;
  static ::javax::swing::text::html::HTML$Attribute * VALIGN;
  static ::javax::swing::text::html::HTML$Attribute * VALUE;
  static ::javax::swing::text::html::HTML$Attribute * VALUETYPE;
  static ::javax::swing::text::html::HTML$Attribute * VERSION;
  static ::javax::swing::text::html::HTML$Attribute * VLINK;
  static ::javax::swing::text::html::HTML$Attribute * VSPACE;
  static ::javax::swing::text::html::HTML$Attribute * WIDTH;
public: // actually package-private
  static ::javax::swing::text::html::HTML$Attribute * PSEUDO_CLASS;
  static ::javax::swing::text::html::HTML$Attribute * DYNAMIC_CLASS;
private:
  ::java::lang::String * __attribute__((aligned(__alignof__( ::java::lang::Object)))) name;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_swing_text_html_HTML$Attribute__


text:
package execution

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"

	"github.com/hyperledger/burrow/acm"
	"github.com/hyperledger/burrow/bcm"
	"github.com/hyperledger/burrow/consensus/tendermint/codes"
	"github.com/hyperledger/burrow/event"
	"github.com/hyperledger/burrow/execution/errors"
	"github.com/hyperledger/burrow/execution/exec"
	"github.com/hyperledger/burrow/logging"
	"github.com/hyperledger/burrow/logging/structure"
	"github.com/hyperledger/burrow/txs"
	abciTypes "github.com/tendermint/tendermint/abci/types"
	tmTypes "github.com/tendermint/tendermint/types"
)

const (
	SubscribeBufferSize = 10
)

// Transactor is responsible for helping to formulate, sign, and broadcast transactions to tendermint
//
// The BroadcastTx* methods are able to work against the mempool Accounts (pending) state rather than the
// committed (final) Accounts state and can assign a sequence number based on all of the txs
// seen since the last block - provided these transactions are successfully committed (via DeliverTx) then
// subsequent transactions will have valid sequence numbers. This allows Burrow to coordinate sequencing and signing
// for a key it holds or is provided - it is down to the key-holder to manage the mutual information between transactions
// concurrent within a new block window.
type Transactor struct {
	BlockchainInfo  bcm.BlockchainInfo
	Emitter         *event.Emitter
	MempoolAccounts *Accounts
	checkTxAsync    func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error
	txEncoder       txs.Encoder
	logger          *logging.Logger
}

func NewTransactor(tip bcm.BlockchainInfo, emitter *event.Emitter, mempoolAccounts *Accounts,
	checkTxAsync func(tx tmTypes.Tx, cb func(*abciTypes.Response)) error, txEncoder txs.Encoder,
	logger *logging.Logger) *Transactor {

	return &Transactor{
		BlockchainInfo:  tip,
		Emitter:         emitter,
		MempoolAccounts: mempoolAccounts,
		checkTxAsync:    checkTxAsync,
		txEncoder:       txEncoder,
		logger:          logger.With(structure.ComponentKey, "Transactor"),
	}
}

func (trans *Transactor) BroadcastTxSync(ctx context.Context, txEnv *txs.Envelope) (*exec.TxExecution, error) {
	// Sign unless already signed - note we must attempt signing before subscribing so we get accurate final TxHash
	unlock, err := trans.MaybeSignTxMempool(txEnv)
	if err != nil {
		return nil, err
	}
	// We will try and call this before the function exits unless we error but it is idempotent
	defer unlock()
	// Subscribe before submitting to mempool
	txHash := txEnv.Tx.Hash()
	subID := event.GenSubID()
	out, err := trans.Emitter.Subscribe(ctx, subID, exec.QueryForTxExecution(txHash), SubscribeBufferSize)
	if err != nil {
		// We do not want to hold the lock with a defer so we must
		return nil, err
	}
	defer trans.Emitter.UnsubscribeAll(context.Background(), subID)
	// Push Tx to mempool
	checkTxReceipt, err := trans.CheckTxSync(ctx, txEnv)
	unlock()
	if err != nil {
		return nil, err
	}
	// Get all the execution events for this Tx
	select {
	case <-ctx.Done():
		syncInfo := bcm.GetSyncInfo(trans.BlockchainInfo)
		bs, err := json.Marshal(syncInfo)
		syncInfoString := string(bs)
		if err != nil {
			syncInfoString = fmt.Sprintf("{error could not marshal SyncInfo: %v}", err)
		}
		return nil, fmt.Errorf("waiting for tx %v, SyncInfo: %s", checkTxReceipt.TxHash, syncInfoString)
	case msg := <-out:
		txe := msg.(*exec.TxExecution)
		callError := txe.CallError()
		if callError != nil && callError.ErrorCode() != errors.ErrorCodeExecutionReverted {
			return nil, errors.Wrap(callError, "exception during transaction execution")
		}
		return txe, nil
	}
}

// Broadcast a transaction without waiting for confirmation - will attempt to sign server-side and set sequence numbers
// if no signatures are provided
func (trans *Transactor) BroadcastTxAsync(ctx context.Context, txEnv *txs.Envelope) (*txs.Receipt, error) {
	return trans.CheckTxSync(ctx, txEnv)
}

// Broadcast a transaction and waits for a response from the mempool. Transactions to BroadcastTx will block during
// various mempool operations (managed by Tendermint) including mempool Reap, Commit, and recheckTx.
func (trans *Transactor) CheckTxSync(ctx context.Context, txEnv *txs.Envelope) (*txs.Receipt, error) {
	trans.logger.Trace.Log("method", "CheckTxSync",
		structure.TxHashKey, txEnv.Tx.Hash(),
		"tx", txEnv.String())
	// Sign unless already signed
	unlock, err := trans.MaybeSignTxMempool(txEnv)
	if err != nil {
		return nil, err
	}
	defer unlock()
	err = txEnv.Validate()
	if err != nil {
		return nil, err
	}
	txBytes, err := trans.txEncoder.EncodeTx(txEnv)
	if err != nil {
		return nil, err
	}
	return trans.CheckTxSyncRaw(ctx, txBytes)
}

func (trans *Transactor) MaybeSignTxMempool(txEnv *txs.Envelope) (UnlockFunc, error) {
	// Sign unless already signed
	if len(txEnv.Signatories) == 0 {
		var err error
		var unlock UnlockFunc
		// We are writing signatures back to txEnv so don't shadow txEnv here
		txEnv, unlock, err = trans.SignTxMempool(txEnv)
		if err != nil {
			return nil, fmt.Errorf("error signing transaction: %v", err)
		}
		// Hash will have change since we signed
		txEnv.Tx.Rehash()
		// Make this idempotent for defer
		var once sync.Once
		return func() { once.Do(unlock) }, nil
	}
	return func() {}, nil
}

func (trans *Transactor) SignTxMempool(txEnv *txs.Envelope) (*txs.Envelope, UnlockFunc, error) {
	inputs := txEnv.Tx.GetInputs()
	signers := make([]acm.AddressableSigner, len(inputs))
	unlockers := make([]UnlockFunc, len(inputs))
	for i, input := range inputs {
		ssa, err := trans.MempoolAccounts.SequentialSigningAccount(input.Address)
		if err != nil {
			return nil, nil, err
		}
		sa, unlock, err := ssa.Lock()
		if err != nil {
			return nil, nil, err
		}
		// Hold lock until safely in mempool - important that this is held until after CheckTxSync returns
		unlockers[i] = unlock
		signers[i] = sa
		// Set sequence number consecutively from mempool
		input.Sequence = sa.Sequence + 1
	}

	err := txEnv.Sign(signers...)
	if err != nil {
		return nil, nil, err
	}
	return txEnv, UnlockFunc(func() {
		for _, unlock := range unlockers {
			defer unlock()
		}
	}), nil
}

func (trans *Transactor) SignTx(txEnv *txs.Envelope) (*txs.Envelope, error) {
	var err error
	inputs := txEnv.Tx.GetInputs()
	signers := make([]acm.AddressableSigner, len(inputs))
	for i, input := range inputs {
		signers[i], err = trans.MempoolAccounts.SigningAccount(input.Address)
		if err != nil {
			return nil, err
		}
	}
	err = txEnv.Sign(signers...)
	if err != nil {
		return nil, err
	}
	return txEnv, nil
}

func (trans *Transactor) CheckTxSyncRaw(ctx context.Context, txBytes []byte) (*txs.Receipt, error) {
	responseCh := make(chan *abciTypes.Response, 3)
	err := trans.CheckTxAsyncRaw(txBytes, func(res *abciTypes.Response) {
		responseCh <- res
	})
	if err != nil {
		return nil, err
	}

	select {
	case <-ctx.Done():
		return nil, fmt.Errorf("waiting for CheckTx response in CheckTxSyncRaw: %v", ctx.Err())
	case response := <-responseCh:
		checkTxResponse := response.GetCheckTx()
		if checkTxResponse == nil {
			return nil, fmt.Errorf("application did not return CheckTx response")
		}

		switch checkTxResponse.Code {
		case codes.TxExecutionSuccessCode:
			receipt, err := txs.DecodeReceipt(checkTxResponse.Data)
			if err != nil {
				return nil, fmt.Errorf("could not deserialise transaction receipt: %s", err)
			}
			return receipt, nil
		default:
			return nil, errors.ErrorCodef(errors.Code(checkTxResponse.Code),
				"error returned by Tendermint in BroadcastTxSync ABCI log: %v", checkTxResponse.Log)
		}
	}
}

func (trans *Transactor) CheckTxAsyncRaw(txBytes []byte, callback func(res *abciTypes.Response)) error {
	return trans.checkTxAsync(txBytes, callback)
}

func (trans *Transactor) CheckTxAsync(txEnv *txs.Envelope, callback func(res *abciTypes.Response)) error {
	err := txEnv.Validate()
	if err != nil {
		return err
	}
	txBytes, err := trans.txEncoder.EncodeTx(txEnv)
	if err != nil {
		return fmt.Errorf("error encoding transaction: %v", err)
	}
	return trans.CheckTxAsyncRaw(txBytes, callback)
}


text:
require 'net/http'
require 'uri'

module Uploader
  class Put < Net::HTTP::Put
    def initialize(path, headers, handlers)
      @handlers = handlers
      super path, headers
    end

    private

    def send_request_with_body_stream(sock, ver, path, f)
      write_header sock, ver, path
      wait_for_continue sock, ver if sock.continue_timeout
      chunker = Chunker.new(sock, self['Content-Length'], @handlers)
      IO.copy_stream(f, chunker)
      chunker.finish
    end
  end

  class Chunker
    def initialize(sock, content_length, handlers)
      @sock = sock
      @prev = nil
      @count = 0
      @total_count = nil
      @content_length = content_length.to_i
      @handlers = handlers
    end

    def write(buf)
      @total_count = @content_length / buf.bytesize.to_i if @total_count.nil?

      @handlers[:before_chunk].each do |handler|
        handler.execute buf, @count, @total_count, @content_length
      end

      @sock.write("#{buf.bytesize.to_s(16)}\r\n")
      rv = @sock.write(buf)
      @sock.write("\r\n")

      @handlers[:after_chunk].each do |handler|
        handler.execute buf, @count, @total_count, @content_length
      end

      @count += 1

      rv
    end

    def finish
      @sock.write("0\r\n\r\n")
    end
  end
end


text:
function Texture(gl) {
    this.gl = gl;
    this.texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, this.texture);

    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);

    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
Texture.prototype.bind = function (n, program, name) {
    var gl = this.gl;
    gl.activeTexture([gl.TEXTURE0, gl.TEXTURE1, gl.TEXTURE2][n]);
    gl.bindTexture(gl.TEXTURE_2D, this.texture);
    gl.uniform1i(gl.getUniformLocation(program, name), n);
}
Texture.prototype.fill = function (width, height, data) {
    var gl = this.gl;
    gl.bindTexture(gl.TEXTURE_2D, this.texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, data);
}

function render(canvas, videoFrame) {
    var gl = canvas.gl;
    gl.y.fill(videoFrame.width, videoFrame.height,
              videoFrame.subarray(0, videoFrame.uOffset));
    gl.u.fill(videoFrame.width >> 1, videoFrame.height >> 1,
              videoFrame.subarray(videoFrame.uOffset, videoFrame.vOffset));
    gl.v.fill(videoFrame.width >> 1, videoFrame.height >> 1,
              videoFrame.subarray(videoFrame.vOffset, videoFrame.length));
}

var renderFallback = function(canvas, videoFrame) {
    var buf = canvas.img.data;
    var width = videoFrame.width;
    var height = videoFrame.height;
    for (var i = 0; i < height; ++i) {
        for (var j = 0; j < width; ++j) {
            var o = (j + (width*i))*4;
            buf[o + 0] = videoFrame[o+2];
            buf[o + 1] = videoFrame[o+1];
            buf[o + 2] = videoFrame[o+0];
            buf[o + 3] = videoFrame[o+3];
        }
    };
    canvas.ctx.putImageData(canvas.img, 0, 0);
}

function setupCanvas(canvas, vlc, fallbackRenderer) {
    if (!fallbackRenderer) canvas.gl = canvas.getContext("webgl"); // Comment this line out to test fallback
    var gl = canvas.gl;
    if (!gl || fallbackRenderer) {
        console.log(fallbackRenderer ? "Fallback renderer forced, not using WebGL" : "Unable to initialize WebGL, falling back to canvas rendering");
        vlc.pixelFormat = vlc.RV32;
        canvas.ctx = canvas.getContext("2d");
        delete canvas.gl; // in case of fallback renderer
        return;
    }

    vlc.pixelFormat = vlc.I420;
    canvas.I420Program = gl.createProgram();
    var program = canvas.I420Program;
    var vertexShaderSource = [
        "attribute highp vec4 aVertexPosition;",
        "attribute vec2 aTextureCoord;",
        "varying highp vec2 vTextureCoord;",
        "void main(void) {",
        " gl_Position = aVertexPosition;",
        " vTextureCoord = aTextureCoord;",
        "}"].join("\n");
    var vertexShader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vertexShader, vertexShaderSource);
    gl.compileShader(vertexShader);
    var fragmentShaderSource = [
        "precision highp float;",
        "varying lowp vec2 vTextureCoord;",
        "uniform sampler2D YTexture;",
        "uniform sampler2D UTexture;",
        "uniform sampler2D VTexture;",
        "const mat4 YUV2RGB = mat4",
        "(",
        " 1.1643828125, 0, 1.59602734375, -.87078515625,",
        " 1.1643828125, -.39176171875, -.81296875, .52959375,",
        " 1.1643828125, 2.017234375, 0, -1.081390625,",
        " 0, 0, 0, 1",
        ");",
        "void main(void) {",
        " gl_FragColor = vec4( texture2D(YTexture, vTextureCoord).x, texture2D(UTexture, vTextureCoord).x, texture2D(VTexture, vTextureCoord).x, 1) * YUV2RGB;",
        "}"].join("\n");

    var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fragmentShader, fragmentShaderSource);
    gl.compileShader(fragmentShader);
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    gl.useProgram(program);
    if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        console.log("Shader link failed.");
    }
    var vertexPositionAttribute = gl.getAttribLocation(program, "aVertexPosition");
    gl.enableVertexAttribArray(vertexPositionAttribute);
    var textureCoordAttribute = gl.getAttribLocation(program, "aTextureCoord");
    gl.enableVertexAttribArray(textureCoordAttribute);

    var verticesBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, verticesBuffer);
    gl.bufferData(gl.ARRAY_BUFFER,
                  new Float32Array([1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, -1.0, -1.0, 0.0]),
                  gl.STATIC_DRAW);
    gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
    var texCoordBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
    gl.bufferData(gl.ARRAY_BUFFER,
                  new Float32Array([1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0]),
                  gl.STATIC_DRAW);
    gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);

    gl.y = new Texture(gl);
    gl.u = new Texture(gl);
    gl.v = new Texture(gl);
    gl.y.bind(0, program, "YTexture");
    gl.u.bind(1, program, "UTexture");
    gl.v.bind(2, program, "VTexture");
}

function frameSetup(canvas, width, height, pixelFormat) {
    var gl = canvas.gl;
    canvas.width = width;
    canvas.height = height;
    if (!gl) {
        canvas.img = canvas.ctx.createImageData(width, height);
        return;
    }
    gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}

module.exports = {
    skipFrames: function(times) {
        this.skip = parseInt(times);
    },
    init: function(canvas, params, fallbackRenderer) {
        var vlc = require("wcjs-prebuilt").createPlayer(params);

        var drawLoop, newFrame;

        if(typeof canvas === 'string')
            canvas = window.document.querySelector(canvas);

        this._canvas = canvas;

        setupCanvas(canvas, vlc, fallbackRenderer);

        vlc.onFrameSetup =
            function(width, height, pixelFormat) {
                frameSetup(canvas, width, height, pixelFormat);

                var loopB = function() {
                    var gl = canvas.gl;
                    if (newFrame && gl) gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
                    newFrame = false;
                    drawB();
                };

                var loopA = function() {
                    var gl = canvas.gl;
                    if (newFrame && gl) gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
                    newFrame = false;
                    drawA();
                };

                var drawA = function() {
                    drawLoop = window.requestAnimationFrame(loopB);
                };

                var drawB = function() {
                    drawLoop = window.requestAnimationFrame(loopA);
                };

                drawA();

                canvas.addEventListener("webglcontextlost",
                    function(event) {
                        event.preventDefault();
                        console.log("webgl context lost");
                    }, false);

                canvas.addEventListener("webglcontextrestored",
                    function(w,h,p) {
                        return function(event) {
                            setupCanvas(canvas, vlc);
                            frameSetup(canvas, w, h, p);
                            console.log("webgl context restored");
                        }
                    }(width,height,pixelFormat), false);

            };

        setFrame = this;
        vlc.onFrameReady =
            function(videoFrame) {
                if (setFrame.skip && setFrame.skip > 0) {
                    setFrame.skip--;
                    return;
                }
                (canvas.gl ? render : renderFallback)(canvas, videoFrame);
                newFrame = true;
            };
        vlc.onFrameCleanup =
            function() {
                if (drawLoop) { window.cancelAnimationFrame(drawLoop); drawLoop = null; }
            };
        return vlc;
    },

    clearCanvas: function() {
        var gl = this._canvas.gl,
            arr1 = new Uint8Array(1),
            arr2 = new Uint8Array(1);

        arr1[0] = 0;
        arr2[0] = 128;

        gl.y.fill(1, 1, arr1);
        gl.u.fill(1, 1, arr2);
        gl.v.fill(1, 1, arr2);

        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
    },

    _canvas: false
};