text:
package org.apache.commons.lang3.time;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import junit.framework.TestCase;

import org.apache.commons.lang3.SerializationUtils;

/**
 * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}.
 *
 * @since 2.0
 * @version $Id: FastDateFormatTest.java 1146138 2011-07-13 17:01:37Z joehni $
 */
public class FastDateFormatTest extends TestCase {

    public FastDateFormatTest(String name) {
        super(name);
    }

    public void test_getInstance() {
        FastDateFormat format1 = FastDateFormat.getInstance();
        FastDateFormat format2 = FastDateFormat.getInstance();
        assertSame(format1, format2);
        assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern());
    }

    public void test_getInstance_String() {
        FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy");
        FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy");
        FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy");

        assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
        assertSame(format2, format3);
        assertEquals("MM/DD/yyyy", format1.getPattern());
        assertEquals(TimeZone.getDefault(), format1.getTimeZone());
        assertEquals(TimeZone.getDefault(), format2.getTimeZone());
    }

    public void test_getInstance_String_TimeZone() {
        Locale realDefaultLocale = Locale.getDefault();
        TimeZone realDefaultZone = TimeZone.getDefault();
        try {
            Locale.setDefault(Locale.US);
            TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));

            FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
                    TimeZone.getTimeZone("Atlantic/Reykjavik"));
            FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
            FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
            FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
            FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
            FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");

            assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
            assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
            assertEquals(TimeZone.getDefault(), format2.getTimeZone());
            assertSame(format3, format4);
            assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5);
            assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5);

        } finally {
            Locale.setDefault(realDefaultLocale);
            TimeZone.setDefault(realDefaultZone);
        }
    }

    public void test_getInstance_String_Locale() {
        Locale realDefaultLocale = Locale.getDefault();
        try {
            Locale.setDefault(Locale.US);
            FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
            FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
            FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);

            assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
            assertSame(format1, format3);
            assertEquals(Locale.GERMANY, format1.getLocale());

        } finally {
            Locale.setDefault(realDefaultLocale);
        }
    }

    public void test_changeDefault_Locale_DateInstance() {
        Locale realDefaultLocale = Locale.getDefault();
        try {
            Locale.setDefault(Locale.US);
            FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
            FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
            Locale.setDefault(Locale.GERMANY);
            FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);

            assertSame(Locale.GERMANY, format1.getLocale());
            assertSame(Locale.US, format2.getLocale());
            assertSame(Locale.GERMANY, format3.getLocale());
            assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
            assertTrue(format2 != format3);

        } finally {
            Locale.setDefault(realDefaultLocale);
        }
    }

    public void test_changeDefault_Locale_DateTimeInstance() {
        Locale realDefaultLocale = Locale.getDefault();
        try {
            Locale.setDefault(Locale.US);
            FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
            FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
            Locale.setDefault(Locale.GERMANY);
            FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);

            assertSame(Locale.GERMANY, format1.getLocale());
            assertSame(Locale.US, format2.getLocale());
            assertSame(Locale.GERMANY, format3.getLocale());
            assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2);
            assertTrue(format2 != format3);

        } finally {
            Locale.setDefault(realDefaultLocale);
        }
    }

    public void test_getInstance_String_TimeZone_Locale() {
        Locale realDefaultLocale = Locale.getDefault();
        TimeZone realDefaultZone = TimeZone.getDefault();
        try {
            Locale.setDefault(Locale.US);
            TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));

            FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
                    TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY);
            FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
            FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
                    TimeZone.getDefault(), Locale.GERMANY);

            assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2);
            assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
            assertEquals(TimeZone.getDefault(), format2.getTimeZone());
            assertEquals(TimeZone.getDefault(), format3.getTimeZone());
            assertEquals(Locale.GERMANY, format1.getLocale());
            assertEquals(Locale.GERMANY, format2.getLocale());
            assertEquals(Locale.GERMANY, format3.getLocale());

        } finally {
            Locale.setDefault(realDefaultLocale);
            TimeZone.setDefault(realDefaultZone);
        }
    }

    public void testFormat() {
        Locale realDefaultLocale = Locale.getDefault();
        TimeZone realDefaultZone = TimeZone.getDefault();
        try {
            Locale.setDefault(Locale.US);
            TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));

            GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20);
            GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00);
            Date date1 = cal1.getTime();
            Date date2 = cal2.getTime();
            long millis1 = date1.getTime();
            long millis2 = date2.getTime();

            FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            assertEquals(sdf.format(date1), fdf.format(date1));
            assertEquals("2003-01-10T15:33:20", fdf.format(date1));
            assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
            assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
            assertEquals("2003-07-10T09:00:00", fdf.format(date2));
            assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
            assertEquals("2003-07-10T09:00:00", fdf.format(millis2));

            fdf = FastDateFormat.getInstance("Z");
            assertEquals("-0500", fdf.format(date1));
            assertEquals("-0500", fdf.format(cal1));
            assertEquals("-0500", fdf.format(millis1));

            assertEquals("-0400", fdf.format(date2));
            assertEquals("-0400", fdf.format(cal2));
            assertEquals("-0400", fdf.format(millis2));

            fdf = FastDateFormat.getInstance("ZZ");
            assertEquals("-05:00", fdf.format(date1));
            assertEquals("-05:00", fdf.format(cal1));
            assertEquals("-05:00", fdf.format(millis1));

            assertEquals("-04:00", fdf.format(date2));
            assertEquals("-04:00", fdf.format(cal2));
            assertEquals("-04:00", fdf.format(millis2));

            String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" +
                " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
            fdf = FastDateFormat.getInstance(pattern);
            sdf = new SimpleDateFormat(pattern);
            // SDF bug fix starting with Java 7
            assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
            assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
        } finally {
            Locale.setDefault(realDefaultLocale);
            TimeZone.setDefault(realDefaultZone);
        }
    }

    /**
     * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}.
     */
    public void testShortDateStyleWithLocales() {
        Locale usLocale = Locale.US;
        Locale swedishLocale = new Locale("sv", "SE");
        Calendar cal = Calendar.getInstance();
        cal.set(2004, 1, 3);
        FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale);
        assertEquals("2/3/04", fdf.format(cal));

        fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale);
        assertEquals("2004-02-03", fdf.format(cal));

    }

    /**
     * Tests that pre-1000AD years get padded with yyyy
     */
    public void testLowYearPadding() {
        Calendar cal = Calendar.getInstance();
        FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD");

        cal.set(1,0,1);
        assertEquals("0001/01/01", format.format(cal));
        cal.set(10,0,1);
        assertEquals("0010/01/01", format.format(cal));
        cal.set(100,0,1);
        assertEquals("0100/01/01", format.format(cal));
        cal.set(999,0,1);
        assertEquals("0999/01/01", format.format(cal));
    }
    /**
     * Show Bug #39410 is solved
     */
    public void testMilleniumBug() {
        Calendar cal = Calendar.getInstance();
        FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy");

        cal.set(1000,0,1);
        assertEquals("01.01.1000", format.format(cal));
    }

    /**
     * testLowYearPadding showed that the date was buggy
     * This test confirms it, getting 366 back as a date
     */
    public void testSimpleDate() {
        Calendar cal = Calendar.getInstance();
        FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd");

        cal.set(2004,11,31);
        assertEquals("2004/12/31", format.format(cal));
        cal.set(999,11,31);
        assertEquals("0999/12/31", format.format(cal));
        cal.set(1,2,2);
        assertEquals("0001/03/02", format.format(cal));
    }

    public void testLang303() {
        Calendar cal = Calendar.getInstance();
        cal.set(2004,11,31);

        FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd");
        String output = format.format(cal);

        format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) );
        assertEquals(output, format.format(cal));
    }

    public void testLang538() {
        // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
        // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
        GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
        cal.clear();
        cal.set(2009, 9, 16, 8, 42, 16);

        FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
        assertEquals("dateTime", "2009-10-16T16:42:16.000Z", format.format(cal.getTime()));
        assertEquals("dateTime", "2009-10-16T08:42:16.000Z", format.format(cal));
    }

    public void testLang645() {
        Locale locale = new Locale("sv", "SE");

        Calendar cal = Calendar.getInstance();
        cal.set(2010, 0, 1, 12, 0, 0);
        Date d = cal.getTime();

        FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale);

        assertEquals("fredag, week 53", fdf.format(d));
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Web.Routing;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;

namespace Orchard.Themes {
    public class ThemeManager : IThemeManager {
        private readonly IEnumerable<IThemeSelector> _themeSelectors;
        private readonly IExtensionManager _extensionManager;

        public ThemeManager(IEnumerable<IThemeSelector> themeSelectors,
                            IExtensionManager extensionManager) {
            _themeSelectors = themeSelectors;
            _extensionManager = extensionManager;
        }

