text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>coverc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>coverc</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <jsp-config>
        <taglib>
            <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
            <taglib-location>/WEB-INF/tld/c.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>http://java.sun.com/jsp/jstl/fmt</taglib-uri>
            <taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
        </taglib>
    </jsp-config>

</web-app>


text:
import RingChart from './RingChart';
export default RingChart;

redpajama_set_name: RedPajamaGithub


text:
GEOMultiLineRasterSymbol::GEOMultiLineRasterSymbol(const std::vector<std::vector<Geodetic2D*>*>* coordinatesArray,
                                                   const GEO2DLineRasterStyle& style,
                                                   const int minTileLevel,
                                                   const int maxTileLevel) :
GEORasterSymbol( calculateSectorFromCoordinatesArray(coordinatesArray), minTileLevel, maxTileLevel ),
_coordinatesArray( copyCoordinatesArray(coordinatesArray) ),
_style(style)
{
}

GEOMultiLineRasterSymbol::~GEOMultiLineRasterSymbol() {
  if (_coordinatesArray != NULL) {
    const int coordinatesArrayCount = _coordinatesArray->size();
    for (int i = 0; i < coordinatesArrayCount; i++) {
      std::vector<Geodetic2D*>* coordinates = _coordinatesArray->at(i);
      const int coordinatesCount = coordinates->size();
      for (int j = 0; j < coordinatesCount; j++) {
        const Geodetic2D* coordinate = coordinates->at(j);
        delete coordinate;
      }
      delete coordinates;
    }
    delete _coordinatesArray;
  }

#ifdef JAVA_CODE
  super.dispose();
#endif

}

void GEOMultiLineRasterSymbol::rawRasterize(ICanvas*                   canvas,
                                            const GEORasterProjection* projection) const {
  if (_style.apply(canvas)) {
    const int coordinatesArrayCount = _coordinatesArray->size();
    for (int i = 0; i < coordinatesArrayCount; i++) {
      std::vector<Geodetic2D*>* coordinates = _coordinatesArray->at(i);
      rasterLine(coordinates,
                 canvas,
                 projection);
    }
  }
}


text:
from bt import backend_to_check, prog_check

from pyscreenshot.util import use_x_display

if use_x_display():
    if prog_check(["scrot", "-version"]):

        def test_scrot():
            backend_to_check("scrot")


text:
#ifndef OPENALPR_DETECTOROPENCL_H
#define	OPENALPR_DETECTOROPENCL_H

#include <stdio.h>
#include <iostream>
#include <vector>

#if OPENCV_MAJOR_VERSION == 3

#include BOSS_OPENCV_U_opencv2__objdetect__objdetect_hpp //original-code:"opencv2/objdetect/objdetect.hpp"
#include BOSS_OPENCV_U_opencv2__imgproc__imgproc_hpp //original-code:"opencv2/imgproc/imgproc.hpp"
#include BOSS_OPENCV_U_opencv2__core__core_hpp //original-code:"opencv2/core/core.hpp"
#include BOSS_OPENCV_U_opencv2__ml__ml_hpp //original-code:"opencv2/ml/ml.hpp"
#include BOSS_OPENCV_U_opencv2__core__ocl_hpp //original-code:"opencv2/core/ocl.hpp"

#include "detector.h"

namespace alpr
{

  class DetectorOCL : public Detector {
  public:
    DetectorOCL(Config* config, PreWarp* prewarp);
    virtual ~DetectorOCL();

    std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);

  private:

    cv::CascadeClassifier plate_cascade;

  };

}

#endif

#endif	/* OPENALPR_DETECTOROPENCL_H */


text:
'use strict';

var ReactDOMFeatureFlags = {
  useCreateElement: false,
};

module.exports = ReactDOMFeatureFlags;


text:
package org.securegraph.accumulo.blueprints.io.graphson;

import org.securegraph.accumulo.blueprints.util.AccumuloBlueprintsGraphTestHelper;
import org.securegraph.blueprints.io.graphson.SecureGraphBlueprintsGraphSONReaderTestBase;

public class AccumuloGraphSONReaderTest extends SecureGraphBlueprintsGraphSONReaderTestBase {
    public AccumuloGraphSONReaderTest() {
        super(new AccumuloBlueprintsGraphTestHelper());
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        ((AccumuloBlueprintsGraphTestHelper) this.graphTest).setUp();
    }
}


text:
struct callout {
	struct	callout *c_next;		/* next callout in queue */
	void	*c_arg;				/* function argument */
	void	(*c_func) __P((void *));	/* function to call */
	int	c_time;				/* ticks to the event */
};

#ifdef KERNEL
struct	callout *callfree, *callout, calltodo;
int	ncallout;
#endif


text:
///////////////////////////////////////////////////////////////////////////////
// AUTHOR:       Henry Pinkard, henry.pinkard@gmail.com
//
// COPYRIGHT:    University of California, San Francisco, 2015
//
// LICENSE:      This file is distributed under the BSD license.
//               License text is included with the source distribution.
//
//               This file is distributed in the hope that it will be useful,
//               but WITHOUT ANY WARRANTY; without even the implied warranty
//               of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//               IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//               CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//               INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//

package org.micromanager.plugins.magellan.autofocus;

import org.micromanager.plugins.magellan.acq.FixedAreaAcquisition;
import org.micromanager.plugins.magellan.acq.MultiResMultipageTiffStorage;
import ij.ImagePlus;
import ij.ImageStack;
import ij3d.image3d.FHTImage3D;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.micromanager.plugins.magellan.main.Magellan;
import org.micromanager.plugins.magellan.misc.Log;
import org.apache.commons.math.ArgumentOutsideDomainException;
import org.apache.commons.math.analysis.interpolation.SplineInterpolator;
import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction;

/**
 *
 * @author Henry
 */
public class CrossCorrelationAutofocus {

   //number of interppolated points per z step
   private static final double SPLINE_PRECISION = 10;
   //5e6--13 s
   //1e7--37 s
   //4e7--92 s
   //1e8--92 s
   //8e8--682 s
   private static final int NUM_VOXEL_TARGET = 20000000; //this target shuld take 1-2 min to calculate, while maintaining images of a resonable size
   private static final int AF_TIMEOUT_MIN = 30;

   private final int channelIndex_;
   private final double maxDisplacement_;
   private double initialPosition_;
   private double previousPosition_;
   private double currentPosition_;
   private FixedAreaAcquisition acq_;
   private int downsampleIndex_;
   private int downsampledWidth_;
   private int downsampledHeight_;
   private ExecutorService afExecutor_;

   public CrossCorrelationAutofocus(final FixedAreaAcquisition acq, int channelIndex, double maxDisplacement , double initialPosition) {
      afExecutor_ = Executors.newSingleThreadExecutor(new ThreadFactory() {
          @Override
          public Thread newThread(Runnable r) {
              return new Thread(r, acq.getName() + " Autofocusexecutor");
          }
      });
       channelIndex_ = channelIndex;
      maxDisplacement_ = maxDisplacement;
      acq_ = acq;
      initialPosition_ = initialPosition;
   }

//   public static void debug() {
//      ImagePlus tp0 = new ImagePlus("C:/Users/Henry/Desktop/tp0.tif");
//      ImagePlus tpc = new ImagePlus("C:/Users/Henry/Desktop/tp4.tif");
//      ImageStack stack1 = createAFStackFromDisk(tp0);
//      ImageStack stack2 = createAFStackFromDisk(tpc);
//      double drift = calcFocusDrift("test", stack1, stack2, 4.5);
//      System.out.println(drift);
//   }
//
//   //for debug
//   private static ImageStack createAFStackFromDisk(ImagePlus ip) {
//      //pad by half of stack size in either direction so wrap around of xCorr doesnt give false values
//      ImageStack stack = new ImageStack(ip.getWidth(), ip.getHeight());
//      int numSlices = (ip.getNSlices());
//      int frontPadding = 0;
//      //get background pixel value
//      int backgroundVal = 9;
//      for (int slice = 0; slice < numSlices; slice++) {
//         int dataSlice = slice - frontPadding;
//         //add as int
//         byte[] pix = (byte[]) ip.getStack().getPixels(dataSlice + 1);
//         float[] pix32 = new float[pix.length];
//         for (int i = 0; i < pix.length; i++) {
//            pix32[i] = pix[i] == 0 ? backgroundVal : pix[i] & 0xff;
//         }
//         stack.addSlice(null, pix32);
//      }
//      return stack;
//   }

   public double getAutofocusPosition() {
      return currentPosition_;
   }

   public void close() {
       afExecutor_.shutdownNow();
   }

   /**
    * Called by acquisitions at then end of time point
    * @param timeIndex
     */
    public void run(int timeIndex) throws Exception {
        Log.log("________", true);
        Log.log("Autofocus for acq " + acq_.getName() + "  Time point " + timeIndex, true);
        if (timeIndex == 0) {
            //get initial position
            try {
                currentPosition_ = initialPosition_;
                previousPosition_ = initialPosition_;
            } catch (Exception e) {
               Log.log("Couldn't get autofocus Z drive initial position", true);
            }
            //figure out which resolution level will be used for xCorr
            MultiResMultipageTiffStorage storage = acq_.getStorage();
            //do these calulations with BigIntegers to prevent overflow and Nan values
            BigInteger tileWidth = new BigInteger(storage.getTileWidth() + "");
            BigInteger tileHeight = new BigInteger(storage.getTileHeight() + "");
            BigInteger numCols = new BigInteger(acq_.getNumColumns() + "");
            BigInteger numRows = new BigInteger(acq_.getNumRows() + "");
            //figure out how much downsampling needed to run autofocus in a reasonable amount of time
            //factor of two is for z padding
            BigDecimal numPix2D = new BigDecimal(tileWidth.multiply(numCols).multiply(tileHeight).multiply(numRows));
            BigDecimal numXCorrSlices = new BigDecimal((acq_.getNumSlices()) + "");
            double dsFactor = //ratio of number of voxels to voxel target
                    Math.sqrt(numPix2D.multiply(numXCorrSlices).divide(new BigDecimal((double) NUM_VOXEL_TARGET),
                    RoundingMode.UP).doubleValue());
            downsampleIndex_ = (int) Math.max(0, Math.round(Math.log(dsFactor) / Math.log(2)));
            downsampledWidth_ = (int) (tileWidth.multiply(numCols).longValue() / Math.pow(2, downsampleIndex_));
            downsampledHeight_ = (int) (tileHeight.multiply(numRows).longValue() / Math.pow(2, downsampleIndex_));
            Log.log("Drift compensation DS Index: " + downsampleIndex_, false);
            Log.log("Drift compensation DS Width: " + downsampledWidth_, false);
            Log.log("Drift compensation DS Height: " + downsampledHeight_, false);
        } else {
            ImageStack lastTPStack = createAFStack(acq_, timeIndex - 1, channelIndex_, downsampledWidth_, downsampledHeight_, downsampleIndex_);
            ImageStack currentTPStack = createAFStack(acq_, timeIndex, channelIndex_, downsampledWidth_, downsampledHeight_, downsampleIndex_);
            //run autofocus
            //image drift is the difference between this TP and the previous one
            //but does not represent the acutal drift because these 2 TPs will likely have different
            //positions for the AF compensation Z device
            //drifteCorrection = move for the AF drive to bring current TP to position of previous TP
            double driftCorrection = -calcFocusDrift(acq_.getName(), lastTPStack, currentTPStack, acq_.getZStep());
            Log.log(acq_.getName() + " Drift compensation: correction = " + driftCorrection, true);
            //now add in a factor accounting for the previous AF
            //i.e. how far the reference image is from the desired position
            driftCorrection += (currentPosition_ - previousPosition_);
            Log.log(acq_.getName() + " Drift compensation: correction (accounting for previous position) = " + driftCorrection, true);

            //check if outside max displacement
            if (Math.abs(currentPosition_ + driftCorrection - initialPosition_) > maxDisplacement_) {
                Log.log("Calculated focus drift of " + driftCorrection + " um exceeds tolerance. Leaving autofocus offset unchanged", true);
                return;
            }
            Log.log("New position: " + (currentPosition_ + driftCorrection), true);
            previousPosition_ = currentPosition_;
            currentPosition_ += driftCorrection;
        }
    }

