text:
package org.kaleidofoundry.mail.dispatcher;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.kaleidofoundry.mail.MailTestConstants.CC_ADRESS;
import static org.kaleidofoundry.mail.MailTestConstants.FROM_ADRESS;
import static org.kaleidofoundry.mail.MailTestConstants.INVALID_MAIL_ADDRESS_01;
import static org.kaleidofoundry.mail.MailTestConstants.MAIL_BODY_HTML;
import static org.kaleidofoundry.mail.MailTestConstants.MAIL_ENCODING;
import static org.kaleidofoundry.mail.MailTestConstants.MAIL_HTML;
import static org.kaleidofoundry.mail.MailTestConstants.MAIL_PRIORITY;
import static org.kaleidofoundry.mail.MailTestConstants.MAIL_SUBJECT;
import static org.kaleidofoundry.mail.MailTestConstants.TO_ADRESS;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

import org.junit.Test;
import org.kaleidofoundry.core.store.FileStore;
import org.kaleidofoundry.core.store.FileStoreFactory;
import org.kaleidofoundry.core.util.StringHelper;
import org.kaleidofoundry.mail.InvalidMailAddressException;
import org.kaleidofoundry.mail.MailAttachmentBean;
import org.kaleidofoundry.mail.MailException;
import org.kaleidofoundry.mail.MailMessage;
import org.kaleidofoundry.mail.MailMessageBean;
import org.kaleidofoundry.mail.MailTestConstants;
import org.kaleidofoundry.mail.MailingDispatcherReport;
import org.kaleidofoundry.mail.session.MailSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dumbster.smtp.SmtpServer;

public abstract class AbstractMailDispatcherTest {

   private static Logger LOGGER = LoggerFactory.getLogger(AbstractMailDispatcherTest.class);

   private FileStore attachementStore;

   public AbstractMailDispatcherTest() {
	attachementStore = FileStoreFactory.provides("classpath:/");
   }

   protected abstract MailDispatcher getMailDispatcher();

   protected abstract MailMessageErrorHandler getMailMessageErrorHandler();

   @Test
   public void sendMail() throws MailException {

	assertNotNull(getMailDispatcher());

	MailMessage message = MailTestConstants.createDefaultMailMessage();

	try {
	   if (getMailMessageErrorHandler() != null) {
		getMailDispatcher().send(getMailMessageErrorHandler(), message);
	   } else {
		getMailDispatcher().send(message);
	   }
	} catch (MailException mae) {
	   LOGGER.error("sendMail.send", mae);
	   if (mae instanceof MailDispatcherException) {
		LOGGER.error(((MailDispatcherException) mae).getReport().toString());
	   }
	   throw mae;
	}
   }

   @Test
   public void sendMailWithAttachments() throws MailDispatcherException, MailException, FileNotFoundException, IOException {
	assertNotNull(getMailDispatcher());

	MailMessage message = MailTestConstants.createDefaultMailMessage();
	// first attach using POJO
	message.attach(new MailAttachmentBean("helloworld.xml", attachementStore.get("attachments/helloworld.xml").getInputStream(), null, "text/xml", "UTF-8"));
	// second attach using filestore
	message.attach("helloworld.gif", attachementStore.get("attachments/helloworld.gif"));
	// third attach using uri
	message.attach("helloworld.txt", "/${basedir}/src/test/resources/attachments/helloworld.txt", "UTF-8");

	try {
	   if (getMailMessageErrorHandler() != null) {
		getMailDispatcher().send(getMailMessageErrorHandler(), message);
	   } else {
		getMailDispatcher().send(message);
	   }
	} catch (MailException mae) {
	   LOGGER.error("sendMailWithAttachments.send", mae);
	   if (mae instanceof MailDispatcherException) {
		LOGGER.error(((MailDispatcherException) mae).getReport().toString());
	   }
	   throw mae;
	}
   }

   @Test
   public void sendMailWithoutFromAddress() throws MailException {
	MailMessage message = new MailMessageBean();
	try {
	   message.withSubject(MAIL_SUBJECT).withBody(MAIL_BODY_HTML).withBodyAs(MAIL_HTML).withBodyCharSet(MAIL_ENCODING).withPriority(MAIL_PRIORITY)
		   .withToAddresses(TO_ADRESS);

	   if (getMailMessageErrorHandler() != null) {
		getMailDispatcher().send(getMailMessageErrorHandler(), message);
	   } else {
		getMailDispatcher().send(message);
		fail();
	   }

	} catch (MailDispatcherException mde) {
	   sendMailWithoutFromAddressAssertions(message, mde);
	} catch (MailException mae) {
	   LOGGER.error(mae.getMessage(), mae);
	   if (mae instanceof MailDispatcherException) {
		LOGGER.error(((MailDispatcherException) mae).getReport().toString());
	   }
	   throw mae;
	}
   }

   @Test
   public void sendMailWithoutAddress() {
	MailMessage message = new MailMessageBean();
	try {
	   message.withSubject(MAIL_SUBJECT).withBody(MAIL_BODY_HTML).withBodyAs(MAIL_HTML).withBodyCharSet(MAIL_ENCODING).withFromAddress(FROM_ADRESS)
		   .withPriority(MAIL_PRIORITY);

	   if (getMailMessageErrorHandler() != null) {
		getMailDispatcher().send(getMailMessageErrorHandler(), message);
	   } else {
		getMailDispatcher().send(message);
		fail();
	   }

	} catch (MailDispatcherException mde) {
	   LOGGER.debug("sendMailWithAUniqueInvalidAddress.MailDispatcherException", mde);
	   assertEquals("mail.service.send.error", mde.getCode());

	   final MailingDispatcherReport mailReport = mde.getReport();

	   assertNotNull(mailReport);
	   assertNotNull(mailReport.getInvalidAddresses());
	   assertTrue(mailReport.getInvalidAddresses().isEmpty());

	   assertNotNull(mailReport.getMailExceptions());
	   assertEquals(1, mailReport.getMailExceptions().size());

	   MailException mae = mailReport.getMailExceptions().get(message);
	   assertTrue(mae instanceof InvalidMailAddressException);
	   assertEquals("mail.service.message.address.none", mae.getCode());
	   assertTrue(((InvalidMailAddressException) mae).getInvalidAddresses().isEmpty());

	} catch (MailSessionException mse) {
	   LOGGER.error(mse.getMessage(), mse);
	   fail();
	}
   }

   @Test
   // send with only one address that is invalid
   public void sendMailWithAUniqueInvalidAddress() {

	MailMessage message = null;
	try {
	   message = new MailMessageBean();
	   message.withSubject(MAIL_SUBJECT).withBody(MAIL_BODY_HTML).withBodyAs(MAIL_HTML).withBodyCharSet(MAIL_ENCODING).withFromAddress(FROM_ADRESS)
		   .withPriority(MAIL_PRIORITY).getToAddresses().add(INVALID_MAIL_ADDRESS_01);

	   if (getMailMessageErrorHandler() != null) {
		getMailDispatcher().send(getMailMessageErrorHandler(), message);
	   } else {
		getMailDispatcher().send(message);
		fail();
	   }

	} catch (MailDispatcherException mde) {
	   LOGGER.debug("sendMailWithAUniqueInvalidAddress.MailDispatcherException", mde);
	   final MailingDispatcherReport mailReport = mde.getReport();

	   assertEquals("mail.service.send.error", mde.getCode());

	   assertNotNull(mailReport);
	   assertNotNull(mailReport.getInvalidAddresses());
	   assertEquals(1, mailReport.getInvalidAddresses().size());
	   assertTrue(mailReport.getInvalidAddresses().get(message).contains(INVALID_MAIL_ADDRESS_01));

	   assertNotNull(mailReport.getMailExceptions());
	   assertEquals(1, mailReport.getMailExceptions().size());

	   MailException mae = mailReport.getMailExceptions().get(message);
	   assertTrue(mae instanceof InvalidMailAddressException);
	   assertEquals("mail.service.message.address.invalid", mae.getCode());

	   assertArrayEquals(new String[] { INVALID_MAIL_ADDRESS_01 }, ((InvalidMailAddressException) mae).getInvalidAddresses().toArray(new String[0]));

	} catch (MailSessionException mse) {
	   LOGGER.error(mse.getMessage(), mse);
	   fail();
	}
   }

   @Test
   // send several mails with valid and invalid address
   public void sendMailWithValidAndInvalidAddress() {
	MailMessage message = new MailMessageBean();

	try {
	   message.withSubject(MAIL_SUBJECT).withBody(MAIL_BODY_HTML).withBodyAs(MAIL_HTML).withBodyCharSet(MAIL_ENCODING).withFromAddress(FROM_ADRESS)
		   .withPriority(MAIL_PRIORITY);
	   message.withToAddresses(TO_ADRESS);
	   message.getToAddresses().add("wrongmail.com");

	   if (getMailMessageErrorHandler() != null) {
		getMailDispatcher().send(getMailMessageErrorHandler(), message);
	   } else {
		getMailDispatcher().send(message);
		fail();
	   }

	} catch (MailDispatcherException mde) {
	   LOGGER.debug("sendMailWithAUniqueInvalidAddress.MailDispatcherException", mde);
	   assertEquals("mail.service.send.error", mde.getCode());

	   final MailingDispatcherReport mailReport = mde.getReport();

	   assertNotNull(mailReport);
	   assertNotNull(mailReport.getInvalidAddresses());
	   assertEquals(1, mailReport.getInvalidAddresses().size());
	   assertTrue(mailReport.getInvalidAddresses().get(message).contains(INVALID_MAIL_ADDRESS_01));

	   assertNotNull(mailReport.getMailExceptions());
	   assertEquals(1, mailReport.getMailExceptions().size());

	   MailException mae = mailReport.getMailExceptions().get(message);
	   assertTrue(mae instanceof InvalidMailAddressException);
	   assertEquals("mail.service.message.address.invalid", mae.getCode());
	   assertEquals(((InvalidMailAddressException) mae).getInvalidAddresses(), Arrays.asList(INVALID_MAIL_ADDRESS_01));

	} catch (MailSessionException mse) {
	   LOGGER.error(mse.getMessage(), mse);
	   fail();
	}
   }

   public static void mailAssertions(SmtpServer server, int mailIndex) {
	assertEquals(1, server.getEmailCount());
	assertEquals(String.valueOf(MAIL_PRIORITY), server.getMessage(mailIndex).getFirstHeaderValue("X-Priority"));
	assertEquals(FROM_ADRESS, server.getMessage(mailIndex).getFirstHeaderValue("From"));
	assertArrayEquals(TO_ADRESS, extractEmails(server.getMessage(mailIndex), "To"));
	assertArrayEquals(CC_ADRESS, extractEmails(server.getMessage(mailIndex), "Cc"));
	// assertArrayEquals(BCC_ADRESS, extractEmails(server.getMessage(mailIndex), "Bcc"));
	assertEquals(MAIL_SUBJECT, server.getMessage(mailIndex).getFirstHeaderValue("Subject"));
	assertTrue(server.getMessage(mailIndex).getBody().contains(MAIL_BODY_HTML));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Type: " + (MAIL_HTML ? "text/html" : "text/plain")));
	assertTrue(server.getMessage(mailIndex).getBody().contains("charset=" + MAIL_ENCODING));
   }

