text:
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper")

describe "AssociationAutoreloading plugin" do
  before do
    @c = Class.new(Sequel::Model)
    @c.plugin :association_autoreloading
    @Artist = Class.new(@c).set_dataset(:artists)
    @Artist.dataset._fetch = {:id=>2, :name=>'Ar'}
    @Album = Class.new(@c).set_dataset(:albums)
    @Artist.columns :id, :name
    @Album.columns :id, :name, :artist_id
    @Album.db_schema[:artist_id][:type] = :integer
    @Album.many_to_one :artist, :class=>@Artist
    MODEL_DB.reset
  end

  specify "should reload many_to_one association when foreign key is modified" do
    album = @Album.load(:id => 1, :name=>'Al', :artist_id=>2)
    album.artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 2) LIMIT 1']

    album.artist_id = 1
    album.artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 1) LIMIT 1']
  end

  specify "should handle multiple many_to_one association with the same foreign key" do
    @Album.many_to_one :artist2, :key=>:artist_id, :class=>@Artist
    album = @Album.load(:id => 1, :name=>'Al', :artist_id=>2)
    album.artist
    album.artist2
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 2) LIMIT 1'] * 2

    album.artist
    album.artist2
    MODEL_DB.sqls.should == []

    album.artist_id = 1
    album.artist
    album.artist2
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 1) LIMIT 1'] * 2
  end

  specify "should not reload when value has not changed" do
    album = @Album.load(:id => 1, :name=>'Al', :artist_id=>2)
    album.artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 2) LIMIT 1']

    album.artist_id = 2
    album.artist
    MODEL_DB.sqls.should == []

    album.artist_id = "2"
    album.artist
    MODEL_DB.sqls.should == []
  end

  specify "should reload all associations which use the foreign key" do
    @Album.many_to_one :other_artist, :key => :artist_id, :foreign_key => :id, :class => @Artist
    album = @Album.load(:id => 1, :name=>'Al', :artist_id=>2)
    album.artist
    album.other_artist
    MODEL_DB.reset

    album.artist_id = 1
    album.artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 1) LIMIT 1']

    album.other_artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 1) LIMIT 1']
  end

  specify "should work with composite keys" do
    @Album.many_to_one :composite_artist, :key => [:artist_id, :name], :primary_key => [:id, :name], :class => @Artist
    album = @Album.load(:id => 1, :name=>'Al', :artist_id=>2)
    album.composite_artist
    MODEL_DB.reset

    album.artist_id = 1
    album.composite_artist
    MODEL_DB.sqls.should == ["SELECT * FROM artists WHERE ((artists.id = 1) AND (artists.name = 'Al')) LIMIT 1"]

    album.name = 'Al2'
    album.composite_artist
    MODEL_DB.sqls.should == ["SELECT * FROM artists WHERE ((artists.id = 1) AND (artists.name = 'Al2')) LIMIT 1"]
  end

  specify "should work with subclasses" do
    salbum = Class.new(@Album)
    oartist = Class.new(@c).set_dataset(:oartist)
    oartist.columns :id, :name
    salbum.many_to_one :artist2, :class=>oartist, :key=>:artist_id
    album = salbum.load(:id => 1, :name=>'Al', :artist_id=>2)
    album.artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 2) LIMIT 1']

    album.artist_id = 1
    album.artist
    MODEL_DB.sqls.should == ['SELECT * FROM artists WHERE (artists.id = 1) LIMIT 1']
  end

end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>couchdbkit.client</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package couchdbkit ::
        Module client

[hide private]

[frames] | no frames]

Module client

source code

Client implementation for CouchDB access. It allows you to manage a
  CouchDB server, databases, documents and views. All objects mostly
  reflect python objects for convenience. Server and Database objects for
  example, can be used as easy as a dict.

Example:

>>> from couchdbkit import Server
>>> server = Server()
>>> db = server.create_db('couchdbkit_test')
>>> doc = { 'string': 'test', 'number': 4 }
>>> db.save_doc(doc)
>>> docid = doc['_id']
>>> doc2 = db.get(docid)
>>> doc['string']
u'test'
>>> del db[docid]
>>> docid in db
False
>>> del server['simplecouchdb_test']

        Classes
        [hide private]

        Server

      Server object that allows you to access and manage a couchdb node.

        Database

      Object that abstract access to a CouchDB database A Database object
        can act as a Dict object.

        ViewResults

      Object to retrieve view results.

        ViewInterface

      Generic object interface used by View and TempView objects.

        View

      Object used to wrap a view and return ViewResults.

        TempView

      Object used to wrap a temporary and return ViewResults.

        Functions
        [hide private]

          _maybe_serialize(doc)

            source code

        Variables
        [hide private]

        UNKOWN_INFO = {}

        DEFAULT_UUID_BATCH_COUNT = 1000

        __package__ = 'couchdbkit'

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Fri Feb 18 10:31:27 2011

      http://epydoc.sourceforge.net

redpajama_set_name: RedPajamaGithub


text:
/******************************************
 *                                        *
 *  dcm4che: A OpenSource DICOM Toolkit   *
 *                                        *
 *  Distributable under LGPL license.     *
 *  See terms of license at gnu.org.      *
 *                                        *
 ******************************************/
package org.dcm4chex.archive.codec;

import java.awt.color.ColorSpace;
import java.awt.image.BandedSampleModel;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferShort;
import java.awt.image.DataBufferUShort;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteOrder;
import java.security.DigestOutputStream;
import java.security.MessageDigest;

import javax.imageio.IIOImage;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;

import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmDecodeParam;
import org.dcm4che.data.DcmEncodeParam;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.DcmParser;
import org.dcm4che.data.DcmParserFactory;
import org.dcm4che.data.FileFormat;
import org.dcm4che.data.FileMetaInfo;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.dict.VRs;

import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam;

/**
 * @author gunter.zeilinter@tiani.com
 * @version $Revision: 1617 $ $Date: 2005-03-16 23:31:20 +0800 (周三, 16 3月 2005) $
 * @since 11.06.2004
 *
 */
public abstract class CompressCmd extends CodecCmd {

    private static final byte[] ITEM_TAG = { (byte) 0xfe, (byte) 0xff,
            (byte) 0x00, (byte) 0xe0};

    private static final int[] GRAY_BAND_OFFSETS = { 0};

    private static final int[] RGB_BAND_OFFSETS = { 0, 1, 2};

    private static class Jpeg2000 extends CompressCmd {

        public Jpeg2000(Dataset ds) {
            super(ds, true);
        }

        public void coerceDataset(Dataset ds) {
            if (samples == 3) {
                ds.putUS(Tags.PlanarConfiguration, 0);
                ds.putCS(Tags.PhotometricInterpretation, YBR_RCT);
            }
        }

        protected ImageWriter getWriter() {
            return CodecCmd.getImageWriter(JPEG2000, J2K_IMAGE_WRITER_CODEC_LIB);
        }

        protected void initWriteParam(ImageWriteParam param) {
            J2KImageWriteParam j2KwParam = (J2KImageWriteParam) param;
            j2KwParam.setWriteCodeStreamOnly(true);
        }
    };

    private static class JpegLossless extends CompressCmd {

        public JpegLossless(Dataset ds) {
            super(ds, false);
        }

        public void coerceDataset(Dataset ds) {
            if (samples == 3) {
                ds.putUS(Tags.PlanarConfiguration, 0);
            }
        }

        protected ImageWriter getWriter() {
            return CompressCmd.getImageWriter(JPEG, CLIB_JPEG_IMAGE_WRITER);
        }

        protected void initWriteParam(ImageWriteParam param) {
            param.setCompressionType(JPEG_LOSSLESS);
        }
    };

    private static class JpegLS extends CompressCmd {

        public JpegLS(Dataset ds) {
            super(ds, false);
        }

        public void coerceDataset(Dataset ds) {
            if (samples == 3) {
                ds.putUS(Tags.PlanarConfiguration, 0);
            }

        }

        protected ImageWriter getWriter() {
            return CompressCmd.getImageWriter(JPEG, CLIB_JPEG_IMAGE_WRITER);
        }

        protected void initWriteParam(ImageWriteParam param) {
            param.setCompressionType(JPEG_LS);
        }
    };

    public static byte[] compressFile(File inFile, File outFile, String tsuid,
    		int[] pxdataVR)
    		throws Exception {
        log.info("M-READ file:" + inFile);
    	InputStream in = new BufferedInputStream(new FileInputStream(inFile));
    	try {
    		DcmParser p = DcmParserFactory.getInstance().newDcmParser(in);
    		final DcmObjectFactory of = DcmObjectFactory.getInstance();
			Dataset ds = of.newDataset();
    		p.setDcmHandler(ds.getDcmHandler());
    		p.parseDcmFile(FileFormat.DICOM_FILE, Tags.PixelData);
    		if (pxdataVR != null && pxdataVR.length != 0)
    			pxdataVR[0] = p.getReadVR();
    		FileMetaInfo fmi = of.newFileMetaInfo(ds, tsuid);
    		ds.setFileMetaInfo(fmi);
            log.info("M-WRITE file:" + outFile);
            BufferedOutputStream os = new BufferedOutputStream(
                    new FileOutputStream(outFile));
            MessageDigest md = MessageDigest.getInstance("MD5");
            DigestOutputStream dos = new DigestOutputStream(os, md);
            try {
                DcmDecodeParam decParam = p.getDcmDecodeParam();
    			DcmEncodeParam encParam = DcmEncodeParam.valueOf(tsuid);
                CompressCmd compressCmd = CompressCmd.createCompressCmd(ds);
                compressCmd.coerceDataset(ds);
                ds.writeFile(dos, encParam);
                ds.writeHeader(dos, encParam, Tags.PixelData, VRs.OB, -1);
                int read = compressCmd.compress(decParam.byteOrder, in, dos);
                ds.writeHeader(dos, encParam, Tags.SeqDelimitationItem,
                        VRs.NONE, 0);
                in.skip(p.getReadLength() - read);
                p.parseDataset(decParam, -1);
                ds.subSet(Tags.PixelData, -1).writeDataset(dos, encParam);
            } finally {
                dos.close();
            }
            return md.digest();
    	} finally {
    		in.close();
    	}
    }

    public static CompressCmd createCompressCmd(Dataset ds) {
    	String tsuid = ds.getFileMetaInfo().getTransferSyntaxUID();
    	if (UIDs.JPEG2000Lossless.equals(tsuid))
                return new Jpeg2000(ds);
        if (UIDs.JPEGLSLossless.equals(tsuid)) return new JpegLS(ds);
        if (UIDs.JPEGLossless.equals(tsuid)
                || UIDs.JPEGLossless14.equals(tsuid))
                return new JpegLossless(ds);
        throw new IllegalArgumentException("tsuid:" + tsuid);
    }

    private final DcmEncodeParam encParam;