    /**
     * return a 32 bit for use with cross corr autofocus
     *

    * @return
    */
   private static ImageStack createAFStack(FixedAreaAcquisition acq, int timeIndex, int channelIndex, int width, int height, int dsIndex) {
      ImageStack stack = new ImageStack(width, height);
      //get background pixel value
      for (int slice = acq.getMinSliceIndex(); slice < acq.getMinSliceIndex() + acq.getNumSlices(); slice++) {
         //add as int
         float[] pix32;
         if (Magellan.getCore().getBytesPerPixel() == 1) {
            byte[] pix = (byte[]) acq.getStorage().getImageForDisplay(channelIndex, slice, timeIndex, dsIndex, 0, 0, width, height).pix;
            pix32 = new float[pix.length];
            for (int i = 0; i < pix.length; i++) {
               pix32[i] = pix[i] & 0xff;
            }
         } else {
            short[] pix = (short[]) acq.getStorage().getImageForDisplay(channelIndex, slice, timeIndex, dsIndex, 0, 0, width, height).pix;
            pix32 = new float[pix.length];
            for (int i = 0; i < pix.length; i++) {
               pix32[i] = pix[i] & 0xffff;
            }
         }
         stack.addSlice(null, pix32);
      }
      return stack;
   }

   /**
    *
    * @param original
   * @param current
   * @param pixelSizeZ
   * @return double representing the focus position of current relative to original (i.e. 4 means
   * that current is focused 4 um deeper than current)
   */
   private double calcFocusDrift(String acqName, final ImageStack tp0Stack, final ImageStack currentTPStack, double pixelSizeZ) throws Exception {
      Log.log( acqName + " Autofocus: cross correlating", true);
      //do actual autofocusing on a seperate thread so a bug in it won't crash everything
      Future<ImageStack> f = afExecutor_.submit(new Callable<ImageStack>() {
          @Override
          public ImageStack call() throws Exception {
              return FHTImage3D.crossCorrelation(tp0Stack, currentTPStack);
          }
      });
      ImageStack xCorrStack;
       try {
           xCorrStack = f.get(AF_TIMEOUT_MIN, TimeUnit.MINUTES);
       } catch (InterruptedException ex) {
           Log.log("autofocus aborted");
           throw new Exception();
       } catch (ExecutionException ex) {
           Log.log("Exception while running autofocus");
           Log.log(ex);
           throw new Exception();
       } catch (TimeoutException ex) {
           Log.log("Autofocus timeout for acquisition: " + acqName);
           throw new Exception();
       }

      Log.log( acqName + " Autofocus: finished cross correlating..calculating drift", true);
      ImagePlus xCorr = new ImagePlus("XCorr", xCorrStack);
      //find the maximum cross correlation intensity at each z slice
      double[] ccIntensity = new double[xCorr.getNSlices()], interpolatedCCMax = new double[xCorr.getNSlices()];
      for (int i = 1; i <= ccIntensity.length; i++) {
         xCorr.setSlice(i);
         ccIntensity[i - 1] = findMaxPixelVal((float[]) xCorr.getProcessor().getPixels(), xCorr.getWidth(), xCorr.getHeight());
         interpolatedCCMax[i - 1] = i - 1;
      }

      //find maximum value of interpolated spline function
      PolynomialSplineFunction func = new SplineInterpolator().interpolate(interpolatedCCMax, ccIntensity);
      double[] sliceIndexInterpolationPoints = new double[(int) (SPLINE_PRECISION * (interpolatedCCMax.length - 1))];
      int maxIndex = 0;
      for (int i = 0; i < sliceIndexInterpolationPoints.length; i++) {
         sliceIndexInterpolationPoints[i] = i / SPLINE_PRECISION;
         try {
            if (func.value(sliceIndexInterpolationPoints[i]) > func.value(sliceIndexInterpolationPoints[maxIndex])) {
               maxIndex = i;
            }
         } catch (ArgumentOutsideDomainException ex) {
            Log.log("Spline value calculation outside range");
         }
      }
      //get maximum value of xCorr in slice index units
      double ccMaxSliceIndex = sliceIndexInterpolationPoints[maxIndex];
      //convert to um
      double drift_um = (ccMaxSliceIndex - (((double) xCorr.getNSlices()) / 2.0)) * pixelSizeZ;
      xCorr.close();

      return drift_um;
   }

   private static float findMaxPixelVal(float[] pix, int width, int height) {
      //only use central square for calulating max, because weird large values can occur on the edges of the xCorr
      float max = 0;
      for (int i = 0; i < width*height; i++) {
         if (i / width < height / 4 || i / width > 3*height / 4 ||
                 i % width  < width / 4 || i % width > 3*width/4) {
            continue; // use only central square of pixels
         }
         max = Math.max(max, pix[i]);
      }
      return max;
   }

}


text:
package org.springframework.transaction.interceptor;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Simple implementation of TransactionAttributeSource that
 * allows attributes to be matched by registered name.
 * @author Juergen Hoeller
 * @since 21.08.2003
 * @see #isMatch
*  @version $Id: NameMatchTransactionAttributeSource.java,v 1.7 2004/07/26 17:49:48 johnsonr Exp $
 */
public class NameMatchTransactionAttributeSource implements TransactionAttributeSource, Serializable {

	/**
	 * Static for optimal serialization
	 */
	protected static final Log logger = LogFactory.getLog(NameMatchTransactionAttributeSource.class);

	/**
	 * Keys are methods: values are TransactionAttributes
	 */
	private Map nameMap = new HashMap();

	/**
	 * Set a name/attribute map, consisting of method names
	 * (e.g. "myMethod") and TransactionAttribute instances.
	 * @see TransactionAttribute
	 */
	public void setNameMap(Map nameMap) {
		this.nameMap = nameMap;
	}

	/**
	 * Parses the given properties into a name/attribute map.
	 * Expects method names as keys and String attributes definitions as values,
	 * parsable into TransactionAttribute instances via TransactionAttributeEditor.
	 * @see #setNameMap
	 * @see TransactionAttributeEditor
	 */
	public void setProperties(Properties transactionAttributes) {
		TransactionAttributeEditor tae = new TransactionAttributeEditor();
		for (Iterator it = transactionAttributes.keySet().iterator(); it.hasNext(); ) {
			String methodName = (String) it.next();
			String value = transactionAttributes.getProperty(methodName);
			tae.setAsText(value);
			TransactionAttribute attr = (TransactionAttribute) tae.getValue();
			addTransactionalMethod(methodName, attr);
		}
	}

	/**
	 * Add an attribute for a transactional method.
	 * Method names can end with "*" for matching multiple methods.
	 * @param methodName the name of the method
	 * @param attr attribute associated with the method
	 */
	public void addTransactionalMethod(String methodName, TransactionAttribute attr) {
		logger.debug("Adding transactional method [" + methodName + "] with attribute [" + attr + "]");
		this.nameMap.put(methodName, attr);
	}

	public TransactionAttribute getTransactionAttribute(Method method, Class targetClass) {
		String methodName = method.getName();
		TransactionAttribute attr = (TransactionAttribute) this.nameMap.get(methodName);
		if (attr != null) {
			return attr;
		}
		else {
			// look up most specific name match
			String bestNameMatch = null;
			for (Iterator it = this.nameMap.keySet().iterator(); it.hasNext();) {
				String mappedName = (String) it.next();
				if (isMatch(methodName, mappedName) &&
						(bestNameMatch == null || bestNameMatch.length() <= mappedName.length())) {
					attr = (TransactionAttribute) this.nameMap.get(mappedName);
					bestNameMatch = mappedName;
				}
			}
			return attr;
		}
	}

	/**
	 * Return if the given method name matches the mapped name.
	 * The default implementation checks for "xxx*" and "*xxx" matches.
	 * Can be overridden in subclasses.
	 * @param methodName the method name of the class
	 * @param mappedName the name in the descriptor
	 * @return if the names match
	 */
	protected boolean isMatch(String methodName, String mappedName) {
		return (mappedName.endsWith("*") && methodName.startsWith(mappedName.substring(0, mappedName.length() - 1))) ||
				(mappedName.startsWith("*") && methodName.endsWith(mappedName.substring(1, mappedName.length())));
	}

}


text:
start_time = Time.now

def prime?(number)
  return false if number < 2
  (2..Math.sqrt(number)).each do |possible_factor|
    return false if number % possible_factor == 0
  end
  true
end

def first_n_primes(n)
  primes = []
  counter = 2
  until primes.length == n
    primes << counter if prime?(counter)
    counter += 1
  end
  primes
end

p first_n_primes(10001).last
p "calculated in #{(Time.now - start_time) * 1000} ms"

# This may be solved very quickly and in only two lines if we use the Prime class:

# require 'prime'
# Prime.take(10001).last

# But I took this as an opportunity to build a prime number generator from stratch.
# I'll let my original solution stay for educational purposes.


text:
from __future__ import unicode_literals

import django
from django.test import TestCase
from django.utils.timezone import now

import job.test.utils as job_test_utils
from error.exceptions import ScaleDatabaseError, ScaleIOError, ScaleOperationalError
from error.models import reset_error_cache
from job.execution.configuration.exceptions import MissingSetting
from job.execution.configuration.json.exe_config import ExecutionConfiguration
from job.execution.tasks.pre_task import PreTask
from job.tasks.update import TaskStatusUpdate

class TestPreTask(TestCase):
    """Tests the PreTask class"""

    fixtures = ['basic_errors.json', 'basic_job_errors.json']

    def setUp(self):
        django.setup()

        self.job_exe = job_test_utils.create_job_exe()

        # Clear error cache so tests work correctly
        reset_error_cache()

    def test_determine_error(self):
        """Tests that a pre-task successfully determines the correct error"""

        scale_errors = [ScaleDatabaseError(), ScaleIOError(), ScaleOperationalError(), MissingSetting('')]

        for scale_error in scale_errors:
            config = ExecutionConfiguration()
            config.create_tasks(['pre'])
            config.set_task_ids(self.job_exe.get_cluster_id())
            task = PreTask('agent_1', self.job_exe, self.job_exe.job_type, config)
            update = job_test_utils.create_task_status_update(task.id, task.agent_id, TaskStatusUpdate.RUNNING, now())
            task.update(update)
            update = job_test_utils.create_task_status_update(task.id, task.agent_id, TaskStatusUpdate.FAILED, now(),
                                                              exit_code=scale_error.exit_code)
            error = task.determine_error(update)
            self.assertEqual(scale_error.error_name, error.name)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/mRv"
        android:layout_width="match_parent"
        android:padding="3dp"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>


text:
/*! Sly v1.0rc2 <http://sly.digitarald.com> - (C) 2009 Harald Kirschner <http://digitarald.de> - Open source under MIT License */

/**
 * Credits
 *
 * Sly's code and pattern are inspired by several open source developers.
 *
 * Valerio Proietti & MooTools contributors
 *  - Idea of modular combinator and pseudo filters
 *  - Code for several pseudo filters
 *  - Slickspeed benchmark framework
 * Steven Levithan
 *  - Improved Sly.parse expression
 * Diego Perini
 *  - Research on querySelectorAll and browser quirks
 *  - Patches for Sly.parse expression
 *  - Combined tests from jQuery and Prototype
 * Thomas Aylott & Slick contributors
 *   - Idea of using regular expressions in attribute filter.
 * John Resig & jQuery/Sizzle contributors
 *  - Browser feature/quirks detection
 *  - Additional pseudo filters
 *  - Extensive Unit Tests, (c) 2008 John Resig, Jörn Zaefferer, MIT/GPL dual license
 * Sam Stephenson & Prototype contributors
 *  - Extensive Unit Tests, (c) 2005-2008 Sam Stephenson, MIT-style license
 * Alan Kang & JSSpec contributors
 *  - JSSpec BDD framework
 *
 * Kudos to every single one of them for supporting the open web.
 */