   public static void mailWithAttachmentsAssertions(SmtpServer server, int mailIndex) {
	assertEquals(1, server.getEmailCount());
	assertEquals(String.valueOf(MAIL_PRIORITY), server.getMessage(mailIndex).getFirstHeaderValue("X-Priority"));
	assertEquals(FROM_ADRESS, server.getMessage(mailIndex).getFirstHeaderValue("From"));
	assertArrayEquals(TO_ADRESS, extractEmails(server.getMessage(mailIndex), "To"));
	assertArrayEquals(CC_ADRESS, extractEmails(server.getMessage(mailIndex), "Cc"));
	// assertArrayEquals(BCC_ADRESS, extractEmails(server.getMessage(mailIndex), "Bcc"));
	assertEquals(MAIL_SUBJECT, server.getMessage(mailIndex).getFirstHeaderValue("Subject"));
	assertTrue(server.getMessage(mailIndex).getBody().contains(MAIL_BODY_HTML));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Type: " + (MAIL_HTML ? "text/html" : "text/plain")));
	assertTrue(server.getMessage(mailIndex).getBody().contains("charset=" + MAIL_ENCODING));

	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Type: text/html; charset=UTF-8"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Transfer-Encoding: 7bit"));

	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Type: text/xml; charset=UTF-8; name=helloworld.xml"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Transfer-Encoding: quoted-printable"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Disposition: attachment; filename=helloworld.xml"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("<line>this is an email attachment with some specials characters</line>"));

	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Type: image/gif; name=helloworld.gif"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Transfer-Encoding: base64"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Disposition: attachment; filename=helloworld.gif"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("R0lGODlhvAIsAfcAAHPLLiEkIqQnKhkoKjNKYjNUJ9Amc3FrJJAmarInV/LMmP4mavvmsycoHTYo"));

	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Type: text/plain; charset=UTF-8; name=helloworld.txt"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Transfer-Encoding: 7bit"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("Content-Disposition: attachment; filename=helloworld.txt"));
	assertTrue(server.getMessage(mailIndex).getBody().contains("this is an email attachment"));
   }

   public static void sendMailWithoutFromAddressAssertions(MailMessage message, MailDispatcherException mde) {

	LOGGER.debug("sendMailWithAUniqueInvalidAddress.MailDispatcherException", mde);
	assertEquals("mail.service.send.error", mde.getCode());

	final MailingDispatcherReport mailReport = mde.getReport();

	assertNotNull(mailReport);
	assertNotNull(mailReport.getInvalidAddresses());
	assertTrue(mailReport.getInvalidAddresses().isEmpty());

	assertNotNull(mailReport.getMailExceptions());
	assertEquals(1, mailReport.getMailExceptions().size());

	MailException mae = mailReport.getMailExceptions().get(message);
	assertTrue(mae instanceof InvalidMailAddressException);
	assertEquals("mail.service.message.fromaddress.none", mae.getCode());
	assertTrue(((InvalidMailAddressException) mae).getInvalidAddresses().isEmpty());

   }

   public static String[] extractEmails(com.dumbster.smtp.MailMessage message, String headerField) {
	String[] adresses = StringHelper.split(message.getFirstHeaderValue(headerField), ",");
	if (adresses != null) {
	   for (int i = 0; i < adresses.length; i++) {
		adresses[i] = adresses[i].trim();
	   }
	}
	return adresses;
   }

}


text:
package edu.gemini.spModel.gemini.parallacticangle;

import edu.gemini.pot.sp.ISPObservation;
import edu.gemini.pot.sp.SPComponentType;
import edu.gemini.shared.util.immutable.ImOption;
import edu.gemini.shared.util.immutable.Option;
import edu.gemini.spModel.core.Angle;
import edu.gemini.spModel.core.Angle$;
import edu.gemini.spModel.inst.ParallacticAngleSupport;
import edu.gemini.spModel.obs.ObsTargetCalculatorService;
import edu.gemini.spModel.obscomp.SPInstObsComp;

/**
 * A superclass for instruments that support the parallactic angle feature with most of the implementation in place.
 */
public abstract class ParallacticAngleSupportInst extends SPInstObsComp implements ParallacticAngleSupport {

    /**
     * Constructor and methods for parallactic angle support.
     */
    protected ParallacticAngleSupportInst(final SPComponentType type) {
        super(type);
    }

    /**
     * Perform the parallactic angle computation for the observation.
     * Instruments who need specific modifications based on settings should override this, e.g. GMOS.
     */
    @Override
    public Option<Angle> calculateParallacticAngle(final ISPObservation obs) {
        return ImOption.fromScalaOpt(ObsTargetCalculatorService.targetCalculation(obs))
                .flatMap(targetCalculator -> ImOption.fromScalaOpt(targetCalculator.weightedMeanParallacticAngle()))
                .map(angleObj -> Angle$.MODULE$.fromDegrees((double)angleObj));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.sourceforge.mayfly.acceptance;

import java.sql.ResultSet;

public class PerformanceTest extends SqlTestCase {

    private static final int COLUMNS_PER_TABLE = 15;
    private static final int TABLE_COUNT = 30;
    private static final int TABLES_TO_INSERT_INTO = 10;
    private static final int ROWS_TO_INSERT = 3;

    // this test is not part of the default build because it is a bit slow,
    // and more importantly because it contains few assertions, so it is
    // more interesting for manual than automated use.
    public void xtestTypicalUnitTest() throws Exception {
        long start = System.currentTimeMillis();
        createTables();
        insertSomeData();
        dropTables();
        long end = System.currentTimeMillis();
        if (false) {
            System.out.println("Elapsed time = " + (end - start) / 1000.0 + " s");
        }
    }

    public void xtestLotsOfRows() throws Exception {
        // At the moment, I'm getting 360 ms for hypersonic;
        // 111 s for MySQL (4.1.21 on Windows);
        // 953 ms for Mayfly.
        // (try MySQL 5.x on Linux; I think it is faster).
        execute("create table foo(x integer, y integer, z integer, w varchar(50))");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i) {
            execute("insert into foo(x, y, w) values (" +
                i + ", " + i % 100 + ", " + "'string " + i + "')");
        }
        long end = System.currentTimeMillis();
        System.out.println("Elapsed time = " + (end - start) / 1000.0 + " s");
    }

    public void xtestLotsOfRowsWithUnique() throws Exception {
        // Really slow for mayfly (15x slower than without unique
        // on 10,000 rows),
        // once we get to more than about 1000 rows (or so).
        execute(
            "create table foo(x integer, y integer, z integer, w varchar(50)" +
            ",unique(x), unique(y)" +
            ")");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i) {
            execute("insert into foo(x, y, w) values (" +
                i + ", " + (i + 100) + ", " + "'string " + i + "')");
        }
        long end = System.currentTimeMillis();
        System.out.println("Elapsed time = " + (end - start) / 1000.0 + " s");
    }

    public void xtestDozensOfColumns() throws Exception {
        // 1000 rows: 188 ms hypersonic, 422 ms mayfly.
        // 10000 rows: 0.891 s hypersonic, 3.14 s mayfly
        execute("create table foo(a integer, b integer, c integer, " +
            "d integer, e integer, f integer, g integer, h integer," +
            "i integer, j integer, k integer, l integer, m integer," +
            "n integer, o integer, p integer, q integer, r integer," +
            "s integer, t integer, u integer, v integer, w integer," +
            "x integer, y integer, z integer," +
            "alpha varchar(50), beta varchar(50), gamma varchar(50)," +
            "delta varchar(50), epsilon varchar(50), zeta varchar(50), " +
            "eta varchar(50), theta varchar(50), " +
            "iota varchar(50), kappa varchar(50), lambda varchar(50), " +
            "mu varchar(50), nu varchar(50), xi varchar(50), " +
            "omicron varchar(50), " +
            "pi varchar(50), rho varchar(50), sigma varchar(50), " +
            "tau varchar(50), upsilon varchar(50), phi varchar(50), " +
            "chi varchar(50), psi varchar(50), omega varchar(50) )");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; ++i) {
            execute("insert into foo(omega, chi, upsilon, sigma, pi," +
                "xi, mu, kappa, theta, zeta, delta, beta," +
                "z, x, v, t, r, p, n, l, j, h, f, d, b) " +
                "values ('xcvz', 'jkweflwe', 'uiiwecjewc', 'jksjfkasdf'," +
                "'skdfskjdf'," +
                "'jskdlkjsdf', 'wjef', 'ijeif', 'jksldkf'," +
                "'jkwefjk', 'jweifje', 'jiowejif'," +
                "789, 6897, 34, 235, 2783, 2378, 1234, 7474, 8293," +
                "235, 0, 1, " + i + ")");
        }
        long end = System.currentTimeMillis();
        if (true) {
            System.out.println(
                "Elapsed time = " + (end - start) / 1000.0 + " s");
        }
    }

    public void xtestQueries() throws Exception {
        // Goal here is to test parsing, per-command overhead, etc, not the time evaluating
        // complicated joins and wheres.
        // hypersonic 125 ms, mayfly 125 ms
        execute("create table foo (a integer, b integer, c integer, d integer, e integer)");
        execute("insert into foo (a, b, c, d, e) values (1, 2, 3, 4, 5)");
        execute("insert into foo (a, b, c, d, e) values (10, 20, 30, 40, 50)");
        execute("insert into foo (a, b, c, d, e) values (100, 200, 300, 400, 500)");
        long start = System.currentTimeMillis();
        int rows = 0;
        int sum = 0;
        for (int i = 0; i < 1000; ++i) {
            ResultSet results = query("select a, c, e from foo where e > " + i);
            while (results.next()) {
                rows += 1;
                sum += results.getInt(1);
            }
            results.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("Elapsed time = " + (end - start) / 1000.0 + " s");

        assertEquals(5 * 3 + 45 * 2 + 450 * 1 + 500 * 0, rows);
        assertEquals(5 * 111 + 45 * 110 + 450 * 100 + 500 * 0, sum);
    }

    private void createTables() throws Exception {
        for (int i = 0; i < TABLE_COUNT; ++i) {
            StringBuilder command = new StringBuilder();
            command.append("create table some_table_" + i + " (\n");
            for (int j = 0; j < COLUMNS_PER_TABLE; ++j) {
                command.append("  column_" + j + " integer");
                if (j < COLUMNS_PER_TABLE - 1) {
                    command.append(",");
                }
                command.append("\n");
            }
            command.append(")\n");
            execute(command.toString());
        }
        assertTableCount(TABLE_COUNT);
    }

    private void insertSomeData() throws Exception {
        for (int i = 0; i < TABLES_TO_INSERT_INTO; ++i) {
            for (int j = 0; j < ROWS_TO_INSERT; ++j) {
                insertRow("some_table_" + i);
            }
        }
    }

    private void insertRow(String table) throws Exception {
        // INSERT INTO table (COLUMN_0, COLUMN_1) VALUES (100, 101)

        StringBuilder command = new StringBuilder();
        command.append("insert into " + table + " (");
        for (int i = 0; i < COLUMNS_PER_TABLE; i++) {
            command.append("column_" + i);
            if (i < COLUMNS_PER_TABLE - 1) {
                command.append(",");
            }
        }
        command.append(") VALUES (");
        for (int i = 0; i < COLUMNS_PER_TABLE; i++) {
            command.append(100 + i);
            if (i < COLUMNS_PER_TABLE - 1) {
                command.append(",");
            }
        }
        command.append(")");

        execute(command.toString());
    }

    private void dropTables() throws Exception {
        for (int i = 0; i < TABLE_COUNT; ++i) {
            execute("drop table some_table_" + i + "\n");
        }
        assertTableCount(0);
    }

    public void testStringBuilder() throws Exception {
//        long start = System.currentTimeMillis();
        int appendCount = TABLE_COUNT * COLUMNS_PER_TABLE * 10;

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < appendCount; i++) {
            builder.append("string foo " + i);
        }
        assertTrue(builder.toString(), builder.length() > 100);
//        long end = System.currentTimeMillis();
//        System.out.println("Elapsed time = " + (end - start) / 1000.0 + " s");
    }

    public static void main(String[] args) throws Exception {
        PerformanceTest test = new PerformanceTest();
        test.setUp();
        test.xtestDozensOfColumns();
    }

}