    protected final int dataType;

    protected CompressCmd(Dataset ds, boolean supportSigned) {
    	super(ds);
        this.encParam = DcmEncodeParam.valueOf(ds.getFileMetaInfo()
                .getTransferSyntaxUID());

        switch (bitsAllocated) {
        case 8:
            this.dataType = DataBuffer.TYPE_BYTE;
            break;
        case 16:
            this.dataType = pixelRepresentation == 0 || !supportSigned ? DataBuffer.TYPE_USHORT
                    : DataBuffer.TYPE_SHORT;
            break;
        default:
            throw new IllegalArgumentException("bits allocated:"
                    + bitsAllocated);
        }
    }

    public abstract void coerceDataset(Dataset ds);

    protected abstract ImageWriter getWriter();

    protected abstract void initWriteParam(ImageWriteParam param);

    public int compress(ByteOrder byteOrder, InputStream in, OutputStream out)
            throws Exception {
        long t1;
        ImageWriter w = null;
        boolean codecSemaphoreAquired = false;
        long end = 0;
        try {
            log.debug("acquire codec semaphore");
            codecSemaphore.acquire();
            codecSemaphoreAquired = true;
            log.info("start compression of image: " + rows + "x" + columns
                    + "x" + frames);
            t1 = System.currentTimeMillis();
            ImageOutputStream ios = new MemoryCacheImageOutputStream(out);
            ios.setByteOrder(ByteOrder.LITTLE_ENDIAN);
            w = getWriter();
            ImageWriteParam wParam = w.getDefaultWriteParam();
            initWriteParam(wParam);
            WritableRaster raster = Raster.createWritableRaster(
                    getSampleModel(), null);
            DataBuffer db = raster.getDataBuffer();
            BufferedImage bi = new BufferedImage(getColorModel(), raster,
                    false, null);
            ios.write(ITEM_TAG);
            ios.writeInt(0);
            for (int i = 0; i < frames; ++i) {
                log.debug("start compression of frame #" + (i + 1));
                ios.write(ITEM_TAG);
                long mark = ios.getStreamPosition();
                ios.writeInt(0);
                switch (dataType) {
                case DataBuffer.TYPE_BYTE:
                    read(in, ((DataBufferByte) db).getBankData());
                    break;
                case DataBuffer.TYPE_SHORT:
                    read(byteOrder, in, ((DataBufferShort) db).getBankData());
                    break;
                case DataBuffer.TYPE_USHORT:
                    read(byteOrder, in, ((DataBufferUShort) db).getBankData());
                    break;
                default:
                    throw new RuntimeException("dataType:" + db.getDataType());
                }
                w.setOutput(ios);
                w.write(null, new IIOImage(bi, null, null), wParam);
                end = ios.getStreamPosition();
                if ((end & 1) != 0) {
                    ios.write(0);
                    ++end;
                }
                ios.seek(mark);
                ios.writeInt((int) (end - mark - 4));
                ios.seek(end);
                ios.flush();
            }
        } finally {
            if (w != null) w.dispose();
            if (codecSemaphoreAquired) {
                log.debug("release codec semaphore");
                codecSemaphore.release();
            }
        }
        long t2 = System.currentTimeMillis();
        int pixelDataLength = frameLength * frames;
        log.info("finished compression " + ((float) pixelDataLength / end)
                + " : 1 in " + (t2 - t1) + "ms.");
        return pixelDataLength;
    }

    private void read(ByteOrder byteOrder, InputStream in, short[][] data)
            throws IOException {
        if (byteOrder == ByteOrder.LITTLE_ENDIAN)
            readLE(in, data);
        else
            readBE(in, data);
    }

    private void readLE(InputStream in, short[][] data) throws IOException {
        int lo, hi;
        for (int i = 0; i < data.length; i++) {
            short[] bank = data[i];
            for (int j = 0; j < bank.length; j++) {
                lo = in.read();
                hi = in.read();
                if ((lo | hi) < 0) throw new EOFException();
                bank[j] = (short) ((lo & 0xff) + (hi << 8));
            }
        }
    }

    private void readBE(InputStream in, short[][] data) throws IOException {
        int lo, hi;
        for (int i = 0; i < data.length; i++) {
            short[] bank = data[i];
            for (int j = 0; j < bank.length; j++) {
                hi = in.read();
                lo = in.read();
                if ((lo | hi) < 0) throw new EOFException();
                bank[j] = (short) ((lo & 0xff) + (hi << 8));
            }
        }
    }

    private void read(InputStream in, byte[][] data) throws IOException {
    	int read;
        for (int i = 0; i < data.length; i++) {
            byte[] bank = data[i];
            for (int toread = bank.length; toread > 0;) {
                read = in.read(bank, bank.length - toread, toread);
                if ( read == -1 ) throw new EOFException("Length of pixel matrix is too short!");
                toread -= read;
            }
        }
    }

    private SampleModel getSampleModel() {
        if (planarConfiguration == 0) {
            return new PixelInterleavedSampleModel(dataType, columns, rows,
                    samples, columns * samples,
                    samples == 1 ? GRAY_BAND_OFFSETS : RGB_BAND_OFFSETS);
        } else {
            return new BandedSampleModel(dataType, columns, rows, samples);
        }
    }

    private ColorModel getColorModel() {
        if (samples == 3) {
            return new ComponentColorModel(ColorSpace
                    .getInstance(ColorSpace.CS_sRGB), new int[] { bitsStored,
                    bitsStored, bitsStored}, false, false, ColorModel.OPAQUE,
                    dataType);
        } else {
            return new ComponentColorModel(ColorSpace
                    .getInstance(ColorSpace.CS_GRAY), new int[] { bitsStored},
                    false, false, ColorModel.OPAQUE, dataType);
        }
    }
}


text:
module Billing
  class Resource < ActiveRecord::Base
  end
end


text:
<?php

namespace VMelnik\SecureFormBundle\Config;

/**
 * Config for secure form type extension
 *
 * @author Victor Melnik <melnikvictorl@gmail.com>
 */
class ExtensionConfig
{

    /**
     * Is extension enabled flag
     *
     * @var boolean
     */
    protected $enabled;

    /**
     * Option name to enable/disable extension in forms
     *
     * @var string
     */
    protected $enabledOptionName;

    /**
     * Is client side validation enabled
     *
     * @var boolean
     */
    protected $csv;

    /**
     * Client side validation class name
     *
     * @var string
     */
    protected $csvClass;

    /**
     * Client side validation option name to enable/disable this type of validation
     *
     * @var string
     */
    protected $csvOptionName;

    /**
     * Server side filtering with stip tags flag
     *
     * @var boolean
     */
    protected $ssvStripTags;

    /**
     * Strip tags option name to enable/disable this type of filtering
     *
     * @var string
     */
    protected $ssvStripTagsOptionName;

    /**
     * Ignore fields option name
     *
     * @var string
     */
    protected $ignoreFieldsOptionName;

    /**
     * Initialization of config object
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->enabled = $config['enabled'];
        $this->enabledOptionName = $config['enabled_option_name'];
        $this->csv = $config['csv']['enabled'];
        $this->csvClass = $config['csv']['class'];
        $this->csvOptionName = $config['csv']['option_name'];
        $this->ssvStripTags = $config['ssv']['strip_tags']['enabled'];
        $this->ssvStripTagsOptionName = $config['ssv']['strip_tags']['option_name'];
        $this->ignoreFieldsOptionName = $config['ignore_fields_option_name'];
    }

    /**
     * Is validation enabled
     *
     * @return boolean
     */
    public function isEnabled()
    {
        return $this->enabled;
    }

    /**
     * Get validation enabled option name
     *
     * @return string
     */
    public function getEnabledOptionName()
    {
        return $this->enabledOptionName;
    }

    /**
     * Is client side validation enabled
     *
     * @return boolean
     */
    public function isCsvEnabled()
    {
        return $this->csv;
    }

    /**
     * Get client side validation class name
     *
     * @return string
     */
    public function getCsvClass()
    {
        return $this->csvClass;
    }

    /**
     * Get client side validation option name
     *
     * @return string
     */
    public function getCsvOptionName()
    {
        return $this->csvOptionName;
    }

    /**
     * Is server side strip tags filtering enabled
     *
     * @return boolean
     */
    public function isSsvStripTagsEnabled()
    {
        return $this->ssvStripTags;
    }

    /**
     * Get server side strip tags option name
     *
     * @return string
     */
    public function getSsvStripTagsOptionName()
    {
        return $this->ssvStripTagsOptionName;
    }

    /**
     * Get ignore fields option name
     *
     * @return string
     */
    public function getIgnoreFieldsOptionName()
    {
        return $this->ignoreFieldsOptionName;
    }

}


text:
classdef KeyPointsFilter
    %KEYPOINTSFILTER  Methods to filter a vector of keypoints.
    %
    % See also: cv.FeatureDetector
    %

    methods (Static)
        function keypoints = runByImageBorder(keypoints, imgSize, borderSize)
            %RUNBYIMAGEBORDER  Remove keypoints within borderPixels of an image edge.
            %
            %    keypoints = cv.KeyPointsFilter.runByImageBorder(keypoints, imgSize, borderSize)
            %
            % ## Input
            % * __keypoints__ input collection of keypoints.
            % * __imgSize__ image size `[width,height]`
            % * __borderSize__ border size
            %
            % ## Output
            % * __keypoints__ output filtered keypoints.
            %
            keypoints = KeyPointsFilter_('runByImageBorder', keypoints, imgSize, borderSize);
        end

        function keypoints = runByKeypointSize(keypoints, minSize, maxSize)
            %RUNBYKEYPOINTSIZE  Remove keypoints of sizes out of range.
            %
            %    keypoints = cv.KeyPointsFilter.runByKeypointSize(keypoints, minSize, maxSize)
            %
            % ## Input
            % * __keypoints__ input collection of keypoints.
            % * __minSize__ minimum keypoint size
            % * __maxSize__ maximum keypoint size. default `realmax('single')`
            %
            % ## Output
            % * __keypoints__ output filtered keypoints.
            %
            keypoints = KeyPointsFilter_('runByKeypointSize', keypoints, minSize, maxSize);
        end

        function keypoints = runByPixelsMask(keypoints, mask)
            %RUNBYPIXELSMASK  Remove keypoints from some image by mask for pixels of this image.
            %
            %    keypoints = cv.KeyPointsFilter.runByPixelsMask(keypoints, mask)
            %
            % ## Input
            % * __keypoints__ input collection of keypoints.
            % * __mask__ image mask
            %
            % ## Output
            % * __keypoints__ output filtered keypoints.
            %
            keypoints = KeyPointsFilter_('runByPixelsMask', keypoints, mask);
        end

        function keypoints = removeDuplicated(keypoints)
            %REMOVEDUPLICATED  Remove duplicated keypoints.
            %
            %    keypoints = cv.KeyPointsFilter.removeDuplicated(keypoints)
            %
            % ## Input
            % * __keypoints__ input collection of keypoints.
            %
            % ## Output
            % * __keypoints__ output filtered keypoints.
            %
            keypoints = KeyPointsFilter_('removeDuplicated', keypoints);
        end

        function keypoints = retainBest(keypoints, npoints)
            %RETAINBEST  Retain the specified number of the best keypoints (according to the response).
            %
            %    keypoints = cv.KeyPointsFilter.retainBest(keypoints, npoints)
            %
            % ## Input
            % * __keypoints__ input collection of keypoints.
            % * __npoints__ number of keypoints to retain
            %
            % ## Output
            % * __keypoints__ output filtered keypoints.
            %
            keypoints = KeyPointsFilter_('retainBest', keypoints, npoints);
        end
    end

