text:
package com.ymsino.esb.archives.model;

/**
 * WaterCustomer entity. @author MyEclipse Persistence Tools
 */

public class WaterCustomer  implements java.io.Serializable {

    // Fields

     /**
      * ÓÃË®Óû§±àºÅ
     */
     private String customerId;
     /**
      * ÓÃË®Óû§Ãû³Æ
     */
     private String customerName;
     /**
      * ×Ô¶¨Òå²éѯºÅ
     */
     private String customNum;
     /**
      * Óû§id
     */
     private Long uid;
     /**
      * ¿Í»§±àºÅ
     */
     private String userId;
     /**
      * ¿Í»§Ãû³Æ
     */
     private String userName;
     /**
      * Êշѵ¥Î»±àºÅ
     */
     private String chargingUnitId;
     /**
      * Éϼ¶Êշѵ¥Î»±àºÅ£¬¶à¸öÓÃ"||"°üס£¬Èç|123||456|,ÓÃÓÚËÑË÷
     */
     private String parentUnits;
     /**
      * Ô¿Í»§±àºÅ
     */
     private String oldUserId;
     /**
      * Óû§·ÖÀà
     */
     private String customerType;
     /**
      * Óû§×´Ì¬
     */
     private String customerStatus;
     /**
      * ÐÐÒµ·ÖÀà
     */
     private String category;
     /**
      * ÒµÎñÀà±ð
     */
     private String businessType;
     /**
      * ºÏͬÈÝÁ¿
     */
     private String contractCapacity;
     /**
      * ¸ßºÄÄÜÐÐÒµÀà±ð
     */
     private String highEnergySectors;
     /**
      * ¿ª»§ÈÕÆÚ
     */
     private Long openTimestamp;
     /**
      * Ïú»§ÈÕÆÚ
     */
     private Long closeTimestamp;
     /**
      * µ½ÆÚÈÕÆÚ
     */
     private Long maturityTimestamp;
     /**
      * Ë®·Ñ֪ͨ·½Ê½
     */
     private String notifyType;
     /**
      * Ë®·Ñ½áË㷽ʽ
     */
     private String settlementType;
     /**
      * Ʊ¾ÝÀàÐÍ
     */
     private String billType;
     /**
      * ͣˮ±êÖ¾
     */
     private String withoutWaterMark;
     /**
      * ת¹©±êÖ¾
     */
     private String turnForMark;
     /**
      * ³±í¶Î±àºÅ
     */
     private String meterSegmentNum;
     /**
      * ÒµÎñµØÖ·
     */
     private String busiAddress;
     /**
      * ¹©Ë®µãÃû³Æ
     */
     private String waterPointsName;
     /**
      * ¹©Ë®µãÀàÐÍ
     */
     private String waterPointsType;
     /**
      * ÔËÐÐ״̬
     */
     private String workStatus;
     /**
      * ¶¨¼Û²ßÂÔÀàÐÍ
     */
     private String pricStrategyType;
     /**
      * »ù±¾Ë®·Ñ¼ÆË㷽ʽ
     */
     private String basicWaterPriceCalc;
     /**
      * Ë®¼ÛÐÐÒµÀà±ð
     */
     private String waterPriceIndustry;
     /**
      * ÓÃË®ÐÔÖÊ
     */
     private String waterNature;
     /**
      * ÊÇ·ñÖ´Ðн×ÌݱêÖ¾
     */
     private String ladderFlag;
     /**
      * ¼ÛÄ¿Ä£°æid
     */
     private Long priceTemplateId;
     /**
      * ¹©Ë®µã±¸×¢
     */
     private String remark;
     /**
      * ´´½¨Ê±¼ä
     */
     private Long createTimestamp;

    // Constructors

    /** default constructor */
    public WaterCustomer() {
    }

	/** minimal constructor */
    public WaterCustomer(String customerId) {
        this.customerId = customerId;
    }

    /** full constructor */
    public WaterCustomer(String customerId, String customerName, String customNum, Long uid, String userId, String userName, String chargingUnitId, String parentUnits, String oldUserId, String customerType, String customerStatus, String category, String businessType, String contractCapacity, String highEnergySectors, Long openTimestamp, Long closeTimestamp, Long maturityTimestamp, String notifyType, String settlementType, String billType, String withoutWaterMark, String turnForMark, String meterSegmentNum, String busiAddress, String waterPointsName, String waterPointsType, String workStatus, String pricStrategyType, String basicWaterPriceCalc, String waterPriceIndustry, String waterNature, String ladderFlag, Long priceTemplateId, String remark, Long createTimestamp) {
        this.customerId = customerId;
        this.customerName = customerName;
        this.customNum = customNum;
        this.uid = uid;
        this.userId = userId;
        this.userName = userName;
        this.chargingUnitId = chargingUnitId;
        this.parentUnits = parentUnits;
        this.oldUserId = oldUserId;
        this.customerType = customerType;
        this.customerStatus = customerStatus;
        this.category = category;
        this.businessType = businessType;
        this.contractCapacity = contractCapacity;
        this.highEnergySectors = highEnergySectors;
        this.openTimestamp = openTimestamp;
        this.closeTimestamp = closeTimestamp;
        this.maturityTimestamp = maturityTimestamp;
        this.notifyType = notifyType;
        this.settlementType = settlementType;
        this.billType = billType;
        this.withoutWaterMark = withoutWaterMark;
        this.turnForMark = turnForMark;
        this.meterSegmentNum = meterSegmentNum;
        this.busiAddress = busiAddress;
        this.waterPointsName = waterPointsName;
        this.waterPointsType = waterPointsType;
        this.workStatus = workStatus;
        this.pricStrategyType = pricStrategyType;
        this.basicWaterPriceCalc = basicWaterPriceCalc;
        this.waterPriceIndustry = waterPriceIndustry;
        this.waterNature = waterNature;
        this.ladderFlag = ladderFlag;
        this.priceTemplateId = priceTemplateId;
        this.remark = remark;
        this.createTimestamp = createTimestamp;
    }

    // Property accessors
    /**
     *      * ÓÃË®Óû§±àºÅ
     */

    public String getCustomerId() {
        return this.customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }
    /**
     *      * ÓÃË®Óû§Ãû³Æ
     */