text:
package com.sss.modules.category.entity;

import com.sss.common.entity.BaseEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * 视频分类实体类
 * Created by Jade on 2017/4/16.
 */
@Entity
@Table(name = "CMS_CATEGORY")
public class Category extends BaseEntity{

    @Column
    private String name;
    @Column
    private String parentId;

    public String getName() {
        return name;
    }

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

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
}


text:
using System;
using System.Configuration;
using System.Configuration.Internal;
using System.Reflection;

public class TempConfigurationHost : DelegatingConfigHost
{
    private static string s_assemblyName = PlatformDetection.IsFullFramework ? "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" : "System.Configuration.ConfigurationManager";
    private static IInternalConfigConfigurationFactory s_configurationFactory;

    private ConfigurationFileMap _fileMap;

    public TempConfigurationHost()
    {
        Type type = Type.GetType(InternalHostTypeName, true);
        Host = (IInternalConfigHost) Activator.CreateInstance(type, true);
    }

    public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams)
    {
        Host.Init(configRoot, hostInitParams);
    }

    public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath,
                        IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams)
    {

        Host.Init(configRoot, hostInitConfigurationParams);

        _fileMap = hostInitConfigurationParams[1] as ConfigurationFileMap;

        locationSubPath = ConfigurationFactory.NormalizeLocationSubPath(locationSubPath, null);
        configPath = "MACHINE/EXE";
        locationConfigPath = locationSubPath;
    }

    public override bool IsTrustedConfigPath(string configPath)
    {
        return true;
    }

    public override bool IsLocationApplicable(string configPath)
    {
        return true;
    }

    public override bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord)
    {
        return true;
    }

    public override bool PrefetchAll(string configPath, string streamName)
    {
        return false;
    }

    public override bool PrefetchSection(string sectionGroupName, string sectionName)
    {
        return false;
    }

    public override string GetStreamName(string configPath)
    {
        return _fileMap.MachineConfigFilename;
    }

    static string InternalConfigConfigurationFactoryTypeName
    {
        get { return "System.Configuration.Internal.InternalConfigConfigurationFactory, " + s_assemblyName; }
    }

    static string InternalHostTypeName
    {
        get { return "System.Configuration.Internal.InternalConfigHost, " + s_assemblyName; }
    }

    static internal IInternalConfigConfigurationFactory ConfigurationFactory
    {
        get
        {
            if (s_configurationFactory == null)
            {
                Type type = Type.GetType(InternalConfigConfigurationFactoryTypeName, true);
                s_configurationFactory = (IInternalConfigConfigurationFactory) Activator.CreateInstance(type, true);
            }

            return s_configurationFactory;
        }
    }
}


text:
<html>
<body>
Reports methods that are identical to their super methods. Such methods have the same signature
as their super method and either have an identical body or only their body consists only of a call to the super method.
These methods are redundant and can be removed.
<!-- tooltip end -->
<p>
  Use the checkbox below to run the inspection for the methods that override library methods.
  Checking library methods may slow down the inspection.
</body>
</html>


text:
txaio
=====

| |Version| |Build Status| |Coverage| |Docs|

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

**txaio** is a helper library for writing code that runs unmodified on
both `Twisted <https://twistedmatrix.com/>`_ and `asyncio <https://docs.python.org/3/library/asyncio.html>`_ / `Trollius <http://trollius.readthedocs.org/en/latest/index.html>`_.

This is like `six <http://pythonhosted.org/six/>`_, but for wrapping
over differences between Twisted and asyncio so one can write code
that runs unmodified on both (aka *source code compatibility*). In
other words: your *users* can choose if they want asyncio **or** Twisted
as a dependency.

Note that, with this approach, user code **runs under the native event
loop of either Twisted or asyncio**. This is different from attaching
either one's event loop to the other using some event loop adapter.

Platform support
----------------

**txaio** runs on CPython 2.7/3.3+ and PyPy 2/3, on top of Twisted or asyncio. Specifically, **txaio** is tested on the following platforms:

**Python 2:**

* CPython 2.7 on Twisted 12.1, 13.2, 15.4, 16.5, trunk and on Trollius 2.0
* PyPy 2 on Twisted 12.1, 13.2, 15.4, 16.5, trunk and on Trollius 2.0

**Python 3:**

* CPython 3.3 on Twisted 15.4, 16.5, trunk and on Trollius 2.0
* CPython 3.4 on Twisted 15.4, 16.5, trunk and on asyncio (stdlib)
* CPython 3.5 on Twisted 15.4, 16.5, trunk and on asyncio (stdlib)
* CPython 3.6 on Twisted 15.4, 16.5, trunk and on asyncio (stdlib)
* PyPy 3 on Twisted 15.4, 16.5, trunk and on asyncio (stdlib)

How it works
------------

Instead of directly importing, instantiating and using ``Deferred``
(for Twisted) or ``Future`` (for asyncio) objects, **txaio** provides
helper-functions to do that for you, as well as associated things like
adding callbacks or errbacks.

This obviously changes the style of your code, but then you can choose
at runtime (or import time) which underlying event-loop to use. This
means you can write **one** code-base that can run on Twisted *or*
asyncio (without a Twisted dependency) as you or your users see fit.

Code like the following can then run on *either* system:

.. sourcecode:: python

    import txaio
    txaio.use_twisted()  # or .use_asyncio()

    f0 = txaio.create_future()
    f1 = txaio.as_future(some_func, 1, 2, key='word')
    txaio.add_callbacks(f0, callback, errback)
    txaio.add_callbacks(f1, callback, errback)
    # ...
    txaio.resolve(f0, "value")
    txaio.reject(f1, RuntimeError("it failed"))

Please refer to the `documentation <https://txaio.readthedocs.io/en/latest/>`_ for description and usage of the library features.

.. |Version| image:: https://img.shields.io/pypi/v/txaio.svg
   :target: https://pypi.python.org/pypi/txaio

.. |Build Status| image:: https://travis-ci.org/crossbario/txaio.svg?branch=master
   :target: https://travis-ci.org/crossbario/txaio

.. |Coverage| image:: https://codecov.io/github/crossbario/txaio/coverage.svg?branch=master
   :target: https://codecov.io/github/crossbario/txaio

.. |Docs| image:: https://readthedocs.org/projects/txaio/badge/?version=latest
   :target: https://txaio.readthedocs.io/en/latest/


text:
First install TBTK following instructions on https://github.com/dafer45/TBTK/.
Make sure the installed version is v0.9.4. If TBTK has been compiled with CUDA
support this project can be compiled immediately by typing 'make'. If TBTK has
been compiled without CUDA support, the lines

```
CPropertyExtractor propertyExtractor(
	cSolver,
	NUM_COEFFICIENTS,
	true,
	false,
	true
);
```

in src/main.cpp first need to be modified to

```
CPropertyExtractor propertyExtractor(
	cSolver,
	NUM_COEFFICIENTS,
	false,
	false,
	true
);
```

and the makefile will need to be modified in accordance with instructions
provided there. Once this is done, type 'make' to compile the project.

# Setup calculation
To setup the calculation for a certain set of parameters, open the file
"Parameters" and change the values. The first ten values controls the model,
the eleventh parameter controls whether the calculations are done along a 1D
cut or over the full surface, and the last parameters controls the
ChebyshevSolver.

# Run calculation
Type './build/a.out' to run a calculation. Note that the calculations can take
many hours to complete (in 2017) for lattice sizes comparable to those in the
corresponding article (201x201) even if a GPU is used. At the time of writing
the full 2D calculation is likely to be too computationally demanding to be
done on a CPU other than for comparatively small lattice sizes.

# Plot results
Two different plot scripts are provided for the two cases where cut1D is set
to true (1) and false (0). If a calculation was done with cut1D=1, type
```
./plot.py TBTKResults.h5 1.57 0 0.005
```
to plot the results. Here The first parameter is the file TBTKResults.h5 where
the results are stored after the calculation, the second and third are the
polar and azimuthal angles of the spin-polarization, respectively, and the
fourth is a smoothing parameter (sigma) used to perform Gaussian smoothing in
the energy direction. The value of these parameters can be played with to see
the result for different polarization axes and smoothing. The ploted results
are found in the folder 'figures'. If the calculation instead was done with
cut1D=0, instead write
```
./plot.py TBTKResults.h5 1.57 0 0.005
```


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.container.v1beta1.model;

/**
 * TierConfig is the configuration for a tier offering.  For example the GKE standard or advanced
 * offerings which contain different levels of functionality and possibly cost.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class TierConfig extends com.google.api.client.json.GenericJson {

  /**
   * The tier from which the tier being configured inherits.  The configured tier will inherit all
   * the features from its parent tier.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String parent;

  /**
   * The tier that is being configured with this value.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String tier;

  /**
   * The tier from which the tier being configured inherits.  The configured tier will inherit all
   * the features from its parent tier.
   * @return value or {@code null} for none
   */
  public java.lang.String getParent() {
    return parent;
  }

  /**
   * The tier from which the tier being configured inherits.  The configured tier will inherit all
   * the features from its parent tier.
   * @param parent parent or {@code null} for none
   */
  public TierConfig setParent(java.lang.String parent) {
    this.parent = parent;
    return this;
  }

  /**
   * The tier that is being configured with this value.
   * @return value or {@code null} for none
   */
  public java.lang.String getTier() {
    return tier;
  }

  /**
   * The tier that is being configured with this value.
   * @param tier tier or {@code null} for none
   */
  public TierConfig setTier(java.lang.String tier) {
    this.tier = tier;
    return this;
  }

  @Override
  public TierConfig set(String fieldName, Object value) {
    return (TierConfig) super.set(fieldName, value);
  }

  @Override
  public TierConfig clone() {
    return (TierConfig) super.clone();
  }

}


text:
package com.intellij.openapi.fileEditor;

public enum FileEditorPolicy {

  /**
   * Place created editor before default IDEA's editor (if any)
   *
   */
  /*
   * should be the first declaration
   */
  PLACE_BEFORE_DEFAULT_EDITOR,

