text:
from sqlalchemy import Column, String, Integer, create_engine, TEXT, DATE
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import *
import sqlalchemy

#setting for connect to database, we use MySQL
db = create_engine('mysql://fird0s:fird0s@localhost/banda_maps.db', convert_unicode=True)
#banda-maps is Mysql Username Privileges
#banda-maps is Mysql Password of Username
#banda-maps.db is Database Name

Base = declarative_base()

class Users(Base):
	__tablename__ = "maps_users"

	id = Column(Integer, primary_key=True)
	Username = Column(String(25), primary_key=True, unique=True)
	FullName = Column(String(40))
	Alamat = Column(String(60))
	Password = Column(String(30))
	Email = Column(String(30), unique=True)
	Phone = Column(String(16))
	Work = Column(String(16))
	Profile_Image_Location = Column(String(200))
	Profile_Description = Column(TEXT())
	Website = Column(String(30))
	Date_Joined = Column(DATE())
	Last_Log = Column(String(100))

	def __init__(self, Username, FullName, Password, Email, Phone, Work, Last_Log):
		self.Username = Username
		self.FullName = FullName
		self.Password = Password
		self.Email = Email
		self.Phone = Phone
		self.Work = Work
		self.Last_Log = Last_Log

class Markers(Base):
	__tablename__ = "maps_markers"

	id = Column(Integer, primary_key=True)
	Adder = Column(String(30))
	Title = Column(String(50))
	Latitude = Column(String(30))
	Longtitude = Column(String(30))
	Description = Column(TEXT)
	Location = Column(String(30))
	Icon_Set = Column(String(15))
	Image_Upload1 = Column(String(40))
	Image_Upload2 = Column(String(40))
	Image_Upload3 = Column(String(40))
	Last = Column(String(100))
	Tags = Column(String(100))

	#icon set
	#Home = icon-home
	#Bank = icon-money
	#Building = icon-building
	#store = icon-shopping-cart
	#Field =
	#Toilet =  icon-user
	#Airport =  icon-plane
	#Terminal = truck
	#coffe = icon-coffee
	#Restaurant/Cantten  =  icon-food
	#Park = default-marker
	#ATM = icon-credit-card
	#Perpusakaan = icon-book
	#Rumah Sakir = icon-hospital
	#perkantoran = icon-suitcase
	#Uncategorized = no icon (use default marker without use awesome Markers)

	def __init__(self, Adder, Latitude, Longtitude, Description, Location, Icon_Set, Image_Upload1, Last):
		self.Adder = Adder
		self.Latitude = Latitude
		self.Longtitude = Longtitude
		self.Description = Description
		self.Location = Location
		self.Icon_Set = Icon_Set
		self.Image_Upload1 = Image_Upload1
		self.Last = Last

Session = sessionmaker(bind=db)
session_db = Session()
Base.metadata.create_all(db)


text:
package br.unb.unbomber.systems;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import br.unb.bomberman.ui.screens.ScreenDimensions;
import br.unb.unbomber.core.EntityManager;
import br.unb.unbomber.core.EntityManagerImpl;
import br.unb.unbomber.gridphysics.Vector2D;

public class RenderSystemTestCase {

	/** Gerenciador das entidades. */
	EntityManager entityManager;

	RenderSystem renderSystem;

	ScreenDimensions screenDimensions;

	@Before
	public void setUp() throws Exception {

		/** Inicia um sistema para cada caso de teste. */
		EntityManagerImpl.init();
		entityManager = EntityManagerImpl.getInstance();
		renderSystem = new RenderSystem(entityManager);

		screenDimensions = new ScreenDimensions();
	}

	@Test
	public void testGridPositionToScreenPosition() {

		Vector2D<Float> screenPosition = renderSystem.gridPositionToScreenPosition(new Vector2D<Float>(0.0f, 0.0f));

		assertEquals("x position", 0, screenPosition.getX().intValue());

		assertEquals("y position", screenDimensions.getScreenHeight()
				- screenDimensions.getHudHeight() - screenDimensions.getCellSize(),
				 screenPosition.getY().intValue());

	}

}

redpajama_set_name: RedPajamaGithub


text:
from . import Request
from pygithub3.resources.users import User
from pygithub3.resources.repos import Repo

class List(Request):

    uri = 'repos/{user}/{repo}/watchers'
    resource = User

class List_repos(Request):

    uri = 'users/{user}/watched'
    resource = Repo

    def clean_uri(self):
        if not self.user:
            return 'user/watched'

class Is_watching(Request):

    uri = 'user/watched/{user}/{repo}'

class Watch(Request):

    uri = 'user/watched/{user}/{repo}'

class Unwatch(Request):

    uri = 'user/watched/{user}/{repo}'


text:
from k5test import *

realm = K5Realm(create_user=False, create_host=False)

# Create a principal with no keys.
realm.run([kadminl, 'addprinc', '-nokey', 'user'])
realm.run([kadminl, 'getprinc', 'user'], expected_msg='Number of keys: 0')

# Change its password and check the resulting kvno.
realm.run([kadminl, 'cpw', '-pw', 'password', 'user'])
realm.run([kadminl, 'getprinc', 'user'], expected_msg='vno 1')

# Delete all of its keys.
realm.run([kadminl, 'purgekeys', '-all', 'user'])
realm.run([kadminl, 'getprinc', 'user'], expected_msg='Number of keys: 0')

# Randomize its keys and check the resulting kvno.
realm.run([kadminl, 'cpw', '-randkey', 'user'])
realm.run([kadminl, 'getprinc', 'user'], expected_msg='vno 1')

# Return true if patype appears to have been received in a hint list
# from a KDC error message, based on the trace file fname.
def preauth_type_received(fname, patype):
    f = open(fname, 'r')
    found = False
    for line in f:
        if 'Processing preauth types:' in line:
            ind = line.find('types:')
            patypes = line[ind + 6:].strip().split(', ')
            if str(patype) in patypes:
                found = True
    f.close()
    return found

# Make sure the KDC doesn't offer encrypted timestamp for a principal
# with no keys.
tracefile = os.path.join(realm.testdir, 'trace')
realm.run([kadminl, 'purgekeys', '-all', 'user'])
realm.run([kadminl, 'modprinc', '+requires_preauth', 'user'])
realm.run(['env', 'KRB5_TRACE=' + tracefile, kinit, 'user'], expected_code=1)
if preauth_type_received(tracefile, 2):
    fail('encrypted timestamp')

# Make sure it doesn't offer encrypted challenge either.
realm.run([kadminl, 'addprinc', '-pw', 'fast', 'armor'])
realm.kinit('armor', 'fast')
os.remove(tracefile)
realm.run(['env', 'KRB5_TRACE=' + tracefile, kinit, '-T', realm.ccache,
           'user'], expected_code=1)
if preauth_type_received(tracefile, 138):
    fail('encrypted challenge')

success('Key data tests')


text:
package com.autonomy.nonaci;

import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/**
 * Holds the protocol, host and port details of a non-ACI Server.
 *
 * @author boba
 */
public class ServerDetails {

    /** Holds the different types of transport protocol that can be used by ACI servers. */
    public enum TransportProtocol {HTTP, HTTPS}

    /** Holds value of property protocol. Defaults to <tt>TransportProtocol.HTTP</tt>. */
    private TransportProtocol protocol = TransportProtocol.HTTP;

    /** Holds value of property host. */
    private String host;

    /** Holds value of property port. */
    private int port;

    /** Holds value of property charsetName. Defaults to UTF-8. */
    private String charsetName = "UTF-8";

    /**
     * Default constructor
     */
    public ServerDetails() {
        super();
    }

    /**
     * Creates connection details for a server, with the specified {@code host} and {@code port} details and
     * with the default {@code protocol} and {@code charsetName} values.
     *
     * @param host The host of the server
     * @param port The port of the server
     */
    public ServerDetails(final String host, final int port) {
        Validate.notNull(host, "host must not be null, it must be set to a value");
        Validate.isTrue((port >= 0) && (port <= 65536), "port is out of range, it should be between 0 and 65536.");

        this.host = host;
        this.port = port;
    }

    /**
     * Creates connection details for a server, with the specified {@code protocol}, {@code host} and {@code port}
     * details and with the default {@code charsetName} value.
     *
     * @param protocol The protocol to use when communicating with the ACI server
     * @param host The host of the ACI server
     * @param port The port of the ACI server
     */
    public ServerDetails(final TransportProtocol protocol, final String host, final int port) {
        Validate.notNull(protocol, "protocol must not be null, it must be set to a value");
        Validate.notNull(host, "host must not be null, it must be set to a value");
        Validate.isTrue((port >= 0) && (port <= 65536), "port is out of range, it should be between 0 and 65536.");

        this.protocol = protocol;
        this.host = host;
        this.port = port;
    }

    /**
     * Copy constructor.
     *
     * @param that The {@link ServerDetails} to copy details from.
     */
    public ServerDetails(final ServerDetails that) {
        this.protocol = that.protocol;
        this.host = that.host;
        this.port = that.port;
        this.charsetName = that.charsetName;
    }