        public ExtensionDescriptor GetRequestTheme(RequestContext requestContext) {
            var requestTheme = _themeSelectors
                .Select(x => x.GetTheme(requestContext))
                .Where(x => x != null)
                .OrderByDescending(x => x.Priority);

            if (requestTheme.Count() < 1)
                return null;

            foreach (var theme in requestTheme) {
                var t = _extensionManager.GetExtension(theme.ThemeName);
                if (t != null)
                    return t;
            }

            return _extensionManager.GetExtension("SafeMode");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var day=new Date();
var m=day.getMonth();
var d=day.getDate();
var y=day.getFullYear();
var today=new Date(y,m,d);

//var checkFlag=true;
var arrivalFlag=true;
var departureFlag=true;
var roomFlag=true;

//searchCheck();
var arrival=document.getElementById('arrival');
var departure=document.getElementById('departure');
var single=document.getElementById('single');
var double=document.getElementById('double');
var submit=document.getElementById('submitBtn');
var cancel=document.getElementById('cancelBtn');
var edit=document.getElementById('editBtn');
var usecase=document.getElementById('checkInfoUseCase');
var single=document.getElementById('single');
var double=document.getElementById('double');
var d1=document.getElementById('arrival');
var d2=document.getElementById('departure');
// d1.setAttribute("style","background:#ffffff;");
// d2.setAttribute("style","background:#ffffff;");

// arrivalCheck();
// dateCheck();
// singleCheck();
function singleCheck(){
  if(single.value==0&&double.value==0){
    document.getElementById("singleRow").setAttribute("class","form-group has-error row");
    document.getElementById("doubleRow").setAttribute("class","form-group has-error row");
    document.getElementById("roomMsg").removeAttribute("hidden");
    roomFlag=false;
  }
  else{
    document.getElementById("singleRow").setAttribute("class","form-group has-success row");
    document.getElementById("doubleRow").setAttribute("class","form-group has-success row");
    try{document.getElementById("roomMsg").setAttribute("hidden",null);}catch(e){console.log("error2");}
    roomFlag=true;
  }
  searchCheck();
}
function arrivalCheck(){
  console.log("ARRIVAL KO YOUK TL");
  var arrival=new Date(d1.value);
  var departure=new Date(d2.value);
  if(d1.value!=""){
    if(arrival>=today){
      document.getElementById("arrivalRow").setAttribute("class","form-group has-success row");
      try{document.getElementById("arrivalMsg").setAttribute("hidden",null);}catch(e){console.log("error2");}
      arrivalFlag=true;
    }
    else {
      console.log("Must be today or later");
      document.getElementById("arrivalRow").setAttribute("class","form-group has-error row");
      document.getElementById("arrivalMsg").removeAttribute("hidden");
      arrivalFlag=false;
    }
    //arrivalFlag=true;
    try{dateCheck()}catch(e){console.log("error1"); }
  }
  searchCheck();
}
function dateCheck(){

  var arrival=new Date(d1.value);
  var departure=new Date(d2.value);
  if(d2.value!=""){
    if(departure<arrival){
      console.log("DEPARTURE FALSE");
      document.getElementById("departureRow").setAttribute("class","form-group has-error row");
      document.getElementById("departureMsg").removeAttribute("hidden");
      departureFlag=false;
    }
    else{
      console.log("DEPARTURE TRUE");
      document.getElementById("departureRow").setAttribute("class","form-group has-success row");
      try{document.getElementById("departureMsg").setAttribute("hidden",null);}catch(e){console.log("error2");}
      departureFlag=true;
    }
    searchCheck();
  }
}
function searchCheck(){
  if(arrivalFlag==true && departureFlag==true&&roomFlag==true){
    console.log("all true");
    submit.removeAttribute("disabled");
  }
  else{
    console.log("FALSE");
    submit.setAttribute("disabled","true");
  }
}
////////////////////////////////////////////////////

function onEdit(){
  d1.removeAttribute("disabled");
  d1.setAttribute("style","background:#ffffff;");
  d2.removeAttribute("disabled");
  d2.setAttribute("style","background:#ffffff;");
  single.removeAttribute("readonly");
  double.removeAttribute("readonly");
  submit.setAttribute("style","float:right;");
  cancel.setAttribute("style","float:right;display:none;");
  edit.setAttribute("onclick","javascript:onEdit2();");
  edit.setAttribute("value","Cancel Edit");
  usecase.setAttribute("value","editReservation");
  console.log(usecase.value);
  arrivalCheck();
  dateCheck();
  singleCheck();
}
function onEdit2(){
  d1.setAttribute("readonly",true);
  d1.setAttribute("disabled",true);
  d1.removeAttribute("style");
  d2.setAttribute("readonly",true);
  d2.setAttribute("disabled",true);
  d2.removeAttribute("style");
  single.setAttribute("readonly",true);
  double.setAttribute("readonly",true);
  submit.setAttribute("style","float:right;display:none;");
  cancel.setAttribute("style","float:right;");
  edit.setAttribute("onclick","javascript:onEdit();");
  edit.setAttribute("value","Edit");
  usecase.setAttribute("value","cancelReservation");
  console.log(usecase.value);
}


text:
package com.twitter.finatra.http.tests.routing

import com.twitter.finagle.Filter
import com.twitter.finagle.http.{Method, Request, Response}
import com.twitter.finatra.http.contexts.RouteInfo
import com.twitter.finatra.http.internal.routing.{Route, Routes}
import com.twitter.inject.Test
import com.twitter.util.Future
import org.scalatest.OptionValues

class RoutesTest extends Test with OptionValues {

  "constant route" in {
    val routes = Routes.createForMethod(
      Seq(createRoute(Method.Get, "/groups/")), Method.Get)

    routes.handle(
      Request("/groups/")) should be('defined)

    routes.handle(
      Request("/groups")) should be('empty)

    routes.handle(
      Request("/foo")) should be('empty)
  }

  "path pattern route" in {
    val routes = Routes.createForMethod(
      Seq(createRoute(Method.Get, "/groups/:id")), Method.Get)

    routes.handle(
      Request("/groups/1")) should be('defined)

    routes.handle(
      Request("/groups/")) should be('empty)
  }

  "route info" in {
    val routes = Routes.createForMethod(
      Seq(createRoute(Method.Get, "/groups/")), Method.Get)

    val request = Request("/groups/")
    routes.handle(request) should be('defined)

    RouteInfo(request).value should be(RouteInfo("my_endpoint", "/groups/"))
  }

  def defaultCallback(request: Request) = {
    Future(Response())
  }

  def createRoute(method: Method, path: String): Route = {
    Route(
      name = "my_endpoint",
      method = method,
      path = path,
      admin = false,
      adminIndexInfo = None,
      callback = defaultCallback,
      annotations = Seq(),
      requestClass = classOf[Request],
      responseClass = classOf[Response],
      filter = Filter.identity)
  }
}


text:
// Submodules
#include <ITKHelpers/ITKHelpers.h>
#include <Mask/Mask.h>

// ITK
#include "itkImageFileReader.h"
#include "itkMaskImageFilter.h"
#include "itkRGBToLuminanceImageFilter.h"

static void CreateMask(Mask::Pointer mask);

int main(int argc, char *argv[])
{
  Mask::Pointer mask = Mask::New();
  CreateMask(mask);

  itk::Index<2> queryPixel;
  queryPixel[0] = 5;
  queryPixel[1] = 5;

  typedef itk::CovariantVector<float, 2> FloatVector2Type;
  FloatVector2Type direction;
  direction[0] = 1;
  direction[1] = 1;
  direction.Normalize();

  // TODO: Update this to the new API
  //itk::Index<2> pixelAcross = mask->FindPixelAcrossHole(queryPixel, direction);
  itk::Index<2> pixelAcross; // TODO: placeholder

  std::cout << "Pixel across: " << pixelAcross << std::endl;

  //HelpersOutput::WriteImage<Mask>(blurredLuminance, "Test/TestIsophotes.blurred.mha");

  return EXIT_SUCCESS;
}

static void CreateMask(Mask::Pointer mask)
{
  itk::Size<2> size;
  size.Fill(20);

  itk::Index<2> start;
  start.Fill(0);

  itk::ImageRegion<2> region(start,size);

  mask->SetRegions(region);
  mask->Allocate();
  mask->FillBuffer(mask->GetValidValue());

  itk::ImageRegionIterator<Mask> iterator(mask, mask->GetLargestPossibleRegion());

  while(!iterator.IsAtEnd())
  {
    if(iterator.GetIndex()[0] > 5 && iterator.GetIndex()[0] < 15 &&
       iterator.GetIndex()[1] > 5 && iterator.GetIndex()[1] < 15)
    {
      mask->SetPixel(iterator.GetIndex(), mask->GetHoleValue());
    }

    ++iterator;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

	<!-- ========================= GENERAL DEFINITIONS ========================= -->

	<!-- Configurer that replaces ${...} placeholders with values from properties files -->
	<!-- (in this case, JDBC related properties) -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>WEB-INF/jdbc.properties</value>
			</list>
		</property>
	</bean>

	<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

	<!-- Generic validator for Account objects, to be used for example by the Spring web tier -->
	<bean id="accountValidator" class="org.springframework.samples.jpetstore.domain.logic.AccountValidator"/>

	<!-- Generic validator for Order objects, to be used for example by the Spring web tier -->
	<bean id="orderValidator" class="org.springframework.samples.jpetstore.domain.logic.OrderValidator"/>

	<!--
		This marker creates the full auto-proxy infrastructure
		that is necessary for applying Spring's Transactional annotation
		(as contained in the PetStoreAnnotationImpl class). By default,
		it will refer to the transaction manager bean named "transactionManager".
	-->
	<tx:annotation-driven/>

	<!--
		JPetStore primary business object: default implementation,
		Note that this is just a POJO definition in this file:
		there's no need to use a TransactionFactoryProxyBean if the class has
		source-level transaction annotations; the "tx:annotation-driven"
		marker above will apply transaction advice automatically.
	-->
	<bean id="petStore" class="org.springframework.samples.jpetstore.domain.logic.PetStoreAnnotationImpl">
		<property name="accountDao" ref="accountDao"/>
		<property name="categoryDao" ref="categoryDao"/>
		<property name="productDao" ref="productDao"/>
		<property name="itemDao" ref="itemDao"/>
		<property name="orderDao" ref="orderDao"/>
	</bean>

	<!-- ========================= REMOTE EXPORTER DEFINITIONS ========================= -->

	<!-- RMI exporter for the JPetStore OrderService -->
	<!-- Commented out by default to avoid conflicts with EJB containers -->
	<!--
	<bean id="order-rmi" class="org.springframework.remoting.rmi.RmiServiceExporter">
		<property name="service" ref="petStore"/>
		<property name="serviceInterface" value="org.springframework.samples.jpetstore.domain.logic.OrderService"/>
		<property name="serviceName" value="order"/>
		<property name="registryPort" value="1099"/>
	</bean>
	-->

</beans>


text:
package uk.ac.ebi.pride.indexutils.modifications;

import uk.ac.ebi.pride.archive.dataprovider.identification.ModificationProvider;
import uk.ac.ebi.pride.archive.dataprovider.param.CvParamProvider;
import uk.ac.ebi.pride.indexutils.helpers.ModificationHelper;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Noemi del Toro, Jose A. Dianes
 * @version $Id$
 */
public class Modification implements ModificationProvider {

    private String accession;
    private String name;
    private Integer mainPosition;
    private Map<Integer, CvParamProvider> positionMap = new TreeMap<Integer, CvParamProvider>();
    private CvParamProvider neutralLoss;

    public Modification() {
    }

    public Modification(String asString) {
        ModificationProvider mod = ModificationHelper.convertFromString(asString);
        this.accession = mod.getAccession();
        this.name = mod.getName();
        this.mainPosition = mod.getMainPosition();
        this.positionMap = mod.getPositionMap();
        this.neutralLoss = mod.getNeutralLoss();
    }

    @Override
    public String getAccession() {
        return accession;
    }

    public void setAccession(String accession) {
        this.accession = accession;
    }

    @Override
    public String getName() {
        return name;
    }

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

    /**
     * Position used by the Archive web app. In the case of ambiguous position
     * it will be the first one reported
     */
    @Override
    public Integer getMainPosition() {
        //TODO: Change the selection from the first one to the highest one
        //In the case that we have ambiguous modification we choose the one with highest score to be expose
        if (this.getPositionMap() != null && !this.getPositionMap().isEmpty()) {
            this.mainPosition = this.getPositionMap().entrySet().iterator().next().getKey();
        }

        return mainPosition;
    }

    @Override
    public Map<Integer, CvParamProvider> getPositionMap() {
        return positionMap;
    }

    public void addPosition(Integer id, CvParamProvider param) {
        this.positionMap.put(id, param);
    }

    public void setPositionMap(Map<Integer, CvParamProvider> positionMap) {
        this.positionMap = positionMap;
    }

    public CvParamProvider getNeutralLoss() {
        return neutralLoss;
    }

    public void setNeutralLoss(CvParamProvider neutralLoss) {
        this.neutralLoss = neutralLoss;
    }

    public String getModificationAsString() {
        return ModificationHelper.convertToString(this);
    }

}


text:
title: portfolio
layout: post
---

Testing

{% for item in site.portfolio %}
  {{ item.title }}
{% endfor %}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**message_type_name** | **string** | Message Type Name | [optional]
**template** | [**\BumbalClient\Model\TemplateModel**](TemplateModel.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
// Should be used *before* connect.static

module.exports = function(docroot,phpBin) {
  'use strict';

  phpBin = phpBin || 'php';

  var fs = require('fs')
    , join = require('path').join
    , norm = require('path').normalize;

  return function(req, res, next) {
    if(/\.php$/i.test(req.url)) {
      var phpFile = norm(join(docroot, req.url));
      fs.exists(phpFile, function(exists) {
        if(exists) {
          res.setHeader('Content-Type', 'text/html');

          var cp = require('child_process').spawn(phpBin, [phpFile]);

          cp.stdout.on('data', function(data) {
            res.write(data);
          });

          cp.stderr.on('data', function(data) {
            res.write(data);
          });

          cp.on('close', function() {
            res.end('');
          });

        } else {
          next();
        }
      });
    } else {
      next();
    }
  };
};


text:
<img src="http://static.jboss.org/hibernate/images/hibernate_logo_whitebkg_200px.png" />

## This project is no longer maintained separately.  It's code has been moved into Hibernate ORM proper.

It's original README is comtained below...

___

This project defines:

* the Hibernate semantic query model (SQM), which is just a fancy way to say it defines
an object view of a query
* a walker (visitor) over SQM
* capability to interpret HQL/JPQL and JPA Criteria queries into SQM

The SQM can then be handed to Hibernate ORM (or other Hibernate projects accepting SQM)
and be executed.


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('courses', '0002_auto_20150403_2321'),
    ]

    operations = [
        migrations.AddField(
            model_name='course',
            name='departments',
            field=models.ManyToManyField(to='courses.Department'),
        ),
        migrations.AddField(
            model_name='course',
            name='semester',
            field=models.ForeignKey(to='courses.Semester', default=1),
            preserve_default=False,
        ),
    ]


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require "myrrha"
class Object

  def eq(x)
    lambda{|y| raise("Expected #{x} but was #{y} ") unless x == y}
  end

  def be_a(clazz)
    lambda{|y| raise("Expected #{y.inspect} to be a #{clazz}") unless y.is_a?(clazz)}
  end

  def should(matcher)
    matcher.call(self)
  end

end


text:
(function($) {

	$.fn.easyPaginate = function(options){

		var defaults = {
			step: 4,
			delay: 100,
			numeric: true,
			nextprev: true,
			auto:false,
			loop:false,
			pause:4000,
			clickstop:true,
			controls: 'pagination',
			current: 'current',
			randomstart: false
		};

		var options = $.extend(defaults, options);
		var step = options.step;
		var lower, upper;
		var children = $(this).children();
		var count = children.length;
		var obj, next, prev;
		var pages = Math.floor(count/step);
		var page = (options.randomstart) ? Math.floor(Math.random()*pages)+1 : 1;
		var timeout;
		var clicked = false;

		function show(){
			clearTimeout(timeout);
			lower = ((page-1) * step);
			upper = lower+step;
			$(children).each(function(i){
				var child = $(this);
				child.hide();
				if(i>=lower && i<upper){ setTimeout(function(){ child.fadeIn('fast') }, ( i-( Math.floor(i/step) * step) )*options.delay ); }
				if(options.nextprev){
					if(upper >= count) { next.fadeOut('fast'); } else { next.fadeIn('fast'); };
					if(lower >= 1) { prev.fadeIn('fast'); } else { prev.fadeOut('fast'); };
				};
			});
			$('li','#'+ options.controls).removeClass(options.current);
			$('li[data-index="'+page+'"]','#'+ options.controls).addClass(options.current);

			if(options.auto){
				if(options.clickstop && clicked){}else{ timeout = setTimeout(auto,options.pause); };
			};
		};

		function auto(){
			if(options.loop) if(upper >= count){ page=0; show(); }
			if(upper < count){ page++; show(); }
		};

		this.each(function(){

			obj = this;

			if(count>step){

				if((count/step) > pages) pages++;

				var ol = $('

').insertAfter(obj);

				if(options.nextprev){
					prev = $('
Previous
')
						.hide()
						.appendTo(ol)
						.click(function(){
							clicked = true;
							page--;
							show();
						});
				};

				if(options.numeric){
					for(var i=1;i<=pages;i++){
					$('
'+ i +'
')
						.appendTo(ol)
						.click(function(){
							clicked = true;
							page = $(this).attr('data-index');
							show();
						});
					};
				};

				if(options.nextprev){
					next = $('
Next
')
						.hide()
						.appendTo(ol)
						.click(function(){
							clicked = true;
							page++;
							show();
						});
				};

				show();
			};
		});

	};

})(jQuery);


text:
function d = getSclIsrDiffusionOperatorNormalization( obj, varargin )
% GETSCLISRDIFFUSIONOPERATORNORMALIZATION Get normalization of the scaled
% ISR operator of an nlsaModel_scl object
%
% Modified 2014/07/28

d = getNormalization( getSclIsrDiffusionOperator( obj ), varargin{ : } );


text:
package org.springframework.data.solr.core.convert;

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

import javax.xml.parsers.ParserConfigurationException;

import org.apache.solr.client.solrj.beans.Field;
import org.hamcrest.core.IsEqual;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.solr.AbstractITestWithEmbeddedSolrServer;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.geo.GeoLocation;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.data.solr.core.query.SimpleStringCriteria;
import org.xml.sax.SAXException;

/**
 * @author Christoph Strobl
 */
public class ITestMappingSolrConverter extends AbstractITestWithEmbeddedSolrServer {

	private static final Query DEFAULT_BEAN_OBJECT_QUERY = new SimpleQuery(new Criteria("id").is(DEFAULT_BEAN_ID));
	private static final Query ALL_DOCUMENTS_QUERY = new SimpleQuery(new SimpleStringCriteria("*:*"));

	private SolrTemplate solrTemplate;

	@Before
	public void setUp() throws IOException, ParserConfigurationException, SAXException {
		solrTemplate = new SolrTemplate(solrServer, null);
	}

	@After
	public void tearDown() {
		solrTemplate.delete(ALL_DOCUMENTS_QUERY);
		solrTemplate.commit();
	}

	@Test
	public void convertsGeoLocationCorrectly() {
		BeanWithGeoLocation bean = new BeanWithGeoLocation();
		bean.id = DEFAULT_BEAN_ID;
		bean.location = new GeoLocation(48.30975D, 14.28435D);

		BeanWithGeoLocation loaded = saveAndLoad(bean);

		Assert.assertEquals(bean.location.getLatitude(), loaded.location.getLatitude(), 0.0F);
		Assert.assertEquals(bean.location.getLongitude(), loaded.location.getLongitude(), 0.0F);
	}

	@Test
	public void convertsJodaDateTimeCorrectly() {
		BeanWithJodaDateTime bean = new BeanWithJodaDateTime();
		bean.id = DEFAULT_BEAN_ID;
		bean.manufactured = new DateTime(2013, 6, 18, 6, 0, 0);

		BeanWithJodaDateTime loaded = saveAndLoad(bean);

		Assert.assertThat(loaded.manufactured, IsEqual.equalTo(bean.manufactured));
	}

	@Test
	public void convertsJodaLcoalDateTimeCorrectly() {
		BeanWithJodaLocalDateTime bean = new BeanWithJodaLocalDateTime();
		bean.id = DEFAULT_BEAN_ID;
		bean.manufactured = new LocalDateTime(2013, 6, 18, 6, 0, 0);

		BeanWithJodaLocalDateTime loaded = saveAndLoad(bean);

		Assert.assertThat(loaded.manufactured, IsEqual.equalTo(bean.manufactured));
	}

	@Test
	public void testProcessesListCorrectly() {
		BeanWithList bean = new BeanWithList();
		bean.id = DEFAULT_BEAN_ID;
		bean.categories = Arrays.asList("spring", "data", "solr");

		BeanWithList loaded = saveAndLoad(bean);

		Assert.assertThat(loaded.categories, IsEqual.equalTo(bean.categories));
	}

	@Test
	public void testProcessesInheritanceCorrectly() {
		BeanWithBaseClass bean = new BeanWithBaseClass();
		bean.id = DEFAULT_BEAN_ID;
		bean.name = "christoph strobl";

		BeanWithBaseClass loaded = saveAndLoad(bean);

		Assert.assertEquals(bean.id, loaded.id);
		Assert.assertEquals(bean.name, loaded.name);
	}

	@Test
	public void testProcessesEnumCorrectly() {
		BeanWithEnum bean = new BeanWithEnum();
		bean.id = DEFAULT_BEAN_ID;
		bean.enumProperty = LiteralNumberEnum.TWO;

		BeanWithEnum loaded = saveAndLoad(bean);

		Assert.assertEquals(bean.id, loaded.id);
		Assert.assertEquals(bean.enumProperty, loaded.enumProperty);

		Query query = new SimpleQuery(new Criteria("enumProperty_s").is(LiteralNumberEnum.TWO));

		BeanWithEnum loadedViaProperty = solrTemplate.queryForObject(query, BeanWithEnum.class);
		Assert.assertEquals(bean.id, loadedViaProperty.id);
		Assert.assertEquals(bean.enumProperty, loadedViaProperty.enumProperty);
	}

	@SuppressWarnings("unchecked")
	private <T> T saveAndLoad(T o) {
		solrTemplate.saveBean(o);
		solrTemplate.commit();

		return (T) solrTemplate.queryForObject(DEFAULT_BEAN_OBJECT_QUERY, o.getClass());
	}

	private static class BeanWithGeoLocation {

		@SuppressWarnings("unused")
		@Id
		@Field
		private String id;

		@Field("store")
		private GeoLocation location;

	}

	private static class BeanWithJodaDateTime {

		@SuppressWarnings("unused")
		@Id
		@Field
		private String id;

		@Field("manufacturedate_dt")
		private DateTime manufactured;

	}

	private static class BeanWithJodaLocalDateTime {

		@SuppressWarnings("unused")
		@Id
		@Field
		private String id;

		@Field("manufacturedate_dt")
		private LocalDateTime manufactured;

	}

	private static class BeanWithList {

		@SuppressWarnings("unused")
		@Id
		@Field
		private String id;

		@Field("cat")
		private List<String> categories;

	}

	private static class BeanBaseClass {

		@Id
		@Field
		protected String id;

	}

	private static class BeanWithBaseClass extends BeanBaseClass {

		@Field("name")
		private String name;

	}

	private enum LiteralNumberEnum {
		ONE, TWO, THREE;
	}

	private static class BeanWithEnum {

		@Id
		@Field
		private String id;

		@Field("enumProperty_s")
		private LiteralNumberEnum enumProperty;

	}

}


text:
package org.ocpsoft.rewrite.param;

import org.apache.http.client.methods.HttpGet;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.ocpsoft.rewrite.Root;
import org.ocpsoft.rewrite.config.ConfigurationProvider;
import org.ocpsoft.rewrite.test.HttpAction;
import org.ocpsoft.rewrite.test.RewriteTest;

/**
 * @author Lincoln Baxter, III
 *
 */
public class ParameterizedOperationTest extends RewriteTest
{
   @Deployment(testable = false)
   public static WebArchive getDeployment()
   {
      WebArchive deployment = RewriteTest
               .getDeployment()
               .addPackages(true, Root.class.getPackage())
               .addAsWebResource(new StringAsset("exists"), "index.html")
               .addAsServiceProvider(ConfigurationProvider.class, ParameterizedOperationConfigurationProvider.class);
      return deployment;
   }

   @Test
   public void testParameterizedOperationReturningNullParametersDeploysNormally() throws Exception
   {
      HttpAction<HttpGet> action = get("/index.html");
      Assert.assertEquals(200, action.getResponse().getStatusLine().getStatusCode());
   }

}


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * ReplaceNetworkAclEntryRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ReplaceNetworkAclEntryRequestMarshaller implements Marshaller<Request<ReplaceNetworkAclEntryRequest>, ReplaceNetworkAclEntryRequest> {

    public Request<ReplaceNetworkAclEntryRequest> marshall(ReplaceNetworkAclEntryRequest replaceNetworkAclEntryRequest) {

        if (replaceNetworkAclEntryRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<ReplaceNetworkAclEntryRequest> request = new DefaultRequest<ReplaceNetworkAclEntryRequest>(replaceNetworkAclEntryRequest, "AmazonEC2");
        request.addParameter("Action", "ReplaceNetworkAclEntry");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (replaceNetworkAclEntryRequest.getNetworkAclId() != null) {
            request.addParameter("NetworkAclId", StringUtils.fromString(replaceNetworkAclEntryRequest.getNetworkAclId()));
        }

        if (replaceNetworkAclEntryRequest.getRuleNumber() != null) {
            request.addParameter("RuleNumber", StringUtils.fromInteger(replaceNetworkAclEntryRequest.getRuleNumber()));
        }

        if (replaceNetworkAclEntryRequest.getProtocol() != null) {
            request.addParameter("Protocol", StringUtils.fromString(replaceNetworkAclEntryRequest.getProtocol()));
        }

        if (replaceNetworkAclEntryRequest.getRuleAction() != null) {
            request.addParameter("RuleAction", StringUtils.fromString(replaceNetworkAclEntryRequest.getRuleAction()));
        }

        if (replaceNetworkAclEntryRequest.getEgress() != null) {
            request.addParameter("Egress", StringUtils.fromBoolean(replaceNetworkAclEntryRequest.getEgress()));
        }

        if (replaceNetworkAclEntryRequest.getCidrBlock() != null) {
            request.addParameter("CidrBlock", StringUtils.fromString(replaceNetworkAclEntryRequest.getCidrBlock()));
        }

        if (replaceNetworkAclEntryRequest.getIpv6CidrBlock() != null) {
            request.addParameter("Ipv6CidrBlock", StringUtils.fromString(replaceNetworkAclEntryRequest.getIpv6CidrBlock()));
        }

        IcmpTypeCode icmpTypeCode = replaceNetworkAclEntryRequest.getIcmpTypeCode();
        if (icmpTypeCode != null) {

            if (icmpTypeCode.getType() != null) {
                request.addParameter("Icmp.Type", StringUtils.fromInteger(icmpTypeCode.getType()));
            }

            if (icmpTypeCode.getCode() != null) {
                request.addParameter("Icmp.Code", StringUtils.fromInteger(icmpTypeCode.getCode()));
            }
        }

        PortRange portRange = replaceNetworkAclEntryRequest.getPortRange();
        if (portRange != null) {

            if (portRange.getFrom() != null) {
                request.addParameter("PortRange.From", StringUtils.fromInteger(portRange.getFrom()));
            }

            if (portRange.getTo() != null) {
                request.addParameter("PortRange.To", StringUtils.fromInteger(portRange.getTo()));
            }
        }

        return request;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Backlog4net.Api.Option
{
    public class UpdateProjectParams : PatchParams
    {
        public UpdateProjectParams(IdOrKey projectIdOrKey)
        {
            this.ProjectIdOrKey = projectIdOrKey;
        }

        public IdOrKey ProjectIdOrKey { get; private set; }

        public string Name { set => AddNewParamValue(value); }

        public string ProjectKey { set => AddNewParam("key", value); }

        public bool ChartEnabled { set => AddNewParamValue(value); }

        public bool SubtaskingEnabled { set => AddNewParamValue(value); }

        public TextFormattingRule TextFormattingRule { set => AddNewParamValue(value.ToString().ToStartLower()); }

        public bool Archived { set => AddNewParamValue(value); }
    }
}


text:
INCLUDE(delta3d_common)

#variable names of the individual Delta3D libraries.  Can be used in application cmakelist.txt files.
FIND_DELTA3D_LIBRARY(DTINPUTISENSE_LIBRARY         dtInputIsense)
FIND_DELTA3D_LIBRARY(DTINPUTISENSE_DEBUG_LIBRARY   dtInputIsenseD)

IF (NOT DTINPUTISENSE_DEBUG_LIBRARY)
  SET(DTINPUTISENSE_DEBUG_LIBRARY ${DTINPUTISENSE_LIBRARY})
  MESSAGE(STATUS "No debug library was found for DTINPUTISENSE_DEBUG_LIBRARY")
ENDIF()

#convienent list of libraries to link with when using dtInputIsense
SET(DTINPUTISENSE_LIBRARIES
    optimized ${DTINPUTISENSE_LIBRARY}      debug ${DTINPUTISENSE_DEBUG_LIBRARY}
    )

SET(DTINPUTISENSE_INCLUDE_DIRECTORIES ${DELTA3D_INCLUDE_DIR}
    )

# handle the QUIETLY and REQUIRED arguments and set DELTA3D_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(dtInputIsense DEFAULT_MSG DELTA3D_INCLUDE_DIR     DTINPUTISENSE_LIBRARY
                                  )


text:
class TaskApi::UsersController < TaskApi::ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = TaskApi::User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = TaskApi::User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = TaskApi::User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to root_path, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = TaskApi::User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :mail, :password,
                                   :password_confirmation)
    end
end


text:
<?php

interface MappableGeocoder
{

    /**
     * Get locations given a search string
     * @param  string $searchString place name to search for, e.g. 'Bangkok'
     * @return array  List of places matching the search term
     */
    public function getLocations($searchString);
}


text:
import { FrameworkConfiguration } from 'aurelia-framework';
import { PLATFORM } from 'aurelia-pal';

import { Emoji } from './emoji-value-converter';

export function configure(aurelia: FrameworkConfiguration) {
    aurelia.globalResources([
        PLATFORM.moduleName('./emoji-value-converter')
    ]);
}

export { Emoji };


text:
package scadla.assembly

import scadla._
import scadla.backends.Renderer

//final for pickling

//TODO immutable
final class Part(val name: String, val model: Solid, val printableModel: Option[Solid] = None) {

  var description: String = ""

  var vitamin = false

  //TODO should be protected but serialization ...
  var poly: Polyhedron = null
  var polyPrint: Polyhedron = null

  def preRender(r: Renderer): Unit = {
    if (poly == null) {
      poly = r(model)
      polyPrint = printableModel.map(r(_)).getOrElse(poly)
    }
  }

  def mesh = {
    if (poly != null) {
      poly
    } else {
      sys.error("Part not yet rendered.")
    }
  }

  def printable = {
    if (polyPrint != null) {
      polyPrint
    } else {
      sys.error("Part not yet rendered.")
    }
  }

  override def equals(any: Any) = {
    if (any.isInstanceOf[Part]) {
      val p = any.asInstanceOf[Part]
      name == p.name && model == p.model
    } else false
  }

}


text:
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements.  See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18331
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace LocationDotNetSample.Properties
{

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
    {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default
        {
            get
            {
                return defaultInstance;
            }
        }
    }
}


text:
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.valueobjects;

/**
 * This object is used to store information about the yearToEntityCount Map in the format
 * easily expressed to Google Visualization's DataTableAPI.
 * @author cdtank
 *
 */
public class YearToEntityCountDataElement {

	private int yearToEntityCounter;
	private String year;
	private int currentEntitiesCount;

	public YearToEntityCountDataElement(int yearToEntityCounter,
			String year, int currentEntitiesCount) {
		this.yearToEntityCounter = yearToEntityCounter;
		this.year = year;
		this.currentEntitiesCount = currentEntitiesCount;
	}

	public int getYearToEntityCounter() {
		return yearToEntityCounter;
	}

	public String getYear() {
		return year;
	}

	public int getCurrentEntitiesCount() {
		return currentEntitiesCount;
	}

}


text:
package org.apache.metron.common.configuration;

import com.google.common.collect.ImmutableList;
import org.apache.metron.common.field.validation.FieldValidation;
import org.apache.metron.common.field.validation.FieldValidations;
import org.json.simple.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FieldValidator implements Serializable {

  public enum Config {
     FIELD_VALIDATIONS("fieldValidations")
    ,VALIDATION("validation")
    ,INPUT("input")
    ,CONFIG("config")
    ;
    String key;
    Config(String key) {
      this.key = key;
    }
    public <T> T get(Map<String, Object> config, Class<T> clazz) {
      Object o = config.get(key);
      if(o == null) {
        return null;
      }
      return clazz.cast(o);
    }
  }
  private FieldValidation validation;
  private List<String> input;
  private Map<String, Object> config;

  public FieldValidator(Object o) {
    if(o instanceof Map) {
      Map<String, Object> validatorConfig = (Map<String, Object>) o;
      Object inputObj = Config.INPUT.get(validatorConfig, Object.class);
      if(inputObj instanceof String) {
        input = ImmutableList.of(inputObj.toString());
      }
      else if(inputObj instanceof List) {
        input = new ArrayList<>();
        for(Object inputO : (List<Object>)inputObj) {
          input.add(inputO.toString());
        }
      }
      config = Config.CONFIG.get(validatorConfig, Map.class);
      if(config == null) {
        config = new HashMap<>();
      }
      String validator = Config.VALIDATION.get(validatorConfig, String.class);
      if(validator == null) {
        throw new IllegalStateException("Validation not set.");
      }
      validation= FieldValidations.get(validator);
    }
    else {
      throw new IllegalStateException("Unable to configure field validations");
    }
  }

  public FieldValidation getValidation() {
    return validation;
  }

  public List<String> getInput() {
    return input;
  }

  public Map<String, Object> getConfig() {
    return config;
  }

  public boolean isValid(JSONObject inputData, Map<String, Object> globalConfig) {
    Map<String, Object> in = inputData;
    if(input != null && !input.isEmpty()) {
      in = new HashMap<>();
      for(String i : input) {
        Object o = inputData.get(i);
        in.put(i,o);
      }
    }
    return validation.isValid(in, config, globalConfig);
  }

  public static List<FieldValidator> readValidations(Map<String, Object> globalConfig) {
    List<FieldValidator> validators = new ArrayList<>();
    List<Object> validations = (List<Object>) Config.FIELD_VALIDATIONS.get(globalConfig, List.class);
    if(validations != null) {
      for (Object o : validations) {
        FieldValidator f = new FieldValidator(o);
        f.getValidation().initialize(f.getConfig(), globalConfig);
        validators.add(new FieldValidator(o));
      }
    }
    return validators;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    FieldValidator that = (FieldValidator) o;

    if (getValidation() != null ? !getValidation().equals(that.getValidation()) : that.getValidation() != null)
      return false;
    if (getInput() != null ? !getInput().equals(that.getInput()) : that.getInput() != null) return false;
    return getConfig() != null ? getConfig().equals(that.getConfig()) : that.getConfig() == null;

  }

  @Override
  public int hashCode() {
    int result = getValidation() != null ? getValidation().hashCode() : 0;
    result = 31 * result + (getInput() != null ? getInput().hashCode() : 0);
    result = 31 * result + (getConfig() != null ? getConfig().hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "FieldValidator{" +
            "validation=" + validation +
            ", input=" + input +
            ", config=" + config +
            '}';
  }

}


text:
/**
 * Build {@link org.apache.sis.feature.DefaultFeatureType}s by inspection of database schemas.
 * The work done here is similar to reverse engineering.
 *
 * Do not use!
 *
 * This package is for internal use by SIS only. Classes in this package
 * may change in incompatible ways in any future version without notice.
 *
 *
Implementation notes

 * Feature type analysis is done through {@link org.apache.sis.internal.sql.feature.Analyzer} class.
 *
 * @author  Johann Sorel (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @author  Alexis Manin (Geomatys)
 * @version 1.2
 * @since   1.0
 * @module
 */
package org.apache.sis.internal.sql.feature;


text:
// ----- this file has been automatically generated - do not edit
import { DataType, VariantOptions } from "node-opcua-variant"
import { LocalizedText } from "node-opcua-data-model"
import { UABaseEvent, UABaseEvent_Base } from "./ua_base_event"
import { UATransitionVariable } from "./ua_transition_variable"
import { UAStateVariable } from "./ua_state_variable"
/**
 * |                |                                                  |
 * |----------------|--------------------------------------------------|
 * |namespace       |http://opcfoundation.org/UA/                      |
 * |nodeClass       |ObjectType                                        |
 * |typedDefinition |TransitionEventType ns=0;i=2311                   |
 * |isAbstract      |true                                              |
 */
export interface UATransitionEvent_Base extends UABaseEvent_Base {
    transition: UATransitionVariable<LocalizedText>;
    fromState: UAStateVariable<LocalizedText>;
    toState: UAStateVariable<LocalizedText>;
}
export interface UATransitionEvent extends UABaseEvent, UATransitionEvent_Base {
}


text:
captcha break based on opencv2, tesseract-ocr and some machine learning algorithm.

## Types
### Basic[[cpp](./basic/cpp)][[python](./basic/python)]
![](./basic/basic.jpg)
The simplest captcha breaking.

### CSDN[[cpp](./csdn/cpp)][[python](./csdn/python)]
![](./csdn/csdn.png)
CAPTCHA from http://download.csdn.net/

### SubMail[[cpp](./submail/cpp)]
![](./submail/submail.png)
CAPTCHA from http://submail.cn/sms

### Weibo.cn[[cpp](./weibo.cn/cpp)][[python](./weibo.cn/python)]
![](./weibo.cn/weibo.cn.png)
CAPTCHA from http://login.weibo.cn/login/.
(Note: This website has changed now, and the captcha is not available!)

### JiKeXueYuan[[python](./jikexueyuan/python)]
![](./jikexueyuan/jikexueyuan.png)
CAPTCHA of http://passport.jikexueyuan.com/sso/verify

### Weibo.com[[python3](./weibo.com)]
![](./weibo.com/weibo.com.png)
CAPTCHA of [http://login.sina.com.cn/cgi/pin.php?r=8787878&s=0](http://login.sina.com.cn/cgi/pin.php?r=8787878&s=0)

## License
MIT


text:
define("dojox/form/nls/pt/PasswordValidator",{nomatchMessage:"As senhas n\u00e3o correspondem.",badPasswordMessage:"Senha Inv\u00e1lida."});
//# sourceMappingURL=PasswordValidator.js.map


text:
.class Landroid/widget/SearchView$9;
.super Ljava/lang/Object;
.source "SearchView.java"

# interfaces
.implements Landroid/widget/AdapterView$OnItemClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/SearchView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/SearchView;

# direct methods
.method constructor <init>(Landroid/widget/SearchView;)V
    .locals 0
    .parameter

    .prologue
    .line 1377
    iput-object p1, p0, Landroid/widget/SearchView$9;->this$0:Landroid/widget/SearchView;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onItemClick(Landroid/widget/AdapterView;Landroid/view/View;IJ)V
    .locals 3
    .parameter
    .parameter "view"
    .parameter "position"
    .parameter "id"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/widget/AdapterView",
            "<*>;",
            "Landroid/view/View;",
            "IJ)V"
        }
    .end annotation

    .prologue
    .line 1384
    .local p1, parent:Landroid/widget/AdapterView;,"Landroid/widget/AdapterView<*>;"
    iget-object v0, p0, Landroid/widget/SearchView$9;->this$0:Landroid/widget/SearchView;

    const/4 v1, 0x0

    const/4 v2, 0x0

    #calls: Landroid/widget/SearchView;->onItemClicked(IILjava/lang/String;)Z
    invoke-static {v0, p3, v1, v2}, Landroid/widget/SearchView;->access$1700(Landroid/widget/SearchView;IILjava/lang/String;)Z

    .line 1385
    return-void
.end method


text:
@implementation HKWTControlFlowDummyPlugin

@synthesize parentTextView;

+ (instancetype)dummyPluginWithName:(NSString *)name {
    HKWTControlFlowDummyPlugin *plugin = [self new];
    plugin.pluginName = name;
    return plugin;
}

- (void)performInitialSetup {
    if (self.registerBlock) {
        self.registerBlock();
    }
}

- (void)performFinalCleanup {
    if (self.unregisterBlock) {
        self.unregisterBlock();
    }
}

- (void)resetBlocks {
    self.registerBlock = nil;
    self.unregisterBlock = nil;

    self.shouldBeginEditingBlock = nil;
    self.didBeginEditingBlock = nil;
    self.shouldEndEditingBlock = nil;
    self.didEndEditingBlock = nil;
    self.shouldChangeTextInRangeBlock = nil;
    self.didChangeBlock = nil;
    self.didChangeSelectionBlock = nil;
    self.shouldInteractWithTextAttachmentBlock = nil;
    self.shouldInteractWithURLBlock = nil;
}

#pragma mark - Delegate

- (BOOL)textViewShouldBeginEditing:(__unused UITextView *)textView {
    if (self.shouldBeginEditingBlock) {
        self.shouldBeginEditingBlock();
    }
    return YES;
}

- (void)textViewDidBeginEditing:(__unused UITextView *)textView {
    if (self.didBeginEditingBlock) {
        self.didBeginEditingBlock();
    }
}

- (BOOL)textViewShouldEndEditing:(__unused UITextView *)textView {
    if (self.shouldEndEditingBlock) {
        self.shouldEndEditingBlock();
    }
    return YES;
}

- (void)textViewDidEndEditing:(__unused UITextView *)textView {
    if (self.didEndEditingBlock) {
        self.didEndEditingBlock();
    }
}

- (BOOL)textView:(__unused UITextView *)textView shouldChangeTextInRange:(__unused NSRange)range replacementText:(__unused NSString *)replacementText {
    if (self.shouldChangeTextInRangeBlock) {
        self.shouldChangeTextInRangeBlock();
    }
    return YES;
}

- (void)textViewDidChange:(__unused UITextView *)textView {
    if (self.didChangeBlock) {
        self.didChangeBlock();
    }
}

- (void)textViewDidChangeSelection:(__unused UITextView *)textView {
    if (self.didChangeSelectionBlock) {
        self.didChangeSelectionBlock();
    }
}

- (BOOL)textView:(__unused UITextView *)textView shouldInteractWithTextAttachment:(__unused NSTextAttachment *)textAttachment inRange:(__unused NSRange)characterRange interaction:(__unused UITextItemInteraction)interaction {
    if (self.shouldInteractWithTextAttachmentBlock) {
        self.shouldInteractWithTextAttachmentBlock();
    }
    return YES;
}

- (BOOL)textView:(__unused UITextView *)textView shouldInteractWithURL:(__unused NSURL *)URL inRange:(__unused NSRange)characterRange interaction:(__unused UITextItemInteraction)interaction {
    if (self.shouldInteractWithURLBlock) {
        self.shouldInteractWithURLBlock();
    }
    return YES;
}

@end


text:
import fileinput
import glob
import optparse
import os
import re
import subprocess
import sys

from bisect import bisect_left
from collections import defaultdict
from operator import itemgetter

_SYMBOLS_DIR_FORMAT = \
  '%s/Library/Developer/Xcode/iOS DeviceSupport/%s/Symbols*'
_XCODE_SYMBOLS_DIR_FORMAT = \
  '%s/Contents/Developer/Platforms/*.platform/DeviceSupport/%s/Symbols*'
_VIEWFINDER_DSYMS_PATH = \
  os.path.expanduser('~/Dropbox/viewfinder/dSYMS')
_VIEWFINDER_DSYMS_SUFFIX = \
  'Contents/Resources/DWARF/Viewfinder'
_VIEWFINDER_DSYMS_UUID_PATH = \
  os.path.expanduser('~/Dropbox/viewfinder/dSYMS.uuid')

kOSVersionRE = re.compile(r'\D*([0-9\.]+)(?:\s+\((?:Build )?(\w+)\))?')

kThreadTraceStartRE = re.compile(r'(?i)^thread \d+( crashed| name)?:.*$')

kBacktraceRE = re.compile(
    r'\s*(?P<frame_number>[0-9]+)\s+(?P<bundle_id>[-_a-zA-Z0-9\./]+)' +
    r'\s+(?P<address>0x[0-9A-Fa-f]+)\s+(?P<base>0x[0-9A-Fa-f]+)' )

kSymbolRE = re.compile(r'\s*\(in .*?\)\s*.*')
kHexadecimalNumRE = re.compile(r'0x[a-f0-9]+')

# uuid -> path (None indicating a path was not found)
uuid_cache = {}

class Symbolicator(object):
  def __init__(self):
    self.preamble_output = ''
    self.crashed_thread_backtrace_output = ''
    self.crashed_thread_title_output = ''
    self.backtrace_output = ''
    self.thread_state_output = ''
    self.binary_images_output = ''

  def FullOutput(self):
    return self.preamble_output + \
           self.crashed_thread_title_output + self.crashed_thread_backtrace_output + \
           self.backtrace_output + self.thread_state_output + self.binary_images_output

  def SummaryOutput(self):
    return self.preamble_output + \
           self.crashed_thread_title_output + self.crashed_thread_backtrace_output

  def OutputDict(self):
    return {'preamble': self.preamble_output,
            'crashed_thread_title': self.crashed_thread_title_output,
            'crashed_thread_backtrace': self.crashed_thread_backtrace_output,
            'backtrace': self.backtrace_output,
            'thread_state': self.thread_state_output,
            'binary_images': self.binary_images_output}

  @staticmethod
  def ReformatUuid(uuid):
    "Takes a plain-hex-number uuid, uppercases it, and inserts hyphens."
    uuid = uuid.upper()
    if len(uuid) == 36:
      # Already hyphenated.
      pass
    else:
      uuid = '-'.join([uuid[0:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:]])
    return uuid

  @staticmethod
  def FindSymbolsDirs(version, build):
    version_dirs = [ '%s (%s)' % (version, build), version, build ]
    library_dirs = [ "/System", "", os.path.expanduser("~") ]
    dirs = [ '' ]
    for l in library_dirs:
      for v in version_dirs:
        pat = _SYMBOLS_DIR_FORMAT % (l, v)
        dirs.extend(glob.glob(pat))

    mdfind = subprocess.Popen(
        ['mdfind', "kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode' || " +
         "kMDItemCFBundleIdentifier == 'com.apple.Xcode'"],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    for line in mdfind.stdout:
      d = line.strip()
      for v in version_dirs:
        pat = _XCODE_SYMBOLS_DIR_FORMAT % (d, v)
        dirs.extend(glob.glob(pat))

    return dirs

  @staticmethod
  def FindBinaryImageByAddress(address):
    global addresses
    global binary_images
    index = bisect_left(addresses, int(address, 0))
    if index:
      return binary_images[index - 1]
    return None

  @staticmethod
  def FindPathByUuid(path, uuid, arch):
    def ViewfinderPath(uuid):
      p = os.path.join(_VIEWFINDER_DSYMS_UUID_PATH, uuid)
      if not os.path.exists(p):
        return None
      p = open(p).read().strip();
      if not p:
        return None
      return os.path.join(_VIEWFINDER_DSYMS_PATH, p, _VIEWFINDER_DSYMS_SUFFIX)

    def DsymForUuid(path, uuid, arch):
      dwarfdump = subprocess.Popen(
          ['dwarfdump', '--arch=%s' % arch, '--uuid', path],
          stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      for line in dwarfdump.stdout:
        if uuid in line:
          return ' '.join(line.strip().split(' ')[3:])
      return None

    try:
      p = uuid_cache[uuid]
    except KeyError:
      p = ViewfinderPath(uuid)

      if not p:
        mdfind = subprocess.Popen(
            ['mdfind', 'com_apple_xcode_dsym_uuids = ' + uuid],
            stdout=subprocess.PIPE)

        try:
          p = iter(mdfind.stdout).next()[:-1] # Strip \n
          if p.endswith(".xcarchive"):
            dsym_folder = os.path.join(p, "dSYMs")
            dsyms = glob.glob(os.path.join(p, "dSYMs/*.dSYM"))
            # I only know how to handle the case for one dsym. I'm sure there's a
            # way to figure out which we want for multiple-dsym xcarchives (if such
            # a thing exists?).
            if len(dsyms) == 1:
              p = os.path.join(p, "dSYMs", dsyms[0])
            else:
              p = None
        except StopIteration:
          p = None

        mdfind.wait()

      if p:
        # Translate the path to the dsym directory to the correct dsym file.
        p = DsymForUuid(p, uuid, arch)
      else:
        # Unable to find a dsym file, search through the symbol dirs looking for
        # an appropriately named library containing the desired uuid.
        global symbol_dirs
        for d in symbol_dirs:
          p = '%s/%s' % (d, path)
          if os.path.exists(p):
            p = DsymForUuid(p, uuid, arch)
            if p:
              break
          p = None

      uuid_cache[uuid] = p

    return p

  @staticmethod
  def LookupSymbols(path, arch, base, addresses):
    """using atos looks up symbols"""
    atos = subprocess.Popen(
        ['xcrun', 'atos', '-arch', arch, '-l', base, '-o', path ] + addresses,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    symbols = []
    for line in atos.stdout:
      symbols.append(kSymbolRE.sub('', line.strip()))
    return symbols

  def SymbolicateBacktraceLines(self, lines):
    # Invoking atos is expensive, so we minimize the calls by batching all of the
    # lookups for addresses associated with a particular path.
    path_to_addrs = defaultdict(dict)
    path_to_base = {}
    path_to_corrected_base = {}
    path_to_arch = {}

    for line in lines:
      match = kBacktraceRE.match(line)
      if not match:
        continue

      addr = match.group('address')
      base = match.group('base')

      image = Symbolicator.FindBinaryImageByAddress(addr)
      if not image:
        continue

      path = Symbolicator.FindPathByUuid(image[3], image[2], image[4])
      if not path:
        continue

      path_to_arch[path] = image[4]
      path_to_base[path] = base
      path_to_addrs[path][addr] = int(addr, 16) - int(image[0])

    addr_to_symbol = {}
    for (path, addrs) in path_to_addrs.items():
      corrected_addresses = addrs.values()
      addrs = addrs.keys()

      symbols = Symbolicator.LookupSymbols(
          path, path_to_arch[path], path_to_base[path], addrs)
      for i in xrange(0, len(addrs)):
        addr_to_symbol[addrs[i]] = (symbols[i], corrected_addresses[i])

    is_crashed_thread = False
    for line in lines:
      def _AppendLine(to_append):
        if is_crashed_thread:
          self.crashed_thread_backtrace_output += to_append
        else:
          self.backtrace_output += to_append

      stripped_line = line.strip()
      if kThreadTraceStartRE.match(stripped_line):
        is_crashed_thread = stripped_line.endswith('Crashed:')
        if is_crashed_thread:
          self.crashed_thread_title_output = line
          continue

      match = kBacktraceRE.match(line)
      if not match:
        _AppendLine(line)
        continue
      addr = match.group('address')
      symbol, corrected_address = addr_to_symbol.get(addr, ('unknown', 0))
      if kHexadecimalNumRE.match(symbol):
        # Replace address-only symbols by 'unknown'
        symbol = 'unknown'
      # To display addresses (corrected for random memory layout, display corrected_address.
      _AppendLine('%-30s %s\n' % (line[0:match.end('bundle_id')], symbol))

  @staticmethod
  def ParseOSVersion(line):
    match = kOSVersionRE.match(line)
    if not match:
      return None
    return (match.group(1), match.group(2))

  @staticmethod
  def ParseBinaryImageLine(line):
    elements = iter(line.split())
    start_address = elements.next()
    elements.next() # Hyphen
    end_address = elements.next()
    # The main(?) executable has plus sign before its bundle ID. Strip this off.
    bundle_id = elements.next().strip('+')
    arch = elements.next()
    uuid = Symbolicator.ReformatUuid(elements.next().strip('<>'))

    try:
      path = elements.next()
      try:
        while True:
          path += ' ' + elements.next()
      except StopIteration:
        pass
    except StopIteration:
      return (None, None, None)

    return (start_address, end_address, arch, bundle_id, uuid, path)

  def process_one_file(self, content_lines):
    global addresses
    global binary_images
    binary_images = []

    work = False
    is_in_backtrace = False
    is_in_thread_state = False
    is_in_binary_images = False
    backtrace_lines = []
    thread_state_lines = []
    binary_image_lines = []

    #assert False
    def flush_buffers():
      global binary_images
      global addresses
      binary_images = sorted(binary_images, key=itemgetter(0))
      addresses = [b[0] for b in binary_images]

      global symbol_dirs
      symbol_dirs = Symbolicator.FindSymbolsDirs(os_version, os_build)

      self.SymbolicateBacktraceLines(backtrace_lines)
      for line in thread_state_lines:
        self.thread_state_output += line
      for line in binary_image_lines:
        self.binary_images_output += line

      binary_images = []

    for line in content_lines:
      line_stripped = line.strip()
      if (line_stripped.startswith('Incident Identifier:') or
          line_stripped.startswith('Process:')):
        if is_in_binary_images:
          # End previous crash
          flush_buffers()
          is_in_binary_images = False

        # New crash
        work = True
        is_in_backtrace = is_in_thread_state = is_in_binary_images = False
        self.preamble_output += line
      elif not work:
        continue
      elif line_stripped.startswith('OS Version:'):
        os_version, os_build = Symbolicator.ParseOSVersion(line_stripped)
        self.preamble_output += line
      elif kThreadTraceStartRE.match(line_stripped):
        is_in_backtrace = True
        backtrace_lines.append(line)
      elif is_in_backtrace and ('Thread State' in line_stripped):
        is_in_backtrace = False
        is_in_thread_state = True
        thread_state_lines.append(line)
      elif line_stripped == 'Binary Images:':
        is_in_thread_state = False
        is_in_backtrace = False
        is_in_binary_images = True
        binary_image_lines.append(line)
      elif is_in_thread_state:
        thread_state_lines.append(line)
      elif is_in_backtrace:
        backtrace_lines.append(line)
      elif not is_in_binary_images:
        # We haven't gotten to backtrace or binary images yet. Pass this line
        # through.
        self.preamble_output += line
      elif is_in_binary_images:
        if line_stripped:
          binary_image_lines.append(line)
          start_address, end_address, arch, bundle_id, uuid, path = \
              Symbolicator.ParseBinaryImageLine(line_stripped)
          if bundle_id:
            binary_images.append((
                int(start_address, 0),
                int(end_address, 0),
                uuid, path, arch ))
        else:
          # End of crash
          flush_buffers()
          is_in_binary_images = False

    if is_in_binary_images:
      # Crash not followed by a newline
      flush_buffers()

def main(argv):
  parser = optparse.OptionParser(
    usage="%prog [options] [files]",
    description=\
"""Reads one or more crash logs from named files or standard input,
symbolicates them, and writes them to standard output.""",
    version='%prog 1.0.2 by Peter Hosey',
  )
  opts, args = parser.parse_args(argv[1:])
  for f in args:
    contents = open(f, 'r').readlines()
    sym = Symbolicator()
    sym.process_one_file(contents)
    sys.stdout.write(sym.FullOutput())

if __name__ == '__main__':
  main(sys.argv)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Platform.AppCompat" parent="@android:style/Theme.DeviceDefault">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
    </style>
    <style name="Platform.AppCompat.Light" parent="@android:style/Theme.DeviceDefault">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:colorBackground">#b0555555</item>
        <item name="android:backgroundTint">#a0555555</item>
        <item name="android:statusBarColor">#ff555555</item>
    </style>
    <style name="Platform.AppCompat.Light.Dialog" parent="@android:style/Theme.Material.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
    </style>
    <style name="Base.ThemeOverlay.AppCompat.Light" parent="@android:style/ThemeOverlay.Material.Dark" />
</resources>


text:
/**
 * Created by dionp on 01.05.2017.
 */
export class Bookmark {

  choiceId: number;
  contentId: number;
  constructor(choiceId: number,
              contentId: number) {
    this.choiceId = choiceId;
    this.contentId = contentId;
  }
}


text:
Image classification using the ResNet50 model described in
[Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385).

Contents:

- `resnet50.py`: Model definition
- `resnet50_test.py`: Sanity unittests and benchmarks for using the model with
  eager execution enabled.
- `resnet50_graph_test.py`: Sanity unittests and benchmarks when using the same
  model code to construct a TensorFlow graph.

# Benchmarks

Using a synthetic data, run:

```
# Using eager execution
python resnet50_test.py --benchmarks=.

# Using graph execution
python resnet50_graph_test.py --benchmarks=.
```

The above uses the model definition included with the TensorFlow pip
package. To build (and run benchmarks) from source:

```
# Using eager execution
bazel run -c opt --config=cuda :resnet50_test -- --benchmarks=.

# Using graph execution
bazel run -c opt --config=cuda :resnet50_graph_test -- --benchmarks=.
```

(Or remove the `--config=cuda` flag for running on CPU instead of GPU).

On October 31, 2017, the benchmarks demonstrated comparable performance
for eager and graph execution of this particular model when using
a single NVIDIA Titan X (Pascal) GPU on a host with an
Intel Xeon E5-1650 CPU @ 3.50GHz and a batch size of 32.

| Benchmark name                           | batch size    | images/second |
| ---------------------------------------  | ------------- | ------------- |
| eager_train_gpu_batch_32_channels_first  |            32 |           171 |
| graph_train_gpu_batch_32_channels_first  |            32 |           172 |


text:
module Main (main) where
fac n = if n < 2 then 1 else n * fac (n - 1)
main = print (fac 6)


text:
import {useTextTracks} from 'frontend/useTextTracks';
import {useFile} from 'entryState';
import {settings} from 'pageflow/frontend';

import {renderHookInEntry} from 'support';
import {useFakeTranslations} from 'pageflow/testHelpers';
import {act} from '@testing-library/react';

describe('useTextTracks', () => {
  const videoFile1Id = 2004;
  const videoFile1PermaId = 2400;
  const videoFile1SubtitlesEnId = 3001;
  const videoFile1SubtitlesEnPermaId = 3100;
  const videoFile1CaptionsDeId = 3002;
  const videoFile1CaptionsDePermaId = 3200;

  const videoFile2Id = 2005;
  const videoFile2PermaId = 2500;
  const videoFile2CaptionsDeId = 4001;
  const videoFile2CaptionsDePermaId = 4100;

  const seed = {
    videoFiles: [
      {id: videoFile1Id, permaId: videoFile1PermaId},
      {id: videoFile2Id, permaId: videoFile2PermaId}
    ],
    textTrackFiles: [
      {
        id: videoFile1SubtitlesEnId,
        permaId: videoFile1SubtitlesEnPermaId,
        parentFileId: videoFile1Id,
        parentFileModelType: 'Pageflow::VideoFile',
        configuration: {
          kind: 'subtitles',
          srclang: 'en'
        }
      },
      {
        id: videoFile1CaptionsDeId,
        permaId: videoFile1CaptionsDePermaId,
        parentFileId: videoFile1Id,
        parentFileModelType: 'Pageflow::VideoFile',
        configuration: {
          kind: 'captions',
          srclang: 'de'
        }
      },
      {
        id: videoFile2CaptionsDeId,
        permaId: videoFile2CaptionsDePermaId,
        parentFileId: videoFile2Id,
        parentFileModelType: 'Pageflow::VideoFile',
        configuration: {
          kind: 'captions',
          srclang: 'de',
          label: 'German'
        }
      }
    ]
  };

  useFakeTranslations({
    'pageflow_scrolled.public.languages.en': 'English',
    'pageflow_scrolled.public.languages.unknown': 'Unknown',
    'pageflow_scrolled.public.text_track_modes.auto': 'Auto (%{label})',
    'pageflow_scrolled.public.text_track_modes.auto_off': 'Auto (Off)'
  });

  beforeEach(() => settings.set('textTrack', null));

  it('returns text tracks of given file', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId})
    }), {seed});

    expect(result.current.files).toMatchObject([
      {
        id: videoFile1SubtitlesEnId,
        displayLabel: 'English'
      },
      {
        id: videoFile1CaptionsDeId,
        displayLabel: 'Unknown'
      }
    ]);
  });

  it('uses custom display label', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile2PermaId})
    }), {seed});

    expect(result.current.files).toMatchObject([
      {
        id: videoFile2CaptionsDeId,
        displayLabel: 'German'
      }
    ]);
  });

  it('sets activeFileId to id of text track matching current settings', () => {
    settings.set('textTrack', {kind: 'captions', srclang: 'de'});

    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId})
    }), {seed});

    expect(result.current).toMatchObject({
      activeFileId: videoFile1CaptionsDeId,
      mode: 'user',
      autoDisplayLabel: 'Auto (Off)'
    });
  });

  it('sets activeFileId to null if kind in settings is "off"', () => {
    settings.set('textTrack', {kind: 'off'});

    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId})
    }), {seed});

