text:
require "hotel_beds/parser/hotel"
require "hotel_beds/parser/supplier"
require "hotel_beds/parser/reference"
require "hotel_beds/parser/available_room"

module HotelBeds
  module Parser
    class HotelService < Hotel
      # attributes
      attribute :id, attr: "SPUI"
      attribute :type, attr: "xsi:type"
      attribute :status, selector: "Status"
      attribute :date_from, selector: "DateFrom", attr: "date"
      attribute :date_to, selector: "DateTo", attr: "date"
      attribute :currency, selector: "Currency", attr: "code"
      attribute :amount, selector: "TotalAmount"
      attribute :supplier, selector: "Supplier",
        parser: HotelBeds::Parser::Supplier
      attribute :reference, selector: "Reference",
        parser: HotelBeds::Parser::Reference
      attribute :available_rooms, selector: "AvailableRoom", multiple: true,
        parser: HotelBeds::Parser::AvailableRoom

    end
  end
end


text:
package org.testng;

import com.beust.jcommander.JCommander;
import org.testng.remote.RemoteArgs;

import java.util.Arrays;

public class TestNGForkedStarter  {
  public static void main(String[] args) throws Exception {
    final IDEARemoteTestNG testNG = new IDEARemoteTestNG(null);
    CommandLineArgs cla = new CommandLineArgs();
    RemoteArgs ra = new RemoteArgs();
    new JCommander(Arrays.asList(cla, ra), args);
    testNG.configure(cla);
    testNG.run();
    System.exit(0);
  }
}

redpajama_set_name: RedPajamaGithub


text:
from typing import List, Optional

from pydantic import BaseModel

class JigsawMeta(BaseModel):
    id: str
    name: str

    version: Optional[str] = None
    description: Optional[str] = None
    author: Optional[str] = None
    dependencies: List[str] = []
    main_file: str = "__init__.py"
    main_class: str = "Plugin"
    path: str = ""

class Manifest(BaseModel):
    jigsaw: JigsawMeta


text:
<?php

namespace Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * Type that maps an SQL INT to a PHP integer.
 *
 * @author Roman Borschel <roman@code-factory.org>
 * @since 2.0
 */
class IntegerType extends Type
{
    public function getName()
    {
        return Type::INTEGER;
    }

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getIntegerTypeDeclarationSQL($fieldDeclaration);
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return (int) $value;
    }

    public function getBindingType()
    {
        return \PDO::PARAM_INT;
    }
}


text:
package core.engine.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import core.exception.EpikosException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by nitina on 5/17/16.
 */
public final class DynamicRequest implements IDynamicRequest{

    ContainerRequestContext requestContext;
    InputStream requestStream;
    MultivaluedMap<String,String> pathParams;

    public DynamicRequest(ContainerRequestContext requestContext, MultivaluedMap<String,String> pathParams){
        this.requestContext = requestContext;
        this.requestStream = requestContext.getEntityStream();
        this.pathParams = pathParams;
    }

    @Override
    public <T> T getRequest(final Class<T> typeOfRequest) throws EpikosException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            //Note: by this time the inputstream has been decoded by one of filter (PostRequestFilter/PreReqeustFilter)
            return (T) mapper.readValue(requestStream, typeOfRequest.newInstance().getClass());
        }catch (IOException ioExp){
            throw new EpikosException(ioExp.getMessage());

        }catch (InstantiationException instExp){
            throw new EpikosException(instExp.getMessage());

        }catch (IllegalAccessException illExp){
            throw new EpikosException(illExp.getMessage());
        }
    }

    @Override
    public MultivaluedMap<String, String> getPathParams() {
        return pathParams;
    }

    @Override
    public ContainerRequestContext getRequestContext() {
        return requestContext;
    }

}


text:
namespace odb {

class _dbTech;
class _dbBlock;
class _dbTechLayerRule;
class _dbTechVia;
class _dbTechLayer;
class _dbTechViaGenerateRule;
class _dbTechSameNetRule;
class _dbDatabase;
class dbIStream;
class dbOStream;
class dbDiff;

struct _dbTechNonDefaultRuleFlags
{
  uint _hard_spacing : 1;
  uint _block_rule : 1;
  uint _spare_bits : 30;
};

class _dbTechNonDefaultRule : public _dbObject
{
 public:
  // PERSISTANT-MEMBERS
  _dbTechNonDefaultRuleFlags _flags;
  char* _name;
  dbVector<dbId<_dbTechLayerRule>> _layer_rules;
  dbVector<dbId<_dbTechVia>> _vias;
  dbVector<dbId<_dbTechSameNetRule>> _samenet_rules;
  dbMatrix<dbId<_dbTechSameNetRule>> _samenet_matrix;
  dbVector<dbId<_dbTechVia>> _use_vias;
  dbVector<dbId<_dbTechViaGenerateRule>> _use_rules;
  dbVector<dbId<_dbTechLayer>> _cut_layers;
  dbVector<int> _min_cuts;

  _dbTechNonDefaultRule(_dbDatabase*);
  _dbTechNonDefaultRule(_dbDatabase*, const _dbTechNonDefaultRule& r);
  ~_dbTechNonDefaultRule();

  _dbTech* getTech();
  _dbBlock* getBlock();

  bool operator==(const _dbTechNonDefaultRule& rhs) const;
  bool operator!=(const _dbTechNonDefaultRule& rhs) const
  {
    return !operator==(rhs);
  }
  bool operator<(const _dbTechNonDefaultRule& rhs) const;
  void differences(dbDiff& diff,
                   const char* field,
                   const _dbTechNonDefaultRule& rhs) const;
  void out(dbDiff& diff, char side, const char* field) const;
};

dbOStream& operator<<(dbOStream& stream, const _dbTechNonDefaultRule& rule);
dbIStream& operator>>(dbIStream& stream, _dbTechNonDefaultRule& rule);

}  // namespace odb


text:
#pragma once

class RemoteHost;

// do not include any headers here, they must all be in QRDInterface.h
#include "QRDInterface.h"

DOCUMENT("A handle for interacting with a remote servers on a given host.");
class RemoteHost
{
public:
  RemoteHost();

  VARIANT_CAST(RemoteHost);

  DOCUMENT(
      "Ping the host to check current status - if the server is running, connection status, etc.");
  void CheckStatus();
  DOCUMENT("Runs the command specified in :data:`RunCommand`.");
  void Launch();

  DOCUMENT("``True`` if a remote server is currently running on this host.");
  bool ServerRunning : 1;
  DOCUMENT("``True`` if an active connection exists to this remote server.");
  bool Connected : 1;
  DOCUMENT("``True`` if someone else is currently connected to this server.");
  bool Busy : 1;
  DOCUMENT("``True`` if there is a code version mismatch with this server.");
  bool VersionMismatch : 1;

  DOCUMENT("The hostname of this host.");
  QString Hostname;
  DOCUMENT("The friendly name for this host, if available (if empty, the Hostname is used).");
  QString FriendlyName;
  DOCUMENT("The command to run locally to try to launch the server remotely.");
  QString RunCommand;

  DOCUMENT(R"(
Returns the name to display for this host in the UI, either :data:`FriendlyName` or :data:`Hostname`
)");
  const QString &Name() const { return !FriendlyName.isEmpty() ? FriendlyName : Hostname; }
  DOCUMENT("Returns ``True`` if this host represents a connected ADB (Android) device.");
  bool IsHostADB() const { return Hostname.startsWith(lit("adb:")); }
};

DECLARE_REFLECTION_STRUCT(RemoteHost);


text:
module Gemlike
end


text:
@interface JMFirstViewController : UIViewController

@end


text:
{-# LANGUAGE OverloadedStrings #-}

module FTagSpec where

import Test.Hspec
import FTag

spec :: Spec
spec = return ()


text:
<?php
namespace Dkd\PhpCmis\Data;

/**
 * Secondary Object Type.
 */
interface SecondaryTypeInterface extends ObjectTypeInterface
{
}


text:
package org.drools.benchmark.benchmarks;

import org.drools.benchmark.*;
import org.drools.benchmark.util.DroolsUtil;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.builder.KnowledgeBuilder;

public abstract class AbstractBenchmark implements Benchmark {

    protected final String LINE_SEPARATOR = System.getProperty("line.separator");

    public void init(BenchmarkDefinition definition) {
        init(definition, true);
    }

    public void init(BenchmarkDefinition definition, boolean isFirst) { }

    public void terminate() {
        terminate(true);
    }

    public void terminate(boolean isLast) { }

    protected final KnowledgeBuilder createKnowledgeBuilder(String... drlFiles) {
        return DroolsUtil.createKnowledgeBuilder(this, drlFiles);
    }

    protected final KnowledgeBase createKnowledgeBase(KnowledgeBuilder kbuilder) {
        return DroolsUtil.createKnowledgeBase(kbuilder);
    }

    protected final KnowledgeBase createKnowledgeBase(String drl) {
        return DroolsUtil.createKnowledgeBase(drl);
    }

    public Benchmark clone() {
        throw new UnsupportedOperationException("Override clone() to allow to run this benchmark in parallel");
    }

    protected final String repeatPatternString(String pattern, int times) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append(pattern.replaceAll("%i", "" + i));
        }
        return sb.toString();
    }
}


text: Rails.application.config.session_store :cookie_store, key: '_imobeasy_session'


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * String.prototype.substring (start, end) can be applied to non String object instance and
 * returns a string value(not object)
 *
 * @path ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T8.js
 * @description Apply String.prototype.substring to Number instance. Start is Infinity, end is NaN
 */

var __instance = new Number(NaN);

__instance.substring = String.prototype.substring;

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__instance.substring(Infinity, NaN) !== "NaN") {
  $ERROR('#1: __instance = new Number(NaN); __instance.substring = String.prototype.substring;  __instance.substring(Infinity, NaN) === "NaN". Actual: '+__instance.substring(Infinity, NaN) );
}
//
//////////////////////////////////////////////////////////////////////////////


text:
package collins.callbacks

import java.beans.PropertyChangeSupport

import play.api.Logger

import akka.actor.Actor

case class CallbackMessageQueue(pcs: PropertyChangeSupport) extends Actor {
  private[this] val logger = Logger("CallbackMessageQueue")

  override def receive = {
    case CallbackMessage(name, oldValue, newValue) =>
      pcs.firePropertyChange(name, oldValue, newValue)
  }
}


text:
#include "mainwindow.h"
#include "autoware_socket.h"

#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>

struct struct_PID_controller *shm_ptr;

// these parameters can be configured later.
int can_tx_interval = 10; // ms
int cmd_rx_interval = 100; // ms
std::string ros_ip_address = "192.168.1.101";

// vehicle state.
vehicle_state_t vstate;