  /**
   * No policy
   */
  NONE,

  /**
   * Do not create default IDEA's editor (if any) for the file
   */
  HIDE_DEFAULT_EDITOR,

  /**
   * Place created editor after the default EDEA'a editor (if any)
   *
   *
   */
  /*
   * should be the last declaration
   */
  PLACE_AFTER_DEFAULT_EDITOR
}


text:
<?php

class m110517_155003_create_tables_hist_trail extends CDbMigration
{

	/**
	 * Creates initial version of the audit trail table
	 */
	public function up()
	{

		//Create our first version of the audittrail table
		//Please note that this matches the original creation of the
		//table from version 1 of the extension. Other migrations will
		//upgrade it from here if we ever need to. This was done so
		//that older versions can still use migrate functionality to upgrade.
		$this->createTable( 'tbl_hist_trail',
			array(
				'id' => 'pk',
				'old_value' => 'text',
				'new_value' => 'text',
				'action' => 'string NOT NULL',
				'model' => 'NOT NULL',
				'field' => 'NOT NULL',
				'stamp' => 'datetime NOT NULL',
				'user_id' => 'string',
				'model_id' => 'string NOT NULL',
				'valid_from' => 'date',
				'valid_to' => 'date',
			)
		);

		//Index these bad boys for speedy lookups
		$this->createIndex( 'idx_hist_trail_user_id', 'tbl_hist_trail', 'user_id');
		$this->createIndex( 'idx_hist_trail_model_id', 'tbl_hist_trail', 'model_id');
		$this->createIndex( 'idx_hist_trail_model', 'tbl_hist_trail', 'model');
		$this->createIndex( 'idx_hist_trail_field', 'tbl_hist_trail', 'field');
		$this->createIndex( 'idx_hist_trail_old_value', 'tbl_hist_trail', 'old_value');
		$this->createIndex( 'idx_hist_trail_new_value', 'tbl_hist_trail', 'new_value');
		$this->createIndex( 'idx_hist_trail_action', 'tbl_hist_trail', 'action');
		$this->createIndex( 'idx_hist_trail_from', 'tbl_hist_trail', 'valid_from');
		$this->createIndex( 'idx_hist_trail_to', 'tbl_hist_trail', 'valid_to');
	}

	/**
	 * Drops the audit trail table
	 */
	public function down()
	{
		$this->dropTable( 'tbl_hist_trail' );
	}

	/**
	 * Creates initial version of the audit trail table in a transaction-safe way.
	 * Uses $this->up to not duplicate code.
	 */
	public function safeUp()
	{
		$this->up();
	}

	/**
	 * Drops the audit trail table in a transaction-safe way.
	 * Uses $this->down to not duplicate code.
	 */
	public function safeDown()
	{
		$this->down();
	}
}


text:
<?php

namespace Bitrix24\Exceptions;

/**
 * Class Bitrix24TokenIsExpiredException
 * @package Bitrix24
 */
class Bitrix24TokenIsExpiredException extends Bitrix24ApiException
{
}


text:
// Copyright (C) 2005, 2006 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Common Public License.
//
// $Id: IpLapack.cpp 759 2006-07-07 03:07:08Z andreasw $
//
// Authors:  Andreas Waechter              IBM    2005-12-25

#include "IpoptConfig.h"
#include "IpLapack.hpp"

#if SimTK_DEFAULT_PRECISION==1 // float
#define DPOTRS  spotrs_
#define DPOTRF  spotrf_
#define DSYEV   ssyev_
#else // double
#define DPOTRS  dpotrs_
#define DPOTRF  dpotrf_
#define DSYEV   dsyev_
#endif

// Prototypes for the LAPACK routines
extern "C"
{
  /** LAPACK Fortran subroutine DPOTRS. */
  void dpotrs_(char *uplo, ipfint *n,
                               ipfint *nrhs, const double *A, ipfint *ldA,
                               double *B, ipfint *ldB, ipfint *info,
                               int uplo_len);
  /** LAPACK Fortran subroutine DPOTRF. */
  void dpotrf_(char *uplo, ipfint *n,
                               double *A, ipfint *ldA,
                               ipfint *info, int uplo_len);

  /** LAPACK Fortran subroutine DSYEV */
  void dsyev_(char *jobz, char *uplo, ipfint *n,
                             double *A, ipfint *ldA, double *W,
                             double *WORK, ipfint *LWORK, ipfint *info,
                             int jobz_len, int uplo_len);

  /** LAPACK Fortran subroutine DPOTRS. */
  void spotrs_(char *uplo, ipfint *n,
                               ipfint *nrhs, const float *A, ipfint *ldA,
                               float *B, ipfint *ldB, ipfint *info,
                               int uplo_len);
  /** LAPACK Fortran subroutine DPOTRF. */
  void spotrf_(char *uplo, ipfint *n,
                               float *A, ipfint *ldA,
                               ipfint *info, int uplo_len);

  /** LAPACK Fortran subroutine DSYEV */
  void ssyev_(char *jobz, char *uplo, ipfint *n,
                             float *A, ipfint *ldA, float *W,
                             float *WORK, ipfint *LWORK, ipfint *info,
                             int jobz_len, int uplo_len);
}

namespace Ipopt
{
  /* Interface to FORTRAN routine DPOTRS. */
  void IpLapackDpotrs(Index ndim, Index nrhs, const Number *a, Index lda,
                      Number *b, Index ldb)
  {
#ifdef COIN_HAS_LAPACK
    ipfint N=ndim, NRHS=nrhs, LDA=lda, LDB=ldb, INFO;
    char uplo = 'L';

    DPOTRS(&uplo, &N, &NRHS, a, &LDA, b, &LDB, &INFO, 1);
    DBG_ASSERT(INFO==0);
#else

    std::string msg = "Ipopt has been compiled without LAPACK routine DPOTRS, but options are chosen that require this dependency.  Abort.";
    THROW_EXCEPTION(LAPACK_NOT_INCLUDED, msg);
#endif

  }

  void IpLapackDpotrf(Index ndim, Number *a, Index lda, Index& info)
  {
#ifdef COIN_HAS_LAPACK
    ipfint N=ndim, LDA=lda, INFO;

    char UPLO = 'L';

    DPOTRF(&UPLO, &N, a, &LDA, &INFO, 1);

    info = INFO;
#else

    std::string msg = "Ipopt has been compiled without LAPACK routine DPOTRF, but options are chosen that require this dependency.  Abort.";
    THROW_EXCEPTION(LAPACK_NOT_INCLUDED, msg);
#endif

  }

  void IpLapackDsyev(bool compute_eigenvectors, Index ndim, Number *a,
                     Index lda, Number *w, Index& info)
  {
#ifdef COIN_HAS_LAPACK
    ipfint N=ndim, LDA=lda, INFO;

    char JOBZ;
    if (compute_eigenvectors) {
      JOBZ = 'V';
    }
    else {
      JOBZ = 'N';
    }
    char UPLO = 'L';

    // First we find out how large LWORK should be
    ipfint LWORK = -1;
    Number WORK_PROBE;
    DSYEV(&JOBZ, &UPLO, &N, a, &LDA, w,
          &WORK_PROBE, &LWORK, &INFO, 1, 1);
    DBG_ASSERT(INFO==0);

    LWORK = (ipfint) WORK_PROBE;
    DBG_ASSERT(LWORK>0);

    Number* WORK = new Number[LWORK];
    for (Index i=0; i<LWORK; i++) {
      WORK[i] = Number(i);
    }
    DSYEV(&JOBZ, &UPLO, &N, a, &LDA, w,
          WORK, &LWORK, &INFO, 1, 1);

    DBG_ASSERT(INFO>=0);
    info = INFO;

    delete [] WORK;
#else

    std::string msg = "Ipopt has been compiled without LAPACK routine DSYEV, but options are chosen that require this dependency.  Abort.";
    THROW_EXCEPTION(LAPACK_NOT_INCLUDED, msg);
#endif

  }
}


text:
var EventEmitter = require('events').EventEmitter;

var async = require('async');
var httpify = require('httpify');

const apiUrl = (window.location.protocol === 'https:') ? 'https://randomuser.me/api?nat=au&results=16' : 'http://api.randomuser.me/?nat=au&results=16';

function PeopleStore () {
	EventEmitter.call(this);

	// initialize internal cache
	var storage = this.cache = {
		people: []
	};
	var self = this;

	// Dispatchers
	this.starQueue = async.queue((data, callback) => {
		var { id, starred } = data;

		// update internal data
		self.cache.people
			.filter(person => person.id === id)
			.forEach(person => person.isStarred = starred);

		// emit events
		self.emit('people-updated', storage.people);

		callback();
	}, 1);

	this.refreshQueue = async.queue((_, callback) => {
		// update
		httpify({
			method: 'GET',
			url: apiUrl
		}, function (err, res) {
			if (err) return callback(err);

			storage.people = res.body.results.map(p => p.user);

			// post process new data
			storage.people.forEach((person, i) => {
				person.id = i;
				person.name.first = person.name.first[0].toUpperCase() + person.name.first.slice(1);
				person.name.last = person.name.last[0].toUpperCase() + person.name.last.slice(1);
				person.name.initials = person.name.first[0] + person.name.last[0];
				person.name.full = person.name.first + ' ' + person.name.last;
				person.category = Math.random() > 0.5 ? 'A' : 'B';
				person.github = person.name.first.toLowerCase() + person.name.last.toLowerCase();
				person.picture = person.picture.medium;
				person.twitter = '@' + person.name.first.toLowerCase() + (Math.random().toString(32).slice(2, 5));
			});

			// emit events
			self.emit('people-updated', storage.people);
			self.emit('refresh');

			callback(null, storage.people);
		});
	}, 1);

	// refresh immediately
	this.refresh();
}

Object.assign(PeopleStore.prototype, EventEmitter.prototype);

// Intents
PeopleStore.prototype.refresh = function (callback) {
	this.refreshQueue.push(null, callback);
}

PeopleStore.prototype.star = function ({ id }, starred, callback) {
	this.starQueue.push({ id, starred }, callback);
}

// Getters
PeopleStore.prototype.getPeople = function () { return this.cache.people; };

module.exports = PeopleStore;


text:
title: Contact
menu: contact
simple_form:
    token: "your token goes here"
    messages:
        success: "Your message has been sent."
        error: "Sorry, it seems that mail server is not responding. Please try again later or send me message to email "
    fields:
        name:
            position: 1
            type: "text"
            title: "Name"
            default: ""
            placeholder: "Name"
            class: ""
            required: true
            required_message: "Please enter your name"
        email:
            position: 2
            type: "email"
            title: "Email Address"
            default: ""
            placeholder: "Email Address"
            class: ""
            required: true
            required_message: "Please enter your email address"
        phone:
            position: 3
            type: "tel"
            title: "Phone Number"
            default: ""
            placeholder: "Phone Number"
            class: ""
            required: true
            required_message: "Please enter your phone number"
        message:
            position: 4
            type: "textarea"
            title: "Message"
            default: ""
            placeholder: "Message"
            class: ""
            required: true
            required_message: "Please enter a message"
        submit:
            position: 5
            type: "submit"
            title: "Send"
            default: ""
            class: ""
