text:
[![Dependency Status](https://gemnasium.com/pacso/paperclip-wav-mp3.png)](https://gemnasium.com/pacso/paperclip-wav-mp3)

Paperclip processor to convert .wav files to .mp3 using ffmpeg

## Requirements

### Paperclip

This is a processor written for the quite excellent [Paperclip](https://github.com/thoughtbot/paperclip) gem by [ThoughtBot](https://github.com/thoughtbot). You will need to be using Paperclip to use it.

### FFmpeg

FFmpeg is used to convert WAV audio to MP3. It must be installed within your environment and available on your PATH.

#### OS X

If you're developing on OS X, you can install FFmpeg using homebrew:

```
brew install ffmpeg
```

#### Ubuntu Linux

I've not tested on other linux distributions, but you can install FFmpeg and the required codecs with the following:

```
apt-get install ffmpeg libavcodec-extra-52 libavdevice-extra-52 libavfilter-extra-0 libavformat-extra-52 libavutil-extra-49 libpostproc-extra-51 libswscale-extra-0
```

## Installation

This processor is distributed as a gem, which is how it should be used in your app.

Include the gem in your Gemfile:

```
gem 'paperclip-wav-mp3', '~> 0.1'
```

Once you've installed the gem, update the model which uses Paperclip to attach audio to add the processor:

```
class Voicemail < ActiveRecord::Base
  has_attached_file :audio,
                    styles: { mp3: {} },
                    processors: [:ffmpeg_wav_to_mp3]
end
```

Now, when you attach a new `WAV` audio file, you will also create an `MP3` version.

To generate the missing `MP3` versions for files you've already attached you can use this paperclip rake task:

```
rake paperclip:refresh:missing_styles
```

## Contributing

Feel free to raise any issues you have [here](https://github.com/pacso/paperclip-wav-mp3/issues), or if you're feeling generous then just send a [pull request](https://github.com/pacso/paperclip-wav-mp3/compare/) with your new feature/bugfix.

## License

Copyright (c) 2014 Jon Pascoe.

This is free software and may be redistributed under the terms and conditions of The MIT License (MIT). Full details are available in the LICENSE file.


text:
#ifndef MITKHOTSPOTCALCULATOR_H
#define MITKHOTSPOTCALCULATOR_H

#include <itkObject.h>
#include <mitkImage.h>
#include <itkImage.h>
#include <itkTimeStamp.h>
#include <stdexcept>
#include <MitkImageStatisticsExports.h>
#include <mitkImageTimeSelector.h>
#include <mitkMaskGenerator.h>

namespace mitk
{
/**
     * @brief The HotspotMaskGenerator class is used when a hotspot has to be found in an image. A hotspot is
     * the region of the image where the mean intensity is maximal (=brightest spot). It is usually used in PET scans.
     * The identification of the hotspot is done as follows: First a cubic (or circular, if image is 2d)
     * mask of predefined size is generated. This mask is then convolved with the input image (in fourier domain).
     * The maximum value of the convolved image then corresponds to the hotspot.
     * If a maskGenerator is set, only the pixels of the convolved image where the corresponding mask is == @a label
     * are searched for the maximum value.
     */
    class MITKIMAGESTATISTICS_EXPORT HotspotMaskGenerator: public MaskGenerator
    {
    public:
        /** Standard Self typedef */
        typedef HotspotMaskGenerator                Self;
        typedef MaskGenerator                       Superclass;
        typedef itk::SmartPointer< Self >           Pointer;
        typedef itk::SmartPointer< const Self >     ConstPointer;

        /** Method for creation through the object factory. */
        itkNewMacro(Self)

        /** Runtime information support. */
        itkTypeMacro(HotspotMaskGenerator, MaskGenerator)

        /**
        @brief Set the input image. Required for this class
         */
        void SetInputImage(mitk::Image::Pointer inputImage);

        /**
        @brief Set a mask (can be nullptr if no mask is desired)
         */
        void SetMask(MaskGenerator::Pointer mask);

        /**
        @brief Set the radius of the hotspot (in MM)
         */
        void SetHotspotRadiusInMM(double radiusInMillimeter);

        const double& GetHotspotRadiusinMM() const;

        /**
        @brief Define whether the hotspot must be completely inside the image. Default is true
         */
        void SetHotspotMustBeCompletelyInsideImage(bool hotspotCompletelyInsideImage);

        bool GetHotspotMustBeCompletelyInsideImage() const;

        /**
        @brief If a maskGenerator is set, this detemines which mask value is used
         */
        void SetLabel(unsigned short label);

        /**
        @brief Computes and returns the hotspot mask. The hotspot mask has the same size as the input image. The hopspot has value 1, the remaining pixels are set to 0
         */
        mitk::Image::Pointer GetMask();

        /**
        @brief Returns the image index where the hotspot is located
         */
        vnl_vector<int> GetHotspotIndex();

        /**
        @brief Returns the index where the convolution image is minimal (darkest spot in image)
         */
        vnl_vector<int> GetConvolutionImageMinIndex();

        /**
         * @brief SetTimeStep is used to set the time step for which the mask is to be generated
         * @param timeStep
         */
        void SetTimeStep(unsigned int timeStep);

    protected:
        HotspotMaskGenerator();

        ~HotspotMaskGenerator();

        class ImageExtrema
        {
        public:
          bool Defined;
          double Max;
          double Min;
          vnl_vector<int> MaxIndex;
          vnl_vector<int> MinIndex;

          ImageExtrema()
            :Defined(false)
            ,Max(itk::NumericTraits<double>::min())
            ,Min(itk::NumericTraits<double>::max())
          {
          }
        };

    private:
        /** \brief Returns size of convolution kernel depending on spacing and radius. */
        template <unsigned int VImageDimension>
        itk::Size<VImageDimension>
          CalculateConvolutionKernelSize(double spacing[VImageDimension], double radiusInMM);

        /** \brief Generates image of kernel which is needed for convolution. */
        template <unsigned int VImageDimension>
        itk::SmartPointer< itk::Image<float, VImageDimension> >
          GenerateHotspotSearchConvolutionKernel(double spacing[VImageDimension], double radiusInMM);

        /** \brief Convolves image with spherical kernel image. Used for hotspot calculation.   */
        template <typename TPixel, unsigned int VImageDimension>
        itk::SmartPointer< itk::Image<TPixel, VImageDimension> >
          GenerateConvolutionImage( const itk::Image<TPixel, VImageDimension>* inputImage );

        /** \brief Fills pixels of the spherical hotspot mask. */
        template < typename TPixel, unsigned int VImageDimension>
        void
          FillHotspotMaskPixels( itk::Image<TPixel, VImageDimension>* maskImage,
          itk::Point<double, VImageDimension> sphereCenter,
          double sphereRadiusInMM);

        /** \brief */
        template <typename TPixel, unsigned int VImageDimension>
        void
          CalculateHotspotMask(itk::Image<TPixel, VImageDimension>* inputImage,
                               typename itk::Image<unsigned short, VImageDimension>::Pointer maskImage,
                               unsigned int label);

        template <typename TPixel, unsigned int VImageDimension  >
        ImageExtrema CalculateExtremaWorld( const itk::Image<TPixel, VImageDimension>* inputImage,
                                                        typename itk::Image<unsigned short, VImageDimension>::Pointer maskImage,
                                                        double neccessaryDistanceToImageBorderInMM,
                                                        unsigned int label);

        bool IsUpdateRequired() const;

        HotspotMaskGenerator(const HotspotMaskGenerator &);
        HotspotMaskGenerator & operator=(const HotspotMaskGenerator &);

        MaskGenerator::Pointer m_Mask;
        mitk::Image::Pointer m_internalImage;
        itk::Image<unsigned short, 2>::Pointer m_internalMask2D;
        itk::Image<unsigned short, 3>::Pointer m_internalMask3D;
        double m_HotspotRadiusinMM;
        bool m_HotspotMustBeCompletelyInsideImage;
        bool m_HotspotParamsChanged;
        unsigned short m_Label;
        vnl_vector<int> m_ConvolutionImageMinIndex, m_ConvolutionImageMaxIndex;
        unsigned long m_InternalMaskUpdateTime;
    };
}
#endif // MITKHOTSPOTCALCULATOR

redpajama_set_name: RedPajamaGithub


text:
// Generated by CoffeeScript 1.4.0
(function() {
  var AccessDenied, AccessDeniedUserRequired, ClearPassportSession, NotFound, UnprocessableEntity,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  exports.NotFound = NotFound = (function(_super) {

    __extends(NotFound, _super);

    function NotFound(path) {
      this.name = 'NotFound';
      this.status = 404;
      if (path) {
        Error.call(this, "Cannot find " + path);
        this.path = path;
      } else {
        Error.call(this, "Not Found");
      }
      Error.captureStackTrace(this, arguments.callee);
    }

    return NotFound;

  })(Error);

  exports.ClearPassportSession = ClearPassportSession = (function(_super) {

    __extends(ClearPassportSession, _super);

    function ClearPassportSession(path) {
      this.path = path;
      this.name = 'ClearPassportSession';
      this.message = "Could not find user";
      this.status = 401;
      Error.call(this, this.message);
      Error.captureStackTrace(this, arguments.callee);
    }

    return ClearPassportSession;

  })(Error);

  exports.AccessDenied = AccessDenied = (function(_super) {

    __extends(AccessDenied, _super);

    function AccessDenied(path) {
      this.path = path;
      this.name = 'AccessDenied';
      this.message = "You cannot access the resource " + this.path;
      this.status = 401;
      Error.call(this, this.message);
      Error.captureStackTrace(this, arguments.callee);
    }

    return AccessDenied;

  })(Error);

  exports.AccessDeniedUserRequired = AccessDeniedUserRequired = (function(_super) {

    __extends(AccessDeniedUserRequired, _super);

    function AccessDeniedUserRequired(path) {
      this.path = path;
      this.name = 'AccessDenied';
      this.message = "You cannot access the resource " + this.path + " because a user is required.";
      this.status = 401;
      Error.call(this, this.message);
      Error.captureStackTrace(this, arguments.callee);
    }

    return AccessDeniedUserRequired;

  })(Error);

  exports.UnprocessableEntity = UnprocessableEntity = (function(_super) {

    __extends(UnprocessableEntity, _super);

    function UnprocessableEntity(parameter) {
      this.parameter = parameter;
      this.name = 'UnprocessableEntity';
      this.message = "At least one parameter is missing or invalid " + this.parameter;
      this.status = 422;
      Error.call(this, this.message);
      Error.captureStackTrace(this, arguments.callee);
    }

    return UnprocessableEntity;

  })(Error);

  /*
  Check if we have an error, indicating not found if @see item is null
  @example
  return if errors.isError(...)
  */

  exports.isError = function(err, item, itemUrl, next) {
    if (err) {
      next(err);
      return true;
    }
    if (!item) {
      next(new exports.NotFound(itemUrl));
      return true;
    }
    return false;
  };

}).call(this);


text:
package org.citydb.gui.plugin.internal;

import org.citydb.config.Config;
import org.citydb.config.ProjectConfig;
import org.citydb.config.gui.GuiConfig;
import org.citydb.gui.plugin.util.DefaultPreferencesComponent;

public abstract class InternalPreferencesComponent extends DefaultPreferencesComponent {
	protected final Config config;

	public InternalPreferencesComponent(Config config) {
		this.config = config;
	}

	public void resetSettings() {
		ProjectConfig projectConfig = config.getProjectConfig();
		GuiConfig guiConfig = config.getGuiConfig();

		config.setProjectConfig(new ProjectConfig());
		config.setGuiConfig(new GuiConfig());
		loadSettings();

		config.setProjectConfig(projectConfig);
		config.setGuiConfig(guiConfig);
	}
}


text:
import { Inject, Injectable, Optional } from '@angular/core';
import {
    MatMomentDateAdapterOptions,
    MAT_MOMENT_DATE_ADAPTER_OPTIONS,
    MomentDateAdapter
} from '@angular/material-moment-adapter';
import { MAT_DATE_LOCALE } from '@angular/material/core';

import { LangChangeEvent, TranslateService } from '@ngx-translate/core';

/**
 * A custom DateAdapter for the datetimepicker in the config. Uses MomentDateAdapter for localisation.
 * Is needed to subscribe to language changes
 */
@Injectable()
export class OpenSlidesDateAdapter extends MomentDateAdapter {
    public constructor(
        translate: TranslateService,
        @Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string,
        @Optional() @Inject(MAT_MOMENT_DATE_ADAPTER_OPTIONS) _options?: MatMomentDateAdapterOptions
    ) {
        super(dateLocale, _options);
        // subscribe to language changes to change localisation of dates accordingly
        // DateAdapter seems not to be a singleton so we do that in this subclass instead of app.component
        this.setLocale(translate.currentLang);
        translate.onLangChange.subscribe((e: LangChangeEvent) => {
            this.setLocale(e.lang);
        });
    }
}


text:
package check

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"math/rand"
	"os"
	"path"
	"path/filepath"
	"reflect"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
)

// -----------------------------------------------------------------------
// Internal type which deals with suite method calling.

const (
	fixtureKd = iota
	testKd
)

type funcKind int

const (
	succeededSt = iota
	failedSt
	skippedSt
	panickedSt
	fixturePanickedSt
	missedSt
)

type funcStatus int

// A method value can't reach its own Method structure.
type methodType struct {
	reflect.Value
	Info reflect.Method
}

func newMethod(receiver reflect.Value, i int) *methodType {
	return &methodType{receiver.Method(i), receiver.Type().Method(i)}
}

func (method *methodType) PC() uintptr {
	return method.Info.Func.Pointer()
}

func (method *methodType) suiteName() string {
	t := method.Info.Type.In(0)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	return t.Name()
}

func (method *methodType) String() string {
	return method.suiteName() + "." + method.Info.Name
}

func (method *methodType) matches(re *regexp.Regexp) bool {
	return (re.MatchString(method.Info.Name) ||
		re.MatchString(method.suiteName()) ||
		re.MatchString(method.String()))
}

type C struct {
	method    *methodType
	kind      funcKind
	testName  string
	status    funcStatus
	logb      *logger
	logw      io.Writer
	done      chan *C
	reason    string
	mustFail  bool
	tempDir   *tempDir
	benchMem  bool
	startTime time.Time
	timer
}

func (c *C) stopNow() {
	runtime.Goexit()
}

// logger is a concurrency safe byte.Buffer
type logger struct {
	sync.Mutex
	writer bytes.Buffer
}

func (l *logger) Write(buf []byte) (int, error) {
	l.Lock()
	defer l.Unlock()
	return l.writer.Write(buf)
}

func (l *logger) WriteTo(w io.Writer) (int64, error) {
	l.Lock()
	defer l.Unlock()
	return l.writer.WriteTo(w)
}

func (l *logger) String() string {
	l.Lock()
	defer l.Unlock()
	return l.writer.String()
}

// -----------------------------------------------------------------------
// Handling of temporary files and directories.

type tempDir struct {
	sync.Mutex
	path    string
	counter int
}

func (td *tempDir) newPath() string {
	td.Lock()
	defer td.Unlock()
	if td.path == "" {
		var err error
		for i := 0; i != 100; i++ {
			path := fmt.Sprintf("%s/check-%d", os.TempDir(), rand.Int())
			if err = os.Mkdir(path, 0700); err == nil {
				td.path = path
				break
			}
		}
		if td.path == "" {
			panic("Couldn't create temporary directory: " + err.Error())
		}
	}
	result := filepath.Join(td.path, strconv.Itoa(td.counter))
	td.counter += 1
	return result
}

func (td *tempDir) removeAll() {
	td.Lock()
	defer td.Unlock()
	if td.path != "" {
		err := os.RemoveAll(td.path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temporaries: "+err.Error())
		}
	}
}

// Create a new temporary directory which is automatically removed after
// the suite finishes running.
func (c *C) MkDir() string {
	path := c.tempDir.newPath()
	if err := os.Mkdir(path, 0700); err != nil {
		panic(fmt.Sprintf("Couldn't create temporary directory %s: %s", path, err.Error()))
	}
	return path
}

// -----------------------------------------------------------------------
// Low-level logging functions.

func (c *C) log(args ...interface{}) {
	c.writeLog([]byte(fmt.Sprint(args...) + "\n"))
}

func (c *C) logf(format string, args ...interface{}) {
	c.writeLog([]byte(fmt.Sprintf(format+"\n", args...)))
}

func (c *C) logNewLine() {
	c.writeLog([]byte{'\n'})
}

func (c *C) writeLog(buf []byte) {
	c.logb.Write(buf)
	if c.logw != nil {
		c.logw.Write(buf)
	}
}

func hasStringOrError(x interface{}) (ok bool) {
	_, ok = x.(fmt.Stringer)
	if ok {
		return
	}
	_, ok = x.(error)
	return
}

func (c *C) logValue(label string, value interface{}) {
	if label == "" {
		if hasStringOrError(value) {
			c.logf("... %#v (%q)", value, value)
		} else {
			c.logf("... %#v", value)
		}
	} else if value == nil {
		c.logf("... %s = nil", label)
	} else {
		if hasStringOrError(value) {
			fv := fmt.Sprintf("%#v", value)
			qv := fmt.Sprintf("%q", value)
			if fv != qv {
				c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv)
				return
			}
		}
		if s, ok := value.(string); ok && isMultiLine(s) {
			c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value))
			c.logMultiLine(s)
		} else {
			c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value)
		}
	}
}