    /**
     * Returns a string representation of the object.
     *
     * @return a string representation of the object.
     */
    @Override
    public String toString() {
        return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

    /**
     * Indicates whether some other object is equal to this one.
     *
     * @param obj the reference object with which to compare.
     * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise.
     */
    @Override
    public boolean equals(final Object obj) {
        boolean returnValue = false;

        if(this == obj) {
            returnValue = true;
        }
        else if(obj instanceof ServerDetails) {
            final ServerDetails that = (ServerDetails) obj;

            // Build the comparison...
            returnValue = new EqualsBuilder()
                    .append(this.protocol, that.protocol)
                    .append(this.host, that.host)
                    .append(this.port, that.port)
                    .append(this.charsetName, that.charsetName)
                    .isEquals();
        }

        return returnValue;
    }

    /**
     * Returns a hash code value for the object.
     *
     * @return a hash code value for this object.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder(3, 27)
                .append(protocol)
                .append(host)
                .append(port)
                .append(charsetName)
                .toHashCode();
    }

    /**
     * Getter for property protocol.
     * @return Value of property protocol.
     */
    public TransportProtocol getProtocol() {
        return protocol;
    }

    /**
     * Setter for property protocol.
     *
     * @param protocol New value of property protocol.
     * @throws java.lang.IllegalArgumentException if <tt>protocol</tt> is null.
     */
    public void setProtocol(final TransportProtocol protocol) {
        Validate.notNull(protocol, "protocol must not be null, it must be set to a value");
        this.protocol = protocol;
    }

    /**
     * Getter for property host.
     * @return Value of property host.
     */
    public String getHost() {
        return this.host;
    }

    /**
     * Setter for property host.
     * @param host New value of property host.
     */
    public void setHost(final String host) {
        Validate.notNull(host, "host must not be null, it must be set to a value");
        this.host = host;
    }

    /**
     * Getter for property port.
     * @return Value of property port.
     */
    public int getPort() {
        return this.port;
    }

    /**
     * Setter for property port. The port number must be in the range <tt>0 <= port <= 65536</tt> or an
     * <tt>IllegalArgumentException</tt> will be thrown.
     *
     * @param port New value of property port.
     * @throws IllegalArgumentException if the <tt>port</tt> is outside the range <tt>0 <= port <= 65536</tt>.
     */
    public void setPort(final int port) {
        Validate.isTrue((port >= 0) && (port <= 65536), "port is out of range, it should be between 0 and 65536.");
        this.port = port;
    }

    /**
     * Getter for property charsetName.
     * @return Value of property charsetName.
     */
    public String getCharsetName() {
        return this.charsetName;
    }

    /**
     * Setter for property charsetName.
     *
     * @param charsetName The name of the requested charset; may be either a canonical name or an alias
     * @throws java.lang.IllegalArgumentException If <tt>charsetName</tt> is null
     * @throws java.nio.charset.IllegalCharsetNameException If the given charset name is illegal
     * @throws java.nio.charset.UnsupportedCharsetException If no support for the named charset is available in this
     *         instance of the Java virtual machine
     */
    public void setCharsetName(final String charsetName) {
        if(Charset.isSupported(charsetName)) {
            this.charsetName = charsetName;
        }
        else {
            throw new UnsupportedCharsetException("No support for, " + charsetName + ", is available in this instance of the JVM");
        }
    }

}


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 io.trino.spi;

import io.trino.spi.block.BlockEncoding;
import io.trino.spi.connector.ConnectorFactory;
import io.trino.spi.eventlistener.EventListenerFactory;
import io.trino.spi.resourcegroups.ResourceGroupConfigurationManagerFactory;
import io.trino.spi.security.CertificateAuthenticatorFactory;
import io.trino.spi.security.GroupProviderFactory;
import io.trino.spi.security.HeaderAuthenticatorFactory;
import io.trino.spi.security.PasswordAuthenticatorFactory;
import io.trino.spi.security.SystemAccessControlFactory;
import io.trino.spi.session.SessionPropertyConfigurationManagerFactory;
import io.trino.spi.type.ParametricType;
import io.trino.spi.type.Type;

import java.util.Set;

import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;

public interface Plugin
{
    default Iterable<ConnectorFactory> getConnectorFactories()
    {
        return emptyList();
    }

    default Iterable<BlockEncoding> getBlockEncodings()
    {
        return emptyList();
    }

    default Iterable<Type> getTypes()
    {
        return emptyList();
    }

    default Iterable<ParametricType> getParametricTypes()
    {
        return emptyList();
    }

    default Set<Class<?>> getFunctions()
    {
        return emptySet();
    }

    default Iterable<SystemAccessControlFactory> getSystemAccessControlFactories()
    {
        return emptyList();
    }

    default Iterable<GroupProviderFactory> getGroupProviderFactories()
    {
        return emptyList();
    }

    default Iterable<PasswordAuthenticatorFactory> getPasswordAuthenticatorFactories()
    {
        return emptyList();
    }

    default Iterable<HeaderAuthenticatorFactory> getHeaderAuthenticatorFactories()
    {
        return emptyList();
    }

    default Iterable<CertificateAuthenticatorFactory> getCertificateAuthenticatorFactories()
    {
        return emptyList();
    }

    default Iterable<EventListenerFactory> getEventListenerFactories()
    {
        return emptyList();
    }

    default Iterable<ResourceGroupConfigurationManagerFactory> getResourceGroupConfigurationManagerFactories()
    {
        return emptyList();
    }

    default Iterable<SessionPropertyConfigurationManagerFactory> getSessionPropertyConfigurationManagerFactories()
    {
        return emptyList();
    }
}


text:
package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.isNonNullUsingDataflow;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.InstanceOfTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;

/**
 * Matches instanceof checks where the expression is a subtype of the checked type.
 *
 * @author ghm@google.com (Graeme Morgan)
 */
@BugPattern(
    name = "BadInstanceof",
    summary = "instanceof used in a way that is equivalent to a null check.",
    severity = WARNING,
    tags = SIMPLIFICATION)
public final class BadInstanceof extends BugChecker implements InstanceOfTreeMatcher {

  private static final String NON_NULL =
      "`%s` is a non-null instance of %s which is a subtype of %s, so this check is always true.";

  private static final String NULLABLE =
      "`%s` is an instance of %s which is a subtype of %s, so this is equivalent to a null check.";

  @Override
  public Description matchInstanceOf(InstanceOfTree tree, VisitorState state) {
    if (!isSubtype(getType(tree.getExpression()), getType(tree.getType()), state)) {
      return NO_MATCH;
    }
    String subType = SuggestedFixes.prettyType(getType(tree.getExpression()), state);
    String expression = state.getSourceForNode(tree.getExpression());
    String superType = state.getSourceForNode(tree.getType());
    if (isNonNullUsingDataflow().matches(tree.getExpression(), state)) {
      return buildDescription(tree)
          .setMessage(String.format(NON_NULL, expression, subType, superType))
          .build();
    }
    return buildDescription(tree)
        .setMessage(String.format(NULLABLE, expression, subType, superType))
        .addFix(getFix(tree, state))
        .build();
  }

  private static SuggestedFix getFix(InstanceOfTree tree, VisitorState state) {
    Tree parent = state.getPath().getParentPath().getLeaf();
    Tree grandParent = state.getPath().getParentPath().getParentPath().getLeaf();
    if (parent.getKind() == Kind.PARENTHESIZED
        && grandParent.getKind() == Kind.LOGICAL_COMPLEMENT) {
      return SuggestedFix.replace(
          grandParent, state.getSourceForNode(tree.getExpression()) + " == null");
    }
    return SuggestedFix.replace(tree, state.getSourceForNode(tree.getExpression()) + " != null");
  }
}


text:
package org.brunel.data.stats;

import org.brunel.data.Field;
import org.brunel.data.util.MapInt;

public class NominalStats {

    public static void populate(Field f) {
        MapInt counts = new MapInt();
        int N = f.rowCount();

        // Create map of counts
        for (int i = 0; i < N; i++)
            counts.increment(f.value(i));

        f.set("n", N);
        f.set("unique", counts.size());
        f.set("valid", counts.getTotalCount());
        f.set("mode", counts.mode());

        Object[] naturalOrder;
        if (f.isProperty("categoriesOrdered")) {
            naturalOrder = f.categories();
        } else {
            if (f.name.equals("#selection")) {
                // The categories are as follows
                naturalOrder = new Object[]{Field.VAL_UNSELECTED, Field.VAL_SELECTED};
            } else {
                // Extract categories from the counts
                naturalOrder = counts.sortedKeys();
            }
            f.set("categories", naturalOrder);
        }

        f.set("categoryCounts", counts.getCounts(naturalOrder));
    }

    public static boolean creates(String key) {
        return "n".equals(key) || "mode".equals(key) || "unique".equals(key) || "valid".equals(key)
                || "categories".equals(key) || "categoryCounts".equals(key);
    }
}


text:
package iso20022

// Reason for an update to an account status.
type AccountStatusUpdateInstructionReason1 struct {

	// Reason for the instruction to change the account status.
	Code *AccountStatusUpdateInstructionReason2Choice `xml:"Cd,omitempty"`

	// Additional information about the reason for the instruction to change the account status.
	AdditionalInformation *Max350Text `xml:"AddtlInf,omitempty"`
}

func (a *AccountStatusUpdateInstructionReason1) AddCode() *AccountStatusUpdateInstructionReason2Choice {
	a.Code = new(AccountStatusUpdateInstructionReason2Choice)
	return a.Code
}

func (a *AccountStatusUpdateInstructionReason1) SetAdditionalInformation(value string) {
	a.AdditionalInformation = (*Max350Text)(&value)
}


text:
<?= view('app/default/common/head_top') ?>

    <meta http-equiv="Content-Security-Policy" content="<?= getCsp('Config', true) ?>">

    <title>Email address - <?= config('Config\App')->siteName ?></title>

    <meta name="robots" content="noindex">

    <?= view('app/default/common/css') ?>
    <?= view('app/default/common/head_bottom') ?>
    <?= view('app/default/common/menu') ?>

                <?= view('app/default/common/account_menu') ?>

                        Home

                        Account

                        Email address

Change email address

                        <form method="post" data-url="account/email" data-timeout="1000">

                                New email address *
                                <input class="form-control" name="email" type="email" required>

                                <input name="<?= $csrf['name'] ?>" type="hidden" value="<?= $csrf['hash'] ?>">
                                <input class="btn btn-primary" type="submit" value="Update">

                        </form>