var Sly = (function() {

var cache = {};

/**
 * Sly::constructor
 *
 * Acts also as shortcut for Sly::search if context argument is given.
 */
var Sly = function(text, context, results, options) {
  // normalise
  text = (typeof(text) == 'string') ? text.replace(/^\s+|\s+$/g, '') : '';

  var cls = cache[text] || (cache[text] = new Sly.initialize(text));
  return (context == null) ? cls : cls.search(context, results, options);
};

Sly.initialize = function(text) {
  this.text = text;
};

var proto = Sly.initialize.prototype = Sly.prototype;

/**
 * Sly.implement
 */
Sly.implement = function(key, properties) {
  for (var prop in properties) Sly[key][prop] = properties[prop];
};

/**
 * Sly.support
 *
 * Filled with experiment results.
 */
var support = Sly.support = {};

// Checks similar to NWMatcher, Sizzle
(function() {

  // Our guinea pig
  var testee = document.createElement('div'), id = (new Date()).getTime();
  testee.innerHTML = '';
  testee.appendChild(document.createComment(''));

  // IE returns comment nodes for getElementsByTagName('*')
  support.byTagAddsComments = (testee.getElementsByTagName('*').length > 1);

  // Safari can't handle uppercase or unicode characters when in quirks mode.
  support.hasQsa = !!(testee.querySelectorAll && testee.querySelectorAll('.€').length);

  support.hasByClass = (function() {
    if (!testee.getElementsByClassName || !testee.getElementsByClassName('b').length) return false;
    testee.firstChild.className = 'c';
    return (testee.getElementsByClassName('c').length == 1);
  })();

  var root = document.documentElement;
  root.insertBefore(testee, root.firstChild);

  // IE returns named nodes for getElementById(name)
  support.byIdAddsName = !!(document.getElementById(id));

  root.removeChild(testee);

})();

var locateFast = function() {
  return true;
};

/**
 * Sly::search
 */
proto.search = function(context, results, options) {
  options = options || {};

  var iterate, i, item;

  if (!context) {
    context = document;
  } else if (context.nodeType != 1 && context.nodeType != 9) {
    if (typeof(context) == 'string') {
      context = Sly.search(context);
      iterate = true;
    } else if (Object.prototype.toString.call(context) == '[object Array]' || (typeof(context.length) == 'number' && context.item)) { // simple isArray
      var filtered = [];
      for (i = 0; (item = context[i]); i++) {
        if (item.nodeType == 1 || item.nodeType == 9) filtered.push(item);
      }
      iterate = (filtered.length > 1);
      context = (iterate) ? filtered : (filtered[0] || document);
    }
  }

  var mixed, // results need to be sorted, comma
    combined, // found nodes from one iteration process
    nodes, // context nodes from one iteration process
    all = {}, // unique ids for overall result
    state = {}; // matchers temporary state
  var current = all; // unique ids for one iteration process

  // unifiers
  var getUid = Sly.getUid;
  var locateCurrent = function(node) {
    var uid = getUid(node);
    return (current[uid]) ? null : (current[uid] = true);
  };

  if (results && results.length) { // fills unique ids, does not alter the given results
    for (i = 0; (item = results[i]); i++) locateCurrent(item);
  }

  if (support.hasQsa && !iterate && context.nodeType == 9 && !(/\[/).test(this.text)) {
    try {
      var query = context.querySelectorAll(this.text);
    } catch(e) {}
    if (query) {
      if (!results) return Sly.toArray(query);
      for (i = 0; (item = query[i]); i++) {
        if (locateCurrent(item)) results.push(item);
      }
      if (!options.unordered) results.sort(Sly.compare);
      return results;
    }
  }

  var parsed = this.parse();
  if (!parsed.length) return [];

  for (var i = 0, selector; (selector = parsed[i]); i++) {

    var locate = locateCurrent;

    if (selector.first) {
      if (!results) locate = locateFast;
      else mixed = true;
      if (iterate) nodes = context;
      else if (selector.combinator) nodes = [context]; // allows combinators before selectors
    }

    if (selector.last && results) {
      current = all;
      combined = results;
    } else {
      // default stack
      current = {};
      combined = [];
    }

    if (!selector.combinator && !iterate) {
      // without prepended combinator
      combined = selector.combine(combined, context, selector, state, locate, !(combined.length));
    } else {
      // with prepended combinators
      for (var k = 0, l = nodes.length; k < l; k++) {
        combined = selector.combine(combined, nodes[k], selector, state, locate);
      }
    }

    if (selector.last) {
      if (combined.length) results = combined;
    } else {
      nodes = combined;
    }
  }

  if (!options.unordered && mixed && results) results.sort(Sly.compare);

  return results || [];
};

/**
 * Sly::find
 */
proto.find = function(context, results, options) {
  return this.search(context, results, options)[0];
};

/**
 * Sly::match
 */
proto.match = function(node, parent) {
  var parsed = this.parse();
  if (parsed.length == 1) return !!(this.parse()[0].match(node, {}));
  if (!parent) {
    parent = node;
    while (parent.parentNode) parent = parent.parentNode
  }
  var found = this.search(parent), i = found.length;
  if (!i--) return false;
  while (i--) {
    if (found[i] == node) return true;
  }
  return false;
};

/**
 * Sly::filter
 */
proto.filter = function(nodes) {
  var results = [], match = this.parse()[0].match;
  for (var i = 0, node; (node = nodes[i]); i++) {
    if (match(node)) results.push(node);
  }
  return results;
};

/**
 * Sly.recompile()
 */
var pattern;

Sly.recompile = function() {

  var key, combList = [','], operList = ['!'];

  for (key in combinators) {
    if (key != ' ') {
      combList[(key.length > 1) ? 'unshift' : 'push'](Sly.escapeRegExp(key));
    }
  }
  for (key in operators) operList.push(key);

  /**
    The regexp is a group of every possible selector part including combinators.
    "|" separates the possible selectors.

    Capturing parentheses:
    1 - Combinator (only requires to allow multiple-character combinators)
    2 - Attribute name
    3 - Attribute operator
    4, 5, 6 - The value
    7 - Pseudo name
    8, 9, 10 - The value
   */

  pattern = new RegExp(
    // A tagname
    '[\\w\\u00a1-\\uFFFF][\\w\\u00a1-\\uFFFF-]*|' +

    // An id or the classname
    '[#.](?:[\\w\\u00a1-\\uFFFF-]|\\\\:|\\\\.)+|' +

    // Whitespace (descendant combinator)
    '[ \\t\\r\\n\\f](?=[\\w\\u00a1-\\uFFFF*#.[:])|' +

    // Other combinators and the comma
    '[ \\t\\r\\n\\f]*(' + combList.join('|') + ')[ \\t\\r\\n\\f]*|' +

    // An attribute, with the various and optional value formats ([name], [name=value], [name="value"], [name='value']
    '\\[([\\w\\u00a1-\\uFFFF-]+)[ \\t\\r\\n\\f]*(?:([' + operList.join('') + ']?=)[ \\t\\r\\n\\f]*(?:"([^"]*)"|\'([^\']*)\'|([^\\]]*)))?]|' +

    // A pseudo-class, with various formats
    ':([-\\w\\u00a1-\\uFFFF]+)(?:\\((?:"([^"]*)"|\'([^\']*)\'|([^)]*))\\))?|' +

    // The universial selector, not process
    '\\*|(.+)', 'g'
  );
};

// I prefer it outside, not sure if this is faster
var create = function(combinator) {
  return {
    ident: [],
    classes: [],
    attributes: [],
    pseudos: [],
    combinator: combinator
  };
};

var blank = function($0) {
  return $0;
};

/**
 * Sly::parse
 *
 * Returns an array with one object for every selector:
 *
 * {
 *   tag: (String) Tagname (defaults to null for universal *)
 *   id: (String) Id
 *   classes: (Array) Classnames
 *   attributes: (Array) Attribute objects with "name", "operator" and "value"
 *   pseudos: (Array) Pseudo objects with "name" and "value"
 *   operator: (Char) The prepended operator (not comma)
 *   first: (Boolean) true if it is the first selector or the first after a comma
 *   last: (Boolean) true if it is the last selector or the last before a comma
 *   ident: (Array) All parsed matches, can be used as cache identifier.
 * }
 */
proto.parse = function(plain) {
  var save = (plain) ? 'plain' : 'parsed';
  if (this[save]) return this[save];

  var text = this.text;
  var compute = (plain) ? blank : this.compute;

  var parsed = [], current = create(null);
  current.first = true;

  var refresh = function(combinator) {
    parsed.push(compute(current));
    current = create(combinator);
  };

  pattern.lastIndex = 0; // to fix some weird behavior
  var match, $0;

  while ((match = pattern.exec(text))) {

    if (match[11]) {
      if (Sly.verbose) throw SyntaxError('Syntax error, "' + $0 + '" unexpected at #' + pattern.lastIndex + ' in "' + text + '"');
      return (this[save] = []);
    }

    $0 = match[0];

    switch ($0.charAt(0)) {
      case '.':
        current.classes.push($0.slice(1).replace(/\\/g, ''));
        break;
      case '#':
        current.id = $0.slice(1).replace(/\\/g, '');
        break;
      case '[':
        current.attributes.push({
          name: match[2],
          operator: match[3] || null,
          value: match[4] || match[5] || match[6] || null
        });
        break;
      case ':':
        current.pseudos.push({
          name: match[7],
          value: match[8] || match[9] || match[10] || null
        });
        break;
      case ' ': case '\t': case '\r': case '\n': case '\f':
        match[1] = match[1] || ' ';
      default:
        var combinator = match[1];
        if (combinator) {
          if (combinator == ',') {
            current.last = true;
            refresh(null);
            current.first = true;
            continue;
          }
          if (current.first && !current.ident.length) current.combinator = combinator;
          else refresh(combinator);
        } else {
          if ($0 != '*') current.tag = $0;
        }
    }
    current.ident.push($0);
  }

  current.last = true;
  parsed.push(compute(current));

  return (this[save] = parsed);
};

// chains two given functions

function chain(prepend, append, aux, unshift) {
  return (prepend) ? ((unshift) ? function(node, state) {
    return append(node, aux, state) && prepend(node, state);
  } : function(node, state) {
    return prepend(node, state) && append(node, aux, state);
  }) : function(node, state) {
    return append(node, aux, state);
  };
  // fn.$slyIndex = (prepend) ? (prepend.$slyIndex + 1) : 0;
};

// prepared match comperators, probably needs namespacing
var empty = function() {
  return true;
};

var matchId = function(node, id) {
  return (node.id == id);
};

var matchTag = function(node, tag) {
  return (node.nodeName.toUpperCase() == tag);
};

var prepareClass = function(name) {
  return (new RegExp('(?:^|[ \\t\\r\\n\\f])' + name + '(?:$|[ \\t\\r\\n\\f])'));
};

var matchClass = function(node, expr) {
  return node.className && expr.test(node.className);
};

var prepareAttribute = function(attr) {
  attr.getter = Sly.lookupAttribute(attr.name) || Sly.getAttribute;
  if (!attr.operator || !attr.value) return attr;
  var parser = operators[attr.operator];
  if (parser) { // @todo: Allow functions, not only regex
    attr.escaped = Sly.escapeRegExp(attr.value);
    attr.pattern = new RegExp(parser(attr.value, attr.escaped, attr));
  }
  return attr;
};

var matchAttribute = function(node, attr) {
  var read = attr.getter(node, attr.name);
  switch (attr.operator) {
    case null: return read;
    case '=': return (read == attr.value);
    case '!=': return (read != attr.value);
  }
  if (!read && attr.value) return false;
  return attr.pattern.test(read);
};

/**
 * Sly::compute
 *
 * Attaches the following methods to the selector object:
 *
 * {
 *   search: Uses the most convinient properties (id, tag and/or class) of the selector as search.
 *   matchAux: If search does not contain all selector properties, this method matches an element against the rest.
 *   match: Matches an element against all properties.
 *   simple: Set when matchAux is not needed.
 *   combine: The callback for the combinator
 * }
 */
proto.compute = function(selector) {

  var i, item, match, search, matchSearch, tagged,
    tag = selector.tag,
    id = selector.id,
    classes = selector.classes;

  var nodeName = (tag) ? tag.toUpperCase() : null;

  if (id) {
    tagged = true;

    matchSearch = chain(null, matchId, id);

    search = function(context) {
      if (context.getElementById) {
        var el = context.getElementById(id);
        return (el
          && (!nodeName || el.nodeName.toUpperCase() == nodeName)
          && (!support.getIdAdds || el.id == id))
            ? [el]
            : [];
      }

      var query = context.getElementsByTagName(tag || '*');
      for (var j = 0, node; (node = query[j]); j++) {
        if (node.id == id) return [node];
      }
      return [];
    };
  }

  if (classes.length > 0) {

    if (!search && support.hasByClass) {

      for (i = 0; (item = classes[i]); i++) {
        matchSearch = chain(matchSearch, matchClass, prepareClass(item));
      }

      var joined = classes.join(' ');
      search = function(context) {
        return context.getElementsByClassName(joined);
      };

    } else if (!search && classes.length == 1) { // optimised for typical .one-class-only

      tagged = true;

      var expr = prepareClass(classes[0]);
      matchSearch = chain(matchSearch, matchClass, expr);

      search = function(context) {
        var query = context.getElementsByTagName(tag || '*');
        var found = [];
        for (var i = 0, node; (node = query[i]); i++) {
          if (node.className && expr.test(node.className)) found.push(node);
        }
        return found;
      };

    } else {

      for (i = 0; (item = classes[i]); i++) {
        match = chain(match, matchClass, prepareClass(item));
      }

    }
  }

  if (tag) {

    if (!search) {
      matchSearch = chain(matchSearch, matchTag, nodeName);

      search = function(context) {
        return context.getElementsByTagName(tag);
      };
    } else if (!tagged) { // search does not filter by tag yet
      match = chain(match, matchTag, nodeName);
    }

  } else if (!search) { // default engine

    search = function(context) {
      var query = context.getElementsByTagName('*');
      if (!support.byTagAddsComments) return query;
      var found = [];
      for (var i = 0, node; (node = query[i]); i++) {
        if (node.nodeType === 1) found.push(node);
      }
      return found;
    };

  }

  for (i = 0; (item = selector.pseudos[i]); i++) {

    if (item.name == 'not') { // optimised :not(), fast as possible
      var not = Sly(item.value);
      match = chain(match, function(node, not) {
        return !not.match(node);
      }, (not.parse().length == 1) ? not.parsed[0] : not);
    } else {
      var parser = pseudos[item.name];
      if (parser) match = chain(match, parser, item.value);
    }

  }

  for (i = 0; (item = selector.attributes[i]); i++) {
    match = chain(match, matchAttribute, prepareAttribute(item));
  }

  if ((selector.simple = !(match))) {
    selector.matchAux = empty;
  } else {
    selector.matchAux = match;
    matchSearch = chain(matchSearch, match);
  }

  selector.match = matchSearch || empty;

  selector.combine = Sly.combinators[selector.combinator || ' '];

  selector.search = search;

  return selector;
};

// Combinators/Pseudos partly from MooTools 1.2-pre, (c) 2006-2009 Valerio Proietti, MIT License

/**
 * Combinators
 */
var combinators = Sly.combinators = {

  ' ': function(combined, context, selector, state, locate, fast) {
    var nodes = selector.search(context);
    if (fast && selector.simple) return Sly.toArray(nodes);
    for (var i = 0, node, aux = selector.matchAux; (node = nodes[i]); i++) {
      if (locate(node) && aux(node, state)) combined.push(node);
    }
    return combined;
  },

  '>': function(combined, context, selector, state, locate) {
    var nodes = selector.search(context);
    for (var i = 0, node; (node = nodes[i]); i++) {
      if (node.parentNode == context && locate(node) && selector.matchAux(node, state)) combined.push(node);
    }
    return combined;
  },

  '+': function(combined, context, selector, state, locate) {
    while ((context = context.nextSibling)) {
      if (context.nodeType == 1) {
        if (locate(context) && selector.match(context, state)) combined.push(context);
        break;
      }

    }
    return combined;
  },

  '~': function(combined, context, selector, state, locate) {
    while ((context = context.nextSibling)) {
      if (context.nodeType == 1) {
        if (!locate(context)) break;
        if (selector.match(context, state)) combined.push(context);
      }
    }
    return combined;
  }

};

/**
 * Pseudo-Classes
 */
var pseudos = Sly.pseudos = {

  // w3c pseudo classes

  'first-child': function(node) {
    return pseudos.index(node, 0);
  },

  'last-child': function(node) {
    while ((node = node.nextSibling)) {
      if (node.nodeType === 1) return false;
    }
    return true;
  },

  'only-child': function(node) {
    var prev = node;
    while ((prev = prev.previousSibling)) {
      if (prev.nodeType === 1) return false;
    }
    var next = node;
    while ((next = next.nextSibling)) {
      if (next.nodeType === 1) return false;
    }
    return true;
  },

  'nth-child': function(node, value, state) {
    var parsed = Sly.parseNth(value || 'n');
    if (parsed.special != 'n') return pseudos[parsed.special](node, parsed.a, state);
    state = state || {}; // just to be sure
    state.positions = state.positions || {};
    var uid = Sly.getUid(node) ;
    if (!state.positions[uid]) {
      var count = 0;
      while ((node = node.previousSibling)) {
        if (node.nodeType != 1) continue;
        count++;
        var position = state.positions[Sly.getUid(node)];
        if (position != undefined) {
          count = position + count;
          break;
        }
      }
      state.positions[uid] = count;
    }
    return (state.positions[uid] % parsed.a == parsed.b);
  },

  'empty': function(node) {
    return !(node.innerText || node.textContent || '').length;
  },

  'contains': function(node, text) {
    return (node.innerText || node.textContent || '').indexOf(text) != -1;
  },

  'index': function(node, index) {
    var count = 1;
    while ((node = node.previousSibling)) {
      if (node.nodeType == 1 && ++count > index) return false;
    }
    return (count == index);
  },

  'even': function(node, value, state) {
    return pseudos['nth-child'](node, '2n+1', state);
  },

  'odd': function(node, value, state) {
    return pseudos['nth-child'](node, '2n', state);
  }

};

pseudos.first = pseudos['first-child'];
pseudos.last = pseudos['last-child'];
pseudos.nth = pseudos['nth-child'];
pseudos.eq = pseudos.index;

/**
 * Attribute operators
 */
var operators = Sly.operators = {

  '*=': function(value, escaped) {
    return escaped;
  },

  '^=': function(value, escaped) {
    return '^' + escaped;
  },

  '$=': function(value, escaped) {
    return value + '$';
  },

  '~=': function(value, escaped) {
    return '(?:^|[ \\t\\r\\n\\f])' + escaped + '(?:$|[ \\t\\r\\n\\f])';
  },

  '|=': function(value, escaped) {
    return '(?:^|\\|)' + escaped + '(?:$|\\|)';
  }

};

// public, overridable

/**
 * Sly.getAttribute & Sly.lookupAttribute
 *
 * @todo add more translations
 */
var translate = {
  'class': 'className'
}

Sly.lookupAttribute = function(name) {
  var prop = translate[name];
  if (prop) {
    return function(node) {
      return node[prop];
    }
  }
  var flag = /^(?:src|href|action)$/.test(name) ? 2 : 0;
  return function(node) {
    return node.getAttribute(name, flag);
  }
};

Sly.getAttribute = function(node, name) {
  return node.getAttribute(name);
};

/**
 * Sly.toArray
 */
var toArray = Array.slice || function(nodes) {
  return Array.prototype.slice.call(nodes);
};

try {
  toArray(document.documentElement.childNodes);
} catch (e) {
  toArray = function(nodes) {
    if (nodes instanceof Array) return nodes;
    var i = nodes.length, results = new Array(i);
    while (i--) results[i] = nodes[i];
    return results;
  };
}

Sly.toArray = toArray;

Sly.compare = (document.compareDocumentPosition) ? function (a, b) {
  return (3 - (a.compareDocumentPosition(b) & 6));
} : function (a, b) {
  return (a.sourceIndex - b.sourceIndex);
};

/**
 * Sly.getUid
 */
var nextUid = 1;

Sly.getUid = (window.ActiveXObject) ? function(node) {
  return (node.$slyUid || (node.$slyUid = {id: nextUid++})).id;
} : function(node) {
  return node.$slyUid || (node.$slyUid = nextUid++);
};

var nthCache = {};

Sly.parseNth = function(value) {
  if (nthCache[value]) return nthCache[value];

  var parsed = value.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);
  if (!parsed) return false;

  var a = parseInt(parsed[1], 10), b = (parseInt(parsed[3], 10) || 0) - 1;

  if ((a = (isNaN(a)) ? 1 : a)) {
    while (b < 1) b += a;
    while (b >= a) b -= a;
  }
  switch (parsed[2]) {
    case 'n': parsed = {a: a, b: b, special: 'n'}; break;
    case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break;
    case 'even': parsed = {a: 2, b: 1, special: 'n'}; break;
    case 'first': parsed = {a: 0, special: 'index'}; break;
    case 'last': parsed = {special: 'last-child'}; break;
    case 'only': parsed = {special: 'only-child'}; break;
    default: parsed = {a: (a) ? (a - 1) : b, special: 'index'};
  }

  return (nthCache[value] = parsed);
};

Sly.escapeRegExp = function(text) {
  return text.replace(/[-.*+?^${}()|[\]\/\\]/g, '\\$&');
};

// generic accessors

Sly.generise = function(name) {
  Sly[name] = function(text) {
    var cls = Sly(text);
    return cls[name].apply(cls, Array.prototype.slice.call(arguments, 1));
  }
};

var generics = ['parse', 'search', 'find', 'match', 'filter'];
for (var i = 0; generics[i]; i++) Sly.generise(generics[i]);

// compile pattern for the first time

Sly.recompile();

// FIN

return Sly;

})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Indian Phytopath. 40(4): 453 (1988)