bool MainWindow::ConfigSocket(void)
{
  std::ifstream ifs("./config");
  std::string str;
  if (ifs.fail()) {
    return false;
  }

  if (getline(ifs,str)) {
    can_tx_interval = atoi(str.c_str());
    cout << "CAN Interval = " << can_tx_interval << " ms" << endl;
  } else {
    return false;
  }

  if (getline(ifs, str)) {
    cmd_rx_interval = atoi(str.c_str());
    cout << "CMD Interval = " << cmd_rx_interval << " ms" << endl;
  } else {
    return false;
  }

  if (getline(ifs,str)) {
    ros_ip_address = str;
    cout << "ROS IP Address = " << ros_ip_address << endl;
  } else {
    return false;
  }

  // key generation
  key_t shm_key = ftok(SHM_SEED_PATH.c_str(), 1);

  // open shared memory
  int shm_id = shmget(shm_key, sizeof(struct_PID_controller), 0444); // read only

  // get address of shared memory
  shm_ptr = (struct struct_PID_controller *)shmat(shm_id, NULL, 0);

  return true;
}

void MainWindow::UpdateState(void)
{
  ZMP_UPDATE_STATE();
  vstate.accel_stroke = ZMP_ACCEL_STROKE();
  vstate.brake_stroke = ZMP_BRAKE_STROKE();
  vstate.steering_torque = ZMP_STEERING_TORQUE();
  vstate.steering_angle = ZMP_STEERING_ANGLE();
  vstate.velocity = ZMP_VELOCITY();
  vstate.tstamp = (long long int) (getTime());
}

void MainWindow::ClearCntDiag(void)
{
  ZMP_CLEAR_CNT_DIAG();
}


text: """Glue code used in jasyscript.py to have a convenient API on top of the full Jasy API."""


text:
package org.broadleafcommerce.common.sitemap.service;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.config.domain.ModuleConfiguration;
import org.broadleafcommerce.common.config.service.ModuleConfigurationService;
import org.broadleafcommerce.common.config.service.type.ModuleConfigurationType;
import org.broadleafcommerce.common.file.domain.FileWorkArea;
import org.broadleafcommerce.common.file.service.BroadleafFileService;
import org.broadleafcommerce.common.sitemap.domain.SiteMapConfiguration;
import org.broadleafcommerce.common.sitemap.domain.SiteMapGeneratorConfiguration;
import org.broadleafcommerce.common.sitemap.exception.SiteMapException;
import org.broadleafcommerce.common.util.BLCSystemProperty;
import org.broadleafcommerce.common.web.BaseUrlResolver;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;

import javax.annotation.Resource;

/**
 * Component responsible for generating a sitemap.   Relies on SiteMapGenerators to
 * produce the actual url entries within the sitemap.
 *
 * Create a sitemap index file and at least one sitemap file with the URL elements.
 *
 * @author bpolster
 *
 */
@Service("blSiteMapService")
public class SiteMapServiceImpl implements SiteMapService {

    protected static final Log LOG = LogFactory.getLog(SiteMapServiceImpl.class);

    protected static final String ENCODING_EXTENSION = ".gz";

    protected Boolean gzipSiteMapFiles;

    @Resource(name = "blModuleConfigurationService")
    protected ModuleConfigurationService moduleConfigurationService;

    @Resource(name = "blSiteMapGenerators")
    protected List<SiteMapGenerator> siteMapGenerators = new ArrayList<SiteMapGenerator>();

    @Resource(name = "blFileService")
    protected BroadleafFileService broadleafFileService;

    @Resource(name = "blBaseUrlResolver")
    protected BaseUrlResolver baseUrlResolver;