    expect(result.current).toMatchObject({
      activeFileId: null,
      mode: 'off',
      autoDisplayLabel: 'Auto (Off)'
    });
  });

  it('sets activeFileId to null if non matches setting', () => {
    settings.set('textTrack', {kind: 'subtitle', srclang: 'en'});

    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile2PermaId})
    }), {seed});

    expect(result.current.activeFileId).toBeNull();
  });

  it('sets activeFileId to given default if non matches setting', () => {
    settings.set('textTrack', {kind: 'subtitle', srclang: 'en'});

    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile2PermaId}),
      defaultTextTrackFilePermaId: videoFile2CaptionsDePermaId
    }), {seed});

    expect(result.current).toMatchObject({
      activeFileId: videoFile2CaptionsDeId,
      mode: 'user',
      autoDisplayLabel: 'Auto (German)'
    });
  });

  it('sets activeFileId to first captions if captions enabled by default', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId}),
      captionsByDefault: true
    }), {seed});

    expect(result.current).toMatchObject({
      activeFileId: videoFile1CaptionsDeId,
      mode: 'auto',
      autoDisplayLabel: 'Auto (Unknown)'
    });
  });

  it('sets activeFileId to subtitles matching entry locale by default', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId}),
      captionsByDefault: true
    }), {
      seed: {
        entry: {locale: 'en'},
        ...seed
      }
    });

    expect(result.current).toMatchObject({
      activeFileId: videoFile1SubtitlesEnId,
      mode: 'auto',
      autoDisplayLabel: 'Auto (English)'
    });
  });

  it('provides select function which update settings', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId})
    }), {seed});

    const {select} = result.current;
    act(() => select(videoFile1CaptionsDeId));

    expect(settings.get('textTrack')).toMatchObject({
      kind: 'captions',
      srclang: 'de'
    });
  });

  it('provides select function which allows turning text tracks off', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId})
    }), {seed});

    const {select} = result.current;
    act(() => select('off'));

    expect(settings.get('textTrack')).toMatchObject({
      kind: 'off'
    });
  });

  it('provides select function which allows returning to auto mode', () => {
    const {result} = renderHookInEntry(() => useTextTracks({
      file: useFile({collectionName: 'videoFiles', permaId: videoFile1PermaId})
    }), {seed});

    const {select} = result.current;
    act(() => select('auto'));

    expect(settings.get('textTrack')).toMatchObject({});
  });
});