#### Original name
Lycoperdon gulmargense K.S. Thind & I.P.S. Thind

### Remarks
null


text:
from django.db import models
import logging

logger = logging.getLogger("open-knesset.laws.models")

class GovLegislationCommitteeDecision(models.Model):
    class Meta:
        app_label = 'laws'

    title = models.CharField(max_length=1000)
    subtitle = models.TextField(null=True, blank=True)
    text = models.TextField(blank=True, null=True)
    date = models.DateField(blank=True, null=True)
    source_url = models.URLField(max_length=1024, null=True, blank=True)
    bill = models.ForeignKey('Bill', blank=True, null=True, related_name='gov_decisions')
    stand = models.IntegerField(blank=True, null=True)
    number = models.IntegerField(blank=True, null=True)

    def __unicode__(self):
        return u"%s" % self.title

    def get_absolute_url(self):
        return self.bill.get_absolute_url()


text:
'use strict';

function searchQueryController(req, res, next) {
  return res.render('pages/searchquery', {
    layout: 'layouts/layout'
  });
}

module.exports = searchQueryController;


text:
/*
Main redis controller module
 */

const _ = require('underscore'),
    async = require('async'),
    caps = require('./server/caps'),
    common = require('./common'),
    config = require('./config'),
    events = require('events'),
    fs = require('fs'),
    hooks = require('./util/hooks'),
	Muggle = require('./util/etc').Muggle,
	okyaku = require('./server/websockets'),
	state = require('./server/state'),
	{hot} = state,
	cache = state.dbCache,
	nodeRedis = require('redis'),
    tail = require('./util/tail'),
    winston = require('winston');

//Caches. Maps post numbers to threads.
const OPs = exports.OPs = cache.OPs,
	// Maps thread numbers to boards
	BOARDS = exports.boards = cache.boards,
	// Contains all public redis subscriptions for sharing
	SUBS = exports.SUBS = cache.threadSubs;