---

## CONTACT ME


text:
package org.ovirt.engine.core.bll.validator;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.stub;
import static org.mockito.Mockito.when;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.pm.FenceProxyLocator;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.pm.FenceAgent;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.config.IConfigUtilsInterface;
import org.ovirt.engine.core.compat.DateTime;
import org.ovirt.engine.core.compat.Version;

@RunWith(MockitoJUnitRunner.class)
public class FenceValidatorTest {

    @Mock
    private FenceValidator validator;

    @Mock
    private FenceProxyLocator proxyLocator;

    @Mock
    private BackendInternal backend;

    @Mock
    private IConfigUtilsInterface configUtils;

    @Before
    public void setup() {
        validator = new FenceValidator();
        validator = spy(validator);
        stub(validator.getProxyLocator(any(VDS.class))).toReturn(proxyLocator);
        doReturn(backend).when(validator).getBackend();
        Config.setConfigUtils(configUtils);
    }

    @Test
    public void failWhenProxyHostNotAvailable() {
        when(proxyLocator.isProxyHostAvailable()).thenReturn(false);
        List<String> messages = new LinkedList<>();
        boolean result = validator.isProxyHostAvailable(new VDS(), messages);
        assertFalse(result);
        assertEquals(messages.size(), 1);
        assertEquals(messages.get(0), "VDS_NO_VDS_PROXY_FOUND");
    }

    @Test
    public void succeedWhenProxyHostAvailable() {
        when(proxyLocator.isProxyHostAvailable()).thenReturn(true);
        List<String> messages = new LinkedList<>();
        boolean result = validator.isProxyHostAvailable(new VDS(), messages);
        assertTrue(result);
        assertTrue(messages.isEmpty());
    }

    @Test
    public void failWhenHostDoesNotExist() {
        List<String> messages = new LinkedList<>();
        boolean result = validator.isHostExists(null, messages);
        assertFalse(result);
        assertEquals(messages.size(), 1);
        assertEquals(messages.get(0), "ACTION_TYPE_FAILED_HOST_NOT_EXIST");
    }

    @Test
    public void succeedWhenHostExists() {
        List<String> messages = new LinkedList<>();
        boolean result = validator.isHostExists(new VDS(), messages);
        assertTrue(result);
        assertTrue(messages.isEmpty());
    }

    @Test
    public void failWhenStartupTimeoutHasNotPassed() {
        List<String> messages = new LinkedList<>();
        when(configUtils.getValue(eq(ConfigValues.DisableFenceAtStartupInSec), any(String.class))).thenReturn(5);
        when(backend.getStartedAt()).thenReturn(new DateTime(new Date()));
        boolean result = validator.isStartupTimeoutPassed(messages);
        assertEquals(messages.size(), 1);
        assertEquals(messages.get(0), "VDS_FENCE_DISABLED_AT_SYSTEM_STARTUP_INTERVAL");
        assertFalse(result);
    }

    @Test
    public void succeedWhenStartupTimeoutHasPassed() {
        List<String> messages = new LinkedList<>();
        when(configUtils.getValue(eq(ConfigValues.DisableFenceAtStartupInSec), any(String.class))).thenReturn(5);
        when(backend.getStartedAt()).thenReturn(new DateTime(new Date().getTime() - 20000));
        boolean result = validator.isStartupTimeoutPassed(messages);
        assertTrue(result);
    }

    @Test
    public void failWhenPowerManagementDisabled() {
        VDS vds = new VDS();
        List<String> messages = new LinkedList<>();
        boolean result = validator.isPowerManagementEnabledAndLegal(vds, null, messages);
        assertFalse(result);
        assertEquals(messages.size(), 1);
        assertEquals(messages.get(0), "VDS_FENCE_DISABLED");
    }

    @Test
    public void failWhenNoAgentsExist() {
        VDS vds = new VDS();
        vds.setPmEnabled(true);
        List<String> messages = new LinkedList<>();
        boolean result = validator.isPowerManagementEnabledAndLegal(vds, null, messages);
        assertFalse(result);
        assertEquals(messages.size(), 2);
        assertTrue(messages.contains("ACTION_TYPE_FAILED_PM_ENABLED_WITHOUT_AGENT"));
        assertTrue(messages.contains("VDS_FENCE_DISABLED"));
    }

    @Test
    public void failWhenClusterVersionNotCompatible() {
        VDS vds = new VDS();
        vds.setPmEnabled(true);
        Cluster cluster = new Cluster();
        cluster.setCompatibilityVersion(Version.v3_3);
        FenceAgent agent = new FenceAgent();
        agent.setType("Some_Type");
        vds.getFenceAgents().add(agent);
        List<String> messages = new LinkedList<>();
        boolean result = validator.isPowerManagementEnabledAndLegal(vds, cluster, messages);
        assertFalse(result);
        assertEquals(messages.size(), 2);
        assertTrue(messages.contains("ACTION_TYPE_FAILED_AGENT_NOT_SUPPORTED"));
        assertTrue(messages.contains("VDS_FENCE_DISABLED"));
    }

    @Test
    public void succeedWhenClusterVersionCompatible() {
        VDS vds = new VDS();
        vds.setPmEnabled(true);
        Cluster cluster = new Cluster();
        cluster.setCompatibilityVersion(Version.v3_3);
        FenceAgent agent = new FenceAgent();
        agent.setType("apc");
        vds.getFenceAgents().add(agent);
        List<String> messages = new LinkedList<>();
        when(configUtils.getValue(eq(ConfigValues.VdsFenceType), any(String.class))).thenReturn("apc");
        when(configUtils.getValue(eq(ConfigValues.CustomVdsFenceType), any(String.class))).thenReturn("apc");
        boolean result = validator.isPowerManagementEnabledAndLegal(vds, cluster, messages);
        assertTrue(result);
    }

}


text:
/*
 * Created on 20.10.2005
 * Last modification G.Seryakova
 * Last modified on 07.11.2005
 *
 * Test for threads.
 *
 * scenario
 */
package org.apache.harmony.test.func.api.java.lang.F_ThreadTest_08;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.apache.harmony.test.func.share.ScenarioTest;

/**
 * Test for threads.
 *
 */
public class F_ThreadTest_08 extends ScenarioTest {
    int     res            = 0;
    Object obj = new Object();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream ps;

    public static void main(String[] args) {
        System.exit(new F_ThreadTest_08().test());
    }

    class MyThread extends Thread {

        public void run() {
            synchronized(obj) {
                obj.notify();
            }
            destroy();
        }
    }

    public int test() {
        ps = System.err;

        if (!task1()) {
            fail("FAIL in task1().");
            res++;
        } else {
            log.info("task1 passed.");
        }
        if (!task2()) {
            fail("FAIL in task2().");
            res++;
        } else {
            log.info("task2 passed.");
        }

        if (!task3()) {
            fail("FAIL in task3().");
            res++;
        } else {
            log.info("task3 passed.");
        }

        if (res > 0) {
            return fail("TEST FAILED.");
        } else {
            return pass();
        }
    }

    private boolean task1() {
        out.reset();
        System.setErr(new PrintStream(out));
        Thread.dumpStack();
        System.setErr(ps);
        log.info(out.toString());
        String str[] = out.toString().split("\n");
        if (str[1].indexOf("java.lang.Thread.dumpStack(") == -1) {
            fail("FAIL: fail in 2 str. of dumpStack().");
            return false;
        }
        if (str[2].indexOf("org.apache.harmony.test.func.api.java.lang.F_ThreadTest_08.F_ThreadTest_08.task1(") == -1) {
            fail("FAIL: fail in 3 str. of dumpStack().");
            return false;
        }
        if (str[3].indexOf("org.apache.harmony.test.func.api.java.lang.F_ThreadTest_08.F_ThreadTest_08.test(") == -1) {
            fail("FAIL: fail in 4 str. of dumpStack().");
            return false;
        }
//        if (str[4].indexOf("org.apache.harmony.test.func.api.java.lang.F_ThreadTest_08.F_ThreadTest_08.main([Ljava.lang.String;") == -1) {
//            fail("FAIL: fail in 5 str. of dumpStack().");
//            return false;
//        }
        return true;
    }

    private boolean task2() {
        out.reset();
        System.setErr(new PrintStream(out));
        Thread t = new MyThread();
        synchronized(obj) {
            t.start();
            try {
                obj.wait();
                t.join();
            } catch (InterruptedException e) {
                fail("FAIL: unexpected InterruptedException in wait().");
                res++;
            }
        }
        System.setErr(ps);
        log.info(out.toString());
        String str = out.toString();
        int ind = -1;
        if ((ind = str.indexOf("java.lang.NoSuchMethodError")) == -1) {
            fail("FAIL: fail in 1 str. in task2.");
            return false;
        }
        if ((ind = str.indexOf("java.lang.Thread.destroy(", ind)) == -1) {
            fail("FAIL: fail in 2 str. in task2.");
            return false;
        }
        if ((ind = str.indexOf(" org.apache.harmony.test.func.api.java.lang.F_ThreadTest_08.F_ThreadTest_08$MyThread.run(", ind)) == -1) {
            fail("FAIL: fail in 3 str. in task2.");
            return false;
        }
        return true;
    }

    private boolean task3() {
        out.reset();
        ThreadGroup tg = new ThreadGroup("group1.");
        Thread th = new Thread(tg, "thread1.");
        Throwable ex = new Throwable("test.");
        System.setErr(new PrintStream(out));
        tg.uncaughtException(th, ex);
        String str =out.toString();
        out.reset();
        ex.printStackTrace();
        System.setErr(ps);
        log.info(str);
        log.info(out.toString());
        if (str.indexOf(out.toString()) == -1) {
            fail("FAIL: in task3 result string isn't expected.");
            return false;
        }
        return true;
    }
}


text:
Dashboard

  Selamat Datang, <?php echo $this->session->userdata('display_name');?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>AMC</groupId>
    <artifactId>ModelChecker</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-runtime</artifactId>
            <version>4.5.1-1</version>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
CREATE TABLE `arc_ecom_brands` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `image` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for table `arc_ecom_brands`
--
ALTER TABLE `arc_ecom_brands`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `arc_ecom_brands`
--
ALTER TABLE `arc_ecom_brands`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;


text:
mcnp2cad
=========

MCNP to iGeom/CAD converter: a program to extract the geomtery from MCNP
input files and write it out using any ITAPS iGeom backend.

This program is currently maintained by Julie Zachman (zachman@engr.wisc.edu).
Bug reports are appreciated.

The home of mcnp2cad on the web is https://github.com/svalinn/mcnp2cad

This tool is based on an concept first developed at Argonne National
Laboratory.

Compiling (with CGM):
---------------------

At present CGM_BASE_DIR must be specifed as a make paramter, e.g.
::
   make CGM_BASE_DIR=<path to CGM>

CGM_BASE_DIR must point to a valid installation of the CGM library.  Information and instructions
for getting and using CGM are available at https://press3.mcs.anl.gov/sigma/cgm-library/

In addition, any shared libraries required by CGM must be located either in
standard system directories, or in a location pointed to by the
LD_LIBRARY_PATH environment variable.  If your version of CGM was compiled
against CUBIT, you  will likely need to set LD_LIBRARY_PATH as follows:
::
    export LD_LIBRARY_PATH=/path/to/cubit13.1/bin