func (c *C) logMultiLine(s string) {
	b := make([]byte, 0, len(s)*2)
	i := 0
	n := len(s)
	for i < n {
		j := i + 1
		for j < n && s[j-1] != '\n' {
			j++
		}
		b = append(b, "...     "...)
		b = strconv.AppendQuote(b, s[i:j])
		if j < n {
			b = append(b, " +"...)
		}
		b = append(b, '\n')
		i = j
	}
	c.writeLog(b)
}

func isMultiLine(s string) bool {
	for i := 0; i+1 < len(s); i++ {
		if s[i] == '\n' {
			return true
		}
	}
	return false
}

func (c *C) logString(issue string) {
	c.log("... ", issue)
}

func (c *C) logCaller(skip int) {
	// This is a bit heavier than it ought to be.
	skip += 1 // Our own frame.
	pc, callerFile, callerLine, ok := runtime.Caller(skip)
	if !ok {
		return
	}
	var testFile string
	var testLine int
	testFunc := runtime.FuncForPC(c.method.PC())
	if runtime.FuncForPC(pc) != testFunc {
		for {
			skip += 1
			if pc, file, line, ok := runtime.Caller(skip); ok {
				// Note that the test line may be different on
				// distinct calls for the same test.  Showing
				// the "internal" line is helpful when debugging.
				if runtime.FuncForPC(pc) == testFunc {
					testFile, testLine = file, line
					break
				}
			} else {
				break
			}
		}
	}
	if testFile != "" && (testFile != callerFile || testLine != callerLine) {
		c.logCode(testFile, testLine)
	}
	c.logCode(callerFile, callerLine)
}

func (c *C) logCode(path string, line int) {
	c.logf("%s:%d:", nicePath(path), line)
	code, err := printLine(path, line)
	if code == "" {
		code = "..." // XXX Open the file and take the raw line.
		if err != nil {
			code += err.Error()
		}
	}
	c.log(indent(code, "    "))
}

var valueGo = filepath.Join("reflect", "value.go")
var asmGo = filepath.Join("runtime", "asm_")

func (c *C) logPanic(skip int, value interface{}) {
	skip += 1 // Our own frame.
	initialSkip := skip
	for {
		if pc, file, line, ok := runtime.Caller(skip); ok {
			if skip == initialSkip {
				c.logf("... Panic: %s (PC=0x%X)\n", value, pc)
			}
			name := niceFuncName(pc)
			path := nicePath(file)
			if name == "Value.call" && strings.HasSuffix(path, valueGo) {
				break
			}
			if name == "call16" && strings.Contains(path, asmGo) {
				break
			}
			c.logf("%s:%d\n  in %s", nicePath(file), line, name)
		} else {
			break
		}
		skip += 1
	}
}