    <?= view('app/default/common/foot_top') ?>
    <?= view('app/default/common/js/form') ?>
    <?= view('app/default/common/js') ?>
    <?= view('app/default/common/foot_bottom') ?>


text:
from django.http import HttpResponse
from django.shortcuts import render
from django.http import JsonResponse
from testCon.models import Account
from testCon.models import Account_Teacher
import simplejson
import json

def hello(request):
	return HttpResponse("hi")
def welcome(request):
	context = {}
	return render(request,'hello.html',context)


text:
package tsmap

import (
"testing"
"runtime"
"sync"
"time"
)

type TestElement struct {
	a int
	b string
	key string
}

func (e *TestElement) Key() string {
	return e.key
}

// Test doing an add
func TestLockedMapAdd (t *testing.T) {
	m := CreateLockedMap()

	e1 := &TestElement {
		a: 5,
		b: "hello",
		key :"key1",
	}
	if m.Add(e1) != true {
		t.Error("Add did not return true")
	}

	//second add should fail, due to same key
	if m.Add(e1) != false {
		t.Error("Add did not return false")
	}

	//make sure a different key works
	e2 := &TestElement {
		a: 5,
		b: "hello",
		key :"key2",
	}
	if m.Add(e2) == false {
		t.Error("Add should have passed")
	}

	// try deleting an element

	ret := m.Delete(e2.Key())
	if ret != true {
		t.Error("Delete should have passed")
	}

	// Test deleting an element whilst others are trying to lock.
	// Test and (expected behaviour)
	// 1. A locks element (and gets it)
	// 2. B deletes element (blocks)
	// 3. C locks element (blocks)
	// 3. A unlocks element (allowing B to delete)
	// 4. (C's lock request returns as a failure)

	// A lock an element
	eltLoan := m.Lock(e1.key)
	if eltLoan == nil {
		t.Error("Lock failed")
	}

	deleteEndChan := make(chan int)
	ClockResultChan := make(chan bool)

	CLockFn := func (lockResult chan bool) {
		ret := m.Lock(e1.key)
		if ret == nil {
			lockResult <- true
		} else {
			lockResult <- false
		}
	}

	BDeleteFn := func(doneChan chan int) {
		ret = m.Delete(e1.key)
		if ret != true {
			t.Error("Delete should have passed")
		}
		doneChan <- 0
	}

	go BDeleteFn(deleteEndChan)
	// Wait for B to get blocked on the channel
	time.Sleep(time.Millisecond*300) // I swear officer, I was just going to fix this!

	go CLockFn(ClockResultChan)
	// Wait for C to call Lock
	time.Sleep(time.Millisecond*300) // I swear officer, I was just going to fix this!

	// get A to unlock
	m.Unlock(eltLoan)

	//wait for delete to finish
	<- deleteEndChan

	//check that C returned with the correct
	delayChan := time.After(time.Millisecond*500)
	select {
	case cret := <- ClockResultChan:
		if cret != true {
			t.Error("C's lock did not fail as expected")
		}
	case <-delayChan:
		t.Error("C's Lock fn never returned")

	}

}

// Test to make sure that a read-modify-write cycle (with Lock and Unlock) works
func TestLockedMapEdit (t *testing.T) {
	m := CreateLockedMap()
	src_e1 := &TestElement {
		a: 5,
		b: "hello",
		key :"key1",
	}
	if m.Add(src_e1) != true {
		t.Error("Add did not return true")
	}

	eltLoan :=m.Lock(src_e1.key)

	if eltLoan == nil {
		t.Error("couldn't get item")
	}

	e1 := eltLoan.Element().(*TestElement)
	e1.a=e1.a +1
	e1.b="new"

	if m.Unlock(eltLoan) !=true {
		t.Error("couldn't return item")
	}

	//make sure the loan is no longer valid
	if eltLoan.Element() != nil {
		t.Error("loan shouldn't still hand out element")
	}

	//Retrieve again and make sure changes were saved
	eltLoan2 :=m.Lock(e1.key)

	if eltLoan2 == nil {
		t.Error("couldn't get item second time")
	}

	e2 := eltLoan2.Element().(*TestElement)

	if e2.a != 6 {
		t.Error("wrong values")
	}
	if e2.b != "new" {
		t.Error("wrong values")
	}
}

// Run a lot of go routines that increment a counter inside a map element
// if the count at the end isn't equal to the number of go routines then
// there is a thread safety issue
func TestThreadSafety(t *testing.T) {
	if runtime.GOMAXPROCS(-1) == 1 {
		//have more than 1 cpu to really test thread safety
		runtime.GOMAXPROCS(4)
	}

	m := CreateLockedMap()
	src_e1 := &TestElement {
		a: 0,
		b: "hello",
		key :"key1",
	}
	if m.Add(src_e1) != true {
		t.Error("Add did not return true")
	}

	workerFunc := func (m *LockedMap, wg *sync.WaitGroup) {
		eltLoan := m.Lock("key1")
		if (eltLoan == nil) {
			t.Error("Lock failed")
			return
		}
		eltInterface := eltLoan.Element()
		if eltInterface == nil {
			t.Error("Element was nil")
		} else {
			e1 := eltInterface.(*TestElement)
			e1.a = e1.a + 1
		}

		if !m.Unlock(eltLoan) {
			t.Error("unlock failed")
			panic("thread block")
		}

		wg.Done()
	}

	total := 10000
	var wg sync.WaitGroup
	wg.Add(total)
	for i := 1; i <= total; i++ {
		go workerFunc(m,&wg)
	}

	wg.Wait()

	eltLoan := m.Lock("key1")
	if (eltLoan == nil) {
		t.Error("Lock failed")
	}
	e1 := eltLoan.Element().(*TestElement)
	if e1.a != total {
		t.Error("count does not match")
	}
}

/*
// Test to confirm behaviour of the sync.Mutex if you call Unlock twice
func TestMutexDoubleUnlock(t *testing.T) {
	mutex := sync.Mutex{}
	mutex.Lock()
	mutex.Unlock()
	mutex.Unlock() // panic occurs here (when tested on go version go1.1.2 linux/amd64)

	//check for normal op
	mutex.Lock()
	mutex.Unlock()
}
*/


text:
package org.apache.camel.management.mbean;

import org.apache.camel.CamelContext;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedBeanIntrospectionMBean;
import org.apache.camel.spi.BeanIntrospection;

/**
 *
 */
@ManagedResource(description = "Managed BeanIntrospection")
public class ManagedBeanIntrospection extends ManagedService implements ManagedBeanIntrospectionMBean {

    private final BeanIntrospection beanIntrospection;

    public ManagedBeanIntrospection(CamelContext context, BeanIntrospection beanIntrospection) {
        super(context, beanIntrospection);
        this.beanIntrospection = beanIntrospection;
    }

    public BeanIntrospection getBeanIntrospection() {
        return beanIntrospection;
    }

    @Override
    public Long getInvokedCounter() {
        return beanIntrospection.getInvokedCounter();
    }

    @Override
    public Boolean isExtendedStatistics() {
        return beanIntrospection.isExtendedStatistics();
    }

    @Override
    public void setExtendedStatistics(Boolean extendedStatistics) {
        beanIntrospection.setExtendedStatistics(extendedStatistics);
    }

    @Override
    public void resetCounters() {
        beanIntrospection.resetCounters();
    }

    @Override
    public Long getCachedClasses() {
        return beanIntrospection.getCachedClassesCounter();
    }

    @Override
    public void clearCache() {
        beanIntrospection.clearCache();
    }
}


text:
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;

namespace Umbraco.Cms.Core.Notifications;

public class MemberTypeSavingNotification : SavingNotification<IMemberType>
{
    public MemberTypeSavingNotification(IMemberType target, EventMessages messages)
        : base(target, messages)
    {
    }

    public MemberTypeSavingNotification(IEnumerable<IMemberType> target, EventMessages messages)
        : base(target, messages)
    {
    }
}


text:
import os
from unittest import mock

import django_dynamic_fixture as fixture
from django.conf import settings
from textwrap import dedent
from django.core.cache import cache
from django.http import HttpResponse
from django.test.utils import override_settings
from django.urls import reverse

from readthedocs.builds.constants import EXTERNAL, INTERNAL, LATEST
from readthedocs.builds.models import Version
from readthedocs.projects import constants
from readthedocs.projects.constants import (
    MKDOCS,
    SPHINX,
    SPHINX_HTMLDIR,
    SPHINX_SINGLEHTML,
    PUBLIC,
    PRIVATE,
)
from readthedocs.projects.models import Project, Domain
from readthedocs.rtd_tests.storage import BuildMediaFileSystemStorageTest

from .base import BaseDocServing

@override_settings(
    PYTHON_MEDIA=False,
    PUBLIC_DOMAIN='dev.readthedocs.io',
)
class TestFullDocServing(BaseDocServing):
    # Test the full range of possible doc URL's

