text:
using System;
using System.Collections.Generic;
using CCSkype.SkypeWrapper;

namespace CCSkype
{
    public class MessengerClient : IMessengerClient
    {
        private readonly ISkype _skype;
        private IUserCollection _userCollection;
        private readonly IChats _chats;

        public MessengerClient(ISkype skype, IUserCollection userCollection, IChats chats)
        {
            _skype = skype;
            _userCollection = userCollection;
            _chats = chats;
        }

        public void SendMessage(string message, IUserCollection userCollection, string name)
        {
            _userCollection = userCollection;
            SendMessage(message, name);
        }

        public void SendMessage(string message, string name)
        {
            StartSkypeIfNotRunning();
            var chat = GetChatWindow(name);
            chat.SendMessage(message);
        }

        private IChat GetChatWindow(string name)
        {
            var chat = _chats.Get(name, _userCollection);
            chat.OpenWindow();
            return chat;
        }

        private void StartSkypeIfNotRunning()
        {
            if (!_skype.SkypeClient().IsRunning())
            {
                _skype.SkypeClient().Start(false, true);
            }
        }

        public void SetUserList(List<User> users)
        {
            users.ForEach(AddUser);
        }

        private void  AddUser(User user)
        {
            _userCollection.Add(_skype.GetUser(user.Username));
        }

        public bool AllKnownUsers(List<User> users)
        {
            StartSkypeIfNotRunning();
            var skypeUsers = _skype.GetUsers();

            foreach (var user in users)
            {
                if (!skypeUsers.Contains(user.Username))
                {
                    throw new UserNotKnowException(user.Username);
                }
            }
            return true;
        }
    }
}


text:
package org.kie.internal.builder.conf;

import org.kie.api.conf.SingleValueKieBaseOption;

/**
 * By default all the Drools artifacts under the resources folder, at any level, are included into the KieBase.
 * The package attribute of the kmodule.xml allows to limit the artifacts that will be compiled in this KieBase
 * to only the ones belonging to the list of packages. However older versions of Drools actually checked the folder
 * name instead of the package one. This option allows to re-eanble that old folder-based behaviour.
 *
 * drools.groupDRLsInKieBasesByFolder = <true|false>
 *
 * DEFAULT = false
 */
public enum GroupDRLsInKieBasesByFolderOption implements SingleValueKnowledgeBuilderOption, SingleValueKieBaseOption {

    ENABLED(true),
    DISABLED(false);

    /**
     * The property name for the enabling/disabling trim of cells values
     */
    public static final String PROPERTY_NAME = "drools.groupDRLsInKieBasesByFolder";

    private boolean value;

    GroupDRLsInKieBasesByFolderOption( final boolean value ) {
        this.value = value;
    }

    @Override
    public String getPropertyName() {
        return PROPERTY_NAME;
    }

    public boolean isGroupDRLsInKieBasesByFolder() {
        return this.value;
    }
}

redpajama_set_name: RedPajamaGithub


text:
local opacityMaster = 0.68
local showHitboxes = not true
gui.register(function()
	local frame = emu.framecount()
	local lagframe = emu.lagcount()
	local moviemode = ""

	local igframe = memory.readdword(0x02100374)
	local camx = math.floor(memory.readdwordsigned(0x021000bc) / 0x1000)
	local camy = math.floor(memory.readdwordsigned(0x021000c0) / 0x1000)
	local ch_x = memory.readdwordsigned(0x02109850)
	local ch_y = memory.readdwordsigned(0x02109854)
	local ch_vx = memory.readdwordsigned(0x0210985c)
	local ch_vy = memory.readdwordsigned(0x02109860)
	local ch_inv = memory.readbyte(0x021098e5)
	local ch_mptimer = memory.readword(0x020ffec0)
	local ch_atktimer = memory.readword(0x020ffec2)
	local hp = memory.readword(0x021002b4)
	local mp = memory.readword(0x021002b8)
	local mode = memory.readbyte(0x020d88d0)
	local fade = 1.0 -- math.min(1.0, 1.0 - math.abs(memory.readbytesigned(0x020f61fc)/16.0)) -- FIXME

	moviemode = movie.mode()
	if not movie.active() then moviemode = "no movie" end

	local framestr = ""
	if movie.active() and not movie.recording() then
		framestr = string.format("%d/%d", frame, movie.length())
	else
		framestr = string.format("%d", frame)
	end
	framestr = framestr .. (moviemode ~= "" and string.format(" (%s)", moviemode) or "")

	gui.opacity(opacityMaster)
	gui.text(1, 26, string.format("%s\n%d", framestr, lagframe))

	if mode == 0 then
		gui.opacity(opacityMaster * (fade/2 + 0.5))

		gui.text(1, 60, string.format("(%6d,%6d) %d %d %d\nHP%03d/MP%03d",
			ch_vx, ch_vy, ch_inv, ch_mptimer, ch_atktimer, hp, mp))

		-- enemy info
		local basead = 0x0210d308
		local dispy = 26
		for i = -40, 127 do
			local base = basead + i * 0x160
			--if memory.readword(base) > 0 then
				-- hp display
				local en_hp = memory.readword(base)
				local en_mp = memory.readword(base+2)
				local en_x = memory.readdword(base-0xf8)
				local en_dmtyp1 = memory.readbyte(base-0x66)
				local en_dmtyp2 = memory.readbyte(base-0x65)
				local en_dmtyp3 = memory.readbyte(base-0x64)
				local en_inv1 = memory.readbyte(base-0x63)
				local en_inv2 = memory.readbyte(base-0x62)
				local en_inv3 = memory.readbyte(base-0x61)
				memory.writedword(base-0xec, 0) -- x velocity
				memory.writedword(base-0xe8, 0) -- y velocity
				memory.writeword(base-0xa6, 255) -- animation
				--gui.text(189, dispy, string.format("%02X %08X", i, base))
				-- gui.text(183, dispy, string.format("%02X %4d %4d", i, en_hp, en_mp))
				-- gui.text(171, dispy, string.format("%X %03d %08X", i, en_hp, en_x))
				-- gui.text(123, dispy, string.format("%02X %4d %d/%02X %d/%02X %d/%02X", i, en_hp, en_dmtyp1, en_inv1, en_dmtyp2, en_inv2, en_dmtyp3, en_inv3))
				dispy = dispy + 10
			--end
		end

		-- enemy's hitbox
		if showHitboxes then
			for i = 0, 63 do
				local rectad = 0x02128f62 + (i * 0x14)
				local left = memory.readwordsigned(rectad+0) - camx
				local top = memory.readwordsigned(rectad+2) - camy
				local right = memory.readwordsigned(rectad+4) - camx
				local bottom = memory.readwordsigned(rectad+6) - camy
				if top >= 0 then
					gui.box(left, top, right, bottom, "clear", "#00ff00aa")
				end
			end
		end

		-- Shanoa's hitbox
		if showHitboxes then
			local left = memory.readwordsigned(0x02128c2e) - camx
			local top = memory.readwordsigned(0x02128c30) - camy
			local right = memory.readwordsigned(0x02128c32) - camx
			local bottom = memory.readwordsigned(0x02128c34) - camy
			gui.box(left, top, right, bottom, "clear", "#00ff00aa")
		end

		-- Glyph absorb timer
		local absorbTimerStr = ""
		for i = 0, 15 do
			local baseaddr = 0x02101000 + (i * 0x100)
			local timer = memory.readdwordsigned(baseaddr + 0x144)
			if timer > 0 and (
				memory.readdwordsigned(baseaddr + 0x38) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0x60) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0x88) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xb0) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xbc) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xc4) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xcc) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xd4) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xd8) == 0x10000 or
				memory.readdwordsigned(baseaddr + 0xdc) == 0x10000
			) then
				-- absorbTimerStr = absorbTimerStr .. i .. ":"
				absorbTimerStr = absorbTimerStr .. string.format("%05X", timer) .. " "
			end
		end
		if absorbTimerStr ~= "" then
			gui.text(1, 183, "(Glyph) " .. absorbTimerStr)
		end
	end
end)


text:
class Helper {
  /**
   * method returnUnAuthorized is to return Unauthorized message
   * @param {object} res; the response obect
   * @returns {object} response sent to the frontend
   */
  static returnUnAuthorized(res) {
    return res.status(401).json({
      message: 'Unauthorized request'
    });
  }
}

export default Helper;


text:
package com.jayway.jsonassert.impl.matcher;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;

import java.util.Collection;

/**
 * Tests if collection is empty.
 */
public class IsEmptyCollection<E> extends CollectionMatcher<Collection<E>> {

    @Override
    public boolean matchesSafely(Collection<E> item) {
        return item.isEmpty();
    }

    public void describeTo(Description description) {
        description.appendText("an empty collection");
    }

    /**
     * Matches an empty collection.
     */
    @Factory
    public static <E> Matcher<Collection<E>> empty() {
        return new IsEmptyCollection<E>();
    }
}


text:
package org.elasticsearch.xpack.ql.expression;

import org.elasticsearch.xpack.ql.capabilities.Unresolvable;
import org.elasticsearch.xpack.ql.capabilities.UnresolvedException;
import org.elasticsearch.xpack.ql.tree.NodeInfo;
import org.elasticsearch.xpack.ql.tree.Source;
import org.elasticsearch.xpack.ql.type.DataType;
import org.elasticsearch.xpack.ql.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

// unfortunately we can't use UnresolvedNamedExpression
public class UnresolvedAttribute extends Attribute implements Unresolvable {

    private final String unresolvedMsg;
    private final boolean customMessage;
    private final Object resolutionMetadata;

    public UnresolvedAttribute(Source source, String name) {
        this(source, name, null);
    }

    public UnresolvedAttribute(Source source, String name, String qualifier) {
        this(source, name, qualifier, null);
    }

    public UnresolvedAttribute(Source source, String name, String qualifier, String unresolvedMessage) {
        this(source, name, qualifier, null, unresolvedMessage, null);
    }

    public UnresolvedAttribute(Source source, String name, String qualifier, NameId id, String unresolvedMessage,
            Object resolutionMetadata) {
        super(source, name, qualifier, id);
        this.customMessage = unresolvedMessage != null;
        this.unresolvedMsg = unresolvedMessage == null ? errorMessage(qualifiedName(), null) : unresolvedMessage;
        this.resolutionMetadata = resolutionMetadata;
    }