func (c *C) logSoftPanic(issue string) {
	c.log("... Panic: ", issue)
}

func (c *C) logArgPanic(method *methodType, expectedType string) {
	c.logf("... Panic: %s argument should be %s",
		niceFuncName(method.PC()), expectedType)
}

// -----------------------------------------------------------------------
// Some simple formatting helpers.

var initWD, initWDErr = os.Getwd()

func init() {
	if initWDErr == nil {
		initWD = strings.Replace(initWD, "\\", "/", -1) + "/"
	}
}

func nicePath(path string) string {
	if initWDErr == nil {
		if strings.HasPrefix(path, initWD) {
			return path[len(initWD):]
		}
	}
	return path
}

func niceFuncPath(pc uintptr) string {
	function := runtime.FuncForPC(pc)
	if function != nil {
		filename, line := function.FileLine(pc)
		return fmt.Sprintf("%s:%d", nicePath(filename), line)
	}
	return "<unknown path>"
}

func niceFuncName(pc uintptr) string {
	function := runtime.FuncForPC(pc)
	if function != nil {
		name := path.Base(function.Name())
		if i := strings.Index(name, "."); i > 0 {
			name = name[i+1:]
		}
		if strings.HasPrefix(name, "(*") {
			if i := strings.Index(name, ")"); i > 0 {
				name = name[2:i] + name[i+1:]
			}
		}
		if i := strings.LastIndex(name, ".*"); i != -1 {
			name = name[:i] + "." + name[i+2:]
		}
		if i := strings.LastIndex(name, "·"); i != -1 {
			name = name[:i] + "." + name[i+2:]
		}
		return name
	}
	return "<unknown function>"
}

// -----------------------------------------------------------------------
// Result tracker to aggregate call results.

type Result struct {
	Succeeded        int
	Failed           int
	Skipped          int
	Panicked         int
	FixturePanicked  int
	ExpectedFailures int
	Missed           int    // Not even tried to run, related to a panic in the fixture.
	RunError         error  // Houston, we've got a problem.
	WorkDir          string // If KeepWorkDir is true
}

type resultTracker struct {
	result          Result
	_lastWasProblem bool
	_waiting        int
	_missed         int
	_expectChan     chan *C
	_doneChan       chan *C
	_stopChan       chan bool
}

func newResultTracker() *resultTracker {
	return &resultTracker{_expectChan: make(chan *C), // Synchronous
		_doneChan: make(chan *C, 32), // Asynchronous
		_stopChan: make(chan bool)}   // Synchronous
}

func (tracker *resultTracker) start() {
	go tracker._loopRoutine()
}

func (tracker *resultTracker) waitAndStop() {
	<-tracker._stopChan
}

func (tracker *resultTracker) expectCall(c *C) {
	tracker._expectChan <- c
}

func (tracker *resultTracker) callDone(c *C) {
	tracker._doneChan <- c
}

func (tracker *resultTracker) _loopRoutine() {
	for {
		var c *C
		if tracker._waiting > 0 {
			// Calls still running. Can't stop.
			select {
			// XXX Reindent this (not now to make diff clear)
			case c = <-tracker._expectChan:
				tracker._waiting += 1
			case c = <-tracker._doneChan:
				tracker._waiting -= 1
				switch c.status {
				case succeededSt:
					if c.kind == testKd {
						if c.mustFail {
							tracker.result.ExpectedFailures++
						} else {
							tracker.result.Succeeded++
						}
					}
				case failedSt:
					tracker.result.Failed++
				case panickedSt:
					if c.kind == fixtureKd {
						tracker.result.FixturePanicked++
					} else {
						tracker.result.Panicked++
					}
				case fixturePanickedSt:
					// Track it as missed, since the panic
					// was on the fixture, not on the test.
					tracker.result.Missed++
				case missedSt:
					tracker.result.Missed++
				case skippedSt:
					if c.kind == testKd {
						tracker.result.Skipped++
					}
				}
			}
		} else {
			// No calls.  Can stop, but no done calls here.
			select {
			case tracker._stopChan <- true:
				return
			case c = <-tracker._expectChan:
				tracker._waiting += 1
			case c = <-tracker._doneChan:
				panic("Tracker got an unexpected done call.")
			}
		}
	}
}

// -----------------------------------------------------------------------
// The underlying suite runner.

type suiteRunner struct {
	suite                     interface{}
	setUpSuite, tearDownSuite *methodType
	setUpTest, tearDownTest   *methodType
	tests                     []*methodType
	tracker                   *resultTracker
	tempDir                   *tempDir
	keepDir                   bool
	output                    *outputWriter
	reportedProblemLast       bool
	benchTime                 time.Duration
	benchMem                  bool
}

type RunConf struct {
	Output        io.Writer
	Stream        bool
	Verbose       bool
	Filter        string
	Benchmark     bool
	BenchmarkTime time.Duration // Defaults to 1 second
	BenchmarkMem  bool
	KeepWorkDir   bool
}

// Create a new suiteRunner able to run all methods in the given suite.
func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner {
	var conf RunConf
	if runConf != nil {
		conf = *runConf
	}
	if conf.Output == nil {
		conf.Output = os.Stdout
	}
	if conf.Benchmark {
		conf.Verbose = true
	}

	suiteType := reflect.TypeOf(suite)
	suiteNumMethods := suiteType.NumMethod()
	suiteValue := reflect.ValueOf(suite)

	runner := &suiteRunner{
		suite:     suite,
		output:    newOutputWriter(conf.Output, conf.Stream, conf.Verbose),
		tracker:   newResultTracker(),
		benchTime: conf.BenchmarkTime,
		benchMem:  conf.BenchmarkMem,
		tempDir:   &tempDir{},
		keepDir:   conf.KeepWorkDir,
		tests:     make([]*methodType, 0, suiteNumMethods),
	}
	if runner.benchTime == 0 {
		runner.benchTime = 1 * time.Second
	}

	var filterRegexp *regexp.Regexp
	if conf.Filter != "" {
		if regexp, err := regexp.Compile(conf.Filter); err != nil {
			msg := "Bad filter expression: " + err.Error()
			runner.tracker.result.RunError = errors.New(msg)
			return runner
		} else {
			filterRegexp = regexp
		}
	}

	for i := 0; i != suiteNumMethods; i++ {
		method := newMethod(suiteValue, i)
		switch method.Info.Name {
		case "SetUpSuite":
			runner.setUpSuite = method
		case "TearDownSuite":
			runner.tearDownSuite = method
		case "SetUpTest":
			runner.setUpTest = method
		case "TearDownTest":
			runner.tearDownTest = method
		default:
			prefix := "Test"
			if conf.Benchmark {
				prefix = "Benchmark"
			}
			if !strings.HasPrefix(method.Info.Name, prefix) {
				continue
			}
			if filterRegexp == nil || method.matches(filterRegexp) {
				runner.tests = append(runner.tests, method)
			}
		}
	}
	return runner
}

// Run all methods in the given suite.
func (runner *suiteRunner) run() *Result {
	if runner.tracker.result.RunError == nil && len(runner.tests) > 0 {
		runner.tracker.start()
		if runner.checkFixtureArgs() {
			c := runner.runFixture(runner.setUpSuite, "", nil)
			if c == nil || c.status == succeededSt {
				for i := 0; i != len(runner.tests); i++ {
					c := runner.runTest(runner.tests[i])
					if c.status == fixturePanickedSt {
						runner.skipTests(missedSt, runner.tests[i+1:])
						break
					}
				}
			} else if c != nil && c.status == skippedSt {
				runner.skipTests(skippedSt, runner.tests)
			} else {
				runner.skipTests(missedSt, runner.tests)
			}
			runner.runFixture(runner.tearDownSuite, "", nil)
		} else {
			runner.skipTests(missedSt, runner.tests)
		}
		runner.tracker.waitAndStop()
		if runner.keepDir {
			runner.tracker.result.WorkDir = runner.tempDir.path
		} else {
			runner.tempDir.removeAll()
		}
	}
	return &runner.tracker.result
}

// Create a call object with the given suite method, and fork a
// goroutine with the provided dispatcher for running it.
func (runner *suiteRunner) forkCall(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
	var logw io.Writer
	if runner.output.Stream {
		logw = runner.output
	}
	if logb == nil {
		logb = new(logger)
	}
	c := &C{
		method:    method,
		kind:      kind,
		testName:  testName,
		logb:      logb,
		logw:      logw,
		tempDir:   runner.tempDir,
		done:      make(chan *C, 1),
		timer:     timer{benchTime: runner.benchTime},
		startTime: time.Now(),
		benchMem:  runner.benchMem,
	}
	runner.tracker.expectCall(c)
	go (func() {
		runner.reportCallStarted(c)
		defer runner.callDone(c)
		dispatcher(c)
	})()
	return c
}

// Same as forkCall(), but wait for call to finish before returning.
func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
	c := runner.forkCall(method, kind, testName, logb, dispatcher)
	<-c.done
	return c
}

// Handle a finished call.  If there were any panics, update the call status
// accordingly.  Then, mark the call as done and report to the tracker.
func (runner *suiteRunner) callDone(c *C) {
	value := recover()
	if value != nil {
		switch v := value.(type) {
		case *fixturePanic:
			if v.status == skippedSt {
				c.status = skippedSt
			} else {
				c.logSoftPanic("Fixture has panicked (see related PANIC)")
				c.status = fixturePanickedSt
			}
		default:
			c.logPanic(1, value)
			c.status = panickedSt
		}
	}
	if c.mustFail {
		switch c.status {
		case failedSt:
			c.status = succeededSt
		case succeededSt:
			c.status = failedSt
			c.logString("Error: Test succeeded, but was expected to fail")
			c.logString("Reason: " + c.reason)
		}
	}

	runner.reportCallDone(c)
	c.done <- c
}