text:
from waterbutler.server.api.v1 import provider
PREFIX = 'v1'

HANDLERS = [
    provider.ProviderHandler.as_entry()
]


text:
installation:

    $ curl -L https://raw.github.com/lyondhill/voltometer/master/install | sh
    $ curl -L https://raw.github.com/lyondhill/voltometer/master/setup | sh


text:
package sorting

import org.salgo.sorting.{GeneralFunctionalSortingAlgorithm, SelectionSort}

class SelectionSortSpec extends GenericFunctionalSortSpec {
  override def getSortingAlgorithm: GeneralFunctionalSortingAlgorithm = SelectionSort
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" version="3.1">
    <enterprise-beans>
        <session>
            <ejb-name>MainAppBean</ejb-name>
      <!-- add a application local reference, the reference points to a server configuration specific -->
            <ejb-ref>
                <ejb-ref-name>AppTwoAlias</ejb-ref-name>
                <lookup-name>java:global/AliasAppTwo</lookup-name>
            </ejb-ref>
        </session>
    </enterprise-beans>
</ejb-jar>


text:
package fpt.qa.intent.detection.qc;

import java.util.List;
import java.util.Map;

public class Observation {

    public String originalData = "";
    public int[] cps = null;
    public int humanLabel = -1;
    public int modelLabel = -1;