end


text:
import Reflux from 'reflux';

import {Indicator} from 'app/actionCreators/indicator';
import IndicatorActions from 'app/actions/indicatorActions';
import {t} from 'app/locale';

type IndicatorStoreInterface = {
  init: () => void;
  addSuccess: (message: string) => Indicator;
  addError: (message?: string) => Indicator;
  /**
   * Appends a message to be displayed in list of indicators
   *
   * @param message Toast message to be displayed
   * @param type One of ['error', 'success', '']
   * @param options Options object
   */
  append: (
    message: string,
    type: Indicator['type'],
    options?: Indicator['options']
  ) => Indicator;
  /**
   * When this method is called directly via older parts of the application,
   * we want to maintain the old behavior in that it is replaced (and not queued up)
   *
   * @param message Toast message to be displayed
   * @param type One of ['error', 'success', '']
   * @param options Options object
   */
  add: (
    message: string,
    type?: Indicator['type'],
    options?: Indicator['options']
  ) => Indicator;
  /**
   * Alias for add()
   */
  addMessage: (
    message: string,
    type: Indicator['type'],
    options?: Indicator['options']
  ) => Indicator;
  /**
   * Remove all current indicators.
   */
  clear: () => void;
  /**
   * Remove an indicator
   */
  remove: (indicator: Indicator) => void;
};

type Internals = {
  items: any[];
  lastId: number;
};

const storeConfig: Reflux.StoreDefinition & IndicatorStoreInterface & Internals = {
  items: [],
  lastId: 0,
  init() {
    this.items = [];
    this.lastId = 0;
    this.listenTo(IndicatorActions.append, this.append);
    this.listenTo(IndicatorActions.replace, this.add);
    this.listenTo(IndicatorActions.remove, this.remove);
    this.listenTo(IndicatorActions.clear, this.clear);
  },

  addSuccess(message) {
    return this.add(message, 'success', {duration: 2000});
  },

  addError(message = t('An error occurred')) {
    return this.add(message, 'error', {duration: 2000});
  },

  addMessage(message, type, {append, ...options} = {}) {
    const indicator: Indicator = {
      id: this.lastId++,
      message,
      type,
      options,
      clearId: null,
    };

    if (options.duration) {
      indicator.clearId = window.setTimeout(() => {
        this.remove(indicator);
      }, options.duration);
    }

    const newItems = append ? [...this.items, indicator] : [indicator];

    this.items = newItems;
    this.trigger(this.items);
    return indicator;
  },

  append(message, type, options) {
    return this.addMessage(message, type, {
      ...options,
      append: true,
    });
  },

  add(message, type = 'loading', options = {}) {
    return this.addMessage(message, type, {
      ...options,
      append: false,
    });
  },

  clear() {
    this.items = [];
    this.trigger(this.items);
  },

  remove(indicator) {
    if (!indicator) {
      return;
    }

    this.items = this.items.filter(item => item !== indicator);

    if (indicator.clearId) {
      window.clearTimeout(indicator.clearId);
      indicator.clearId = null;
    }

    this.trigger(this.items);
  },
};

type IndicatorStore = Reflux.Store & IndicatorStoreInterface;

export default Reflux.createStore(storeConfig) as IndicatorStore;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pimelea menkeana Lehm.

### Remarks
null


text:
@interface YRHtestViewController ()

@end

@implementation YRHtestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"test";
    self.view.backgroundColor = [UIColor redColor];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = YRHRGBColor(200, 50, 30);
    [self.navigationController pushViewController:vc animated:YES];
}

@end


text:
.. image:: logo-large.png

|
|

.. image:: https://circleci.com/gh/SpectoLabs/hoverfly.svg?style=shield
    :target: https://circleci.com/gh/SpectoLabs/hoverfly

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

.. image:: https://img.shields.io/badge/license-Apache%202-blue.svg
     :target: https://raw.githubusercontent.com/SpectoLabs/hoverfly/master/LICENSE

.. image:: https://img.shields.io/github/stars/SpectoLabs/hoverfly.svg
    :target: https://github.com/SpectoLabs/hoverfly/stargazers

.. image:: https://badges.gitter.im/SpectoLabs/hoverfly.svg
    :target: https://gitter.im/SpectoLabs/hoverfly

|

What is Hoverfly?
=================

Hoverfly is a lightweight, open source API simulation tool. Using Hoverfly, you can create realistic simulations of the APIs your application depends on.

- Replace slow, flaky API dependencies with realistic, re-usable simulations
- Simulate network latency, random failures or rate limits to test edge-cases
- Extend and customize with any programming language
- Export, share, edit and import API simulations
- CLI and native language bindings for `Java <http://docs.hoverfly.io/projects/hoverfly-java>`_ and `Python <http://docs.hoverfly.io/projects/hoverpy/>`_
- REST API
- Lightweight, high-performance, run anywhere
- Apache 2 license

Source
------

The Hoverfly source code is available on `GitHub <https://github.com/SpectoLabs/hoverfly>`_.

Hoverfly is developed and maintained by `SpectoLabs <https://specto.io>`_.

Contents
--------

.. toctree::
    :maxdepth: 2

    pages/introduction/introduction
    pages/keyconcepts/keyconcepts
    pages/bindings/bindings
    pages/tutorials/tutorials
    pages/reference/reference
    pages/contributing
    pages/community


text:
@interface PodsDummy_Pods_Wattpad_Life_AFNetworking : NSObject
@end
@implementation PodsDummy_Pods_Wattpad_Life_AFNetworking
@end


text:
package controllers

import (
	"github.com/robfig/revel"
	"github.com/robfig/revel/samples/chat/app/chatroom"
)

type Refresh struct {
	*rev.Controller
}

func (c Refresh) Index(user string) rev.Result {
	chatroom.Join(user)
	return c.Room(user)
}

func (c Refresh) Room(user string) rev.Result {
	subscription := chatroom.Subscribe()
	defer subscription.Cancel()
	events := subscription.Archive
	for i, _ := range events {
		if events[i].User == user {
			events[i].User = "you"
		}
	}
	return c.Render(user, events)
}

func (c Refresh) Say(user, message string) rev.Result {
	chatroom.Say(user, message)
	return c.Room(user)
}

func (c Refresh) Leave(user string) rev.Result {
	chatroom.Leave(user)
	return c.Redirect(Application.Index)
}


text:
import db from '../../db/mongodb';

export default db.get('notifications') as any; // fuck type definition


text:
package com.vc.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vc.service.BaseService;

@Service("baseService")
@Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class BaseServiceImpl implements BaseService {

}


text:
package edu.lab.web.controller.user;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import edu.lab.admin.user.UserTransactionBeanRemote;
import edu.lab.modelo.constant.ITipoUsuario;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author EstebanC02
 */
public class ManagementUser extends ActionSupport implements Serializable {

    UserTransactionBeanRemote userTransactionBean = lookupUserTransactionBeanRemote();

    private List<String> usersList = new ArrayList<>();
    private List<String> tipoList = new ArrayList<>();
    private List<Object> infoList = new ArrayList<>();

    private String idUser;
    private String itemSelected;
    private String tipoSelected;
    private String textoSelected;

    public ManagementUser() {
        loadValuesByDefault();
    }

    private void loadValuesByDefault() {
        try {
            List<String> obtenerCamposTablaUsuario = userTransactionBean.obtenerCamposTablaUsuario();
            if (obtenerCamposTablaUsuario != null) {
                usersList = obtenerCamposTablaUsuario;
            }
            tipoList.add(ITipoUsuario.ADMIN);
            tipoList.add(ITipoUsuario.MODERADOR);
            tipoList.add(ITipoUsuario.SIMPLE);
        } catch (Exception ex) {
            addActionError(ex.getMessage());
        }
    }

    @Override
    public String execute() throws Exception {
        List<Object> obtenerInfoTablaUsuario = userTransactionBean.obtenerUsuariosPorTipoDato(itemSelected, (itemSelected == null || textoSelected.isEmpty()) ? tipoSelected : textoSelected);
        infoList = obtenerInfoTablaUsuario;
        ActionContext.getContext().getSession().put("resultSearch", obtenerInfoTablaUsuario);
        itemSelected = textoSelected = tipoSelected = "";  // ESTO NO SE HACE
        return SUCCESS;
    }

    public String deleteUserAction() {
        try {
            userTransactionBean.eliminarUsuario(idUser);
            infoList = userTransactionBean.obtenerUsuariosPorTipoDato(itemSelected, (itemSelected == null || textoSelected.isEmpty()) ? tipoSelected : textoSelected);
        } catch (Exception ex) {
            addActionError(ex.getMessage());
        }
        return SUCCESS;
    }

    public List<Object> getInfoList() {
        infoList = (List<Object>) ActionContext.getContext().getSession().get("resultSearch");
        return infoList;
    }

    public String getIdUser() {
        return idUser;
    }

    public void setIdUser(String idUser) {
        this.idUser = idUser;
    }

    public void setInfoList(List<Object> infoList) {
        this.infoList = infoList;
    }

    public List<String> getTipoList() {
        return tipoList;
    }

    public void setTipoList(List<String> tipoList) {
        this.tipoList = tipoList;
    }

    public String getTipoSelected() {
        return tipoSelected;
    }

    public void setTipoSelected(String tipoSelected) {
        this.tipoSelected = tipoSelected;
    }

    public List<String> getUsersList() {
        return usersList;
    }

    public void setUsersList(List<String> usersList) {
        this.usersList = usersList;
    }

    public String getItemSelected() {
        return itemSelected;
    }

    public void setItemSelected(String itemSelected) {
        this.itemSelected = itemSelected;
    }

    public String getTextoSelected() {
        return textoSelected;
    }

    public void setTextoSelected(String textoSelected) {
        this.textoSelected = textoSelected;
    }