// Runs a fixture call synchronously.  The fixture will still be run in a
// goroutine like all suite methods, but this method will not return
// while the fixture goroutine is not done, because the fixture must be
// run in a desired order.
func (runner *suiteRunner) runFixture(method *methodType, testName string, logb *logger) *C {
	if method != nil {
		c := runner.runFunc(method, fixtureKd, testName, logb, func(c *C) {
			c.ResetTimer()
			c.StartTimer()
			defer c.StopTimer()
			c.method.Call([]reflect.Value{reflect.ValueOf(c)})
		})
		return c
	}
	return nil
}

// Run the fixture method with runFixture(), but panic with a fixturePanic{}
// in case the fixture method panics.  This makes it easier to track the
// fixture panic together with other call panics within forkTest().
func (runner *suiteRunner) runFixtureWithPanic(method *methodType, testName string, logb *logger, skipped *bool) *C {
	if skipped != nil && *skipped {
		return nil
	}
	c := runner.runFixture(method, testName, logb)
	if c != nil && c.status != succeededSt {
		if skipped != nil {
			*skipped = c.status == skippedSt
		}
		panic(&fixturePanic{c.status, method})
	}
	return c
}

type fixturePanic struct {
	status funcStatus
	method *methodType
}

// Run the suite test method, together with the test-specific fixture,
// asynchronously.
func (runner *suiteRunner) forkTest(method *methodType) *C {
	testName := method.String()
	return runner.forkCall(method, testKd, testName, nil, func(c *C) {
		var skipped bool
		defer runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, &skipped)
		defer c.StopTimer()
		benchN := 1
		for {
			runner.runFixtureWithPanic(runner.setUpTest, testName, c.logb, &skipped)
			mt := c.method.Type()
			if mt.NumIn() != 1 || mt.In(0) != reflect.TypeOf(c) {
				// Rather than a plain panic, provide a more helpful message when
				// the argument type is incorrect.
				c.status = panickedSt
				c.logArgPanic(c.method, "*check.C")
				return
			}
			if strings.HasPrefix(c.method.Info.Name, "Test") {
				c.ResetTimer()
				c.StartTimer()
				c.method.Call([]reflect.Value{reflect.ValueOf(c)})
				return
			}
			if !strings.HasPrefix(c.method.Info.Name, "Benchmark") {
				panic("unexpected method prefix: " + c.method.Info.Name)
			}

			runtime.GC()
			c.N = benchN
			c.ResetTimer()
			c.StartTimer()
			c.method.Call([]reflect.Value{reflect.ValueOf(c)})
			c.StopTimer()
			if c.status != succeededSt || c.duration >= c.benchTime || benchN >= 1e9 {
				return
			}
			perOpN := int(1e9)
			if c.nsPerOp() != 0 {
				perOpN = int(c.benchTime.Nanoseconds() / c.nsPerOp())
			}

			// Logic taken from the stock testing package:
			// - Run more iterations than we think we'll need for a second (1.5x).
			// - Don't grow too fast in case we had timing errors previously.
			// - Be sure to run at least one more than last time.
			benchN = max(min(perOpN+perOpN/2, 100*benchN), benchN+1)
			benchN = roundUp(benchN)

			skipped = true // Don't run the deferred one if this panics.
			runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, nil)
			skipped = false
		}
	})
}

// Same as forkTest(), but wait for the test to finish before returning.
func (runner *suiteRunner) runTest(method *methodType) *C {
	c := runner.forkTest(method)
	<-c.done
	return c
}

// Helper to mark tests as skipped or missed.  A bit heavy for what
// it does, but it enables homogeneous handling of tracking, including
// nice verbose output.
func (runner *suiteRunner) skipTests(status funcStatus, methods []*methodType) {
	for _, method := range methods {
		runner.runFunc(method, testKd, "", nil, func(c *C) {
			c.status = status
		})
	}
}

// Verify if the fixture arguments are *check.C.  In case of errors,
// log the error as a panic in the fixture method call, and return false.
func (runner *suiteRunner) checkFixtureArgs() bool {
	succeeded := true
	argType := reflect.TypeOf(&C{})
	for _, method := range []*methodType{runner.setUpSuite, runner.tearDownSuite, runner.setUpTest, runner.tearDownTest} {
		if method != nil {
			mt := method.Type()
			if mt.NumIn() != 1 || mt.In(0) != argType {
				succeeded = false
				runner.runFunc(method, fixtureKd, "", nil, func(c *C) {
					c.logArgPanic(method, "*check.C")
					c.status = panickedSt
				})
			}
		}
	}
	return succeeded
}

func (runner *suiteRunner) reportCallStarted(c *C) {
	runner.output.WriteCallStarted("START", c)
}

func (runner *suiteRunner) reportCallDone(c *C) {
	runner.tracker.callDone(c)
	switch c.status {
	case succeededSt:
		if c.mustFail {
			runner.output.WriteCallSuccess("FAIL EXPECTED", c)
		} else {
			runner.output.WriteCallSuccess("PASS", c)
		}
	case skippedSt:
		runner.output.WriteCallSuccess("SKIP", c)
	case failedSt:
		runner.output.WriteCallProblem("FAIL", c)
	case panickedSt:
		runner.output.WriteCallProblem("PANIC", c)
	case fixturePanickedSt:
		// That's a testKd call reporting that its fixture
		// has panicked. The fixture call which caused the
		// panic itself was tracked above. We'll report to
		// aid debugging.
		runner.output.WriteCallProblem("PANIC", c)
	case missedSt:
		runner.output.WriteCallSuccess("MISS", c)
	}
}

// -----------------------------------------------------------------------
// Output writer manages atomic output writing according to settings.

type outputWriter struct {
	m                    sync.Mutex
	writer               io.Writer
	wroteCallProblemLast bool
	Stream               bool
	Verbose              bool
}

func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter {
	return &outputWriter{writer: writer, Stream: stream, Verbose: verbose}
}

func (ow *outputWriter) Write(content []byte) (n int, err error) {
	ow.m.Lock()
	n, err = ow.writer.Write(content)
	ow.m.Unlock()
	return
}

func (ow *outputWriter) WriteCallStarted(label string, c *C) {
	if ow.Stream {
		header := renderCallHeader(label, c, "", "\n")
		ow.m.Lock()
		ow.writer.Write([]byte(header))
		ow.m.Unlock()
	}
}

func (ow *outputWriter) WriteCallProblem(label string, c *C) {
	var prefix string
	if !ow.Stream {
		prefix = "\n-----------------------------------" +
			"-----------------------------------\n"
	}
	header := renderCallHeader(label, c, prefix, "\n\n")
	ow.m.Lock()
	ow.wroteCallProblemLast = true
	ow.writer.Write([]byte(header))
	if !ow.Stream {
		c.logb.WriteTo(ow.writer)
	}
	ow.m.Unlock()
}

func (ow *outputWriter) WriteCallSuccess(label string, c *C) {
	if ow.Stream || (ow.Verbose && c.kind == testKd) {
		// TODO Use a buffer here.
		var suffix string
		if c.reason != "" {
			suffix = " (" + c.reason + ")"
		}
		if c.status == succeededSt {
			suffix += "\t" + c.timerString()
		}
		suffix += "\n"
		if ow.Stream {
			suffix += "\n"
		}
		header := renderCallHeader(label, c, "", suffix)
		ow.m.Lock()
		// Resist temptation of using line as prefix above due to race.
		if !ow.Stream && ow.wroteCallProblemLast {
			header = "\n-----------------------------------" +
				"-----------------------------------\n" +
				header
		}
		ow.wroteCallProblemLast = false
		ow.writer.Write([]byte(header))
		ow.m.Unlock()
	}
}

func renderCallHeader(label string, c *C, prefix, suffix string) string {
	pc := c.method.PC()
	return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc),
		niceFuncName(pc), suffix)
}


text:
package com.optimuscode.core.java.metrics;

import com.optimuscode.core.common.model.CompilationUnit;
import com.optimuscode.core.common.model.Project;
import com.optimuscode.core.java.metrics.result.Metric;
import com.optimuscode.core.common.model.JavaProject;
import com.optimuscode.core.utils.CommonUtils;
import com.optimuscode.core.utils.SupportedLanguage;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.assertNotNull;

/**
 * Created with IntelliJ IDEA.
 * User: sujay
 * Date: 11/30/13
 * Time: 2:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class CheckStyleServiceTest {
    Project project;

    @Before
    public void setUp() throws Exception {
        project = JavaProject.create("session1", CommonUtils.generateUUID(),
                "/home/sbhowmick/tmp/");
    }

    @After
    public void tearDown() throws Exception {
        project.close();
    }

    @Test
    public void testRunMetrics() throws Exception {
        System.out.println("runTest");
        final String javaFileName1 = "./optimuscode-api/src/test/resources/Reverse.txt";
        final String javaFileName2 = "./optimuscode-api/src/test/resources/ReverseTest.txt";
        final String className1 = "Reverse";
        final String className2 = "ReverseTest";
        String fileContents1 = FileUtils.fileRead(javaFileName1);
        String fileContents2 = FileUtils.fileRead(javaFileName2);
        assertNotNull(fileContents1);
        CompilationUnit unit = new CompilationUnit(SupportedLanguage.Java);
        unit.addSource(className1, fileContents1);
        unit.addSource(className2, fileContents2);
        project.setTestClassName(className2);
        project.setUnit(unit);

        MetricsService metricsService = CheckStyleService.create();
        metricsService.runMetrics(project);
        MetricsListener listener = metricsService.getMetricsListener();
        Map<String, Collection<Metric>> groupedMetrics =
                                            listener.getMetricGroups();
        for(String key: groupedMetrics.keySet()){
            System.out.println(key);
            Collection<Metric> metrics = groupedMetrics.get(key);
            for(Metric metric: metrics){
                System.out.println(metric.getMessage());
            }
        }

    }

    @Test
    public void testRunMetricsErrors() throws Exception {
        System.out.println("runTest");
        final String javaFileName1 = "./optimuscode-api/src/test/resources/TestSourceFile.txt";
        final String javaFileName2 = "./optimuscode-api/src/test/resources/TestSourceFileTest.txt";
        final String className1 = "TestSourceFile";
        final String className2 = "TestSourceFileTest";
        String fileContents1 = FileUtils.fileRead(javaFileName1);
        String fileContents2 = FileUtils.fileRead(javaFileName2);
        assertNotNull(fileContents1);
        CompilationUnit unit = new CompilationUnit(SupportedLanguage.Java);
        unit.addSource(className1, fileContents1);
        unit.addSource(className2, fileContents2);
        project.setTestClassName(className2);
        project.setUnit(unit);

        MetricsService metricsService = CheckStyleService.create();
        metricsService.runMetrics(project);
        MetricsListener listener = metricsService.getMetricsListener();
        Map<String, Collection<Metric>> groupedMetrics =
                listener.getMetricGroups();
        for(String key: groupedMetrics.keySet()){
            System.out.println(key);
            Collection<Metric> metrics = groupedMetrics.get(key);
            for(Metric metric: metrics){
                System.out.println(metric.getMessage());
            }
        }

    }
}


text:
namespace ReactNative.Modules.Dialog
{
    static class DialogModuleHelper
    {
        public const string ActionButtonClicked = "buttonClicked";
        public const string ActionDismissed = "dismissed";

        public const string KeyButtonPositive = "buttonPositive";
        public const string KeyButtonNegative = "buttonNegative";

        public const int KeyButtonPositiveValue = 0;
        public const int KeyButtonNegativeValue = 1;
    }
}


text:
package org.mojavemvc.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *

 * Only one instance of this controller will exist in the application, placed in
 * the front controller context. Its dependencies, if any, are re-injected with
 * every new request.
 *

 *
 *

 * The following are valid declarations of singleton controllers:
 *

 *
 *

 * @SingletonController
 * public class SomeController {
 *  ...
 * }
 *

 *
 *

 * @SingletonController("some-name")
 * public class SomeController {
 *  ...
 * }
 *

 *
 *

 * NOTE: It is up to the developer to address thread-safety in singleton
 * controllers. The single instance will be accessed simultaneously by multiple
 * threads, and thus there will be concurrency issues to address. The container
 * will not attempt to address those issues.
 *

 *
 * @author Luis Antunes
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SingletonController {
    String value() default "";
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package UI;

import bancodequestoes.ConexaoBD;
import java.awt.Color;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author ThalesGSN
 */