    def test_health_check(self):
        url = reverse('health_check')
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.json(), {'status': 200})

        # Test with IP address, which should still work
        # since we're skipping middleware
        host = '127.0.0.1'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.json(), {'status': 200})

    def test_subproject_serving(self):
        url = '/projects/subproject/en/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/subproject/latest/awesome.html',
        )

    def test_subproject_single_version(self):
        self.subproject.single_version = True
        self.subproject.save()
        url = '/projects/subproject/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/subproject/latest/awesome.html',
        )

    def test_subproject_translation_serving(self):
        url = '/projects/subproject/es/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/subproject-translation/latest/awesome.html',
        )

    def test_subproject_alias_serving(self):
        url = '/projects/this-is-an-alias/en/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/subproject-alias/latest/awesome.html',
        )

    def test_translation_serving(self):
        url = '/es/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/translation/latest/awesome.html',
        )

    def test_normal_serving(self):
        url = '/en/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/project/latest/awesome.html',
        )

    def test_single_version_serving(self):
        self.project.single_version = True
        self.project.save()
        url = '/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/project/latest/awesome.html',
        )

    def test_single_version_serving_looks_like_normal(self):
        self.project.single_version = True
        self.project.save()
        url = '/en/stable/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/project/latest/en/stable/awesome.html',
        )

    def test_index_serving(self):
        host = 'project.dev.readthedocs.io'
        urls = ('/en/latest/awesome/', '/en/latest/awesome/index.html')
        for url in urls:
            resp = self.client.get(url, HTTP_HOST=host)
            self.assertEqual(
                resp['x-accel-redirect'], '/proxito/media/html/project/latest/awesome/index.html',
            )

    @override_settings(
        RTD_EXTERNAL_VERSION_DOMAIN='dev.readthedocs.build',
    )
    def test_single_version_external_serving(self):
        self.project.single_version = True
        self.project.save()
        fixture.get(
            Version,
            verbose_name='10',
            slug='10',
            type=EXTERNAL,
            active=True,
            project=self.project,
        )
        url = '/awesome.html'
        host = 'project--10.dev.readthedocs.build'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/external/html/project/10/awesome.html',
        )

    @override_settings(
        RTD_EXTERNAL_VERSION_DOMAIN='dev.readthedocs.build',
    )
    def test_external_version_serving(self):
        fixture.get(
            Version,
            verbose_name='10',
            slug='10',
            type=EXTERNAL,
            active=True,
            project=self.project,
        )
        url = '/awesome.html'
        host = 'project--10.dev.readthedocs.build'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/external/html/project/10/awesome.html',
        )

        # Invalid tests

    @override_settings(
        RTD_EXTERNAL_VERSION_DOMAIN='dev.readthedocs.build',
    )
    def test_invalid_domain_for_external_version_serving(self):
        fixture.get(
            Version,
            verbose_name='10',
            slug='10',
            type=EXTERNAL,
            active=True,
            project=self.project,
        )
        url = '/html/project/10/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 404)

    def test_invalid_language_for_project_with_versions(self):
        url = '/foo/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 404)

    def test_invalid_translation_for_project_with_versions(self):
        url = '/cs/latest/awesome.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 404)

    def test_invalid_subproject(self):
        url = '/projects/doesnt-exist/foo.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 404)

    # https://github.com/readthedocs/readthedocs.org/pull/6226/files/596aa85a4886407f0eb65233ebf9c38ee3e8d485#r332445803
    def test_valid_project_as_invalid_subproject(self):
        url = '/projects/translation/es/latest/foo.html'
        host = 'project.dev.readthedocs.io'
        resp = self.client.get(url, HTTP_HOST=host)
        self.assertEqual(resp.status_code, 404)

    def test_public_domain_hsts(self):
        host = 'project.dev.readthedocs.io'
        response = self.client.get('/', HTTP_HOST=host)
        self.assertFalse('strict-transport-security' in response)

        response = self.client.get("/", HTTP_HOST=host, secure=True)
        self.assertFalse('strict-transport-security' in response)

        with override_settings(PUBLIC_DOMAIN_USES_HTTPS=True):
            response = self.client.get('/', HTTP_HOST=host)
            self.assertFalse('strict-transport-security' in response)

            response = self.client.get("/", HTTP_HOST=host, secure=True)
            self.assertEqual(
                response['strict-transport-security'],
                'max-age=31536000; includeSubDomains; preload',
            )

    def test_custom_domain_response_hsts(self):
        hostname = 'docs.random.com'
        domain = fixture.get(
            Domain,
            project=self.project,
            domain=hostname,
            hsts_max_age=0,
            hsts_include_subdomains=False,
            hsts_preload=False,
        )

        response = self.client.get("/", HTTP_HOST=hostname)
        self.assertFalse('strict-transport-security' in response)

        response = self.client.get("/", HTTP_HOST=hostname, secure=True)
        self.assertFalse('strict-transport-security' in response)

        domain.hsts_max_age = 3600
        domain.save()

        response = self.client.get("/", HTTP_HOST=hostname)
        self.assertFalse('strict-transport-security' in response)

        response = self.client.get("/", HTTP_HOST=hostname, secure=True)
        self.assertTrue('strict-transport-security' in response)
        self.assertEqual(
            response['strict-transport-security'], 'max-age=3600',
        )

        domain.hsts_include_subdomains = True
        domain.hsts_preload = True
        domain.save()

        response = self.client.get("/", HTTP_HOST=hostname, secure=True)
        self.assertTrue('strict-transport-security' in response)
        self.assertEqual(
            response['strict-transport-security'], 'max-age=3600; includeSubDomains; preload',
        )

class TestDocServingBackends(BaseDocServing):
    # Test that nginx and python backends both work

    @override_settings(PYTHON_MEDIA=True)
    def test_python_media_serving(self):
        with mock.patch(
                'readthedocs.proxito.views.mixins.serve', return_value=HttpResponse()) as serve_mock:
            url = '/en/latest/awesome.html'
            host = 'project.dev.readthedocs.io'
            self.client.get(url, HTTP_HOST=host)
            serve_mock.assert_called_with(
                mock.ANY,
                '/media/html/project/latest/awesome.html',
                os.path.join(settings.SITE_ROOT, 'media'),
            )

    @override_settings(PYTHON_MEDIA=False)
    def test_nginx_media_serving(self):
        resp = self.client.get('/en/latest/awesome.html', HTTP_HOST='project.dev.readthedocs.io')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            resp['x-accel-redirect'], '/proxito/media/html/project/latest/awesome.html',
        )

    @override_settings(PYTHON_MEDIA=False)
    def test_project_nginx_serving_unicode_filename(self):
        resp = self.client.get('/en/latest/úñíčódé.html', HTTP_HOST='project.dev.readthedocs.io')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            resp['x-accel-redirect'],
            '/proxito/media/html/project/latest/%C3%BA%C3%B1%C3%AD%C4%8D%C3%B3d%C3%A9.html',
        )