    private UserTransactionBeanRemote lookupUserTransactionBeanRemote() {
        try {
            Context c = new InitialContext();
            return (UserTransactionBeanRemote) c.lookup("java:global/JEE_Cookbook-ejb/UserTransactionBean!edu.lab.admin.user.UserTransactionBeanRemote");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}


text:
<#
.SYNOPSIS
   Retrieves Microsoft eBook from web location.
.DESCRIPTION
   Retrieves Microsoft eBook from web location and outputs information about the retrieval.
.PARAMETER MsftBook
   The URL of the Microsoft eBook to retrieve.
.PARAMETER DestinationFolder
   The optional filepath location to save the retrieved eBook.
.PARAMETER NoDownload
   If this switch is specified the eBook will not be retrieved.
.INPUTS
   System.String
   You can pipe a string that contains the URL of the Microsoft eBook to retrieve.
.OUTPUTS
   System.Management.Automation.PSCustomObject
   The cmdlet returns a PS custom object with the following member properties:
     Destination  - Full filepath name to retrieved eBook
     File         - Web server response file name
     Item         - Web request URL
     Source       - Web server response URI
.NOTES
   Name:    Get-MSFTBook
   Author:  Carnegie Johnson, MCT
   Email:   CarnegieJ@msn.com
   Twitter: @CarnegieJ
   Created: 2016-Jul-12
   Copyright (c) 2016 Carnegie Johnson

   Thank you to Microsoft Director of Sales Excellence - Eric Ligman
   for the inspiration to create this script. God bless you and our Microsoft family.
.LINK
   https://IAYFConsulting.com/Carnegie
.EXAMPLE
   PS C:\>Get-MSFTBook -MsftBook 'http://ligman.me/1omCrM6'

   Description
   -----------
   This command will retrieve the Microsoft eBook "PowerShell_Examples_v4.pdf" to the temporary folder,
   the cmdlet returns the custom object.
.EXAMPLE
   PS C:\>Get-MSFTBook -MsftBook 'http://ligman.me/1omCrM6' -DestinationFolder 'C:\eBooks'

   Description
   -----------
   This command will retrieve the Microsoft eBook "PowerShell_Examples_v4.pdf" to the "C:\eBooks" folder
   and create the folder if it does not exist, the cmdlet returns the custom object.
.EXAMPLE
   PS C:\>Get-MSFTBook -MsftBook 'http://ligman.me/1omCrM6' -NoDownload

   Description
   -----------
   This command uses the NoDownload switch and will NOT retrieve the Microsoft eBook "PowerShell_Examples_v4.pdf",
   the cmdlet returns the custom object.
#>
Function Get-MSFTBook {
  [CmdletBinding(DefaultParameterSetName='Pset1'
                , PositionalBinding=$true)]
  Param (
    # Web resource(s) to download
    [Parameter(Mandatory=$true
            , Position=0
            , HelpMessage="Please specify URL."
            , ParameterSetName='Pset1')]
    [ValidateNotNullOrEmpty()]
    [string[]]$MsftBook,
    # Folder path to store download
    [Parameter(Mandatory=$false,
              Position=1,
              ParameterSetName='Pset1')]
    [string]$DestinationFolder = $env:TEMP,
    [Parameter(Mandatory=$false,
              Position=2,
              ParameterSetName='Pset1')]
    [switch]$NoDownload)
  Begin {
    $www = New-Object System.Net.Webclient
    $output = [PSCustomObject]@{
      Item = [string]$MsftBook;
      File = $null;
      Source = $null;
      Destination = $null}

    $resource = ''
    $nl = [System.Environment]::NewLine
  }

  Process {
    Trap [System.Net.WebException] {
      $errX = $_.Exception
      $errmsg = $nl + $errX.ToString() + $nl
      $errmsg += ("  Argument= {0}" -f $MsftBook) + $nl
      $status = [System.Net.WebExceptionStatus]$errX.Status

      switch ($true) {
        $($status -match 'ProtocolError') {
          $errResponse = [System.Net.WebResponse]$errX.Response
          $errHttpResponse = [System.Net.HttpWebResponse]$errX.Response
          $errmsg += "ProtocolError Status Code = {0}{1}" -f $errResponse.StatusCode.Value__, $nl
          $errmsg += "Description: {0} <{1}>" -f $errResponse.StatusDescription, $errHttpResponse.ResponseUri
          $errmsg += "Message: {0}" -f $weberr.Message; break}
        default {
          $errmsg += ("  Status = {0}" -f $status.ToString())
        }
      }
      $errmsg
      Break
    } # End Trap
    If ($MsftBook -match '(http[s]?|[s]?ftp[s]?)(:\/\/)([^\s,]+)') {
      Try {
        If (-not (Test-Path -Path $DestinationFolder)) {
          New-Item -ItemType Directory -Path $DestinationFolder -Force
        }
        $requestURI = New-Object System.Uri($MsftBook)
        $request = [System.Net.WebRequest]::CreateHttp($requestURI)
        $response = $request.GetResponse()
        If ($response -eq $null) {
          return
        }
        $responseURI = $response.ResponseUri
        $resource = (($responseURI -split "/")[-1]).Split("?", 2)[0]
        $response.Dispose()
        $dest = Join-Path -Path $DestinationFolder -ChildPath $resource
        If(-not $NoDownload) {
          $www.DownloadFile($responseURI, $dest)
        }
        $output.File = [string]$resource
        $output.Source = [string]$responseURI
        $output.Destination = [string]$dest
      } # End Try
      Catch {
        $errX = $_.Exception
        $errmsg = $errX.ToString() + $nl + ("  Argument= {0}" -f $MsftBook)
        $errmsg
      }
    } # Endif URL
  }

  End {
    $www.Dispose()
    $output
  }
}

# Source of "Download All" list for Microsoft FREE eBooks
$MsftBooks = "http://www.mssmallbiz.com/ericligman/Key_Shorts/MSFTFreeEbooks.txt"
# Get contents of the book list and split each line into an object collection
$URLs = (Invoke-WebRequest -URI $MsftBooks).Content.Split("`n").Trim()
# Filter object colletion for URL's in HTTP:// or FTP:// protocol formats
$URLs = $URLs | ?{$_ -match '(http[s]?|[s]?ftp[s]?)(:\/\/)([^\s,]+)'}
# Filter duplicate URL's
$URLs = $URLs | Sort-Object | Get-Unique
# Retrieve each eBook into "Downloads" folder and output to grid
$URLs | %{Get-MSFTBook -MsftBook $_ -DestinationFolder "C:\Downloads\Microsoft\eBooks"} | Out-GridView


text:
/*!
* This is used to style the siteviewer
*/
/* #### Use a minimum height for sections so that they can be hovered over when there are no modules in them #### */
/* line 6, ../../Sass/_inner-site-viewer.scss */
.cofoundry-sv__section, .cofoundry-sv__module-empty {
  min-height: 30px;
}

/* for Internet Explorer */
/*\*/
/* line 11, ../../Sass/_inner-site-viewer.scss */
* html .cofoundry__sv-section {
  height: 30px;
  opacity: 1;
}

/* line 16, ../../Sass/_inner-site-viewer.scss */
.cofoundry-editmode__custom-entity .cofoundry__sv-section[data-cms-page-section] {
  cursor: not-allowed;
  opacity: .5;
}

/* line 21, ../../Sass/_inner-site-viewer.scss */
.cofoundry-editmode__page .cofoundry__sv-section[data-cms-custom-entity-section] {
  cursor: not-allowed;
  opacity: .5;
}

/* Editable Section/Module Hover */
/* line 27, ../../Sass/_inner-site-viewer.scss */
.cofoundry-sv__hover-module {
  box-shadow: 0px 0px 2px #4af386 !important;
}

/* line 34, ../../Sass/_inner-site-viewer.scss */
.cofoundry-sv__hover-section {
  box-shadow: 0px 0px 1px #003399 !important;
}

/* Used when the html for a section is being replaced */
/* line 40, ../../Sass/_inner-site-viewer.scss */
.cofoundry-sv__section-loading {
  opacity: 0.5;
}

/*# sourceMappingURL=inner-site-viewer.css.map */


text:
package org.zeropage.apps.zeropage.main;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import org.zeropage.apps.zeropage.R;

public class PushListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push_list);
    }
}


text:
module Azure::Automation::Mgmt::V2015_10_31
  module Models
    #
    # Defines values for DscConfigurationProvisioningState
    #
    module DscConfigurationProvisioningState
      Succeeded = "Succeeded"
    end
  end
end


text:
using Bridge.Test.NUnit;

namespace Bridge.ClientTest.Batch3.BridgeIssues
{
    [Category(Constants.MODULE_ISSUES)]
    [TestFixture(TestNameFormat = "#1184 - {0}")]
    public class Bridge1184
    {
        [Test]
        public static void TestGetTypeForNumberTypes()
        {
            byte b = 1;
            Assert.AreEqual(typeof(byte), b.GetType());

            sbyte sb = 1;
            Assert.AreEqual(typeof(sbyte), sb.GetType());

            short s = 1;
            Assert.AreEqual(typeof(short), s.GetType());

            ushort us = 1;
            Assert.AreEqual(typeof(ushort), us.GetType());

            int i = 1;
            Assert.AreEqual(typeof(int), i.GetType());

            uint ui = 1;
            Assert.AreEqual(typeof(uint), ui.GetType());

            double d = 1.1;
            Assert.AreEqual(typeof(double), d.GetType());

            float f = 1.1f;
            Assert.AreEqual(typeof(float), f.GetType());

            object o = b;
            Assert.AreEqual(typeof(byte), o.GetType());

            o = f;
            Assert.AreEqual(typeof(float), o.GetType());
        }
    }
}


text:
package net.kyori.adventure.text;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.kyori.adventure.text.format.Style;
import net.kyori.examination.ExaminableProperty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import static java.util.Objects.requireNonNull;

final class TranslatableComponentImpl extends AbstractComponent implements TranslatableComponent {
  private final String key;
  private final List<Component> args;

  TranslatableComponentImpl(final @NotNull List<Component> children, final @NotNull Style style, final @NotNull String key, final @NotNull ComponentLike@NotNull[] args) {
    this(children, style, key, Arrays.asList(args));
  }

  TranslatableComponentImpl(final @NotNull List<? extends ComponentLike> children, final @NotNull Style style, final @NotNull String key, final @NotNull List<? extends ComponentLike> args) {
    super(children, style);
    this.key = requireNonNull(key, "key");
    // Since translation arguments can be indexed, empty components are also included.
    this.args = ComponentLike.asComponents(args);
  }

  @Override
  public @NotNull String key() {
    return this.key;
  }

  @Override
  public @NotNull TranslatableComponent key(final @NotNull String key) {
    if (Objects.equals(this.key, key)) return this;
    return new TranslatableComponentImpl(this.children, this.style, requireNonNull(key, "key"), this.args);
  }

  @Override
  public @NotNull List<Component> args() {
    return this.args;
  }