public class Pesquisar extends javax.swing.JFrame {

    /**
     * Creates new form Home
     */
    public Pesquisar() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            Logger.getLogger(Pesquisar.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        container = new javax.swing.JPanel();
        Home = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        homePesquisar = new javax.swing.JButton();
        enviarPesquisar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        disciplinasPesquisar = new javax.swing.JComboBox<>();
        materiaPesquisar = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        pesquisaPesquisar = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();

        javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
        jLayeredPane1.setLayout(jLayeredPane1Layout);
        jLayeredPane1Layout.setHorizontalGroup(
            jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jLayeredPane1Layout.setVerticalGroup(
            jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));

        container.setBackground(new java.awt.Color(255, 255, 255));
        container.setLayout(new java.awt.CardLayout());

        Home.setBackground(new java.awt.Color(255, 255, 255));
        Home.setMaximumSize(new java.awt.Dimension(90, 99));
        Home.setMinimumSize(new java.awt.Dimension(90, 99));

        jLabel5.setFont(new java.awt.Font("Trebuchet MS", 0, 48)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(1, 87, 155));
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Banco de Questões");
        jLabel5.setToolTipText("Banco de Questões");
        jLabel5.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jLabel5.setAlignmentX(0.5F);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        homePesquisar.setBackground(new java.awt.Color(33, 150, 243));
        homePesquisar.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        homePesquisar.setForeground(new java.awt.Color(255, 255, 255));
        homePesquisar.setText("HOME");
        homePesquisar.setToolTipText("Ir para  o inicio");
        homePesquisar.setAlignmentX(0.5F);
        homePesquisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        homePesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                homePesquisarActionPerformed(evt);
            }
        });

        enviarPesquisar.setBackground(new java.awt.Color(33, 150, 243));
        enviarPesquisar.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        enviarPesquisar.setForeground(new java.awt.Color(255, 255, 255));
        enviarPesquisar.setText("PESQUISAR QUESTÕES");
        enviarPesquisar.setToolTipText("Pesquisar");
        enviarPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enviarPesquisarActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(153, 153, 153));
        jLabel2.setText("Pesquise por um texto:");
        jLabel2.setToolTipText("Defina um um texto presente na questão");

        disciplinasPesquisar.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        disciplinasPesquisar.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Defina a disciplina:", "Aplicações para Web", "Arquitetura de Sistemas Digitais", "Linguagem de Programação - JAVA", "Manutenção de Computadores", "Biologia", "Filosofia", "Física", "Geografia", "História", "Matemática", "Português", "Química", "Sociologia", "Outra" }));
        disciplinasPesquisar.setToolTipText("Defina a disciplina:");

        materiaPesquisar.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        materiaPesquisar.setForeground(new java.awt.Color(153, 153, 153));
        materiaPesquisar.setText("DIGITE O TEXTO AQUI.");
        materiaPesquisar.setToolTipText("Defina a materia da questão");
        materiaPesquisar.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                materiaPesquisarFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                materiaPesquisarFocusLost(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(153, 153, 153));
        jLabel3.setText("Selecione a matéria:");
        jLabel3.setToolTipText("Defina a materia da questão");

        pesquisaPesquisar.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        pesquisaPesquisar.setForeground(new java.awt.Color(153, 153, 153));
        pesquisaPesquisar.setText("DIGITE O TEXTO AQUI.");
        pesquisaPesquisar.setToolTipText("Defina um um texto presente na questão");
        pesquisaPesquisar.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                pesquisaPesquisarFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                pesquisaPesquisarFocusLost(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(disciplinasPesquisar, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(materiaPesquisar))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pesquisaPesquisar)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(251, 251, 251)
                .addComponent(enviarPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(251, Short.MAX_VALUE)
                .addComponent(homePesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(251, 251, 251))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(homePesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(disciplinasPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(materiaPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pesquisaPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(enviarPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
        );

        jLabel6.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("A ferramenta que produz provas de maneira simples e funcional");
        jLabel6.setToolTipText("Descrição");

        javax.swing.GroupLayout HomeLayout = new javax.swing.GroupLayout(Home);
        Home.setLayout(HomeLayout);
        HomeLayout.setHorizontalGroup(
            HomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(HomeLayout.createSequentialGroup()
                .addGroup(HomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 1028, Short.MAX_VALUE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        HomeLayout.setVerticalGroup(
            HomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(HomeLayout.createSequentialGroup()
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(68, 68, 68))
        );

        container.add(Home, "Home");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(container, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(107, 107, 107)
                .addComponent(container, javax.swing.GroupLayout.PREFERRED_SIZE, 516, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(122, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void homePesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homePesquisarActionPerformed
        FormInicial home = new FormInicial();
        home.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_homePesquisarActionPerformed

    private void enviarPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviarPesquisarActionPerformed
       ConexaoBD conn = new ConexaoBD();

       if(disciplinasPesquisar.getSelectedItem().toString().equals("Defina a disciplina:" )
               && materiaPesquisar.getText().trim().equals("DIGITE O TEXTO AQUI.")
               && pesquisaPesquisar.getText().trim().equals("DIGITE O TEXTO AQUI.")){
           JOptionPane.showMessageDialog(this, " Essa"
                       + "não é uma pesquisa valida,", "ERRO",
                    JOptionPane.ERROR_MESSAGE);
       } else {

        try {
            String disciplinas = null;
            String materia = null;
            String pesquisa = null;
            if(!disciplinasPesquisar.getSelectedItem().toString().equals("Defina a disciplina:")){
                disciplinas = disciplinasPesquisar.getSelectedItem().toString();
            }
            if(!materiaPesquisar.getText().trim().equals("DIGITE O TEXTO AQUI.")){
                materia = materiaPesquisar.getText().trim();
            }
            if(!pesquisaPesquisar.getText().trim().equals("DIGITE O TEXTO AQUI.")){
                pesquisa =  pesquisaPesquisar.getText().trim();
            }
          Tabela pesquiTabela = new Tabela(conn.pesquisarQuestoes(disciplinas, materia,  pesquisa));
          this.setVisible(false);
          pesquiTabela.setVisible(true);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao conectar ao banco de "
                    + "dados. Cheque sua conexão.", "ERRO",
                    JOptionPane.ERROR_MESSAGE);
        }
       }
    }//GEN-LAST:event_enviarPesquisarActionPerformed

    private void materiaPesquisarFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_materiaPesquisarFocusGained
         if(materiaPesquisar.getText().equals("DIGITE O TEXTO AQUI.")){
           materiaPesquisar.setText("");
           materiaPesquisar.setForeground(new Color(0,0,0));
       }
    }//GEN-LAST:event_materiaPesquisarFocusGained

    private void pesquisaPesquisarFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_pesquisaPesquisarFocusGained
         if(pesquisaPesquisar.getText().equals("DIGITE O TEXTO AQUI.")){
           pesquisaPesquisar.setText("");
           pesquisaPesquisar.setForeground(new Color(0,0,0));
       }
    }//GEN-LAST:event_pesquisaPesquisarFocusGained

    private void materiaPesquisarFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_materiaPesquisarFocusLost
        if(materiaPesquisar.getText().equals("")){
            materiaPesquisar.setText("DIGITE O TEXTO AQUI.");
            materiaPesquisar.setForeground(new Color(153, 153, 153));
        }
    }//GEN-LAST:event_materiaPesquisarFocusLost

    private void pesquisaPesquisarFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_pesquisaPesquisarFocusLost
        if(pesquisaPesquisar.getText().equals("")){
            pesquisaPesquisar.setText("DIGITE O TEXTO AQUI.");
            pesquisaPesquisar.setForeground(new Color(153, 153, 153));
        }
    }//GEN-LAST:event_pesquisaPesquisarFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Pesquisar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Pesquisar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Pesquisar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pesquisar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new Pesquisar().setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Home;
    private javax.swing.JPanel container;
    private javax.swing.JComboBox<String> disciplinasPesquisar;
    private javax.swing.JButton enviarPesquisar;
    private javax.swing.JButton homePesquisar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField materiaPesquisar;
    private javax.swing.JTextField pesquisaPesquisar;
    // End of variables declaration//GEN-END:variables
}


text:
package com.hathway.androidinterviewquestion;

public interface ConnectionRepository {
    void setConnection(String connection);
    String getConnection();
    void removeConnection();
}


text:
function short = splitLongSeqIntoManyShort(long, Tsmall)
% splitLongSeqIntoManyShort Put groups of columns  into a cell array of narrower matrices
% function short = splitLongSeqIntoManyShort(long, Tsmall)
%
% long(:,t)
% short{i} = long(:,ndx1:ndx2) where each segment (except maybe the last) is of length Tsmall

T = length(long);
Nsmall = ceil(T/Tsmall);
short = cell(Nsmall,1);

t = 1;
for i=1:Nsmall
  short{i} = long(:,t:min(T,t+Tsmall-1));
  t = t+Tsmall;
end


text:
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    init();
}

Widget::~Widget()
{

    delete ui;
}

void Widget::init()
{
    setWindowFlags(Qt::FramelessWindowHint);  //ÒþÈ¥´°¿Ú±ß¿ò
    setAttribute(Qt::WA_TranslucentBackground, true);  //ÉèÖô°¿Ú±³¾°Í¸Ã÷

    GlowEffect *effect = new GlowEffect(this);
    effect->setRadius(10);
    effect->setGlowColor(Qt::white);
    ui->title->setGraphicsEffect(effect);

    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
    shadow_effect->setOffset(1, 1);
    shadow_effect->setColor(Qt::black);
    shadow_effect->setBlurRadius(100);
    ui->main_bkg_frame->setGraphicsEffect(shadow_effect);

    return;
}

void Widget::loginMainWidgetFinished(QString name)
{
    ui->nickname->setText(name);
 //   qDebug() << "name=" << name;
}


text:
QTelnetServer::QTelnetServer(QObject* parent)
 : QObject(parent)
{
    Server = new TelnetTCPServer(this);
}

//-----------------------------------------------------------------------------
//
QTelnetServer::~QTelnetServer()
{
    delete Server;
}

//-----------------------------------------------------------------------------
//
int QTelnetServer::Start(quint16 telnetport)
{
    int ret = Server->StartServer( telnetport );
    return ret;
}

//-----------------------------------------------------------------------------
//
int QTelnetServer::Stop()
{
    Server->StopServer();
    return 0;
}

//-----------------------------------------------------------------------------
//
QString QTelnetServer::Exec(QString command, QStringList args) const
{
    if ( !args.count() > 1 )
    {
        return "Please include the arguments to the command!";
    }

    QString ret = "Not a valid command.";

    //Set the password
    if ( command == "setpassword" )
    {
        //Hash the password and then base64 encode it
        QByteArray hash = QCryptographicHash::hash(args.at(0).toLatin1(), QCryptographicHash::Sha1);
        QString hashedpass = QString(hash.toBase64());
        Server->setPasswordHash(hashedpass);
        ret = "Password has been set.";
    }

    return ret;
}

//-----------------------------------------------------------------------------
//


text:
<!DOCTYPE html>

  <title>router.js</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="docco.css" />

          Jump To …
          +

                  annotation.js

                  async.js

                  context.js

                  core.js

                  di.js

                  bus.js

                  router.js

                  storage.js

                  dot.js

                  test.js

                  html.js

                  loader.js

                  object.js

                  url.js

router.js

                ¶

/*global Arenite:true*/
Arenite.Router = function (arenite) {

  var _routes = {};

  var _trigger = function (hash, updateHash) {
    if (hash.indexOf('#') !== 0) {
      hash = '#' + hash;
    }
    arenite.object.keys(_routes).forEach(function (route) {
      var args = _routes[route].regex.exec(hash);
      if (args) {
        args.splice(0, 1);
        _executeRoute(route, args, _routes[route].vars, updateHash ? hash : updateHash);
      }
    });
  };

  var _executeRoute = function (route, args, vars, updateHash) {
    _routes[route].executions.forEach(function (execution) {
      var exec = JSON.parse(JSON.stringify(execution));
      if (typeof execution.func === 'function') {
        exec.func = execution.func;
        exec.args = [{ref: 'arenite'}];
      }
      if (!exec.args) {
        exec.args = [];
      }
      var values = {};
      args.forEach(function (arg, i) {
        values[vars[i]] = arg;
      });
      exec.args.push({value:values});
      window.console.log('Arenite.Router: Executing route "' + route + '" with:', exec);
      if (updateHash) {
        window.location.hash = updateHash;
      }
      arenite.di.exec(exec);
    });
  };

  var _handleChange = function () {
    _trigger(window.location.hash);
  };

  var _init = function (routes, passive) {
    if (!passive) {
      document.body.onhashchange = _handleChange;
    }
    arenite.object.keys(routes).forEach(function (route) {
      _add(route, routes[route]);
    });
    arenite.config.context.start.splice(0, 0, {func: _handleChange});
  };

  var _add = function (route, executions) {
    var regex = '^#' + route.replace(/:[^/]+/g, '([^/]+)') + "$";
    var vars = route.match(/:[^/]+/g);
    vars.forEach(function (v, i) {
      vars[i] = v.substring(1);
    });
    _routes[route] = {executions: executions, regex: new RegExp(regex), vars: vars};
  };

  var _remove = function (route) {
    delete _routes[route];
  };

  return {
    init: _init,
    add: _add,
    remove: _remove,
    trigger: _trigger
  };
};


text:
var module = angular.module("example", ["angularGrid"]);

module.controller("exampleCtrl", function($scope) {

    var columnDefs = [
        {displayName: "Make", field: "make"},
        {displayName: "Model", field: "model"},
        {displayName: "Price", field: "price", filter: "number"}
    ];

    var rowData = [
        {make: "Toyota", model: "Celica", price: 35000},
        {make: "Ford", model: "Mondeo", price: 32000},
        {make: "Ford", model: "Focus", price: 27000},
        {make: "BMW", model: "M5", price: 38000},
        {make: "Phantom", model: "Speed Car", price: 120000},
        {make: "Porsche", model: "Boxter", price: 72000}
    ];

    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: rowData,
        enableColResize: true, //one of [true, false]
        enableSorting: true, //one of [true, false]
        enableFilter: true, //one of [true, false]
        rowSelection: "single",
        dontUseScrolls: true
    };

});


text:
var _ = require('./lodash');
var Dom = require('./packages/dom');

module.exports = {
  tagName: 'div',
  className: 'sir-trevor__view',
  attributes: {},

  $: function(selector) {
    return this.el.querySelectorAll(selector);
  },

  render: function() {
    return this;
  },

  destroy: function() {
    if (!_.isUndefined(this.stopListening)) { this.stopListening(); }
    Dom.remove(this.el);
  },

  _ensureElement: function() {
    if (!this.el) {
      var attrs = Object.assign({}, _.result(this, 'attributes'));
      if (this.id) { attrs.id = this.id; }
      if (this.className) { attrs['class'] = this.className; }

      var el = Dom.createElement(this.tagName, attrs);
      this._setElement(el);
    } else {
      this._setElement(this.el);
    }
  },

  _setElement: function(element) {
    this.el = element;
    return this;
  }
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: AlexanderC <self@alexanderc.me>
 * Date: 7/22/14
 * Time: 11:49
 */

namespace AlexanderC\Api\MasheryBundle\Orm;

trait MasheryObjectTrait
{
    /**
     * Only if it is set to true the entity would be synced
     *
     * @var bool
     */
    protected $masherySyncState = true;

    /**
     * Skip object validation if set to true
     *
     * @var bool
     */
    protected $skipValidation = false;

    /**
     * @var int
     *
     * @ORM\Column(type="integer", unique=true, nullable=true, options={"comment"="Id of current object stored in mashery."})
     */
    protected $mashery_object_id;

    /**
     * Important!!!
     * Override this methods in entities
     * since doctrine is generating issues
     * @TODO: make a patch!
     *
     * @param int $mashery_object_id
     */
    abstract public function setMasheryObjectId($mashery_object_id);

    /**
     * Important!!!
     * Override this methods in entities
     * since doctrine is generating issues
     * @TODO: make a patch!
     *
     * @return int
     */
    abstract public function getMasheryObjectId();

    /**
     * Properties that should be synced
     *
     * @return array
     * @throws \RuntimeException
     */
    final public function getMasherySyncProperties()
    {
        if(!method_exists($this, '__getMasherySyncProperties')) {
            throw new \RuntimeException(
                "You must implement __getMasherySyncProperties() method".
                " instead of getMasherySyncProperties(), because it is used internally"
            );
        }

        return array_merge($this->__getMasherySyncProperties(), ['mashery_object_id' => 'id']);
    }

    /**
     * Allow only a normal code!
     *
     * @return bool
     */
    final public function masheryUseSettersAndGetters()
    {
        return true;
    }

    /**
     * @param boolean $masherySyncState
     */
    final public function setMasherySyncState($masherySyncState)
    {
        $this->masherySyncState = (bool) $masherySyncState;
    }

    /**
     * @return boolean
     */
    final public function getMasherySyncState()
    {
        return $this->masherySyncState;
    }

    /**
     * @param boolean $skipValidation
     */
    final public function setSkipValidation($skipValidation)
    {
        $this->skipValidation = $skipValidation;
    }

    /**
     * @return boolean
     */
    final public function getSkipValidation()
    {
        return $this->skipValidation;
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;

namespace System.Windows.Controls.WpfPropertyGrid
{
    /// <summary>
    /// Provides a wrapper around property value to be used at presentation level.
    /// </summary>
    public class PropertyItemValue : INotifyPropertyChanged
    {
        private readonly PropertyItem _property;

        #region Events

        /// <summary>
        /// Occurs when exception is raised at Property Value.
        /// <remarks>This event is reserved for future implementations.</remarks>
        /// </summary>
        public event EventHandler<ValueExceptionEventArgs> PropertyValueException;
        /// <summary>
        /// Occurs when root value is changed.
        /// <remarks>This event is reserved for future implementations.</remarks>
        /// </summary>
        public event EventHandler RootValueChanged;
        /// <summary>
        /// Occurs when sub property changed.
        /// </summary>
        public event EventHandler SubPropertyChanged;

        #endregion

        /// <summary>
        /// Gets the parent property.
        /// </summary>
        /// <value>The parent property.</value>
        public PropertyItem ParentProperty
        {
            get { return _property; }
        }

        private readonly GridEntryCollection<PropertyItem> _subProperties = new GridEntryCollection<PropertyItem>();
        public GridEntryCollection<PropertyItem> SubProperties
        {
            get { return _subProperties; }
        }

        private readonly bool _hasSubProperties;
        /// <summary>
        /// Gets a value indicating whether encapsulated value has sub-properties.
        /// </summary>
        /// <remarks>This property is reserved for future implementations.</remarks>
        /// <value>
        /// 	<c>true</c> if this instance has sub properties; otherwise, <c>false</c>.
        /// </value>
        public bool HasSubProperties
        {
            get { return _hasSubProperties; }
        }

        #region ctor
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyItemValue"/> class.
        /// </summary>
        /// <param name="property">The property.</param>
        public PropertyItemValue(PropertyItem property)
        {
            if (property == null) throw new ArgumentNullException("property");
            this._property = property;

            _hasSubProperties = property.Converter.GetPropertiesSupported();

            if (_hasSubProperties)
            {
                object value = property.GetValue();

                var propertyAttributes = PropertyGridUtils.GetAttributes<BrowsablePropertyAttribute>(value);

                PropertyDescriptorCollection descriptors = property.Converter.GetProperties(value);
                List<BrowsablePropertyAttribute> temp = new List<BrowsablePropertyAttribute>(propertyAttributes);

                foreach (PropertyDescriptor d in descriptors)
                {
                    if (ShoudDisplayProperty(d, temp))
                    {
                        _subProperties.Add(new PropertyItem(property.Owner, value, d));
                        // TODO: Move to PropertyData as a public property
                        NotifyParentPropertyAttribute notifyParent = d.Attributes[KnownTypes.Attributes.NotifyParentPropertyAttribute] as NotifyParentPropertyAttribute;
                        if (notifyParent != null && notifyParent.NotifyParent)
                        {
                            d.AddValueChanged(value, NotifySubPropertyChanged);
                        }
                    }
                }
            }

            this._property.PropertyChanged += new PropertyChangedEventHandler(ParentPropertyChanged);
        }

        private bool ShoudDisplayProperty(PropertyDescriptor propertyDescriptor, List<BrowsablePropertyAttribute> browsableAttributes)
        {
            if (propertyDescriptor == null) return false;

            // Check whether owning category is not restricted to ouput

            // Check the explicit declaration
            var attribute = browsableAttributes.FirstOrDefault(item => item.PropertyName == propertyDescriptor.Name);
            if (attribute != null) return attribute.Browsable;

            // Check the wildcard
            var wildcard = browsableAttributes.FirstOrDefault(item => item.PropertyName == BrowsablePropertyAttribute.All);
            if (wildcard != null) return wildcard.Browsable;

            // Return default/standard Browsable settings for the property
            return propertyDescriptor.IsBrowsable;
        }
        #endregion

        void ParentPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "PropertyValue")
                NotifyRootValueChanged();

            if (e.PropertyName == "IsReadOnly")
            {
                OnPropertyChanged("IsReadOnly");
                OnPropertyChanged("IsEditable");
            }
        }

        #region PropertyValue implementation

        /// <summary>
        /// Gets a value indicating whether this instance can convert from string.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance can convert from string; otherwise, <c>false</c>.
        /// </value>
        public bool CanConvertFromString
        {
            get { return (((_property.Converter != null) && _property.Converter.CanConvertFrom(typeof(string))) && !_property.IsReadOnly); }
        }

        /// <summary>
        /// Clears the value.
        /// </summary>
        public void ClearValue()
        {
            _property.ClearValue();
        }

        /// <summary>
        /// Converts the string to value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>Value instance</returns>
        protected object ConvertStringToValue(string value)
        {
            if (_property.PropertyType == typeof(string)) return value;
            //if (value.Length == 0) return null;
            if (string.IsNullOrEmpty(value)) return null;
            if (!_property.Converter.CanConvertFrom(typeof(string)))
                throw new InvalidOperationException("Value to String conversion is not supported!");
            return _property.Converter.ConvertFromString(null, GetSerializationCulture(), value);
        }

        /// <summary>
        /// Converts the value to string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>String presentation of the value</returns>
        protected string ConvertValueToString(object value)
        {
            string collectionValue = string.Empty;
            if (value == null) return collectionValue;

            collectionValue = value as String;
            if (collectionValue != null) return collectionValue;

            var converter = this._property.Converter;
            if (converter.CanConvertTo(typeof(string)))
                collectionValue = converter.ConvertToString(null, GetSerializationCulture(), value);
            else
                collectionValue = value.ToString();

            // TODO: refer to resources or some constant
            if (string.IsNullOrEmpty(collectionValue) && (value is IEnumerable))
                collectionValue = "(Collection)";

            return collectionValue;
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <returns>Property value</returns>
        protected object GetValueCore()
        {
            return this._property.GetValue();
        }

        /// <summary>
        /// Gets a value indicating whether encapsulated property value is collection.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if encapsulated property value is collection; otherwise, <c>false</c>.
        /// </value>
        public bool IsCollection
        {
            get { return _property.IsCollection; }
        }

        /// <summary>
        /// Gets a value indicating whether encapsulated property value is default value.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if encapsulated property value is default value; otherwise, <c>false</c>.
        /// </value>
        public bool IsDefaultValue
        {
            get { return _property.IsDefaultValue; }
        }

        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="value">The value.</param>
        protected void SetValueCore(object value)
        {
            _property.SetValue(value);
        }

        // TODO: DependencyProperty validation should be placed here
        /// <summary>
        /// Validates the value.
        /// </summary>
        /// <param name="valueToValidate">The value to validate.</param>
        protected void ValidateValue(object valueToValidate)
        {
            //throw new NotImplementedException();
            // Do nothing
        }

        private void SetValueImpl(object value)
        {
            //this.ValidateValue(value);
            if (ParentProperty.Validate(value))
                SetValueCore(value);

            NotifyValueChanged();
            OnRootValueChanged();
        }

        /// <summary>
        /// Raises the <see cref="PropertyValueException"/> event.
        /// </summary>
        /// <param name="e">The <see cref="WpfPropertyGrid.ValueExceptionEventArgs"/> instance containing the event data.</param>
        protected virtual void OnPropertyValueException(ValueExceptionEventArgs e)
        {
            if (e == null) throw new ArgumentNullException("e");
            if (PropertyValueException != null) PropertyValueException(this, e);
        }

        /// <summary>
        /// Gets a value indicating whether exceptions should be cought.
        /// </summary>
        /// <value><c>true</c> if expceptions should be cought; otherwise, <c>false</c>.</value>
        protected virtual bool CatchExceptions
        {
            get { return (PropertyValueException != null); }
        }

        /// <summary>
        /// Gets or sets the string representation of the value.
        /// </summary>
        /// <value>The string value.</value>
        public string StringValue
        {
            get
            {
                string str = string.Empty;
                if (CatchExceptions)
                {
                    try
                    {
                        str = ConvertValueToString(Value);
                    }
                    catch (Exception exception)
                    {
                        OnPropertyValueException(new ValueExceptionEventArgs("Cannot convert value to string", this, ValueExceptionSource.Get, exception));
                    }
                    return str;
                }
                return ConvertValueToString(Value);
            }
            set
            {
                if (CatchExceptions)
                {
                    try
                    {
                        Value = ConvertStringToValue(value);
                    }
                    catch (Exception exception)
                    {
                        OnPropertyValueException(new ValueExceptionEventArgs("Cannot create value from string", this, ValueExceptionSource.Set, exception));
                    }
                }
                else
                {
                    Value = ConvertStringToValue(value);
                }
            }
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>The value.</value>
        public object Value
        {
            get
            {
                object valueCore = null;
                if (CatchExceptions)
                {
                    try
                    {
                        valueCore = GetValueCore();
                    }
                    catch (Exception exception)
                    {
                        OnPropertyValueException(new ValueExceptionEventArgs("Value Get Failed", this, ValueExceptionSource.Get, exception));
                    }
                    return valueCore;
                }
                return GetValueCore();
            }
            set
            {
                if (CatchExceptions)
                {
                    try
                    {
                        SetValueImpl(value);
                    }
                    catch (Exception exception)
                    {
                        OnPropertyValueException(new ValueExceptionEventArgs("Value Set Failed", this, ValueExceptionSource.Set, exception));
                    }
                }
                else
                {
                    SetValueImpl(value);
                }
            }
        }

        #endregion

        #region Helper properties

        /// <summary>
        /// Gets a value indicating whether encapsulated property value is read only.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is read only; otherwise, <c>false</c>.
        /// </value>
        public bool IsReadOnly
        {
            get { return _property.IsReadOnly; }
        }

        /// <summary>
        /// Gets a value indicating whether encapsulated property value is editable.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is editable; otherwise, <c>false</c>.
        /// </value>
        public bool IsEditable
        {
            get { return !_property.IsReadOnly; }
        }

        public bool IsMultiLines
        {
            get { return _property.IsMultiLines; }
        }

        public int MaxLines
        {
            get
            {
                return _property.MaxLines;
            }
        }
        public int MinLines
        {
            get
            {
                return _property.MinLines;
            }
        }

        #endregion

        /// <summary>
        /// Gets the serialization culture.
        /// </summary>
        /// <returns>Culture to serialize value.</returns>
        protected virtual CultureInfo GetSerializationCulture()
        {
            return ObjectServices.GetSerializationCulture(_property.PropertyType);
        }

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Called when property value is changed.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// Notifies the root value changed.
        /// </summary>
        protected virtual void NotifyRootValueChanged()
        {
            OnPropertyChanged("IsDefaultValue");
            OnPropertyChanged("IsMixedValue");
            OnPropertyChanged("IsCollection");
            OnPropertyChanged("Collection");
            OnPropertyChanged("HasSubProperties");
            OnPropertyChanged("SubProperties");
            OnPropertyChanged("Source");
            OnPropertyChanged("CanConvertFromString");
            NotifyValueChanged();
            OnRootValueChanged();
        }

        private void NotifyStringValueChanged()
        {
            OnPropertyChanged("StringValue");
        }

        /// <summary>
        /// Notifies the sub property changed.
        /// </summary>
        protected void NotifySubPropertyChanged(object sender, EventArgs args)
        {
            NotifyValueChanged();
            OnSubPropertyChanged();
        }

        private void NotifyValueChanged()
        {
            OnPropertyChanged("Value");
            NotifyStringValueChanged();
        }

        private void OnRootValueChanged()
        {
            var handler = RootValueChanged;
            if (handler != null) handler(this, EventArgs.Empty);
        }

        private void OnSubPropertyChanged()
        {
            var handler = SubPropertyChanged;
            if (handler != null) handler(this, EventArgs.Empty);
        }

        #endregion

    }
}


text:
'use strict'
/*jshint expr:true*/

var helper = require('../../lib/agent_helper.js')
  , chai = require('chai')
  , assert = chai.assert
  , Transaction = require('../../../lib/transaction')
  , tests = require('../../lib/cross_agent_tests/cat_map.json')
  , _isValidReferringHash = require('../../../lib/instrumentation/core/http.js')._isValidReferringHash

function mockTransaction(agent, test, duration) {
  var trans = new Transaction(agent)

  // non-CAT data
  trans.name = test.transactionName
  trans.timer.duration = duration
  trans.timer.start = 2
  trans.id = test.transactionGuid
  trans.webSegment = {getDurationInMillis: function () {return trans.timer.duration}}

  // CAT data

  if (test.inboundPayload) {
    trans.tripId = test.inboundPayload[2]
    trans.referringTransactionGuid = test.inboundPayload[0]

    if (_isValidReferringHash(test.inboundPayload[3])) {
      trans.referringPathHash = test.inboundPayload[3]
    }
  }

  if (test.outboundRequests) {
    test.outboundRequests.forEach(function (req) {
      trans.pushPathHash(req.expectedOutboundPayload[3])
    })
  }

  return trans
}

describe('when CAT is disabled', function () {
  var agent

  before(function() {
    agent = helper.loadMockedAgent({cat: false});
  })

  after(function() {
    helper.unloadAgent(agent)
  })

  tests.forEach(function(test) {
    it(test.name + ' transaction event should only contain non-CAT intrinsic attributes', function() {
      var trans = mockTransaction(agent, test, 5000)

      var attrs = agent._addIntrinsicAttrsFromTransaction(trans)

      var expected = {
        duration: 5,
        name: test.transactionName,
        timestamp: 2,
        type: 'Transaction',
        webDuration: 5,
      }

      assert.deepEqual(attrs, expected)
    })
  })
})

describe('when CAT is enabled', function () {
  var agent

  before(function() {
    // App name from test data
    // encoding_key from ben in agent dev
    agent = helper.loadMockedAgent({cat: true})
    agent.config.applications = function newFake() {return ['testAppName'];}
  })

  after(function() {
    helper.unloadAgent(agent)
  })

  var durations = [100, 300, 1000]

  tests.forEach(function(test, index) {
    it(test.name + ' transaction event should contain all intrinsic attributes', function() {
      var idx = index % durations.length
      var duration = durations[idx]
      var trans = mockTransaction(agent, test, duration)

      var attrs = agent._addIntrinsicAttrsFromTransaction(trans)

      var expected = {
        duration: duration/1000,
        name: test.transactionName,
        timestamp: 2,
        type: 'Transaction',
        webDuration: duration/1000,
        'nr.guid': test.expectedIntrinsicFields['nr.guid'],
        'nr.pathHash': test.expectedIntrinsicFields['nr.pathHash'],
        'nr.referringPathHash': test.expectedIntrinsicFields['nr.referringPathHash'],
        'nr.tripId': test.expectedIntrinsicFields['nr.tripId'],
        'nr.referringTransactionGuid': test.expectedIntrinsicFields['nr.referringTransactionGuid'],
        'nr.alternatePathHashes': test.expectedIntrinsicFields['nr.alternatePathHashes'],
      }
      if (test.expectedIntrinsicFields['nr.pathHash']) {
        // nr.apdexPerfZone not specified in the test, this is used to exercise it.
        switch (idx) {
          case 0:
            expected['nr.apdexPerfZone'] = 'S'
            break
          case 1:
            expected['nr.apdexPerfZone'] = 'T'
            break
          case 2:
            expected['nr.apdexPerfZone'] = 'F'
            break
        }

      }
      for (var i = 0; i < test.nonExpectedIntrinsicFields.length; i++) {
        delete expected[test.nonExpectedIntrinsicFields[i]]
      }
      assert.deepEqual(attrs, expected)
    })
  })
})


text:
package com.github.danielwegener.logback.kafka.encoding;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Layout;
import org.hamcrest.Matchers;
import org.junit.Test;

import java.nio.charset.Charset;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class LayoutKafkaMessageEncoderTest {

    private static final Charset UTF8 = Charset.forName("UTF-8");
    private final PatternLayout layout = new PatternLayout();
    private final LayoutKafkaMessageEncoder<ILoggingEvent> unit = new LayoutKafkaMessageEncoder<ILoggingEvent>(layout, UTF8);

    @Test
    public void testStart() {
        unit.start();
        assertTrue("isStarted",unit.isStarted());
    }

    @Test
    public void testDoEncode() {
        final LoggerContext ctx = new LoggerContext();
        layout.setContext(ctx);
        layout.setPattern("prefix %msg");
        layout.start();
        final Logger logger = ctx.getLogger("logger");
        final LoggingEvent evt = new LoggingEvent("fqcn", logger, Level.ALL,"message", null, new Object[0]);
        assertThat(unit.doEncode(evt), equalTo("prefix message".getBytes()));
    }

    @Test
    public void testGetLayout() {
        assertThat(unit.getLayout(), Matchers.<Layout<?>>equalTo(layout));
    }

    @Test
    public void testGetCharset() {
        assertThat(unit.getCharset(), equalTo(UTF8));
    }

}


text:
package org.apache.harmony.rmi.registry;

import java.rmi.registry.LocateRegistry;

import junit.framework.TestCase;

public class LocateRegistryTest extends TestCase {

    /**
     * Test for method createRegistry(int port)
     */
    public void test_createRegistryI() throws Exception {
        try {
            LocateRegistry.createRegistry(-1);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
        	//expected
        }
    }
}


text:
package org.apache.hadoop.hbase.ipc;

import com.google.protobuf.Message;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader;

/**
 * Function to figure priority of incoming request.
 */
@InterfaceAudience.LimitedPrivate({HBaseInterfaceAudience.COPROC, HBaseInterfaceAudience.PHOENIX})
@InterfaceStability.Evolving
public interface PriorityFunction {
  /**
   * @param header
   * @param param
   * @return Priority of this request.
   */
  int getPriority(RequestHeader header, Message param);
}


text:
<!DOCTYPE html>

        <title>Simple Search - demos</title>

Simple Search - demos

Hello World list

as plain text repsponse

as HTML response


text:
package com.eaw1805.data.managers.forum;

import com.eaw1805.data.managers.AbstractManager;
import com.eaw1805.data.managers.beans.UserPermissionManagerBean;
import com.eaw1805.data.model.User;
import com.eaw1805.data.model.forum.UserPermissions;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import java.util.List;

/**
 * CRUD operations for UserPermissions objects.
 */
public class UserPermissionManager extends AbstractManager<UserPermissions>
        implements UserPermissionManagerBean {

    /**
     * static instance(ourInstance) initialized as null.
     */
    private static UserPermissionManagerBean ourInstance = null;

    /**
     * Private constructor suppresses generation of a (public) default constructor.
     */
    public UserPermissionManager() {
        // Does nothing
        super();
    }

    /**
     * GameManager is loaded on the first execution of UserPermissionManager.getInstance()
     * or the first access to UserPermissionManager.ourInstance, not before.
     *
     * @return ourInstance
     */
    public static UserPermissionManagerBean getInstance() {
        synchronized (UserPermissionManager.class) {
            if (ourInstance == null) {
                ourInstance = new UserPermissionManager();
            }
        }

        return ourInstance;
    }

    /**
     * Set the global instance of the manager. Used for the integration with Spring.
     *
     * @param thisInstance the manager bean.
     */
    public static void setInstance(final UserPermissionManagerBean thisInstance) {
        ourInstance = thisInstance;
    }

    /**
     * Delete the input UserPermission Entity from the database.
     *
     * @param userPermissions the UserPermission Entity that we want to delete
     */
    public void delete(final UserPermissions userPermissions) {
        super.delete(userPermissions, userPermissions.getId());
    }

    /**
     * Listing all the UserPermissions from the database.
     *
     * @return a list of all the UserPermissions that exist inside the table Users.
     */
    public List<UserPermissions> list() {
        return super.list(new UserPermissions());
    }

    /**
     * Listing all the UserPermissions for a specific user from the database.
     *
     * @param user the input user.
     * @return a list of all the UserPermissions that exist inside the table phpbb_acl_users.
     */
    @Override
    public List<UserPermissions> list(final User user) {
        final Session session = getSessionFactory().getCurrentSession();
        final Criteria criteria = session.createCriteria(UserPermissions.class);
        criteria.add(Restrictions.eq("user", user));
        return criteria.list();
    }

    /**
     * Returning the UserPermission for a specific user and forum from the database.
     *
     * @param user    the input user.
     * @param forumId the forum id.
     * @return the UserPermission, if exists inside the table phpbb_acl_users.
     */
    @Override
    public UserPermissions getForumPermissions(final User user, final int forumId) {
        final Session session = getSessionFactory().getCurrentSession();
        final Criteria criteria = session.createCriteria(UserPermissions.class);
        criteria.add(Restrictions.eq("user", user));
        criteria.add(Restrictions.eq("forumId", forumId));
        return (UserPermissions) criteria.uniqueResult();
    }
}