    public String getCustomerName() {
        return this.customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    /**
     *      * ×Ô¶¨Òå²éѯºÅ
     */

    public String getCustomNum() {
        return this.customNum;
    }

    public void setCustomNum(String customNum) {
        this.customNum = customNum;
    }
    /**
     *      * Óû§id
     */

    public Long getUid() {
        return this.uid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }
    /**
     *      * ¿Í»§±àºÅ
     */

    public String getUserId() {
        return this.userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
    /**
     *      * ¿Í»§Ãû³Æ
     */

    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    /**
     *      * Êշѵ¥Î»±àºÅ
     */

    public String getChargingUnitId() {
        return this.chargingUnitId;
    }

    public void setChargingUnitId(String chargingUnitId) {
        this.chargingUnitId = chargingUnitId;
    }
    /**
     *      * Éϼ¶Êշѵ¥Î»±àºÅ£¬¶à¸öÓÃ"||"°üס£¬Èç|123||456|,ÓÃÓÚËÑË÷
     */

    public String getParentUnits() {
        return this.parentUnits;
    }

    public void setParentUnits(String parentUnits) {
        this.parentUnits = parentUnits;
    }
    /**
     *      * Ô¿Í»§±àºÅ
     */

    public String getOldUserId() {
        return this.oldUserId;
    }

    public void setOldUserId(String oldUserId) {
        this.oldUserId = oldUserId;
    }
    /**
     *      * Óû§·ÖÀà
     */

    public String getCustomerType() {
        return this.customerType;
    }

    public void setCustomerType(String customerType) {
        this.customerType = customerType;
    }
    /**
     *      * Óû§×´Ì¬
     */

    public String getCustomerStatus() {
        return this.customerStatus;
    }

    public void setCustomerStatus(String customerStatus) {
        this.customerStatus = customerStatus;
    }
    /**
     *      * ÐÐÒµ·ÖÀà
     */

    public String getCategory() {
        return this.category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
    /**
     *      * ÒµÎñÀà±ð
     */

    public String getBusinessType() {
        return this.businessType;
    }

    public void setBusinessType(String businessType) {
        this.businessType = businessType;
    }
    /**
     *      * ºÏͬÈÝÁ¿
     */

    public String getContractCapacity() {
        return this.contractCapacity;
    }

    public void setContractCapacity(String contractCapacity) {
        this.contractCapacity = contractCapacity;
    }
    /**
     *      * ¸ßºÄÄÜÐÐÒµÀà±ð
     */

    public String getHighEnergySectors() {
        return this.highEnergySectors;
    }

    public void setHighEnergySectors(String highEnergySectors) {
        this.highEnergySectors = highEnergySectors;
    }
    /**
     *      * ¿ª»§ÈÕÆÚ
     */

    public Long getOpenTimestamp() {
        return this.openTimestamp;
    }

    public void setOpenTimestamp(Long openTimestamp) {
        this.openTimestamp = openTimestamp;
    }
    /**
     *      * Ïú»§ÈÕÆÚ
     */

    public Long getCloseTimestamp() {
        return this.closeTimestamp;
    }

    public void setCloseTimestamp(Long closeTimestamp) {
        this.closeTimestamp = closeTimestamp;
    }
    /**
     *      * µ½ÆÚÈÕÆÚ
     */

    public Long getMaturityTimestamp() {
        return this.maturityTimestamp;
    }

    public void setMaturityTimestamp(Long maturityTimestamp) {
        this.maturityTimestamp = maturityTimestamp;
    }
    /**
     *      * Ë®·Ñ֪ͨ·½Ê½
     */

    public String getNotifyType() {
        return this.notifyType;
    }

    public void setNotifyType(String notifyType) {
        this.notifyType = notifyType;
    }
    /**
     *      * Ë®·Ñ½áË㷽ʽ
     */

    public String getSettlementType() {
        return this.settlementType;
    }

    public void setSettlementType(String settlementType) {
        this.settlementType = settlementType;
    }
    /**
     *      * Ʊ¾ÝÀàÐÍ
     */

    public String getBillType() {
        return this.billType;
    }

    public void setBillType(String billType) {
        this.billType = billType;
    }
    /**
     *      * ͣˮ±êÖ¾
     */

    public String getWithoutWaterMark() {
        return this.withoutWaterMark;
    }

    public void setWithoutWaterMark(String withoutWaterMark) {
        this.withoutWaterMark = withoutWaterMark;
    }
    /**
     *      * ת¹©±êÖ¾
     */

    public String getTurnForMark() {
        return this.turnForMark;
    }

    public void setTurnForMark(String turnForMark) {
        this.turnForMark = turnForMark;
    }
    /**
     *      * ³±í¶Î±àºÅ
     */

    public String getMeterSegmentNum() {
        return this.meterSegmentNum;
    }

    public void setMeterSegmentNum(String meterSegmentNum) {
        this.meterSegmentNum = meterSegmentNum;
    }
    /**
     *      * ÒµÎñµØÖ·
     */

    public String getBusiAddress() {
        return this.busiAddress;
    }

    public void setBusiAddress(String busiAddress) {
        this.busiAddress = busiAddress;
    }
    /**
     *      * ¹©Ë®µãÃû³Æ
     */

    public String getWaterPointsName() {
        return this.waterPointsName;
    }

    public void setWaterPointsName(String waterPointsName) {
        this.waterPointsName = waterPointsName;
    }
    /**
     *      * ¹©Ë®µãÀàÐÍ
     */

    public String getWaterPointsType() {
        return this.waterPointsType;
    }

    public void setWaterPointsType(String waterPointsType) {
        this.waterPointsType = waterPointsType;
    }
    /**
     *      * ÔËÐÐ״̬
     */

    public String getWorkStatus() {
        return this.workStatus;
    }

    public void setWorkStatus(String workStatus) {
        this.workStatus = workStatus;
    }
    /**
     *      * ¶¨¼Û²ßÂÔÀàÐÍ
     */

    public String getPricStrategyType() {
        return this.pricStrategyType;
    }

    public void setPricStrategyType(String pricStrategyType) {
        this.pricStrategyType = pricStrategyType;
    }
    /**
     *      * »ù±¾Ë®·Ñ¼ÆË㷽ʽ
     */

    public String getBasicWaterPriceCalc() {
        return this.basicWaterPriceCalc;
    }

    public void setBasicWaterPriceCalc(String basicWaterPriceCalc) {
        this.basicWaterPriceCalc = basicWaterPriceCalc;
    }
    /**
     *      * Ë®¼ÛÐÐÒµÀà±ð
     */

    public String getWaterPriceIndustry() {
        return this.waterPriceIndustry;
    }

    public void setWaterPriceIndustry(String waterPriceIndustry) {
        this.waterPriceIndustry = waterPriceIndustry;
    }
    /**
     *      * ÓÃË®ÐÔÖÊ
     */

    public String getWaterNature() {
        return this.waterNature;
    }

    public void setWaterNature(String waterNature) {
        this.waterNature = waterNature;
    }
    /**
     *      * ÊÇ·ñÖ´Ðн×ÌݱêÖ¾
     */

    public String getLadderFlag() {
        return this.ladderFlag;
    }

    public void setLadderFlag(String ladderFlag) {
        this.ladderFlag = ladderFlag;
    }
    /**
     *      * ¼ÛÄ¿Ä£°æid
     */

    public Long getPriceTemplateId() {
        return this.priceTemplateId;
    }

    public void setPriceTemplateId(Long priceTemplateId) {
        this.priceTemplateId = priceTemplateId;
    }
    /**
     *      * ¹©Ë®µã±¸×¢
     */

    public String getRemark() {
        return this.remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
    /**
     *      * ´´½¨Ê±¼ä
     */

    public Long getCreateTimestamp() {
        return this.createTimestamp;
    }

    public void setCreateTimestamp(Long createTimestamp) {
        this.createTimestamp = createTimestamp;
    }

	public boolean equals(Object other) {
		if ( (this == other ) ) return true;
		if ( (other == null ) ) return false;
		if ( !(other instanceof WaterCustomer) ) return false;
		WaterCustomer castOther = ( WaterCustomer ) other;
		if( this.getCustomerId() == null || castOther.getCustomerId() == null){
			return false;
		}

		return ( (this.getCustomerId()==castOther.getCustomerId()) || ( this.getCustomerId()!=null && castOther.getCustomerId()!=null && this.getCustomerId().equals(castOther.getCustomerId()) ) );
	}

	public int hashCode() {
		java.util.Random random = new java.util.Random();
		int result = 0;
		result += result + (this.getCustomerId() == null ? random.nextInt(Integer.MAX_VALUE) : this.getCustomerId().hashCode());
		return result;
	}

}


text:
#include <iostream>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "../gen-cpp/Calculator.h"

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace tutorial;
using namespace shared;

int main() {
  boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9090));
  boost::shared_ptr<TTransport> transport(new  TFramedTransport(socket));
  boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
  CalculatorClient client(protocol);

  try {
    transport->open();

    client.ping();
    cout << "ping()" << endl;

    cout << "1 + 1 = " << client.add(1, 1) << endl;

    Work work;
    work.op = Operation::DIVIDE;
    work.num1 = 1;
    work.num2 = 0;

    try {
      client.calculate(1, work);
      cout << "Whoa? We can divide by zero!" << endl;
    } catch (InvalidOperation& io) {
      cout << "InvalidOperation: " << io.why << endl;
      // or using generated operator<<: cout << io << endl;
      // or by using std::exception native method what(): cout << io.what() << endl;
    }

    work.op = Operation::SUBTRACT;
    work.num1 = 15;
    work.num2 = 10;
    int32_t diff = client.calculate(1, work);
    cout << "15 - 10 = " << diff << endl;

    // Note that C++ uses return by reference for complex types to avoid
    // costly copy construction
    SharedStruct ss;
    client.getStruct(ss, 1);
    cout << "Received log: " << ss << endl;

    transport->close();
  } catch (TException& tx) {
    cout << "ERROR: " << tx.what() << endl;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.maven.model.plugin;

import javax.inject.Named;
import javax.inject.Singleton;

import org.apache.maven.model.Model;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.model.ReportSet;
import org.apache.maven.model.Reporting;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelProblemCollector;
import org.codehaus.plexus.util.xml.Xpp3Dom;

/**
 * Handles expansion of general report plugin configuration into individual report sets.
 *
 * @author Benjamin Bentmann
 */
@Named
@Singleton
public class DefaultReportConfigurationExpander
        implements ReportConfigurationExpander
{

    @Override
    public void expandPluginConfiguration( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
    {
        Reporting reporting = model.getReporting();

        if ( reporting != null )
        {
            for ( ReportPlugin reportPlugin : reporting.getPlugins() )
            {
                Xpp3Dom parentDom = (Xpp3Dom) reportPlugin.getConfiguration();

                if ( parentDom != null )
                {
                    for ( ReportSet execution : reportPlugin.getReportSets() )
                    {
                        Xpp3Dom childDom = (Xpp3Dom) execution.getConfiguration();
                        childDom = Xpp3Dom.mergeXpp3Dom( childDom, new Xpp3Dom( parentDom ) );
                        execution.setConfiguration( childDom );
                    }
                }
            }
        }
    }

}


text:
package com.zuora.interview.visitsimulator;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Random;

/**
 * Created by liqingsong on 29/05/2017.
 */
public class SimulatorUtil {
    public static final String[] PATH_DICTIONARY = {"/", "subscribers", "filter", "catalog",
            "edit", "delete", "update", "export", "pay", "invoice", "rate", "help", "search",
            "product", "bill", "charge", "provider", "account", "seller", "dun", "provision"};

    public static final String USER_PREFIX = "USER";
    public static final String USER_PATH_SEPERATOR = ":";
    public static final String dir = System.getProperty ("user.dir");

    /**
     * Create visit log mock file.
     *
     * @param visitAmount
     * @param userNum
     * @return
     */
    public static Path createVisitLogFile(int visitAmount, int userNum) {
        Path file = FileSystems.getDefault ( ).getPath (dir,
                "visit.log");
        Charset charset = Charset.forName ("UTF-8");
        StringBuilder line = new StringBuilder ( );
        Random randomUserNo = new Random ( );
        Random randomPathNo = new Random ( );
        try (BufferedWriter writer = Files.newBufferedWriter (file, charset)) {
            for (int n = 0; n < visitAmount; n++) {
                int randomNum = randomUserNo.nextInt (userNum);
                line.append (USER_PREFIX).append (randomNum).append (USER_PATH_SEPERATOR).append
                        (PATH_DICTIONARY[randomPathNo.nextInt (PATH_DICTIONARY.length)]);
                writer.write (line.toString ( ), 0, line.length ( ));
                writer.newLine ( );
                line.delete (0, line.length ( ));
            }
            return file;
        } catch (IOException x) {
            System.err.format ("IOException: %s%n", x);
        }
        return null;
    }

    /**
     * Get (user, path) array
     *
     * @param visitAmount visit total paths number
     * @param userNum     visit user count
     * @return
     */
    public static String[][] getVistiData(int visitAmount, int userNum) {
        Path visitLogFile = createVisitLogFile (visitAmount, userNum);
        Charset charset = Charset.forName ("UTF-8");
        String[][] data = new String[visitAmount][2];

        try (BufferedReader reader = Files.newBufferedReader (visitLogFile, charset)) {
            String line;
            int i = 0;
            String[] pair;
            while ((line = reader.readLine ( )) != null) {
                pair = line.split (USER_PATH_SEPERATOR);
                data[i][0] = pair[0];
                data[i][1] = pair[1];
                i++;
            }
        } catch (IOException e) {
            e.printStackTrace ( );
        }
        return data;
    }

}


text:
namespace ui {

class DrmDevice;

// Wrapper for a DRM allocated buffer. Keeps track of the native properties of
// the buffer and wraps the pixel memory into a SkSurface which can be used to
// draw into using Skia.
class DrmBuffer : public ScanoutBuffer {
 public:
  DrmBuffer(const scoped_refptr<DrmDevice>& drm);

  // Allocates the backing pixels and wraps them in |surface_|. |info| is used
  // to describe the buffer characteristics (size, color format).
  // |should_register_framebuffer| is used to distinguish the buffers that are
  // used for modesetting.
  bool Initialize(const SkImageInfo& info, bool should_register_framebuffer);

  SkCanvas* GetCanvas() const;

  // ScanoutBuffer:
  uint32_t GetFramebufferId() const override;
  uint32_t GetFramebufferPixelFormat() const override;
  uint32_t GetHandle() const override;
  gfx::Size GetSize() const override;
  bool RequiresGlFinish() const override;

 protected:
  ~DrmBuffer() override;

  scoped_refptr<DrmDevice> drm_;

  // Length of a row of pixels.
  uint32_t stride_ = 0;

  // Buffer handle used by the DRM allocator.
  uint32_t handle_ = 0;

  // Base address for memory mapping.
  void* mmap_base_ = 0;

  // Size for memory mapping.
  size_t mmap_size_ = 0;

  // Buffer ID used by the DRM modesettings API. This is set when the buffer is
  // registered with the CRTC.
  uint32_t framebuffer_ = 0;

  // Pixel format of |framebuffer_|
  uint32_t fb_pixel_format_ = 0;

  // Wrapper around the native pixel memory.
  skia::RefPtr<SkSurface> surface_;

  DISALLOW_COPY_AND_ASSIGN(DrmBuffer);
};

}  // namespace ui

#endif  // UI_OZONE_PLATFORM_DRM_GPU_DRM_BUFFER_H_


text:
<Addin namespace="FSpot"
	id="PixelateEditor"
	version="0.9"
	compatVersion="0.9"
	name="PixelateEditor"
	description="Pixelates an area of the image."
	author="Brian J. Murrell"
	url="http://f-spot.org/Extensions"
	category="Editors"
	defaultEnabled="false">
	<Dependencies>
		<Addin id="Core" version="0.9"/>
	</Dependencies>
	<Extension path = "/FSpot/Editors">
		<Editor EditorType = "FSpot.Addins.Editors.PixelateEditor"/>
	</Extension>
</Addin>


text:
package beginner;

import com.sandwich.koan.Koan;

import static com.sandwich.util.Assert.fail;

public class AboutKoans {

	@Koan
	public void findAboutKoansFile(){
	}

	@Koan
	public void definitionOfKoanCompletion(){
		boolean koanIsComplete = true;
		if(koanIsComplete){

		}
	}

}


text:
"""
Tests for cinder.api.contrib.quotas.py
"""

import mock

from lxml import etree

import uuid
import webob.exc

from cinder.api.contrib import quotas
from cinder import context
from cinder import db
from cinder import test
from cinder.tests.unit import test_db_api

from oslo_config import cfg

CONF = cfg.CONF

def make_body(root=True, gigabytes=1000, snapshots=10,
              volumes=10, backups=10, backup_gigabytes=1000,
              tenant_id='foo', per_volume_gigabytes=-1):
    resources = {'gigabytes': gigabytes,
                 'snapshots': snapshots,
                 'volumes': volumes,
                 'backups': backups,
                 'backup_gigabytes': backup_gigabytes,
                 'per_volume_gigabytes': per_volume_gigabytes, }
    # need to consider preexisting volume types as well
    volume_types = db.volume_type_get_all(context.get_admin_context())
    for volume_type in volume_types:
        resources['gigabytes_' + volume_type] = -1
        resources['snapshots_' + volume_type] = -1
        resources['volumes_' + volume_type] = -1

    if tenant_id:
        resources['id'] = tenant_id
    if root:
        result = {'quota_set': resources}
    else:
        result = resources
    return result

def make_subproject_body(root=True, gigabytes=0, snapshots=0,
                         volumes=0, backups=0, backup_gigabytes=0,
                         tenant_id='foo', per_volume_gigabytes=0):
    return make_body(root=root, gigabytes=gigabytes, snapshots=snapshots,
                     volumes=volumes, backups=backups,
                     backup_gigabytes=backup_gigabytes, tenant_id=tenant_id,
                     per_volume_gigabytes=per_volume_gigabytes)

class QuotaSetsControllerTest(test.TestCase):

    class FakeProject(object):

        def __init__(self, id='foo', parent_id=None):
            self.id = id
            self.parent_id = parent_id
            self.subtree = None

    def setUp(self):
        super(QuotaSetsControllerTest, self).setUp()
        self.controller = quotas.QuotaSetsController()

        self.req = self.mox.CreateMockAnything()
        self.req.environ = {'cinder.context': context.get_admin_context()}
        self.req.environ['cinder.context'].is_admin = True
        self.req.environ['cinder.context'].auth_token = uuid.uuid4().hex
        self.req.environ['cinder.context'].project_id = 'foo'

        self._create_project_hierarchy()
        self.auth_url = CONF.keymgr.encryption_auth_url

    def _create_project_hierarchy(self):
        """Sets an environment used for nested quotas tests.

        Create a project hierarchy such as follows:
        +-----------+
        |           |
        |     A     |
        |    / \    |
        |   B   C   |
        |  /        |
        | D         |
        +-----------+
        """
        self.A = self.FakeProject(id=uuid.uuid4().hex, parent_id=None)
        self.B = self.FakeProject(id=uuid.uuid4().hex, parent_id=self.A.id)
        self.C = self.FakeProject(id=uuid.uuid4().hex, parent_id=self.A.id)
        self.D = self.FakeProject(id=uuid.uuid4().hex, parent_id=self.B.id)

        # update projects subtrees
        self.B.subtree = {self.D.id: self.D.subtree}
        self.A.subtree = {self.B.id: self.B.subtree, self.C.id: self.C.subtree}

        # project_by_id attribute is used to recover a project based on its id.
        self.project_by_id = {self.A.id: self.A, self.B.id: self.B,
                              self.C.id: self.C, self.D.id: self.D}

    def _get_project(self, context, id, subtree_as_ids=False):
        return self.project_by_id.get(id, self.FakeProject())

    @mock.patch('keystoneclient.v3.client.Client')
    def test_keystone_client_instantiation(self, ksclient_class):
        context = self.req.environ['cinder.context']
        self.controller._get_project(context, context.project_id)
        ksclient_class.assert_called_once_with(auth_url=self.auth_url,
                                               token=context.auth_token,
                                               project_id=context.project_id)

    @mock.patch('keystoneclient.v3.client.Client')
    def test_get_project(self, ksclient_class):
        context = self.req.environ['cinder.context']
        keystoneclient = ksclient_class.return_value
        self.controller._get_project(context, context.project_id)
        keystoneclient.projects.get.assert_called_once_with(
            context.project_id, subtree_as_ids=False)

    def test_defaults(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        result = self.controller.defaults(self.req, 'foo')
        self.assertDictMatch(make_body(), result)

    def test_subproject_defaults(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        context = self.req.environ['cinder.context']
        context.project_id = self.B.id
        result = self.controller.defaults(self.req, self.B.id)
        expected = make_subproject_body(tenant_id=self.B.id)
        self.assertDictMatch(expected, result)

    def test_show(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        result = self.controller.show(self.req, 'foo')
        self.assertDictMatch(make_body(), result)

    def test_subproject_show(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].project_id = self.A.id
        result = self.controller.show(self.req, self.B.id)
        expected = make_subproject_body(tenant_id=self.B.id)
        self.assertDictMatch(expected, result)

    def test_subproject_show_in_hierarchy(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        # An user scoped to a root project in an hierarchy can see its children
        # quotas.
        self.req.environ['cinder.context'].project_id = self.A.id
        result = self.controller.show(self.req, self.D.id)
        expected = make_subproject_body(tenant_id=self.D.id)
        self.assertDictMatch(result, expected)
        # An user scoped to a parent project can see its immediate children
        # quotas.
        self.req.environ['cinder.context'].project_id = self.B.id
        result = self.controller.show(self.req, self.D.id)
        expected = make_subproject_body(tenant_id=self.D.id)
        self.assertDictMatch(result, expected)

    def test_subproject_show_target_project_equals_to_context_project(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].project_id = self.B.id
        result = self.controller.show(self.req, self.B.id)
        expected = make_subproject_body(tenant_id=self.B.id)
        self.assertDictMatch(result, expected)

    def test_show_not_authorized(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].is_admin = False
        self.req.environ['cinder.context'].user_id = 'bad_user'
        self.req.environ['cinder.context'].project_id = 'bad_project'
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.show,
                          self.req, 'foo')

    def test_subproject_show_not_authorized(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].project_id = self.B.id
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.show,
                          self.req, self.C.id)
        self.req.environ['cinder.context'].project_id = self.B.id
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.show,
                          self.req, self.A.id)

    def test_update(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        result = self.controller.update(self.req, 'foo', body)
        self.assertDictMatch(body, result)

        body = make_body(gigabytes=db.MAX_INT, tenant_id=None)
        result = self.controller.update(self.req, 'foo', body)
        self.assertDictMatch(body, result)

    def test_update_subproject(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        # Update the project A quota.
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        result = self.controller.update(self.req, self.A.id, body)
        self.assertDictMatch(result, body)
        # Update the quota of B to be equal to its parent quota
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        result = self.controller.update(self.req, self.B.id, body)
        self.assertDictMatch(result, body)
        # Try to update the quota of C, it will not be allowed, since the
        # project A doesn't have free quota available.
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, self.C.id, body)
        # Successfully update the quota of D.
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=1000, snapshots=7,
                         volumes=3, backups=3, tenant_id=None)
        result = self.controller.update(self.req, self.D.id, body)
        self.assertDictMatch(result, body)
        # An admin of B can also update the quota of D, since D is its an
        # immediate child.
        self.req.environ['cinder.context'].project_id = self.B.id
        body = make_body(gigabytes=1500, snapshots=10,
                         volumes=4, backups=4, tenant_id=None)
        result = self.controller.update(self.req, self.D.id, body)

    def test_update_subproject_not_in_hierarchy(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project

        # Create another project hierarchy
        E = self.FakeProject(id=uuid.uuid4().hex, parent_id=None)
        F = self.FakeProject(id=uuid.uuid4().hex, parent_id=E.id)
        E.subtree = {F.id: F.subtree}
        self.project_by_id[E.id] = E
        self.project_by_id[F.id] = F

        # Update the project A quota.
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        result = self.controller.update(self.req, self.A.id, body)
        self.assertDictMatch(result, body)
        # Try to update the quota of F, it will not be allowed, since the
        # project E doesn't belongs to the project hierarchy of A.
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.update,
                          self.req, F.id, body)

    def test_update_subproject_with_not_root_context_project(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        # Update the project A quota.
        self.req.environ['cinder.context'].project_id = self.A.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        result = self.controller.update(self.req, self.A.id, body)
        self.assertDictMatch(result, body)
        # Try to update the quota of B, it will not be allowed, since the
        # project in the context (B) is not a root project.
        self.req.environ['cinder.context'].project_id = self.B.id
        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5, tenant_id=None)
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.update,
                          self.req, self.B.id, body)

    @mock.patch(
        'cinder.api.openstack.wsgi.Controller.validate_string_length')
    @mock.patch(
        'cinder.api.openstack.wsgi.Controller.validate_integer')
    def test_update_limit(self, mock_validate_integer, mock_validate):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        mock_validate_integer.return_value = 10

        body = {'quota_set': {'volumes': 10}}
        result = self.controller.update(self.req, 'foo', body)

        self.assertEqual(10, result['quota_set']['volumes'])
        self.assertTrue(mock_validate.called)
        self.assertTrue(mock_validate_integer.called)

    def test_update_wrong_key(self):
        body = {'quota_set': {'bad': 'bad'}}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def test_update_invalid_value_key_value(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        body = {'quota_set': {'gigabytes': "should_be_int"}}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def test_update_invalid_type_key_value(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        body = {'quota_set': {'gigabytes': None}}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def test_update_multi_value_with_bad_data(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        orig_quota = self.controller.show(self.req, 'foo')
        body = make_body(gigabytes=2000, snapshots=15, volumes="should_be_int",
                         backups=5, tenant_id=None)
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)
        # Verify that quota values are not updated in db
        new_quota = self.controller.show(self.req, 'foo')
        self.assertDictMatch(orig_quota, new_quota)

    def test_update_bad_quota_limit(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        body = {'quota_set': {'gigabytes': -1000}}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)
        body = {'quota_set': {'gigabytes': db.MAX_INT + 1}}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def test_update_no_admin(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].is_admin = False
        self.req.environ['cinder.context'].project_id = 'foo'
        self.req.environ['cinder.context'].user_id = 'foo_user'
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.update,
                          self.req, 'foo', make_body(tenant_id=None))

    def test_update_without_quota_set_field(self):
        body = {'fake_quota_set': {'gigabytes': 100}}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def test_update_empty_body(self):
        body = {}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def _commit_quota_reservation(self):
        # Create simple quota and quota usage.
        ctxt = context.get_admin_context()
        res = test_db_api._quota_reserve(ctxt, 'foo')
        db.reservation_commit(ctxt, res, 'foo')
        expected = {'project_id': 'foo',
                    'volumes': {'reserved': 0, 'in_use': 1},
                    'gigabytes': {'reserved': 0, 'in_use': 2},
                    }
        self.assertEqual(expected,
                         db.quota_usage_get_all_by_project(ctxt, 'foo'))

    def test_update_lower_than_existing_resources_when_skip_false(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self._commit_quota_reservation()
        body = {'quota_set': {'volumes': 0},
                'skip_validation': 'false'}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)
        body = {'quota_set': {'gigabytes': 1},
                'skip_validation': 'false'}
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          self.req, 'foo', body)

    def test_update_lower_than_existing_resources_when_skip_true(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self._commit_quota_reservation()
        body = {'quota_set': {'volumes': 0},
                'skip_validation': 'true'}
        result = self.controller.update(self.req, 'foo', body)
        self.assertEqual(body['quota_set']['volumes'],
                         result['quota_set']['volumes'])

    def test_update_lower_than_existing_resources_without_skip_argument(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self._commit_quota_reservation()
        body = {'quota_set': {'volumes': 0}}
        result = self.controller.update(self.req, 'foo', body)
        self.assertEqual(body['quota_set']['volumes'],
                         result['quota_set']['volumes'])

    def test_delete(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        result_show = self.controller.show(self.req, 'foo')
        self.assertDictMatch(result_show, make_body())

        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5,
                         backup_gigabytes=1000, tenant_id=None)
        result_update = self.controller.update(self.req, 'foo', body)
        self.assertDictMatch(result_update, body)

        self.controller.delete(self.req, 'foo')

        result_show_after = self.controller.show(self.req, 'foo')
        self.assertDictMatch(result_show, result_show_after)

    def test_subproject_delete(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].project_id = self.A.id

        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5,
                         backup_gigabytes=1000, tenant_id=None)
        result_update = self.controller.update(self.req, self.A.id, body)
        self.assertDictMatch(result_update, body)

        # Set usage param to True in order to see get allocated values.
        self.req.params = {'usage': 'True'}
        result_show = self.controller.show(self.req, self.A.id)

        result_update = self.controller.update(self.req, self.B.id, body)
        self.assertDictMatch(result_update, body)

        self.controller.delete(self.req, self.B.id)

        result_show_after = self.controller.show(self.req, self.A.id)
        self.assertDictMatch(result_show, result_show_after)

    def test_delete_with_allocated_quota_different_from_zero(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].project_id = self.A.id

        body = make_body(gigabytes=2000, snapshots=15,
                         volumes=5, backups=5,
                         backup_gigabytes=1000, tenant_id=None)
        result_update = self.controller.update(self.req, self.A.id, body)
        self.assertDictMatch(result_update, body)

        # Set usage param to True in order to see get allocated values.
        self.req.params = {'usage': 'True'}
        result_show = self.controller.show(self.req, self.A.id)

        result_update = self.controller.update(self.req, self.B.id, body)
        self.assertDictMatch(result_update, body)

        self.controller.delete(self.req, self.B.id)

        result_show_after = self.controller.show(self.req, self.A.id)
        self.assertDictMatch(result_show, result_show_after)

    def test_delete_no_admin(self):
        self.controller._get_project = mock.Mock()
        self.controller._get_project.side_effect = self._get_project
        self.req.environ['cinder.context'].is_admin = False
        self.assertRaises(webob.exc.HTTPForbidden, self.controller.delete,
                          self.req, 'foo')

class QuotaSerializerTest(test.TestCase):

    def setUp(self):
        super(QuotaSerializerTest, self).setUp()
        self.req = self.mox.CreateMockAnything()
        self.req.environ = {'cinder.context': context.get_admin_context()}

    def test_update_serializer(self):
        serializer = quotas.QuotaTemplate()
        quota_set = make_body(root=False)
        text = serializer.serialize({'quota_set': quota_set})
        tree = etree.fromstring(text)
        self.assertEqual('quota_set', tree.tag)
        self.assertEqual(quota_set['id'], tree.get('id'))
        body = make_body(root=False, tenant_id=None)
        for node in tree:
            self.assertIn(node.tag, body)
            self.assertEqual(str(body[node.tag]), node.text)


text:
<?php

namespace Quartet\Bundle\KakarotBundle\Form\Type;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    private $class;

    /**
     * @param string $class The User class name
     */
    public function __construct($class)
    {
        $this->class = $class;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email', array('label' => 'メールアドレス', 'translation_domain' => 'FOSUserBundle'))
            ->add('username', null, array('label' => 'ログイン名', 'translation_domain' => 'FOSUserBundle'))
            ->add('name', null, array('label' => '氏名', 'required' => true))
            ->add('role', 'entity', array('label' => '権限', 'class' => 'QuartetKakarotBundle:Role', 'query_builder' => function(EntityRepository $er){
                return $er->createQueryBuilder('r');
            }))
            ->add('division', 'entity', array('label' => '部署', 'class' => 'QuartetKakarotBundle:Division', 'query_builder' => function(EntityRepository $er){
                return $er->createQueryBuilder('d');
            }))
            ->add('position', 'entity', array('label' => '役職', 'class' => 'QuartetKakarotBundle:Position', 'query_builder' => function(EntityRepository $er){
                return $er->createQueryBuilder('p');
            }))
            ->add('parent', 'entity', array('label' => '上長', 'required' => false, 'class' => 'QuartetKakarotBundle:User', 'query_builder' => function(EntityRepository $er){
                return $er->createQueryBuilder('p');
            }))
            ->add('plainPassword', 'repeated', array(
                'label' => 'パスワード',
                'type' => 'password',
                'options' => array('translation_domain' => 'FOSUserBundle'),
                'first_options' => array('label' => 'パスワード'),
                'second_options' => array('label' => 'パスワード再入力'),
                'invalid_message' => 'パスワードが一致しません。',
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => $this->class,
            'intention'  => 'registration',
            'label'      => ''
        ));
    }

    public function getName()
    {
        return 'fos_user_registration2';
    }
}


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>sID Social Identity</title>

    <!-- Bootstrap -->
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" integrity="sha384-aUGj/X2zp5rLCbBxumKTCw2Z50WgIr1vs/PFN4praOTvYXWlVyh2UtNUU0KAUhAX" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

    <!-- Angular JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>

    <!-- Angular UI router -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>

    <!-- icon themes -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">

    <script src="/javascripts/angularApp.js" charset="utf-8"></script>
    <script src='/javascripts/controllers/controllers.js'></script>

    <!-- Facebook like theme for home page -->
    <script src='/javascripts/facebook.js'></script>
    <link href="/stylesheets/facebook.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body ng-app="app">
    <ui-view></ui-view>
  </body>
</html>


text:
title: About
---

Hello.

The main purpose of this is for me documenting some of what I do and experiment with, so I might refer to those notes at some point in the future. If anything is of any use to anybody else, all the better.

Enjoy!


text:
package T2;

/**
 * Created by Administrator on 2016/3/15.
 */
public class Test {
    public static void main(String[] args) {
        A a=new A();
        a.say();
    }
}


text:
EntervoteDialog::EntervoteDialog(std::string& nation, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EntervoteDialog), model(0)
{
    ui->setupUi(this);

    GUIUtil::setupAddressWidget(ui->addressEdit, this);

    setWindowTitle(tr("Enter Vote Amount for Empire"));

    std::string voteStr = "Vote for " + nation;
    ui->labelEdit->setText(QString::fromStdString(voteStr));

    ui->labelEdit->setEnabled(false);
    ui->addressEdit->setEnabled(false);
    ui->voteAmountEdit->setEnabled(true);
}

EntervoteDialog::~EntervoteDialog()
{
    delete ui;
}

void EntervoteDialog::setModel(WalletModel *model)
{
    this->model = model;
}

bool EntervoteDialog::submitVote()
{
    if(!model)
        return false;

    nation = ui->labelEdit->text();
    address = ui->addressEdit->text();
    amount = ui->voteAmountEdit->text();

    return !address.isEmpty() && !amount.isEmpty();
}

void EntervoteDialog::accept()
{
    if (!model)
        return;

    if (submitVote())
        QDialog::accept();
}

QString EntervoteDialog::getAddress() const
{
    return address;
}

void EntervoteDialog::setAddress(const QString &address)
{
    this->address = address;
    ui->addressEdit->setText(address);
}

QString EntervoteDialog::getNation() const
{
    return nation;
}

void EntervoteDialog::setNation(const QString &nation)
{
    this->nation = nation;
    ui->labelEdit->setText(nation);
}

QString EntervoteDialog::getAmount() const
{
    return amount;
}

void EntervoteDialog::setAmount(const QString &amount)
{
    this->amount = amount;
    ui->voteAmountEdit->setText(amount);
}


text:
const conf = require("./build/config");

module.exports = function (config) {
	config.set({
		basePath: "./",
		frameworks: ["systemjs", "jasmine"],

		systemjs: {
			configFile: "system.config.js",
			config: {
				paths: {
					"*": "*",
					"src/*": "src/*",
					"typescript": "node_modules/typescript/lib/typescript.js",
					"systemjs": "node_modules/systemjs/dist/system.js",
					"system-polyfills": "node_modules/systemjs/dist/system-polyfills.js",
					"es6-module-loader": "node_modules/es6-module-loader/dist/es6-module-loader.js"
				},
				packages: {
					"src": {
						defaultExtension: "ts"
					}
				},
				transpiler: "typescript"
			},
			serveFiles: [
				conf.src.ts,
				"jspm_packages/**/*.js"
			]
		},
		files: [
			conf.src.testTs,
			"src/*.spec.ts",

			// { pattern: "node_modules/lodash/**/*.js", included: false, watched: false, served: true },
		],
		exclude: [],
		preprocessors: {},
		reporters: ["mocha"], // note: gulp using config from config.js instead
		port: 9876,
		colors: true,
		logLevel: config.LOG_INFO,
		autoWatch: true,
		browsers: ["Chrome"], // note: gulp using config from config.js instead
		singleRun: false
	});
};


text:
"""Common image processing operations."""
from typing import Tuple

from absl import logging
import attr
import numpy as np
from reservoir_nn.typing import types
from reservoir_nn.utils import preprocessing
import tensorflow as tf
from tensorflow_addons import image as tfa_image

@attr.s(auto_attribs=True)
class TileImage(preprocessing.TensorTransform):
  """Creates overlapping tiles from an image.

  input_ must be rank 2 `(row, col)`.
  output is rank 3 `(tiles, row, col)` The tiles will be ordered row by row.
    That is, for patches

    A B C
    D E F

    the output will be in the order of (A, B, C, D, E, F).

  Note, padding='VALID' is used so only patches which are fully contained in
  the input image are included.

  Attributes:
    sizes: (size_rows, size_cols) The size of the extracted patches.
    strides: (stride_rows, stride_cols) How far the centers of two consecutive
      patches are in the images. Needs to be > 0.
    rates: This (inversed) rate to sample the input pixels, specifying how far
      two consecutive patch samples are in the input. For example (1, 1) samples
      every pixel. (2, 2) samples every two pixels.
    padding: Whether to use padding='VALID' (default) or 'SAME'. If
      padding='VALID' is used, only patches which are fully contained in the
      input image are included. If padding='SAME' is used, the entire input
      image is included. All patches whose starting point is within the input
      image are included, and all pixels outside the image are set to 0.
  """
  sizes: Tuple[int, int]
  strides: Tuple[int, int]
  rates: Tuple[int, int] = (1, 1)
  padding: str = 'VALID'

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    tf.debugging.assert_rank(input_, 2,
                             'Input to TileImage must be 2D tensors.')
    output = tf.image.extract_patches(
        input_[tf.newaxis, :, :, tf.newaxis],  # Expand to a 4D tensor
        sizes=(1, self.sizes[0], self.sizes[1], 1),
        strides=(1, self.strides[0], self.strides[1], 1),
        rates=(1, self.rates[0], self.rates[1], 1),
        padding=self.padding,
    )
    # Output is (num_img_in_row, num_img_in_col, flatten_img)
    # Reshape to (tiles, row, col)
    output = tf.reshape(output, (-1, self.sizes[0], self.sizes[1]))

    return output

@attr.s(auto_attribs=True)
class TileImage3D(preprocessing.TensorTransform):
  """Creates overlapping tiles from an image.

  input_ must be rank 3 `(row, col, channel)`.
  output is rank 4 `(tiles, row, col, channel)` The tiles will be ordered row by
  row.
    That is, for patches

    A B C
    D E F

    the output will be in the order of (A, B, C, D, E, F).

  Note, padding='VALID' is used so only patches which are fully contained in
  the input image are included.

  Attributes:
    sizes: (size_rows, size_cols, channels) The size of the extracted patches.
    strides: (stride_rows, stride_cols) How far the centers of two consecutive
      patches are in the images. Needs to be > 0.
    rates: This (inversed) rate to sample the input pixels, specifying how far
      two consecutive patch samples are in the input. For example (1, 1) samples
      every pixel. (2, 2) samples every two pixels.
  """
  sizes: Tuple[int, int, int]
  strides: Tuple[int, int]
  rates: Tuple[int, int] = (1, 1)

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    tf.debugging.assert_rank(input_, 3,
                             'Input to TileImage3D must be 3D tensors.')
    output = tf.image.extract_patches(
        input_[tf.newaxis, :, :, :],  # Expand to a 4D tensor
        sizes=(1, self.sizes[0], self.sizes[1], 1),
        strides=(1, self.strides[0], self.strides[1], 1),
        rates=(1, self.rates[0], self.rates[1], 1),
        padding='VALID',
    )

    # Output is (num_img_in_row, num_img_in_col, flatten_img)
    # Reshape to (tiles, row, col, chan)
    output = tf.reshape(output,
                        (-1, self.sizes[0], self.sizes[1], self.sizes[2]))

    return output

@attr.s(auto_attribs=True)
class TileNoOverlap(preprocessing.TensorTransform):
  """Tiles an image without overlapping.

  Attributes:
    input_shape: The shape of the input tensor.
    tile_shape: The (height, width) of the tiling window.
  """
  input_shape: Tuple[int, int]
  tile_shape: Tuple[int, int]

  def call(self, input_: tf.Tensor) -> tf.Tensor:

    # Check shape
    input_ = tf.ensure_shape(input_, (*self.input_shape, None))

    row_max = self.input_shape[0] // self.tile_shape[0] * self.tile_shape[0]
    col_max = self.input_shape[1] // self.tile_shape[1] * self.tile_shape[1]
    out_stack = []

    for row in range(0, row_max, self.tile_shape[0]):

      for col in range(0, col_max, self.tile_shape[1]):
        # get a tile:
        tile = input_[row:row + self.tile_shape[0],
                      col:col + self.tile_shape[1], :]
        out_stack.append(tile)

    return tf.stack(out_stack, axis=0)

@attr.s(auto_attribs=False)
class MixRGBChannels(preprocessing.TensorTransform):
  """Mixes the RGB channels of an image.

  input shape = [row, col, 3]
  output shape = [row, col]

  Attributes:
    red: Contribution from the red channel.
    green: Contribution from the green channel.
    blue: Contribution from the blue channel.
  """
  red = attr.ib(default=0, type=float)
  green = attr.ib(default=0, type=float)
  blue = attr.ib(default=0, type=float)
  _scale_factors = attr.ib(init=False, repr=False)

  def __attrs_post_init__(self):
    self._scale_factors = tf.reshape(
        tf.constant([self.red, self.green, self.blue], dtype=tf.float32),
        (1, 1, 3))

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    scaled = input_ * self._scale_factors
    return tf.reduce_sum(scaled, axis=-1)

@attr.s(auto_attribs=False)
class SelectChannels(preprocessing.TensorTransform):
  """Selects channels of an image.

  input shape = [row, col, 3]
  output shape = [row, col, num_channels]

  Attributes:
    red: Whether to select the red channel.
    green: Whether to select the green channel.
    blue: Whether to select the blue channel.
  """
  red = attr.ib(default=False, type=bool)
  green = attr.ib(default=False, type=bool)
  blue = attr.ib(default=False, type=bool)

  def __attrs_post_init__(self):
    channels = []
    if self.red:
      channels.append(0)
    if self.green:
      channels.append(1)
    if self.blue:
      channels.append(2)
    if not channels:
      raise ValueError(f'Expect at least one channel, but received: '
                       f'red={self.red}, green={self.green}, blue={self.blue}')
    self._channels = channels

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    return tf.gather(input_, self._channels, axis=-1)

def tile_image(image: np.ndarray, tile_size: int = 30) -> np.ndarray:
  """Deprecated.

  Creates overlapping tiles from an image.

  Please use `TileImage()` instead.

  The tiles will overlap each other by half of their size, to make sure that
  no "edges" of objects in the original image ever end up only on the edge of
  a tile.

  Args:
    image: 2D numpy array - the image to tile.
    tile_size: the desired tile size.

  Returns:
    out_stack: a stacked np.array with dims (num_tiles, tile_size, tile_size).
  """
  logging.warning('`tile_image` is deprecated. Please use TileImage() instead.')
  sizes = (tile_size, tile_size)
  strides = (tile_size // 2, tile_size // 2)

  return TileImage(sizes, strides)(image).numpy()

def image_to_tiles(image: np.ndarray,
                   tile_size: int,
                   strides: Tuple[int, int],
                   padding=True) -> np.ndarray:
  """Creates overlapping tiles from an image.

  The tiles are created by sliding a window of (tile_size, tile_size) along
  the height and width of the image with stride as the sliding step size.

  Args:
    image: 2D numpy array - the image to tile.
    tile_size: the size of one side of the square tile.
    strides: tuple of step sizes of moving the tiling window along the image's
      height and width, respectively.
    padding: boolean, if True, the image is expanded and padded with zeros on
      the right and bottom edges, so that all tiles are fully inside the image.

  Returns:
    A stacked np.array with shape (num_tiles, tile_size, tile_size).

  Raises:
    ValueError: if tile_size is larger than the smaller dimension of the image.
  """
  height, width = image.shape

  if tile_size > min(height, width):
    raise ValueError('tile_size = {} exceeds the image height = {} '
                     'or width = {}'.format(tile_size, height, width))

  if padding:
    image = pad_image_right_bottom(image, tile_size, strides)
    height, width = image.shape

  num_tiles_per_height = (height - tile_size) // strides[0] + 1
  num_tiles_per_width = (width - tile_size) // strides[1] + 1

  out_stack = []

  for row in range(0, num_tiles_per_height * strides[0], strides[0]):

    for col in range(0, num_tiles_per_width * strides[1], strides[1]):
      # get a tile:
      tile = image[row:row + tile_size, col:col + tile_size]
      out_stack.append(tile)

  return np.stack(out_stack)

# TODO(b/175058778): unify pad_image_right_bottom and PadRightBottom
def pad_image_right_bottom(image: np.ndarray, tile_size: int,
                           strides: Tuple[int, int]) -> np.ndarray:
  """Pads the right and bottom edges of the image with zeros.

  Padding is done if afer tiling the image, there are still leftovers that
  are not fit in tiles.

  Args:
    image: 2D numpy array - the image to be padded.
    tile_size: the size of one side of the square tiling window.
    strides: tuple of step sizes of moving the tiling window along the image's
      height and width, respectively.

  Returns:
    The padded image.
  """

  height, width = image.shape
  leftover_rows = (height - tile_size) % strides[0]
  if leftover_rows > 0:
    pad_height = strides[0] - leftover_rows
  else:
    pad_height = 0

  leftover_cols = (width - tile_size) % strides[1]
  if leftover_cols > 0:
    pad_width = strides[1] - leftover_cols
  else:
    pad_width = 0

  if leftover_rows > 0 or leftover_cols > 0:
    return np.pad(image, ((0, pad_height), (0, pad_width)), 'constant')

  return image

@attr.s(auto_attribs=True)
class PadRightBottom(preprocessing.TensorTransform):
  """Pads the right and bottom edges of an image in tf.Tensor format with zeros.

    Padding is done if after tiling the image, there are still leftovers that
    do not fit in tiles.

  Attributes:
    tile_size: the size of one side of the square tiling window.
    strides: tuple of step sizes of moving the tiling window along the image's
      height and width, respectively.
  """
  tile_size: int
  strides: Tuple[int, int]

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    """Pads the right and bottom edges of the image with zeros.

    Padding is done if after tiling the image, there are still leftovers that
    do not fit in tiles.

    Args:
      input_: The image to be padded.

    Returns:
      The padded image.
    """
    tf.debugging.assert_rank_in(input_, (2, 3), 'Input must be either 2D or 3D')

    height, width = tf.shape(input_)[0], tf.shape(input_)[1]

    leftover_rows = (height - self.tile_size) % self.strides[0]
    pad_height = (self.strides[0] - leftover_rows) % self.strides[0]

    leftover_cols = (width - self.tile_size) % self.strides[1]
    pad_width = (self.strides[1] - leftover_cols) % self.strides[1]

    if leftover_rows == 0 and leftover_cols == 0:
      return input_

    if len(tf.shape(input_)) == 2:
      return tf.pad(input_, [[0, pad_height], [0, pad_width]], 'constant')

    return tf.pad(input_, [[0, pad_height], [0, pad_width], [0, 0]], 'constant')

@attr.s(auto_attribs=True)
class ResizeImage(preprocessing.TensorTransform):
  """Resizes an image to a target size.

  Note, if the new shape doesn't have the same aspect ratio of the original
  image, padding is done to avoid image distortion.

  Attributes:
    new_shape: (target_height, target_width) of the resized image.
  """
  shape: Tuple[int, int]

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    target_height, target_width = self.shape
    return tf.image.resize_with_pad(
        input_, target_height, target_width, method='bilinear', antialias=False)

@attr.s(auto_attribs=True)
class ResizeImageWithCropOrPad(preprocessing.TensorTransform):
  """Resizes an image to a target size without any interpolation.

  Note, if the new shape doesn't have the same aspect ratio of the original
  image, cropping or padding is done to completely avoid image distortion.

  Attributes:
    new_shape: (target_height, target_width) of the resized image.
  """
  shape: Tuple[int, int]

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    target_height, target_width = self.shape
    return tf.image.resize_with_crop_or_pad(input_, target_height, target_width)

@attr.s(auto_attribs=True)
class ResizeLabel(preprocessing.TensorTransform):
  """Resizes a label to a target size.

  Note, if the new shape doesn't have the same aspect ratio of the original
  label, padding is done to avoid image distortion.

  Attributes:
    shape: (target_height, target_width) of the resized label.
  """
  shape: Tuple[int, int]

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    target_height, target_width = self.shape
    label = tf.image.resize_with_pad(
        input_, target_height, target_width, method='bilinear', antialias=False)
    return tf.cast(tf.math.rint(label), tf.int32)

@attr.s(auto_attribs=True)
class ResizeLabelWithCropOrPad(preprocessing.TensorTransform):
  """Resizes a label to a target size without any interpolation.

  Note, if the new shape doesn't have the same aspect ratio of the original
  label, cropping or padding is done to completely avoid image distortion.

  Attributes:
    shape: (target_height, target_width) of the resized label.
  """
  shape: Tuple[int, int]

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    target_height, target_width = self.shape
    label = tf.image.resize_with_crop_or_pad(input_, target_height,
                                             target_width)
    return tf.cast(tf.math.rint(label), tf.int32)

@attr.s(auto_attribs=True)
class Crop(preprocessing.TensorTransform):
  """Crops an image on the right and bottom edges to the target shape.

  Original height and width must accommodate the cropping that:
  ```original_size >= target_size + offset```

  Attributes:
    shape: (target_height, target_width) of the cropped image.
    offset: (offset_height, offset_width), vertical and horizontal coordinates
      of the top-left corner of the result in the input.
  """
  shape: Tuple[int, int]
  offset: Tuple[int, int] = (0, 0)

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    return tf.image.crop_to_bounding_box(input_, *self.offset, *self.shape)

class EqualizeHistogram(preprocessing.TensorTransform):
  """Equalizes image histogram."""

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    return tfa_image.equalize(input_)

@attr.s(repr=True)
class PreserveTwoContrastiveLabels(preprocessing.TensorTransform):
  """Preserves two contrastive labels in data and converts them to -1 and 1.

  Only two labels that are in the input list are preserved. The rest are
  converted to "unlabeled" 0.

  Attributes:
    two_labels: The list of two labels to be preserved.
  """
  all_class_label_values = attr.ib(default=attr.Factory(dict))
  two_labels = attr.ib(default=attr.Factory(list))

  @two_labels.validator
  def check_class_labels(self, attribute, values):
    # check that list has exactly two labels:
    if len(values) != 2:
      raise ValueError(
          f'Expecting exactly two classes, but getting two_labels = {values}')

    # check invalid labels:
    for label in values:
      if label not in self.all_class_label_values:
        raise ValueError(
            f'Input class {label} is not one of {self.all_class_label_values}')

  def __attrs_post_init__(self):
    # list of values corresponding to the input labels:
    label_values = [
        self.all_class_label_values[label] for label in self.two_labels
    ]
    # convert to tf.Tensor format:
    label_tensor = tf.constant(label_values)
    # two new labels:
    new_labels = tf.constant([-1, 1])
    # labels not included in input are assigned the value of zero:
    otherwise = 0
    self._lookup_table = tf.lookup.StaticHashTable(
        tf.lookup.KeyValueTensorInitializer(label_tensor, new_labels),
        otherwise)

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    return self._lookup_table.lookup(input_)

@attr.s(repr=True)
class PreserveSplitLabels(preprocessing.TensorTransform):
  """Preserves a list of labels in data and split them into separate channels.

  Only labels that are in the input list are preserved. The rest are converted
  to "unlabeled", i.e., zeros.

  Attributes:
    all_class_label_values: Input dict of all class labels and values. Note that
      the dict must have field "unlabeled".
    class_labels: Input list of labels to be preserved.
  """
  all_class_label_values = attr.ib(default=attr.Factory(dict))
  class_labels = attr.ib(default=attr.Factory(list))

  @all_class_label_values.validator
  def check_all_class_label_values(self, attribute, values):
    # It must have field "unlabeled".
    if 'unlabeled' not in values:
      raise ValueError(
          f'Input dict `all_class_label_values` does not have field "unlabel" '
          f'as expected: {values}')

  @class_labels.validator
  def check_class_labels(self, attribute, values):
    # Check empty list of labels
    if not values:
      raise ValueError('Input class_labels is an empty list: {}'.format(values))

    # Check invalid labels
    for label in values:
      if label not in self.all_class_label_values:
        raise ValueError(
            'input label {} is not in `all_class_label_values` = {}'.format(
                label, self.all_class_label_values))

  def __attrs_post_init__(self):
    # List of label values corresponding to the input class_labels
    self._labels = [
        self.all_class_label_values[item] for item in self.class_labels
    ]

    # Convert to tf.Tensor
    label_tensor = tf.constant(self._labels)

    # Classes not included in input are assigned the value of class "unlabeled"
    otherwise = self.all_class_label_values['unlabeled']

    self._lookup_table = tf.lookup.StaticHashTable(
        tf.lookup.KeyValueTensorInitializer(label_tensor, label_tensor),
        otherwise)

  def call(self, input_: tf.Tensor) -> tf.Tensor:
    """Preserves then separates labels in the input data.

    Args:
      input_: The input labels.

    Returns:
      The transformed label data.
    """
    # Remove the color channel dimension if there is only one color
    if input_.shape[-1] == 1:
      input_ = tf.squeeze(input_, axis=-1)

    # Preserve the input classes and assign the unwanted classes to 'unlabeled'
    output = self._lookup_table.lookup(input_)

    # Create one-hot channels for all potential classes
    outputs = tf.one_hot(
        output, depth=len(self.all_class_label_values), dtype=tf.int32)

    return tf.gather(outputs, self._labels, axis=-1)

def merge_labels(label: types.TensorLike) -> tf.Tensor:
  """Merges the channels of the label.

  Assuming the input `label` has different channels representing different
  classes that are defined by `CLASS_LABELS_VALUES`. The input shape is
  (height, width, channels). This functions merges all separated channels so
  that the output shape is (height, width).

  Args:
    label: The input label with the classes separated into different channels.

  Returns:
    The merged label.
  """
  label = tf.convert_to_tensor(label)
  return tf.argmax(label, axis=-1, output_type=tf.int32)

def tiles_to_image(tiles: np.ndarray,
                   image_shape: Tuple[int, int],
                   strides: Tuple[int, int],
                   padding=True) -> np.ndarray:
  """Reconstructs an image from a stack of tiles.

  Suppose an image is converted to stack of tiles using function image_to_tiles,
  then the stack is transformed via some model without changing its shape, this
  function unpacks the transformed stack to reconstruct the transformed image.

  Args:
    tiles: stack of tiles with shape (num_tiles, tile_size, tile_size).
    image_shape: the desire shape of the constructed image.
    strides: tuple of step sizes of moving the tiling window along the image's
      height and width, respectively, as used in image_to_tiles.
    padding: boolean, if True, take into account the original image was expanded
      and padded with zeros on the right and top edges, so that all tiles are
      fully inside the image.

  Returns:
    The reconstructed image.
  """
  height, width = image_shape
  _, tile_size, _ = tiles.shape

  if padding:
    leftover_rows = (height - tile_size) % strides[0]
    if leftover_rows > 0:
      height = height + strides[0] - leftover_rows

    leftover_cols = (width - tile_size) % strides[1]
    if leftover_cols > 0:
      width = width + strides[1] - leftover_cols

  image = np.zeros(shape=(height, width))
  count = np.zeros(shape=(height, width))

  num_tiles_per_height = (height - tile_size) // strides[0] + 1
  num_tiles_per_width = (width - tile_size) // strides[1] + 1

  tile_idx = 0

  for row in range(0, num_tiles_per_height * strides[0], strides[0]):

    for col in range(0, num_tiles_per_width * strides[1], strides[1]):
      # add tile to image and count occurrences of each pixel:
      image[row:row + tile_size, col:col + tile_size] += tiles[tile_idx, :, :]
      count[row:row + tile_size, col:col + tile_size] += 1

      # move to the next tile_idx:
      tile_idx += 1

  # original shape:
  height, width = image_shape
  return image[:height, :width] / count[:height, :width]

def circular_mask(height: int,
                  width: int,
                  radius: float,
                  dtype=np.bool_) -> np.ndarray:
  """Creates a 2D circular mask centered at the middle of the output matrix.

  Elements in the circle are 1s and the rest is 0.

  Args:
    height: Height of the output matrix.
    width: Width of the output matrix.
    radius: Radius of the circle.
    dtype: Output dtype.

  Returns:
    A 2D circular mask.
  """
  vertical_points = height - 1
  horizontal_points = width - 1
  i, j = np.meshgrid(
      np.linspace(-vertical_points / 2, vertical_points / 2, height),
      np.linspace(-horizontal_points / 2, horizontal_points / 2, width),
      indexing='ij')
  distance_2 = i**2 + j**2
  radius_2 = radius**2

  return np.less_equal(distance_2, radius_2).astype(dtype)

def gaussian_mask(height: int,
                  width: int,
                  radius: float,
                  dtype=np.float32) -> np.ndarray:
  """Creates a 2D isotropic Gaussian mask centered at the middle of the matrix.

  We omit the 1 / (2 pi sigma^2) term in calculating the Gaussian distribution.
  The max value in the mask is 1.

  Args:
    height: Height of the output matrix.
    width: Width of the output matrix.
    radius: Standard deviation of the Gaussian kernel.
    dtype: Output dtype.

  Returns:
    A 2D Gaussian mask.
  """
  vertical_points = height - 1
  horizontal_points = width - 1
  i, j = np.meshgrid(
      np.linspace(-vertical_points / 2, vertical_points / 2, height),
      np.linspace(-horizontal_points / 2, horizontal_points / 2, width),
      indexing='ij')
  distance_2 = i**2 + j**2
  radius_2 = radius**2

  return np.exp(-(distance_2 / (2.0 * radius_2)), dtype=dtype)


text:
<?php

declare (strict_types=1);
namespace Ssch\TYPO3Rector\FileProcessor\TypoScript\Conditions;

use RectorPrefix20210615\Nette\Utils\Strings;
use Ssch\TYPO3Rector\Helper\ArrayUtility;
final class GlobalStringConditionMatcher extends \Ssch\TYPO3Rector\FileProcessor\TypoScript\Conditions\AbstractGlobalConditionMatcher
{
    /**
     * @var string
     */
    private const TYPE = 'globalString';
    public function change(string $condition) : ?string
    {
        \preg_match('#' . self::TYPE . self::ZERO_ONE_OR_MORE_WHITESPACES . '=' . self::ZERO_ONE_OR_MORE_WHITESPACES . '(?<subCondition>.*)#', $condition, $subConditions);
        if (!\is_string($subConditions['subCondition'])) {
            return $condition;
        }
        $subConditions = \Ssch\TYPO3Rector\Helper\ArrayUtility::trimExplode(',', $subConditions['subCondition']);
        $newConditions = [];
        foreach ($subConditions as $subCondition) {
            \preg_match('#(?<type>ENV|IENV|GP|TSFE|LIT)' . self::ZERO_ONE_OR_MORE_WHITESPACES . ':' . self::ZERO_ONE_OR_MORE_WHITESPACES . '(?<property>.*)\\s*(?<operator>' . self::ALLOWED_OPERATORS_REGEX . ')' . self::ZERO_ONE_OR_MORE_WHITESPACES . '(?<value>.*)$#Ui', $subCondition, $matches);
            $type = \trim($matches['type']);
            $property = \trim($matches['property']);
            $operator = \trim($matches['operator']);
            $value = \trim($matches['value']);
            if ('ENV' === $type) {
                $newConditions[] = $this->createEnvCondition($property, $operator, $value);
            } elseif ('IENV' === $type) {
                $newConditions[] = $this->createIndependentCondition($property, $operator, $value);
            } elseif ('TSFE' === $type) {
                $newConditions[] = $this->refactorTsfe($property, $operator, $value);
            } elseif ('GP' === $type) {
                $newConditions[] = $this->refactorGetPost($property, $operator, $value);
            } elseif ('LIT' === $type) {
                $newConditions[] = \sprintf('"%s" %s "%s"', $value, self::OPERATOR_MAPPING[$operator], $property);
            }
        }
        return \implode(' || ', $newConditions);
    }
    public function shouldApply(string $condition) : bool
    {
        if (\RectorPrefix20210615\Nette\Utils\Strings::contains($condition, self::CONTAINS_CONSTANT)) {
            return \false;
        }
        return \RectorPrefix20210615\Nette\Utils\Strings::startsWith($condition, self::TYPE);
    }
    private function refactorGetPost(string $property, string $operator, string $value) : string
    {
        $parameters = \Ssch\TYPO3Rector\Helper\ArrayUtility::trimExplode('|', $property);
        if (!\is_numeric($value)) {
            $value = \sprintf("'%s'", $value);
        }
        if (1 === \count($parameters)) {
            return \sprintf('request.getQueryParams()[\'%1$s\'] %2$s %3$s', $parameters[0], self::OPERATOR_MAPPING[$operator], $value);
        }
        return \sprintf('traverse(request.getQueryParams(), \'%1$s\') %2$s %3$s || traverse(request.getParsedBody(), \'%1$s\') %2$s %3$s', \implode('/', $parameters), self::OPERATOR_MAPPING[$operator], $value);
    }
}


text:
<?php

namespace Concrete\Core\Install;

/**
 * Interface for the checks to be performed before installing concrete5 that need a web environment.
 */
interface WebPreconditionInterface extends PreconditionInterface
{
    /**
     * Get the initial state of the precondition.
     *
     * @return int|null One of the PreconditionResult::STATE_... constants (or NULL if working)
     */
    public function getInitialState();

    /**
     * Get the initial message of the precondition.
     *
     * @return string
     */
    public function getInitialMessage();

    /**
     * Get the HTML used to check the precondition.
     */
    public function getHtml();

    /**
     * Get the answer of ajax calls.
     *
     * @param string $argument
     */
    public function getAjaxAnswer($argument);
}


text:
In Trying to migrate into VPC, I had instances in EC2-Classic and EC2-VPC trying to connect to each
other using either Public and Private IPs, which would fail, depending on what is connecting to
what. Rather than modify the code to have rules of which to use, a better fix is to make one-off
iptables rules to force the instance to route traffic for IP-A to IP-B.

```bash
$ iptables -t nat -A OUTPUT -p all -d [ VPC IP ] -j DNAT --to-destination [ Public IP ]

$ iptables -t nat -A OUTPUT -p all -d 10.10.4.117 -j DNAT --to-destination 54.1.51.234
```


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!--  Palette generated by Material Palette - materialpalette.com/purple/yellow
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="primary">#9C27B0</color>
        <color name="primary_dark">#7B1FA2</color>
        <color name="primary_light">#E1BEE7</color>
        <color name="accent">#FFEB3B</color>
        <color name="primary_text">#212121</color>
        <color name="secondary_text">#757575</color>
        <color name="icons">#FFFFFF</color>
        <color name="divider">#BDBDBD</color>
    </resources>
    -->

    <!-- Palette generated by Material Palette - materialpalette.com/indigo/deep-orange -->
    <color name="primary">#3F51B5</color>
    <color name="primary_dark">#303F9F</color>
    <color name="primary_light">#C5CAE9</color>
    <color name="accent">#9C27B0</color>
    <color name="primary_text">#000000</color>
    <color name="secondary_text">#000000</color>
    <color name="icons">#FFFFFF</color>
    <color name="divider">#BDBDBD</color>

    <!-- Palette generated by Material Palette - materialpalette.com/red/brown -->
    <!--
        <color name="primary">#F44336</color>
        <color name="primary_dark">#D32F2F</color>
        <color name="primary_light">#FFCDD2</color>
        <color name="accent">#795548</color>
        <color name="primary_text">#212121</color>
        <color name="secondary_text">#757575</color>
        <color name="icons">#FFFFFF</color>
        <color name="divider">#BDBDBD</color>
    -->

    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#7B1FA2</color>
    <color name="colorAccent">#FFEB3B</color>
    <!--
    <color name="primary">#795548</color>
    <color name="primary_dark">#5D4037</color>
    <color name="primary_light">#D7CCC8</color>
    <color name="accent">#FFEB3B</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#757575</color>
    <color name="icons">#FFFFFF</color>
    <color name="divider">#BDBDBD</color>
    -->

    <color name="indigo">#4B0082</color>
    <color name="pink">#ff1493</color>

    <color name="orange">#FF9900</color>
    <color name="green">#009900</color>
    <color name="blue">#000099</color>
</resources>


text:
package com.google.security.zynamics.binnavi.yfileswrap.Gui.GraphWindows;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.BottomPanel.RegisterTracker.CTracking;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CGraphModel;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.InitialTab;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Extensions.ICodeNodeExtension;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations.CGraphDebugger;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations.CGraphOpener;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations.CGraphZoomer;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations.CLineGrayer;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations.CLineHighlighter;
import com.google.security.zynamics.binnavi.ZyGraph.Builders.Wrappers.CGlobalNodeCommentWrapper;
import com.google.security.zynamics.binnavi.ZyGraph.Builders.Wrappers.CLocalNodeCommentWrapper;
import com.google.security.zynamics.binnavi.ZyGraph.Implementations.CNodeFunctions;
import com.google.security.zynamics.binnavi.ZyGraph.Menus.ZyGraphPopupMenus;
import com.google.security.zynamics.binnavi.disassembly.CCodeNodeHelpers;
import com.google.security.zynamics.binnavi.disassembly.COperandTreeNode;
import com.google.security.zynamics.binnavi.disassembly.INaviCodeNode;
import com.google.security.zynamics.binnavi.disassembly.INaviFunction;
import com.google.security.zynamics.binnavi.disassembly.INaviFunctionNode;
import com.google.security.zynamics.binnavi.disassembly.INaviGroupNode;
import com.google.security.zynamics.binnavi.disassembly.INaviInstruction;
import com.google.security.zynamics.binnavi.disassembly.INaviOperandTree;
import com.google.security.zynamics.binnavi.disassembly.INaviViewNode;
import com.google.security.zynamics.binnavi.yfileswrap.Gui.GraphWindows.Implementations.CGraphDialogs;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode;
import com.google.security.zynamics.reil.algorithms.mono2.common.enums.AnalysisDirection;
import com.google.security.zynamics.reil.algorithms.mono2.registertracking.RegisterTrackingOptions;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.zylib.disassembly.ExpressionType;
import com.google.security.zynamics.zylib.disassembly.IAddress;
import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode;
import com.google.security.zynamics.zylib.disassembly.IReference;
import com.google.security.zynamics.zylib.disassembly.ReferenceType;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ZyNodeContentHelpers;

import java.awt.event.MouseEvent;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JPopupMenu;

/**
 * Class that handles clicks on nodes of a graph.
 */
public final class CNodeClickHandler {
  /**
   * Represents the displayed graph whose nodes were clicked.
   */
  private final CGraphModel m_model;

  /**
   * Used to gray individual lines of a node.
   */
  private final CLineGrayer m_grayer = new CLineGrayer();

  /**
   * Used to highlight individual lines of a node.
   */
  private final CLineHighlighter m_highlighter = new CLineHighlighter();

  /**
   * Creates a new node click handler object.
   *
   * @param model Represents the displayed graph whose nodes were clicked.
   */
  public CNodeClickHandler(final CGraphModel model) {
    m_model = Preconditions.checkNotNull(model, "IE01628: Model argument can not be null");
  }

  /**
   * Collects all code references from an operand tree node and all of its children.
   *
   * @param node The root node where reference collection starts.
   * @param references The collected references are stored here.
   */
  private void collectReferences(final IOperandTreeNode node, final Set<IAddress> references) {
    for (final IReference reference : node.getReferences()) {
      if (ReferenceType.isCodeReference(reference.getType())) {
        references.add(reference.getTarget());
      }
    }

    for (final IOperandTreeNode child : node.getChildren()) {
      collectReferences(child, references);
    }
  }

  /**
   * Invoked when the user wants to set or remove breakpoints.
   *
   * @param node The node where the user clicked.
   * @param y The y location where the user clicked.
   */
  private void handleBreakpointClick(final NaviNode node, final double y) {
    if (node.getRawNode() instanceof INaviCodeNode) {
      final int row = node.positionToRow(y - node.getY());

      CGraphDebugger.toggleBreakpoint(m_model.getDebuggerProvider(),
          (INaviCodeNode) node.getRawNode(), row);
    } else if (node.getRawNode() instanceof INaviFunctionNode) {
      CGraphDebugger.toggleBreakpoint(m_model.getDebuggerProvider(),
          (INaviFunctionNode) node.getRawNode());
    }
  }

  /**
   * Handles right-clicks on nodes.
   *
   * @param node The node where the user clicked.
   * @param event Mouse-event that was created when the user clicked.
   * @param x The x location where the user clicked.
   * @param y The y location where the user clicked.
   * @param extensions List of objects that extend code node context menus.
   */
  private void handleRightClick(final NaviNode node, final MouseEvent event, final double x,
      final double y, final List<ICodeNodeExtension> extensions) {
    final Object positionObject = ZyNodeContentHelpers.getObject(node, x, y);

    if (event.isAltDown() && event.isShiftDown()) {
      m_grayer.handleGrayLine(m_model, node, y);
    } else if (event.isAltDown() && event.isControlDown()) {
      m_highlighter.handleHighlightLine(node, y);
    } else if (event.isAltDown()) {
      if (positionObject instanceof CLocalNodeCommentWrapper) {
        CNodeFunctions.editNodeComments(m_model,
            ((CLocalNodeCommentWrapper) positionObject).getNode(), InitialTab.LocalNodeComments);
      } else if (positionObject instanceof CGlobalNodeCommentWrapper) {
        CNodeFunctions.editNodeComments(m_model,
            ((CGlobalNodeCommentWrapper) positionObject).getNode(), InitialTab.GlobalNodeComments);
      } else if (node.getRawNode() instanceof INaviCodeNode) {
        handleShowInstructionComment(node, y);
      }
    } else if (event.isShiftDown()) {
      handleBreakpointClick(node, y);
    } else if (event.isControlDown() && positionObject instanceof COperandTreeNode) {
      handleDoRegisterTrackingDown(node, y, x, (COperandTreeNode) positionObject);
    } else if (event.isControlDown() && event.isShiftDown()
        && positionObject instanceof COperandTreeNode) {
      handleDoRegisterTrackingUp(node, y, x, (COperandTreeNode) positionObject);
    } else {
      showPopupMenu(node, event, positionObject, y, extensions);
    }
  }

  /**
   * Sets the direction of the register tracker analysis to down and then calls the
   * handleRegisterTracker function.
   *
   * @param node The {@link NaviNode} where the mouse event happened.
   * @param y The y coordinate of the mouse event.
   * @param x The x coordinate of the mouse event.
   * @param operand The operand which has been under the cursor in the event.
   */
  private void handleDoRegisterTrackingDown(final NaviNode node, final double y, final double x,
      final COperandTreeNode operand) {
    handleRegisterTracking(node, y, operand, AnalysisDirection.DOWN);
  }

  private void handleRegisterTracking(final NaviNode node, final double y,
      final COperandTreeNode operand, final AnalysisDirection direction) {
    if (!(node.getRawNode() instanceof INaviCodeNode)) {
      return; // register tracking is only possible on code nodes.
    }

    final INaviCodeNode codeNode = (INaviCodeNode) node.getRawNode();
    final double yPos = y - node.getY();
    final int row = node.positionToRow(yPos);
    final INaviInstruction instruction = CCodeNodeHelpers.lineToInstruction(codeNode, row);
    if (instruction == null) {
      return;
    }
    if (!operand.getType().equals(ExpressionType.REGISTER)) {
      return;
    }

    final Set<String> clearedRegisters = Sets.newHashSet();

    if (instruction.getArchitecture().equalsIgnoreCase("x86-32")) {
      clearedRegisters.add("eax");
    } else if (instruction.getArchitecture().equalsIgnoreCase("x86-64")) {
      clearedRegisters.add("rax");
    } else if (instruction.getArchitecture().equalsIgnoreCase("PowerPC-32")) {
      clearedRegisters.addAll(
          Lists.newArrayList("R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11", "R12"));
    } else if (instruction.getArchitecture().equalsIgnoreCase("ARM-32")) {
      clearedRegisters.addAll(Lists.newArrayList("r0", "r1", "r2", "r3", "r12", "r14"));
    } else if (instruction.getArchitecture().equalsIgnoreCase("MIPS-32")) {
      clearedRegisters.addAll(Lists.newArrayList("$a0",
          "$a1",
          "$a2",
          "$a3",
          "$t0",
          "$t1",
          "$t2",
          "$t3",
          "$t4",
          "$t5",
          "$t6",
          "$t7",
          "$v0",
          "$v1"));
    } else {
      return;
    }

    final boolean trackIncoming = instruction.getOperandPosition(operand.getOperand()) != 0;

    final RegisterTrackingOptions options =
        new RegisterTrackingOptions(false, clearedRegisters, trackIncoming, direction);
    try {
      // TODO(timkornau): comment this code in once we know how to access the bottom panel.
      // final CTrackingResult result =
      CTracking.track(m_model.getGraph().getRawView(), instruction, operand.getValue(), options);
    } catch (final InternalTranslationException exception) {
      CUtilityFunctions.logException(exception);
    }

    // TODO: (timkornau@google) there is currently no way to access the bottom panel to display the
    // results. We need to somehow get access to the register tracking results container which
    // exposes a method to set a new result.

  }

  /**
   * Sets the direction of the register tracker analysis to up and then calls the
   * handleRegisterTracker function.
   *
   * @param node The {@link NaviNode} where the mouse event happened.
   * @param y The y coordinate of the mouse event.
   * @param x The x coordinate of the mouse event.
   * @param operand The operand which has been under the cursor in the event.
   */
  private void handleDoRegisterTrackingUp(final NaviNode node, final double y, final double x,
      final COperandTreeNode operand) {
    handleRegisterTracking(node, y, operand, AnalysisDirection.UP);
  }

  /**
   * Handles clicks on code nodes that should bring up the dialog for editing instruction comments.
   *
   * @param node The clicked node.
   * @param y Y-Coordinate of the mouse click.
   */
  private void handleShowInstructionComment(final NaviNode node, final double y) {
    if (!(node.getRawNode() instanceof INaviCodeNode)) {
      return;
    }

    final INaviCodeNode codeNode = (INaviCodeNode) node.getRawNode();
    final double yPos = y - node.getY();
    final int row = node.positionToRow(yPos);
    final INaviInstruction instruction = CCodeNodeHelpers.lineToInstruction(codeNode, row);
    if (instruction == null) {
      return;
    }

    CGraphDialogs.showInstructionCommentDialog(m_model.getParent(), m_model, codeNode, instruction);
  }

  /**
   * Displays a popup menu for the given node.
   *
   * @param node The node where the user clicked.
   * @param event Mouse-event that was created when the user clicked.
   * @param y The y location where the user clicked.
   * @param clickedObject The clicked object.
   * @param extensions List of objects that extend code node context menus.
   */
  private void showPopupMenu(final NaviNode node, final MouseEvent event,
      final Object clickedObject, final double y, final List<ICodeNodeExtension> extensions) {
    final boolean isActiveNode = m_model.getGraph().getEditMode().getLabelEventHandler()
        .isActiveLabel(node.getRealizer().getNodeContent());

    final JPopupMenu menu = ZyGraphPopupMenus.getPopupMenu(m_model,
        node,
        clickedObject,
        y - node.getY(),
        isActiveNode,
        extensions);

    if (menu != null) {
      menu.show(m_model.getGraph().getView(), event.getX(), event.getY());
    }
  }

  /**
   * Handles clicks on nodes.
   *
   * @param node The clicked node.
   * @param event The click event.
   * @param x The x-coordinate of the click.
   * @param y The y-coordinate of the click.
   * @param extensions List of objects that extend code node context menus.
   */
  public void nodeClicked(final NaviNode node, final MouseEvent event, final double x,
      final double y, final List<ICodeNodeExtension> extensions) {
    if (event.getButton() == MouseEvent.BUTTON3) {
      handleRightClick(node, event, x, y, extensions);
    } else if ((event.getButton() == MouseEvent.BUTTON1) && (event.getClickCount() == 2)
        && event.isControlDown()) {
      final INaviViewNode rawNode = node.getRawNode();

      if (rawNode instanceof INaviFunctionNode) {
        final INaviFunction function = ((INaviFunctionNode) rawNode).getFunction();

        CGraphOpener.showFunction(m_model.getParent(), m_model.getViewContainer(), function);
      } else if (rawNode instanceof INaviCodeNode) {
        final INaviCodeNode cnode = (INaviCodeNode) rawNode;

        final int row = node.positionToRow(y - node.getY());

        final INaviInstruction instruction = CCodeNodeHelpers.lineToInstruction(cnode, row);

        if (instruction == null) {
          return;
        }

        final Set<IAddress> references = new HashSet<IAddress>();

        for (final INaviOperandTree operand : instruction.getOperands()) {
          collectReferences(operand.getRootNode(), references);
        }

        final List<INaviFunction> functions = m_model.getViewContainer().getFunctions();

        for (final INaviFunction function : functions) {
          for (final IAddress address : references) {
            if (function.getAddress().equals(address)) {
              CGraphOpener.showFunction(m_model.getParent(), m_model.getViewContainer(), function);
            }
          }
        }
      }
    } else if (!m_model.getGraph().getEditMode().getLabelEventHandler().isActive()
        && (event.getButton() == MouseEvent.BUTTON1) && (event.getClickCount() == 2)) {
      if ((node.getRawNode() instanceof INaviGroupNode) && event.isShiftDown()) {
        final INaviGroupNode gnode = (INaviGroupNode) node.getRawNode();

        gnode.setCollapsed(!gnode.isCollapsed());
      } else {
        CGraphZoomer.zoomNode(m_model.getGraph(), node);
      }
    }
  }
}