    @Override
    protected NodeInfo<UnresolvedAttribute> info() {
        return NodeInfo.create(this, UnresolvedAttribute::new,
            name(), qualifier(), id(), unresolvedMsg, resolutionMetadata);
    }

    public Object resolutionMetadata() {
        return resolutionMetadata;
    }

    public boolean customMessage() {
        return customMessage;
    }

    @Override
    public boolean resolved() {
        return false;
    }

    @Override
    protected Attribute clone(Source source, String name, DataType dataType, String qualifier, Nullability nullability,
                              NameId id, boolean synthetic) {
        return this;
    }

    public UnresolvedAttribute withUnresolvedMessage(String unresolvedMsg) {
        return new UnresolvedAttribute(source(), name(), qualifier(), id(), unresolvedMsg, resolutionMetadata());
    }

    @Override
    public DataType dataType() {
        throw new UnresolvedException("dataType", this);
    }

    @Override
    public String toString() {
        return UNRESOLVED_PREFIX + qualifiedName();
    }

    @Override
    protected String label() {
        return UNRESOLVED_PREFIX;
    }

    @Override
    public String nodeString() {
        return toString();
    }

    @Override
    public String unresolvedMessage() {
        return unresolvedMsg;
    }

    public static String errorMessage(String name, List<String> potentialMatches) {
        String msg = "Unknown column [" + name + "]";
        if (CollectionUtils.isEmpty(potentialMatches) == false) {
            msg += ", did you mean " + (potentialMatches.size() == 1 ? "[" + potentialMatches.get(0)
                    + "]": "any of " + potentialMatches.toString()) + "?";
        }
        return msg;
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), resolutionMetadata, unresolvedMsg);
    }

    @Override
    public boolean equals(Object obj) {
        if (super.equals(obj)) {
            UnresolvedAttribute ua = (UnresolvedAttribute) obj;
            return Objects.equals(resolutionMetadata, ua.resolutionMetadata) && Objects.equals(unresolvedMsg, ua.unresolvedMsg);
        }
        return false;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:c="http://www.springframework.org/schema/context"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
                           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                           http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

    <c:property-placeholder location="classpath:test.properties" />
    <c:annotation-config />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}${jdbc.dbname}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="caseManager" class="org.xeneo.db.JdbcCaseManager" />

    <bean id="activityRepository" class="org.xeneo.db.JdbcActivityRepository">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

    <bean id="taskContextManager" class="org.xeneo.db.JdbcTaskContextManager">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

    <bean id="userService" class="org.xeneo.db.security.JdbcUserService" />

    <bean id="userManager" class="org.xeneo.db.security.JdbcUserManager">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

    <bean id="uriGen" class="org.xeneo.db.services.URIGenerator" factory-method="getInstance">
        <property name="baseURI" value="http://mytest.org" />
    </bean>

    <bean id="markovRec" class="org.xeneo.db.recommendation.MarkovRecommendation" />

</beans>


text:
package network::hp::moonshot::snmp::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{modes} = {
        'cpu'             => 'network::hp::moonshot::snmp::mode::cpu',
        'interfaces'      => 'network::hp::moonshot::snmp::mode::interfaces',
        'list-interfaces' => 'snmp_standard::mode::listinterfaces',
        'memory'          => 'network::hp::moonshot::snmp::mode::memory'
    };

    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check HP Moonshot Switch Module for HP Moonshot chassis in SNMP.

=cut


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 com.facebook.presto.operator;

import com.facebook.presto.spi.type.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.Futures.transform;

public final class SettableLookupSourceSupplier
        implements LookupSourceSupplier
{
    private final List<Type> types;
    private final SettableFuture<SharedLookupSource> lookupSourceFuture = SettableFuture.create();
    private final AtomicInteger referenceCount = new AtomicInteger(1);

    public SettableLookupSourceSupplier(List<Type> types)
    {
        this.types = ImmutableList.copyOf(checkNotNull(types, "types is null"));
    }

    @Override
    public List<Type> getTypes()
    {
        return types;
    }

    @Override
    public ListenableFuture<LookupSource> getLookupSource(OperatorContext operatorContext)
    {
        return transform(lookupSourceFuture, (AsyncFunction<SharedLookupSource, LookupSource>) Futures::immediateFuture);
    }

    public void setLookupSource(SharedLookupSource lookupSource)
    {
        checkNotNull(lookupSource, "lookupSource is null");
        boolean wasSet = lookupSourceFuture.set(lookupSource);
        checkState(wasSet, "Lookup source already set");
    }

    @Override
    public void retain()
    {
        referenceCount.incrementAndGet();
    }

    @Override
    public void release()
    {
        if (referenceCount.decrementAndGet() == 0) {
            // We own the shared lookup source, so we need to free their memory
            Futures.addCallback(lookupSourceFuture, new FutureCallback<SharedLookupSource>() {
                @Override
                public void onSuccess(SharedLookupSource result)
                {
                    result.freeMemory();
                }

                @Override
                public void onFailure(Throwable t)
                {
                    // ignored
                }
            });
        }
    }
}


text:
import pytest
import numpy as np
from scipy import sparse
from sklearn.datasets import load_iris
from umap import UMAP, AlignedUMAP

# Globals, used for all the tests
SEED = 189212  # 0b101110001100011100
np.random.seed(SEED)

# Spatial and Binary Data
# -----------------------
@pytest.fixture(scope="session")
def spatial_data():
    # - Spatial Data
    spatial_data = np.random.randn(10, 20)
    # Add some all zero data for corner case test
    return np.vstack([spatial_data, np.zeros((2, 20))])

@pytest.fixture(scope="session")
def binary_data():
    binary_data = np.random.choice(a=[False, True], size=(10, 20), p=[0.66, 1 - 0.66])
    # Add some all zero data for corner case test
    binary_data = np.vstack([binary_data, np.zeros((2, 20), dtype="bool")])
    return binary_data

# Sparse Spatial and Binary Data
# ------------------------------
@pytest.fixture(scope="session")
def sparse_spatial_data(spatial_data, binary_data):
    return sparse.csr_matrix(spatial_data * binary_data)

@pytest.fixture(scope="session")
def sparse_binary_data(binary_data):
    return sparse.csr_matrix(binary_data)

# Nearest Neighbour Data
# -----------------------
@pytest.fixture(scope="session")
def nn_data():
    nn_data = np.random.uniform(0, 1, size=(1000, 5))
    nn_data = np.vstack(
        [nn_data, np.zeros((2, 5))]
    )  # Add some all zero data for corner case test
    return nn_data

@pytest.fixture(scope="session")
def binary_nn_data():
    binary_nn_data = np.random.choice(
        a=[False, True], size=(1000, 5), p=[0.66, 1 - 0.66]
    )
    binary_nn_data = np.vstack(
        [binary_nn_data, np.zeros((2, 5), dtype="bool")]
    )  # Add some all zero data for corner case test
    return binary_nn_data

@pytest.fixture(scope="session")
def sparse_nn_data():
    return sparse.random(1000, 50, density=0.5, format="csr")

# Data With Repetitions
# ---------------------

@pytest.fixture(scope="session")
def repetition_dense():
    # Dense data for testing small n
    return np.array(
        [
            [5, 6, 7, 8],
            [5, 6, 7, 8],
            [5, 6, 7, 8],
            [5, 6, 7, 8],
            [5, 6, 7, 8],
            [5, 6, 7, 8],
            [1, 1, 1, 1],
            [1, 2, 3, 4],
            [1, 1, 2, 1],
        ]
    )

@pytest.fixture(scope="session")
def spatial_repeats(spatial_data):
    # spatial data repeats
    spatial_repeats = np.vstack(
        [np.repeat(spatial_data[0:2], [2, 0], axis=0), spatial_data, np.zeros((2, 20))]
    )
    # Add some all zero data for corner case test.  Make the first three rows identical
    # binary Data Repeat
    return spatial_repeats

@pytest.fixture(scope="session")
def binary_repeats(binary_data):
    binary_repeats = np.vstack(
        [
            np.repeat(binary_data[0:2], [2, 0], axis=0),
            binary_data,
            np.zeros((2, 20), dtype="bool"),
        ]
    )
    # Add some all zero data for corner case test.  Make the first three rows identical
    return binary_repeats

@pytest.fixture(scope="session")
def sparse_spatial_data_repeats(spatial_repeats, binary_repeats):
    return sparse.csr_matrix(spatial_repeats * binary_repeats)

@pytest.fixture(scope="session")
def sparse_binary_data_repeats(binary_repeats):
    return sparse.csr_matrix(binary_repeats)

@pytest.fixture(scope="session")
def sparse_test_data(nn_data, binary_nn_data):
    return sparse.csr_matrix(nn_data * binary_nn_data)

@pytest.fixture(scope="session")
def iris():
    return load_iris()

@pytest.fixture(scope="session")
def iris_selection():
    return np.random.choice([True, False], 150, replace=True, p=[0.75, 0.25])

@pytest.fixture(scope="session")
def aligned_iris(iris):
    slices = [iris.data[i : i + 50] for i in range(0, 125, 25)]
    target = [iris.target[i : i + 50] for i in range(0, 125, 25)]
    return slices, target

@pytest.fixture(scope="session")
def aligned_iris_relations():
    return [{a: a + 25 for a in range(25)} for i in range(4)]

@pytest.fixture(scope="session")
def iris_model(iris):
    return UMAP(n_neighbors=10, min_dist=0.01, random_state=42).fit(iris.data)

@pytest.fixture(scope="session")
def iris_model_large(iris):
    return UMAP(
        n_neighbors=10,
        min_dist=0.01,
        random_state=42,
        force_approximation_algorithm=True,
    ).fit(iris.data)

@pytest.fixture(scope="session")
def iris_subset_model(iris, iris_selection):
    return UMAP(n_neighbors=10, min_dist=0.01, random_state=42).fit(
        iris.data[iris_selection]
    )

@pytest.fixture(scope="session")
def iris_subset_model_large(iris, iris_selection):
    return UMAP(
        n_neighbors=10,
        min_dist=0.01,
        random_state=42,
        force_approximation_algorithm=True,
    ).fit(iris.data[iris_selection])

@pytest.fixture(scope="session")
def supervised_iris_model(iris):
    return UMAP(n_neighbors=10, min_dist=0.01, n_epochs=200, random_state=42).fit(
        iris.data, iris.target
    )