  @Override
  public @NotNull TranslatableComponent args(final @NotNull ComponentLike@NotNull... args) {
    return new TranslatableComponentImpl(this.children, this.style, this.key, args);
  }

  @Override
  public @NotNull TranslatableComponent args(final @NotNull List<? extends ComponentLike> args) {
    return new TranslatableComponentImpl(this.children, this.style, this.key, args);
  }

  @Override
  public @NotNull TranslatableComponent children(final @NotNull List<? extends ComponentLike> children) {
    return new TranslatableComponentImpl(children, this.style, this.key, this.args);
  }

  @Override
  public @NotNull TranslatableComponent style(final @NotNull Style style) {
    return new TranslatableComponentImpl(this.children, style, this.key, this.args);
  }

  @Override
  public boolean equals(final @Nullable Object other) {
    if (this == other) return true;
    if (!(other instanceof TranslatableComponent)) return false;
    if (!super.equals(other)) return false;
    final TranslatableComponent that = (TranslatableComponent) other;
    return Objects.equals(this.key, that.key()) && Objects.equals(this.args, that.args());
  }

  @Override
  public int hashCode() {
    int result = super.hashCode();
    result = (31 * result) + this.key.hashCode();
    result = (31 * result) + this.args.hashCode();
    return result;
  }

  @Override
  protected @NotNull Stream<? extends ExaminableProperty> examinablePropertiesWithoutChildren() {
    return Stream.concat(
      Stream.of(
        ExaminableProperty.of("key", this.key),
        ExaminableProperty.of("args", this.args)
      ),
      super.examinablePropertiesWithoutChildren()
    );
  }

  @Override
  public @NotNull Builder toBuilder() {
    return new BuilderImpl(this);
  }

  static final class BuilderImpl extends AbstractComponentBuilder<TranslatableComponent, Builder> implements TranslatableComponent.Builder {
    private @Nullable String key;
    private List<? extends Component> args = Collections.emptyList();

    BuilderImpl() {
    }

    BuilderImpl(final @NotNull TranslatableComponent component) {
      super(component);
      this.key = component.key();
      this.args = component.args();
    }

    @Override
    public @NotNull Builder key(final @NotNull String key) {
      this.key = key;
      return this;
    }

    @Override
    public @NotNull Builder args(final @NotNull ComponentBuilder<?, ?> arg) {
      return this.args(Collections.singletonList(arg.build()));
    }

    @Override
    @SuppressWarnings("checkstyle:GenericWhitespace")
    public @NotNull Builder args(final @NotNull ComponentBuilder<?, ?>@NotNull... args) {
      if (args.length == 0) return this.args(Collections.emptyList());
      return this.args(Stream.of(args).map(ComponentBuilder::build).collect(Collectors.toList()));
    }

    @Override
    public @NotNull Builder args(final @NotNull Component arg) {
      return this.args(Collections.singletonList(arg));
    }

    @Override
    public @NotNull Builder args(final @NotNull ComponentLike@NotNull... args) {
      if (args.length == 0) return this.args(Collections.emptyList());
      return this.args(Arrays.asList(args));
    }

    @Override
    public @NotNull Builder args(final @NotNull List<? extends ComponentLike> args) {
      this.args = ComponentLike.asComponents(args);
      return this;
    }

    @Override
    public @NotNull TranslatableComponentImpl build() {
      if (this.key == null) throw new IllegalStateException("key must be set");
      return new TranslatableComponentImpl(this.children, this.buildStyle(), this.key, this.args);
    }
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<artifactId>tabula-core</artifactId>
	<packaging>jar</packaging>

	<dependencies>

		<dependency>
			<groupId>de.tu-dresden.inf.lat.util</groupId>
			<artifactId>util-map</artifactId>
		</dependency>

		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
		</dependency>

	</dependencies>

	<parent>
		<groupId>de.tu-dresden.inf.lat.tabula</groupId>
		<artifactId>tabula-parent</artifactId>
		<version>0.3.0-SNAPSHOT</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<mainClass>de.tudresden.inf.lat.tabula.main.Main</mainClass>

		<exec.args>simple src/test/resources/example.properties target/example.properties</exec.args>
	</properties>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
			</plugin>

		</plugins>
	</build>

	<name>Tabula Core</name>

</project>


text:
using UnityEngine;
using System.Collections;

public class SneezeBehaviour : MonoBehaviour {

	public void PlaySneezeSound()
	{
		this.GetComponent<AudioSource> ().Play ();
	}
}


text:
#include "config.h"
#include "platform/graphics/filters/FETile.h"

#include "SkTileImageFilter.h"

#include "platform/graphics/filters/Filter.h"
#include "platform/graphics/filters/SkiaImageFilterBuilder.h"
#include "platform/text/TextStream.h"

namespace blink {

FETile::FETile(Filter* filter)
    : FilterEffect(filter)
{
}

PassRefPtr<FETile> FETile::create(Filter* filter)
{
    return adoptRef(new FETile(filter));
}

FloatRect FETile::mapPaintRect(const FloatRect& rect, bool forward)
{
    return forward ? maxEffectRect() : inputEffect(0)->maxEffectRect();
}

static FloatRect getRect(FilterEffect* effect)
{
    FloatRect result = effect->filter()->filterRegion();
    FloatRect boundaries = effect->effectBoundaries();
    if (effect->hasX())
        result.setX(boundaries.x());
    if (effect->hasY())
        result.setY(boundaries.y());
    if (effect->hasWidth())
        result.setWidth(boundaries.width());
    if (effect->hasHeight())
        result.setHeight(boundaries.height());
    return result;
}

PassRefPtr<SkImageFilter> FETile::createImageFilter(SkiaImageFilterBuilder* builder)
{
    RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
    FloatRect srcRect = inputEffect(0) ? getRect(inputEffect(0)) : filter()->filterRegion();
    FloatRect dstRect = getRect(this);
    return adoptRef(SkTileImageFilter::Create(srcRect, dstRect, input.get()));
}

TextStream& FETile::externalRepresentation(TextStream& ts, int indent) const
{
    writeIndent(ts, indent);
    ts << "[feTile";
    FilterEffect::externalRepresentation(ts);
    ts << "]\n";
    inputEffect(0)->externalRepresentation(ts, indent + 1);

    return ts;
}

} // namespace blink


text:
@interface SelectActivityViewController : UITableViewController

+ (NSDictionary *)sampleDataForActivity:(NSString *)activity;
+ (NSArray *)activityTypes;
- (NSString *)selectedActivity;

@end


text:
package org.bigtesting.fixd.tests;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 *
 * @author Luis Antunes
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
    TestCapturedRequest.class,
    TestResponseBodyInterpolator.class,
    TestPathParamSessionHandler.class,
    TestRequestParamSessionHandler.class,
    TestSimpleHttpRequest.class,
    TestServerFixture.class
})
public class FixdTestSuite {
    /*
     *  the class remains completely empty,
     *  being used only as a placeholder for
     *  the above annotations
     */
}


text:
#ifndef GDCMIMAGEEXTENTREADER_H
#define GDCMIMAGEEXTENTREADER_H

#include "gdcmImageReader.h"
#include "gdcmImage.h"
#include "gdcmRegion.h"

namespace gdcm
{

class ImageRegionReaderInternals;
/**
 * \brief ImageRegionReader
 * \see ImageReader
 */
class GDCM_EXPORT ImageRegionReader : public ImageReader
{
public:
  ImageRegionReader();
  ~ImageRegionReader();

  /// Set/Get Region to be read
  void SetRegion(Region const & region);
  Region const &GetRegion() const;

  /// Explicit call which will compute the minimal buffer length that can hold the whole
  /// uncompressed image as defined by Region `region`.
  /// \return 0 upon error
  size_t ComputeBufferLength() const;

  /// Read meta information (not Pixel Data) from the DICOM file.
  /// \return false upon error
  bool ReadInformation();

  /// Read into buffer:
  /// \return false upon error
  bool ReadIntoBuffer(char *inreadbuffer, size_t buflen);

protected:
  /// To prevent user from calling super class Read() function
  bool Read();

private:
  bool ReadRAWIntoBuffer(char *buffer, size_t buflen);
  bool ReadRLEIntoBuffer(char *buffer, size_t buflen);
  bool ReadJPEG2000IntoBuffer(char *buffer, size_t buflen);
  bool ReadJPEGIntoBuffer(char *buffer, size_t buflen);
  bool ReadJPEGLSIntoBuffer(char *buffer, size_t buflen);
  ImageRegionReaderInternals *Internals;
};

} // end namespace gdcm

#endif //GDCMIMAGEEXTENTREADER_H


text:
#ifndef COP_STRDICT_H
#define COP_STRDICT_H

#include "cop_strtypes.h"
#include <stddef.h>

/* This structure is defined later in this header. Don't access members
 * directly. Use the accessor functions below. */
struct cop_strdict_node;

/* ---------------------------------------------------------------------------
 * Dictionary initialisation and cleanup
 * ------------------------------------------------------------------------ */

/* Initialise an empty dictionary. You do not strictly need to use this
 * function and may always assign the root-node pointer to null. There are no
 * cleanup functions as this library does not perform any allocations. If you
 * dynamically allocate nodes and wish to free them, you may use the enumerate
 * method to achieve this. */
static COP_ATTR_UNUSED struct cop_strdict_node *cop_strdict_init(void) {
	return NULL;
}

/* ---------------------------------------------------------------------------
 * Node initialisation prior to insertion
 *
 * Use the below functions to prepare a node to be inserted into the
 * dictionary using cop_strdict_insert() or extract the key or data from an
 * a node that has been setup.
 * ------------------------------------------------------------------------ */

/* Setup a new node with a key and data pointer using a cop_strh structure
 * for the key.
 *
 * The function takes a cop_strdict_node structure and fills in the required
 * parameters. The cop_strh structure will be used for the key and must have a
 * persistent data pointer. p_data is the initial data pointer value. No
 * allocations take place. It is undefined for p_node or p_strh to be null. */
void
cop_strdict_node_init
	(struct cop_strdict_node *p_node
	,const struct cop_strh   *p_strh
	,void                    *p_data
	);

/* Setup a new node with a key and data pointer using a null-terminated stirng
 * for the key.
 *
 * The function takes a cop_strdict_node structure and fills in the required
 * parameters. p_persistent_cstr must be a persistent null-terminated string
 * which will be used for the key. p_data is the initial data pointer value.
 * No allocations take place. It is undefined for p_node or p_persistend_cstr
 * to be null. */
void
cop_strdict_node_init_by_cstr
	(struct cop_strdict_node *p_node
	,const char              *p_persistent_cstr
	,void                    *p_data
	);

/* Get the key from an initialised node. The function never fails. It is
 * undefined for p_node to be null. */
void cop_strdict_node_to_key(const struct cop_strdict_node *p_node, struct cop_strh *p_key);

/* Return the data pointer from an initialised node. The function never
 * fails. It is undefined for p_node to be null. */