function redis_client() {
	const client = nodeRedis.createClient(config.REDIS_PORT);
	client.select(config.redis_database || 0);
	return client;
}
exports.redis_client = redis_client;
const redis = global.redis = redis_client();
redis.on('error', err => winston.error('Redis error:', err));

// Validate database spec version
{
	const dbVersion = '1',
		m = redis.multi();
	m.get('postctr');
	m.get('dbVersion');
	m.exec((err, res) => {
		if (err)
			throw err;

		// If post counter does not exist, we assume the database does not
		// have any posts
		if (!res[0]) {
			redis.set('dbVersion', dbVersion, err => {
				if (err)
					throw err;
			});
		}
		else if (res[1] !== dbVersion) {
			throw new Error(`Incompatable database version: ${res[1] || 0}: `
				+ 'See docs/migration.md')
		}
	})
}

// Depend on global redis client
const admin = require('./server/admin'),
	amusement = require('./server/amusement'),
	imager = require('./imager');

exports.UPKEEP_IDENT = {
	auth: 'Upkeep',
	ip: '127.0.0.1'
};

/* REAL-TIME UPDATES */

class Subscription extends events.EventEmitter {
	constructor(targetInfo) {
		super();
		this.setMaxListeners(0);

		this.fullKey = targetInfo.key;
		this.target = targetInfo.target;
		this.channel = targetInfo.channel;
		SUBS[this.fullKey] = this;

		this.pending_subscriptions = [];
		this.subscription_callbacks = [];

		this.k = redis_client();
		this.k.on('error', this.on_sub_error.bind(this));
		this.k.on('subscribe', this.on_one_sub.bind(this));
		this.k.subscribe(this.target);
		this.pending_subscriptions.push(this.target);
		if (this.target != this.fullKey) {
			this.k.subscribe(this.fullKey);
			this.pending_subscriptions.push(this.fullKey);
		}
	}
	on_one_sub(name) {
		const i = this.pending_subscriptions.indexOf(name);
		if (i < 0)
			throw "Obtained unasked-for subscription " + name + "?!";
		this.pending_subscriptions.splice(i, 1);
		if (this.pending_subscriptions.length == 0)
			this.on_all_subs();
	}
	on_all_subs() {
		let k = this.k;
		k.removeAllListeners('subscribe');
		k.on('message', this.on_message.bind(this));
		k.removeAllListeners('error');
		k.on('error', this.sink_sub.bind(this));
		this.subscription_callbacks.forEach(sub => sub(null));
		delete this.pending_subscriptions;
		delete this.subscription_callbacks;
	}
	sink_sub(err) {
		if (config.DEBUG)
			throw err;
		this.emit('error', this.target, err);
		this.commit_sudoku();
	}
	commit_sudoku() {
		const k = this.k;
		k.removeAllListeners('error');
		k.removeAllListeners('message');
		k.removeAllListeners('subscribe');
		k.quit();
		if (SUBS[this.fullKey] === this)
			delete SUBS[this.fullKey];
		this.removeAllListeners('update');
		this.removeAllListeners('error');
	}
	on_sub_error(err) {
		winston.error("Subscription error:", (err.stack || err));
		this.commit_sudoku();
		this.subscription_callbacks.forEach(sub => sub(err));
		this.subscription_callbacks = null;
	}
	on_message(chan, msg) {
		/* Do we need to clarify whether this came from target or fullKey? */
		const parsed = this.parse_pub_message(msg);
		let extra;
		if (this.channel && parsed.suffixPos) {
			const suffix = JSON.parse(msg.slice(parsed.suffixPos));
			extra = suffix[this.channel];
		}
		msg = parsed.body;
		const m = msg.match(/^(\d+),(\d+)/),
			op = parseInt(m[1], 10),
			kind = parseInt(m[2], 10);

		if (extra) {
			const modified = this.inject_extra(kind, msg, extra);
			// currently this won't modify op or kind,
			// but will have to watch out for that if that changes
			if (modified)
				msg = modified;
		}
		this.emit('update', op, kind, '[[' + msg + ']]');
	}
	parse_pub_message(msg) {
		const m = msg.match(/^(\d+)\|/),
			prefixLen = m[0].length,
			bodyLen = parseInt(m[1], 10),
			suffixPos = prefixLen + bodyLen,
			info = {body: msg.substr(prefixLen, bodyLen)};
		if (msg.length > suffixPos)
			info.suffixPos = suffixPos;
		return info;
	}
	inject_extra(kind, msg, extra) {
		// XXX: Why the fuck don't you just stringify arrays?
		const parsed = JSON.parse(`[${msg}]`);
		switch (kind) {
			case common.INSERT_POST:
				parsed[2].mnemonic = extra.mnemonic;
				break;

			// Add moderation information for staff
			case common.SPOILER_IMAGES:
			case common.DELETE_IMAGES:
			case common.DELETE_POSTS:
			case common.LOCK_THREAD:
			case common.UNLOCK_THREAD:
			case common.BAN:
				parsed.push(extra);
				break;
			default:
				return;
		}
		return JSON.stringify(parsed).slice(1, -1);
	}
	has_no_listeners() {
		/* Possibly idle out after a while */
		if (this.idleOutTimer)
			clearTimeout(this.idleOutTimer);
		this.idleOutTimer = setTimeout(() => {
			this.idleOutTimer = null;
			if (this.listeners('update').length == 0)
				this.commit_sudoku();
		}, 30000);
	}
	static get(target, ident) {
		const full = Subscription.full_key(target, ident);
		return SUBS[full.key] || new Subscription(full);
	}
	static full_key(target, ident) {
		let channel;
		if (common.checkAuth('dj', ident))
			channel = 'mod';
		else if (common.checkAuth('janitor', ident))
			channel = 'auth';
		const key = channel ? `${channel}:${target}` : target;
		return {key, channel, target};
	}
	when_ready(cb) {
		if (this.subscription_callbacks)
			this.subscription_callbacks.push(cb);
		else
			cb(null);
	}
}

/* OP CACHE */

// Validate the post number points to a thread on the specific board
function validateOP(op, board) {
	return OPs[op] == op && BOARDS[op] === board;
}
exports.validateOP = validateOP;

function track_OPs (callback) {
	const redis = redis_client();
	redis.subscribe('cache');
	redis.once('subscribe', () => load_OPs(callback));
	redis.on('message', update_cache);
	// connection persists for the purpose of cache updates
}
exports.track_OPs = track_OPs;

// Build caches on server start
function load_OPs(callback) {
	const boards = config.BOARDS,
		threadList = [];
	async.waterfall([
		next => {
			const m = redis.multi();
			for (let board of boards) {
				m.zrange(`board:${board}:threads`, 0, -1);
			}
			m.exec(next);
		},
		(allThreads, next) => {
			// Gather posts from all boards and their threads
			const m = redis.multi();
			for (let i = 0; i < boards.length; i++) {
				for (let thread of allThreads[i]) {
					const num = parseInt(thread, 10);
					cacheBoard(boards[i], num);

					// For consitency, an OP will have it's own post
					// number in the cache
					cacheOP(num, num);
					threadList.push(num);
					m.lrange(`thread:${thread}:posts`, 0, -1);
				}
			}
			m.exec(next);
		},
		(threads, next) => {
			for (let i = 0; i < threads.length; i++) {
				for (let post of threads[i]) {
					cacheOP(post, threadList[i]);
				}
			}
			next();
		}
	], callback);
}

function cacheBoard(board, op) {
	BOARDS[op] = board;
}

function cacheOP(num, op) {
	OPs[num] = op;
}

function uncacheThread(num) {
	delete BOARDS[num];

	// And all of the thread's posts. This includes the OP.
	for (let post in OPs) {
		if (OPs[post] == num)
			delete OPs[post];
	}
}

// To have as little inconsitent state between the database and server(s)
// very little is chached into memory - only thread to board and post to
// thread parenthood. This function is called through redis pub/sun to ensure
// cache consitency between possible  multiple slave servers, once
// clustering is implemnted.
function update_cache(chan, msg) {
	msg = JSON.parse(msg);
	let [kind, num, parent] = msg;
	switch (kind) {
		// Insert thread
		case 0:
			cacheBoard(parent, num);
			parent = num;
		// Insert post
		case 1:
			cacheOP(num, parent);
			break;
		// Thread purged from database
		case 2:
			uncacheThread(num);
			break;
		// Reaload ban list and reverify all connected clients
		case 3:
			admin.loadBans(okyaku.scan_client_caps);
			break;
	}
}

function on_pub (name, handler) {
	const redis = redis_client();
	redis.subscribe(name);
	redis.on('message', handler);
}
exports.on_pub = on_pub;

/* SOCIETY */