@override_settings(
    PYTHON_MEDIA=False,
    PUBLIC_DOMAIN='readthedocs.io',
    RTD_BUILD_MEDIA_STORAGE='readthedocs.rtd_tests.storage.BuildMediaFileSystemStorageTest',
)
class TestAdditionalDocViews(BaseDocServing):
    # Test that robots.txt and sitemap.xml work

    def tearDown(self):
        super().tearDown()
        # Cleanup cache to avoid throttling on tests
        cache.clear()

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_default_robots_txt(self, storage_exists):
        storage_exists.return_value = False
        self.project.versions.update(active=True, built=True)
        response = self.client.get(
            reverse('robots_txt'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(response.status_code, 200)
        expected = dedent(
            """
            User-agent: *

            Disallow: # Allow everything

            Sitemap: https://project.readthedocs.io/sitemap.xml
            """
        ).lstrip()
        self.assertEqual(response.content.decode(), expected)

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_default_robots_txt_disallow_hidden_versions(self, storage_exists):
        storage_exists.return_value = False
        self.project.versions.update(active=True, built=True)
        fixture.get(
            Version,
            project=self.project,
            slug='hidden',
            active=True,
            hidden=True,
            privacy_level=PUBLIC,
        )
        fixture.get(
            Version,
            project=self.project,
            slug='hidden-2',
            active=True,
            hidden=True,
            privacy_level=PUBLIC,
        )
        fixture.get(
            Version,
            project=self.project,
            slug='hidden-and-inactive',
            active=False,
            hidden=True,
            privacy_level=PUBLIC,
        )
        fixture.get(
            Version,
            project=self.project,
            slug='hidden-and-private',
            active=False,
            hidden=True,
            privacy_level=PRIVATE,
        )

        response = self.client.get(
            reverse('robots_txt'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(response.status_code, 200)
        expected = dedent(
            """
            User-agent: *

            Disallow: /en/hidden-2/ # Hidden version

            Disallow: /en/hidden/ # Hidden version

            Sitemap: https://project.readthedocs.io/sitemap.xml
            """
        ).lstrip()
        self.assertEqual(response.content.decode(), expected)

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_default_robots_txt_private_version(self, storage_exists):
        storage_exists.return_value = False
        self.project.versions.update(active=True, built=True, privacy_level=constants.PRIVATE)
        response = self.client.get(
            reverse('robots_txt'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(response.status_code, 404)

    def test_custom_robots_txt(self):
        self.project.versions.update(active=True, built=True)
        response = self.client.get(
            reverse('robots_txt'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(
            response['x-accel-redirect'], '/proxito/media/html/project/latest/robots.txt',
        )

    def test_custom_robots_txt_private_version(self):
        self.project.versions.update(active=True, built=True, privacy_level=constants.PRIVATE)
        response = self.client.get(
            reverse('robots_txt'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(response.status_code, 404)

    def test_directory_indexes(self):
        self.project.versions.update(active=True, built=True)
        # Confirm we've serving from storage for the `index-exists/index.html` file
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/latest/index-exists'}),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(
            response.status_code, 302
        )
        self.assertEqual(
            response['location'], '/en/latest/index-exists/',
        )

    def test_versioned_no_slash(self):
        self.project.versions.update(active=True, built=True)
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/latest'}),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(
            response.status_code, 302
        )
        self.assertEqual(
            response['location'], '/en/latest/',
        )

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_directory_indexes_readme_serving(self, storage_exists):
        self.project.versions.update(active=True, built=True)

        storage_exists.side_effect = [False, True]
        # Confirm we've serving from storage for the `index-exists/index.html` file
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/latest/readme-exists'}),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(
            response.status_code, 302
        )
        self.assertEqual(
            response['location'], '/en/latest/readme-exists/README.html',
        )

    def test_directory_indexes_get_args(self):
        self.project.versions.update(active=True, built=True)
        # Confirm we've serving from storage for the `index-exists/index.html` file
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/latest/index-exists'}) + '?foo=bar',
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(
            response.status_code, 302
        )
        self.assertEqual(
            response['location'], '/en/latest/index-exists/?foo=bar',
        )

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'open')
    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_storage_serves_custom_404_sphinx(self, storage_exists, storage_open):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX,
        )

        storage_exists.side_effect = [False, False, True]
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
            ]
        )
        self.assertEqual(response.status_code, 404)

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_redirects_to_correct_index(self, storage_exists):
        """This case is when the project uses a README.html as index."""
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX,
        )

        storage_exists.side_effect = [False, True]
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found/'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
            ]
        )
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['location'], '/en/fancy-version/not-found/README.html')

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'open')
    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_storage_serves_custom_404_sphinx_single_html(self, storage_exists, storage_open):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX_SINGLEHTML,
        )

        storage_exists.side_effect = [False, False, True]
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
            ]
        )
        self.assertEqual(response.status_code, 404)

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'open')
    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_storage_serves_custom_404_sphinx_htmldir(self, storage_exists, storage_open):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX_HTMLDIR,
        )

        storage_exists.side_effect = [False, False, True]
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
            ]
        )
        self.assertEqual(response.status_code, 404)

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'open')
    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_storage_serves_custom_404_mkdocs(self, storage_exists, storage_open):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=MKDOCS,
        )

        storage_exists.side_effect = [False, False, True]
        response = self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
            ]
        )
        self.assertEqual(response.status_code, 404)

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'open')
    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_all_paths_checked_sphinx(self, storage_exists, storage_open):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX,
        )
        latest = self.project.versions.get(slug=LATEST)
        latest.documentation_type = SPHINX
        latest.save()

        storage_exists.return_value = False
        self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/404.html'),
                mock.call('html/project/latest/404.html'),
            ]
        )

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'open')
    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_all_paths_checked_sphinx_single_html(self, storage_exists, storage_open):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX_SINGLEHTML,
        )
        latest = self.project.versions.get(slug=LATEST)
        latest.documentation_type = SPHINX_SINGLEHTML
        latest.save()

        storage_exists.return_value = False
        self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/404.html'),
                mock.call('html/project/latest/404.html'),
            ]
        )

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_all_paths_checked_sphinx_html_dir(self, storage_exists):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX_HTMLDIR,
        )
        latest = self.project.versions.get(slug=LATEST)
        latest.documentation_type = SPHINX_HTMLDIR
        latest.save()

        storage_exists.return_value = False
        self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
                mock.call('html/project/fancy-version/404/index.html'),
                mock.call('html/project/latest/404.html'),
                mock.call('html/project/latest/404/index.html'),
            ]
        )

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_all_paths_checked_mkdocs(self,storage_exists):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=MKDOCS,
        )
        latest = self.project.versions.get(slug=LATEST)
        latest.documentation_type = MKDOCS
        latest.save()

        storage_exists.return_value = False
        self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
                mock.call('html/project/latest/404.html')
            ]
        )

    @mock.patch.object(BuildMediaFileSystemStorageTest, 'exists')
    def test_404_all_paths_checked_default_version_different_doc_type(self, storage_exists):
        self.project.versions.update(active=True, built=True)
        fancy_version = fixture.get(
            Version,
            slug='fancy-version',
            privacy_level=constants.PUBLIC,
            active=True,
            built=True,
            project=self.project,
            documentation_type=SPHINX,
        )
        latest = self.project.versions.get(slug=LATEST)
        latest.documentation_type = SPHINX_HTMLDIR
        latest.save()

        storage_exists.return_value = False
        self.client.get(
            reverse('proxito_404_handler', kwargs={'proxito_path': '/en/fancy-version/not-found'}),
            HTTP_HOST='project.readthedocs.io',
        )
        storage_exists.assert_has_calls(
            [
                mock.call('html/project/fancy-version/not-found/index.html'),
                mock.call('html/project/fancy-version/not-found/README.html'),
                mock.call('html/project/fancy-version/404.html'),
                mock.call('html/project/latest/404.html'),
                mock.call('html/project/latest/404/index.html'),
            ]
        )

    def test_sitemap_xml(self):
        self.project.versions.update(active=True)
        private_version = fixture.get(
            Version,
            privacy_level=constants.PRIVATE,
            project=self.project,
        )
        not_translated_public_version = fixture.get(
            Version,
            identifier='not-translated-version',
            verbose_name='not-translated-version',
            slug='not-translated-version',
            privacy_level=constants.PUBLIC,
            project=self.project,
            active=True
        )
        stable_version = fixture.get(
            Version,
            identifier='stable',
            verbose_name='stable',
            slug='stable',
            privacy_level=constants.PUBLIC,
            project=self.project,
            active=True
        )
        # This is a EXTERNAL Version
        external_version = fixture.get(
            Version,
            identifier='pr-version',
            verbose_name='pr-version',
            slug='pr-9999',
            project=self.project,
            active=True,
            type=EXTERNAL
        )
        # This also creates a Version `latest` Automatically for this project
        translation = fixture.get(
            Project,
            main_language_project=self.project,
            language='translation-es',
            privacy_level=constants.PUBLIC,
        )
        translation.versions.update(privacy_level=constants.PUBLIC)
        # sitemap hreflang should follow correct format.
        # ref: https://en.wikipedia.org/wiki/Hreflang#Common_Mistakes
        hreflang_test_translation_project = fixture.get(
            Project,
            main_language_project=self.project,
            language='zh_CN',
            privacy_level=constants.PUBLIC,
        )
        hreflang_test_translation_project.versions.update(
            privacy_level=constants.PUBLIC,
        )

        response = self.client.get(
            reverse('sitemap_xml'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/xml')
        for version in self.project.versions(manager=INTERNAL).filter(privacy_level=constants.PUBLIC):
            self.assertContains(
                response,
                self.project.get_docs_url(
                    version_slug=version.slug,
                    lang_slug=self.project.language,
                ),
            )

        # PRIVATE version should not appear here
        self.assertNotContains(
            response,
            self.project.get_docs_url(
                version_slug=private_version.slug,
                lang_slug=self.project.language,
            ),
        )
        # The `translation` project doesn't have a version named `not-translated-version`
        # so, the sitemap should not have a doc url for
        # `not-translated-version` with `translation-es` language.
        # ie: http://project.readthedocs.io/translation-es/not-translated-version/
        self.assertNotContains(
            response,
            self.project.get_docs_url(
                version_slug=not_translated_public_version.slug,
                lang_slug=translation.language,
            ),
        )
        # hreflang should use hyphen instead of underscore
        # in language and country value. (zh_CN should be zh-CN)
        self.assertContains(response, 'zh-CN')

        # External Versions should not be in the sitemap_xml.
        self.assertNotContains(
            response,
            self.project.get_docs_url(
                version_slug=external_version.slug,
                lang_slug=self.project.language,
            ),
        )

        # Check if STABLE version has 'priority of 1 and changefreq of weekly.
        self.assertEqual(
            response.context['versions'][0]['loc'],
            self.project.get_docs_url(
                version_slug=stable_version.slug,
                lang_slug=self.project.language,
            ),)
        self.assertEqual(response.context['versions'][0]['priority'], 1)
        self.assertEqual(response.context['versions'][0]['changefreq'], 'weekly')

        # Check if LATEST version has priority of 0.9 and changefreq of daily.
        self.assertEqual(
            response.context['versions'][1]['loc'],
            self.project.get_docs_url(
                version_slug='latest',
                lang_slug=self.project.language,
            ),)
        self.assertEqual(response.context['versions'][1]['priority'], 0.9)
        self.assertEqual(response.context['versions'][1]['changefreq'], 'daily')

    def test_sitemap_all_private_versions(self):
        self.project.versions.update(active=True, built=True, privacy_level=constants.PRIVATE)
        response = self.client.get(
            reverse('sitemap_xml'),
            HTTP_HOST='project.readthedocs.io',
        )
        self.assertEqual(response.status_code, 404)


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies;

import java.util.Iterator;

import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.common.core.command.ICompositeCommand;
import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EndpointDiagram2EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.Sequences2EditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TemplateTemplateCompartmentEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;

/**
 * @generated
 */
public class TemplateItemSemanticEditPolicy extends EsbBaseItemSemanticEditPolicy {

    /**
     * @generated
     */
    public TemplateItemSemanticEditPolicy() {
        super(EsbElementTypes.Template_3664);
    }

    /**
     * @generated
     */
    protected Command getDestroyElementCommand(DestroyElementRequest req) {
        View view = (View) getHost().getModel();
        CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null);
        cmd.setTransactionNestingEnabled(false);
        EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$
        if (annotation == null) {
            // there are indirectly referenced children, need extra commands: false
            addDestroyChildNodesCommand(cmd);
            addDestroyShortcutsCommand(cmd, view);
            // delete host element
            cmd.add(new DestroyElementCommand(req));
        } else {
            cmd.add(new DeleteCommand(getEditingDomain(), view));
        }
        return getGEFWrapper(cmd.reduce());
    }

    /**
     * @generated
     */
    private void addDestroyChildNodesCommand(ICompositeCommand cmd) {
        View view = (View) getHost().getModel();
        for (Iterator<?> nit = view.getChildren().iterator(); nit.hasNext();) {
            Node node = (Node) nit.next();
            switch (EsbVisualIDRegistry.getVisualID(node)) {
            case TemplateTemplateCompartmentEditPart.VISUAL_ID:
                for (Iterator<?> cit = node.getChildren().iterator(); cit.hasNext();) {
                    Node cnode = (Node) cit.next();
                    switch (EsbVisualIDRegistry.getVisualID(cnode)) {
                    case Sequences2EditPart.VISUAL_ID:
                        cmd.add(new DestroyElementCommand(
                                new DestroyElementRequest(getEditingDomain(), cnode.getElement(), false))); // directlyOwned: true
                        // don't need explicit deletion of cnode as parent's view deletion would clean child views as well
                        // cmd.add(new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand(getEditingDomain(), cnode));
                        break;
                    case EndpointDiagram2EditPart.VISUAL_ID:
                        cmd.add(new DestroyElementCommand(
                                new DestroyElementRequest(getEditingDomain(), cnode.getElement(), false))); // directlyOwned: true
                        // don't need explicit deletion of cnode as parent's view deletion would clean child views as well
                        // cmd.add(new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand(getEditingDomain(), cnode));
                        break;
                    }
                }
                break;
            }
        }
    }

}


text:
extern const struct SingleEntityRelatedToMappedEntityWithNestedMappedAttributesAttributes {
} SingleEntityRelatedToMappedEntityWithNestedMappedAttributesAttributes;

extern const struct SingleEntityRelatedToMappedEntityWithNestedMappedAttributesRelationships {
	__unsafe_unretained NSString *mappedEntity;
} SingleEntityRelatedToMappedEntityWithNestedMappedAttributesRelationships;

extern const struct SingleEntityRelatedToMappedEntityWithNestedMappedAttributesFetchedProperties {
} SingleEntityRelatedToMappedEntityWithNestedMappedAttributesFetchedProperties;

@class MappedEntity;

@interface SingleEntityRelatedToMappedEntityWithNestedMappedAttributesID : NSManagedObjectID {}
@end

@interface _SingleEntityRelatedToMappedEntityWithNestedMappedAttributes : NSManagedObject {}
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_;
+ (NSString*)entityName;
+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_;
- (SingleEntityRelatedToMappedEntityWithNestedMappedAttributesID*)objectID;

@property (nonatomic, strong) MappedEntity* mappedEntity;

//- (BOOL)validateMappedEntity:(id*)value_ error:(NSError**)error_;

@end

@interface _SingleEntityRelatedToMappedEntityWithNestedMappedAttributes (CoreDataGeneratedAccessors)

@end

@interface _SingleEntityRelatedToMappedEntityWithNestedMappedAttributes (CoreDataGeneratedPrimitiveAccessors)

- (MappedEntity*)primitiveMappedEntity;
- (void)setPrimitiveMappedEntity:(MappedEntity*)value;

@end


text:
package org.hisp.dhis.webapi.controller.event;

import org.hisp.dhis.schema.descriptors.TrackedEntityFormSchemaDescriptor;
import org.hisp.dhis.trackedentity.TrackedEntityForm;
import org.hisp.dhis.webapi.controller.AbstractCrudController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@Controller
@RequestMapping( value = TrackedEntityFormSchemaDescriptor.API_ENDPOINT )
public class TrackedEntityFormController
    extends AbstractCrudController<TrackedEntityForm>
{
}


text:
#connection-configuration {
    z-index: 1301;
    display: none;
    width: 700px;
    height: 400px;
}