void *cop_strdict_node_to_data(const struct cop_strdict_node *p_node);

/* ---------------------------------------------------------------------------
 * Dictionary insertion, retrieval, modification and deletion methods
 * ------------------------------------------------------------------------ */

/* Insert a node into the dictionary.
 *
 * The key pointer and it's internal key pointer must point to persistent
 * memory until such time as it is deleted from the dictionary. The function
 * returns zero if the key was inserted successfully. It returns non-zero if
 * a node with the given key already existed in the dictionary - if this
 * occurs, no change is made to the dictionary. */
int
cop_strdict_insert
	(struct cop_strdict_node **pp_root
	,struct cop_strdict_node  *p_key
	);

/* Find an existing value in the dictionary by cop_strh structure.
 *
 * Search for a key using the data in the given cop_strh structure. If
 * pp_value is not NULL and the key exists, the pointer will be set to
 * the data pointer of the item with the given key. The function returns
 * zero if the key exists. It returns non-zero if the key does not exist. */
int /* zero on success, non-zero when key does not exist */
cop_strdict_get
	(const struct cop_strdict_node  *p_root
	,const struct cop_strh          *p_key
	,void                         **pp_value
	);

/* Find an existing value in the dictionary by null-terminated string.
 *
 * Search for a key using the data in the given null-terminated string (
 * which will be converted to a cop_strh structure using the
 * cop_strh_init_shallow() function). If pp_value is not NULL and the key
 * exists, the pointer will be set to the data pointer of the item with the
 * given key. The function returns zero if the key exists. It returns non-
 * zero if the key does not exist. */
int  /* zero on success, non-zero when key does not exist */
cop_strdict_get_by_cstr
	(const struct cop_strdict_node  *p_root
	,const char                     *p_key
	,void                          **pp_value
	);

int /* zero on success, non-zero when key does not exist */
cop_strdict_update
	(struct cop_strdict_node *p_root
	,const struct cop_strh   *p_key
	,void                    *p_value
	);
int /* zero on success, non-zero when key does not exist */
cop_strdict_update_by_cstr
	(struct cop_strdict_node *p_root
	,const char              *p_key
	,void                    *p_value
	);

/* Remove an item using a key defined by a cop_strh structure.
 *
 * If the return value is NULL, the key was not found in the dictionary.
 * Otherwise, it will be the same pointer that was passed to the
 * cop_strdict_insert() function to insert the node. */
struct cop_strdict_node *
cop_strdict_delete
	(struct cop_strdict_node **pp_root
	,const struct cop_strh    *p_key
	);

/* Remove an item using a key defined by a null-terminated string.
 *
 * Finds a node and returns it. The key will be converted to a cop_strh using
 * the cop_strh_init_shallow() function to search. If the return value is
 * NULL, the key was not found in the dictionary. Otherwise, it will be the
 * same pointer that was passed to the cop_strdict_insert() function to insert
 * the node. */
struct cop_strdict_node *
cop_strdict_delete_by_cstr
	(struct cop_strdict_node **pp_root
	,const char               *p_key
	);

/* ---------------------------------------------------------------------------
 * Enumeration of dictionary keys and values.
 * ------------------------------------------------------------------------ */

/* Return non-zero in the enumeration function to signal an early termination
 * of the enumeration. p_context will have the value passed as p_context to
 * the call to cop_strdict_enumerate. p_node is the current node and may be
 * examined using the cop_strdict_node_to_* functions - it is never null.
 * depth is the height of the node in the tree and is purely informational. */
typedef int (cop_strdict_enumerate_fn)(void *p_context, struct cop_strdict_node *p_node, int depth);

/* Enumerate the keys in the dictionary. The return value is zero if all calls
 * to the callback return zero. If a callback function ever returns non-zero,
 * the enumeration terminates and the return value of the terminating callback
 * is returned.
 *
 * The ordering of the enumeration is strictly leaves-first. This permits
 * using the enumerate function to clean up memory for dynamically allocated
 * node objects (i.e. you may call free(p_node) in the callback function as
 * all the child nodes will have already been enumerated). The value of
 * p_context is passed to the callback function. p_root is the root node which
 * may be NULL (which will result in no calls to the callback). */
int
cop_strdict_enumerate
	(struct cop_strdict_node  *p_root
	,cop_strdict_enumerate_fn *p_fn
	,void                     *p_context
	);

/* ---------------------------------------------------------------------------
 * Internal bits
 *
 * These are defined so that you can know their memory requirements and
 * allocate them potentially on the stack. You should not depend on their
 * members being stable and should interact with them using only the above
 * APIs.
 * ------------------------------------------------------------------------ */

/* These macros define the number of children per node. 4 has been found to
 * give excellent performance for arbitrary sized dictionaries. */
#define COP_STRDICT_CHID_BITS (2)
#define COP_STRDICT_CHID_NB   (1u<<COP_STRDICT_CHID_BITS)
#define COP_STRDICT_CHID_MASK (COP_STRDICT_CHID_NB-1u)

/* Internal node structure */
struct cop_strdict_node {
	/* Lower 32 bits is the hash. Upper 32 bits is the key data length. */
	uint_fast64_t            key;

	/* Pointer to the key data that was in the cop_strh object used to build
	 * the node. */
	const unsigned char     *key_data;

	/* Current value of the node data pointer. */
	void                    *data;

	/* Pointers to child nodes. Initialised to NULL. */
	struct cop_strdict_node *kids[COP_STRDICT_CHID_NB];

};

#endif /* COP_STRDICT_H */


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.media.videoanalyzer.edge.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Options for changing video publishing behavior on the video sink and output video. */
@Fluent
public final class VideoPublishingOptions {
    /*
     * When set to 'true' the video will publish preview images. Default is
     * 'false'.
     */
    @JsonProperty(value = "enableVideoPreviewImage")
    private String enableVideoPreviewImage;

    /**
     * Get the enableVideoPreviewImage property: When set to 'true' the video will publish preview images. Default is
     * 'false'.
     *
     * @return the enableVideoPreviewImage value.
     */
    public String getEnableVideoPreviewImage() {
        return this.enableVideoPreviewImage;
    }

    /**
     * Set the enableVideoPreviewImage property: When set to 'true' the video will publish preview images. Default is
     * 'false'.
     *
     * @param enableVideoPreviewImage the enableVideoPreviewImage value to set.
     * @return the VideoPublishingOptions object itself.
     */
    public VideoPublishingOptions setEnableVideoPreviewImage(String enableVideoPreviewImage) {
        this.enableVideoPreviewImage = enableVideoPreviewImage;
        return this;
    }
}


text:
package aqa.value;

import aqa.InterpreterException;

/**
 * A representation of strings
 *
 * @author martinhart
 */
public class StringValue extends ValueBase {

    final public String value;

    public StringValue(String value) {
        super("string");
        this.value = value;
    }

    @Override
    public String inspect() {
        return "'" + value + "'";
    }

    @Override
    public String output() {
        return value;
    }

    @Override
    public String toString() {
        return inspect();
    }

    @Override
    public boolean equal(Value other) throws InterpreterException {
        if (other instanceof StringValue) {
            StringValue o = (StringValue) other;
            return value.equals(o.value);
        }
        return super.equal(other);
    }

    @Override
    public Value add(Value other) throws InterpreterException {
        if (other instanceof StringValue) {
            StringValue o = (StringValue) other;
            return new StringValue(this.value + o.value);
        }
        return super.add(other);
    }

    @Override
    public IntegerValue length() throws InterpreterException {
        return new IntegerValue(value.length());
    }

    @Override
    public Object getValue() {
        return value;
    }
}


text:
require 'spec_helper'

describe CivicAide::Client do

  before do
    @client = CivicAide::Client.new("AIzaSyDWJSisG_4Azd6nVJTU5gdKPiKKTCovupY")
  end

  describe '.new' do
    it 'raises an error with no API key' do
      CivicAide.api_key = nil
      expect{ CivicAide::Client.new }.to raise_error(APIKeyNotSet)
    end

    it "doesn't raise an error with class API key set" do
      CivicAide.api_key = "AIzaSyDWJSisG_4Azd6nVJTU5gdKPiKKTCovupY"
      expect{ CivicAide::Client.new }.to_not raise_error
    end

    it "defaults to false for official only" do
      expect(@client.official_only).to eq(false)
    end
  end

  describe "#new" do
    it "takes one parameter and returns a Client object" do
      @client.should be_an_instance_of CivicAide::Client
    end
  end

  describe 'configuration' do
    it 'should have correct API endpoint' do
      expect(CivicAide::Client::API_ENDPOINT).to eq('https://www.googleapis.com/civicinfo/')
    end

    it 'should have the correct API version' do
      expect(CivicAide::Client::API_VERSION).to eq('us_v1')
    end

    it 'should include HTTParty' do
      @client.extend(HTTParty)
    end

    it 'should have the correct base_uri' do
      expect(CivicAide::Client.base_uri).to eq('https://www.googleapis.com/civicinfo/us_v1')
    end
  end

  describe '#default_query' do
    it 'should have the api key' do
      expect(@client.send(:default_query)).to eq({:key => @client.api_key, :prettyPrint => false})
    end
  end

  describe "#elections" do
    it "should be the right class" do
      expect(@client.elections).to be_an_instance_of CivicAide::Elections
    end
  end

  describe "#representatives" do
    it "should be the right class" do
      expect(@client.representatives).to be_an_instance_of CivicAide::Representatives
    end
  end

  describe "#classify_error" do
    it "should raise an error with NoAddressParameter" do
      expect{ @client.send(:check_response_status, "noAddressParameter") }.to raise_error("NoAddressParameter")
    end

    it "should raise an error with ElectionIdMissing" do
      expect{ @client.send(:check_response_status, "electionIdMissing") }.to raise_error("ElectionIdMissing")
    end

    it "should raise an error with NoStreetSegmentFound" do
      expect{ @client.send(:check_response_status, "noStreetSegmentFound") }.to raise_error("NoStreetSegmentFound")
    end

    it "should raise an error with AddressUnparseable" do
      expect{ @client.send(:check_response_status, "addressUnparseable") }.to raise_error("AddressUnparseable")
    end

    it "should raise an error with NoAddressParameter" do
      expect{ @client.send(:check_response_status, "noAddressParameter") }.to raise_error("NoAddressParameter")
    end

    it "should raise an error with MultipleStreetSegmentsFound" do
      expect{ @client.send(:check_response_status, "multipleStreetSegmentsFound") }.to raise_error("MultipleStreetSegmentsFound")
    end

    it "should raise an error with ElectionOver" do
      expect{ @client.send(:check_response_status, "electionOver") }.to raise_error("ElectionOver")
    end

    it "should raise an error with ElectionUnknown" do
      expect{ @client.send(:check_response_status, "electionUnknown") }.to raise_error("ElectionUnknown")
    end

    it "should raise an error with InternalLookupFailure" do
      expect{ @client.send(:check_response_status, "internalLookupFailure") }.to raise_error("InternalLookupFailure")
    end

    it "should not raise an error" do
      expect{ @client.send(:check_response_status, "success") }.to_not raise_error
    end
  end

  describe "official only" do
    it "should allowing toggling official_only" do
      expect(@client.official_only).to eq(false)
    end

    it "should allowing toggling official_only" do
      @client.official_only = true
      expect(@client.official_only).to eq(true)
    end

    it "should have client instead of class for official_only" do
      CivicAide.official_only = true
      @client.official_only = false
      expect(@client.official_only).to eq(false)
    end
  end