    public Observation() {
	// do nothing
    }

    public Observation(int[] cps) {
	this.cps = new int[cps.length];
        System.arraycopy(cps, 0, this.cps, 0, cps.length);
    }

    public Observation(List intCps) {
	this.cps = new int[intCps.size()];

	for (int i = 0; i < intCps.size(); i++) {
	    Integer intCp = (Integer)intCps.get(i);

	    this.cps[i] = intCp.intValue();
	}
    }

    public Observation(int humanLabel, int[] cps) {
	this.humanLabel = humanLabel;
	this.cps = new int[cps.length];
        System.arraycopy(cps, 0, this.cps, 0, cps.length);
    }

    public String toString(Map lbInt2Str) {
	String res = originalData;

	String modelLabelStr = (String)lbInt2Str.get(new Integer(modelLabel));
	if (modelLabelStr != null) {
	    res += Option.labelSeparator + modelLabelStr;
	}

	return res;
    }

} // end of class Observation


text:
Visit http://ember.js.uy/ to view the Ember Montevideo Meetup website.

You can visit https://github.com/jubar/ember-montevideo-app to contribute to this web application.


text:
"""

    Convert DICOM Data into a Python Dictionary
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
# Also see: https://github.com/darcymason/pydicom/issues/319.
import os
from biovida.support_tools.support_tools import cln, dicom

def _extract_numeric(value):
    """