Running:
---------

The program requires a single command-line argument: the path to an MCNP
input file.  Optionally, the -o flag can be used to specify the file to
which output should be written.  The iGeom backend will choose the output
format based on the extension of the output file name; .sat is the default
format for an ACIS-based or CUBIT-based CGM.

Help on other command-line flags is available by invoking the program with
the ``-h`` (or ``--help``) flag.

The program will, by default, create a boundary volume named "graveyard"
around all created geometry.  This volume is needed for DAGMC analysis,
but users who are only interested in visualization may want to use the ``-G``
flag to turn the graveyard volume off.

Unsupported Features:
-----------------------

* Could be added easily:
   * More direct control over the size of the sphere/graveyard in which
     the geometry sits
   * Support for interpolation (``nI/nILOG``) and multiplication (``nM``) syntax.
   * Make the title card optional, as it apparently is in MCNP.

* Could be added with effort:
   * Correct handling of hexagonal prism lattices for lattices based on irregular
     hexgons
   * Support for ``ELL`` (ellipse), ``WED`` (wedge), and ``ARB`` (arbitrary polyhedron)
     macrobodies
   * Support for lattices in universe 0
   * Faster/more efficient generation of embedded universes within lattices.
   * Complete support for ``M=-1`` argument in ``TRn`` (transform) cards.
   * Automatically annotate reflecting/white boundaries and periodic surfaces.
   * Support for 3-arg and 5-arg specification of rotations in transformations.
   * Support for jump (``nJ``) syntax: requires knowledge of default values in
     many possible contexts

* Could be added with substantial effort:
   * General support for ``SQ``, ``GQ``, ``X``, ``Y``, and ``Z`` surfaces.
     (Simple ``X``, ``Y``, ``Z`` surfaces are already supported.)
   * Robust error detection and reporting for ill-formed MCNP inputs.

Compiling a 32-bit mcnp2cad:
-----------------------------

Users on 64-bit Linux may need to compile a 32-bit version of this program
under certain conditions, for example, if only a 32-bit copy of Cubit 10.2
is available.  This is a two-step process:

* Ensure that CGM is built for 32-bit by configuring it with the ``--enable-32bit``
  flag, and
* Add ``-m32`` to the ``CXXFLAGS`` in the mcnp2cad Makefile.


text:
<?xml version="1.0"?>
<psalm
    errorLevel="8"
    resolveFromConfigFile="true"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://getpsalm.org/schema/config"
    xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
    phpVersion="8.1"
>
    <projectFiles>
        <directory name="lib/Doctrine/Common" />
        <ignoreFiles>
            <!-- Remove ProxyGeneratorTest once Psalm supports native intersection https://github.com/vimeo/psalm/issues/6413 -->
            <file name="lib/Doctrine/Common/Proxy/ProxyGenerator.php" />
            <file name="tests/Doctrine/Tests/Common/Proxy/ProxyGeneratorTest.php" />
            <directory name="vendor" />
        </ignoreFiles>
    </projectFiles>
</psalm>


text: Under maintenance.


text:
namespace Labo.WebCrawler.Core.Modules
{
    using System.Collections.Generic;

    public sealed class DefaultWebContentProcessorModuleFactory : IWebContentProcessorModuleFactory
    {
        private readonly Dictionary<string, List<IWebContentProcessorModule>> m_Modules = new Dictionary<string, List<IWebContentProcessorModule>>();

        public IWebContentProcessorModule[] GetContentProcessorModules(string mimeType)
        {
            List<IWebContentProcessorModule> modules;
            if (m_Modules.TryGetValue(mimeType, out modules))
            {
                return modules.ToArray();
            }

            return new IWebContentProcessorModule[0];
        }

        public void RegisterContentProcessorModule(string mimeType, IWebContentProcessorModule contentProcessorModule)
        {
            List<IWebContentProcessorModule> modules;
            if (m_Modules.TryGetValue(mimeType, out modules))
            {
                modules.Add(contentProcessorModule);
            }
            else
            {
                m_Modules.Add(mimeType, new List<IWebContentProcessorModule> { contentProcessorModule });
            }
        }
    }
}


text:
/* { dg-do compile } */
/* { dg-require-weak "" } */
/* { dg-options "-Waddress" } */
/* Warning when addr convert to bool always gives known result.
   Ada/Pascal programmers sometimes write 0-param functions without
   (), and might as well warn on variables, too.  */

int func (void);
extern int var;
int weak_func (void) __attribute__ ((weak));
extern int weak_var __attribute__ ((weak));

int
test_func_cmp (void)
{
  if (func)      /* { dg-warning "the address of 'func'" } */
    return 1;
  if (!func)     /* { dg-warning "the address of 'func'" } */
    return 1;
  if (&var)     /* { dg-warning "the address of 'var'" } */
    return 1;
  if (!&var)     /* { dg-warning "the address of 'var'" } */
    return 1;
  if (weak_func)
    return 1;
  if (!weak_func)
    return 1;
  if (&weak_var)
    return 1;
  if (!&weak_var)
    return 1;
  return 0;
}

/* Test equality with 0 on the right hand side.  */
int
test_func_cmp_rhs_zero (void)
{
  if (func == 0)     /* { dg-warning "the comparison will always evaluate as 'false'" } */
    return 1;
  if (func != 0)     /* { dg-warning "the comparison will always evaluate as 'true'" } */
    return 1;
  if (&var == 0)     /* { dg-warning "the comparison will always evaluate as 'false'" } */
    return 1;
  if (&var != 0)     /* { dg-warning "the comparison will always evaluate as 'true'" } */
    return 1;
  if (weak_func == 0)
    return 1;
  if (weak_func != 0)
    return 1;
  if (&weak_var == 0)
    return 1;
  if (&weak_var != 0)
    return 1;
  return 0;
}

/* Test equality with 0 on the left hand side.  */
int
test_func_cmp_lhs_zero (void)
{
  if (0 == func)     /* { dg-warning "the comparison will always evaluate as 'false'" } */
    return 1;
  if (0 != func)     /* { dg-warning "the comparison will always evaluate as 'true'" } */
    return 1;
  if (0 == &var)     /* { dg-warning "the comparison will always evaluate as 'false'" } */
    return 1;
  if (0 != &var)     /* { dg-warning "the comparison will always evaluate as 'true'" } */
    return 1;
  if (0 == weak_func)
    return 1;
  if (0 != weak_func)
    return 1;
  if (0 == &weak_var)
    return 1;
  if (0 != &weak_var)
    return 1;
  return 0;
}


text:
# Add NLog logging to EPiServer.

By Jeroen Stemerdink