// Main database controller class
class Yakusoku extends events.EventEmitter {
	constructor(board, ident) {
		super();
		this.id = ++(cache.YAKUMAN);
		this.board = board;

		//Should moderation be allowed on this board?
		this.isContainmentBoard	= config.containment_boards.indexOf(board) > -1;
		this.ident = ident;
		this.subs = [];
	}
	disconnect() {
		this.removeAllListeners();
	}
	kiku(targets, on_update, on_sink, callback) {
		this.on_update = on_update;
		this.on_sink = on_sink;
		forEachInObject(targets, (id, cb) => {
			const target = this.target_key(id),
				sub = Subscription.get(target, this.ident);
			sub.on('update', on_update);
			sub.on('error', on_sink);
			this.subs.push(sub.fullKey);
			sub.when_ready(cb);
		}, callback);
	}
	target_key(id) {
		return id === 'live' ? 'board:' + this.board : 'thread:' + id;
	}
	kikanai() {
		for (let i = 0; i < this.subs.length; i++) {
			const sub = SUBS[this.subs[i]];
			if (!sub)
				continue;
			sub.removeListener('update', this.on_update);
			sub.removeListener('error', this.on_sink);
			if (sub.listeners('update').length == 0)
				sub.has_no_listeners();
		}
		this.subs = [];
		return this;
	}
	reserve_post(op, ip, callback) {
		if (config.READ_ONLY)
			return callback(Muggle("Can't post right now."));
		if (ip === '127.0.0.1' || ip === '::1')
			return this.reserve(op, callback);

		const key = `ip:${ip}:throttle:`,
			now = Date.now(),
			shortTerm = key + this.short_term_timeslot(now),
			longTerm = key + this.long_term_timeslot(now);
		redis.mget([shortTerm, longTerm], (err, quants) => {
			if (err)
				return callback(Muggle("Limiter failure.", err));
			if (quants[0] > config.SHORT_TERM_LIMIT
				|| quants[1] > config.LONG_TERM_LIMIT
			)
				return callback(Muggle('Reduce your speed.'));

			this.reserve(op, callback);
		});
	}
	reserve(op, cb) {
		redis.incr('postctr', function(err, num) {
			if (err)
				return cb(err);
			OPs[num] = op || num;
			cb(null, num);
		});
	}
	short_term_timeslot(when) {
		return Math.floor(when / (1000 * 60 * 5));
	}
	long_term_timeslot(when) {
		return Math.floor(when / (1000 * 60 * 60 * 24));
	}
	insert_post(msg, body, extra, callback) {
		if (config.READ_ONLY)
			return callback(Muggle("Can't post right now."));
		if (!this.board)
			return callback(Muggle("Can't retrieve board for posting."));
		const {num} = msg,
			op = msg.op || num,
			{ip, board} = extra,
			isThread = !msg.op;
		if (!num)
			return callback(Muggle("No post number."));
		else if (!ip)
			return callback(Muggle("No IP."));
		else if (!isThread && !validateOP(op, board)) {
			uncacheThread(op);
			return callback(Muggle('Thread does not exist.'));
		}

		const view = {
			ip, num, board,
			time: msg.time
		};
		const optPostFields = ['name', 'trip', 'email', 'auth', 'subject',
			'dice'];
		for (let field of optPostFields) {
			if (msg[field])
				view[field] = msg[field];
		}
		const boardKey = 'board:' + this.board;
		if (!isThread)
			view.op = op;

		if (extra.image_alloc) {
			msg.image = extra.image_alloc.image;
			if (isThread && msg.image.pinky)
				return callback(Muggle("Image is the wrong size."));
			delete msg.image.pinky;
		}

		const key = (isThread ? 'thread:' : 'post:') + num,
			m = redis.multi();
		m.incr(boardKey + ':postctr'); // must be first
		m.sadd('liveposts', key);

		hooks.trigger_sync('inlinePost', {
			src: msg,
			dest: view
		});

		if (msg.image) {
			if (isThread)
				view.imgctr = 1;
			else
				m.hincrby('thread:' + op, 'imgctr', 1);
			this.imageDuplicateHash(m, msg.image.hash, msg.num);
		}
		m.hmset(key, view);
		m.set(key + ':body', body);

		const dice = msg.dice;
		if (dice) {
			this.writeDice(m, dice, key);
			view.dice = dice;
		}
		const {links} = msg;
		if (links) {
			m.hmset(key + ':links', links);
			view.links = links;
			this.addBacklinks(m, num, op, links);
		}

		const etc = {augments: {}};
		if (isThread) {
			etc.cacheUpdate = [0, num, board];
			/* Rate-limit new threads */
			if (~['127.0.0.1', '::1'].indexOf(ip))
				m.setex(`ip:${ip}:throttle:thread`, config.THREAD_THROTTLE, op);
		}
		else {
			etc.cacheUpdate = [1, num, op];
			m.rpush(`thread:${op}:posts`, num);
		}

		// Denormalize for backlog
		view.nonce = msg.nonce;
		view.body = body;

		let bump;
		async.waterfall(
			[
				next => {
					if (!msg.image)
						return next();
					imager.commit_image_alloc(extra.image_alloc, next);
				},
				// Determine, if we need to bump the thread to the top of
				// the board
				next => {
					if (isThread) {
						bump = true;
						return next();
					}

					redis.llen(`thread:${op}:posts`, (err, res) => {
						if (err)
							return next(err);
						bump = !common.is_sage(view.email)
							&& res < config.BUMP_LIMIT[board];
						next();
					});
				},
				next => {
					if (ip) {
						const n = this.post_volume(view, body);
						if (n > 0)
							this.update_throughput(m, ip, view.time, n);

						// Only the client-private Reader() instances need
						// to embed mnemonics in-post. Doing that here would
						// publish it to everyone. Instead live mnemonic
						// updates are pushed through the 'mod' channel to
						// authenticated moderatots and up only.
						const mnemonic = admin.genMnemonic(ip);
						if (mnemonic)
							etc.augments.mod = {mnemonic};
					}

					// Don't parse dice, because they aren't stringified on
					// live publishes
					extract(view);
					if (bump)
						m.incr(boardKey + ':bumpctr');
					this._log(m, op, common.INSERT_POST, [view, bump], etc);
					m.exec(next);
				},
				(res, next) => {
					if (!bump)
						return next();
					redis.zadd(boardKey + ':threads', res[0], op, next);
				}
			],
			err => {
				if (err) {
					delete OPs[num];
					return callback(err);
				}
				msg.body = body;
				callback();
			}
		);
	}
	imageDuplicateHash(m, hash, num) {
		m.zadd('imageDups', Date.now() + (config.DEBUG ? 30000 : 3600000),
			`${num}:${hash}`);
	}
	writeDice(m, dice, key) {
		dice.forEach(die => m.lpush(key + ':dice', JSON.stringify(die)))
	}
	addBacklinks(m, num, op, links) {
		for (let targetNum in links) {
			// Check if post exists through cache
			if (!(targetNum in OPs))
				continue;
			const key = (targetNum in BOARDS ? 'thread' : 'post')
				+ `:${targetNum}:backlinks`;
			m.hset(key, num, op);
			this._log(m, links[targetNum], common.BACKLINK,
				[targetNum, num, op]);
		}
	}
	post_volume(view, body) {
		return (body ? body.length : 0) +
			(view ? (config.NEW_POST_WORTH || 0) : 0) +
			((view && view.image) ? (config.IMAGE_WORTH || 0) : 0);
	}
	update_throughput(m, ip, when, quant) {
		const key = `ip:${ip}:throttle:`,
			shortKey = key + this.short_term_timeslot(when),
			longKey = key + this.long_term_timeslot(when);
		m.incrby(shortKey, quant);
		m.incrby(longKey, quant);

		/* Don't want to use expireat in case of timezone trickery
		 or something dumb. (Really, UTC should be OK though...) */
		// Conservative expirations
		m.expire(shortKey, 10 * 60);
		m.expire(longKey, 2 * 24 * 3600);
	}
	_log(m, op, kind, msg, opts = {}) {
		msg = JSON.stringify(msg).slice(1, -1);
		msg = msg.length ? (kind + ',' + msg) : ('' + kind);
		winston.verbose("Log: " + msg);
		if (!op)
			throw new Error('No OP.');
		const key = 'thread:' + op;

		if (common.is_pubsub(kind)) {
			m.rpush(key + ':history', msg);
			m.hincrby(key, 'hctr', 1);
		}

		const opBit = op + ',',
			len = opBit.length + msg.length;
		msg = len + '|' + opBit + msg;

		if (!_.isEmpty(opts.augments))
			msg += JSON.stringify(opts.augments);
		m.publish(key, msg);
		m.publish('board:' + this.board, msg);
		if (opts.cacheUpdate)
			m.publish('cache', JSON.stringify(opts.cacheUpdate));
	}
	add_image(post, alloc, ip, callback) {
		const {num, op} = post;
		if (!op)
			return callback(Muggle("Can't add another image to an OP."));
		const {image} = alloc;
		if (!image.pinky)
			return callback(Muggle("Image is wrong size."));
		delete image.pinky;

		const key = 'post:' + num;
		async.waterfall([
			next => redis.exists(key, next),
			(exists, next) => {
				if (!exists)
					return next(Muggle("Post does not exist."));
				imager.commit_image_alloc(alloc, next);
			},
			next => {
				const m = redis.multi();
				this.imageDuplicateHash(m, image.hash, num);
				m.hmset(key, image);
				m.hincrby('thread:' + op, 'imgctr', 1);

				// Useless once image is commited
				delete image.hash;
				this._log(m, op, common.INSERT_IMAGE, [num, image]);

				const now = Date.now();
				this.update_throughput(m, ip, now,
					this.post_volume({image: true}));
				m.exec(next);
			}
		], callback);
	}
	append_post(post, tail, extra, cb) {
		const m = redis.multi(),
			key = (post.op ? 'post:' : 'thread:') + post.num;

		// Don't need to check .exists() thanks to client state
		m.append(key + ':body', tail);

		this.update_throughput(m, this.ident.ip, Date.now(),
			this.post_volume(null, tail));
		const {num} = post,
			op = post.op || num,
			{links, dice} = extra;
		if (links) {
			m.hmset(key + ':links', links);
			this.addBacklinks(m, num, op, links);
		}
		if (dice)
			this.writeDice(m, dice, key);

		this._log(m, op, common.UPDATE_POST, [num, tail, extra]);
		m.exec(cb);
	}
	finish_post(post, callback) {
		const m = redis.multi(),
			key = (post.op ? 'post:' : 'thread:') + post.num;

		/* Don't need to check .exists() thanks to client state */
		this.finish_off(m, key, post.body);
		this._log(m, post.op || post.num, common.FINISH_POST, [post.num]);
		m.exec(callback);
	}
	finish_off(m, key, body) {
		m.hset(key, 'body', body);
		m.del(key + ':body');
		m.srem('liveposts', key);
	}
	finish_all(callback) {
		redis.smembers('liveposts', (err, keys) => {
			if (err)
				return callback(err);
			async.forEach(keys, (key, cb) => {
				const m = redis.multi();
				m.get(key + ':body');
				const isPost = key.slice(0, 5) == 'post:';
				if (isPost)
					m.hget(key, 'op');
				m.exec((err, rs) => {
					if (err)
						return cb(err);
					const m = redis.multi();
					this.finish_off(m, key, rs[0]);
					const n = parseInt(key.match(/:(\d+)$/)[1]),
						op = isPost ? parseInt(rs[1], 10) : n;
					this._log(m, op, common.FINISH_POST, [n]);
					m.srem('liveposts', key);
					m.exec(cb);
				});
			}, callback);
		});
	}
	fetch_backlogs(watching, callback) {
		const combined = [];
		forEachInObject(watching,
			function (thread, cb) {
				if (thread == 'live')
					return cb();
				const key = `thread:${thread}:history`,
					sync = watching[thread];
				redis.lrange(key, sync, -1, function (err, log) {
					if (err)
						return cb(err);
					const prefix = thread + ',';
					for (let i = 0; i < log.length; i++) {
						combined.push(prefix + log[i]);
					}
					cb(null);
				});
			},
			function (errs) {
				callback(errs, combined);
			}
		);
	}
	check_thread_locked(op, callback) {
		redis.hexists('thread:' + op, 'locked', (err, lock) => {
			if (err)
				return callback(err);
			callback(lock && Muggle('Thread is locked.'));
		});
	}
	check_throttle(ip, callback) {
		// So we can spam new threads in debug mode
		if (config.DEBUG)
			return callback();
		redis.exists(`ip:${ip}:throttle:thread`, (err, exists) => {
			if (err)
				return callback(err);
			callback(exists && Muggle('Too soon.'));
		});
	}
	get_tag(page) {
		const keyBase = 'board:' + this.board,
			key = keyBase + ':threads',
			// -1 is for live pages and -2 is for catalog
			catalog = page === -2;
		if (page < 0)
			page = 0;
		let start, end;
		if (catalog) {
			// Read all threads
			start = 0;
			end = -1;
		}
		else {
			start = page * hot.THREADS_PER_PAGE;
			end = start + hot.THREADS_PER_PAGE - 1;
		}

		const m = redis.multi();
		m.zrevrange(key, start, end);
		m.zcard(key);

		// Used for building board eTags
		m.get(keyBase + ':postctr');
		m.exec((err, res) => {
			if (err)
				return this.emit('error', err);
			const nums = res[0];
			if (page > 0 && !nums.length)
				return this.emit('nomatch');
			this.emit('begin', res[1] || 0, res[2] || 0);
			const reader = new Reader(this.ident);

			// Proxy Reader events to Yakusoku
			reader.on('error', this.emit.bind(this, 'error'));
			reader.on('thread', this.emit.bind(this, 'thread'));
			reader.on('post', this.emit.bind(this, 'post'));
			reader.on('endthread', this.emit.bind(this, 'endthread'));
			this._get_each_thread(reader, 0, nums, catalog);
		});
	}
	_get_each_thread(reader, ix, nums, catalog) {
		if (!nums || ix >= nums.length) {
			this.emit('end');
			reader.removeAllListeners('endthread');
			reader.removeAllListeners('end');
			return;
		}

		const self = this;
		function next_please() {
			reader.removeListener('end', next_please);
			reader.removeListener('nomatch', next_please);
			self._get_each_thread(reader, ix+1, nums, catalog);
		}

		reader.on('end', next_please);
		reader.on('nomatch', next_please);
		reader.get_thread(nums[ix], {
			catalog,
			abbrev: hot.ABBREVIATED_REPLIES || 5
		});
	}
	// Purges all the thread's keys from the database and delete's all images
	// contained
	purge_thread(op, board, callback) {
		const key = 'thread:' + op,
			// Key suffixes that might or might not exist
			optional = ['links', 'backlinks', 'body', 'dice', 'mod'],
			keysToDel = [],
			filesToDel = [],
			nums = [];
		async.waterfall([
			// Confirm thread can be deleted
			next => redis.exists(key, next),
			(res, next) => {
				// Likely to happen, if interrupted mid-purge
				if (!res) {
					redis.zrem(`board:${board}:threads`, op);
					return callback();
				}

				// Get reply list
				redis.lrange(key + ':posts', 0, -1, next);
			},
			// Read all post hashes
			(posts, next) => {
				const m = redis.multi();
				for (let i = 0; i < posts.length; i++) {
					// Queue for removal from post cache
					nums.push(posts[i]);
					posts[i] = 'post:' + posts[i];
				}

				// Parse OP key like all other hashes. `res` will always be an
				// array, even if empty.
				posts.unshift(key);
				for (let key of posts) {
					m.hgetall(key);
					for (let suffix of optional) {
						m.exists(`${key}:${suffix}`);
					}
				}

				// A bit more complicated, because we need to pass two arguments
				// to the next function, to map the arrays
				m.exec((err, res) => next(err, res, posts));
			},
			// Populate key and file to delete arrays
			(res, posts, next) => {
				const imageTypes = ['src', 'thumb', 'mid'];
				for (let i = 0; i < res.length; i += 6) {
					const hash = res[i],
						key = posts[i / 6];
					if (!hash)
						continue;

					keysToDel.push(key);
					for (let o = 0; o < optional.length; o++) {
						if (res[i + o])
							keysToDel.push(`${key}:${optional[o]}`);
					}

					// Add images to delete list
					for (let type of imageTypes) {
						const image = hash[type];
						if (image)
							filesToDel.push(imager.media_path(type, image));
					}
				}
				next();
			},
			// Check for OP-only keys
			next => {
				const m = redis.multi(),
					OPKeys = [];
				for (let suffix of ['history', 'posts']) {
					OPKeys.push(`${key}:${suffix}`);
				}
				for (let key of OPKeys) {
					m.exists(key);
				}
				m.exec((err, res) => next(err, res, OPKeys));
			},
			(res, OPKeys, next) => {
				for (let i = 0; i < res.length; i++) {
					if (res[i])
						keysToDel.push(OPKeys[i]);
				}

				// Delete all keys
				const m = redis.multi();
				for (let key of keysToDel) {
					m.del(key);
				}
				m.exec(next);
			},
			(res, next) =>
				// Delete all images
				async.each(filesToDel,
					(file, cb) =>
						fs.unlink(file, err => cb(err)),
					err => next(err)),
			next => {
				const m = redis.multi();
				m.zrem(`board:${board}:threads`, op, next);
				// Clear thread and post numbers from caches on all slaves
				m.publish('cache', JSON.stringify([2, +op]));
				m.exec(next);
			}
		], callback);
	}
	get_banner(cb) {
		redis.get('banner:info', cb);
	}
	set_banner(message, cb) {
		redis.set('banner:info', message, err => {
			if (err)
				return cb(err);

			// Dispatch new banner
			const m = redis.multi();
			this._log(m, 0, common.UPDATE_BANNER, [message]);
			m.exec(cb);
		});
	}
	modHandler(kind, nums, cb) {
		if (this.isContainmentBoard)
			return false;

		// Group posts by thread for live publishes to the clients
		const threads = {};
		for (let num of nums) {
			const op = OPs[num];
			if (!(op in threads))
				threads[op] = [];
			threads[op].push(num);
		}
		async.forEachOf(threads, (nums, op, cb) =>
			this.handleModeration(nums, op, kind, cb),
		cb);
		return true;
	}
	handleModeration(nums, op, kind, cb) {
		const opts = this.moderationSpecs[kind],
			{props, check, persist} = opts,
			keys = [];
		async.waterfall([
			// Read required post properties from redis
			next => {
				const m = redis.multi();
				for (let num of nums) {
					const key = postKey(num, op);
					keys.push(key);
					const command = props.slice();
					command.unshift(key);
					m.hmget(command);
				}
				m.exec(next);
			},
			(res, next) => {
				const m = redis.multi();
				for (let i = 0; i < res.length; i++) {
					// Check if post is eligible for moderation action
					if (check(res[i]))
						continue;

					// Persist to redis
					const key = keys[i],
						num = nums[i],
						msg = [num];
					persist(m, key, msg);

					// Live publish
					this.logModeration(m, {key, op, kind, num, msg});
				}
				m.exec(next);
			}
		], cb);
	}
	logModeration(m, opts) {
		const time = Date.now();
		const info = {
			time,
			num: opts.num,
			op: opts.op,
			ident: this.hideEmail(),
			kind: opts.kind
		};

		const stringified = JSON.stringify(info);
		m.lpush(opts.key + ':mod', stringified);
		m.zadd('modLog', time, stringified);

		this._log(m, opts.op, opts.kind, opts.msg, {
			augments: {
				// Duplicating channels for now. Will add some differences later
				auth: info,
				mod: info
			}
		});
	}
	// Abstract the email as to not reveal it to all staff
	hideEmail() {
		return config.staff[this.ident.auth][this.ident.email];
	}
	// Bans are somewhat more complicated and do not fit into the common
	// modHandler() pathway. Plenty of duplication here, because of that.
	ban(msg, cb) {
		const [num, days, hours, minutes, reason, display] = msg,
			now = Date.now(),
			till = ((days * 24 + hours) * 60 + minutes) * 60 * 1000 + now,
			op = OPs[num],
			key = `${op === num ? 'thread' : 'post'}:${num}`;
		async.waterfall([
			next => redis.hget(key, 'ip', next),
			(ip, next) => {
				const info = {
					num, op, till, reason,
					time: now,
					ident: this.hideEmail(),
					kind: common.BAN
				};

				// Publically display a ban to all users, if display option
				// set. Otherwise only published to staff and others get a
				// useless 0, for compatability with the current pub/sub
				// pathway.
				const m = redis.multi();
				this._log(m, op, common.BAN, [display ? num : 0], {
					augments: {
						auth: info,
						mod: info
					},
					cacheUpdate: [3]
				});

				m.lpush(key + ':mod', JSON.stringify(info));

				// Mnemonic needed only for logging
				info.mnemonic = admin.genMnemonic(ip);
				m.zadd('modLog', now, JSON.stringify(info));

				// XXX: The ban duration in the sorted set will that of the
				// most recently applied ban to this IP.
				m.zadd('bans', till, ip);
				if (display)
					m.hset(key, 'banned', 1);
				m.exec(next);
			}
		], cb);
	}
	// We don't pass the banned IPs to clients, so now we have to fetch all
	// the banned IPs, generate a mnemonic for each and remove the
	// corresponding one, if any.
	unban(mnemonic, cb) {
		async.waterfall([
			next => redis.zrange('bans', 0, -1, next),
			(bans, next) => {
				let match;
				for (let ip of bans) {
					if (admin.genMnemonic(ip) === mnemonic) {
						match = ip;
						break;
					}
				}

				if (!match)
					return cb();
				const m = redis.multi();
				m.zrem('bans', match);
				m.publish('cache', '[3]');

				const time = Date.now();
				m.zadd('modLog', time, JSON.stringify({
					time,
					ident: this.hideEmail(),
					kind: common.UNBAN
				}));

				m.exec(next);
			}
		], cb);
	}
}