    :param value:
    :return:
    """
    return float("".join((i for i in value if i.isdigit() or i == '.')))

def parse_age(value):
    """

    :param value:
    :return:
    """
    if not isinstance(value, str):
        raise TypeError('`value` must be a string.')
    elif len(value) > 4:
        return value

    if 'y' in value.lower():
        return _extract_numeric(value)
    elif 'm' in value.lower():
        return _extract_numeric(value) / 12.0
    else:
        return value

def parse_string_to_tuple(value):
    """

    :param value:
    :type value: ``str``
    :return:
    """
    braces = [['[', ']'], ['(', ')']]
    for (left, right) in braces:
        if left in value and right in value:
            value_split = value.replace(left, "").replace(right, "").split(",")
            value_split_cln = list(filter(None, map(cln, value_split)))
            if len(value_split_cln) == 0:
                return None
            try:
                to_return = tuple(map(_extract_numeric, value_split_cln))
            except:
                to_return = tuple(value_split_cln)
            return to_return[0] if len(to_return) == 1 else to_return
    else:
        raise ValueError("Cannot convert `value` to a tuple.")

def dicom_value_parse(key, value):
    """

    Try to convert ``value`` to a numeric or tuple of numerics.

    :param key:
    :param value:
    :return:
    """
    value = cln(str(value).replace("\'", "").replace("\"", ""))

    if not len(value) or value.lower() == 'none':
        return None

    if key.lower().endswith(' age') or key == 'PatientAge':
        try:
            return parse_age(value)
        except:
            return value
    else:
        try:
            return int(value)
        except:
            try:
                return float(value)
            except:
                try:
                    return parse_string_to_tuple(value)
                except:
                    return value

def dicom_object_dict_gen(dicom_object):
    """