@pytest.fixture(scope="session")
def aligned_iris_model(aligned_iris, aligned_iris_relations):
    data, target = aligned_iris
    model = AlignedUMAP()
    model.fit(data, relations=aligned_iris_relations)
    return model

# UMAP Distance Metrics
# ---------------------
@pytest.fixture(scope="session")
def spatial_distances():
    return (
        "euclidean",
        "manhattan",
        "chebyshev",
        "minkowski",
        "hamming",
        "canberra",
        "braycurtis",
        "cosine",
        "correlation",
    )

@pytest.fixture(scope="session")
def binary_distances():
    return (
        "jaccard",
        "matching",
        "dice",
        "kulsinski",
        "rogerstanimoto",
        "russellrao",
        "sokalmichener",
        "sokalsneath",
        "yule",
    )


text:
// Problem 6.* Matrix class
//Write a class Matrix, to hold a matrix of integers. Overload the operators for adding,
//subtracting and multiplying of matrices, indexer for accessing the matrix content and ToString().

using System;
using System.Text;

public class MatrixClass
{
    public class Matrix
    {
        private int[,] matrix;
        private int rows;
        private int cols;

        public Matrix(int rows, int cols)
        {
            this.matrix = new int[rows, cols];
            this.Rows = rows;
            this.Cols = cols;
        }

        public int Rows
        {
            get { return rows; }
            set
            {
                if (value < 1)
                {
                    throw new ArgumentException("Rows count cannot be less than 1.");
                }

                rows = value;
            }
        }

        public int Cols
        {
            get { return cols; }
            set
            {
                if (value < 1)
                {
                    throw new ArgumentException("Cols count cannot be less than 1.");
                }

                cols = value;
            }
        }

        public int this[int row, int col]
        {
            get
            {
                return this.matrix[row, col];
            }

            set
            {
                this.matrix[row, col] = value;
            }
        }

        public static Matrix operator +(Matrix first, Matrix second)
        {
            if (first.Cols != second.Cols || first.Rows != second.Rows)
            {
                throw new Exception("Adding cannot be applied to matrices with different dimensions.");
            }

            Matrix result = new Matrix(first.Rows, first.Cols);

            for (int i = 0; i < first.Rows; i++)
            {
                for (int j = 0; j < first.Cols; j++)
                {
                    result[i, j] = first[i, j] + second[i, j];
                }
            }

            return result;
        }

        public static Matrix operator -(Matrix first, Matrix second)
        {
            if (first.Cols != second.Cols || first.Rows != second.Rows)
            {
                throw new Exception("Substraction cannot be applied to matrices with different dimensions.");
            }

            Matrix result = new Matrix(first.Rows, first.Cols);

            for (int row = 0; row < first.Rows; row++)
            {
                for (int col = 0; col < first.Cols; col++)
                {
                    result[row, col] = first[row, col] - second[row, col];
                }
            }

            return result;
        }

        public static Matrix operator *(Matrix first, Matrix second)
        {
            if (first.Cols != second.Rows || first.Rows != second.Cols)
            {
                throw new Exception("Multiplication cannot be applied to matrices with these dimensions.");
            }

            Matrix result = new Matrix(first.Rows, first.Cols);
            int temp;

            for (int matrixRow = 0; matrixRow < result.Rows; matrixRow++)
            {
                for (int matrixCol = 0; matrixCol < result.Cols; matrixCol++)
                {
                    temp = 0;
                    for (int index = 0; index < result.Cols; index++)
                    {
                        temp += first[matrixRow, index] * second[index, matrixCol];
                    }
                    result[matrixRow, matrixCol] = temp;
                }
            }

            return result;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < this.Rows; i++)
            {
                for (int j = 0; j < this.Cols; j++)
                {
                    sb.Append(matrix[i, j] + " ");
                }

                sb.AppendLine();
            }

            return sb.ToString();
        }
    }

    public static void Main()
    {
        Matrix matrix1 = new Matrix(2, 2);
        matrix1[0, 0] = 2;
        matrix1[0, 1] = 24;
        matrix1[1, 0] = 2;
        matrix1[1, 1] = 24;
        Console.WriteLine(matrix1.ToString());

        Matrix matrix2 = new Matrix(2, 2);
        matrix2[0, 0] = 3;
        matrix2[0, 1] = 25;
        matrix2[1, 0] = 3;
        matrix2[1, 1] = 25;
        Console.WriteLine(matrix2.ToString());

        Console.WriteLine("---------------------");
        Matrix sum = matrix1 + matrix2;
        Console.WriteLine(sum.ToString());
    }
}


text:
#pragma once
#include <aws/pinpoint-email/PinpointEmail_EXPORTS.h>
#include <aws/core/utils/Array.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace PinpointEmail
{
namespace Model
{

  /**
   *
The raw email message.

See Also:
   AWS
   * API Reference

   */
  class AWS_PINPOINTEMAIL_API RawMessage
  {
  public:
    RawMessage();
    RawMessage(Aws::Utils::Json::JsonView jsonValue);
    RawMessage& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The raw email message. The message has to meet the following criteria:

     *

The message has to contain a header and a body, separated by one
     * blank line.

All of the required header fields must be present
     * in the message.

Each part of a multipart MIME message must be
     * formatted properly.

Attachments must be in a file format that
     * Amazon Pinpoint supports.

The entire message must be Base64
     * encoded.

If any of the MIME parts in your message contain
     * content that is outside of the 7-bit ASCII character range, you should encode
     * that content to ensure that recipients' email clients render the message
     * properly.

The length of any single line of text in the message
     * can't exceed 1,000 characters. This restriction is defined in RFC 5321.

     */
    inline const Aws::Utils::ByteBuffer& GetData() const{ return m_data; }

    /**
     *
The raw email message. The message has to meet the following criteria:

     *

The message has to contain a header and a body, separated by one
     * blank line.

All of the required header fields must be present
     * in the message.

Each part of a multipart MIME message must be
     * formatted properly.

Attachments must be in a file format that
     * Amazon Pinpoint supports.

The entire message must be Base64
     * encoded.

If any of the MIME parts in your message contain
     * content that is outside of the 7-bit ASCII character range, you should encode
     * that content to ensure that recipients' email clients render the message
     * properly.

The length of any single line of text in the message
     * can't exceed 1,000 characters. This restriction is defined in RFC 5321.

     */
    inline bool DataHasBeenSet() const { return m_dataHasBeenSet; }

    /**
     *
The raw email message. The message has to meet the following criteria:

     *

The message has to contain a header and a body, separated by one
     * blank line.

All of the required header fields must be present
     * in the message.

Each part of a multipart MIME message must be
     * formatted properly.

Attachments must be in a file format that
     * Amazon Pinpoint supports.

The entire message must be Base64
     * encoded.

If any of the MIME parts in your message contain
     * content that is outside of the 7-bit ASCII character range, you should encode
     * that content to ensure that recipients' email clients render the message
     * properly.

The length of any single line of text in the message
     * can't exceed 1,000 characters. This restriction is defined in RFC 5321.

     */
    inline void SetData(const Aws::Utils::ByteBuffer& value) { m_dataHasBeenSet = true; m_data = value; }

    /**
     *
The raw email message. The message has to meet the following criteria:

     *

The message has to contain a header and a body, separated by one
     * blank line.

All of the required header fields must be present
     * in the message.

Each part of a multipart MIME message must be
     * formatted properly.

Attachments must be in a file format that
     * Amazon Pinpoint supports.

The entire message must be Base64
     * encoded.

If any of the MIME parts in your message contain
     * content that is outside of the 7-bit ASCII character range, you should encode
     * that content to ensure that recipients' email clients render the message
     * properly.

The length of any single line of text in the message
     * can't exceed 1,000 characters. This restriction is defined in RFC 5321.

     */
    inline void SetData(Aws::Utils::ByteBuffer&& value) { m_dataHasBeenSet = true; m_data = std::move(value); }

    /**
     *
The raw email message. The message has to meet the following criteria:

     *

The message has to contain a header and a body, separated by one
     * blank line.

All of the required header fields must be present
     * in the message.

Each part of a multipart MIME message must be
     * formatted properly.

Attachments must be in a file format that
     * Amazon Pinpoint supports.

The entire message must be Base64
     * encoded.

If any of the MIME parts in your message contain
     * content that is outside of the 7-bit ASCII character range, you should encode
     * that content to ensure that recipients' email clients render the message
     * properly.

The length of any single line of text in the message
     * can't exceed 1,000 characters. This restriction is defined in RFC 5321.

     */
    inline RawMessage& WithData(const Aws::Utils::ByteBuffer& value) { SetData(value); return *this;}

    /**
     *
The raw email message. The message has to meet the following criteria:

     *

The message has to contain a header and a body, separated by one
     * blank line.

All of the required header fields must be present
     * in the message.

Each part of a multipart MIME message must be
     * formatted properly.

Attachments must be in a file format that
     * Amazon Pinpoint supports.

The entire message must be Base64
     * encoded.

If any of the MIME parts in your message contain
     * content that is outside of the 7-bit ASCII character range, you should encode
     * that content to ensure that recipients' email clients render the message
     * properly.

The length of any single line of text in the message
     * can't exceed 1,000 characters. This restriction is defined in RFC 5321.

     */
    inline RawMessage& WithData(Aws::Utils::ByteBuffer&& value) { SetData(std::move(value)); return *this;}

  private:

    Aws::Utils::ByteBuffer m_data;
    bool m_dataHasBeenSet;
  };

} // namespace Model
} // namespace PinpointEmail
} // namespace Aws


text:
CLI
===

PSX provides several commands which help to rapidly develop and debug PSX
applications. In the following we will describe the available commands:

API
---

It is possible to automatically generate an API controller from a specification.
The following command reads the `/acme/endpoint` and generates the appropriated
controller.

.. code::

    $ vendor/bin/psx api spec.raml php

Schema
------

Through the schema command it is possible to generate a POPO based on a
jsonschema specification.

.. code::

    $ vendor/bin/psx schema schema.json php


text:
var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
// NOTE: prefer setImmediate to nextTick for proper recursion yielding.
// see https://github.com/js-platform/filer/pull/24
var asyncCallback = require('../../lib/async.js').setImmediate;

/**
 * Make shared in-memory DBs possible when using the same name.
 */