// Options for various moderation actions. No class properties in ES6, so
// keep them here.
Yakusoku.prototype.moderationSpecs = {
	[common.SPOILER_IMAGES]: {
		props: ['src', 'spoiler'],
		check(res) {
			// No image or already spoilt
			return !res[0] || !!res[1];
		},
		persist(m, key, msg) {
			const spoiler = common.pick_spoiler(-1).index;
			m.hset(key, 'spoiler', spoiler);
			msg.push(spoiler);
		}
	},
	[common.DELETE_IMAGES]: {
		props: ['src', 'imgDeleted'],
		check(res) {
			// No image or already hidden
			return !res[0] || !!res[1];
		},
		persist(m, key) {
			m.hset(key, 'imgDeleted', 1);
		}
	},
	[common.DELETE_POSTS]: {
		props: ['deleted'],
		check(res) {
			return !!res[0];
		},
		persist(m, key) {
			m.hset(key, 'deleted', 1);
		}
	},
	[common.LOCK_THREAD]: {
		props: ['locked'],
		check(res) {
			return !!res[0];
		},
		persist(m, key) {
			m.hset(key, 'locked', 1);
		}
	},
	[common.UNLOCK_THREAD]: {
		props: ['locked'],
		check(res) {
			return !res[0];
		},
		persist(m, key) {
			m.hdel(key, 'locked');
		}
	}
};

exports.Yakusoku = Yakusoku;

/* LURKERS */

class Reader extends events.EventEmitter {
	constructor(ident) {
		// Call the EventEmitter's constructor
		super()
        this.canSeeMnemonics = ident.auth === 'dj'
            || common.checkAuth('moderator', ident)
        this.canSeeModeration = common.checkAuth('janitor', ident)
	}
	get_thread(num, opts) {
		const key = 'thread:' + num;
		redis.hgetall(key, (err, pre_post) => {
			if (err)
				return this.emit('error', err);
			if (!pre_post || !this.formatPost(pre_post))
				return this.emit('nomatch');

			this.emit('begin', pre_post);

			let nums, opPost,
				total = 0;
			const abbrev = opts.abbrev || 0;
			async.waterfall(
				[
					next => this.with_body(key, pre_post, next),
					(fullPost, next) => {
						opPost = fullPost;
						const m = redis.multi(),
							postsKey = key + ':posts';

						// order is important!
						m.lrange(postsKey, -abbrev, -1);

						// The length of the above array is limited by the
						// amount of posts we are retrieving. A total number
						// of posts is quite useful.
						m.llen(postsKey);
						this.getExtras(m, key);
						if (abbrev)
							m.llen(postsKey);
						m.exec(next);
					},
					(rs, next) => {
						// get results in the same order as before
						nums = rs.shift();
						// NOTE: these are only the displayed replies, not
						// all of them
						opPost.replies = nums || [];
						opPost.replyctr = parseInt(rs.shift(), 10) || 0;
						this.parseExtras(rs, opPost);
						if (abbrev)
							total += parseInt(rs.shift(), 10);

						opPost.omit = Math.max(total - abbrev, 0);
						opPost.hctr = parseInt(opPost.hctr, 10);

						// So we can pass a thread number on `endthread`
						// emission
						opts.op = opPost.num;
						next();
					}
				],
				err => {
					if (err)
						return this.emit('error', err);
					this.emit('thread', opPost);
					if (opts.catalog)
						return this.emit('end');
					this._get_each_reply(0, nums, opts);
				}
			);
		});
	}
	getExtras(m, key) {
		m.hgetall(key + ':links');
		m.hgetall(key + ':backlinks');
		m.lrange(key + ':dice', 0, -1);
		if (this.canSeeModeration)
			m.lrange(key + ':mod', 0, -1);
	}
	parseExtras(res, post) {
		for (let key of ['links', 'backlinks']) {
			const prop = res.shift();
			if (prop)
				post[key] = prop;
		}
		this.parseStringList(res, 'dice', post);
		if (this.canSeeModeration)
			this.parseStringList(res, 'mod', post);
	}
	parseStringList(res, prop, post) {
		const list = res.shift();
		if (!list.length)
			return;

		// Reverse to preserve chronological order
		post[prop] = destringifyList(list.reverse())
	}
	formatPost(post) {
		if (!this.canSeeModeration) {
			if (post.deleted)
				return false;
			if (post.imgDeleted)
				imager.deleteImageProps(post);
		}
		if (this.canSeeMnemonics) {
			const mnemonic = admin.genMnemonic(post.ip);
			if (mnemonic)
				post.mnemonic = mnemonic;
		}
		extract(post);
		return true;
	}
	_get_each_reply(ix, nums, opts) {
		if (!nums || ix >= nums.length) {
			this.emit('endthread', opts.op);
			this.emit('end');
			return;
		}
		const num = parseInt(nums[ix], 10);
		this.get_post('post', num, (err, post) => {
			if (err)
				return this.emit('error', err);
			if (post)
				this.emit('post', post);
			this._get_each_reply(ix + 1, nums, opts);
		});
	}
	get_post(kind, num, cb) {
		const key = `${kind}:${num}`;
		async.waterfall([
			next => {
				const m = redis.multi();
				m.hgetall(key);
				this.getExtras(m, key);
				m.exec(next);
			},
			(data, next) => {
				const pre_post = data.shift();
				this.parseExtras(data, pre_post);
				if (_.isEmpty(pre_post))
					return next();

				pre_post.num = num;
				if (kind === 'post')
					pre_post.op = parseInt(pre_post.op, 10);
				this.with_body(key, pre_post, next);
			},
			(post, next) => {
				if (post) {
					if (!this.formatPost(post))
						post = null;
				}
				next(null, post);
			}
		],	cb);
	}
	with_body(key, post, callback) {
		if (post.body !== undefined)
			return callback(null, post);

		redis.get(key + ':body', function(err, body) {
			if (err)
				return callback(err);
			if (body !== null) {
				post.body = body;
				post.editing = true;
				return callback(null, post);
			}

			// Race condition between finishing posts
			redis.hget(key, 'body', function(err, body) {
				if (err)
					return callback(err);
				post.body = body;
				callback(null, post);
			});
		});
	}
	// Wrapper for retrieving individual posts separatly from threads
	singlePost(num, ident, cb) {
		const info = postInfo(num),
			key = info.isOP ? 'thread' : 'post';
		if (!caps.can_access_board(ident, info.board))
			return cb();
		this.get_post(key, num, function(err, post) {
			if (err || !post)
				return cb();
			cb(post);
		})
	}
}
exports.Reader = Reader;