end


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package openblocks.codeblockutil;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

public class CBorderlessButton extends CButton{
	private static final long serialVersionUID = 328149080229L;
	public CBorderlessButton(String text){
		super(Color.black, CGraphite.darkgreen, text);
	}

	/**
	 * re paints this
	 */
	public void paint(Graphics g){
		// Set up graphics and buffer
		//super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		// Set up first layer
		int buttonHeight = this.getHeight() - (INSET * 2);
		int buttonWidth = this.getWidth() - (INSET * 2);
		if(this.focus){
			int arc = buttonHeight/3;
			Color topColoring;
			Color bottomColoring;
			if(this.pressed || this.selected){
				topColoring =  this.selectedColor.darker();
				bottomColoring = CGraphite.darkgreen;
			}else{
				topColoring =  this.buttonColor;
				bottomColoring = this.buttonColor;
			}
			// Paint the first layer
			g2.setPaint(new GradientPaint(0, 0, topColoring, 0, buttonHeight, bottomColoring, false));
			g2.fillRoundRect(INSET, INSET, buttonWidth, buttonHeight, arc, arc);
			g2.setColor(Color.darkGray);
			g2.drawRoundRect(INSET, INSET, buttonWidth, buttonHeight, arc, arc);

			// set up paint data fields for second layer
			int highlightHeight = buttonHeight/2-HIGHLIGHT_INSET;
			int highlightWidth = buttonWidth - (HIGHLIGHT_INSET * 2)+1;
			if(this.pressed || this.selected){
				topColoring = Color.white;
				bottomColoring = this.selectedColor;
			}else{
				topColoring = Color.white;
				bottomColoring = Color.darkGray;
			}
			// Paint the second layer
			g2.setPaint(new GradientPaint(0,0,topColoring,0,buttonHeight, bottomColoring, false));
			g2.fillRoundRect(INSET+HIGHLIGHT_INSET,INSET+HIGHLIGHT_INSET+1,highlightWidth,highlightHeight,arc,arc);

		}
		// Draw the text (if any)
		if (this.getText() != null){
			g2.setColor(Color.white);
			Font font = g2.getFont().deriveFont((float)(((float)buttonHeight) * .5));
			g2.setFont(font);
			FontMetrics metrics = g2.getFontMetrics();
			Rectangle2D textBounds = metrics.getStringBounds(this.getText(),g2);
			float x = (float)((this.getWidth() / 2) - (textBounds.getWidth() / 2));
			float y = (float)((this.getHeight() / 2) + (textBounds.getHeight() / 2)) - metrics.getDescent();
			g2.drawString(this.getText(),x,y);
		}
	}