var createDB = (function() {
  var pool = {};
  return function getOrCreate(name) {
    if(!pool.hasOwnProperty(name)) {
      pool[name] = {};
    }
    return pool[name];
  };
}());

function MemoryContext(db, readOnly) {
  this.readOnly = readOnly;
  this.objectStore = db;
}

MemoryContext.prototype.clear = function(callback) {
  if(this.readOnly) {
    asyncCallback(function() {
      callback("[MemoryContext] Error: write operation on read only context");
    });
    return;
  }
  var objectStore = this.objectStore;
  Object.keys(objectStore).forEach(function(key){
    delete objectStore[key];
  });
  asyncCallback(callback);
};

// Memory context doesn't care about differences between Object and Buffer
MemoryContext.prototype.getObject =
MemoryContext.prototype.getBuffer =
function(key, callback) {
  var that = this;
  asyncCallback(function() {
    callback(null, that.objectStore[key]);
  });
};
MemoryContext.prototype.putObject =
MemoryContext.prototype.putBuffer =
function(key, value, callback) {
  if(this.readOnly) {
    asyncCallback(function() {
      callback("[MemoryContext] Error: write operation on read only context");
    });
    return;
  }
  this.objectStore[key] = value;
  asyncCallback(callback);
};

MemoryContext.prototype.delete = function(key, callback) {
  if(this.readOnly) {
    asyncCallback(function() {
      callback("[MemoryContext] Error: write operation on read only context");
    });
    return;
  }
  delete this.objectStore[key];
  asyncCallback(callback);
};

function Memory(name) {
  this.name = name || FILE_SYSTEM_NAME;
}
Memory.isSupported = function() {
  return true;
};

Memory.prototype.open = function(callback) {
  this.db = createDB(this.name);
  asyncCallback(callback);
};
Memory.prototype.getReadOnlyContext = function() {
  return new MemoryContext(this.db, true);
};
Memory.prototype.getReadWriteContext = function() {
  return new MemoryContext(this.db, false);
};

module.exports = Memory;


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebCodeFirst.Models;

namespace WebCodeFirst.Controllers
{
    public class ClientesController : Controller
    {
        private ContextoAplicacion db = new ContextoAplicacion();

        // GET: Clientes
        public ActionResult Index()
        {
            var consulta = from c in db.Clientes
                           select new
                           {
                               id=c.ClienteId,
                               NombreCliente=c.Nombre,
                               Edad=c.Edad,
                               Tipo=c.Tipo.NombreTipo
                           };

            return Json(consulta.ToList(), JsonRequestBehavior.AllowGet);
            //return View();
        }

        public string Crear(int idTipo,string nombreCliente,int edad)
        {
            if (nombreCliente != null)
            {
                var tipoCliente = db.Tipos.Find(idTipo);
                if (tipoCliente != null)
                {
                    Cliente cliente = new Cliente();
                    cliente.Nombre = nombreCliente;
                    cliente.Edad = edad;
                    cliente.Tipo = tipoCliente;
                    //db.Clientes.Add(cliente);
                    db.Entry(cliente).State = EntityState.Added;
                    db.SaveChanges();
                    return "El registro se ha agregado";
                }
                else
                    return "El tipo de cliente no se encontro";
            }
            else
                return "No se proporciono el nombre del cliente";
        }
    }
}


text:
module SchemaToScaffold
  class Attribute

    attr_reader :name, :type

    def initialize(name, type)
      @name, @type = name, type
    end

    def to_script
      "#{name}:#{type}" unless ["created_at","updated_at"].include?(name)
    end

    def self.parse(attribute)
      match = attribute.match(/t\.(\w+)\s+"(\w+)"/)
      if match
        name = match.captures[1].sub(/_id$/, "")
        type = $&.nil? ? match.captures[0] : "references"
        Attribute.new(name, type)
      end
    end

  end
end