[![Build status](https://ci.appveyor.com/api/projects/status/etvor9l6ly2fjgxi/branch/master?svg=true)](https://ci.appveyor.com/project/jstemerdink/epi-libraries-logging-nlog/branch/master)
[![GitHub version](https://badge.fury.io/gh/jstemerdink%2FEPi.Libraries.Logging.NLog.svg)](http://badge.fury.io/gh/jstemerdink%2FEPi.Libraries.Logging.NLog)
[![Platform](https://img.shields.io/badge/platform-.NET%204.6.1-blue.svg?style=flat)](https://msdn.microsoft.com/en-us/library/w0x726c2%28v=vs.110%29.aspx)
[![Platform](https://img.shields.io/badge/EPiServer-%2011.0.0-orange.svg?style=flat)](http://world.episerver.com/cms/)
[![GitHub license](https://img.shields.io/badge/license-MIT%20license-blue.svg?style=flat)](license.txt)
[![Quality Gate](https://sonarcloud.io/api/badges/gate?key=jstemerdink:EPi.Libraries.Logging.NLog)](https://sonarcloud.io/dashboard?id=jstemerdink%3AEPi.Libraries.Logging.NLog)

## NOTE
As from CMS12 you can use configure your logging without the need of a custom provider, see [Optimizely logging](https://world.optimizely.com/documentation/developer-guides/CMS/logging/). For adding Serilog see my [blog](https://jstemerdink.blog/)

## About
This will add NLog logging to your EPiServer site without needing to create Log4Net appenders

> *Powered by ReSharper*
> [![image](https://i0.wp.com/jstemerdink.files.wordpress.com/2017/08/logo_resharper.png)](http://jetbrains.com)


text:
import { put, all, select } from 'redux-saga/effects';
import { HitDatabaseMap } from '../types';
import {
  RefreshDatabaseRequest,
  RefreshDatabaseFailure,
  RefreshDatabaseSuccess,
  databaseRefreshFailure,
  databaseRefreshSuccess
} from '../actions/refreshDatabase';
import {
  // FetchStatusDetailRequest,
  statusDetailRequest
} from '../actions/statusDetail';
import { refreshDbSuccessToast, refreshDbErrorToast } from '../utils/toaster';
import { handleStatusDetailRequest } from './statusDetail';
import { hitDatabaseSelector } from '../selectors/index';

export function* handleStatusSummarySuccess(action: RefreshDatabaseRequest) {
  try {
    const { workedDates } = action;

    const initialDb: HitDatabaseMap = yield select(hitDatabaseSelector);

    yield all(
      workedDates.map(function*(date: Date) {
        /**
         * We call the `handleStatusDetailRequest` saga directly instead of
         * dispatching the action to the store because we need to wait for the
         * SUCCESSes to be returned. Otherwise, dispatching a request will cause
         * this saga to continue without waiting for the results of all the
         * requests.
         */
        yield handleStatusDetailRequest(
          /**
           * The format is YYYY-MM-DD automatically because they were retrieved
           * from manually parsing the worker site.
           */
          statusDetailRequest(date)
        );
      })
    );

    const finalDb: HitDatabaseMap = yield select(hitDatabaseSelector);

    refreshDbSuccessToast(workedDates.length, finalDb.size - initialDb.size);
    yield put<RefreshDatabaseSuccess>(databaseRefreshSuccess());
  } catch (e) {
    refreshDbErrorToast();
    yield put<RefreshDatabaseFailure>(databaseRefreshFailure([]));
  }
}


text:
require 'minitest/autorun'
require 'minitest/pride'
require 'active_record'
require 'acts_as_translated'

ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')

def capture_stdout(&block)
  real_stdout = $stdout

  $stdout = StringIO.new
  yield
  $stdout.string
ensure
  $stdout = real_stdout
end

def setup_db
  capture_stdout do
    ActiveRecord::Base.logger
    ActiveRecord::Schema.define(:version => 1) do
      create_table :countries do |t|
        t.column :iso, :string, index: true, unique: true, null: false
        t.column :name_nl, :string
        t.column :name_fr, :string
        t.column :name_en, :string
        t.column :description_nl, :text
        t.column :description_fr, :text
        t.column :description_en, :text
        t.column :slug_nl, :string
        t.column :slug_fr, :string
        t.column :slug_en, :string
        t.column :created_at, :datetime
        t.column :updated_at, :datetime
        t.column :position, :integer
      end
    end
  end
end

def fixtures(filename)
  records = YAML.load_file(File.join(__dir__, "#{filename}.yml"))
  records.each do |key, record|
    Country.create!(record)
  end
end

def teardown_db
  ActiveRecord::Base.connection.tables.each do |table|
    ActiveRecord::Base.connection.drop_table(table)
  end
end

class Country < ActiveRecord::Base
	include ActsAsTranslated

  acts_as_translated :name, :description, default: :nl
  acts_as_translated :slug
  acts_as_translated :custom, default: :fr

  def custom_fr
    "Custom FR method"
  end

  def custom_es
    "Custom ES method"
  end
end

class ActsAsTranslatedTest < Minitest::Test

  def setup
    setup_db
    fixtures :countries
  end

  def teardown
    teardown_db
  end

	def test_version
		refute_nil ActsAsTranslated::VERSION
	end

  def test_fixtures
    assert_equal 3, Country.count
    assert_equal 'Belgium', Country.find_by_iso(:be).name_en
    assert_equal 'Netherlands', Country.find_by_iso(:nl).name_en
    assert_equal 'France', Country.find_by_iso(:fr).name_fr
  end

  def test_acts_as_translated_attribute_presence
    refute_respond_to Country.new, :acts_as_translated_attribute
    assert_respond_to Country, :acts_as_translated_attribute

  end

  def test_acts_as_translated_attribute_matches
    @country = Country.find_by_iso(:be)

    assert_equal 'België', Country.acts_as_translated_attribute(@country, 'name', 'nl')
    assert_equal 'Belgique', Country.acts_as_translated_attribute(@country, 'name', 'fr')
    assert_equal 'Royaume de Belgique', Country.acts_as_translated_attribute(@country, 'description', 'fr')

    @country = Country.find_by_iso(:nl)

    assert_equal 'Nederland', Country.acts_as_translated_attribute(@country, :name, :nl)
    assert_equal 'Pays-Bas', Country.acts_as_translated_attribute(@country, :name, :fr)
    assert_equal 'Kingdom of the Netherlands', Country.acts_as_translated_attribute(@country, 'description', :en)
  end

  def test_acts_as_translated_attribute_defaults
    @country = Country.find_by_iso(:be)

    assert_equal 'België', Country.acts_as_translated_attribute(@country, 'name', 'es', default: 'nl')
    assert_equal 'Belgium', Country.acts_as_translated_attribute(@country, 'name', 'de')
    assert_equal 'Royaume de Belgique', Country.acts_as_translated_attribute(@country, 'description', 'ch', default: 'fr')

    @country = Country.find_by_iso(:nl)

    assert_equal 'Nederland', Country.acts_as_translated_attribute(@country, :name, :es, default: :nl)
    assert_equal 'Netherlands', Country.acts_as_translated_attribute(@country, :name, :de)
    assert_equal 'Koninkrijk der Nederlanden', Country.acts_as_translated_attribute(@country, :description, :ch, default: :nl)
  end

  def test_acts_as_translated_attribute_no_default
    @country = Country.find_by_iso(:be)

    assert_raises NoMethodError do
      Country.acts_as_translated_attribute(@country, 'name', 'es', default: 'es')
    end

    assert_raises NoMethodError do
      Country.acts_as_translated_attribute(@country, :name, :es, default: :es)
    end

    assert_raises NoMethodError do
      Country.acts_as_translated_attribute(@country, 'position', 'es')
    end

    assert_raises NoMethodError do
      Country.acts_as_translated_attribute(@country, :position, :es)
    end
  end

  def test_method_generation
    @country = Country.find_by_iso(:be)

    refute_respond_to Country, :description
    assert_respond_to @country, :description
    assert_respond_to @country, :name
    assert_respond_to @country, :slug
  end

  def test_acts_as_translated_attributes
    @belgium = Country.find_by_iso(:be)
    @netherlands = Country.find_by_iso(:nl)

    I18n.enforce_available_locales = false

    I18n.locale = :nl

    assert_equal 'België', @belgium.name
    assert_equal 'Koninkrijk België', @belgium.description
    assert_equal 'belgie', @belgium.slug

    assert_equal 'Nederland', @netherlands.name
    assert_equal 'Koninkrijk der Nederlanden', @netherlands.description
    assert_equal 'nederland', @netherlands.slug

    I18n.locale = :fr

    assert_equal 'Belgique', @belgium.name
    assert_equal 'Royaume de Belgique', @belgium.description
    assert_equal 'belgique', @belgium.slug

    assert_equal 'Pays-Bas', @netherlands.name
    assert_equal 'Royaume des Pays-Bas', @netherlands.description
    assert_equal 'pays-bas', @netherlands.slug

    I18n.locale = :en

    assert_equal 'Belgium', @belgium.name
    assert_equal 'Kingdom of Belgium', @belgium.description
    assert_equal 'belgium', @belgium.slug

    assert_equal 'Netherlands', @netherlands.name
    assert_equal 'Kingdom of the Netherlands', @netherlands.description
    assert_equal 'netherlands', @netherlands.slug
  end

  def test_acts_as_translated_attribute_defaults
    @belgium = Country.find_by_iso(:be)
    @netherlands = Country.find_by_iso(:nl)

    I18n.enforce_available_locales = false

    I18n.locale = :es

    assert_equal 'België', @belgium.name
    assert_equal 'Koninkrijk België', @belgium.description
    assert_equal 'belgium', @belgium.slug

    assert_equal 'Nederland', @netherlands.name
    assert_equal 'Koninkrijk der Nederlanden', @netherlands.description
    assert_equal 'netherlands', @netherlands.slug
  end

  def test_acts_as_translated_methods_with_defaults
    @belgium = Country.find_by_iso(:be)

    I18n.enforce_available_locales = false

    I18n.locale = :nl
    assert_equal 'Custom FR method', @belgium.custom

    I18n.locale = :es
    assert_equal 'Custom ES method', @belgium.custom
  end

  def test_existing_method_names_should_fail
    Country.acts_as_translated(:some_method_name_that_doesnt_exist)
    assert_raises RuntimeError do
      Country.acts_as_translated(:id)
    end
    assert_raises RuntimeError do
      Country.acts_as_translated(:send)
    end
  end

end


text:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="raphael-min.js"></script>
<script src="app.js"></script>
</head>
<body>

</body>
</html>


text:
using System;
using System.ComponentModel;

namespace Azure.Maps.Rendering
{
    ///  The TilesetID.
    public readonly partial struct MapTileSetId : IEquatable<MapTileSetId>
    {
        private readonly string _value;

        ///  Initializes a new instance of <see cref="MapTileSetId"/>.
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public MapTileSetId(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string MicrosoftBaseValue = "microsoft.base";
        private const string MicrosoftBaseLabelsValue = "microsoft.base.labels";
        private const string MicrosoftBaseHybridValue = "microsoft.base.hybrid";
        private const string MicrosoftTerraMainValue = "microsoft.terra.main";
        private const string MicrosoftBaseRoadValue = "microsoft.base.road";
        private const string MicrosoftBaseDarkgreyValue = "microsoft.base.darkgrey";
        private const string MicrosoftBaseLabelsRoadValue = "microsoft.base.labels.road";
        private const string MicrosoftBaseLabelsDarkgreyValue = "microsoft.base.labels.darkgrey";
        private const string MicrosoftBaseHybridRoadValue = "microsoft.base.hybrid.road";
        private const string MicrosoftBaseHybridDarkgreyValue = "microsoft.base.hybrid.darkgrey";
        private const string MicrosoftImageryValue = "microsoft.imagery";
        private const string MicrosoftWeatherRadarMainValue = "microsoft.weather.radar.main";
        private const string MicrosoftWeatherInfraredMainValue = "microsoft.weather.infrared.main";
        private const string MicrosoftDemValue = "microsoft.dem";
        private const string MicrosoftDemContoursValue = "microsoft.dem.contours";
        private const string MicrosoftTrafficAbsoluteValue = "microsoft.traffic.absolute";
        private const string MicrosoftTrafficAbsoluteMainValue = "microsoft.traffic.absolute.main";
        private const string MicrosoftTrafficRelativeValue = "microsoft.traffic.relative";
        private const string MicrosoftTrafficRelativeMainValue = "microsoft.traffic.relative.main";
        private const string MicrosoftTrafficRelativeDarkValue = "microsoft.traffic.relative.dark";
        private const string MicrosoftTrafficDelayValue = "microsoft.traffic.delay";
        private const string MicrosoftTrafficDelayMainValue = "microsoft.traffic.delay.main";
        private const string MicrosoftTrafficReducedMainValue = "microsoft.traffic.reduced.main";
        private const string MicrosoftTrafficIncidentValue = "microsoft.traffic.incident";

        ///
        /// A base map is a standard map that displays roads, natural and artificial features along with the labels for those features in a vector tile.

        ///
        /// Supports zoom levels 0 through 22. Format: vector (pbf).
        ///
        public static MapTileSetId MicrosoftBase { get; } = new MapTileSetId(MicrosoftBaseValue);
        ///
        /// Displays labels for roads, natural and artificial features in a vector tile.

        ///
        /// Supports zoom levels 0 through 22. Format: vector (pbf).
        ///
        public static MapTileSetId MicrosoftBaseLabels { get; } = new MapTileSetId(MicrosoftBaseLabelsValue);
        ///
        /// Displays road, boundary and label data in a vector tile.

        ///
        /// Supports zoom levels 0 through 22. Format: vector (pbf).
        ///
        public static MapTileSetId MicrosoftBaseHybrid { get; } = new MapTileSetId(MicrosoftBaseHybridValue);
        ///
        /// Shaded relief and terra layers.

        ///
        /// Supports zoom levels 0 through 6. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftTerraMain { get; } = new MapTileSetId(MicrosoftTerraMainValue);
        ///
        /// All layers with our main style.

        ///
        /// Supports zoom levels 0 through 22. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftBaseRoad { get; } = new MapTileSetId(MicrosoftBaseRoadValue);
        ///
        /// All layers with our dark grey style.

        ///
        /// Supports zoom levels 0 through 22. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftBaseDarkgrey { get; } = new MapTileSetId(MicrosoftBaseDarkgreyValue);
        ///
        /// Label data in our main style.

        ///
        /// Supports zoom levels 0 through 22. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftBaseLabelsRoad { get; } = new MapTileSetId(MicrosoftBaseLabelsRoadValue);
        ///
        /// Label data in our dark grey style.

        ///
        /// Supports zoom levels 0 through 22. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftBaseLabelsDarkgrey { get; } = new MapTileSetId(MicrosoftBaseLabelsDarkgreyValue);
        ///
        /// Road, boundary and label data in our main style.

        ///
        /// Supports zoom levels 0 through 22. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftBaseHybridRoad { get; } = new MapTileSetId(MicrosoftBaseHybridRoadValue);
        ///
        /// Road, boundary and label data in our dark grey style.

        ///
        /// Supports zoom levels 0 through 22. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftBaseHybridDarkgrey { get; } = new MapTileSetId(MicrosoftBaseHybridDarkgreyValue);
        ///
        /// A combination of satellite and aerial imagery. Only available in S1 pricing SKU.

        ///
        /// Supports zoom levels 1 through 19. Format: raster (jpeg).
        ///
        public static MapTileSetId MicrosoftImagery { get; } = new MapTileSetId(MicrosoftImageryValue);
        ///
        /// Weather radar tiles. Latest weather radar images including areas of rain, snow, ice and mixed conditions. Please see [coverage information](https://aka.ms/AzureMapsWeatherCoverage) for Azure Maps Weather service.  To learn more about the Radar data, please see [Weather concepts](https://aka.ms/AzureMapsWeatherConcepts).

        ///
        /// Supports zoom levels 0 through 15. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftWeatherRadarMain { get; } = new MapTileSetId(MicrosoftWeatherRadarMainValue);
        ///
        /// Weather infrared tiles. Latest Infrared Satellite images shows clouds by their temperature.  Please see [coverage information](https://aka.ms/AzureMapsWeatherCoverage) for Azure Maps Weather service. To learn more about the returned Satellite data, please see [Weather concepts](https://aka.ms/AzureMapsWeatherConcepts).

        ///
        /// Supports zoom levels 0 through 15. Format: raster (png).
        ///
        public static MapTileSetId MicrosoftWeatherInfraredMain { get; } = new MapTileSetId(MicrosoftWeatherInfraredMainValue);
        ///
        /// Digital Elevation Model tiles. The tiles are in the GeoTIFF format with a single 32-bit floating point band. The tiles cover the whole landmass of Earth. Some small islands (e.g., atolls) might not be represented accurately.

        /// * The vertical unit for measurement of elevation height is meters. An elevation value of -32767.0 is used for points that have no data value, most often returned where there isn't landmass (i.e. water).

        /// * The horizontal reference datum is the World Geodetic System 1984 (WGS84-G1150) and the vertical reference datum is the Earth Gravitational Model 2008 (EGM2008).

        /// * Tiles are 258x258 pixel squares rather than the standard 256 x 256. This is done to allow for accurate interpolation of values at the tile edges. As such adjacent tiles overlap by 1 pixel along all edges.

        /// * Tile data comes from the [Airbus WorldDEM4Ortho product](https://www.intelligence-airbusds.com/worlddem-streaming/). Urban areas are approximately leveled down to ground level. All other areas are represented by the object surface level (e.g., trees).

        ///
        /// Supports zoom level 13 only. Format: raster (tiff).
        ///
        public static MapTileSetId MicrosoftDem { get; } = new MapTileSetId(MicrosoftDemValue);
        ///
        /// Digital elevation contour line tiles. Compared to the microsoft.dem option, these tiles are in vector format and intended for visualization purpose. The tiles cover the whole landmass of Earth. Some small islands (e.g., atolls) might not be represented accurately.

        /// * The vertical unit for measurement of elevation height is meters.

        /// * The horizontal reference datum is the World Geodetic System 1984 (WGS84-G1150) and the vertical reference datum is the Earth Gravitational Model 2008 (EGM2008).

        /// * Tile data comes from the [Airbus WorldDEM4Ortho product](https://www.intelligence-airbusds.com/worlddem-streaming/). Urban areas are approximately leveled down to ground level. All other areas are represented by the object surface level (e.g., trees).

        ///
        /// Supports zoom levels 9 through 14. Format: vector (pbf).
        ///
        public static MapTileSetId MicrosoftDemContours { get; } = new MapTileSetId(MicrosoftDemContoursValue);
        ///  absolute traffic tiles in vector.
        public static MapTileSetId MicrosoftTrafficAbsolute { get; } = new MapTileSetId(MicrosoftTrafficAbsoluteValue);
        ///  absolute traffic tiles in raster in our main style.
        public static MapTileSetId MicrosoftTrafficAbsoluteMain { get; } = new MapTileSetId(MicrosoftTrafficAbsoluteMainValue);
        ///  relative traffic tiles in vector.
        public static MapTileSetId MicrosoftTrafficRelative { get; } = new MapTileSetId(MicrosoftTrafficRelativeValue);
        ///  relative traffic tiles in raster in our main style.
        public static MapTileSetId MicrosoftTrafficRelativeMain { get; } = new MapTileSetId(MicrosoftTrafficRelativeMainValue);
        ///  relative traffic tiles in raster in our dark style.
        public static MapTileSetId MicrosoftTrafficRelativeDark { get; } = new MapTileSetId(MicrosoftTrafficRelativeDarkValue);
        ///  traffic tiles in vector.
        public static MapTileSetId MicrosoftTrafficDelay { get; } = new MapTileSetId(MicrosoftTrafficDelayValue);
        ///  traffic tiles in raster in our main style.
        public static MapTileSetId MicrosoftTrafficDelayMain { get; } = new MapTileSetId(MicrosoftTrafficDelayMainValue);
        ///  reduced traffic tiles in raster in our main style.
        public static MapTileSetId MicrosoftTrafficReducedMain { get; } = new MapTileSetId(MicrosoftTrafficReducedMainValue);
        ///  incident tiles in vector.
        public static MapTileSetId MicrosoftTrafficIncident { get; } = new MapTileSetId(MicrosoftTrafficIncidentValue);
        ///  Determines if two <see cref="MapTileSetId"/> values are the same.
        public static bool operator ==(MapTileSetId left, MapTileSetId right) => left.Equals(right);
        ///  Determines if two <see cref="MapTileSetId"/> values are not the same.
        public static bool operator !=(MapTileSetId left, MapTileSetId right) => !left.Equals(right);
        ///  Converts a string to a <see cref="MapTileSetId"/>.
        public static implicit operator MapTileSetId(string value) => new MapTileSetId(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is MapTileSetId other && Equals(other);
        /// <inheritdoc />
        public bool Equals(MapTileSetId other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
namespace Falcor.Server.Routing
{
    public abstract class RouteHandlerResult
    {
        public abstract RouteResult ToRouteResult(FalcorPath unmatchedPath);
    }
}


text:
package org.jtext.curses;

import java.util.Arrays;
import java.util.Objects;

@SuppressWarnings("checkstyle:visibilitymodifier")
public final class CellDescriptor {

    private final ColorName foreground;
    private final ColorName background;
    private final CharacterAttribute[] attributes;

    private CellDescriptor(final ColorName foreground, final ColorName background, final CharacterAttribute[] attributes) {
        Objects.requireNonNull(foreground);
        Objects.requireNonNull(background);
        Objects.requireNonNull(attributes);
        this.foreground = foreground;
        this.background = background;
        this.attributes = attributes;
    }

    public static CellDescriptor empty() {
        return new CellDescriptor(ColorName.NO_COLOR, ColorName.NO_COLOR, new CharacterAttribute[0]);
    }

    public static CellDescriptor foreground(final ColorName color) {
        return of(ColorName.NO_COLOR, color);
    }

    public static CellDescriptor background(final ColorName color) {
        return of(color, ColorName.NO_COLOR);
    }

    public static CellDescriptor of(final ColorName background, final ColorName foreground) {
        return new CellDescriptor(foreground, background, new CharacterAttribute[0]);
    }

    public static CellDescriptor of(final ColorName background, final ColorName foreground,
                                    final CharacterAttribute first,
                                    final CharacterAttribute... rest) {
        final CharacterAttribute[] attributes = new CharacterAttribute[rest.length + 1];
        attributes[0] = first;
        System.arraycopy(rest, 0, attributes, 1, rest.length);
        return new CellDescriptor(foreground, background, attributes);
    }

    public CellDescriptor withBackground(final ColorName colorName) {
        return new CellDescriptor(colorName, foreground, attributes);
    }

    public CellDescriptor withForeground(final ColorName colorName) {
        return new CellDescriptor(background, colorName, attributes);
    }

    public ColorName getForeground() {
        return foreground;
    }

    public ColorName getBackground() {
        return background;
    }

    public CharacterAttribute[] getAttributes() {
        return Arrays.copyOf(attributes, attributes.length);
    }

    public boolean hasForeground() {
        return foreground != ColorName.NO_COLOR;
    }

    public boolean hasBackground() {
        return background != ColorName.NO_COLOR;
    }

    @Override
    public String toString() {
        return "CellDescriptor{" +
                ", foreground=" + foreground +
                ", background=" + background +
                ", attributes=" + Arrays.toString(attributes) +
                '}';
    }
}


text:
/*

    Name:       Base16 Default Dark
    Author:     Chris Kempson (http://chriskempson.com)

	Brackets Template by Amit Mendapara (https://github.com/cristatus)
    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
*/

.cm-s-default .cm-keyword {color: #aa759f;}
.cm-s-default .cm-atom {color: #d28445;}
.cm-s-default .cm-number {color: #d28445;}
.cm-s-default .cm-def {color: #6a9fb5;}
.cm-s-default .cm-punctuation {color: #aa759f;}
.cm-s-default .cm-property {color: #6a9fb5;}
.cm-s-default .cm-operator {color: #d0d0d0;}
.cm-s-default .cm-variable {color: #ac4142;}
.cm-s-default .cm-variable-2 {color: #ac4142;}
.cm-s-default .cm-variable-3 {color: #ac4142;}
.cm-s-default .cm-comment {color: #505050;}
.cm-s-default .cm-string {color: #90a959;}
.cm-s-default .cm-string-2 {color: #75b5aa;}
.cm-s-default .cm-meta {color: #8f5536;}
.cm-s-default .cm-qualifier {color: #d0d0d0;}
.cm-s-default .cm-builtin {color: #aa759f;}
.cm-s-default .cm-bracket {color: #d0d0d0;}
.cm-s-default .cm-tag {color: #ac4142;}
.cm-s-default .cm-attribute {color: #d28445;}
.cm-s-default .cm-header {color: #6a9fb5;}
.cm-s-default .cm-quote {color: #d28445;}
.cm-s-default .cm-hr {color: #d0d0d0; background-color: #303030;}
.cm-s-default .cm-link {color: #ac4142;}

.cm-s-default .cm-error,
.cm-s-default .cm-invalidchar {color: #f5f5f5 !important; background: #ac4142;}

.cm-s-default.CodeMirror {
    background: #151515;
    color: #d0d0d0;
}

.cm-s-default div.CodeMirror-selected {
    background: rgba(160, 160, 160, 0.33) !important;
}

.cm-s-default .CodeMirror-linenumber {
    color: #505050;
}

.cm-s-default .CodeMirror-gutters {
    background: #151515;
    color: #d0d0d0;
    border-right: 0px;
}

.cm-s-default .CodeMirror-cursor,
.cm-s-default .CodeMirror-cursors .CodeMirror-cursor {
    border-left: 1px solid #f0f0f0 !important;
    z-index: 3;
}

.cm-s-default div.CodeMirror-overwrite div.CodeMirror-cursor {
    border: none !important;
    border-bottom: 1px solid #f0f0f0 !important;
}

.cm-s-default .CodeMirror-matchingbracket {
    color: white !important;
}

.cm-s-default .CodeMirror-activeline-background {
    background: rgba(80, 80, 80, 0.33) !important;
}

.cm-s-default .CodeMirror-activeline .CodeMirror-gutter-elt {
    background: transparent !important;
    color: #303030 !important
}

.cm-s-default span.CodeMirror-matchingbracket,
.cm-s-default span.CodeMirror-matchingtag {
    background: #303030 !important;
}

.cm-s-default span.CodeMirror-matchingbracket {
    color: white !important;
}