// Retrieve post info from cache
function postInfo(num) {
	const isOP = num in BOARDS;
	return {
		isOP,
		board: isOP ? BOARDS[num] : BOARDS[OPs[num]]
	};
}
exports.postInfo = postInfo;

/* HELPERS */

function is_board (board) {
	return config.BOARDS.indexOf(board) >= 0;
}
exports.is_board = is_board;

// Format post hash for passing to renderer and clients
function extract(post) {
	// Only used internally and should not be exported to clients
	for (let key of ['ip', 'deleted', 'imgDeleted']) {
		delete post[key];
	}

	for (let key of ['num', 'time']) {
		post[key] = parseInt(post[key], 10);
	}
	imager.nestImageProps(post);
}

function postKey(num, op) {
	return `${op == num ? 'thread' : 'post'}:${num}`;
}

function destringifyList(list) {
	const parsed = [];
	for (let i = 0; i < list.length; i++) {
		// Stop gap fix until database migration
		try {
			parsed[i] = JSON.parse(list[i]);
		}
		catch (err) {
			winston.error(`Failed to destringify list: ${list.toString()}:`,
				err)
			return []
		}
	}
	return parsed;
}
exports.destrigifyList = destringifyList;

function forEachInObject(obj, f, callback) {
	var total = 0, complete = 0, done = false, errors = [];
	function cb(err) {
		complete++;
		if (err)
			errors.push(err);
		if (done && complete == total)
			callback(errors.length ? errors : null);
	}
	for (let k in obj) {
		if (obj.hasOwnProperty(k)) {
			total++;
			f(k, cb);
		}
	}
	done = true;
	if (complete == total)
		callback(errors.length ? errors : null);
}


text:
// Copyright (C) 2012 iwg molw5
// For conditions of distribution and use, see copyright notice in COPYING

#pragma once

#include <framework/serializable/base_types.hpp>
#include <framework/serializable/utility/interface.hpp>
#include <framework/serializable/mutator_type.hpp>

namespace framework
{
    namespace serializable
    {
        namespace detail
        {
            template <typename T, typename Enabler = void>
            struct is_value_type_impl;

            template <typename T, typename Enabler = void>
            struct is_default_value_serializable_impl;
        }

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        *
        * Provides a common interface used to define the types required to properly
        * interpret a value type.  Value types replace an object's member variables
        * in \c serializable types - \c Implementation is inherited by the derived
        * type and associated with the unique identifier \c Name - see \c serializable
        * for more information.
        *
        * The default specification provided for this type serializes the field
        * \c Name of the input/output object using the specification provided in
        * \c Specification, see the specialization of serializable_default_specification
        * for more information.  Derived types may suppress this default by setting
        * \c Default to false, forcing the generation of a compile time error if an
        * appropriate \c serializable_specification specialization is not found.
        *
        * \tparam Name unique identifying typename
        * \tparam Specification specification used to serialize the value
        * \tparam Implementation implementation required by the value
        */
        template <
            typename Name,
            typename Specification,
            template <typename> class Interface,
            bool Default = true>
#ifndef DOXYGEN
        struct value_type;
#else
        struct value_type
        {
        };
#endif

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        * \brief Determines if \c T is a value type.
        *
        * Type trait testing whether or not T is a \c value_type.
        * Inherits std::true_type or std::false_type.
        */
        template <typename T>
        struct is_value_type :
            std::conditional <
                detail::is_value_type_impl <T>::value,
                std::true_type,
                std::false_type
            >::type
        {
        };

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        * \brief Get name.
        *
        * Retrieves a value type's name, storing the result in \c type.
        *
        * \pre is_value_type <T>::value == true
        */
        template <typename T>
        struct get_value_name
        {
            using type =
                typename std::enable_if <
                    is_value_type <T>::value,
                    typename T::value_name
                >::type;
        };

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        * \brief Get specification.
        *
        * Retrieves a value type's specification, storing the result in \c type.
        *
        * \pre is_value_type <T>::value == true
        */
        template <typename T>
        struct get_value_specification
        {
            using type =
                typename std::enable_if <
                    is_value_type <T>::value,
                    typename T::value_specification
                >::type;
        };

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        * \brief Get implementation.
        *
        * Instantiates a value type's implementation with the parameter \c U,
        * storing the result in \c type.
        *
        * \pre is_value_type <T>::value == true
        */
        template <typename T, typename U>
        struct get_value_implementation
        {
            using type =
                typename std::enable_if <
                    is_value_type <T>::value,
                    typename T::template value_implementation <U>
                >::type;
        };

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        *
        * Type trait testing whether or not T is a default serializable \c value_type.
        * Derives from std::true_type or std::false_type.
        *
        * \note
        * The following relationships always hold
        * \code
        * !is_default_value_serializable <T>::value || is_value_type <T>::value
        * !is_default_value_serializable <T>::value || is_default_serializable <T>::value
        * \endcode
        */
        template <typename T>
        struct is_default_value_serializable :
            std::conditional <
                detail::is_default_value_serializable_impl <T>::value,
                std::true_type,
                std::false_type
            >::type
        {
        };

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        *
        * Required specialization of is_default_serializable.
        */
        template <typename T>
        struct is_default_serializable <T,
            typename std::enable_if <
                is_default_value_serializable <T>::value,
                void
            >::type> : std::true_type
        {
        };

        /**
        * \headerfile value_type.hpp <framework/serializable/value_type.hpp>
        * \brief Default \c value_type specification.
        *
        * Serializes the field identified by
        * \code
        * get_value_name <T>::type
        * \endcode
        * using the specification given by
        * \code
        * get_value_specification <T>::type
        * \endcode
        * The specification is assumed to identify the field's underlying value type, as
        * specified by
        * \code
        * typename type_extractor <typename get_value_specification <T>::type>::type
        * \endcode
        *
        * \note
        * The methods provided here access the implementation's method directly though
        * the reference provided by \c interface.
        */
        template <typename T>
        struct serializable_default_specification <T,
            typename std::enable_if <
                is_default_value_serializable <T>::value,
                void
            >::type>
        {
            /**
            * \note
            * The field's underlying value type must be default constructable with an
            * associated implementation supporting move semantics through it's set method.
            *
            * \post the call succeeds or out is not altered
            * \param in input stream
            * \param out output container
            * \return true on success, false on failure
            */
            template <typename Input, typename Output>
            static bool read (Input& in, Output& out)
            {
                value_type value;
                if (!serializable_specification <value_specification>::read(in, value))
                    return false;

                interface <value_name> (out).set(std::move(value));
                return true;
            }

            /**
            * \param in input container
            * \param out output stream
            * \return true on success, false on failure
            */
            template <typename Input, typename Output>
            static bool write (Input const& in, Output& out)
            {
                auto const& value = interface <value_name> (in).get();
                return serializable_specification <value_specification>::write(value, out);
            }

            private:
                using value_name =
                    typename get_value_name <T>::type;

                using value_specification =
                    typename get_value_specification <T>::type;

                using value_type =
                    typename type_extractor <value_specification>::type;
        };
    }
}

#include <framework/serializable/value_type.inl>


text:
<?php

declare(strict_types = 1);

namespace GhostSt\CoreBundle\Validator\Constraints;

use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Role validator
 */
class RoleValidator extends ConstraintValidator
{
    /**
     * Translator
     *
     * @var TranslatorInterface
     */
    protected $translator;

    /**
     * Constructor
     *
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Validates value
     *
     * @param mixed      $value
     * @param Constraint $constraint
     *
     * @return void
     */
    public function validate($value, Constraint $constraint): void
    {
        if (null === $value) {
            $this->context
                ->buildViolation($this->translator->trans('validator.constraints.role.invalid'))
                ->addViolation();
        }
    }
}


text:
package com.youdevise.fbplugins.deprecate3rdparty;

public class HasADeprecatedClassAsAMethodParameter {

	public HasADeprecatedClassAsAMethodParameter(MyDeprecatedClass deprecated) {

	}

}


text:
tinyMCE.addToLang('',{
insert_advhr_desc : 'Вставить / редактировать горизонтальный разделитель',
insert_advhr_width : 'Ширина',
insert_advhr_size : 'Высота',
insert_advhr_noshade : 'Без тени'
});


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Runtime](./puppeteer.protocol.runtime.md) > [ObjectPreview](./puppeteer.protocol.runtime.objectpreview.md) > [subtype](./puppeteer.protocol.runtime.objectpreview.subtype.md)

## Protocol.Runtime.ObjectPreview.subtype property

Object subtype hint. Specified for `object` type values only. (ObjectPreviewSubtype enum)

<b>Signature:</b>

```typescript
subtype?: ('array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error');
```


text:
class FindPropertyForPosition
  def initialize(position:)
    @position = position
  end

  def call
    property
  end

  private

  def property
    @property ||= Property.find_by(position: @position)
  end
end


text:
package org.springframework.osgi.samples.simpleservice.impl;

import org.springframework.osgi.samples.simpleservice.MyService;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

/**
 * Integration test the service locally (outside of OSGi).
 * Use AbstractOsgiTests and a separate integration test project
 * for testing inside of OSGi.
 *
 * @author Adrian Colyer
 */
public class MyServiceIntegrationTest extends AbstractDependencyInjectionSpringContextTests {

	private MyService service;

	protected String[] getConfigLocations() {
		return new String[] {"META-INF/spring/simpleservice.xml"};
	}

	public void testSimpleService() {
		assertEquals("simple service at your service",
				service.stringValue());
	}

	public void setService(MyService service) {
		this.service = service;
	}

}


text:
package net.teslaworks.visualizer;

import java.awt.Component;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;

import javax.swing.JDialog;
import javax.swing.JFileChooser;

public class FileChooser {
	private File file;
	public void choose() {
        JFileChooser fc = new JFileChooser() {
        	private static final long serialVersionUID = 1170852534375941586L;
            protected JDialog createDialog(Component parent)
                    throws HeadlessException {
                JDialog dialog = super.createDialog(parent);
                // config here as needed - just to see a difference
                dialog.setLocationByPlatform(true);
                // might help - can't know because I can't reproduce the problem
                dialog.setAlwaysOnTop(true);
                return dialog;
            }

        };
        int retValue = fc.showOpenDialog(null);
        if (retValue == JFileChooser.APPROVE_OPTION){
            file = fc.getSelectedFile();
        } else {
            file = null;
        }
    }
	public File getFile() {
		return file;
	}
	public String getFilename() throws IOException {
		return file.getPath();
	}
}


text:
package info.naiv.lab.java.jmt;

import javax.annotation.concurrent.ThreadSafe;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;

/**
 *
 * @author enlo
 * @param <T>
 */
@EqualsAndHashCode(callSuper = false)
@ToString
@ThreadSafe
public class ThreadLocalHolder<T> extends ThreadLocal<T> implements Holder<T> {

    private final Class<? extends T> clazz;

    public ThreadLocalHolder(@NonNull Class<? extends T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T getContent() {
        return get();
    }

    @Override
    public Class<? extends T> getContentType() {
        return clazz;
    }

}