#connection-configuration div.configuration-tab {
    overflow: auto;
    display: none;
}

/*
    Connection details.
*/

div.connection-terminal-label {
    height: 26px;
}

/*
    Connection settings.
*/

#relationship-names-container {
    height: 160px;
    padding-right: 0;
}

#relationship-names {
    padding: 2px;
    height: 150px;
    overflow-y: auto;
    overflow-x: hidden;
    border: 0 solid #cccccc;
    padding: 2px;
    padding-bottom: 0;
}

div.available-relationship-container {
    margin-bottom: 4px;
}

#connection-configuration div.relationship-name {
    display: inline-block;
    line-height: normal;
}

#connection-name-container {
    clear: left;
    float: left;
    margin-top: 10px;
    width: 180px;
}

div.undefined {
    color: #aaa;
    font-style: italic;
}

/* prioritizers */

#prioritizer-available, #prioritizer-selected {
    list-style-type: none;
    margin: 0px;
    background: #eaeef0;
    min-height: 32px;
    margin-bottom: 5px;
    padding: 2px;
}

#prioritizer-available li, #prioritizer-selected li {
    margin: 2px;
    padding: 5px;
    cursor: pointer;
    font-size: 1em;
    height: 12px;
    overflow: hidden;
}

#prioritizer-available li {
    background: #fff;
    border-top: 1px solid #CCDADB;
    border-right: 1px solid #CCDADB;
    border-bottom: 1px solid #CCDADB;
    border-left: 1px solid #CCDADB;
    color: #004849;
    font-weight: 500;
    cursor: grab;
    cursor: -moz-grab;
    cursor: -webkit-grab;
    line-height: 32px;
    height: 32px;
    padding: 0px 10px;
    box-shadow:0 1px 1px rgba(0,0,0,0.4);
}

#prioritizer-selected li {
    background: #355B6A;
    border-top: 1px solid #AAC1CE;
    border-right: 1px solid #85A6B8;
    border-bottom: 1px solid #618BA3;
    border-left: 1px solid #85A6B8;
    color: #fff;
    font-weight: bold;
    line-height: 32px;
    height: 32px;
    padding: 0px 10px;
}

#prioritizer-selected .draggable-control {
    float: right;
}

#prioritizer-selected .fa-remove {
    color: #fff;
}


text:
'use strict'

var invalidityReasons = [
    'outdated',
    'multiple_materials',
    'multiple_buildings',
    'building_fraction',
    'not_a_building'
];

module.exports = invalidityReasons;


text:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import os
from glob import glob

from PIL import Image
import subprocess
import logging
import time

from rhyno import Rhyno

logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.DEBUG)

hdlr = logging.FileHandler('ambracompare.log')
base_logger = logging.getLogger('')
base_logger.addHandler(hdlr)

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def same_size_erize(image_1, image_2):
    img_1 = Image.open(image_1)
    img_2 = Image.open(image_2)
    img_1_height, img_1_width = img_1.size
    img_2_height, img_2_width = img_2.size

    if img_1_height < img_2_height:
        height = img_2_height
        logger.info("cropping %s height to %s ..." % (image_1, img_2_height))
    elif img_2_height < img_1_height:
        height = img_1_height
        logger.info("cropping %s height to %s ..." % (image_2, img_1_height))
    else:
        height = img_2_height
        logger.debug("Both images have same height, no cropping necessary.")

    if img_1_width < img_2_width:
        width = img_2_width
        logger.info("cropping %s width to %s ..." % (image_1, img_2_width))
    elif img_2_width < img_1_width:
        width = img_1_width
        logger.info("cropping %s width to %s ..." % (image_2, img_1_width))
    else:
        width = img_2_width
        logger.debug("Both images have same width, no cropping necessary.")

    img_1 = img_1.crop((0, 0, height, width))
    img_1.save(image_1)

    img_2 = img_2.crop((0, 0, height, width))
    img_2.save(image_2)