text:
This is a binding of the [z80e](https://github.com/KnightOS/z80e), but compiled into JavaScript using emscripten. To make it easy to use, a OpenTI-like wrapper will be written around it. This will also be the holding place of the HTML-based TI emulator (and maybe even TI IDE, later!).

## Help, Bugs, Feedback

If you need help with KnightOS, want to keep up with progress, chat with
developers, or ask any other questions about KnightOS, you can hang out in the
IRC channel: #knightos on irc.libera.chat

To report bugs, please create [a GitHub issue](https://github.com/KnightOS/KnightOS/issues/new) or contact us on IRC.

If you'd like to contribute to the project, please see the [contribution guidelines](http://www.knightos.org/contributing).


text:
layout: page
title: SLIDES
---

{% include presentations.html %}


text:
package org.heigit.ors.fastisochrones;

import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntObjectHashMap;
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntSet;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.graphhopper.routing.util.DefaultEdgeFilter;
import com.graphhopper.routing.util.EdgeFilter;
import com.graphhopper.storage.GraphHopperStorage;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.util.EdgeExplorer;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.PointList;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.index.quadtree.Quadtree;
import org.heigit.ors.fastisochrones.partitioning.storage.CellStorage;
import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage;
import org.heigit.ors.isochrones.builders.concaveballs.PointItemVisitor;
import org.opensphere.geometry.algorithm.ConcaveHull;

import java.util.*;
import java.util.stream.Collectors;

import static org.heigit.ors.fastisochrones.partitioning.FastIsochroneParameters.getMaxCellNodesNumber;
import static org.heigit.ors.fastisochrones.partitioning.FastIsochroneParameters.isSupercellsEnabled;

/**
 * Calculates Outlines (Contour) of cells.
 * Contours are concave hulls of a given set of points.
 * Additionally, contours for super cells can be created.
 * Super cells are again grouped into another set of super super cells.
 * Super cells contain a maximum amount of base cells given by the hierarchy level parameter.
 * Usually, there will be fewer base cells in a super cell, as some branches of the partitioning end earlier than others.
 * <p>
 *
 * @author Hendrik Leuschner
 */
public class Contour {
    //Length that a polygon edge has to have in m to be split into smaller subedges so that there are no artifacts from later concave hull calculations with it
    private static final int MIN_EDGE_LENGTH = 125;
    private static final int MAX_EDGE_LENGTH = Integer.MAX_VALUE;
    //This means that one supercell can contain at most 2^3 = 8 base cells.
    private static final int SUPER_CELL_HIERARCHY_LEVEL = 2;
    //This means that one supersupercell can contain at most 2^(3 + 2) = 32 base cells.
    private static final int SUPER_SUPER_CELL_HIERARCHY_LEVEL = 2; // level above super cell level
    private static final double CONCAVE_HULL_THRESHOLD = 0.006;
    private static final double BUFFER_SIZE = 0.0003;
    protected NodeAccess nodeAccess;
    protected GraphHopperStorage ghStorage;
    private IsochroneNodeStorage isochroneNodeStorage;
    private CellStorage cellStorage;

    public Contour(GraphHopperStorage ghStorage, NodeAccess nodeAccess, IsochroneNodeStorage isochroneNodeStorage, CellStorage cellStorage) {
        this.ghStorage = ghStorage;
        this.nodeAccess = nodeAccess;
        this.isochroneNodeStorage = isochroneNodeStorage;
        this.cellStorage = cellStorage;
    }

    /*
    Calculates the distance between two coordinates in meters
     */
    public static double distance(double lat1, double lat2, double lon1,
                                  double lon2) {

        final int R = 6371; // Radius of the earth

        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distance = R * c * 1000; // convert to meters

        distance = Math.pow(distance, 2);

        return Math.sqrt(distance);
    }

    /**
     * Calculates Contours of base cells and (if enabled) supercells and stores the data in cellStorage
     */
    public void calculateContour() {
        handleBaseCells();
        cellStorage.flush();
        IntObjectMap<IntHashSet> superCells = handleSuperCells();
        cellStorage.storeContourPointerMap();
        if (isSupercellsEnabled())
            cellStorage.storeSuperCells(superCells);
        cellStorage.setContourPrepared(true);
        cellStorage.flush();
    }

    /**
     * Create contour for each base cell and store it
     */
    private void handleBaseCells() {
        for (IntCursor cellId : isochroneNodeStorage.getCellIds()) {
            List<Coordinate> coordinates = createCoordinates(cellId.value);
            LineString ring = createContour(coordinates, cellStorage.getNodesOfCell(cellId.value).size() < 1000);
            if (ring == null || ring.getNumPoints() < 2) {
                cellStorage.setCellContourOrder(cellId.value, new ArrayList<>(), new ArrayList<>());
                continue;
            }
            expandAndSaveContour(cellId.value, ring);
        }
    }

    /**
     * Create Contour for each supercell and store it
     * Create supercells for better querytime performance
     * Current implementation supports 2 levels of supercells. Calculated individually
     * For each super(super)cell, we need to know the corresponding basecells (to get the contour from storage)
     * and the corresponding subcells (these are supercells for supersupercells)
     *
     * @return Mapping of supercell Id -> Set of subcell ids
     */
    private IntObjectMap<IntHashSet> handleSuperCells() {
        IntObjectMap<IntHashSet> superCells = new IntObjectHashMap<>();
        if (isSupercellsEnabled()) {
            superCells = identifySuperCells(isochroneNodeStorage.getCellIds(), SUPER_CELL_HIERARCHY_LEVEL, true);
            IntObjectMap<IntHashSet> superSuperCells = identifySuperCells(new IntHashSet(superCells.keys()), SUPER_SUPER_CELL_HIERARCHY_LEVEL, false);

            IntObjectMap<IntHashSet> superCellsToBaseCells = getBaseCellsOfSuperSuperCells(superSuperCells, superCells);
            superCellsToBaseCells.putAll(superCells);
            superCells.putAll(superSuperCells);

            //Calculate the concave hull for all super cells and super super cells
            for (IntObjectCursor<IntHashSet> superCell : superCellsToBaseCells) {
                List<Coordinate> superCellCoordinates = createSuperCellCoordinates(superCell.value);
                LineString ring = createContour(superCellCoordinates, false);
                if (ring == null || ring.getNumPoints() < 2) {
                    cellStorage.setCellContourOrder(superCell.key, new ArrayList<>(), new ArrayList<>());
                    continue;
                }
                expandAndSaveContour(superCell.key, ring);
            }
        }
        return superCells;
    }

    /**
     * From the superCells Map get all the base cells for each super super cell
     *
     * @param superSuperCells the super super cells for which to get the base cells
     * @param superCells      the mapping of super cells to base cells
     * @return mapping of super super cells to base cells
     */
    private IntObjectMap<IntHashSet> getBaseCellsOfSuperSuperCells(IntObjectMap<IntHashSet> superSuperCells, IntObjectMap<IntHashSet> superCells) {
        IntObjectMap<IntHashSet> baseCellsOfSuperSuperCells = new IntObjectHashMap<>();
        for (IntObjectCursor<IntHashSet> superSuperCell : superSuperCells) {
            IntHashSet newSuperCell = new IntHashSet();
            for (IntCursor cell : superSuperCell.value)
                newSuperCell.addAll(superCells.get(cell.value));
            baseCellsOfSuperSuperCells.put(superSuperCell.key, newSuperCell);
        }
        return baseCellsOfSuperSuperCells;
    }

    /**
     * For a super cell: get the base cell coordinates from storage.
     * Create a sorted list of coordinates
     *
     * @param superCell super cell for which to create the coordinates
     * @return list of contour coordinates of base cells
     */
    private List<Coordinate> createSuperCellCoordinates(IntHashSet superCell) {
        List<Coordinate> superCellCoordinates = new ArrayList<>(superCell.size() * 10);
        for (IntCursor subcell : superCell) {
            List<Double> subCellContour = cellStorage.getCellContourOrder(subcell.value);
            int j = 0;
            while (j < subCellContour.size()) {
                double lat = subCellContour.get(j);
                j++;
                double lon = subCellContour.get(j);
                j++;
                superCellCoordinates.add(new Coordinate(lon, lat));
            }
        }
        //Need to sort the coordinates, because they will be added to a search tree
        //The order of insertion changes the search tree coordinates and we want consistency between runs
        Collections.sort(superCellCoordinates);
        return superCellCoordinates;
    }

    private Geometry concHullOfNodes(List<Coordinate> coordinates, boolean useHighDetail) {
        double defaultVisitorThreshold = useHighDetail ? 0.00005 : 0.0025;
        double defaultSearchWidth = 0.0008;
        double defaulPointWidth = 0.005;

        List<Coordinate> points = new ArrayList<>((int) (1 / 20.0 * coordinates.size()));
        PointItemVisitor visitor = new PointItemVisitor(0, 0, defaultVisitorThreshold);
        Quadtree qtree = new Quadtree();
        Envelope searchEnv = new Envelope();
        TreeSet<Coordinate> treeSet = new TreeSet<>();

        for (Coordinate coordinate : coordinates)
            addPoint(visitor, points, qtree, searchEnv, treeSet, coordinate.x, coordinate.y, defaultSearchWidth, defaulPointWidth, true);

        GeometryFactory geomFactory = new GeometryFactory();
        int size = points.size();
        Geometry[] geometries = new Geometry[size];
        int g = 0;
        for (Coordinate point : points)
            geometries[g++] = geomFactory.createPoint(point);
        GeometryCollection treePoints = new GeometryCollection(geometries, geomFactory);

        ConcaveHull ch = new ConcaveHull(treePoints, CONCAVE_HULL_THRESHOLD, false);
        return ch.getConcaveHull();
    }

    private Boolean addPoint(PointItemVisitor visitor,
                             List<Coordinate> points,
                             Quadtree tree,
                             Envelope searchEnv,
                             Set<Coordinate> treeSet,
                             double lon,
                             double lat,
                             double searchWidth,
                             double pointWidth,
                             boolean checkNeighbours) {
        if (checkNeighbours) {
            visitor.setPoint(lon, lat);
            searchEnv.init(lon - searchWidth, lon + searchWidth, lat - searchWidth, lat + searchWidth);
            tree.query(searchEnv, visitor);
            if (!visitor.isNeighbourFound()) {
                Coordinate p = new Coordinate(lon, lat);

                if (!treeSet.contains(p)) {
                    Envelope env = new Envelope(lon - pointWidth, lon + pointWidth, lat - pointWidth, lat + pointWidth);
                    tree.insert(env, p);
                    points.add(p);
                    treeSet.add(p);

                    return true;
                }
            }
        } else {
            Coordinate p = new Coordinate(lon, lat);
            if (!treeSet.contains(p)) {
                Envelope env = new Envelope(lon - pointWidth, lon + pointWidth, lat - pointWidth, lat + pointWidth);
                tree.insert(env, p);
                points.add(p);
                treeSet.add(p);

                return true;
            }
        }

        return false;
    }

    /**
     * Find the supercells of base cells.
     * For a given cellId, find cells that are connected to it via cellId bitshifting
     * E.g. cells 100 and 101 are subcells of cell 10
     *
     * @param cellIds        cellIds whose super cells should be found
     * @param hierarchyLevel how many bits should be pruned from the id to find a supercell. Influences size of super cell
     * @param isPrimary      Whether super cells are found for base cells or for existing super cells
     * @return a map of supercellId to base cell ids
     */
    private IntObjectMap<IntHashSet> identifySuperCells(IntSet cellIds, int hierarchyLevel, boolean isPrimary) {
        //Account for the subcell division in InertialFlow final step
        int maxId = createMaxId(cellIds);

        IntHashSet visitedCells = new IntHashSet();
        IntObjectMap<IntHashSet> superCells = new IntObjectHashMap<>();
        //Sorting the ids creates better supercells as close Ids are also geographically closer
        List<Integer> orderedCellIds = Arrays.stream(cellIds.toArray()).boxed().sorted().collect(Collectors.toList());
        for (int cellId : orderedCellIds) {
            if (visitedCells.contains(cellId))
                continue;
            //These checks are only needed and possible for supercells built from baseCells and not built from supercells
            if (isPrimary && !isValidBaseCell(cellIds, cellId))
                continue;

            int motherId = cellId >> hierarchyLevel;
            //This cell is too high up in the hierarchy, so we need to adapt the hierarchy level and id
            while (motherId == 0) {
                hierarchyLevel -= 1;
                motherId = cellId >> hierarchyLevel;
            }

            IntHashSet superCell = new IntHashSet();

            createSuperCell(cellIds, visitedCells, superCell, maxId, motherId, isPrimary);
            for (IntCursor cell : superCell)
                visitedCells.add(cell.value);
            if (superCell.size() > 0)
                superCells.put(motherId, superCell);
        }
        return superCells;
    }

    private int createMaxId(IntSet cellIds) {
        int maxId = -1;
        for (IntCursor cellId : cellIds)
            if (cellId.value > maxId)
                maxId = cellId.value;
        return maxId;
    }

    /**
     * Check whether a base cell is valid. It is valid if no cells were disconnected from it and if it is no disconnected cell itself
     *
     * @param cellIds All existing cellIds
     * @param cellId  the cellId to check
     * @return isValid
     */
    private boolean isValidBaseCell(IntSet cellIds, int cellId) {
        //Check if it is part of a separated cell: Has daughter?
        if (cellIds.contains(cellId << 1))
            return false;
        return !isDisconnectedCell(cellIds, cellId);
    }

    private boolean isDisconnectedCell(IntSet cellIds, int cellId) {
        //If it has sister, check if their combined size is smaller than minimum cell size -> disconnected
        return (cellIds.contains(cellId ^ 1) && cellStorage.getNodesOfCell(cellId).size()
                + cellStorage.getNodesOfCell(cellId ^ 1).size()
                < getMaxCellNodesNumber());
    }

    /**
     * Recursively iterate over cellIds to collect all cells that belong to a super cell id
     *
     * @param cellIds      all cellIds
     * @param visitedCells cellIds that have already been added to a supercell
     * @param superCell    the super cell to which other cell ids are added
     * @param maxId        maximum possible search id
     * @param currentCell  the cell currently examined
     * @param isPrimary    true if super cell is built from base cells
     */
    private void createSuperCell(IntSet cellIds, IntHashSet visitedCells, IntHashSet superCell, int maxId, int currentCell, boolean isPrimary) {
        if (currentCell > maxId)
            return;
        //Cells should be only part of one supercell
        if (visitedCells.contains(currentCell))
            return;
        if (isPrimary && cellIds.contains(currentCell) && !isValidBaseCell(cellIds, currentCell))
            return;

        if (!cellIds.contains(currentCell)) {
            createSuperCell(cellIds, visitedCells, superCell, maxId, currentCell << 1, isPrimary);
            createSuperCell(cellIds, visitedCells, superCell, maxId, currentCell << 1 | 1, isPrimary);
        } else {
            superCell.add(currentCell);
        }
    }

    /**
     * Get all coordinates of nodes and edges in a cell
     *
     * @param cellId the cell id
     * @return list of coordinates that represent all edges and nodes in the cell
     */
    private List<Coordinate> createCoordinates(int cellId) {
        IntHashSet cellNodes = cellStorage.getNodesOfCell(cellId);
        int initialSize = cellNodes.size();
        List<Coordinate> coordinates = new ArrayList<>(initialSize);
        EdgeFilter edgeFilter = DefaultEdgeFilter.allEdges(ghStorage.getEncodingManager().fetchEdgeEncoders().get(0));

        EdgeExplorer explorer = ghStorage.getBaseGraph().createEdgeExplorer(edgeFilter);
        EdgeIterator iter;

        IntHashSet visitedEdges = new IntHashSet();
        PointList towerCoordinates = new PointList(cellNodes.keys.length, false);
        for (IntCursor node : cellNodes) {
            towerCoordinates.add(ghStorage.getNodeAccess().getLat(node.value), ghStorage.getNodeAccess().getLon(node.value));
        }
        addLatLon(towerCoordinates, coordinates);
        for (IntCursor node : cellNodes) {
            iter = explorer.setBaseNode(node.value);
            while (iter.next()) {
                if (visitedEdges.contains(iter.getEdge())
                        || !cellNodes.contains(iter.getAdjNode())
                        || !edgeFilter.accept(iter))
                    continue;
                visitedEdges.add(iter.getEdge());
                splitAndAddLatLon(iter.fetchWayGeometry(3), coordinates, MIN_EDGE_LENGTH, MAX_EDGE_LENGTH);
            }
        }
        //Remove duplicates
        coordinates = coordinates.stream()
                .distinct()
                .collect(Collectors.toList());
        //Need to sort the coordinates, because they will be added to a search tree
        //The order of insertion changes the search tree coordinates and we want consistency between runs
        try {
            Collections.sort(coordinates);
        } catch (Exception e) {
            //This happens in less than 1% of the runs and I have not figured out why.
            //It has no real impact as sorting is only for consistency of outlines, not quality
        }
        return coordinates;
    }

    private LineString createContour(List<Coordinate> coordinates, boolean useHighDetail) {
        try {
            Geometry geom = concHullOfNodes(coordinates, useHighDetail);
            Polygon poly = (Polygon) geom;
            poly.normalize();
            return poly.getExteriorRing();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Fill the edges of the polygon representing the contour so that even long straights are represented by regular points.
     * If these long edges were not split, it would lead to "holes" in the edge that can be misinterpreted when building the overall isochrone from multiple contours
     *
     * @param cellId cellId of the contour
     * @param ring   LineString representing the contour in order
     */
    private void expandAndSaveContour(int cellId, LineString ring) {
        List<Double> hullLatitudes = new ArrayList<>(ring.getNumPoints());
        List<Double> hullLongitudes = new ArrayList<>(ring.getNumPoints());
        for (int i = 0; i < ring.getNumPoints(); i++) {
            // Add coordinates to storage, but make sure there are enough on long edges by splitting
            hullLatitudes.add(ring.getPointN(i).getY());
            hullLongitudes.add(ring.getPointN(i).getX());

            if (i < ring.getNumPoints() - 1) {
                splitEdge(ring.getPointN(i),
                        ring.getPointN(i + 1),
                        hullLatitudes,
                        hullLongitudes,
                        MIN_EDGE_LENGTH,
                        MAX_EDGE_LENGTH);
            }
        }
        cellStorage.setCellContourOrder(cellId, hullLatitudes, hullLongitudes);
    }

    public Contour setGhStorage(GraphHopperStorage ghStorage) {
        this.ghStorage = ghStorage;
        return this;
    }

    /**
     * Splits a line between two points of the distance is longer than a limit
     *
     * @param point0     point0 of line
     * @param point1     point1 of line
     * @param latitudes  latitudes to which the new coordinates are added
     * @param longitudes longitudes to which th enew coordinates are added
     * @param minlim     limit above which the edge will be split (in meters)
     * @param maxlim     limit above which the edge will NOT be split anymore (in meters)
     */
    private void splitEdge(Point point0, Point point1, List<Double> latitudes, List<Double> longitudes, double minlim, double maxlim) {
        double lat0 = point0.getY();
        double lon0 = point0.getX();
        double lat1 = point1.getY();
        double lon1 = point1.getX();
        double dist = distance(lat0, lat1, lon0, lon1);

        if (dist > minlim && dist < maxlim) {
            int n = (int) Math.ceil(dist / minlim);
            for (int i = 1; i < n; i++) {
                latitudes.add(lat0 + i * (lat1 - lat0) / n);
                longitudes.add(lon0 + i * (lon1 - lon0) / n);
            }
        }
    }

    private void splitAndAddLatLon(PointList newCoordinates, List<Coordinate> existingCoordinates, double minlim, double maxlim) {
        for (int i = 0; i < newCoordinates.size() - 1; i++) {
            double lat0 = newCoordinates.getLat(i);
            double lon0 = newCoordinates.getLon(i);
            double lat1 = newCoordinates.getLat(i + 1);
            double lon1 = newCoordinates.getLon(i + 1);
            double dist = distance(lat0, lat1, lon0, lon1);
            double dx = (lon0 - lon1);
            double dy = (lat0 - lat1);
            double normLength = Math.sqrt((dx * dx) + (dy * dy));

            int n = (int) Math.ceil(dist / minlim);
            double scale = BUFFER_SIZE / normLength;

            double dx2 = -dy * scale;
            double dy2 = dx * scale;
            if (i != 0) {
                existingCoordinates.add(new Coordinate(lon0 + dx2, lat0 + dy2));
                existingCoordinates.add(new Coordinate(lon0 - dx2, lat0 - dy2));
            }

            if (dist > minlim && dist < maxlim) {
                for (int j = 1; j < n; j++) {
                    existingCoordinates.add(new Coordinate(lon0 + j * (lon1 - lon0) / n + dx2, lat0 + j * (lat1 - lat0) / n + dy2));
                    existingCoordinates.add(new Coordinate(lon0 + j * (lon1 - lon0) / n - dx2, lat0 + j * (lat1 - lat0) / n - dy2));
                }
            }
        }
    }

    private void addLatLon(PointList newCoordinates, List<Coordinate> existingCoordinates) {
        if (newCoordinates.isEmpty())
            return;
        for (int i = 0; i < newCoordinates.size() - 1; i++) {
            double lat0 = newCoordinates.getLat(i);
            double lon0 = newCoordinates.getLon(i);
            existingCoordinates.add(new Coordinate(lon0 + BUFFER_SIZE, lat0 + BUFFER_SIZE));
            existingCoordinates.add(new Coordinate(lon0 - BUFFER_SIZE, lat0 - BUFFER_SIZE));
        }
    }
}


text:
using System;
using System.Collections;
using System.Data;

namespace Mono.Data.SqlExpressions {
	internal class Like : UnaryExpression {
		string pattern;
		bool openStart, openEnd;

		public Like (IExpression e, string pattern) : base (e)
		{
			string original = pattern;
			int len = pattern.Length;
			openStart = (pattern[0] == '*' || pattern[0] == '%');
			openEnd = (pattern[len - 1] == '*' || pattern[len - 1] == '%');

			pattern = pattern.Trim ('*', '%');
			pattern = pattern.Replace ("[*]", "[[0]]");
			pattern = pattern.Replace ("[%]", "[[1]]");
			if (pattern.IndexOf('*') != -1 || pattern.IndexOf('%') != -1)
				throw new EvaluateException (String.Format ("Pattern '{0}' is invalid.", original));
			pattern = pattern.Replace ("[[0]]", "*");
			pattern = pattern.Replace ("[[1]]", "%");
			pattern = pattern.Replace ("[[]", "[");
			pattern = pattern.Replace ("[]]", "]");
			this.pattern = pattern;
		}

		override public object Eval (DataRow row)
		{
			object o = expr.Eval (row);
			if (o == DBNull.Value)
				return o;
			string str = (string)o;
			string pattern = this.pattern;
			if (!row.Table.CaseSensitive) {
				str = str.ToLower();
				pattern = pattern.ToLower();
			}

			int idx = str.IndexOf (pattern);
			if (idx == -1)
				return false;

			return (idx == 0 || openStart) && (idx + pattern.Length == str.Length || openEnd);
		}
	}
}


text:
package com.netflix.servo.publish.graphite;

import com.netflix.servo.Metric;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.tag.Tag;
import com.netflix.servo.tag.TagList;

/**
 * A basic graphite naming convention that handles both "native servo" objects
 * and standard JMX objects pulled out of the JMX registry.
 */
public class BasicGraphiteNamingConvention implements GraphiteNamingConvention {

  private static final String JMX_DOMAIN_KEY = "JmxDomain";

  @Override
  public String getName(Metric metric) {
    MonitorConfig config = metric.getConfig();
    TagList tags = config.getTags();

    Tag domainTag = tags.getTag(JMX_DOMAIN_KEY);
    if (domainTag != null) { // jmx metric
      return handleJmxMetric(config, tags);
    } else {
      return handleMetric(config, tags);
    }
  }

  private String handleMetric(MonitorConfig config, TagList tags) {
    String type = cleanValue(tags.getTag(DataSourceType.KEY), false);
    String instanceName = cleanValue(tags.getTag("instance"), false);
    String name = cleanupIllegalCharacters(config.getName(), false);
    String statistic = cleanValue(tags.getTag("statistic"), false);

    StringBuilder nameBuilder = new StringBuilder();
    if (type != null) {
      nameBuilder.append(type).append(".");
    }
    if (instanceName != null) {
      nameBuilder.append(instanceName).append(".");
    }
    if (name != null) {
      nameBuilder.append(name).append(".");
    }
    if (statistic != null) {
      nameBuilder.append(statistic).append(".");
    }
    // remove trailing "."
    nameBuilder.deleteCharAt(nameBuilder.lastIndexOf("."));
    return nameBuilder.toString();
  }

  private String handleJmxMetric(MonitorConfig config, TagList tags) {
    String domain = cleanValue(tags.getTag(JMX_DOMAIN_KEY), true);
    String type = cleanValue(tags.getTag("Jmx.type"), false);
    String instanceName = cleanValue(tags.getTag("Jmx.instance"), false);
    String name = cleanValue(tags.getTag("Jmx.name"), false);
    String fieldName = cleanupIllegalCharacters(config.getName(), false);

    StringBuilder nameBuilder = new StringBuilder();
    nameBuilder.append(domain).append(".");
    if (type != null) {
      nameBuilder.append(type).append(".");
    }
    if (instanceName != null) {
      nameBuilder.append(instanceName).append(".");
    }
    if (name != null) {
      nameBuilder.append(name).append(".");
    }
    if (fieldName != null) {
      nameBuilder.append(fieldName).append(".");
    }
    // remove trailing "."
    nameBuilder.deleteCharAt(nameBuilder.lastIndexOf("."));
    return nameBuilder.toString();
  }

  private String cleanValue(Tag tag, boolean allowPeriodsInName) {
    if (tag == null) {
      return null;
    }

    return cleanupIllegalCharacters(tag.getValue(), allowPeriodsInName);
  }

  private String cleanupIllegalCharacters(String s, boolean allowPeriodsInName) {
    String legalName = s.replace(" ", "_");
    if (!allowPeriodsInName) {
      legalName = legalName.replace(".", "_");
    }
    return legalName;
  }
}


text:
require 'vulcanize'
require 'minitest/autorun'
require 'minitest/reporters'

reporter_options = {color: true, slow_count: 5}
Minitest::Reporters.use! [Minitest::Reporters::DefaultReporter.new(reporter_options)]

module Vulcanize
  class TestType
    def initialize(value)
      fail ArgumentError unless value == 'valid'
    end
  end
end


text:
import React, { Component } from 'react'
import {
    Text,
    View,
    Image
} from 'react-native'
import { ScrollableTabBar }
       from 'react-native-scrollable-tab-view'
import { computed } from 'mobx'
import { observer } from 'mobx-react/native'

// Importing Pages
import { DiscoverPage } from './screens//DiscoverPage'
import { BarPage } from './screens/BarPage'
import { MenuPage } from './screens/MenuPage'
import { OrderPage } from './screens/OrderPage'

import { handleBackButton } from './components/AndroidBackButton'
import { SideMenu } from './components/sidemenu/SideMenu'
import { ControlPanel } from './components/sidemenu/ControlPanel'
import { TabView } from './components/Tabs'
import { Loader } from './components/Page'
import { NotificationBar } from './components/notification/NotificationBar'

import { store, barStore, tabStore } from './model/store'
import * as _ from './utils/curry'

const { log, assert } = _.utils('/Main')

/* Do not allow font scaling */
Text.defaultProps.allowFontScaling = false

const styles = {
    title: {
        color: '#E72D6B',
        fontWeight: 'bold'
    },
    searchIcon: {
        width: 30,
        height: 30
    }
}

@observer
export class Main extends Component {
    static route = {
        navigationBar: {
            title: 'QDodger',
            backgroundColor: '#fff',
            titleStyle: styles.title
        }
    }

    @computed get barSelected () {
        return !!barStore.barID || tabStore.currentPage !== 0
    }

    render = () => {
        if (!store.initialized) {
            return <Loader />
        }
        if (!this.barSelected) {
            return <DiscoverPage />
        }
        return (
            <View style={{flex: 1}}>
                <NotificationBar />
                { this.barSelected ?
                    <SideMenu content={<ControlPanel />}>
                        <View style={{flex: 1, flexDirection: 'row'}}>
                            {/*
                            <Checkout />
                            <ReceiptModal />
                            */}
                            <TabView>
                                <View tabLabel='Discover' style={{flex: 1}}>
                                    <DiscoverPage />
                                </View>
                                <View tabLabel='Bar' style={{flex: 1}}>
                                    <BarPage />
                                </View>
                                <View tabLabel='Menu' style={{flex: 1}}>
                                    <MenuPage />
                                </View>
                                <View tabLabel='Order' style={{flex: 1}}>
                                    <OrderPage />
                                </View>
                            </TabView>
                        </View>
                    </SideMenu> :
                    <DiscoverPage />
                }
            </View>
        )
    }

    // renderTabBar = () => <DefaultTabBar />
    // renderTabBar = () => <ScrollableTabBar />
}

log('----------------------------------------------------------------')

// Promise.onPossiblyUnhandledRejection(function(error){
//     throw error
// })

// By default the choice is not to propogate errors from Promises...
require('promise/setimmediate/rejection-tracking').enable({
    allRejections: true,
    onUnhandled: (id, error) => {
        console.error(error)
    }
})

/* Initialize

Note: Do not initialize in componentDidMount, as it may be called multiple times.
*/
handleBackButton()
store.initialize()


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var skus = require('../../app/controllers/skus.server.controller');

	// Skus Routes
	app.route('/skus')
		.get(skus.list)
		.post(users.requiresLogin, skus.create);

	app.route('/skus/:skuId')
		.get(skus.read)
		.put(users.requiresLogin, skus.hasAuthorization, skus.update)
		.delete(users.requiresLogin, skus.hasAuthorization, skus.delete);

	// Finish by binding the Sku middleware
	app.param('skuId', skus.skuByID);
};


text:
@interface HeadScrollView : UIScrollView
@property (nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSMutableArray *bannerList;
- (instancetype)initWithFrame:(CGRect)frame andbannerList:(NSMutableArray *)bannerList;

@end


text:
import Terminal from './terminal';

export default () => new Terminal(document.getElementById('terminal'));


text:
package service

import (
	"github.com/brutella/hc/characteristic"
)

const TypeLightSensor = "84"

type LightSensor struct {
	*Service

	CurrentAmbientLightLevel *characteristic.CurrentAmbientLightLevel
}

func NewLightSensor() *LightSensor {
	svc := LightSensor{}
	svc.Service = New(TypeLightSensor)

	svc.CurrentAmbientLightLevel = characteristic.NewCurrentAmbientLightLevel()
	svc.AddCharacteristic(svc.CurrentAmbientLightLevel.Characteristic)

	return &svc
}


text:
package de.uniwue.info3.tablevisor.upperlayer;

import de.uniwue.info3.tablevisor.config.UpperLayerEndpointConfig;
import de.uniwue.info3.tablevisor.core.TableVisor;
import de.uniwue.info3.tablevisor.message.TVMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.projectfloodlight.openflow.protocol.*;

@ChannelHandler.Sharable
public class UpperOpenFlowMessageHandler extends ChannelInboundHandlerAdapter implements IUpperLayerMessageHandler {
	private static final Logger logger = LogManager.getLogger();

	private UpperLayerEndpointConfig cfg;
	private UpperOpenFlowEndpoint parent;

	public UpperOpenFlowMessageHandler(UpperLayerEndpointConfig cfg, UpperOpenFlowEndpoint parent) {
		this.cfg = cfg;
		this.parent = parent;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		TVMessage tvMsg = (TVMessage) msg;

		// Directly handle HELLO and ECHO reqeusts
		if (tvMsg.getOFMessage().getType() == OFType.HELLO) {
			return;
		}
		if (tvMsg.getOFMessage().getType() == OFType.ECHO_REQUEST) {
			sendEchoReply(tvMsg);
			return;
		}

		logger.trace("OFMessage read from control channel: {}", tvMsg.getOFMessage().toString());

		TableVisor.getInstance().getTvToControllerLayer().allToDataPlane(tvMsg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.error("{} - Exception caught by socket", cfg.name, cause);
		//ctx.close();
	}

	@Override
	public void send(TVMessage msg) {
		parent.getChannel().writeAndFlush(msg);
	}

	private void sendEchoReply(TVMessage msg) {
		OFEchoRequest orig = msg.getOFMessage();
		OFEchoReply rep = OFFactories.getFactory(OFVersion.OF_13).buildEchoReply()
				.setXid(orig.getXid())
				.setData(orig.getData())
				.build();
		send(new TVMessage(rep));
	}
}


text:
package cmd

import (
	"github.com/sky-uk/feed/controller"
	"github.com/sky-uk/feed/elb"
	"github.com/sky-uk/feed/k8s"
	"github.com/sky-uk/feed/nlb"
	"github.com/sky-uk/feed/nlb/nlbstatus"
	"github.com/spf13/cobra"
)

var nlbCmd = &cobra.Command{
	Use:   "nlb",
	Short: "Attach to AWS Network Load Balancers",
	Run: func(cmd *cobra.Command, args []string) {
		runCmd(appendNlbIngressUpdaters)
	},
}

func init() {
	rootCmd.AddCommand(nlbCmd)

	nlbCmd.Flags().StringVar(&region, "region", defaultRegion,
		"AWS region for frontend attachment.")
	nlbCmd.Flags().StringVar(&elbFrontendTagValue, "nlb-frontend-tag-value", defaultLbFrontendTagValue,
		"Attach to NLBs tagged with "+elb.FrontendTag+"=value. Leave empty to not attach.")
	nlbCmd.Flags().IntVar(&elbExpectedNumber, "nlb-expected-number", defaultLbExpectedNumber,
		"Expected number of NLBs to attach to. If 0 the controller will not check,"+
			" otherwise it fails to start if it can't attach to this number.")
	nlbCmd.Flags().DurationVar(&drainDelay, "drain-delay", defaultDrainDelay, "Delay to wait"+
		" for feed-ingress to drain from the registration component on shutdown. Should match the NLB's drain time.")
}

func appendNlbIngressUpdaters(kubernetesClient k8s.Client, updaters []controller.Updater) ([]controller.Updater, error) {
	updater, err := nlb.New(region, elbFrontendTagValue, ingressClassName, elbExpectedNumber, drainDelay)
	if err != nil {
		return nil, err
	}
	updaters = append(updaters, updater)

	statusConfig := nlbstatus.Config{
		Region:              region,
		FrontendTagValue:    elbFrontendTagValue,
		IngressNameTagValue: ingressClassName,
		KubernetesClient:    kubernetesClient,
	}
	statusUpdater, err := nlbstatus.New(statusConfig)
	if err != nil {
		return nil, err
	}
	return append(updaters, statusUpdater), nil
}


text:
<title>
Operation Failure in Buffalo
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

A crucial victory for abortion rights activists

Operation Failure in Buffalo

By Mark Larson | May 1992 | Page 16

BUFFALO--"Operation Rescue, wherever you go, you'll remember Buffalo!" was what hundreds of pro-choice clinic defenders chanted at a demoralized Operation "Rescue" (OR), as pro-choicers chased OR out of town.

 OR had promised four weeks of blockades of Buffalo clinics on the scale of their August 1991 attack on Wichita, Kan. Unlike Wichita, in Buffalo, OR was met from day one by angry pro-choice crowds chanting, "You're not in Kansas anymore, we'll defend the clinic door!" From the time OR started its attacks on clinics April 20, it was clear that the clinic defenders controlled access to the clinics and that Buffalo would be a victory for abortion rights.

Wichita focused national attention on OR's anti-woman message, and gave anti-abortion bigots a boost of confidence. It was a clear defeat for abortion rights activists, and since then, pro-choice activists have rallied around the cry "No More Wichitas!"

As soon as OR announced its Buffalo plans, abortion rights groups from all over the country began to make plans to defend the clinics. This organizing went against the "accepted wisdom" of the mainstream pro-choice movement which sought instead to intensify the losing tactics used in Wichita: legislation, court injunctions against OR and relying on the police to keep the clinics open.

Groups like the National Organization of Women (NOW), despite the influence they have over thousands in the pro-choice movement, did not mobilize nationally for Buffalo, and even discouraged clinic defense. The Cincinnati NOW chapter, for example, wanted to send busloads of people to Buffalo, but canceled plans because of National NOW policy.

Despite these obstacles, there were thousands of activists who were sick of remaining passive and defensive in the face of attacks on abortion rights in the streets and in the legislatures.

By April 20, OR leaders were publicly revising and scaling back their expectations. OR no longer felt confident about its ability to close abortion clinics.

On April 20 and 21, everyone expected the "big hit." But, outnumbered by the pro-choice presence, OR could only muster small numbers of supporters for prayers across the street from the clinics. The daily, mass clinic defenses clearly showed who had the edge in this battle, and it showed how easily OR can be defeated when challenged.

On April 22, OR worked out a media stunt with the cops. One hundred and ninety OR activists knelt in the street, just in front of the clinic defense lines, and were carted off by cops without challenging access to the clinic. The media was hungry for OR's big day, and pounced on the event. They reported it as if it were a blockade and took OR leaders' word that "many women had been scared away" by the event.

But the clinic defenders were well aware of the situation and were made more confident. By week's end, Patricia Ireland, the new president of NOW, made an appearance in Buffalo. In light of OR's defeat in Buffalo, Ireland was forced to express support for those defending the clinics. "We support clinic defense," she told a CNN reporter. "We have seen that this is a strategy that works."

Ireland's comments indicate that the abortion rights victory in Buffalo can renew the confidence of pro-choice activists nationwide. But NOW--and other mainstream groups--have yet to show a resolve in building militant action to shift their attention away from electoral politics.

The Buffalo victory shows that the energy and anger of thousands can win battles. Those in Buffalo were not politicians: they were students, working women and men, and others directly threatened by OR's activity. Our victory proved that people who are most affected by restrictions on abortion are the ones capable of offering real political leadership.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
package org.newdawn.slick;

import java.net.URL;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Files.FileType;

/**
 * A single sound effect loaded from either OGG or XM/MOD file. Sounds are allocated to
 * channels dynamically - if not channel is available the sound will not play.
 *
 * @author kevin
 */
public class Sound {
	/** The underlying sound */
	private com.badlogic.gdx.audio.Sound sound;

	/**
	 * Create a new Sound
	 *
	 * @param url The location of the OGG or MOD/XM to load
	 * @throws SlickException Indicates a failure to load the sound effect
	 */
	public Sound(URL url) throws SlickException {
		throw new RuntimeException("URL sound loading not supported in Slick-AE");
	}

	/**
	 * Create a new Sound
	 *
	 * @param ref The location of the OGG or MOD/XM to load
	 * @throws SlickException Indicates a failure to load the sound effect
	 */
	public Sound(String ref) throws SlickException {
        sound = Gdx.audio.newSound(Gdx.files.getFileHandle(ref, FileType.Internal));
	}

	/**
	 * Play this sound effect at default volume and pitch
	 */
	public void play() {
		play(1.0f, 1.0f);
	}

	/**
	 * Play this sound effect at a given volume and pitch
	 *
	 * @param pitch The pitch to play the sound effect at
	 * @param volume The volumen to play the sound effect at
	 */
	public void play(float pitch, float volume) {
		sound.play(volume);
	}

	/**
	 * Play a sound effect from a particular location
	 *
	 * @param x The x position of the source of the effect
 	 * @param y The y position of the source of the effect
	 * @param z The z position of the source of the effect
	 */
	public void playAt(float x, float y, float z) {
		playAt(1.0f, 1.0f, x,y,z);
	}

	/**
	 * Play a sound effect from a particular location
	 *
	 * @param pitch The pitch to play the sound effect at
	 * @param volume The volumen to play the sound effect at
	 * @param x The x position of the source of the effect
 	 * @param y The y position of the source of the effect
	 * @param z The z position of the source of the effect
	 */
	public void playAt(float pitch, float volume, float x, float y, float z) {
		sound.play(volume);
	}

	/**
	 * Loop this sound effect at default volume and pitch
	 */
	public void loop() {
		loop(1.0f, 1.0f);
	}

	/**
	 * Loop this sound effect at a given volume and pitch
	 *
	 * @param pitch The pitch to play the sound effect at
	 * @param volume The volumen to play the sound effect at
	 */
	public void loop(float pitch, float volume) {
		sound.play(volume);
	}

	/**
	 * Check if the sound is currently playing
	 *
	 * @return True if the sound is playing
	 */
	public boolean playing() {
		return false;
	}

	/**
	 * Stop the sound being played
	 */
	public void stop() {
	}
}


text:
using AxosoftAPI.NET.Core.Interfaces;
using AxosoftAPI.NET.Models;

namespace AxosoftAPI.NET.Interfaces
{
	public interface IContacts : IResource<Contact>
	{
		Result<Contact> GetInit();
	}
}


text:
<?php require_once 'templates/data.php'; ?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>E-Mall - Manage Products</title>

    <link rel="stylesheet" href="assets/css/bootstrap.min.css">

    <link rel="stylesheet" href="assets/css/animate.css">
    <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">

    <link rel="stylesheet" href="assets/css/style.css">

    <link rel="stylesheet" href="assets/css/formValidation.min.css">

    <link rel="stylesheet" href="assets/css/plugins/ladda/ladda-themeless.min.css">

    <link rel="stylesheet" href="assets/css/plugins/footable/footable.core.css">

<?php require_once 'templates/header.php'; ?>

Search "<?php echo $_GET['search'];?>"

                <select class="form-control" name="sorting">
                  <option value="" selected>Select</option>
                  <option value="dsort-asc">Product : Older to Lastest</option>
                  <option value="dsort-desc">Product : Lastest to Older</option>
                  <option value="psort-asc">Price   : Low to High</option>
                  <option value="psort-desc">Price   : High to Low</option>
                </select>

  <?php
      use Emall\Pagination\Pagination;
      use Emall\Auth\Session;
      use Emall\Auth\Filter;

      $page     = new Pagination;
      $sellerID = Session::get('sellerSession');

        if (isset($_GET['page'])) {
            if (!is_numeric($_GET['page'])){
                $page_number = 1;
            } else {
                $page_number = Filter::IntegerFilter($_GET['page']);
            }
        } else {
            $page_number = 1;
        }

        if (isset($_GET['limit'])) {
            if (!is_numeric($_GET['limit'])){
                $item_per_page = 24;
            } else {
                $item_per_page = $_GET['limit'];
            }
        } else {
            $item_per_page = 24;
        }

        if (isset($_GET['subcategories'])) {
            if (!is_numeric($_GET['subcategories'])){
                $subcategories = null;
            } else {
                $subcategories = Filter::IntegerFilter($_GET['subcategories']);
            }
        } else {
            $subcategories = null;
        }

        if (isset($_GET['psort'])) {
            if (is_string($_GET['psort'])){
                $priceSort = Filter::StringFilter($_GET['psort']);
            } else {
                $priceSort = 'ASC';
            }
        }

        if (isset($_GET['dsort'])) {
            if (is_string($_GET['dsort'])){
                $defaultSort = Filter::StringFilter($_GET['dsort']);
            } else {
                $defaultSort = 'ASC';
            }
        }

        if (isset($_GET['search'])) {
            if (is_string($_GET['search'])){
                $search = Filter::StringFilter($_GET['search']);
            } else {
                $search = null;
            }
        }

      $total_records = $page->TotalRowsSearch($sellerID, $subcategories, $search);
      $total_pages   = ceil($total_records/$item_per_page);

      if (isset($priceSort, $subcategories) && empty($search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','&subcategories=', '&psort=', '', $subcategories, $priceSort, '');
      } elseif (isset($priceSort) && empty($search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','', '&psort=','', '', $priceSort, '');
      } elseif (isset($subcategories, $defaultSort) && empty($search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','&subcategories=','','&dsort=', $subcategories,'', $defaultSort);
      } elseif (isset($subcategories) && empty($search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','&subcategories=','','', $subcategories,'', '');
      } elseif (isset($defaultSort) && empty($search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','', '','&dsort=', '', '', $defaultSort);
      } elseif (isset($priceSort, $subcategories, $search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','&subcategories=', '&psort=', '', $subcategories, $priceSort, '', '&search=', $search);
      } elseif (isset($priceSort, $search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','', '&psort=','', '', $priceSort, '', '&search=', $search);
      } elseif (isset($subcategories, $defaultSort, $search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','&subcategories=','','&dsort=', $subcategories,'', $defaultSort, '&search=', $search);
      } elseif (isset($subcategories, $search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','&subcategories=','','', $subcategories,'', '', '&search=', $search);
      } elseif (isset($defaultSort, $search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','', '','&dsort=', '', '', $defaultSort, '&search=', $search);
      } elseif (isset($search)) {
          echo $page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page=','', '','', '', '', '', '&search=', $search);
      } else {
          echo json_encode($page->paginate_function($item_per_page, $page_number, $total_records, $total_pages,'product.php?page='));
      }
  ?>

<?php require_once 'templates/footer.php'; ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ 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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.is</groupId>
        <artifactId>identity-integration-tests</artifactId>
        <version>5.12.0-alpha5-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.identity.integration.test</artifactId>
    <packaging>pom</packaging>
    <name>org.wso2.identity.integration.test</name>

    <modules>
        <module>tests-backend</module>
        <!--<module>tests</module>-->
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.automation</groupId>
            <artifactId>org.wso2.carbon.automation.engine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automation</groupId>
            <artifactId>org.wso2.carbon.automation.extensions</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.saucelabs.selenium</groupId> <!-- Exclude Project-E from Project-B -->
                    <artifactId>sauce-ondemand-driver</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.saucelabs.selenium</groupId> <!-- Exclude Project-E from Project-B -->
                    <artifactId>selenium-client-factory</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automation</groupId>
            <artifactId>org.wso2.carbon.automation.test.utils</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automationutils</groupId>
            <artifactId>org.wso2.carbon.integration.common.admin.client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automationutils</groupId>
            <artifactId>org.wso2.carbon.integration.common.utils</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.automationutils</groupId>
            <artifactId>org.wso2.carbon.integration.common.extensions</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.idp.mgt.stub</artifactId>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.wink</groupId>
            <artifactId>wink-client</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.charon</groupId>
            <artifactId>org.wso2.charon.core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.application.common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.application.mgt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.functions.library.mgt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.inbound.provisioning.scim</groupId>
            <artifactId>org.wso2.carbon.identity.scim.common.stub</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.user.store.configuration.stub</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.user.core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.user.ws</groupId>
            <artifactId>org.wso2.carbon.um.ws.api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.template.mgt</artifactId>
        </dependency>
    </dependencies>
</project>


text:
print "Using native SQLite3\n"
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")

class SqliteError < StandardError
end

ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database  => ':memory:')
load("schema/schema.rb")


text:
import type { CompatibleHTMLProps } from '@looker/design-tokens'
import type { ValidationType } from '../../ValidationMessage'

export type SwitchProps = {
  on?: boolean
  validationType?: ValidationType
}

export type SwitchElementProps = SwitchProps &
  CompatibleHTMLProps<HTMLDivElement>