    :param dicom_object:
    :type dicom_object: ``dicom.FileDataset``
    :return:
    """
    d = dict()
    for k in dicom_object.__dir__():
        if not k.startswith("__") and k != 'PixelData':
            try:
                value = dicom_object.data_element(k).value
                if type(value).__name__ != 'Sequence':
                    d[k] = dicom_value_parse(key=k, value=value)
            except:
                pass
    return d

def dicom_to_dict(dicom_file):
    """

    Convert the metadata associated with ``dicom_file`` into a python dictionary

    :param dicom_file: a path to a dicom file or the yield of ``dicom.read_file(FILE_PATH)``.
    :type dicom_file: ``FileDataset`` or ``str``
    :return: a dictionary with the dicom meta data.
    :rtype: ``dict``
    """
    if isinstance(dicom_file, str):
        if not os.path.isfile(dicom_file):
            raise FileNotFoundError("Could not locate '{0}'.".format(dicom_file))
        dicom_object = dicom.read_file(dicom_file)
    elif type(dicom_file).__name__ == 'FileDataset':
        dicom_object = dicom_file
    else:
        raise TypeError("`dicom_file` must be of type `dicom.FileDataset` or a string.")

    return dicom_object_dict_gen(dicom_object)


text:
<?php
/**
 * Created by PhpStorm.
 * User: Kurraz
 */

namespace app\modules\game\models\game_data;

use app\modules\game\models\game_data\base\BaseGameData;

class Debt extends BaseGameData
{
    public $sum;
    public $payDay;

    public function serialize()
    {
        return [
            'sum' => $this->sum,
            'payDay' => $this->payDay,
        ];
    }

    public function unserialize($serialized_data)
    {
        if(empty($serialized_data['sum']))
        {
            $this->sum = 0;
        }else
            $this->sum = $serialized_data['sum'];

        if(empty($serialized_data['payDay']))
        {
            $this->payDay = 0;
        }else
            $this->payDay = $serialized_data['payDay'];
    }

    public function isExist()
    {
        return $this->sum > 0;
    }

    public function daysLeft($current_day)
    {
        return $this->payDay - $current_day;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="PitOfDespair.PitOfDespair">
	<uses-sdk />
	<application android:label="PitOfDespair"></application>
</manifest>


text:
/* eslint no-unused-vars: 0 */
import 'datatables.net';
import dt from 'datatables.net-bs';
import d3 from 'd3';

import '../stylesheets/welcome.css';
import { appSetup } from './common';

appSetup();
require('datatables-bootstrap3-plugin/media/css/datatables-bootstrap3.css');

dt(window, $);

function modelViewTable(selector, modelView, orderCol, order) {
  // Builds a dataTable from a flask appbuilder api endpoint
  let url = '/' + modelView.toLowerCase() + '/api/read';
  url += '?_oc_' + modelView + '=' + orderCol;
  url += '&_od_' + modelView + '=' + order;
  $.getJSON(url, function (data) {
    const columns = ['dashboard_link', 'creator', 'modified'];
    const tableData = $.map(data.result, function (el) {
      const row = $.map(columns, function (col) {
        return el[col];
      });
      return [row];
    });
    const cols = $.map(columns, function (col) {
      return { sTitle: data.label_columns[col] };
    });
    const panel = $(selector).parents('.panel');
    panel.find('img.loading').remove();
    $(selector).DataTable({
      aaData: tableData,
      aoColumns: cols,
      bPaginate: true,
      pageLength: 10,
      bLengthChange: false,
      aaSorting: [],
      searching: true,
      bInfo: false,
    });
    // Hack to move the searchbox in the right spot
    const search = panel.find('.dataTables_filter input');
    search.addClass('form-control').detach();
    search.appendTo(panel.find('.search'));
    panel.find('.dataTables_filter').remove();
    // Hack to display the page navigator properly
    panel.find('.col-sm-5').remove();
    const nav = panel.find('.col-sm-7');
    nav.removeClass('col-sm-7');
    nav.addClass('col-sm-12');
    $(selector).slideDown();
    $('[data-toggle="tooltip"]').tooltip({ container: 'body' });
  });
}
$(document).ready(function () {
  //modelViewTable('#dash_table', 'DashboardModelViewAsync', 'changed_on', 'desc');
});


text:
'use strict';

const util = require('util');
const async = require('async');
const Pool = require('./pool');

/**
 * Пул, осуществляющий обращение к первому доступному хосту.
 *
 * @param {array} hosts Массив хостов или URL
 * @param {object} params Дополнительные параметры
 * @param {number} [params.timeout=10000] Максимальный таймаут запроса
 * @param {object} [params.headers={}] Дополнительные заголовки, добавляемые к каждому запросу
 * @extends Pool
 * @constructor
 */
function FirstAvailableHost(hosts, params) {
    FirstAvailableHost.super_.apply(this, arguments);
}
util.inherits(FirstAvailableHost, Pool);

/**
 * Метод выполняет запрос к первому доступному хосту из списка.
 *
 * @param {string} method Метод запроса
 * @param {string} path Путь запроса
 * @param {object} params Параметры запроса
 * @param {string} [dataType] Тип передаваемых данных: json или application/x-www-form-urlencoded
 * @returns {Promise<string>}
 */
FirstAvailableHost.prototype.request = function (method, path, params, dataType) {
    let lastError = null;
    let lastResponse = null;

    return new Promise((resolve, reject) => {
        async.someSeries(this.hosts, (host, callback) => {
            let r = this.prepareRequest(method, host, path, params, dataType);
            let req = r['protocol'].request(r.request, (response) => {
                let message = '';
                response.on('data', chunk => message += chunk);
                response.on('end', () => {
                    if (response.statusCode >= 400) {
                        lastError = new Error(`${response.statusCode}: ${response.statusMessage}`);
                        callback(false);
                    } else {
                        lastResponse = message;
                        callback(true);
                    }
                });
            });

            req.on('error', (err) => {
                lastError = err;
                callback(false);
            });
            req.on('socket', (socket) => {
                socket.setTimeout(this.params.timeout);
                socket.on('timeout', () => {
                    req.abort();
                });
            });
            if (r['data']) req.write(r['data']);
            req.end();
        }, result => result ? resolve(lastResponse) : reject(lastError));
    });
};

/**
 * Выполняет GET запрос.
 *
 * @param {string} path Путь запроса
 * @param {object} params Параметры запроса
 * @returns {Promise<string>}
 */
FirstAvailableHost.prototype.get = function (path, params) {
    return this.request('GET', path, params);
};

/**
 * Выполняет POST запрос.
 *
 * @param {string} path Путь запроса
 * @param {object} params Параметры запроса
 * @returns {Promise<string>}
 */
FirstAvailableHost.prototype.post = function (path, params) {
    return this.request('POST', path, params);
};

/**
 * Выполняет POST запрос с отправкой JSON объекта.
 *
 * @param {string} path Путь запроса
 * @param {object} data Объект для отправки в виде JSON
 * @returns {Promise<string>}
 */
FirstAvailableHost.prototype.postJson = function (path, data) {
    return this.request('POST', path, data, 'json');
};

module.exports = FirstAvailableHost;