	public static void main(String[] args) {
		JFrame f = new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setLayout(new FlowLayout());
		f.setSize(500, 300);
		CButton c = new CBorderlessButton("hi");
		c.setPreferredSize(new Dimension(400,200));

		f.add(c);
		f.setVisible(true);
		f.repaint();

	}
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CJia.Navigate.App.UI
{
    public partial class ParkingQueryView : CJia.Parking.Tools.View, CJia.Parking.Views.Navigate.IParkingQueryView
    {
        int textBoxIndex = 1;

        DevExpress.XtraTab.XtraTabControl xtra;

        DataTable dtPic;

        CJia.Parking.Views.Navigate.ParkingQueryArgs parkQueryArgs = new Parking.Views.Navigate.ParkingQueryArgs();

        public ParkingQueryView()
        {
            InitializeComponent();
        }

        protected override object CreatePresenter()
        {
            return new CJia.Parking.Presenters.Navigate.ParkingQueryPresenter(this);
        }

        private void Button_Click(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.SimpleButton btn = sender as DevExpress.XtraEditors.SimpleButton;
            switch (textBoxIndex)
            {
                case 1:
                    textBox1.Text = btn.Text;
                    textBoxIndex++;
                    break;
                case 2:
                    textBox2.Text = btn.Text;
                    textBoxIndex++;
                    break;
                case 3:
                    textBox3.Text = btn.Text;
                    textBoxIndex++;
                    break;
                case 4:
                    textBox4.Text = btn.Text;
                    //textBoxIndex++;
                    break;
                default:
                    break;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (textBoxIndex == 4&&textBox4.Text!="")
            {
                textBox4.Text = "";
            }
            else if (textBoxIndex == 4 && textBox4.Text == "")
            {
                textBox3.Text = "";
                textBoxIndex = 3;
            }
            else if(textBoxIndex==3&&textBox3.Text!="")
            {
                textBox3.Text = "";
            }
            else if (textBoxIndex == 3 && textBox3.Text == "")
            {
                textBox2.Text = "";
                textBoxIndex = 2;
            }
            else if (textBoxIndex == 2 && textBox2.Text != "")
            {
                textBox2.Text = "";
            }
            else if (textBoxIndex == 2 && textBox2.Text == "")
            {
                textBox1.Text = "";
                textBoxIndex = 1;
            }
            else if (textBoxIndex == 1 && textBox1.Text != "")
            {
                textBox1.Text = "";
                textBoxIndex = 1;
            }
            else
            {
                textBoxIndex = 1;
            }
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("查询信息不能为空!");
                return;
            }
            parkQueryArgs.park1 = textBox1.Text;
            parkQueryArgs.park2 = textBox2.Text;
            parkQueryArgs.park3 = textBox3.Text;
            parkQueryArgs.park4 = textBox4.Text;
            OnParkQuery(null, parkQueryArgs);

            xtra = this.Parent.Parent.Parent.Parent.Parent as DevExpress.XtraTab.XtraTabControl;
            if (!this.isExistPage("照片查看"))
            {
                string Queryfactor = "%" + parkQueryArgs.park1 + "%" + parkQueryArgs.park2 + "%" + parkQueryArgs.park3 + "%" + parkQueryArgs.park4 + "%";
                CarPhotosView carphotos = new CarPhotosView(dtPic, 4, Queryfactor, null);
                this.ShowPage("照片查看", carphotos);
            }
            else
            {
                for (int i = 0; i < xtra.TabPages.Count; i++)
                {
                    if (xtra.TabPages[i].Name == "照片查看")
                    {
                        xtra.TabPages.Remove(xtra.TabPages[i]);
                        string Queryfactor = "%" + parkQueryArgs.park1 + "%" + parkQueryArgs.park2 + "%" + parkQueryArgs.park3 + "%" + parkQueryArgs.park4 + "%";
                        CarPhotosView carphotos = new CarPhotosView(dtPic, 4, Queryfactor, null);
                        this.ShowPage("照片查看", carphotos);
                        break;
                    }
                }
            }
        }
        #region【页面代码】
        /// <summary>
        /// 判断将要添加的page是否存在
        /// </summary>
        /// <param name="PageTitle">tabpage名</param>
        /// <returns>bool</returns>
        private bool isExistPage(string PageTitle)
        {
            for (int i = 0; i < xtra.TabPages.Count; i++)
            {
                if (xtra.TabPages[i].Name == PageTitle)
                {
                    xtra.SelectedTabPage = xtra.TabPages[i];
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 将用户控件添加到tab中
        /// </summary>
        /// <param name="pageTitle">tabpage名</param>
        /// <param name="userControl">用户控件</param>
        public void ShowPage(string pageTitle, UserControl userControl)
        {
            DevExpress.XtraTab.XtraTabPage page1 = new DevExpress.XtraTab.XtraTabPage();
            page1.Controls.Add(userControl);
            page1.Text = pageTitle;
            page1.Name = pageTitle;
            page1.AutoScroll = true;
            xtra.TabPages.Add(page1);
            userControl.Dock = DockStyle.Fill;
            xtra.SelectedTabPage = page1;
        }
        #endregion

        #region【接口实现】
        public event EventHandler<Parking.Views.Navigate.ParkingQueryArgs> OnParkQuery;

        public void ExeShowPic(DataTable dt)
        {
            dtPic = dt;
        }
        #endregion

        private void ParkingQueryView_SizeChanged(object sender, EventArgs e)
        {
            int parentWidth = this.Width;
            int parentHeight = this.Height;
            int width = panel1.Width;
            int height = panel1.Height;
            panel1.Location = new Point((parentWidth - width) / 2, (parentHeight - height) / 2);
        }
    }
}


text:
package io.github.keyhan.jbsbe.schema;

import java.time.LocalDateTime;

import org.junit.Test;

import io.github.keyhan.jbsbe.iso.I50Factory;
import io.github.keyhan.jbsbe.iso.I50Message;
import io.github.keyhan.jbsbe.iso.PurchaseRequest;
import io.github.keyhan.jbsbe.iso.SimpleTransformer;

/**
 * Created by keyhan on 2017-03-28.
 */
public class SchemaImporterTest {

    @Test
    public void readFromFile() throws Exception {
        I50Factory<SimpleTransformer> factory = new I50Factory<>(SimpleTransformer.class);
        I50Utility.loadFieldSchema(null);
        PurchaseRequest purchaseRequest = PurchaseRequest.builder().amount(100L).date(LocalDateTime.now())
                .cardNumber("1234567891234567").stan(123).build();
        I50Message message = factory.newMessage(purchaseRequest);
        System.out.println("message = " + message);
    }
}


text:
@interface RectManager : UIView

@property (nonatomic, assign)CGRect subRect;

+ (CGRect)getEffectImageRect:(CGSize)size;
+ (CGRect)getGuideFrame:(CGRect)rect;

+ (int)docode:(unsigned char *)pbBuf len:(int)tLen;
+ (CGRect)getCorpCardRect:(int)width  height:(int)height guideRect:(CGRect)guideRect charCount:(int) charCount;

+ (char *)getNumbers;

@end


text: var app = angular.module("perfilApp", ["ngResource", "ui.bootstrap", "alerta.controller", "usuario.service", "telefono.service", "correo.service", "perfil.controller"]);


text:
"""Implementation of the restarting search strategy """

import copy
from heapq import heappop, heappush, heapify
import logging

from cam.sgnmt import utils
from cam.sgnmt.decoding.core import Decoder, PartialHypothesis
from cam.sgnmt.utils import INF
import numpy as np

class RestartingChild(object):
    """Helper class for ``RestartingDecoder``` representing a child
    object in the search tree. """

    def __init__(self, word, score, score_breakdown):
        """Creates a new child instance """
        self.word = word
        self.score = score
        self.score_breakdown = score_breakdown

class RestartingNode(object):
    """Helper class for ``RestartingDecoder``` representing a node
    in the search tree. """

    def __init__(self, hypo, children):
        """Creates a new node instance """
        self.hypo = hypo
        self.children = children

class RestartingDecoder(Decoder):
    """This decoder first creates a path to the final node greedily.
    Then, it looks for the node on this path with the smallest
    difference between best and second best child, and restarts greedy
    decoding from this point. In order to do so, it maintains a
    priority queue of all visited nodes, which is ordered by the
    difference between the worst expanded child and the best unexpanded
    one. If this queue is empty, we have visited the best path. This
    algorithm is similar to DFS but does not backtrace to the last call
    of the recursive function but to the one which is most promising.

    Note that this algorithm is exact. It tries to exploit the problem
    characteristics of NMT search: Reloading predictor states can be
    expensive, node expansion is even more expensive but for free from
    visited nodes, and there is no good admissible heuristic.

    Note2: Does not work properly if predictor scores can be positive
    because of admissible pruning
    """

    def __init__(self,
                 decoder_args,
                 hypo_recombination,
                 max_expansions = 0,
                 low_memory_mode = True,
                 node_cost_strategy='difference',
                 stochastic=False,
                 always_single_step=False):
        """Creates new Restarting decoder instance.

        Args:
            decoder_args (object): Decoder configuration passed through
                                   from the configuration API.
            hypo_recombination (bool): Activates hypo recombination
            max_expansions (int): Maximum number of node expansions for
                                  inadmissible pruning.
            low_memory_mode (bool): Switch on low memory mode at cost
                                    of some computational overhead as
                                    the set of open nodes is reduced
                                    after each decoding pass
            node_cost_strategy (string): How to decide which node to
                                          restart from next
            stochastic (bool): If true, select the next node to restart
                               from randomly. If false, take the one
                               with the best node score
            always_single_step (bool): If false, do greedy decoding
                                       when restarting. If true, expand
                                       the hypothesis only by a single
                                       token
        """
        super(RestartingDecoder, self).__init__(decoder_args)
        self.max_expansions_param = max_expansions
        self.always_single_step = always_single_step
        self.low_memory_mode = low_memory_mode
        self.hypo_recombination = hypo_recombination
        if node_cost_strategy == 'difference':
            self.get_node_cost = self._get_node_cost_difference
        elif node_cost_strategy == 'absolute':
            self.get_node_cost = self._get_node_cost_absolute
        elif node_cost_strategy == 'constant':
            self.get_node_cost = self._get_node_cost_constant
        elif node_cost_strategy == 'expansions':
            self.get_node_cost = self._get_node_cost_expansions
        else:
            logging.fatal("restarting node score strategy unknown!")
        if stochastic:
            self.select_node = self._select_node_stochastic
        else:
            self.select_node = self._select_node_max

    def _select_node_stochastic(self):
        """Implements stochastic node selection. """
        exps = np.exp([-c for c,_ in self.open_nodes])
        total = sum(exps)
        idx = np.random.choice(range(len(exps)),
                               p=[e/total for e in exps])
        return self.open_nodes.pop(idx)

    def _select_node_max(self):
        """Implements deterministic node selection. """
        return heappop(self.open_nodes)

    def _get_node_cost_difference(self,
                                   prev_node_cost,
                                   first_word_score,
                                   sec_word_score):
        """Implements the node scoring function difference. """
        return first_word_score - sec_word_score

    def _get_node_cost_absolute(self,
                                   prev_node_cost,
                                   first_word_score,
                                   sec_word_score):
        """Implements the node scoring function absolute. """
        return -sec_word_score

    def _get_node_cost_constant(self,
                                   prev_node_cost,
                                   first_word_score,
                                   sec_word_score):
        """Implements the node scoring function constant. """
        return 0.0

    def _get_node_cost_expansions(self,
                                   prev_node_cost,
                                   first_word_score,
                                   sec_word_score):
        """Implements the node scoring function constant. """
        return prev_node_cost + 1.0

    def greedy_decode(self, hypo):
        """Helper function for greedy decoding from a certain point in
        the search tree."""
        best_word = hypo.trgt_sentence[-1]
        prev_hypo = hypo
        remaining_exps = max(self.max_expansions - self.apply_predictors_count,
                             1)
        while (best_word != utils.EOS_ID
               and len(prev_hypo.trgt_sentence) <= self.max_len):
            self.consume(best_word)
            posterior,score_breakdown = self.apply_predictors()
            if len(posterior) < 1:
                return
            best_word = utils.argmax(posterior)
            best_word_score = posterior[best_word]
            new_hypo = prev_hypo.expand(best_word,
                                        None,
                                        best_word_score,
                                        score_breakdown[best_word])
            if new_hypo.score < self.best_score: # Admissible pruning
                return
            logging.debug("Expanded hypo: score=%f prefix= %s" % (
                            new_hypo.score,
                            ' '.join([str(w) for w in new_hypo.trgt_sentence])))
            if len(posterior) > 1:
                if not self.always_single_step:
                    posterior.pop(best_word)
                children = sorted([RestartingChild(w,
                                                   posterior[w],
                                                   score_breakdown[w])
                    for w in posterior], key=lambda c: c.score, reverse=True)
                children = children[:remaining_exps]
                node_cost = self.get_node_cost(0.0,
                                               best_word_score,
                                               children[0].score)
                if node_cost <= self.max_heap_node_cost:
                    prev_hypo.predictor_states = copy.deepcopy(
                                                self.get_predictor_states())
                    heappush(self.open_nodes, (node_cost,
                                               RestartingNode(prev_hypo,
                                                              children)))
            prev_hypo = new_hypo
            if self.always_single_step:
                break
        if best_word == utils.EOS_ID:
            self.add_full_hypo(prev_hypo.generate_full_hypothesis())
            if prev_hypo.score > self.best_score:
                logging.info("New_best (ID: %d): score=%f exp=%d hypo=%s"
                    % (self.current_sen_id + 1,
                       prev_hypo.score,
                       self.apply_predictors_count,
                       ' '.join([str(w) for w in prev_hypo.trgt_sentence])))
                self.best_score = prev_hypo.score

    def create_initial_node(self):
        """Create the root node for the search tree. """
        init_hypo = PartialHypothesis()
        posterior,score_breakdown = self.apply_predictors()
        children = sorted([RestartingChild(w, posterior[w], score_breakdown[w])
                            for w in posterior],
                          key=lambda c: c.score, reverse=True)
        init_hypo.predictor_states = self.get_predictor_states()
        heappush(self.open_nodes, (0.0, RestartingNode(init_hypo, children)))

    def decode(self, src_sentence):
        """Decodes a single source sentence using Restarting search. """
        self.initialize_predictors(src_sentence)
        self.max_expansions = self.get_max_expansions(self.max_expansions_param,
                                                      src_sentence)
        self.open_nodes = []
        self.best_score = self.get_lower_score_bound()
        self.max_heap_node_cost = INF
        # First, create a RestartingNode object for the initial state
        self.create_initial_node()
        # Then, restart from open nodes until the heap is empty
        while self.open_nodes:
            prev_node_score,node = self.select_node()
            best_child = node.children.pop(0)
            new_hypo = node.hypo.expand(best_child.word,
                                        None,
                                        best_child.score,
                                        best_child.score_breakdown)
            if new_hypo.score > self.best_score: # Admissible pruning
                logging.debug("Restart from %s" % (
                            ' '.join([str(w) for w in new_hypo.trgt_sentence])))
                if node.children: # Still has children -> back to heap
                    node_cost = self.get_node_cost(prev_node_score,
                                                   best_child.score,
                                                   node.children[0].score)
                    heappush(self.open_nodes, (node_cost, node))
                    self.set_predictor_states(copy.deepcopy(
                                                node.hypo.predictor_states))
                else: # No need to copy, don't put back to heap
                    self.set_predictor_states(node.hypo.predictor_states)
                self.greedy_decode(new_hypo)
            # Reduce heap size (we don't need more nodes than remaining exps
            rest = self.max_expansions - self.apply_predictors_count
            if rest <= 0:
                break
            if self.hypo_recombination:
                new_open = []
                while len(new_open) < rest and self.open_nodes:
                    c_cost,candidate = heappop(self.open_nodes)
                    valid = True
                    for _,node in new_open:
                        if self.are_equal_predictor_states(
                                                candidate.hypo.predictor_states,
                                                node.hypo.predictor_states):
                            valid = False
                            break
                    if valid:
                        new_open.append((c_cost, candidate))
                        if len(new_open) > rest:
                            break
                self.open_nodes = new_open
                heapify(self.open_nodes)
            elif self.low_memory_mode and len(self.open_nodes) > rest:
                new_open = [heappop(self.open_nodes) for _ in range(rest+1)]
                self.max_heap_node_cost = new_open[-1][0]
                self.open_nodes = new_open
                heapify(self.open_nodes)
        return self.get_full_hypos_sorted()


text:
<?php
/**
 * The Sidebar containing the primary and secondary widget areas in their
 * default place in the DOM structure.
 *
 * @package Manning
 */

/**
 * Check to see if the secondary sidebar is active
 * (that is, has any active widgets) AND we're on the
 * home page.  If both of those conditions are true,
 * set a class on our left sidebar (and also on in our
 * main content area) to change the proportions to what
 * they would be on sub pages (which never have a right
 * sidebar) in the wide view.
 */

if ( ( is_front_page() || is_home() ) && ! is_active_sidebar( 'sidebar-secondary' ) ) {
  $left_sidebar_class = 'sidebar-left no-secondary-sidebar';
} else {
  $left_sidebar_class = 'sidebar-left';
}
?>

<div id="sidebar-left" class="<?php echo $left_sidebar_class; ?>">

		<?php do_action( 'before_sidebar' ); ?>
		<?php if ( ! dynamic_sidebar( 'sidebar-primary' ) ) : ?>

			<?php get_search_form(); ?>

<?php _e( 'Archives', 'manning' ); ?>

				<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>

<?php _e( 'Meta', 'manning' ); ?>

				<?php wp_register(); ?>

<?php wp_loginout(); ?>

				<?php wp_meta(); ?>

		<?php endif; // end sidebar widget area ?>

<?php
/**
 * Only display the secondary sidebar if it contains widgets to display.
 */

if ( ( is_home() || is_front_page() ) && is_active_sidebar( 'sidebar-secondary' ) ):
?>

    <?php do_action( 'before_sidebar' ); ?>

    <?php dynamic_sidebar( 'sidebar-secondary' ); ?>

  <?php endif; // display secondary sidebar? ?>