    @Override
    public SiteMapGenerationResponse generateSiteMap() throws SiteMapException, IOException {
        SiteMapGenerationResponse smgr = new SiteMapGenerationResponse();
        SiteMapConfiguration smc = findActiveSiteMapConfiguration();
        if (smc == null) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("No SiteMap generated since no active configuration was found.");
            }
            smgr.setHasError(true);
            smgr.setErrorCode("No SiteMap Configuration Found");
            return smgr;
        }

        FileWorkArea fileWorkArea = broadleafFileService.initializeWorkArea();
        SiteMapBuilder siteMapBuilder = new SiteMapBuilder(smc, fileWorkArea, baseUrlResolver.getSiteBaseUrl(), getGzipSiteMapFiles());

        if (LOG.isTraceEnabled()) {
            LOG.trace("File work area initalized with path " + fileWorkArea.getFilePathLocation());
        }
        for (SiteMapGeneratorConfiguration currentConfiguration : smc.getSiteMapGeneratorConfigurations()) {
            if (currentConfiguration.isDisabled()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Skipping disabled sitemap generator configuration" + currentConfiguration.getId());
                }
                continue;
            }
            SiteMapGenerator generator = selectSiteMapGenerator(currentConfiguration);
            if (generator != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("SiteMapGenerator found, adding entries" + generator.getClass());
                }
                generator.addSiteMapEntries(currentConfiguration, siteMapBuilder);
            } else {
                LOG.warn("No site map generator found to process generator configuration for " + currentConfiguration.getSiteMapGeneratorType());
            }
        }

        siteMapBuilder.persistSiteMap();

        // Check for GZip
        if (getGzipSiteMapFiles()) {
            gzipAndDeleteFiles(fileWorkArea, siteMapBuilder.getIndexedFileNames(), false);
            List<String> indexFileNames = new ArrayList<String>();
            for (String fileName: siteMapBuilder.getIndexedFileNames()) {
                indexFileNames.add(fileName + ENCODING_EXTENSION);
            }
            smgr.setSiteMapFilePaths(indexFileNames);
        } else {
            smgr.setSiteMapFilePaths(siteMapBuilder.getIndexedFileNames());
        }

        // Move the generated files to their permanent location
        broadleafFileService.addOrUpdateResources(fileWorkArea, true);
        broadleafFileService.closeWorkArea(fileWorkArea);

        return smgr;
    }

    @Override
    public File getSiteMapFile(String fileName) throws SiteMapException, IOException {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Method getSiteMapFile() invoked for " + fileName);
        }
        File siteMapFile = broadleafFileService.getResource(fileName, getSiteMapTimeoutInMillis());
        if (siteMapFile.exists()) {

            if (getAutoGenerateSiteMapAfterTimeout()) {
                long lastModified = siteMapFile.lastModified();
                long now = System.currentTimeMillis();
                // Create new SiteMap if timeout expired.
                if ((now - lastModified) > getSiteMapTimeoutInMillis().longValue()) {
                    generateSiteMap();
                    siteMapFile = broadleafFileService.getResource(fileName, getSiteMapTimeoutInMillis());
                }
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Returning existing SiteMap");
            }
            return siteMapFile;

        } else {
            if (getCreateSiteMapIfNotFound()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Generating SiteMap");
                }
                generateSiteMap();
                siteMapFile = broadleafFileService.getResource(fileName, getSiteMapTimeoutInMillis());
                if (siteMapFile.exists()) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Returning SiteMap file " + fileName);
                    }
                } else {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Sitemap file " + fileName + " not found after call to generate siteMap.xml");
                    }
                }
                return siteMapFile;
            } else {
                return null;
            }
        }
    }

    protected SiteMapConfiguration findActiveSiteMapConfiguration() {
        List<ModuleConfiguration> configurations = moduleConfigurationService.findActiveConfigurationsByType(ModuleConfigurationType.SITE_MAP);

        SiteMapConfiguration smc = null;
        if (configurations != null && !configurations.isEmpty()) {
            //Try to find a default configuration
            for (ModuleConfiguration configuration : configurations) {
                if (configuration.getIsDefault()) {
                    smc = (SiteMapConfiguration) configuration;
                    break;
                }
            }
            if (smc == null) {
                //if there wasn't a default one, use the first active one...
                smc = (SiteMapConfiguration) configurations.get(0);
            }
        }

        return smc;
    }

    /**
     * Returns the siteMapGenerator most qualified to handle the given configuration.
     *
     * @param smgc
     * @return
     */
    protected SiteMapGenerator selectSiteMapGenerator(SiteMapGeneratorConfiguration smgc) {
        for (SiteMapGenerator siteMapGenerator : siteMapGenerators) {
            if (siteMapGenerator.canHandleSiteMapConfiguration(smgc)) {
                return siteMapGenerator;
            }
        }
        return null;
    }

    /**
     *
     * @param fileWorkArea
     * @param fileNames
     */
    protected void gzipAndDeleteFiles(FileWorkArea fileWorkArea, List<String> fileNames,boolean shouldDeleteOriginal){
        for (String fileName : fileNames) {
            try {
                String fileNameWithPath = FilenameUtils.normalize(fileWorkArea.getFilePathLocation() + File.separator + fileName);

                FileInputStream fis = new FileInputStream(fileNameWithPath);
                FileOutputStream fos = new FileOutputStream(fileNameWithPath + ENCODING_EXTENSION);
                GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    gzipOS.write(buffer, 0, len);
                }
                //close resources
                gzipOS.close();
                fos.close();
                fis.close();

                if(shouldDeleteOriginal){
                    File originalFile = new File(fileNameWithPath);
                    originalFile.delete();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * GZip a file, Then delete it
     * @param fileWorkArea
     * @param fileNames
     */
    protected void gzipAndDeleteFiles(FileWorkArea fileWorkArea, List<String> fileNames) {
        gzipAndDeleteFiles(fileWorkArea,fileNames,true);
    }

    public List<SiteMapGenerator> getSiteMapGenerators() {
        return siteMapGenerators;
    }

    public void setSiteMapGenerators(List<SiteMapGenerator> siteMapGenerators) {
        this.siteMapGenerators = siteMapGenerators;
    }

    public ModuleConfigurationService getModuleConfigurationService() {
        return moduleConfigurationService;
    }

    public void setModuleConfigurationService(ModuleConfigurationService moduleConfigurationService) {
        this.moduleConfigurationService = moduleConfigurationService;
    }

    protected boolean getGzipSiteMapFilesDefault() {
        return BLCSystemProperty.resolveBooleanSystemProperty("sitemap.gzip.files");
    }

    public boolean getCreateSiteMapIfNotFound() {
        return BLCSystemProperty.resolveBooleanSystemProperty("sitemap.createIfNotFound");
    }

    public boolean getAutoGenerateSiteMapAfterTimeout() {
        return BLCSystemProperty.resolveBooleanSystemProperty("sitemap.createIfTimeoutExpired",false);
    }

    public Long getSiteMapTimeoutInMillis() {
        Long cacheSeconds = BLCSystemProperty.resolveLongSystemProperty("sitemap.cache.seconds");
        return cacheSeconds * 1000;
    }

    public void setGzipSiteMapFiles(Boolean gzipSiteMapFiles) {
        this.gzipSiteMapFiles = gzipSiteMapFiles;
    }

    public boolean getGzipSiteMapFiles() {
        if (this.gzipSiteMapFiles != null) {
            return this.gzipSiteMapFiles.booleanValue();
        } else {
            return getGzipSiteMapFilesDefault();
        }
    }
}


text:
from kobra.tr_utils import prep_out_path
import pandas as pd
from sklearn.cross_validation import train_test_split
from kobra.train_files import TrainFiles
from skimage.io.collection import ImageCollection
import os
from os import path
from shutil import copy, rmtree
import cv2

def get_sample_csv(sample_size = 0.1):
    X, Y, _, _ = TrainFiles.from_csv(inp_file, test_size = sample_size)
    tf = TrainFiles(train_path)

    tf.dump_to_csv(sample_file, X, Y)

def get_sample_of_class(classs, labels, input_path, num = -1):
    """
    Returns images sampled from files by class
    """

    existing_files = pd.DataFrame([path.splitext(f)[0] for f in os.listdir(input_path)], columns =[labels.columns[0]])
    class_labels = pd.DataFrame(labels[labels['level'] == classs]['image'], columns =[labels.columns[0]])
    class_labels = class_labels.merge(existing_files, on=class_labels.columns[0])
    if num == -1:
        num = class_labels.count()

    files = [path.join(raw_train, c + ".jpeg") for c in class_labels[:num][class_labels.columns[0]]]
    return ImageCollection(files, conserve_memory = True)

def sample_files(labels, size, inp_path, out_path):
    if path.exists(out_path):
        rmtree(out_path)
    os.makedirs(out_path)

    files = labels['image']
    levels = labels['level']
    picked_files, _, picked_labels, _ = train_test_split(files, levels, train_size = size)

    inp_files = [path.join(inp_path, f + ".jpeg") for f in picked_files]
    out_files = [path.join(out_path, f + ".jpeg") for f in picked_files]
    for src, dst in zip(inp_files, out_files):
        copy(src, dst)

labels_file = "/Kaggle/Retina/trainLabels.csv"
inp_path = "/Kaggle/retina/train/thresh5ref6535sc17"
out_path = "/Kaggle/retina/train/labelled_1"

def copy_files_to_label_dirs(inp_path, out_path, labels_file, process = None):
    prep_out_path(out_path)

    for i in range(0, 5):
        os.makedirs(path.join(out_path, str(i)))

    labels = pd.read_csv(labels_file)
    existing_files = pd.DataFrame([path.splitext(f)[0] for f in os.listdir(inp_path)], columns =[labels.columns[0]])
    existing_files = existing_files.merge(labels, on=existing_files.columns[0])

    def processAndCopy(inp_file, out_file):
        im = cv2.imread(inp_file)
        im = process(im)
        cv2.imwrite(out_file, im)

    if process == None:
        cp = copy
    else:
        cp = processAndCopy

    for f, l in zip(existing_files['image'], existing_files['level']):
        file_name = path.join(out_path, str(l), f + ".jpeg")
        inp_file = path.join(inp_path, f + '.jpeg')
        cp(inp_file, file_name)

        print "copied {0} to {1}".format(inp_file, file_name)

def post_proc(im):
    return cv2.medianBlur(im, 13)


text:
package mstparser;

import mstparser.io.*;
import mstparser.visual.Image;
import mstparser.visual.ImageQuadrant.Quadrant;
import mstparser.visual.ParserPolygon.Area;
import mstparser.visual.SpatialRelation;

import java.awt.geom.Point2D;
import java.io.*;

import gnu.trove.*;

import java.util.*;

/**
 * A DependencyPipe subclass for parsing Visual Dependency Representations.
 *
 * The types of features needed for parsing these representations are so
 * different from language that it warranted a new class.
 *
 * @author delliott
 *
 */
public class DependencyPipeVisual extends DependencyPipe
{

    private DependencyReader textReader;

    public Hashtable<String, String> cLabels;

    private ParserOptions options;

    private List<DependencyInstance> descriptions;
    private List<List<Alignment>> alignments;
    private List<Image> images;

    public DependencyPipeVisual(ParserOptions options) throws IOException
    {
        super(options);
        this.options = options;

        this.descriptions = new LinkedList<DependencyInstance>();
        this.alignments = new LinkedList<List<Alignment>>();
        this.images = new LinkedList<Image>();
    }

    /**
     * Initialise the data structures associated with the DependencyPipe.
     *
     * This happens here because a Constructor should not block.
     */
    @Override
    public void initialisePipe()
    {
    	try
    	{
    		textReader = DependencyReader.createDependencyReader(options.format,
    				                                             options.discourseMode);
    	}
    	catch (IOException ioe)
    	{
    		ioe.printStackTrace();
    	}

        this.readClusterAssignments(options.clustersFile);

    	if (options.train)
    	{
    		if (options.qg)
    		{
                this.readDescriptions(options.sourceFile);
                this.readAlignments(options.alignmentsFile);
                this.readClusterAssignments(options.clustersFile);
    		}

    		if (options.visualFeatures)
    		{
                this.images = new ArrayList<Image>();
                this.readImageData(options.imagesFile, options.xmlFile);
    		}
    	}
    	else if (options.test)
    	{
    		if (options.qg)
    		{

                this.readDescriptions(options.testSourceFile);
                this.readAlignments(options.testAlignmentsFile);
                this.readClusterAssignments(options.clustersFile);
    		}
    		if (options.visualFeatures)
    		{
	            this.images = new ArrayList<Image>();
	            this.readImageData(options.testImagesFile, options.testXmlFile);
    		}
		}
    }

	private void readClusterAssignments(String string)
    {
	    this.cLabels = new Hashtable<String, String>();
	    try
	    {
	        BufferedReader reader = new BufferedReader(new FileReader(string));
	        String line;

	        while((line = reader.readLine()) != null)
	        {
	            if (line.indexOf(":") != -1)
	            {
	                String assignment = line.split(":")[0];
	                String labels = line.split(":")[1];
	                String[] splitLabels = labels.split(",");
	                for(String s: splitLabels)
	                {
	                    this.cLabels.put(s, assignment);
	                }
	            }
	        }
	        reader.close();
	    }
	    catch (IOException ioe)
	    {
	        ioe.printStackTrace();
	    }
	    //this.cLabels = new Hashtable<String,String>();
    }

    public int[] createInstances(String file, File featFileName)
            throws IOException
    {

        createAlphabet(file);

        if (options.verbose)
          System.out.println(super.typeAlphabet.toString());

        System.out.println("Num Features: " + dataAlphabet.size());

        labeled = depReader.startReading(file);

        TIntArrayList lengths = new TIntArrayList();

        ObjectOutputStream out = options.createForest ? new ObjectOutputStream(
                new FileOutputStream(featFileName)) : null;

        DependencyInstance instance = depReader.getNext();
        depReader.resetCount();

        System.out.println("Creating Feature Vector Instances: ");
        while (instance != null)
        {

            //System.out.println(instance.toString());

            System.out.print(depReader.getCount() + " ");

            FeatureVector fv = this.createFeatureVector(instance);

            instance.setFeatureVector(fv);

            String[] labs = instance.deprels;
            int[] heads = instance.heads;

            StringBuffer spans = new StringBuffer(heads.length * 5);
            for (int i = 1; i < heads.length; i++)
            {
                spans.append(heads[i]).append("|").append(i).append(":")
                        .append(typeAlphabet.lookupIndex(labs[i])).append(" ");
            }
            instance.actParseTree = spans.substring(0, spans.length() - 1);

            lengths.add(instance.length());

            if (options.createForest)
            {
                writeInstance(instance, out);
            }

            instance = null;

            instance = depReader.getNext();
            depReader.incCount();
        }

        System.out.println();

        if (options.createForest)
        {
            out.close();
        }

        return lengths.toNativeArray();

    }

    private final void createAlphabet(String file) throws IOException
    {

        System.out.println("Creating Alphabet ... ");

        labeled = depReader.startReading(file);

        System.out.println("Labelled data: " + labeled);

        DependencyInstance instance = depReader.getNext();

        while (instance != null)
        {
            //System.out.println(String.format("Instance %s", depReader.getCount()));
            String[] labs = instance.deprels;
            for (int i = 0; i < labs.length; i++)
            {
                typeAlphabet.lookupIndex(labs[i]);
            }

            createFeatureVector(instance);

            instance = depReader.getNext();
            depReader.incCount();
        }

        System.out.println(typeAlphabet.toString());

        closeAlphabets();

        System.out.println("Done.");
    }

    /**
     * Read the parsed source sentences from disk into memory.
     *
     * @param sourceFile
     */
    public void readDescriptions(String sourceFile)
    {
        try
        {
            System.out.println(sourceFile);
            textReader.startReading(sourceFile);
            DependencyInstance x = textReader.getNext();
            while (x != null)
            {
                descriptions.add(x);
                x = textReader.getNext();
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    /**
     * Read the alignments from disk into memory.
     *
     * @param alignmentsFile
     * @throws IOException
     */
    public void readAlignments(String alignmentsFile)
    {
        int counter = 0;
    	try
	    {
	        alignments = new LinkedList<List<Alignment>>();

	        AlignmentsReader ar = AlignmentsReader
	                .getAlignmentsReader(alignmentsFile);

	        List<Alignment> thisLine = ar.getNext();

	        while (thisLine != null)
	        {
	            alignments.add(thisLine);
	            counter += thisLine.size();
	            thisLine = ar.getNext();
	        }
    	}
    	catch (IOException ioe)
    	{
    		ioe.printStackTrace();
    	}

    	System.out.println(String.format("Read %d alignments from disk", counter));
    }

    /**
     * Reads the content of LabelMe XML files and the associated raw image data
     * into an Image object. These data structures are used to infer
     * image-level statistics and features about the data set.
     *
     * @param imagesFile
     * @param xmlFile
     */
    public void readImageData(String imagesFile, String xmlFile)
    {
    	try
    	{
    	    System.out.println("Reading image data into memory");
			BufferedReader in = new BufferedReader(new FileReader(imagesFile));
			String line = null;
			while((line = in.readLine()) != null)
			{
				Image i = new Image(line);
				images.add(i);
			}
			in.close();
			in = new BufferedReader(new FileReader(xmlFile));
			line = null;
			int count = 0;
			while((line = in.readLine()) != null)
			{
				Image i = images.get(count);
				i.setXMLFile(line);
				count++;
			}
			for (Image i: images)
			{
				i.parseXMLFile();
				i.getImageDimensions();
				i.calculateSpatialRelationships();
				i.populateQuadrants();
				i.calculatePolygonAreas();
				i.findNearestPolygons();
				//System.out.println(i.toString());
			}
		}
    	catch (FileNotFoundException e)
    	{
			e.printStackTrace();
		}
    	catch (IOException e)
		{
			e.printStackTrace();
		}

	}

    /**
     * This is where we calculate the features over an input, which is
     * represented as a DependencyInstance.
     */
    public FeatureVector createFeatureVector(DependencyInstance instance)
    {
        final int instanceLength = instance.length();

        int[] heads = instance.heads;

        FeatureVector fv = new FeatureVector();
        for (int i = 0; i < instanceLength; i++)
        {
            if (heads[i] == -1)
            {
                continue;
            }

            /* Figure out if i the head and argument indices */
            int headIndex = i < heads[i] ? i : heads[i];
            int argIndex = i > heads[i] ? i : heads[i];
            boolean attR = i < heads[i] ? false : true;

            if (!attR)
            {
                int tmp = headIndex;
                headIndex = argIndex;
                argIndex = tmp;
            }

            this.addFeatures(instance, i, headIndex, argIndex, attR, headIndex == i, fv);
            this.labeledFeatures(instance, i, instance.deprels[i], true, attR, fv);
            this.labeledFeatures(instance, heads[i], instance.deprels[i], false, attR, fv);
        }

        return fv;
    }

    /**
     *
     * Fill the FeatureVectors for an unparsed DependencyInstance.
     *
     * @param fvs A three-dimension array of FeatureVectors where each [i][j][k]
     *            instance represents the features calculated between word i and
     *            word j in the DependencyInstance and k represents whether i or
     *            j was the proposed head node.
     *
     *  @param nt_fvs A four-dimension array of FeatureVectors where each
     *                [i][j][k][l] entry represents a feature vector with
     *                [i] = word token
     *                [j] = arc label
     *                [k=0] = i is head / [k=1] = i is child
     *                means [i] is a head and [k=1] means [i] is a child
     */
    public void fillFeatureVectors(DependencyInstance instance,
            FeatureVector[][][] fvs, double[][][] probs,
            FeatureVector[][][][] nt_fvs, double[][][][] nt_probs,
            Parameters params)
    {

        final int instanceLength = instance.length();

        for (int w1 = 0; w1 < instanceLength; w1++)
        {
            for (int w2 = w1 + 1; w2 < instanceLength; w2++)
            {
                for (int ph = 0; ph < 2; ph++)
                {
                    boolean attR = ph == 0 ? true : false;

                    int childInt = attR ? w2 : w1;
                    int parInt = attR ? w1 : w2;

                    FeatureVector prodFV = new FeatureVector();

                    this.addFeatures(instance, w1, parInt, childInt, attR, parInt == w1, prodFV);

                    double prodProb = params.getScore(prodFV);
                    fvs[w1][w2][ph] = prodFV;
                    probs[w1][w2][ph] = prodProb;
                }
            }
        }

        if (labeled)
        {
            for (int w1 = 0; w1 < instanceLength; w1++)
            {
                // For each word in the input sentence
                for (int t = 0; t < types.length; t++)
                {
                    // For each arc label type
                    String type = types[t];
                    for (int ph = 0; ph < 2; ph++)
                    {
                        // Does this attachment go left or right?
                        boolean attR = ph == 0 ? true : false;
                        for (int ch = 0; ch < 2; ch++)
                        {
                            // Do we include children features?
                            boolean child = ch == 0 ? true : false;

                            FeatureVector prodFV = new FeatureVector();
                            labeledFeatures(instance, w1, type, child, attR, prodFV);

                            double nt_prob = params.getScore(prodFV);
                            nt_fvs[w1][t][ph][ch] = prodFV;
                            nt_probs[w1][t][ph][ch] = nt_prob;

                        }
                    }
                }
            }
        }
    }

    /**
     * Override this method if you have extra features that need to be written
     * to disk. For the basic DependencyPipe, nothing happens.
     *
     */
    protected void writeExtendedFeatures(DependencyInstance instance,
            ObjectOutputStream out) throws IOException
    {
    }

    /**
     * Save the features in a gold standard DependencyInstance to disk at test time.
     *
     * This is used to create a parse forest.
     */
    @Override
    protected void writeInstance(DependencyInstance instance,
            ObjectOutputStream out)
    {
        try
        {
            final int instanceLength = instance.length();

            // Get production crap.

            for (int w1 = 0; w1 < instanceLength; w1++)
            {
                for (int w2 = w1 + 1; w2 < instanceLength; w2++)
                {
                    for (int ph = 0; ph < 2; ph++)
                    {
                        boolean attR = ph == 0 ? true : false;

                        int childInt = attR ? w2 : w1;
                        int parInt = attR ? w1 : w2;

                        FeatureVector prodFV = new FeatureVector();
                        this.addFeatures(instance, w1, parInt, childInt, attR, parInt == w1, prodFV);
                        out.writeObject(prodFV.keys());
                    }
                }
            }

            out.writeInt(-3);

            if (labeled)
            {
                for (int w1 = 0; w1 < instanceLength; w1++)
                {
                    for (int t = 0; t < types.length; t++)
                    {
                        String type = types[t];
                        for (int ph = 0; ph < 2; ph++)
                        {
                            boolean attR = ph == 0 ? true : false;
                            for (int ch = 0; ch < 2; ch++)
                            {
                                boolean child = ch == 0 ? true : false;
                                FeatureVector prodFV = new FeatureVector();
                                labeledFeatures(instance, w1, type, child, attR, prodFV);
                                out.writeObject(prodFV.keys());
                            }
                        }
                    }
                }
                out.writeInt(-3);
            }

            writeExtendedFeatures(instance, out);

            out.writeObject(instance.fv.keys());
            out.writeInt(-4);

            out.writeObject(instance);
            out.writeInt(-1);

            out.reset();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Read an instance from an input stream.
     *
     **/
    @Override
    public DependencyInstance readInstance(ObjectInputStream in, int length,
            FeatureVector[][][] fvs, double[][][] probs,
            FeatureVector[][][][] nt_fvs, double[][][][] nt_probs,
            Parameters params) throws IOException
    {

        try
        {

            // Get production crap.
            for (int w1 = 0; w1 < length; w1++)
            {
                for (int w2 = w1 + 1; w2 < length; w2++)
                {
                    for (int ph = 0; ph < 2; ph++)
                    {
                        FeatureVector prodFV = new FeatureVector(
                                (int[]) in.readObject());
                        double prodProb = params.getScore(prodFV);
                        fvs[w1][w2][ph] = prodFV;
                        probs[w1][w2][ph] = prodProb;
                    }
                }
            }
            int last = in.readInt();
            if (last != -3)
            {
                System.out.println("Error reading file.");
                System.exit(0);
            }

            if (labeled)
            {
                for (int w1 = 0; w1 < length; w1++)
                {
                    for (int t = 0; t < types.length; t++)
                    {
                        for (int ph = 0; ph < 2; ph++)
                        {
                            for (int ch = 0; ch < 2; ch++)
                            {
                                FeatureVector prodFV = new FeatureVector(
                                        (int[]) in.readObject());
                                double nt_prob = params.getScore(prodFV);
                                nt_fvs[w1][t][ph][ch] = prodFV;
                                nt_probs[w1][t][ph][ch] = nt_prob;
                            }
                        }
                    }
                }
                last = in.readInt();
                if (last != -3)
                {
                    System.out.println("Error reading file.");
                    System.exit(0);
                }
            }

            FeatureVector nfv = new FeatureVector((int[]) in.readObject());
            last = in.readInt();
            if (last != -4)
            {
                System.out.println("Error reading file.");
                System.exit(0);
            }

            DependencyInstance marshalledDI;
            marshalledDI = (DependencyInstance) in.readObject();
            marshalledDI.setFeatureVector(nfv);

            last = in.readInt();
            if (last != -1)
            {
                System.out.println("Error reading file.");
                System.exit(0);
            }

            return marshalledDI;

        }
        catch (ClassNotFoundException e)
        {
            System.out.println("Error reading file.");
            System.exit(0);
        }

        // this won't happen, but it takes care of compilation complaints
        return null;
    }

    /**
     * A wrapper method that performs all of the feature addition operations.
     *
     * @param instance the DependencyInstance read from disk
     * @param fv the FeatureVector for this instance.
     */
    public void addFeatures(DependencyInstance instance, int position,
    		int headIndex, int argIndex, boolean attR, boolean isHead, FeatureVector fv)
    {
        this.linguisticFeatures(instance, headIndex, argIndex, fv);
        this.visualFeatures(instance, headIndex, argIndex, fv);
        this.quasiSynchronousFeatures(instance, headIndex, argIndex, fv);
    }

    /**
     *
     * Adds features from the DependencyInstance itself to the FeatureVector.
     *
     * @param instance the DependencyInstance
     * @param headIndex index of the head word in DependencyInstance
     * @param argIndex index of the arg word in DependencyInstance
     * @param fv the FeatureVector to fill
     */
    public void linguisticFeatures(DependencyInstance instance,
            int headIndex, int argIndex, FeatureVector fv)
    {
        int[] heads = instance.heads;
        String[] forms = instance.forms;

        String hWord = checkForRootAttach(headIndex, heads) ? "ROOT" : forms[headIndex];

        hWord = this.cLabels.get(hWord) != null ? this.cLabels.get(hWord) : hWord;

        String aWord = forms[argIndex];
        aWord = this.cLabels.get(aWord) != null ? this.cLabels.get(aWord) : aWord;

        hWord = this.cLabels.get(hWord) != null ? this.cLabels.get(hWord) : hWord;
        StringBuilder feature;

    	//1. H=Head
        feature = new StringBuilder("H=" + hWord);
        this.add(feature.toString(), fv);

        // A=Arg
        feature = new StringBuilder("A=" + aWord);
        this.add(feature.toString(), fv);

        //13. H=Head A=Arg
        feature = new StringBuilder("H=" + hWord + " A=" + aWord);
        add(feature.toString(), fv);

        // IsPerson?

        boolean headIsPerson = this.cLabels.get(hWord) == "person";
        boolean argIsPerson = this.cLabels.get(hWord) == "person";
        feature = new StringBuilder("H=" + hWord + " AIP=" + headIsPerson);
        this.add(feature.toString(), fv);

        feature = new StringBuilder("A=" + aWord + " AIP=" + argIsPerson);
        this.add(feature.toString(), fv);

        feature = new StringBuilder("H=" + hWord + "A=" + aWord + " HIP=" + headIsPerson + " AIP=" + argIsPerson);
        this.add(feature.toString(), fv);
    }

    /**
     * Add the Quasi-synchronous Grammar features to the model.
     *
     * For a pair of Alignments, first and second, and the representation of the
     * target sentence and its corresponding source sentence, add a feature to
     * the model that represents the head word and argument word (in the target)
     * and syntactic configuration of the those words in the source.
     *
     * @param fv
     */
    public void quasiSynchronousFeatures(DependencyInstance instance, int headIndex,
    		                             int argIndex, FeatureVector fv)
    {
    	if (!options.qg)

    	{
    		return;
    	}

		boolean secondonly = false;

    	DependencyInstance source;
    	List<Alignment> a;

    	if (secondonly)
    	{
    		source = descriptions.get((super.depReader.getCount() * 2) + 1);
    		a = alignments.get((super.depReader.getCount() * 2) + 1);
    	}
    	else
    	{
    		source = descriptions.get((super.depReader.getCount() * 2));
    		a = alignments.get((super.depReader.getCount() * 2));
    	}

    	int j = secondonly == true ? 1 : 2;

    	if (secondonly)
    	{
    		j = 1;
    	}

        for (int i = 0; i < j; i++)
        {
        	// This loop runs twice to add features over the first and
        	// second sentences

        	if (a.size() == 0)
            {	// No QG features to add in this sentence
                continue;
            }

        	// Find the verb that relates the head and the argument when the head is not ROOT
            String verb = "";
            if (headIndex > 0)
            {
                int[] heads = source.heads;
                int rootPosition = -1;
                for (int z = 0; z < heads.length; z++)
                {
                    if (heads[z] == 0)
                    {
                        rootPosition = z;
                        break;
                    }
                }
              verb = source.lemmas[rootPosition];
            }

            boolean noverb = false;
            if (verb.equals("is"))
            {
            	noverb = true;
            }
            if (verb.equals("has"))
            {
            	noverb = true;
            }

            for (Alignment one : a)
            {
                for (Alignment two : a)
                {
                    if (one != two && ((one.getImageIndex() == headIndex && two.getImageIndex() == argIndex
                                || one.getImageIndex() == argIndex && two.getImageIndex() == headIndex)))
                    {
                        Alignment.Configuration c = one.getAlignmentConfiguration(two, instance, source);

                        // Get the labels of the head and argument from the clusters
                        String head_word = this.cLabels.contains(instance.forms[headIndex]) ?
                        		this.cLabels.get(instance.forms[headIndex]) : instance.forms[headIndex];
                        String arg_word = this.cLabels.contains(instance.forms[argIndex]) ?
                        		this.cLabels.get(instance.forms[argIndex]) : instance.forms[argIndex];

                        StringBuilder feature;

                        // H=Head CFG=config
                        feature = new StringBuilder("H=" + head_word + " CFG=" + c.toString());
                        add(feature.toString(), fv);

                        if (noverb == false)
                        {
                        // H=Head V=verb CFG=config
                        feature = new StringBuilder("H=" + head_word + " V=" + verb + " CFG=" + c.toString());
                        add(feature.toString(), fv);
                        }

                        // A=Arg CFG=config
                        feature = new StringBuilder("A=" + arg_word + " CFG=" + c.toString());
                        add(feature.toString(), fv);

                        if (noverb == false)
                        {
                         // A=Arg V=verb CFG=config
                        feature = new StringBuilder("A=" + arg_word + " V=" + verb + " CFG=" + c.toString());
                        add(feature.toString(), fv);
                        }

                        // H=Head A=Arg CFG=config
                        feature = new StringBuilder("H=" + head_word + " A=" + arg_word + " CFG=" + c.toString());
                        add(feature.toString(), fv);

                        if (noverb == false)
                        {
                        // H=Head A=Arg V=verb CFG=config
                        feature = new StringBuilder("H=" + head_word + " A=" + arg_word + " V=" + verb + " CFG=" + c.toString());
                        add(feature.toString(), fv);
                        }
                    }
                }
            }

        	source = descriptions.get((super.depReader.getCount() * 2) + 1);
        	a = alignments.get((super.depReader.getCount() * 2 )+ 1);
        }
    }

    /**
     * Adds visual information features to the parsing model.
     *
     * This method currently adds the following types of feature
     * conjoined in many different ways:
     *   polygon position
     *   polygon-polygon spatial relationship
     *
     * @param instance
     * @param headIndex
     * @param argIndex
     * @param fv
     */
    public void visualFeatures(DependencyInstance instance,
            int headIndex, int argIndex, FeatureVector fv)
    {

    	if (!this.options.visualFeatures)
    	{
    		return;
    	}

    	if (argIndex < 1)
    	{
    			return;
    	}

        if (headIndex < 1 || argIndex < 1)
    	{
    		return;
            // we cannot do anything with the ROOT node since there are no
            // spatial relationships between the ROOT node and any other node
    	}

        String[][] feats = instance.feats;
        String[] forms = instance.forms;

        Image i = images.get(depReader.getCount());

        if (options.verbose)
        {
        	System.out.println(feats[headIndex][0] + " " + feats[headIndex][1]);
        	System.out.println(feats[argIndex][0] + " " + feats[argIndex][1]);
        }

        Point2D headPoint = new Point2D.Double(new Double(feats[headIndex][0].replace("\"","")), new Double(feats[headIndex][1].replace("\"","")));
        Point2D argPoint = new Point2D.Double(new Double(feats[argIndex][0].replace("\"","")), new Double(feats[argIndex][1].replace("\"","")));

        int h = i.findPolygon(forms[headIndex], headPoint);
        int a = i.findPolygon(forms[argIndex], argPoint);

        if (h > -1 &&  a > -1)
        {
            // We need to have found valid polygons for these points to continue

        	String headForm = forms[headIndex];
        	headForm = this.cLabels.get(headForm) != null ?
                    this.cLabels.get(headForm) : headForm;
        	String argForm = forms[argIndex];
        	argForm = this.cLabels.get(argForm) != null ?
                    this.cLabels.get(argForm) : argForm;
            Quadrant headQuadrant = i.polygons[h].imageQuadrant;
            Quadrant argQuadrant = i.polygons[a].imageQuadrant;
            double headArea = i.polygons[h].relativeArea;
            double argArea = i.polygons[a].relativeArea;
            SpatialRelation.Relations relationship = i.polygons[h].spatialRelations[a];

            StringBuilder feature = new StringBuilder();

            // BEGIN STRUCTURE FEATURES //

    		// H=Head VHA=spatialLabel || -ROOT + DEP
        	feature = new StringBuilder("H=" + headForm + " VHA=" + relationship);
    		add(feature.toString(), fv);

    		// A=Arg VHA=spatialLabel || +ROOT --DEP
        	feature = new StringBuilder("A=" + argForm + " VHA=" + relationship);
    		add(feature.toString(), fv);

            // H=Head A=Arg VHA=spatial label || ~ROOT +DEP
            feature = new StringBuilder("H=" + headForm + " A=" + argForm + " VHA=" + relationship);
            add(feature.toString(), fv);

    		// END STRUCTURE FEATURES //

    		// BEGIN POSITION FEATURES //

            // H=Head HQ=quadrant || +ROOT -DEP
            feature = new StringBuilder("H=" + headForm + " HQ=" + headQuadrant);
    		add(feature.toString(), fv);

//    		// A=Arg AQ || - ROOT --DEP
//    		feature = new StringBuilder("A=" + argForm + " AQ=" + argQuadrant);
//    		add(feature.toString(), fv);
//
    		// H= A= HQ= AQ= || ~ROOT --DEP
//    		add("H=" + headForm + " HQ=" + headQuadrant + " A=" + argForm + " AQ=" + argQuadrant, fv);

            // H=Head HDFC || +ROOT ~DEP
            feature = new StringBuilder("H=" + headForm + " HDFC=" + i.polygons[h].distanceFromCentre);
            add(feature.toString(), fv);
            feature.append(" VHA=" + relationship);
            add(feature.toString(), fv);

//          // A=Arg ADFC || --ROOT --DEP
//          feature = new StringBuilder("A=" + argForm + " ADFC=" + i.polygons[a].distanceFromCentre);
//          add(feature.toString(), fv);
//          feature.append(" VHA=" + relationship);
//          add(feature.toString(), fv);
//
//          // H= A= HDFC= ADFC= || +ROOT --DEP
//          feature = new StringBuilder("H=" + headForm + " HDFC=" + i.polygons[h].distanceFromCentre + " A=" + argForm + " ADFC=" + i.polygons[a].distanceFromCentre);
//          add(feature.toString(), fv);
//          feature.append(" VHA=" + relationship);
//          add(feature.toString(), fv);

            // END POSITION FEATURES //

            // BEGIN AREA FEATURES //

            // H=Head HArea=area || ~ROOT +DEP
            feature = new StringBuilder("H=" + headForm + " HArea=" + headArea);
            add(feature.toString(), fv);

//            // H=Head HArea=area VHA=label || ~ROOT -DEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);
//
    		// A=Arg AArea=Area || +ROOT -DEP
    		feature = new StringBuilder("A=" + argForm + " AArea=" + argArea);
    		add(feature.toString(), fv);

            // A=Arg AArea=area VHA=label || ++ROOT -DEP
            feature.append(" VHA=" + relationship);
            add(feature.toString(), fv);

//    		// H=Head HArea=area A=Arg AArea=Area || +ROOT -DEP
//    		feature = new StringBuilder("H=" + headForm + " HArea=" + headArea + " A=" + argForm + " AArea=" + argArea);
//    		add(feature.toString(), fv);

//            // H=Head HArea=area A=Arg AArea=Area VHA=label || ++ROOT --DEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);

            // END AREA FEATURES //

    		// BEGIN DISTANCE FEATURES //

//            //H= DBO= ||
//    		feature = new StringBuilder("H=" + headForm + " DBO=" + i.polygons[h].calculateDistanceFromObject(i.polygons[a]));
//            add(feature.toString(), fv);
//
//            //H= DBO= VHA= ~ROOT +UDEP ~-LDEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);

//            // A= DBO= || +ROOT --DEP
//            feature = new StringBuilder("A=" + argForm + " DBO=" + i.polygons[h].calculateDistanceFromObject(i.polygons[a]));
//            add(feature.toString(), fv);
//
//            // A= DBO= VHA= || + ROOT --DEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);

            // H= A= DBO=
    		feature = new StringBuilder("H=" + headForm + " A=" + argForm + " DBO=" + i.polygons[h].calculateDistanceFromObject(i.polygons[a]));
    		add(feature.toString(), fv);

            // H= A= DBO= VHA= || ++ROOT +LDEP --UDEP
    		feature.append(" VHA=" + relationship);
    		add(feature.toString(), fv);

    		// END DISTANCE FEATURES//

    		// BEGIN OVERLAP FEATURES //

//    		//H= OL= || ~ ROOT --LDEP
//    		feature = new StringBuilder("H=" + headForm + " OL=" + i.polygons[h].overlaps(i.polygons[a]));
//    		add(feature.toString(), fv);

//    		 //H= OL= VHA= || ~ ROOT --LDEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);
//
//    		//A= OL= || ~ ROOT --LDEP
//            feature = new StringBuilder("A=" + argForm + " OL=" + i.polygons[h].overlaps(i.polygons[a]));
//            add(feature.toString(), fv);
//
//    		//A= OL= VHA= || ~ ROOT --LDEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);

//    		//H= A= OL= || ~ROOT --LDEP
//            feature = new StringBuilder("H=" + headForm + " A=" + argForm + " OL=" + i.polygons[h].overlaps(i.polygons[a]));
//            add(feature.toString(), fv);
//
//    		//H= A= OL= VHA= || ~ROOT --LDEP
//            feature.append(" VHA=" + relationship);
//            add(feature.toString(), fv);

    		// END OVERLAP FEATURES //

    		// BEGIN NEAREST OBJECT FEATURES //

            String nForm = i.polygons[h].nearestPolygon.label;
        	nForm = this.cLabels.get(nForm) != null ?
                    this.cLabels.get(nForm) : nForm;

//            add("WORD+NEARESTWORD=" + headForm + " " + nForm , fv);

//            add("W+NW+VHA=" + headForm + " " + nForm + " " + i.polygons[h].spatialRelations[i.polygons[h].nearestIndex], fv);

//            add("W+NW+QUAD=" + headForm + " " + nForm + " " + headQuadrant, fv);
//
//            add("W+NW+AREA=" + headForm + " " + nForm + " " + i.polygons[h].relativeArea + " " + i.polygons[i.polygons[h].nearestIndex].relativeArea, fv);
//
//            add("W+NW+DBO=" + headForm + " " + nForm + " " + i.polygons[h].calculateDistanceFromObject(i.polygons[h].nearestPolygon), fv);
//
//            add("WORD+NW+DFC=" + headForm + " " + nForm + " " + i.polygons[i.polygons[h].nearestIndex].distanceFromCentre, fv);

            // END NEAREST OBJECT FEATURES //
        }
    }

    /**
     * Adds features that allow for labelled parsing.
     *
     * @param instance
     * @param wordIndex
     * @param dependencyType
     * @param attR
     * @param childFeatures
     * @param fv
     */

    @Override
    public void labeledFeatures(DependencyInstance instance, int wordIndex,
            String dependencyType, boolean isHead, boolean attR, FeatureVector fv)
    {

    	if (labeled)
    	{
    		String[] forms = instance.forms;

            String word;

            if (wordIndex < 0)
            {
                word = "<root>";
            }
            else
            {
                word = forms[wordIndex]; // word
                word = this.cLabels.get(word) != null ?
                    this.cLabels.get(word) : word;
            }

            // WORD + LABEL
            add("WORD=" + word, fv);

            add("WORD+L=" + word + " " + dependencyType , fv);

            // WORD + RIGHT? + LABEL

            //add("WORD+ATTR+L=" + word + " " + dependencyType + " " + attR, fv);

            // WORD + ISPARENT? + LABEL

            add("WORD+ISHEAD+L=" + word + " " + dependencyType + " " + isHead, fv);

            // WORD + ISPERSON? + LABEL
            add("WORD+L+ISPERSON=" + word + " " + (this.cLabels.get(word) == "person") + " " + dependencyType, fv);

            if (options.visualFeatures)
            {
            	if (wordIndex < 1)
            	{
            		return;
            	}

            	String[][] feats = instance.feats;

            	Image i = images.get(depReader.getCount());

	            if (options.verbose)
	            {
	            	System.out.println(feats[wordIndex][0] + " " + feats[wordIndex][1]);
	            }

	            Point2D headPoint = new Point2D.Double(new Double(feats[wordIndex][0].replace("\"","")), new Double(feats[wordIndex][1].replace("\"","")));

	            int h = i.findPolygon(forms[wordIndex], headPoint);

	            if (h > -1)
	            {
	                // We need to have found valid polygons for these points to continue

	            	String headForm = forms[wordIndex];
	            	headForm = this.cLabels.get(headForm) != null ?
	                        this.cLabels.get(headForm) : headForm;

	                Quadrant headQuadrant = i.polygons[h].imageQuadrant;

	                double headArea = i.polygons[h].relativeArea;

	                StringBuilder feature = new StringBuilder();

				    // BEGIN POSITION FEATURES //

	                // WORD + DISTANCE_CENTRE + LABEL || -ROOT -LDEP -UDEP
//	                feature = new StringBuilder("WORD+DFC+L=" + word + " " + i.polygons[h].distanceFromCentre);
//	                add(feature.toString(), fv);

	                // WORD + QUAD + LABEL || --ROOT ---LDEP -UDEP
//	                feature = new StringBuilder("WORD+WQUAD+L=" + word + " " + headQuadrant);
//	                add(feature.toString(), fv);

	                // WORD + SIZE + LABEL || -
	                feature = new StringBuilder("WORD+AREA=" + word + " "+ headArea);
	                add(feature.toString(), fv);
//	                feature = new StringBuilder("WORD+AREA+ISPERSON=" + word + " "+ headArea + " " + (this.cLabels.get(word) == "person"));
//	                add(feature.toString(), fv);
//	                feature.append(" " + dependencyType);
//	                add(feature.toString(), fv);

	                // END AREA FEATURES //

	                String nForm = i.polygons[h].nearestPolygon.label;
	            	nForm = this.cLabels.get(nForm) != null ?
	                        this.cLabels.get(nForm) : nForm;

	                //add("WORD+NEARESTWORD=" + headForm + " " + nForm + " " + dependencyType, fv);

	            }
            }

        	if (options.qg)
        	{
        		boolean secondonly = false;

            	DependencyInstance source;
            	List<Alignment> a;

            	if (secondonly)
            	{
            		source = descriptions.get((super.depReader.getCount() * 2) + 1);
            		a = alignments.get((super.depReader.getCount() * 2) + 1);
            	}
            	else
            	{
            		source = descriptions.get((super.depReader.getCount() * 2));
            		a = alignments.get((super.depReader.getCount() * 2));
            	}

            	int j = secondonly == true ? 1 : 2;

            	if (secondonly)
            	{
            		j = 1;
            	}

	            for (int i = 0; i < j; i++)
	            {
	            	// This loop runs once because we only want the verb in the first sentence.

//	            	if (a.size() == 0)
//	                {	// No QG features to add in this sentence
//	                    continue;
//	                }

	            	// Find the verb in the sentence when the head is not ROOT
	                String verb = "";
	                if (wordIndex > 0)
	                {
	                    int[] heads = source.heads;
	                    int rootPosition = -1;
	                    for (int z = 0; z < heads.length; z++)
	                    {
	                        if (heads[z] == 0)
	                        {
	                            rootPosition = z;
	                            break;
	                        }
	                    }
	                  verb = source.lemmas[rootPosition];
	                }

	                boolean noverb = false;
	                if (verb.equals("is"))
	                {
	                	noverb = true;
	                }
	                if (verb.equals("has"))
	                {
	                	noverb = true;
	                }

	                if (noverb == false)
	                {
	                add("WORD+UNSUPV=" + word + " " + verb, fv);

	                add("WORD+UNSUPV+L=" + word + " " + verb + " " + dependencyType, fv);
	                }
//	                for (Alignment one : a)
//	                {
//	                    for (Alignment two : a)
//	                    {
//	                        if (one != two && ((one.getImageIndex() == wordIndex && two.getImageIndex() == argIndex
//	                                    || one.getImageIndex() == argIndex && two.getImageIndex() == wordIndex)))
//	                        {
//	                            Alignment.Configuration c = one.getAlignmentConfiguration(two, instance, source);
//
//	                            // Get the labels of the head and argument from the clusters
//	                            String head_word = this.cLabels.contains(instance.forms[wordIndex]) ?
//	                            		this.cLabels.get(instance.forms[wordIndex]) : instance.forms[wordIndex];
//
//	                            StringBuilder feature;
//
//
//	                                // H=Head CFG=config HA=label
//	                                feature = new StringBuilder("H=" + head_word + " CFG=" + c + " HA=" + label);
//	                                add(feature.toString(), fv);
//
//	                                // H=Head V=verb CFG=config HA=label
//	                                feature = new StringBuilder("H=" + head_word + " V=" + verb + " CFG=" + c.toString() + " HA=" + label);
//	                                add(feature.toString(), fv);
//
//	                                // A=Arg CFG=config HA=label
//	                                feature = new StringBuilder("A=" + arg_word + " CFG=" + c + " HA=" + label);
//	                                add(feature.toString(), fv);
//
//	                                // A=Arg V=verb CFG=config HA=label
//	                                feature = new StringBuilder("A=" + arg_word + " V=" + verb + " CFG=" + c.toString() + " HA=" + label);
//	                                add(feature.toString(), fv);
//
//	                                // H=Head A=Arg CFG=config HA=label
//	                                feature = new StringBuilder("H=" + head_word + " A=" + arg_word + " CFG=" + c + " HA=" + label);
//	                                add(feature.toString(), fv);
//
//	                                // H=Head A=Arg V=verb CFG=config HA=label
//	                                feature = new StringBuilder("H=" + head_word + " A=" + arg_word + " V=" + verb + " CFG=" + c.toString() + " HA=" + label);
//	                                add(feature.toString(), fv);
//	                            }
//	                        }
//	                    }
//	                }

	            	source = descriptions.get((super.depReader.getCount() * 2) + 1);
	            	a = alignments.get((super.depReader.getCount() * 2 )+ 1);
	            }
        	}
    	}
    }

    /**
     * @param index the position of the word in the DependencyInstance
     * @param instanceHeads the array of instance heads in the Dependency Instance.
     * @return true if the word at position index has a head at -1.
     */
    public boolean checkForRootAttach(int index, int[] instanceHeads)
    {
    	if (index == -1)
    	{
    		return true;
    	}

        if (instanceHeads[index] == -1)
        {
            return true;
        }
        return false;
    }

    public int numberOfSiblings(int index, int[] instanceHeads)
    {
    	if (index == -1)
    	{
    		return 0;
    	}

    	int thisHead = instanceHeads[index];
    	int siblings = 0;

    	for (int i: instanceHeads)
    	{
    		if (i == index || i == -1)
    		{
    			continue;
    		}
    		if (instanceHeads[i] == thisHead)
    		{
    			siblings += 1;
    		}
    	}

    	return siblings;
    }
}


text:
#ifndef EDITTABLEVIEW_H
#define EDITTABLEVIEW_H

#include <QtWidgets/QTableView>

class EditTableView : public QTableView
{
    Q_OBJECT

public:
    EditTableView(QWidget *parent = 0);
    void keyPressEvent(QKeyEvent *event);

public slots:
    void removeOne();
    void removeAll();
};

#endif // EDITTABLEVIEW_H


text: require 'geography_division_select'


text:
package minichess;

import java.awt.*;
import java.util.List;

/**
 * Created by ben on 5/1/2017.
 */
public class Piece {

    public static final int PAWN_VALUE = 150;
    public static final int KING_VALUE = 10000000;//should be order(s) of magnitude > sum of all others
    public static final int QUEEN_VALUE = 600;//can have up to 6 if all pawns promote
    public static final int KNIGHT_VALUE = 350;
    public static final int ROOK_VALUE = 500;
    public static final int BISHOP_VALUE = 300;

    //private Board board;
    private char self;
    private byte locx;
    private byte locy;
    private char color = 0;

    public Piece() {
        //board = null;//only need this for pieces that move

        self = '.';
    }

    public Piece( Point location, char c) {
        this(location.x, location.y, c);
    }

    public Piece(int xloc, int yloc, char c) {
        //this.board = board;
        this.locx = (byte)xloc;
        locy = (byte)yloc;
        self = c;
        if(Character.isUpperCase(self))
            color = 'w';
        else if (Character.isLowerCase(self))
            color = 'b';
    }

    public boolean isWhite() {
        return color == 'w';
    }

    public boolean isBlack() {
        return color == 'b';
    }

    public static int getValue(char c) {
        switch (Character.toLowerCase(c)) {
            case 'p':
                return PAWN_VALUE;
            case 'r':
                return ROOK_VALUE;
            case 'b':
                return BISHOP_VALUE;
            case 'n':
                return KNIGHT_VALUE;
            case 'q':
                return QUEEN_VALUE;
            case 'k':
                return KING_VALUE;
            default:
                return 0;
        }
    }

    public int getValue() {
        return getValue(self);
    }

    public char toChar() {
        return self;
    }

    @Override
    public String toString() {
        return Character.toString(self);
    }

    public void setLocation(Point location) {
        this.locx = (byte)location.x;
        locy = (byte)location.y;
    }

    public void setLocation(int x, int y) {
        this.locx = (byte)x;
        locy = (byte)y;
    }

    public byte getY() {
        return locy;
    }

    public void addMovesToList(Board board, List<Move> moves) {
        switch (self) {
            case 'p':
                symScan(board, moves, 1, 1, true, -1, 2, this);
                scanMoves(board, moves, 0, 1, true, 0, this);
                break;
            case 'P':
                symScan(board, moves, -1, -1, true, -1, 2, this);
                scanMoves(board, moves, 0, -1, true, 0, this);
                break;
            case 'r':
            case 'R':
                symScan(board, moves, 1, 0, this);
                break;
            case 'b':
            case 'B':
                symScan(board, moves, 1, 1, this);
                symScan(board, moves, 1, 0, true, 0, this);
                break;
            case 'n':
            case 'N':
                symScan(board, moves, 2, 1, true, 1, this);
                symScan(board, moves, 2, -1, true, 1, this);
                break;
            case 'q':
            case 'Q':
                symScan(board, moves, 1, 0, this);
                symScan(board, moves, 1, 1, this);
                break;
            case 'k':
            case 'K':
                symScan(board, moves, 0, 1, true, 1, this);
                symScan(board, moves, 1, 1, true, 1, this);
                break;
            default:
                return;
        }

    }

    private static void symScan(Board board, List<Move> moves, int dx, int dy, Piece piece) { // continuous scan in all directions, for Q,B,R
        symScan(board, moves, dx, dy, false, 1, 4, piece);
    }

    private static void symScan(Board board, List<Move> moves, int dx, int dy, boolean stopShort, int capture, Piece piece) { // stopshort scan in all directions for K,N,B(change color)
        symScan(board, moves, dx, dy, stopShort, capture, 4, piece);
    }

    private static void symScan(Board board, List<Move> moves, int dx, int dy, boolean stopShort, int capture, int steps, Piece piece) { // also used at 2 steps for pawn attacks
        //if(steps <= 0) return;
        for (int i = 0; i < steps; i++) {
            scanMoves(board, moves, dx, dy, stopShort, capture, piece);
            int temp = dx;
            dx = -dy;
            dy = temp;
        }
        //symScan(board, moves, -dy, dx, stopShort, capture, --steps, piece);
    }

    private static void scanMoves(Board board, List<Move> moves, int dx, int dy, boolean stopShort, int capture, Piece piece) {
        byte x, y;
        x = piece.locx;
        y = piece.locy;
        int xBound = Board.WIDTH - 1;
        int yBound = Board.HEIGHT - 1;
        do{
            x+=dx;
            y+=dy;
            if(x > xBound || y > yBound || x < 0 || y < 0)
                break;

            Piece target = board.getSquare(x, y);

            if(target.toChar() != '.') {
                if (piece.isWhite() == target.isWhite() || capture == 0) //same color or can't cap
                    break;
                stopShort = true; //can cap this piece, but we can't continue further
            }
            else if(capture == -1)
                break;

            moves.add(new Move(piece.locx, piece.locy, x, y, board));
        } while (!stopShort);
    }
}


text:
package com.huijimuhe.monolog.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.ImageView;

import com.huijimuhe.monolog.R;
import com.huijimuhe.monolog.core.AppContext;
import com.huijimuhe.monolog.ui.base.AbstractActivity;

import uk.co.senab.photoview.PhotoViewAttacher;

public class PhotoViewActivity extends AbstractActivity {

    ImageView mImageView;
    PhotoViewAttacher mAttacher;
    String mUrl;

    public static Intent newIntent(String url) {
        Intent intent = new Intent(AppContext.getInstance(), PhotoViewActivity.class);
        intent.putExtra("url", url);
        return intent;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("url", mUrl);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            mUrl = savedInstanceState.getString("url");
        } else {
            mUrl = getIntent().getStringExtra("url");
        }
        //toolbar
        setContentView(R.layout.activity_photo_view);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       // toolbar.setTitle("图片浏览");
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);

        // Any implementation of ImageView can be used!
        mImageView = (ImageView) findViewById(R.id.iv_photo);

        // Set the Drawable displayed
        AppContext.getInstance().loadImg(mImageView, mUrl);

        // Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
        mAttacher = new PhotoViewAttacher(mImageView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_contact_list, menu);
        return true;
    }
}


text:
layout: post
title: "A Post with Images"
description: "Examples and code for displaying images in posts."
tags: [sample post, images, test]
---

Here are some examples of what a post with images might look like. If you want to display two or three images next to each other responsively use `figure` with the appropriate `class`. Each instance of `figure` is auto-numbered and displayed in the caption.

## Figures (for images or video)

### One Up

Morning Fog Emerging From Trees by A Guy Taking Pictures, on Flickr.

### Two Up

Apply the `half` class like so to display two images side by side that share the same caption.

```html
<figure class="half">
	<img src="/images/image-filename-1.jpg" alt="">
	<img src="/images/image-filename-2.jpg" alt="">
	<figcaption>Caption describing these two images.</figcaption>
</figure>
```

And you'll get something that looks like this:

Two images.

### Three Up

Apply the `third` class like so to display three images side by side that share the same caption.

```html
<figure class="third">
	<a href="http://placehold.it/1200x600.jpg"><img src="http://placehold.it/600x300.jpg" alt=""></a>
	<a href="http://placehold.it/1200x600.jpg"><img src="http://placehold.it/600x300.jpg" alt=""></a>
	<a href="http://placehold.it/1200x600.jpg"><img src="http://placehold.it/600x300.jpg" alt=""></a>
	<figcaption>Caption describing these three images.</figcaption>
</figure>
```

And you'll get something that looks like this:

Three images.

### Alternative way

Another way to achieve the same result is to include `gallery` Liquid template. In this case you
don't have to write any HTML tags – just copy a small block of code, adjust the parameters (see below)
and fill the block with any number of links to images. You can mix relative and external links.

Here is the block you might want to use:

```liquid
{% raw %}{% capture images %}
	/images/abstract-10.jpg
	/images/abstract-11.jpg
	http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png
{% endcapture %}
{% include gallery images=images caption="Test images" cols=3 %}{% endraw %}
```

Parameters:

- `caption`: Sets the caption under the gallery (see `figcaption` HTML tag above);
- `cols`: Sets the number of columns of the gallery.
Available values: [1..3].

It will look something like this:

{% capture images %}
	/images/abstract-10.jpg
	/images/abstract-11.jpg
	http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png
{% endcapture %}
{% include gallery images=images caption="Test images" cols=3 %}


text:
package com.hyrax.client.email.api.request;

import com.hyrax.client.email.api.domain.BaseTemplate;
import com.hyrax.client.email.api.domain.SubTemplate;
import lombok.Builder;
import lombok.Data;

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

@Data
@Builder
public class EmailNotificationRequest {

    private final String senderEmailAddress;

    private final Collection<String> recipientUsernames;

    private final String subject;

    private final BaseTemplate baseTemplate;

    private final SubTemplate subTemplate;

    private final Map<String, String> model;
}


text:
package oet.wouter.ejbtesting.componentconstruction.jaxrs;

import oet.wouter.ejbtesting.componentconstruction.Target;
import oet.wouter.ejbtesting.componentconstruction.UsageTarget;

import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/")
public class Service {

    @EJB
    Target target;

    @EJB
    UsageTarget usageTarget;

    @GET
    @Path("/usage")
    public String invokeUsage() {
        try {
            usageTarget.invoke();
        } catch (Exception e) {
            return "Received exception: " + e.getClass().getName() + " with cause " + e.getCause().getClass().getName();
        }

        return "success";
    }

    @GET
    @Path("/construct")
    public String invoke() {
        target.invoke();
        return "success";
    }
}


text:
<?php

namespace Drupal\migrate_infob\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;

/**
 * Taxonomy term source from database.
 *
 *
 * @MigrateSource(
 *   id = "taxonomy_term_csolutions",
 *   source_provider = "taxonomy"
 * )
 */
class TermCsolutions extends DrupalSqlBase {

  protected $vocabularyName = 'Complementary Solutions';

  protected $vocVid;

  protected $termsToMigrate = [
    '1010data',
    'ESRI',
    'Google',
    'IBM',
    'IBM PureSystems',
    'IBM System z',
    'Oracle',
    'Redhat',
    'Salesforce Chatter Integration',
    'SAP',
    'Teradata'
    ];

  /**
   * {@inheritdoc}
   */
  public function query() {
    if (empty($this->topicsVid)) {
      $vid = $this->select('vocabulary', 'v')
        ->fields('v', ['vid'])
        ->condition('name', $this->vocabularyName)
        ->distinct()
        ->execute()
        ->fetchCol();
      $this->vocVid = $vid;
    }
    $query = $this->select('term_data', 'td')
      ->fields('td')
      ->distinct()
      ->orderBy('td.tid');

    if (isset($this->vocVid)) {
      $query->condition('td.vid', $this->vocVid);
    }
    $query->condition('name', $this->termsToMigrate, 'IN');

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'tid' => $this->t('The term ID.'),
      'vid' => $this->t('Existing term VID'),
      'name' => $this->t('The name of the term.'),
      'description' => $this->t('The term description.'),
      'weight' => $this->t('Weight'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['tid']['type'] = 'integer';
    return $ids;
  }

}


text:
<?php
$m->mbre->securite_admin('billets_redaction');

	$page="admin.php?billets-categories";
	$table=PREFIX."categories";

	$fil_ariane='Gestion des catégories / ';

	// Gestion des retours
	if (!empty($_GET['mess'])) {
		$mess=$_GET['mess'];

		if ($mess=="ajout_ok") $retour=miseEnForme_admin('ok', "La nouvelle categorie a été ajoutée avec succés !");
		if ($mess=="ajout_erreurForm") $retour=miseEnForme_admin('bad', "La nouvelle categorie n'a pas pu être ajoutée car le formulaire n'a pas été rempli correctement");
		if ($mess=="ajout_erreurSql") $retour=miseEnForme_admin('bad', "La nouvelle categorie n'a pas pu être ajoutée car une erreur est survenue durant l'enregistrement dans la base de donnée");
		if ($mess=="suppr_ok") $retour=miseEnForme_admin('ok', "Suppresion confirmée");
		if ($mess=="suppr_erreur") $retour=miseEnForme_admin('bad', "La suppression de la nouvelle categorie a échoué");
		if ($mess=="edit_ok") $retour=miseEnForme_admin('ok', "La nouvelle categorie a été modifiée avec succés !");
		if ($mess=="edit_erreurForm") $retour=miseEnForme_admin('bad', "La nouvelle categorie n'a pas pu être éditée car le formulaire n'a pas été rempli correctement");
		if ($mess=="edit_erreurSql") $retour=miseEnForme_admin('bad', "La nouvelle categorie n'a pas pu être éditée car une erreur est survenue durant l'enregistrement dans la base de donnée");
		$m->design->assign('retour', $retour);
	}

switch(@$_GET['action']) {

default:

	// Sélection de toutes les données
	$sql=mysql_query("SELECT * FROM $table ORDER BY id_cat DESC");

	$fil_ariane.='Apercu des catégories';

	// Mise en forme du bloc principal
	$c='

Ajouter une categorie

';

	while($d=mysql_fetch_array($sql)) {

		// On récupère les données
		extract(fonctions::recupBdd($d));

		// Nombre de billets liés ?
		$sqlN=mysql_query("SELECT count(id_cat) as nb FROM ".PREFIX."billets WHERE id_cat=$id_cat");
		$n=mysql_fetch_object($sqlN);
			$nb=round($n->nb);

		$c.= '

Categorie #'.$id_cat.'

Nom : '.$cat.'

Nom url : '.$cat_url.'

Billets liés : '.$nb.'

Description

							'.$cat_desc.'

Actions

Editer

Supprimer

';

	}

break;

case "ajouter":

	$fil_ariane.='Ajouter une catégorie';

	$c= '<form action="'.$page.'&action=ajouter_verif" method="post" class="f-wrap-1">

* Champs requis

			<fieldset>

Ajouter une catégorie

			*Nom :
				<input id="cat" name="cat" type="text" class="f-name" tabindex="1" maxlength="50"/>

			Nom rewrité (facultatif) :
				<input id="cat_url" name="cat_url" type="text" class="f-name" tabindex="1" maxlength="50"/>

			Description en quelques mots
				<textarea id="cat_desc" name="cat_desc" class="f-comments" rows="4" cols="30" tabindex="2"></textarea>

<input type="submit" value="Ajouter" class="f-submit" tabindex="5"/>

		</fieldset>
		</form>';

break;

case "ajouter_verif":

	// Vérifications des champs obligatoires
	verif_champs_requis($page.'&action=ajouter&mess=ajout_erreurForm', $_POST, array('cat'));

	// Ajout dans la bdd
	$sql=insererBdd($table, $_POST);

	if ($sql) 	{ header('location: '.$page.'&mess=ajout_ok'); die(); }
	else 		{ header('location: '.$page.'&action=ajouter&mess=ajout_erreurSql'); die(); }

break;

case "supprimer":

	$id_cat=(int)$_GET['id'];

	// Suppresion
	$sql=mysql_query("DELETE FROM ".$table." WHERE id_cat=$id_cat");

	if ($sql) 	{ header('location: '.$page.'&mess=suppr_ok'); die(); }
	else 		{ header('location: '.$page.'&mess=suppr_erreur'); die(); }

break;

case "editer":

	$id=(int)$_GET['id'];

	// Sélection des données pour cet id
	$sql=mysql_query("SELECT * FROM $table WHERE id_cat=".$id);
		extract(fonctions::recupBdd(mysql_fetch_array($sql)));

	// Mise en forme du formulaire
	$fil_ariane.='Editer une categorie';

	$c= '<form action="'.$page.'&action=editer_verif&id='.$id.'" method="post" class="f-wrap-1">

* Champs requis

			<fieldset>

Editer une categorie

			*Nom :
				<input id="cat" name="cat" type="text" class="f-name" tabindex="1" maxlength="50" value="'.$cat.'"/>

			Nom rewrité (facultatif) :
				<input id="cat_url" name="cat_url" type="text" class="f-name" tabindex="1" maxlength="50" value="'.$cat_url.'"/>

			Description en quelques mots
				<textarea id="cat_desc" name="cat_desc" class="f-comments" rows="4" cols="30" tabindex="2" >'.$cat_desc.'</textarea>

<input type="submit" value="Modifier" class="f-submit" tabindex="6"/>

		</fieldset>
		</form>';

	//TODO:Gérer le logo

break;

case "editer_verif":

	$id=(int)$_GET['id'];

	// Vérifications des champs obligatoires
	verif_champs_requis($page.'&action=editer&mess=edit_erreurForm', $_POST, array('cat'));

	// modification dans la bdd
	$sql=majBdd($table, '`id_cat`='.$id.'', $_POST);

	if ($sql) 	{ header('location: '.$page.'&mess=edit_ok'); die(); }
	else 		{ header('location: '.$page.'&action=editer&id='.$id.'&mess=edit_erreurSql'); die(); }

break;

}

	$m->design->assign('titre', 'Gestion des categories');
	$m->design->assign('fil_ariane', $fil_ariane);
	$m->design->assign('contenu', $c);

?>


text:
package org.apache.arrow.flatbuf;

public final class UnionMode {
  private UnionMode() { }
  public static final short Sparse = 0;
  public static final short Dense = 1;

  public static final String[] names = { "Sparse", "Dense", };

  public static String name(int e) { return names[e]; }
}


text:
package com.google.gson;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Lazy JSON node wrapper, that will create generate real JsonElement after first call to it's methods.
 * Note, that in a case if input JSON string is invalid it may throw runtime exception from any method.
 * This is really awkward, but I can extend JsonElement only from com.google.gson package.
 */
public class JsonElementLazyWrapper extends JsonElement implements Serializable {

    private static final JsonParser PARSER = new JsonParser();

    private static final long serialVersionUID = -4882634013737740905L;

    private final String json;

    private JsonElement node;

    public JsonElementLazyWrapper(String json) {
        this.json = json;
    }

    /**
     * This will return source JSON string passed as argument into constructor.
     */
    public String getJsonSource() {
        return this.json;
    }

    private JsonElement element() {
        if (this.node == null) {
            synchronized (this) {
                if (this.node == null) {
                    node = PARSER.parse(json);
                }
            }
        }
        return this.node;
    }

    @Override
    JsonElement deepCopy() {
        return element().deepCopy();
    }

    @Override
    public boolean isJsonArray() {
        return element().isJsonArray();
    }

    @Override
    public boolean isJsonObject() {
        return element().isJsonObject();
    }

    @Override
    public boolean isJsonPrimitive() {
        return element().isJsonPrimitive();
    }

    @Override
    public boolean isJsonNull() {
        return element().isJsonNull();
    }

    @Override
    public JsonObject getAsJsonObject() {
        return element().getAsJsonObject();
    }

    @Override
    public JsonArray getAsJsonArray() {
        return element().getAsJsonArray();
    }

    @Override
    public JsonPrimitive getAsJsonPrimitive() {
        return element().getAsJsonPrimitive();
    }

    @Override
    public JsonNull getAsJsonNull() {
        return element().getAsJsonNull();
    }

    @Override
    public boolean getAsBoolean() {
        return element().getAsBoolean();
    }

    @Override
    public Number getAsNumber() {
        return element().getAsNumber();
    }

    @Override
    public String getAsString() {
        return element().getAsString();
    }

    @Override
    public double getAsDouble() {
        return element().getAsDouble();
    }

    @Override
    public float getAsFloat() {
        return element().getAsFloat();
    }

    @Override
    public long getAsLong() {
        return element().getAsLong();
    }

    @Override
    public int getAsInt() {
        return element().getAsInt();
    }

    @Override
    public byte getAsByte() {
        return element().getAsByte();
    }

    @Override
    public char getAsCharacter() {
        return element().getAsCharacter();
    }

    @Override
    public BigDecimal getAsBigDecimal() {
        return element().getAsBigDecimal();
    }

    @Override
    public BigInteger getAsBigInteger() {
        return element().getAsBigInteger();
    }

    @Override
    public short getAsShort() {
        return element().getAsShort();
    }

    @Override
    public String toString() {
        return element().toString();
    }

    @Override
    public int hashCode() {
        return element().hashCode();
    }

    @Override
    public boolean equals(Object o) {
        return element().equals(o);
    }
}


text:
import collections
d = collections.defaultdict(list)
d[1].append(3)
d[2].append(4)
print(d)
for k in d:
    print(k)


text:
/**
 * Author : Laberat
 * Date   : 16/2/2.
 * Link   : https://leetcode.com/problems/delete-node-in-a-linked-list/
 * Number : # 237
 * Desc   : Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
 *          Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3,
 *          the linked list should become 1 -> 2 -> 4 after calling your function.
 */
public class DelNodeInALinkedList {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}