def make_diff(image_1, image_2, diff):
    compare_proc = subprocess.Popen(["compare", image_1, image_2, diff],
                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    compare_proc.wait()
    logger.debug("imagemagick 'compare' return code: %i", compare_proc.returncode)
    return compare_proc.returncode

def compare_prod_stage(doi):
    stage_url_format = "http://plosone-stage.plos.org/article/info%%3Adoi%%2F10.1371%%2Fjournal.%s"
    prod_url_format = "http://www.plosone.org/article/info%%3Adoi%%2F10.1371%%2Fjournal.%s"

    stage_screenshot = get_screenshot(stage_url_format % doi, "%s-stage.png" % doi)
    prod_screenshot = get_screenshot(prod_url_format % doi, "%s-prod.png" % doi)

    same_size_erize("%s-stage.png" % doi, "%s-prod.png" % doi)
    make_diff("%s-stage.png" % doi, "%s-prod.png" % doi, "%s-diff.png" % doi)

def upload_webprod(filename):
    iad_loc = "iad-webprod-devstack01.int.plos.org:/var/spool/ambra/ingestion-queue/"
    logger.info("running: `scp %s %s`" % (filename, iad_loc))
    proc = subprocess.Popen(["scp", filename, iad_loc],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.wait()
    logger.debug("scp return code: %i", proc.returncode)

class WebprodDriver(object):
    article_url_format = "https://webprod.plosjournals.org/article/info%%3Adoi%%2F10.1371%%2Fjournal.%s"

    def __init__(self):
        self.webdriver = webdriver.Firefox()
 #TODO update to webrod

        self.webdriver.get('https://register-webprod.plosjournals.org/cas/login?service=http%3A%2F%2Fwebprod.plosjournals.org%2Fuser%2Fsecure%2FsecureRedirect.action%3FgoTo%3D%252Fhome.action')
        elem_email = self.webdriver.find_element_by_id('username')
        elem_email.send_keys("brakit@gmail.com") #TODO fill in
        elem_password = self.webdriver.find_element_by_id('password')
        elem_password.send_keys("123456") #TODO fill in
        self.webdriver.find_element_by_name('submit').click()

    def ingest(self, doi):
        logger.info("Web-based ingesting %s ..." % doi)
        self.webdriver.get('https://webprod.plosjournals.org/admin')
        try:
            self.webdriver.find_element_by_xpath("//input[@value='%s.zip']" % doi).click()
        except NoSuchElementException, e:
            logger.error("Could not find '%s.zip' in admin ingestibles" % doi)
            return
        self.webdriver.find_element_by_id('ingestArchives_force').click()
        self.webdriver.find_element_by_id('ingestArchives_action').click()

    def get_screenshot(self, url, filename):
        self.webdriver.get(url)
        self.webdriver.save_screenshot(filename)

    def get_screenshot_doi(self, doi, filename):
        logger.info("Capturing screenshot for %s ..." % doi)
        self.get_screenshot(self.article_url_format % doi, filename)

    def disable(self, doi):
        self.webdriver.get('https://webprod.plosjournals.org/admin')
        elem_doi_field = self.webdriver.find_element_by_xpath("//form[@id='disableArticle']/input[@name='article']")
        elem_doi_field.send_keys("info:doi/10.1371/journal.%s" % doi)
        self.webdriver.find_element_by_xpath("//form[@id='disableArticle']/input[@type='submit']").click()
        alert = self.webdriver.switch_to_alert()
        alert.accept()

    def close(self):
        self.webdriver.close()

def compare_web_rhino(webdriver, rdriver, doi, filename, output_location=""):
    logger.info("Comparing web vs. rhino ingest for %s ..." % doi)
    logger.info("Disabling %s if already exists" % doi)
    webdriver.disable(doi)
    logger.info("Uploading %s ..." % filename)
    upload_webprod(filename)
    webdriver.ingest(doi)
    webdriver.get_screenshot_doi(doi, '%s%s-web.png' % (output_location, doi))

    logger.info("Disabling %s if already exists" % doi)
    webdriver.disable(doi)
    logger.info("Uploading %s ..." % filename)
    upload_webprod(filename)
    logger.info("Rhino ingesting %s ..." % doi)
    rdriver.ingest('%s.zip' % doi, force_reingest=True)
    webdriver.get_screenshot_doi(doi, '%s%s-rhino.png' % (output_location, doi))

    logger.info("Creating visual diff for %s ..." % doi)
    make_diff('%s%s-web.png' % (output_location, doi), '%s%s-rhino.png' % (output_location, doi), '%s%s-diff.png' % (output_location, doi))

    logger.info("Finished comparing %s" % doi)

def get_articles_in_dir(dirpath):
    ret = []

    for f in glob(os.path.join(dirpath, "*.zip")):
        directory, filename = os.path.split(f)
        doi = filename[0:-4]
        ret += [(doi, f)]

    return ret

def get_random_ingested(n, dest):
    """
    get n articles from //ingested/ on stage and put in dest.
    INCOMPLETE
    """
    trans = paramiko.Transport(('stage.plos.org', 22))
    path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
    key = paramiko.DSSKey.from_private_key_file(path, password="")
    trans.connect(username='jlabarba', pkey=key)
    session = trans.open_channel("session")
    s = session.exec_command('ls')
    exit_status = session.recv_exit_status()
    print s
    print exit_status

if __name__ == "__main__":

    wpd = WebprodDriver()
    r = Rhyno('https://webprod.plosjournals.org/api/')

    articles = get_articles_in_dir('test/')
    for a in articles:
        print a
        try:
            compare_web_rhino(wpd, r, a[0], a[1], 'output/')
        except Exception, e:
            logger.error("Comparison for %s broke! See below ..." % a[0])
            logger.exception(e)

    wpd.close()


text:
#ifndef vq2BY_DEFAULT_H
#define vq2BY_DEFAULT_H

#include <vq2Concept.h>

namespace vq2 {
  namespace by_default {

    /**
     * This provides a class for basic vector operation functor when
     * the type is an actual vector (v = 0 have to work).
     */
    template<typename ANY>
    class VectorOp : public vq2::fits<vq2::concept::VectorOp> {
    public:
      void raz(ANY& v)                {v = 0;}
      void add(ANY& v, const ANY& w)  {v += w;}
      void div(ANY& v, double coef)   {v /= coef;}
      void mul(ANY& v, double coef)   {v *= coef;}
    };
  }
}

#endif


text:
package com.sage.cerberus.controller.resourceItems;

import java.util.stream.Collectors;

import com.sage.cerberus.model.Game;
import com.sage.cerberus.model.Platform;
import com.sage.cerberus.model.Publisher;

public class GameResourceItemBuilder implements Builder<Game, GameResourceItem>{

	Builder<Publisher, PublisherResourceItem> publisherBuider = new PublisherResourceItemBuilder();
	Builder<Platform, PlatformResourceItem> platformBuilder = new PlatformResourceItemBuilder();

	@Override
	public GameResourceItem build(Game game) {
		GameResourceItem gameResourceItem = new GameResourceItem();
		gameResourceItem.setId(game.getId());
		gameResourceItem.setName(game.getName());
		gameResourceItem.setReleaseDate(game.getReleaseDate());
		gameResourceItem.setPlatform(game.getPlatforms().stream().map(platformBuilder::build).collect(Collectors.toSet()));
		gameResourceItem.setPublisher(this.publisherBuider.build(game.getPublisher()));

		return gameResourceItem;
	}
}


text:
using System.Collections.Generic;

namespace Zenify.Nottingham.Services.Vendor.Robinhood.Models
{
    public class QuoteResponseWrapper
    {
        public IEnumerable<Quote> Results { get; set; }
    }
}


text:
 Improve this Doc

   View Source

RouteParams

      - type in module ngComponentRouter

Deprecated:

In an effort to keep synchronized with router changes in Angular 2, this implementation of the Component Router (ngComponentRouter module)
has been deprecated and will not receive further updates.
We are investigating backporting the Angular 2 Router to Angular 1, but alternatively, use the ngRoute module or community developed
projects (e.g. ui-router).

A map of parameters for a given route, passed as part of the ComponentInstruction to
the Lifecycle Hooks, such as $routerOnActivate and $routerOnDeactivate.


text:
package org.apache.sling.scripting.sightly.impl.html.dom;

import java.util.Collection;
import java.util.Map;
import java.util.Stack;

import org.apache.commons.lang.StringUtils;
import org.apache.sling.scripting.sightly.impl.compiler.Syntax;
import org.apache.sling.scripting.sightly.impl.compiler.frontend.CompilerContext;
import org.apache.sling.scripting.sightly.impl.compiler.frontend.ElementContext;
import org.apache.sling.scripting.sightly.impl.compiler.frontend.ExpressionParser;
import org.apache.sling.scripting.sightly.impl.compiler.frontend.ExpressionWrapper;
import org.apache.sling.scripting.sightly.impl.compiler.frontend.Fragment;
import org.apache.sling.scripting.sightly.impl.compiler.frontend.Interpolation;
import org.apache.sling.scripting.sightly.impl.compiler.ris.command.Patterns;
import org.apache.sling.scripting.sightly.impl.filter.ExpressionContext;
import org.apache.sling.scripting.sightly.impl.filter.Filter;
import org.apache.sling.scripting.sightly.impl.compiler.expression.Expression;
import org.apache.sling.scripting.sightly.impl.compiler.expression.ExpressionNode;
import org.apache.sling.scripting.sightly.impl.compiler.expression.node.BinaryOperation;
import org.apache.sling.scripting.sightly.impl.compiler.expression.node.BinaryOperator;
import org.apache.sling.scripting.sightly.impl.compiler.expression.node.BooleanConstant;
import org.apache.sling.scripting.sightly.impl.compiler.expression.node.Identifier;
import org.apache.sling.scripting.sightly.impl.compiler.expression.node.StringConstant;
import org.apache.sling.scripting.sightly.impl.plugin.MarkupContext;
import org.apache.sling.scripting.sightly.impl.plugin.Plugin;
import org.apache.sling.scripting.sightly.impl.plugin.PluginCallInfo;
import org.apache.sling.scripting.sightly.impl.plugin.PluginInvoke;
import org.apache.sling.scripting.sightly.impl.compiler.ris.command.Conditional;
import org.apache.sling.scripting.sightly.impl.compiler.ris.command.OutText;
import org.apache.sling.scripting.sightly.impl.compiler.ris.command.OutVariable;
import org.apache.sling.scripting.sightly.impl.compiler.ris.command.VariableBinding;
import org.apache.sling.scripting.sightly.impl.compiler.util.SymbolGenerator;
import org.apache.sling.scripting.sightly.impl.compiler.util.stream.PushStream;
import org.apache.sling.scripting.sightly.impl.html.MarkupUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation for the markup handler
 */
public class MarkupHandler {

    private static final Logger log = LoggerFactory.getLogger(MarkupHandler.class);

    private final PushStream stream;
    private final SymbolGenerator symbolGenerator = new SymbolGenerator();
    private final ExpressionParser expressionParser = new ExpressionParser();
    private final Map<String, Plugin> pluginRegistry;
    private final CompilerContext compilerContext;
    private final ExpressionWrapper expressionWrapper;

    private final Stack<ElementContext> elementStack = new Stack<ElementContext>();

    public MarkupHandler(PushStream stream, Map<String, Plugin> pluginRegistry, Collection<Filter> filters) {
        this.stream = stream;
        this.pluginRegistry = pluginRegistry;
        this.expressionWrapper = new ExpressionWrapper(filters);
        this.compilerContext = new CompilerContext(symbolGenerator, expressionWrapper);
    }

    public void onOpenTagStart(String markup, String tagName) {
        ElementContext context = new ElementContext(tagName, markup);
        elementStack.push(context);
    }

    public void onAttribute(String name, String value) {
        ElementContext context = elementStack.peek();
        if (Syntax.isPluginAttribute(name)) {
            handlePlugin(name, StringUtils.defaultString(value, ""), context);
        } else {
            context.addAttribute(name, value);
        }
    }

    public void onOpenTagEnd(String markup) {
        ElementContext context = elementStack.peek();
        PluginInvoke invoke = context.pluginInvoke();
        invoke.beforeElement(stream, context.getTagName());
        boolean slyTag = "sly".equalsIgnoreCase(context.getTagName());
        if (slyTag) {
            Patterns.beginStreamIgnore(stream);
        }
        invoke.beforeTagOpen(stream);
        out(context.getOpenTagStartMarkup());
        invoke.beforeAttributes(stream);
        traverseAttributes(context, invoke);
        invoke.afterAttributes(stream);
        out(markup);
        invoke.afterTagOpen(stream);
        if (slyTag) {
            Patterns.endStreamIgnore(stream);
        }
        invoke.beforeChildren(stream);
    }

    private void traverseAttributes(ElementContext context, PluginInvoke invoke) {
        for (Map.Entry<String, Object> attribute : context.getAttributes()) {
            String attrName = attribute.getKey();
            Object contentObj = attribute.getValue();
            if (contentObj == null || contentObj instanceof String) {
                String content = (String) contentObj;
                emitAttribute(attrName, content, invoke);
            } else if (contentObj instanceof Map.Entry) {
                Map.Entry entry = (Map.Entry) contentObj;
                PluginCallInfo info = (PluginCallInfo) entry.getKey();
                Expression expression = (Expression) entry.getValue();
                invoke.onPluginCall(stream, info, expression);
            }
        }
    }

    private void emitAttribute(String name, String content, PluginInvoke invoke) {
        invoke.beforeAttribute(stream, name);
        if (content == null) {
            emitSimpleTextAttribute(name, null, invoke);
        } else {
            Interpolation interpolation = expressionParser.parseInterpolation(content);
            String text = tryAsSimpleText(interpolation);
            if (text != null) {
                emitSimpleTextAttribute(name, text, invoke);
            } else {
                emitExpressionAttribute(name, interpolation, invoke);
            }
        }
        invoke.afterAttribute(stream, name);
    }

    private void emitSimpleTextAttribute(String name, String textValue, PluginInvoke invoke) {
        emitAttributeStart(name);
        invoke.beforeAttributeValue(stream, name, new StringConstant(textValue));
        if (textValue != null) {
            emitAttributeValueStart();
            textValue = escapeQuotes(textValue);
            out(textValue);
            emitAttributeEnd();
        }
        invoke.afterAttributeValue(stream, name);
    }

    private String escapeQuotes(String textValue) {
        return textValue.replace("\"", """);
    }

    private void emitExpressionAttribute(String name, Interpolation interpolation, PluginInvoke invoke) {
        interpolation = attributeChecked(name, interpolation);
        if (interpolation.size() == 1) {
            emitSingleFragment(name, interpolation, invoke);
        } else {
            emitMultipleFragment(name, interpolation, invoke);
        }
    }

    private void emitMultipleFragment(String name, Interpolation interpolation, PluginInvoke invoke) {
        // Simplified algorithm for attribute output, which works when the interpolation is not of size 1. In this
        // case we are certain that the attribute value cannot be the boolean value true, so we can skip this test
        // altogether
        Expression expression = expressionWrapper.transform(interpolation, getAttributeMarkupContext(name), ExpressionContext.ATTRIBUTE);
        String attrContent = symbolGenerator.next("attrContent");
        String shouldDisplayAttr = symbolGenerator.next("shouldDisplayAttr");
        stream.emit(new VariableBinding.Start(attrContent, expression.getRoot()));
        stream.emit(
                new VariableBinding.Start(
                        shouldDisplayAttr,
                        new BinaryOperation(
                                BinaryOperator.OR,
                                new Identifier(attrContent),
                                new BinaryOperation(BinaryOperator.EQ, new StringConstant("false"), new Identifier(attrContent))
                        )
                )
        );
        stream.emit(new Conditional.Start(shouldDisplayAttr, true));
        emitAttributeStart(name);
        invoke.beforeAttributeValue(stream, name, expression.getRoot());
        emitAttributeValueStart();
        stream.emit(new OutVariable(attrContent));
        emitAttributeEnd();
        invoke.afterAttributeValue(stream, name);
        stream.emit(Conditional.END);
        stream.emit(VariableBinding.END);
        stream.emit(VariableBinding.END);
    }

    private void emitSingleFragment(String name, Interpolation interpolation, PluginInvoke invoke) {
        Expression valueExpression = expressionWrapper.transform(interpolation, null, ExpressionContext.ATTRIBUTE); //raw expression
        String attrValue = symbolGenerator.next("attrValue"); //holds the raw attribute value
        String attrContent = symbolGenerator.next("attrContent"); //holds the escaped attribute value
        String isTrueVar = symbolGenerator.next("isTrueAttr"); // holds the comparison (attrValue == true)
        String shouldDisplayAttr = symbolGenerator.next("shouldDisplayAttr");
        MarkupContext markupContext = getAttributeMarkupContext(name);
        Expression contentExpression = valueExpression.withNode(new Identifier(attrValue));
        ExpressionNode node = valueExpression.getRoot();
        stream.emit(new VariableBinding.Start(attrValue, node)); //attrContent = <expr>
        stream.emit(new VariableBinding.Start(attrContent, expressionWrapper.adjustToContext(contentExpression, markupContext,
                ExpressionContext.ATTRIBUTE).getRoot()));
        stream.emit(
                new VariableBinding.Start(
                        shouldDisplayAttr,
                        new BinaryOperation(
                                BinaryOperator.OR,
                                new Identifier(attrContent),
                                new BinaryOperation(BinaryOperator.EQ, new StringConstant("false"), new Identifier(attrValue))
                        )
                )
        );
        stream.emit(new Conditional.Start(shouldDisplayAttr, true)); // if (attrContent)
        emitAttributeStart(name);   //write("attrName");
        invoke.beforeAttributeValue(stream, name, node);
        stream.emit(new VariableBinding.Start(isTrueVar, //isTrueAttr = (attrValue == true)
                new BinaryOperation(BinaryOperator.EQ, new Identifier(attrValue), BooleanConstant.TRUE)));
        stream.emit(new Conditional.Start(isTrueVar, false)); //if (!isTrueAttr)
        emitAttributeValueStart(); // write("='");
        stream.emit(new OutVariable(attrContent)); //write(attrContent)
        emitAttributeEnd(); //write("'");
        stream.emit(Conditional.END); //end if isTrueAttr
        stream.emit(VariableBinding.END); //end scope for isTrueAttr
        invoke.afterAttributeValue(stream, name);
        stream.emit(Conditional.END); //end if attrContent
        stream.emit(VariableBinding.END);
        stream.emit(VariableBinding.END); //end scope for attrContent
        stream.emit(VariableBinding.END); //end scope for attrValue
    }

    private void emitAttributeStart(String name) {
        out(" " + name);
    }

    private void emitAttributeValueStart() {
        out("=\"");
    }

    private void emitAttributeEnd() {
        out("\"");
    }

    public void onCloseTag(String markup) {
        ElementContext context = elementStack.pop();
        PluginInvoke invoke = context.pluginInvoke();
        invoke.afterChildren(stream);
        boolean selfClosingTag = StringUtils.isEmpty(markup);
        boolean slyTag = "sly".equalsIgnoreCase(context.getTagName());
        if (slyTag) {
            Patterns.beginStreamIgnore(stream);
        }
        invoke.beforeTagClose(stream, selfClosingTag);
        out(markup);
        invoke.afterTagClose(stream, selfClosingTag);
        if (slyTag) {
            Patterns.endStreamIgnore(stream);
        }
        invoke.afterElement(stream);
    }

    public void onText(String text) {
        String tag = currentElementTag();
        boolean explicitContextRequired = isExplicitContextRequired(tag);
        MarkupContext markupContext = (explicitContextRequired) ? null : MarkupContext.TEXT;
        outText(text, markupContext);
    }

    public void onComment(String markup) {
        if (!Syntax.isSightlyComment(markup)) {
            outText(markup, MarkupContext.COMMENT);
        }
    }

    public void onDataNode(String markup) {
        out(markup);
    }

    public void onDocType(String markup) {
        out(markup);
    }

    public void onDocumentFinished() {
        this.stream.signalDone();
    }

    private void outText(String content, MarkupContext context) {
        Interpolation interpolation = expressionParser.parseInterpolation(content);
        if (context == null) {
            interpolation = requireContext(interpolation);
        }
        String text = tryAsSimpleText(interpolation);
        if (text != null) {
            out(text);
        } else {
            outExprNode(expressionWrapper.transform(interpolation, context, ExpressionContext.TEXT).getRoot());
        }
    }

    private Interpolation requireContext(Interpolation interpolation) {
        Interpolation result = new Interpolation();
        for (Fragment fragment : interpolation.getFragments()) {
            Fragment addedFragment;
            if (fragment.isString()) {
                addedFragment = fragment;
            } else {
                if (fragment.getExpression().containsOption(Syntax.CONTEXT_OPTION)) {
                    addedFragment = fragment;
                } else {
                    String currentTag = currentElementTag();
                    log.warn("Element {} requires that all expressions have an explicit context specified. Expression will be " +
                            "replaced by the empty string", currentTag);
                    addedFragment = new Fragment.Expr(new Expression(StringConstant.EMPTY));
                }
            }
            result.addFragment(addedFragment);
        }
        return result;
    }

    private Interpolation attributeChecked(String attributeName, Interpolation interpolation) {
        if (!MarkupUtils.isSensitiveAttribute(attributeName)) {
            return interpolation;
        }
        Interpolation newInterpolation = new Interpolation();
        for (Fragment fragment : interpolation.getFragments()) {
            Fragment addedFragment = fragment;
            if (fragment.isExpression()) {
                Expression expression = fragment.getExpression();
                if (!expression.containsOption(Syntax.CONTEXT_OPTION)) {
                    log.warn("All expressions within the value of attribute {} need to have an explicit context option. The expression will be erased.",
                            attributeName);
                    addedFragment = new Fragment.Text("");
                }
            }
            newInterpolation.addFragment(addedFragment);
        }
        return newInterpolation;
    }

    private void outExprNode(ExpressionNode node) {
        String variable = symbolGenerator.next();
        stream.emit(new VariableBinding.Start(variable, node));
        stream.emit(new OutVariable(variable));
        stream.emit(VariableBinding.END);
    }

    private String tryAsSimpleText(Interpolation interpolation) {
        if (interpolation.size() == 1) {
            Fragment fragment = interpolation.getFragment(0);
            if (fragment.isString()) {
                return fragment.getText();
            }
        } else if (interpolation.size() == 0) {
            return "";
        }
        return null;
    }

    private void out(String text) {
        stream.emit(new OutText(text));
    }

    private void handlePlugin(String name, String value, ElementContext context) {
        PluginCallInfo callInfo = Syntax.parsePluginAttribute(name);
        if (callInfo != null) {
            Plugin plugin = obtainPlugin(callInfo.getName());
            ExpressionContext expressionContext = ExpressionContext.getContextForPlugin(plugin.name());
            Expression expr = expressionWrapper.transform(expressionParser.parseInterpolation(value), null, expressionContext);
            PluginInvoke invoke = plugin.invoke(expr, callInfo, compilerContext);
            context.addPlugin(invoke, plugin.priority());
            context.addPluginCall(name, callInfo, expr);
        }
    }

    private Plugin obtainPlugin(String name) {
        Plugin plugin = pluginRegistry.get(name);
        if (plugin == null) {
            throw new UnsupportedOperationException(String.format("Plugin %s does not exist", name));
        }
        return plugin;
    }

    private MarkupContext getAttributeMarkupContext(String attributeName) {
        if ("src".equalsIgnoreCase(attributeName) || "href".equalsIgnoreCase(attributeName)) {
            return MarkupContext.URI;
        }
        return MarkupContext.ATTRIBUTE;
    }

    private String currentElementTag() {
        if (elementStack.isEmpty()) {
            return null;
        }
        ElementContext current = elementStack.peek();
        return current.getTagName();
    }

    private boolean isExplicitContextRequired(String parentElementName) {
        return parentElementName != null &&
                ("script".equals(parentElementName) || "style".equals(parentElementName));
    }
}


text:
<?php /** MicroInterfaceOutput */

namespace Micro\Web;

/**
 * Interface IOutput
 *
 * @author Oleg Lunegov <testuser@mail.linpax.org>
 * @link https://github.com/linpax/microphp-framework
 * @copyright Copyright (c) 2013 Oleg Lunegov
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
 * @package Micro
 * @subpackage Web
 * @version 1.0
 * @since 1.0
 * @interface
 */
interface IOutput
{
    /**
     * Send data to browser|console
     *
     * @access public
     * @return void
     */
    public function send();
}