text:
/**
 * Package: MAG - VistA Imaging
 * WARNING: Per VHA Directive 2004-038, this routine should not be modified.
 * @date May 12, 2010
 * Site Name:  Washington OI Field Office, Silver Spring, MD
 * @author vhaiswbeckec
 * @version 1.0
 *
 * ----------------------------------------------------------------
 * Property of the US Government.
 * No permission to copy or redistribute this software is given.
 * Use of unreleased versions of this software requires the user
 * to execute a written test agreement with the VistA Imaging
 * Development Office of the Department of Veterans Affairs,
 * telephone (301) 734-0100.
 *
 * The Food and Drug Administration classifies this software as
 * a Class II medical device.  As such, it may not be changed
 * in any way.  Modifications to this software may result in an
 * adulterated medical device under 21CFR820, the use of which
 * is considered to be a violation of US Federal Statutes.
 * ----------------------------------------------------------------
 */

package gov.va.med.server.tomcat;

import java.security.Principal;
import org.apache.log4j.Logger;
import gov.va.med.server.ServerAgnosticEngine;
import gov.va.med.server.ServerAgnosticEngineAdapter;
import gov.va.med.server.ServerLifecycleEvent;

/**
 * This is a test implementation of a ServerAgnosticEngine, useful only for testing
 * the ServerAgnosticEngineAdapter.
 *
 * @author vhaiswbeckec
 *
 */
public class TestServerAdapter
implements ServerAgnosticEngine
{
	private Logger logger = Logger.getLogger(TestServerAdapter.class);
	private ServerAgnosticEngineAdapter engineAdapter;

	@Override
	public void serverEvent(ServerLifecycleEvent event)
	{
		logger.info("Just got a " + event.toString() + " message.");

		Principal principal = this.engineAdapter.authenticate("boating1", "boating1.".getBytes());
		logger.info("Authenticated as '" + principal.toString() + "'.");
	}

	@Override
	public void setServerAgnosticEngineAdapter(ServerAgnosticEngineAdapter engineAdapter)
	{
		this.engineAdapter = engineAdapter;
	}

}


text:
package com.marklogic.samplestack.security;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.marklogic.samplestack.exception.SamplestackSecurityException;

/**
 * Provides the keys to two different database connections,
 * and a method for referring to their properties in build.gradle.
 */
public enum ClientRole {

	SAMPLESTACK_CONTRIBUTOR, SAMPLESTACK_GUEST;
	private String getPrefix() {
		switch(this) {
    	case SAMPLESTACK_CONTRIBUTOR: return "marklogic.writer";
    	case SAMPLESTACK_GUEST: return "marklogic.guest";
    	default: throw new SamplestackSecurityException();
		}
	}

	/**
	 * Gets the name of the user parameter for this ClientRole.
	 * @return username parameter used in build.gradle to configure the database connection.
	 */
	public String getUserParam() {
		return getPrefix() + ".user";
	}

	/**
	 * Gets the name of the password parameter for this ClientRole.
	 * @return username parameter used in build.gradle to configure the database connection.
	 */
	public String getPasswordParam() {
		return getPrefix() + ".password";
	}

	/**
	 * Provides the database client role implied by the security context for the spring application.
	 * @return The ClientRole enum value that corresponds to the current logged-in user.
	 */
	public static ClientRole securityContextRole() {
		SecurityContext secContext = SecurityContextHolder.getContext();
		Collection<? extends GrantedAuthority> auths = secContext.getAuthentication().getAuthorities();
		if (auths.contains(new SimpleGrantedAuthority("ROLE_CONTRIBUTORS"))) {
			return SAMPLESTACK_CONTRIBUTOR;
		}
		else {
			return SAMPLESTACK_GUEST;
		}
	}

	/**
	 * Provides the username for implied by the security context for the spring application.
	 * @return The username value that corresponds to the current logged-in user.
	 */
	public static String securityContextUserName() {
		SecurityContext secContext = SecurityContextHolder.getContext();
		String userName = secContext.getAuthentication().getName();
		return userName;
	}
}

redpajama_set_name: RedPajamaGithub


text: iex (wget 'https://chocolatey.org/install.ps1' -UseBasicParsing)


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvTheEnd"
    android:textColor="@color/colorText"
    android:layout_width="match_parent"
    android:layout_height="36dp"
    android:gravity="center"
    android:text="THE END"
    android:layout_gravity="center" />


text:
<?php
namespace PhpBrew;

use PEARX\Utils as PEARXUtils;

class ExtensionMetaXml extends ExtensionMetaAbstraction implements ExtensionMetaInterface
{
    protected $meta;

    protected $peclInstallPath;

    public function __construct($packageXml, $peclInstallPath = null)
    {
        $this->meta = PEARXUtils::create_dom();

        if (false === $this->meta->loadXml(file_get_contents($packageXml))) {
            throw new \Exception("Error loading XMl document: {$packageXml}");
        }

        $this->peclInstallPath = $peclInstallPath;
    }

    public function isZend()
    {
        return (bool) $this->meta->getElementsByTagName('zendextsrcrelease')->length;
    }

    public function getName()
    {
        return $this->meta->getElementsByTagName('name')->item(0)->nodeValue;
    }

    public function getRuntimeName()
    {
        $provides = $this->meta->getElementsByTagName('providesextension');

        return $provides->length ? $provides->item(0)->nodeValue : $this->getName();
    }

    public function getSourceFile()
    {
        return strtolower($this->getRuntimeName() . '.so');
    }

    public function getVersion()
    {
        return ($this->meta->getElementsByTagName('version')->item(0)
                           ->getElementsByTagName('release')->item(0)
                           ->nodeValue);
    }
}


text:
const deepAssign = require('deep-assign');

const defaultConf = {
};

const production = {
  server: {
    port: process.env.PORT || 3001
  },
  mongo: {
    uri: process.env.MONGODB_URI,
  },
};

const development = {
  server: {
    port: 3001
  },
  mongo: {
    uri: 'mongodb://localhost/my-smart-fridge',
  },
};

const activeConf = (process.env.NODE_ENV === 'production') ? production : development;

module.exports = deepAssign(defaultConf, activeConf);


text:
source $BASE_PATH/msg.sh

msg_init 'guake'

if [[ "$(command -v guake)" == "" ]]; then
    pip3 install --user guake
    export PATH=$PATH:$HOME/.local/bin:
fi

msg_end 'guake'


text:
package gis.iwacu_new.rit.edu.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

public class GeometrySampleActivity extends FragmentActivity implements
		SampleListFragment.OnSampleNameSelectedListener {

    ProjectFragment projectFrag;
    BufferFragment bufferFrag;
    UnionDifferenceFragment unionDiffFrag;
    SpatialRelationshipsFragment spatialRelationFrag;
    MeasureFragment measureFrag;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.geometry_samples);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first
        // fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create an instance of the SampleListFragment
            SampleListFragment firstFragment = new SampleListFragment();

            // In case this activity was started with special instructions from
            // an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }

        //open specific tool if being called from learning content
        //see if there are incoming args
        Intent intent = getIntent();

        if (intent.hasExtra(getResources().getString((R.string.tool_argument_key_name)))) {

            Bundle incoming_data = intent.getBundleExtra(getResources().getString((R.string.tool_argument_key_name)));

            if (incoming_data != null) {
                String toolName = (String) incoming_data.get(getResources().getString((R.string.tool_argument_tool_name)));
                String toolData = (String) incoming_data.get(getResources().getString((R.string.tool_argument_tool_data)));

                String [] gisTools = getResources().getStringArray(R.array.sample_names);

                int positionToUse = 0;

                for (int x = 0; x < gisTools.length; x++) {
                    if (gisTools[x].equalsIgnoreCase(toolName)) {
                        //find the tool being called and pass arguments in accordingly
                        switch (x) {
                        case 0:
                            positionToUse = x;
                            break;
                        case 1:
                            positionToUse = x;
                            break;
                        case 2:
                            positionToUse = x;
                            break;
                        case 3:
                            positionToUse = x;
                            break;
                        case 4:
                            positionToUse = x;
                            break;
                        default:
                            break;

                        }
                    }
                }
                //make the actual tools call
                this.onArticleSelected(positionToUse);
            }

        }
    }

	public void onArticleSelected(int position) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (projectFrag != null && !projectFrag.isDetached()) {
            ft.detach(projectFrag);
            projectFrag = null;
        }

        if (bufferFrag != null && !bufferFrag.isDetached()) {
            ft.detach(bufferFrag);
            bufferFrag = null;
        }

        if (unionDiffFrag != null && !unionDiffFrag.isDetached()) {
            ft.detach(unionDiffFrag);
            unionDiffFrag = null;
        }

        if (spatialRelationFrag != null && !spatialRelationFrag.isDetached()) {
            ft.detach(spatialRelationFrag);
            spatialRelationFrag = null;
        }

        if (measureFrag != null && !measureFrag.isDetached()) {
            ft.detach(measureFrag);
            measureFrag = null;
        }

		switch (position) {
		case 0:
			if (projectFrag == null || projectFrag.getShownIndex() != position) {
				// Make new fragment to show this selection.
				projectFrag = ProjectFragment.newInstance(position);
				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				// FragmentTransaction ft =
				// getSupportFragmentManager().beginTransaction();
				ft.replace(R.id.sample_fragment, projectFrag);
				ft.setTransition(FragmentTransaction.TRANSIT_NONE);
				ft.commit();
			}
			break;

		case 1:
			if (bufferFrag == null || bufferFrag.getShownIndex() != position) {
				// Make new fragment to show this selection.
				bufferFrag = BufferFragment.newInstance(position);
				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				ft.add(R.id.sample_fragment, bufferFrag);
				ft.setTransition(FragmentTransaction.TRANSIT_NONE);
				ft.commit();
			}
			break;

		case 2:
			if (unionDiffFrag == null
					|| unionDiffFrag.getShownIndex() != position) {
				// Make new fragment to show this selection.
				unionDiffFrag = UnionDifferenceFragment.newInstance(position);
				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				ft.add(R.id.sample_fragment, unionDiffFrag);
				ft.setTransition(FragmentTransaction.TRANSIT_NONE);
				ft.commit();
			}
			break;

		case 3:
			if (spatialRelationFrag == null
					|| spatialRelationFrag.getShownIndex() != position) {
				// Make new fragment to show this selection.
				spatialRelationFrag = SpatialRelationshipsFragment
						.newInstance(position);
				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				ft.add(R.id.sample_fragment, spatialRelationFrag);
				ft.setTransition(FragmentTransaction.TRANSIT_NONE);
				ft.commit();
			}
			break;

		case 4:
			if (measureFrag == null || measureFrag.getShownIndex() != position) {
				// Make new fragment to show this selection.
				measureFrag = MeasureFragment.newInstance(position);
				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				ft.add(R.id.sample_fragment, measureFrag);
				ft.setTransition(FragmentTransaction.TRANSIT_NONE);
				ft.commit();
			}
			break;

		default:
			break;
		}
	}
}


text:
/**
 * Created by ZhiyuanSun on 16/9/21.
 */

class Address{
  constructor(lng, lat, province, city, district, street, streetNumber){
    this.lng = lng;
    this.lat = lat;
    this.province = province;
    this.city = city;
    this.district = district;
    this.street = street;
    this.streetNumber = streetNumber;
  }

  getAddress(){
    let address = "";
    if(this.province){
      address += this.province;
    }
    else
      return address;

    if(this.city)
      address += this.city;
    else
      return address;

    if(this.district)
      address += this.district;
    else
      return address;

    if(this.street)
      address += this.street;
    else
      return address;

    if(this.streetNumber)
      address += this.streetNumber;
    else
      return address;

    return address;
  }
}

module.exports = Address;


text:
class CreateApiKeys < ActiveRecord::Migration
  def change
    create_table :api_keys do |t|
      t.references :user, index: true, foreign_key: true
      t.string :public
      t.string :secret

      t.timestamps null: false
    end
  end
end


text:
package org.apache.kerby.kerberos.kerb.util;

import org.apache.kerby.kerberos.kerb.ccache.CredentialCache;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

import static org.assertj.core.api.Assertions.assertThat;

/*
Default principal: drankye@SH.INTEL.COM

Valid starting       Expires              Service principal
08/05/2014 00:13:17  08/05/2014 10:13:17  krbtgt/SH.INTEL.COM@SH.INTEL.COM
        Flags: FIA, Etype (skey, tkt): des3-cbc-sha1, des3-cbc-sha1
 */
public class CcacheTest {

    private CredentialCache cc;

    @Before
    public void setUp() throws IOException {
        InputStream cis = CcacheTest.class.getResourceAsStream("/test.cc");
        cc = new CredentialCache();
        cc.load(cis);
    }

    @Test
    public void testCc() {
        assertThat(cc).isNotNull();

        PrincipalName princ = cc.getPrimaryPrincipal();
        assertThat(princ).isNotNull();
        assertThat(princ.getName().equals("drankye@SH.INTEL.COM")).isTrue();
    }
}


text:
/*
    Handle facebook messenger API
*/

const request = require('request');
const crypto = require('crypto');
const line = require('@line/bot-sdk');
const fs = require('fs');
const URL = require('url');
const easyimg = require('easyimage');
const mime = require('mime-types');
const Thumbler = require('thumbler');
const mm = require('music-metadata');

const Const = require('../../constants');
const BaseAdapter = require('./BaseAdapter');

class LineAdapter extends BaseAdapter {

    constructor(config) {
        super(config);

        this.provider = Const.line;
    }

    processGet(req,res,service,cb){

        return false;

    }

    processPost(req,res,service,cb){

        const data = req.body;
        const signatureOrig = req.headers['x-line-signature'];

        if(!signatureOrig)
            return false;

        if(!data.events)
            return false;

        if(data.events.length < 1)
            return false;

        const channelSecret = service.config.channelSecret;
        const body = req.rawBody; // Request body string

        const signatureGenerated = crypto.createHmac('SHA256', channelSecret).update(body).digest('base64');

        // process if signature is matched
        if(signatureGenerated == signatureOrig){

            // Iterate over each entry - there may be multiple if batched
            data.events.forEach((event) => {

                if(event.type == 'message'){

                    if(cb){
                        cb(
                            Const.eventTypeMessage,
                            this.generateMessageObj(service,event),
                            event
                        );
                    }

                }

                else if(event.type == 'follow'){

                    if(cb){
                        cb(
                            Const.eventTypeNewChat,
                            this.generateOpenChatObj(service,event),
                            data
                        );
                    }

                }

            });

            res.send('ok');

            return true;

        } else {

            this.logger.warn('Line wrong signature ' + signatureOrig + ' expected ' + signatureGenerated);

        }

        return false;

    }

    generateOpenChatObj(service,event){

        const messageObj = {
            userIdentifier:service.provider + ":" + service.identifier + ":" + event.source.userId,
            providerIdentifier:service.identifier,
            provider:service.provider,
            providerUserId:event.source.userId,
        };

        return messageObj;

    }

    generateMessageObj(service,event){

        const message = {
            userIdentifier:service.provider + ":" + service.identifier + ":" + event.source.userId,
            providerIdentifier:service.identifier,
            provider:service.provider,
            providerUserId:event.source.userId,
        };

        // detect type
        if(event.message.type == 'text'){
            message.content = {
                type: Const.messageTypeText,
                text: event.message.text
            }
        }

        if(event.message.type == 'image'){
            message.content = {
                type: Const.messageTypeImage,
                url: undefined,
                id:event.message.id
            }
        }

        if(event.message.type == 'video'){
            message.content = {
                type: Const.messageTypeVideo,
                url: undefined,
                id:event.message.id
            }
        }

        if(event.message.type == 'audio'){
            message.content = {
                type: Const.messageTypeAudio,
                url: undefined,
                id:event.message.id
            }
        }

        if(event.message.type == 'sticker'){
            message.content = {
                type: Const.messageTypeSticker,
                styckerId: event.message.stickerId
            }
        }

        if(event.message.type == 'location'){

            message.content = {
                type: Const.messageTypeLocation,
                address:event.message.address,
                coordinates: {
                    latitude: event.message.latitude,
                    longitude: event.message.longitude
                }
            }

        }

        return message;

    }

    replyText(text,responseObj,service,cb){

        return new Promise((resolve,reject) => {

            const client = new line.Client({
                channelAccessToken: service.config.channelAccessToken
            });

            const message = {
                type: 'text',
                text: text
            };

            client.replyMessage(responseObj.replyToken, message)

                .then((result) => {

                    resolve({
                        code:200,
                        body:result
                    });

                })
                .catch((err) => {

                    this.logger.warn('Line failed to send message',err);
                    reject();

            });

        });
    }

    sendText(text,userIdentifier,service,cb){

        return new Promise((resolve,reject) => {

            const userIdentifierChunks = userIdentifier.split(':');
            const provider = userIdentifierChunks[0];
            const serviceIdentifier = userIdentifierChunks[1];
            const userId = userIdentifierChunks[2];

            const client = new line.Client({
                channelAccessToken: service.config.channelAccessToken
            });

            const message = {
                type: 'text',
                text: text
            };

            client.pushMessage(userId, message)
            .then((result) => {

                resolve({
                    code:200,
                    body:result
                });

            })
            .catch((err) => {

                this.logger.warn('line failed to send message',err);
                reject();

            });

        });

    }

    downloadFile(response,path,service,cb){

        return new Promise((resolve,reject) => {

            if(!response ||
                !response.message ||
                !response.message.id ){

                    reject();

                    return;
            }

            let extension = "";

            if(response.message.type == 'image'){
                extension = ".jpg";
            }

            if(response.message.type == 'audio'){
                extension = ".m4a";
            }

            if(response.message.type == 'video'){
                extension = ".mp4";
            }

            const messageId = response.message.id;

            const client = new line.Client({
                channelAccessToken: service.config.channelAccessToken
            });

            let filename = this.generateFileName() + extension;
            const pathToDownload = path + "/" + filename;
            const file = fs.createWriteStream(pathToDownload);

            const stream = client.getMessageContent(messageId);
            stream.pipe(file);

            file.on('finish', function() {
                file.close(resolve(filename));
            });

        });

    }

    sendFile(fileId,userIdentifier,service,cb){

        return new Promise((resolve,reject) => {

            const config = service.config;
            const userIdentifierChunks = userIdentifier.split(':');
            const provider = userIdentifierChunks[0];
            const serviceIdentifier = userIdentifierChunks[1];
            const userId = userIdentifierChunks[2];

            const fileURL = this.config.baseURL + this.config.endpointURL + this.config.fileSenderURL + "/" + fileId;

            // get file type
            let typeTest = mime.lookup(fileId);
            let type = "";

            if(/image/.test(typeTest)){

                const fileNameChunk = fileId.split(".");
                let thumbName = fileNameChunk[0] + "_thumb";
                if(fileNameChunk.length > 1)
                    thumbName += "." + fileNameChunk[1];

                easyimg.thumbnail({
                    src:this.config.downloadPath + "/" + fileId,
                    dst:this.config.downloadPath + "/" + thumbName,
                    width:240, height:240,
                    x:0, y:0
                }).then((file) => {

                    return doSend(userId,{
                        type:"image",
                        originalContentUrl:this.config.baseURL + this.config.endpointURL + this.config.fileSenderURL + "/" + fileId ,
                        previewImageUrl:this.config.baseURL + this.config.endpointURL + this.config.fileSenderURL + "/" + thumbName,
                    });

                }).then((result) => {

                    resolve({
                        code:200,
                        body:result
                    });

                }).catch((err) => {

                    this.logger.warn('Line failed to send message',err);
                    reject();

                });

            }
            if(/video/.test(typeTest)){
                type = 'video'

                const fileNameChunk = fileId.split(".");
                let thumbName = fileNameChunk[0] + "_thumb";
                if(fileNameChunk.length > 1)
                    thumbName += ".jpg";

                Thumbler({
                    type: 'video',
                    input: this.config.downloadPath + "/" + fileId,
                    output: this.config.downloadPath + "/" + thumbName,
                    time: '00:00:00'
                }, (err, path) => {

                    if (err) {
                        this.logger.warn('Line failed to generate thumbnail',err);
                        return;
                    };

                    doSend(userId,{
                        type:"video",
                        originalContentUrl:this.config.baseURL + this.config.endpointURL + this.config.fileSenderURL + "/" + fileId ,
                        previewImageUrl:this.config.baseURL + this.config.endpointURL + this.config.fileSenderURL + "/" + thumbName,
                    }).then((result) => {

                        resolve({
                            code:200,
                            body:result
                        });

                    }).catch((err) => {

                        this.logger.warn('Line failed to send message',err);
                        reject();

                    });

                });

            }

            if(/audio/.test(typeTest)){
                type = 'audio'

                const readStream = fs.createReadStream(this.config.downloadPath + "/" + fileId);

                mm.parseFile(this.config.downloadPath + "/" + fileId, {native: true})
                    .then((metadata) => {

                        return doSend(userId,{
                            type:"audio",
                            originalContentUrl:this.config.baseURL + this.config.endpointURL + this.config.fileSenderURL + "/" + fileId ,
                            duration:metadata.format.duration * 1000
                        });

                    })
                    .then((result) => {

                        resolve({
                            code:200,
                            body:result
                        });

                    }).catch((err) => {

                        this.logger.warn('Line failed to send message',err);
                        reject();

                });

            }

            function doSend(userId,message) {

                const client = new line.Client({
                    channelAccessToken: service.config.channelAccessToken
                });

                return client.pushMessage(userId, message);

            }

        });

    }

    sendLocation(userIdentifier,coordinate,service){

        return new Promise((resolve,reject) => {

            this.logger.debug('Line location message sending start');

            const userIdentifierChunks = userIdentifier.split(':');
            const provider = userIdentifierChunks[0];
            const serviceIdentifier = userIdentifierChunks[1];
            const userId = userIdentifierChunks[2];

            const client = new line.Client({
                channelAccessToken: service.config.channelAccessToken
            });

            const message = {
                type: 'location',
                title: 'Location',
                address: coordinate.address,
                latitude: coordinate.latitude,
                longitude: coordinate.longitude
            };

            this.logger.debug('Line location message sending',message);

            client.pushMessage(userId, message)

                .then((result) => {

                    this.logger.debug('Line location message sent',result);

                    resolve({
                        code:200,
                        body:result
                    });

                })
                .catch((err) => {

                    this.logger.warn('Line failed to send message',err);
                    reject();

            });

        });

    }

}

module["exports"] = LineAdapter;


text:
"use strict";

module.exports = function(Chart) {

	var helpers = Chart.helpers,
		globalOpts = Chart.defaults.global;

	globalOpts.elements.rectangle = {
		backgroundColor: globalOpts.defaultColor,
		borderWidth: 0,
		borderColor: globalOpts.defaultColor,
		borderSkipped: 'bottom'
	};

	Chart.elements.Rectangle = Chart.Element.extend({
		draw: function() {
			var ctx = this._chart.ctx;
			var vm = this._view;

			var halfWidth = vm.width / 2,
				leftX = vm.x - halfWidth,
				rightX = vm.x + halfWidth,
				top = vm.base - (vm.base - vm.y),
				halfStroke = vm.borderWidth / 2;

			// Canvas doesn't allow us to stroke inside the width so we can
			// adjust the sizes to fit if we're setting a stroke on the line
			if (vm.borderWidth) {
				leftX += halfStroke;
				rightX -= halfStroke;
				top += halfStroke;
			}

			ctx.beginPath();
			ctx.fillStyle = vm.backgroundColor;
			ctx.strokeStyle = vm.borderColor;
			ctx.lineWidth = vm.borderWidth;

			// Corner points, from bottom-left to bottom-right clockwise
			// | 1 2 |
			// | 0 3 |
			var corners = [
				[leftX, vm.base],
				[leftX, top],
				[rightX, top],
				[rightX, vm.base]
			];

			// Find first (starting) corner with fallback to 'bottom'
			var borders = ['bottom', 'left', 'top', 'right'];
			var startCorner = borders.indexOf(vm.borderSkipped, 0);
			if (startCorner === -1)
				startCorner = 0;

			function cornerAt(index) {
				return corners[(startCorner + index) % 4];
			}

			// Draw rectangle from 'startCorner'
			ctx.moveTo.apply(ctx, cornerAt(0));
			for (var i = 1; i < 4; i++)
				ctx.lineTo.apply(ctx, cornerAt(i));

			ctx.fill();
			if (vm.borderWidth) {
				ctx.stroke();
			}
		},
		height: function() {
			var vm = this._view;
			return vm.base - vm.y;
		},
		inRange: function(mouseX, mouseY) {
			var vm = this._view;
			return vm ?
					(vm.y < vm.base ?
						(mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base) :
						(mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y)) :
					false;
		},
		inLabelRange: function(mouseX) {
			var vm = this._view;
			return vm ? (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) : false;
		},
		tooltipPosition: function() {
			var vm = this._view;
			return {
				x: vm.x,
				y: vm.y
			};
		}
	});

};


text:
package com.riversoft.weixin.mp.care.bean;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Created by exizhai on 11/23/2015.
 */
public class Video {

    @JsonProperty("media_id")
    private String mediaId;

    @JsonProperty("thumb_media_id")
    private String thumbMediaId;

    private String title;

    private String description;

    public String getMediaId() {
        return mediaId;
    }

    public void setMediaId(String mediaId) {
        this.mediaId = mediaId;
    }

    public String getThumbMediaId() {
        return thumbMediaId;
    }

    public void setThumbMediaId(String thumbMediaId) {
        this.thumbMediaId = thumbMediaId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Video mediaId(String mediaId) {
        this.mediaId = mediaId;
        return this;
    }

    public Video thumbMediaId(String thumbMediaId) {
        this.thumbMediaId = thumbMediaId;
        return this;
    }

    public Video title(String title) {
        this.title = title;
        return this;
    }

    public Video description(String description) {
        this.description = description;
        return this;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/guide_concise" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:text="便捷"
            android:textSize="30sp" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_start"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="50dp"
        android:background="@drawable/button_bg"
        android:text="进入主页"
        android:textColor="@android:color/white" />

</RelativeLayout>


text:
package org.oscm.domobjects;

import java.util.*;

import javax.persistence.*;

import org.apache.lucene.analysis.core.LowerCaseFilterFactory;
import org.apache.lucene.analysis.core.WhitespaceTokenizerFactory;
import org.apache.lucene.analysis.de.GermanStemFilterFactory;
import org.apache.lucene.analysis.miscellaneous.WordDelimiterFilterFactory;
import org.apache.lucene.analysis.snowball.SnowballPorterFilterFactory;
import org.hibernate.search.annotations.*;
import org.hibernate.search.annotations.Parameter;
import org.oscm.domobjects.annotations.BusinessKey;
import org.oscm.domobjects.bridge.ProductClassBridge;
import org.oscm.domobjects.enums.LocalizedObjectTypes;
import org.oscm.interceptor.DateFactory;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.enumtypes.ServiceType;
import org.oscm.logging.Log4jLogger;
import org.oscm.logging.LoggerFactory;
import org.oscm.types.enumtypes.LogMessageIdentifier;

/**
 * What is offered on the SaaS platform to the market is called a "product". A
 * product consists of one or more technical products and a pricing model. One
 * technical product can be offered in several (market) products, with different
 * pricing models and different license conditions and capability
 * characteristics (Leistungsmerkmalen). In most cases a product will contain
 * just one technical product. However, the platform should also allow the
 * creation of product bundles consisting of multiple technical products, but
 * with one pricing model.
 *
 * @author schmid
 */
@Entity
@Indexed
@ClassBridge(impl = ProductClassBridge.class)
@AnalyzerDefs({
        @AnalyzerDef(name = "en", tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class),
            filters
            = {
                @TokenFilterDef(factory = WordDelimiterFilterFactory.class, params = {
                        @Parameter(name = "preserveOriginal", value = "1"),
                        @Parameter(name = "catenateAll", value = "1") }),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class)}),
        @AnalyzerDef(name = "de", tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class), filters = {
                @TokenFilterDef(factory = WordDelimiterFilterFactory.class, params = {
                        @Parameter(name = "preserveOriginal", value = "1"),
                        @Parameter(name = "catenateAll", value = "1") }),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class)}), })
@AnalyzerDiscriminator(impl = ProductClassBridge.class)
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "productId",
        "vendorKey" }))
@NamedQueries({
        @NamedQuery(name = "Product.findByBusinessKey", query = "select p from Product p where p.dataContainer.productId=:productId and p.vendorKey=:vendorKey"),
        @NamedQuery(name = "Product.getCustomerSpecificCopiesForTemplate", query = "SELECT p FROM Product p WHERE p.template =:template AND p.dataContainer.type IN (:serviceType) AND p.targetCustomer IS NOT NULL ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductsForVendor", query = "SELECT p FROM Product p WHERE p.vendorKey=:vendorKey AND p.dataContainer.status NOT IN (:filterOutWithStatus) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductCopyForVendor", query = "SELECT p FROM Product p WHERE p.vendorKey=:vendorKey AND p.template=:product AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) AND p.targetCustomer IS NULL ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getPartnerSpecificCopiesForVendor", query = "SELECT p FROM Product p WHERE p.vendorKey=:vendorKey AND p.dataContainer.status IN (:status) AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getPartnerCopiesForTemplate", query = "SELECT p FROM Product p WHERE p.template =:template AND p.targetCustomer IS NULL AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getPartnerCopiesForTemplateNotInState", query = "SELECT p FROM Product p WHERE p.template =:template AND p.dataContainer.status NOT IN (:statusToIgnore) AND p.targetCustomer IS NULL AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductTemplatesForVendor", query = "SELECT p FROM Product p WHERE p.vendorKey=:vendorKey AND p.dataContainer.type IN (:productTypes) AND p.dataContainer.status NOT IN (:filterOutWithStatus) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductsForVendorPaymentConfiguration", query = "SELECT p FROM Product p JOIN p.technicalProduct tp WHERE p.vendorKey=:vendorKey AND p.dataContainer.type IN (org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) AND p.dataContainer.status NOT IN (:statusToIgnore) AND tp.dataContainer.billingIdentifier='NATIVE_BILLING' ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductsForVendorOnMarketplace", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce WHERE p.vendorKey=:vendorKey AND p.dataContainer.type IN (org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) AND EXISTS (SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce.marketplace) AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductsForCustomerOnMarketplace", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce "
                + " WHERE (p.dataContainer.type IN (org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) AND EXISTS(SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce.marketplace)) "
                + "    OR (p.dataContainer.type = org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE AND p.targetCustomer = :customer AND EXISTS (SELECT template FROM Product template LEFT JOIN template.catalogEntries ce2 WHERE template.key = p.template.key AND EXISTS(SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce2.marketplace)) ) "
                + "ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getProductsForTemplateIndexUpdate", query = "SELECT p FROM Product p WHERE p.template =:template AND p.dataContainer.type IN (:type) AND p.dataContainer.status IN (:state) AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getTemplatesInAllStates", query = "SELECT p FROM Product p WHERE p.template IS NULL ORDER BY p.dataContainer.productId ASC"),
        @NamedQuery(name = "Product.getTemplatesForMarketplace", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce WHERE p.template IS NULL AND EXISTS (SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce.marketplace)) AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getRelatedProductsForMarketplace", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce WHERE (p.targetCustomer = :customer OR (p.template IS NULL AND EXISTS (SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce.marketplace))) AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) AND p.technicalProduct=:technicalProduct AND p.vendor=:vendor ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getRelatedPublicProductsForMarketplace", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce WHERE (p.template IS NULL AND EXISTS (SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce.marketplace)) AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) AND p.technicalProduct=:technicalProduct AND ce.dataContainer.anonymousVisible=TRUE AND p.vendor=:vendor ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getPublicProductsForMarketplace", query = "SELECT p FROM Product p, CatalogEntry c WHERE p.template IS NULL AND p.dataContainer.status = org.oscm.internal.types.enumtypes.ServiceStatus.ACTIVE AND c.marketplace = :marketplace AND c.product = p AND c.dataContainer.anonymousVisible=TRUE ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getActiveProductsForMarketplace", query = "SELECT ce FROM Product p INNER JOIN p.catalogEntries ce WHERE p.targetCustomer IS NULL AND (SELECT s from Subscription s WHERE p = s.product) IS NULL AND p.dataContainer.status = org.oscm.internal.types.enumtypes.ServiceStatus.ACTIVE AND p.technicalProduct=:technicalProduct AND p.vendorKey=:vendorKey"),
        @NamedQuery(name = "Product.getCustomerProductsForVendor", query = "select p from Product p where p.vendorKey=:vendorKey AND p.targetCustomer IS NOT NULL AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getCustomerSpecificProducts", query = "select p from Product p where p.vendorKey=:vendorKey AND p.template IS NOT NULL AND p.targetCustomer = :customer AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getSpecificCustomerProduct", query = "SELECT p FROM Product p WHERE p.template = :template AND p.targetCustomer = :customer AND p.dataContainer.type=org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getForCustomerAndTemplate", query = "SELECT prod FROM Product prod WHERE prod.targetCustomer = :customer AND prod.template = :template AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = prod) ORDER BY prod.key ASC"),
        @NamedQuery(name = "Product.getForTemplate", query = "SELECT prod FROM Product prod WHERE prod.template = :template AND EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = prod) ORDER BY prod.key ASC"),
        @NamedQuery(name = "Product.getForCustomerOnly", query = "select p from Product p where p.vendorKey=:vendorKey AND p.targetCustomer = :customer AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = p) ORDER BY p.key ASC"),
        @NamedQuery(name = "Product.getForCustomerAndSubId", query = "SELECT prod FROM Product prod, Subscription sub WHERE prod = sub.product AND sub.dataContainer.subscriptionId = :subscriptionId AND sub.organization = :customer"),
        @NamedQuery(name = "Product.getCustomerCopies", query = "SELECT prod FROM Product prod WHERE prod.template = :template AND prod.targetCustomer IS NOT NULL AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = prod) ORDER BY prod.key ASC"),
        @NamedQuery(name = "Product.countCustomerCopiesForTemplateInState", query = "SELECT COUNT(*) FROM Product prod WHERE prod.template = :template AND prod.dataContainer.status IN (:status) AND prod.targetCustomer IS NOT NULL AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = prod)"),
        @NamedQuery(name = "Product.countAllReferences", query = "SELECT COUNT(*) FROM ProductReference pr WHERE (pr.sourceProduct.key=:productKey AND pr.targetProduct.dataContainer.status NOT IN (:status)) OR (pr.targetProduct.key=:productKey AND pr.sourceProduct.dataContainer.status NOT IN (:status))"),
        @NamedQuery(name = "Product.getCopyForCustomer", query = "SELECT prod FROM Product prod WHERE prod.template = :template AND prod.targetCustomer = :customer AND NOT EXISTS (SELECT sub FROM Subscription sub WHERE sub.product = prod)"),
        @NamedQuery(name = "Product.getPotentialCompatibleForProduct", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce WHERE p.vendorKey=:vendorKey AND p.template IS NULL AND p.technicalProduct=:tp AND p.dataContainer.status NOT IN (:status) AND ce.marketplace IN (:marketplaces)"),
        @NamedQuery(name = "Product.getPublishedProductTemplates", query = "SELECT p FROM Product p INNER JOIN p.catalogEntries ce WHERE p.dataContainer.status NOT IN (:filterOutWithStatus) AND p.dataContainer.type IN (org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) AND ce.marketplace = :marketplace AND NOT EXISTS (SELECT lp FROM PublicLandingpage lp INNER JOIN lp.marketplace mp INNER JOIN lp.landingpageProducts lpp WHERE mp = :marketplace AND lpp.product = p)"),
        @NamedQuery(name = "Product.getActivePublishedProductTemplates", query = "SELECT p FROM Product p INNER JOIN p.catalogEntries ce"
                + " WHERE p.dataContainer.status = org.oscm.internal.types.enumtypes.ServiceStatus.ACTIVE"
                + " AND ce.dataContainer.visibleInCatalog=TRUE"
                + " AND ce.dataContainer.anonymousVisible=TRUE"
                + " AND p.dataContainer.type IN (org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE)"
                + " AND ce.marketplace.dataContainer.marketplaceId = :marketplaceId"
                + " AND NOT EXISTS (SELECT lp FROM LandingpageProduct lp WHERE lp.landingpage.marketplace.dataContainer.marketplaceId = :marketplaceId AND lp.product.key = p.key)"
                + " ORDER BY p.dataContainer.provisioningDate DESC"),
        @NamedQuery(name = "Product.getActivePublishedProducts", query = "SELECT p FROM Product p LEFT JOIN p.catalogEntries ce"
                + " WHERE NOT EXISTS (SELECT lp FROM LandingpageProduct lp WHERE lp.landingpage.marketplace.dataContainer.marketplaceId = :marketplaceId AND ((p.targetCustomer IS NULL AND lp.product = p) OR (p.targetCustomer = :customer AND lp.product = p.template)))"
                + " AND p.dataContainer.type IN (org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE, org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE)"
                + " AND ((EXISTS (SELECT m FROM Marketplace m WHERE m.dataContainer.marketplaceId = :marketplaceId AND m = ce.marketplace AND ce.dataContainer.visibleInCatalog=TRUE))"
                + "  OR (p.dataContainer.type = org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE AND p.targetCustomer = :customer AND EXISTS (SELECT ce1 FROM CatalogEntry ce1 WHERE ce1.marketplace.dataContainer.marketplaceId = :marketplaceId AND ce1.product = p.template AND ce1.dataContainer.visibleInCatalog=TRUE)))"
                + " AND NOT EXISTS (SELECT pr FROM Product pr WHERE pr.dataContainer.type = org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE AND pr.template = p AND pr.targetCustomer = :customer)"
                + " AND p.dataContainer.status = org.oscm.internal.types.enumtypes.ServiceStatus.ACTIVE"
                + " ORDER BY p.dataContainer.provisioningDate DESC") })
@BusinessKey(attributes = { "productId", "vendorKey" })
public class Product extends DomainObjectWithHistory<ProductData> {

    private static final long serialVersionUID = 4336379997821816252L;

    private static final List<LocalizedObjectTypes> LOCALIZATION_TYPES = Collections
            .unmodifiableList(Arrays.asList(
                    LocalizedObjectTypes.PRODUCT_MARKETING_DESC,
                    LocalizedObjectTypes.PRODUCT_MARKETING_NAME,
                    LocalizedObjectTypes.PRODUCT_SHORT_DESCRIPTION,
                    LocalizedObjectTypes.PRODUCT_CUSTOM_TAB_NAME));

    private static final transient Log4jLogger logger = LoggerFactory
            .getLogger(Product.class);

    public Product() {
        super();
        dataContainer = new ProductData();
    }

    /**
     * In order to form a complete business key the Organization key is needed
     * as explicit field inside this class. This field is also used as
     * JoinColumn for the n:1 relation to Organization.
     */
    @Column(name = "vendorKey", insertable = false, updatable = false, nullable = false)
    private long vendorKey;

    /**
     * n:1 relation to the organization the product belongs to, that is the
     * organization it was supplied by or a broker/reseller organization. Has to
     * be set, as each product must belong to exactly one organization.

     * CascadeType: NONE
     */
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "vendorKey")
    private Organization vendor;

    /**
     * 1:1 relation to the product's price model. Currently each product is
     * assigned to a fixed price model.

     * CascadeType: ALL
     */
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private PriceModel priceModel;

    /**
     * 1:1 relation to the product's parameter set. CascadeType: ALL
     */
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private ParameterSet parameterSet;

    /**
     * Reference to the technical product this marketing product is based on.
     */
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private TechnicalProduct technicalProduct;

    /**
     * References a relation to other products indicating supporting migration
     * paths for the product. The cascade type is set to REMOVE, to prevent
     * existence of orphan entries, and to PERSIST, so that the copying works.
     */
    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, mappedBy = "sourceProduct", fetch = FetchType.LAZY)
    @OrderBy
    private List<ProductReference> compatibleProducts = new ArrayList<ProductReference>();

    @OneToMany(cascade = CascadeType.REMOVE, mappedBy = "product", fetch = FetchType.LAZY)
    private List<UserGroupToInvisibleProduct> userGroupToInvisibleProducts = new ArrayList<UserGroupToInvisibleProduct>();

    /**
     * References a relation to other products indicating supporting migration
     * paths for the product. The cascade type is set to REMOVE, to prevent
     * existence of orphan entries, and to PERSIST, so that the copying works.
     * The member is used only for cascade delete on product deleting.
     */
    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, mappedBy = "targetProduct", fetch = FetchType.LAZY)
    @OrderBy
    private List<ProductReference> compatibleProductsTarget = new ArrayList<ProductReference>();

    /**
     * Reference to the parent product object, the current product is a copy of.
     * The copy is created to support subscription- or organization specific
     * settings in e.g. a price model.
     */
    @ManyToOne(optional = true, fetch = FetchType.LAZY)
    private Product template;

    /**
     * Reference to the subscription this (marketing) product has been created
     * for. When this field is set, the field {@link #template} has to be set as
     * well.
     */
    @OneToOne(optional = true, mappedBy = "product", fetch = FetchType.LAZY)
    private Subscription owningSubscription;

    @ManyToOne(optional = true, fetch = FetchType.LAZY)
    private Organization targetCustomer;

    /**
     * References to the catalog entries. A catalog entry defines how a product
     * is shown in the catalog.
     */
    @OneToMany(cascade = CascadeType.REMOVE, mappedBy = "product", fetch = FetchType.LAZY)
    private List<CatalogEntry> catalogEntries = new ArrayList<CatalogEntry>();

    /**
     * Reference to the user reviews for this product and to the average rating.
     * Should be null in case this product is a customer specific
     * product, because only a template product may receive reviews.
     */
    @OneToOne(cascade = CascadeType.REMOVE, optional = true, mappedBy = "product", fetch = FetchType.LAZY)
    private ProductFeedback productFeedback;

    /**
     * Reference to ProductToPaymentType entries.
     */
    @OneToMany(mappedBy = "product", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
    private List<ProductToPaymentType> paymentTypes = new ArrayList<ProductToPaymentType>();

    public List<ProductToPaymentType> getPaymentTypes() {
        return paymentTypes;
    }

    public void setPaymentTypes(List<ProductToPaymentType> paymentTypes) {
        this.paymentTypes = paymentTypes;
    }

    public void setVendor(Organization organization) {
        vendor = organization;
        if (organization != null) {
            setVendorKey(organization.getKey());
        }
    }

    public Organization getVendor() {
        return vendor;
    }

    public void setVendorKey(long organizationKey) {
        vendorKey = organizationKey;
    }

    public long getVendorKey() {
        return vendorKey;
    }

    /**
     * Sets the price model for this product and also updates the price model
     * parameter by setting its product reference to this product.
     *
     * @param priceModel
     *            The price model a reference to which has to be set.
     */
    public void setPriceModel(PriceModel priceModel) {
        this.priceModel = priceModel;
        if (priceModel != null) {
            priceModel.setProduct(this);
        }
    }

    public PriceModel getPriceModel() {
        return priceModel;
    }

    public void setParameterSet(ParameterSet parameterSet) {
        this.parameterSet = parameterSet;
        if (parameterSet != null) {
            parameterSet.setProduct(this);
        }
    }

    public ParameterSet getParameterSet() {
        return parameterSet;
    }

    /**
     * Refer to {@link ProductData#deprovisioningDate}
     */
    public Long getDeprovisioningDate() {
        return dataContainer.getDeprovisioningDate();
    }

    /**
     * Refer to {@link ProductData#deprovisioningDate}
     */
    public void setDeprovisioningDate(Long deprovisioningDate) {
        dataContainer.setDeprovisioningDate(deprovisioningDate);
    }

    /**
     * Refer to {@link ProductData#productId}
     */
    public String getProductId() {
        return dataContainer.getProductId();
    }

    /**
     * Refer to {@link ProductData#productId}
     */
    public void setProductId(String productId) {
        dataContainer.setProductId(productId);
    }

    /**
     * Refer to {@link ProductData#provisioningDate}
     */
    public long getProvisioningDate() {
        return dataContainer.getProvisioningDate();
    }

    /**
     * Refer to {@link ProductData#provisioningDate}
     */
    public void setProvisioningDate(long provisioningDate) {
        dataContainer.setProvisioningDate(provisioningDate);
    }

    /**
     * Refer to {@link ProductData#status}
     */
    public ServiceStatus getStatus() {
        return dataContainer.getStatus();
    }

    /**
     * Refer to {@link ProductData#status}
     */
    public void setStatus(ServiceStatus status) {
        dataContainer.setStatus(status);
    }

    public ServiceType getType() {
        return dataContainer.getType();
    }

    public void setType(ServiceType type) {
        dataContainer.setType(type);
    }

    public TechnicalProduct getTechnicalProduct() {
        return technicalProduct;
    }

    public void setTechnicalProduct(TechnicalProduct technicalProduct) {
        this.technicalProduct = technicalProduct;
    }

    public Boolean isAutoAssignUserEnabled() {
        if (this.getType() == org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) {
            return getTemplate().getDataContainer().isAutoAssignUserEnabled();
        } else {
            return this.getDataContainer().isAutoAssignUserEnabled();
        }
    }

    public void setAutoAssignUserEnabled(Boolean autoAssignUserEnabled) {
        dataContainer.setAutoAssignUserEnabled(autoAssignUserEnabled);
    }

    public String getConfiguratorUrl() {
        return dataContainer.getConfiguratorUrl();
    }

    public void setConfiguratorUrl(String configuratorUrl) {
        dataContainer.setConfiguratorUrl(configuratorUrl);
    }

    public String getCustomTabUrl() {
        return dataContainer.getCustomTabUrl();
    }

    public void setCustomTabUrl(String customTabUrl) {
        dataContainer.setCustomTabUrl(customTabUrl);
    }

    public List<Product> getCompatibleProductsList() {
        Product templ = getType() == org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE ? null
                : getTemplate();
        if (templ != null) {
            return templ.getCompatibleProductsList();
        }
        List<Product> result = new ArrayList<Product>(compatibleProducts.size());
        for (ProductReference ref : compatibleProducts) {
            result.add(ref.getTargetProduct());
        }
        return result;
    }

    /**
     * Returns all product references for the current product. It does also
     * return all product references related to the template, in case the
     * product is a copy itself.
     *
     * @return The list of products the current product can be migrated to.
     */
    public List<ProductReference> getAllCompatibleProducts() {
        Product templ = getType() == org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE ? null
                : getTemplate();
        if (templ != null) {
            return templ.getAllCompatibleProducts();
        }
        return compatibleProducts;
    }

    /**
     * Returns all product references for the current product. It does not
     * consider references stored for the template.
     *
     * @return The list of compatible products stored for this product.
     */
    public List<ProductReference> getCompatibleProducts() {
        return compatibleProducts;
    }

    public Product getTemplate() {
        return template;
    }

    public void setTemplate(Product template) {
        this.template = template;
    }

    public Subscription getOwningSubscription() {
        return owningSubscription;
    }

    public void setOwningSubscription(Subscription owningSubscription) {
        this.owningSubscription = owningSubscription;
    }

    public Organization getTargetCustomer() {
        return targetCustomer;
    }

    public void setTargetCustomer(Organization targetOrganization) {
        targetCustomer = targetOrganization;
    }

    /**
     * Returns a copy of this product keeping all references except the
     *

     *
PriceModel reference

     *
ParameterSet reference

     *

     * Those objects are copied themselves, so that a new marketing product can
     * be based on the returned copy.
     *
     *

     * Furthermore the deprovisioning date will be set to null, the provisioning
     * date to the max value of the current time and the provisioning date of
     * this product.
     *

     *
     * @param targetCustomer
     *            The customer this copy is created and will be used for.
     * @param owningSubscription
     *            The subscription the copy is made and will be used for.
     *
     * @return A copy of the current product.
     */
    public Product copyForSubscription(Organization targetCustomer,
            Subscription owningSubscription) {

        Product copy = new Product();
        copy.setDataContainer(new ProductData());

        setSubscriptionProductType(copy);
        copy.setStatus(this.getStatus());
        copy.setTemplate(getTemplateIfSubscriptionOrSelf());
        copy.setTargetCustomer(targetCustomer);
        copy.setOwningSubscription(owningSubscription);
        copy.setVendor(this.getVendor());
        copy.setTechnicalProduct(this.getTechnicalProduct());

        setDatacontainerValues(copy, copy.getType());

        setParamatersAndPriceModel(copy);

        return copy;
    }

    void setParamatersAndPriceModel(Product copy) {
        ParameterSet parameterSet = getParameterSet();
        if (parameterSet == null && getType() == org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) {
            parameterSet = getTemplate().getParameterSet();
        }

        if (parameterSet != null) {
            copy.setParameterSet(parameterSet.copy());
        }

        PriceModel pm = getPriceModel();
        if (pm == null && getType() == org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE) {
            pm = getTemplate().getPriceModel();
        }

        if (pm != null) {
            PriceModel pmCopy = pm.copy(copy.getParameterSet());
            copy.setPriceModel(pmCopy);
        }
    }

    void setSubscriptionProductType(Product subscriptionCopy) {
        if (this.getType() == null) {
            logger.logWarn(Log4jLogger.SYSTEM_LOG, new Exception(
                    "setSubscriptionProductType, type==null"),
                    LogMessageIdentifier.DEBUG);
            return;
        }
        switch (this.getType()) {
        case TEMPLATE:
            subscriptionCopy.setType(org.oscm.internal.types.enumtypes.ServiceType.SUBSCRIPTION);
            break;
        case CUSTOMER_TEMPLATE:
            subscriptionCopy.setType(org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_SUBSCRIPTION);
            break;
        case PARTNER_TEMPLATE:
            subscriptionCopy.setType(org.oscm.internal.types.enumtypes.ServiceType.PARTNER_SUBSCRIPTION);
            break;
        case SUBSCRIPTION:
            subscriptionCopy.setType(org.oscm.internal.types.enumtypes.ServiceType.SUBSCRIPTION);
            break;
        case CUSTOMER_SUBSCRIPTION:
            subscriptionCopy.setType(org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_SUBSCRIPTION);
            break;
        case PARTNER_SUBSCRIPTION:
            subscriptionCopy.setType(org.oscm.internal.types.enumtypes.ServiceType.PARTNER_SUBSCRIPTION);
            break;
        }
    }

    /**
     * Returns a template copy of this product keeping all references except the
     *

     *
PriceModel reference

     *
ParameterSet reference

     *

     * Those objects are copied themselves, so that a new marketing product can
     * be based on the returned copy.
     *
     *

     * Furthermore the deprovisioning date will be set to null, the provisioning
     * date to the max value of the current time and the provisioning date of
     * this product.
     *

     *
     * @param productId
     *            The productId for the copy.
     *
     * @return A copy of the current product.
     */
    public Product copyTemplate(String productId) {

        Product copy = new Product();
        copy.setDataContainer(new ProductData());

        copy.setType(org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE);
        copy.setStatus(ServiceStatus.INACTIVE);
        copy.setTemplate(null);
        copy.setTargetCustomer(null);
        copy.setOwningSubscription(null);
        copy.setTechnicalProduct(this.getTechnicalProduct());
        copy.setVendor(this.getVendor());
        copy.setProductFeedback(null);

        setDatacontainerValues(copy, org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE);

        // overwrite
        copy.setProductId(productId);
        setParamatersAndPriceModel(copy);

        return copy;
    }

    /**
     * Returns a copy of this product keeping all references except the
     *

     *
PriceModel reference

     *
ParameterSet reference

     *

     * Those objects are copied themselves, so that a new marketing product can
     * be based on the returned copy.
     *
     *

     * Furthermore the deprovisioning date will be set to null, the provisioning
     * date to the max value of the current time and the provisioning date of
     * this product.
     *

     *
     * @param targetCustomer
     *            The customer this copy is created and will be used for.
     * @return A copy of the current product.
     */
    public Product copyForCustomer(Organization targetCustomer) {

        Product copy = new Product();
        copy.setDataContainer(new ProductData());

        copy.setType(org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE);
        copy.setStatus(ServiceStatus.INACTIVE);
        copy.setOwningSubscription(null);
        copy.setTargetCustomer(targetCustomer);
        copy.setVendor(this.getVendor());
        copy.setTechnicalProduct(this.getTechnicalProduct());
        copy.setTemplate(getTemplateOrSelf());

        setDatacontainerValues(copy, org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE);

        setParamatersAndPriceModel(copy);

        return copy;
    }

    void setDatacontainerValues(Product copy, ServiceType serviceType) {
        copy.setDeprovisioningDate(null);
        copy.setProvisioningDate(Math.max(DateFactory.getInstance()
                .getTransactionTime(), this.getProvisioningDate()));
        copy.setProductId(getTemplateOrSelf().getProductId() + "#"
                + UUID.randomUUID());
        copy.setAutoAssignUserEnabled(this.isAutoAssignUserEnabled());
        if (serviceType == org.oscm.internal.types.enumtypes.ServiceType.TEMPLATE) {
            copy.setConfiguratorUrl(this.getConfiguratorUrl());
        } else {
            copy.setConfiguratorUrl(null);
        }
        copy.setCustomTabUrl(this.getCustomTabUrl());

    }

    /**
     * Copies a product for resale. All references are kept except the
     *

     *
PriceModel reference

     *
ParameterSet reference

     *

     * The PriceModel reference is set to null. The ParameterSet is copied, so
     * that a new marketing product can be based on the returned copy.
     *
     *

     * Furthermore the deprovisioning date will be set to null, the provisioning
     * date to the max value of the current time and the provisioning date of
     * this product.
     *

     *
     * @param vendor
     *            The vendor (broker or reseller) this copy is created and will
     *            be used for.
     *
     * @return A copy of the current product.
     */
    public Product copyForResale(Organization vendor) {

        Product copy = new Product();
        copy.setDataContainer(new ProductData());

        copy.setType(org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE);
        copy.setStatus(this.getStatus());
        copy.setVendor(vendor);
        copy.setTechnicalProduct(this.getTechnicalProduct());

        // Price model and parameters can only be modified by the supplier.
        // Thus they are not stored in the resale copy but in the template.
        copy.setPriceModel(null);
        copy.setParameterSet(null);
        copy.setConfiguratorUrl(null);
        copy.setCustomTabUrl(null);

        setDatacontainerValues(copy, org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE);
        copy.setAutoAssignUserEnabled(null);
        // to set the template, ensure that this object is not a copy itself. If
        // it is, set it's parent!
        copy.setTemplate(getTemplateOrSelf());

        return copy;
    }

    /**
     *
     * @return true if and only if the status of the product is
     *         ServiceStatus.DELETED or ServiceStatus.OBSOLETE
     */
    public boolean isDeleted() {
        return getStatus() == ServiceStatus.DELETED
                || getStatus() == ServiceStatus.OBSOLETE;
    }

    /**
     * Setter for compatibleProductsTarget. protected for not using. The member
     * is used only for cascade delete on product deleting.
     *
     * @param compatibleProductsTarget
     *            List of compatible products.
     */
    protected void setCompatibleProductsTarget(
            List<ProductReference> compatibleProductsTarget) {
        this.compatibleProductsTarget = compatibleProductsTarget;
    }

    /**
     * Getter for compatibleProductsTarget. The member is used only for cascade
     * delete on product deleting.
     *
     * @return List of compatible products.
     */
    public List<ProductReference> getCompatibleProductsTarget() {
        return compatibleProductsTarget;
    }

    /**
     * Sets the catalog entries which are representing this product.
     *
     * @param catalogEntries
     *            the catalog entries
     */
    public void setCatalogEntries(List<CatalogEntry> catalogEntries) {
        this.catalogEntries = catalogEntries;
    }

    /**
     * Returns the catalog entries which are representing this product.
     *
     * @return the catalog entries
     */
    public List<CatalogEntry> getCatalogEntries() {
        return catalogEntries;
    }

    public List<UserGroupToInvisibleProduct> getUserGroupToInvisibleProducts() {
        return userGroupToInvisibleProducts;
    }

    public void setUserGroupToInvisibleProducts(
            List<UserGroupToInvisibleProduct> userGroupToInvisibleProducts) {
        this.userGroupToInvisibleProducts = userGroupToInvisibleProducts;
    }

    /**
     * Returns the catalog entry for the marketplace identified by the passed
     * marketplace object. Returns null if no entry exists.
     *
     * @param marketplace
     * @return the catalog entry
     */
    public CatalogEntry getCatalogEntryForMarketplace(Marketplace marketplace) {
        if (marketplace == null) {
            return null;
        }

        CatalogEntry catalogEntry = null;
        List<CatalogEntry> cEntries = getCatalogEntries();
        if (cEntries != null) {
            for (CatalogEntry ce : cEntries) {
                Marketplace mp = ce.getMarketplace();
                if ((mp != null)
                        && (marketplace.getMarketplaceId().equals(mp
                                .getMarketplaceId()))) {
                    catalogEntry = ce;
                    break;
                }
            }
        }
        return catalogEntry;
    }

    public ProductFeedback getProductFeedback() {
        return productFeedback;
    }

    public void setProductFeedback(ProductFeedback productFeedback) {
        this.productFeedback = productFeedback;
    }

    /**
     * Returns the template or if no template exists it returns itself.
     *
     * @return Product
     */
    public Product getTemplateOrSelf() {
        if (isCopy()) {
            return getTemplate();
        }
        return this;
    }

    public Product getTemplateOrSelfForReview() {
        if (this.getType().name().equals(ServiceType.PARTNER_TEMPLATE.name())) {
            return this;
        }
        if (isCopy()) {
            return getTemplate();
        }
        return this;
    }

    /**
     * Returns itself in case this is a template product or a re-sale copy,
     * otherwise the template of this product is returned.
     *
     * @return Product
     */
    public Product getTemplateIfSubscriptionOrSelf() {
        if (targetCustomer == null && owningSubscription == null) {
            return this;
        }
        return getTemplate();
    }

    /**
     * Determine the charging organization of this product. The charging
     * organization is a organization of type SUPPLIER or RESELLER.
     *
     * @return Organization
     */
    public Organization determineChargingOrganization() {
        Organization vendor = getVendor();
        if (vendor.getGrantedRoleTypes()
                .contains(OrganizationRoleType.SUPPLIER)
                || vendor.getGrantedRoleTypes().contains(
                        OrganizationRoleType.RESELLER)) {
            return vendor;
        } else if (vendor.getGrantedRoleTypes().contains(
                OrganizationRoleType.BROKER)) {
            return getProductTemplate().getVendor();
        } else {
            return null;
        }
    }

    /**
     * Returns the product template. If the product is a partner template, the
     * original product template is returned.
     *
     * @return
     */
    public Product getProductTemplate() {
        if (isCopy()) {
            return getTemplate().getProductTemplate();
        } else {
            return this;
        }
    }

    /**
     * Returns true if this product is a copy of a template product.
     *
     * @return boolean
     */
    public boolean isCopy() {
        if (getTemplate() != null && !getTemplate().equals(this)) {
            return true;
        }
        return false;
    }

    /**
     * Checks if the given user is allowed to either create a new review or
     * update is own review.
     *
     * @return boolean
     */
    public boolean isAllowedToWriteReview(PlatformUser user) {
        return isAllowedToCreateReview(user)
                || isAllowedToUpdateOwnReview(user);
    }

    /**
     * The given user is allowed to review the product only in one of the two
     * cases:

     * 1. Its technical product has 'EXTERNAL' access type, or

     * 2. The organization the user belongs to has at least one subscription and
     * the current user has a usage license or is administrator
     */
    public boolean isAllowedToCreateReview(PlatformUser user) {
        if (isExtenalService()) {
            return true;
        }

        Organization org = user.getOrganization();
        List<Subscription> subscriptions = org
                .getUsableSubscriptionsForProduct(this);
        if (subscriptions.isEmpty()) {
            return false;
        }
        if (user.isOrganizationAdmin()) {
            return true;
        }
        for (Subscription subscription : subscriptions) {
            if (subscription.getUsageLicenseForUser(user) != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * Its technical product has 'EXTERNAL' access type or not
     */
    public boolean isExtenalService() {
        if (ServiceAccessType.EXTERNAL.equals(getTechnicalProduct()
                .getAccessType())) {
            return true;
        }
        return false;
    }

    /**
     * Checks if the given user has written a review. In this case he is allowed
     * to update his own review.
     *
     * @param user
     * @return boolean
     */
    public boolean isAllowedToUpdateOwnReview(PlatformUser user) {
        if (getProductFeedback() == null) {
            return false;
        }
        return getProductFeedback().hasReview(user);
    }

    /**
     * If the product id contains a '#' the part before will be returned.
     */
    public String getCleanProductId() {
        return dataContainer.getCleanProductId();
    }

    @Override
    public List<LocalizedObjectTypes> getLocalizedObjectTypes() {
        return LOCALIZATION_TYPES;
    }

    /**
     * In case this is a customer specific or subscription copy, its template
     * or, if the template is a broker copy, its template's template will be
     * returned.
     *
     * @return the supplier or reseller template
     */
    public Product getSupplierOrResellerTemplate() {
        Product prod = this;
        if (prod.getType() == org.oscm.internal.types.enumtypes.ServiceType.CUSTOMER_TEMPLATE
                || org.oscm.internal.types.enumtypes.ServiceType.isSubscription(prod.getType())) {
            prod = prod.getTemplate();
        }
        if (prod.getType() == org.oscm.internal.types.enumtypes.ServiceType.PARTNER_TEMPLATE
                && prod.getVendor().getGrantedRoleTypes()
                        .contains(OrganizationRoleType.BROKER)) {
            prod = prod.getTemplate();
        }
        return prod;
    }
}


text:
$TLab_PluginName_MaterialEditor = "Material Editor";
//==============================================================================
function initMaterialEditor() {
	info( "TorqueLab","->","Initializing Material Editor");
	execMEP(true);
	//exec("./gui/profiles.ed.cs");
	$MatEd = newScriptObject("MatEd");
	//Lab.createPlugin("MaterialEditor","Material Editor");
	MaterialEditorPlugin.superClass = "WEditorPlugin";
	Lab.addPluginGui("MaterialEditor",MaterialEditorTools); //Tools renamed to Gui to store stuff
	Lab.addPluginDlg("MaterialEditor",matEd_cubemapEditor);
	Lab.addPluginDlg("MaterialEditor",matEd_addCubemapWindow);
	Lab.addPluginDlg("MaterialEditor",MaterialEditorDialogs);
	Lab.addPluginToolbar("MaterialEditor",MaterialEditorToolbar);
	new PersistenceManager(matEd_PersistMan);

}
//------------------------------------------------------------------------------
//==============================================================================
function execMEP(%loadGui) {
	if (%loadGui) {
		// Load MaterialEditor Guis
		exec("tlab/materialEditor/gui/matEd_cubemapEditor.gui");
		exec("tlab/materialEditor/gui/matEd_addCubemapWindow.gui");
		exec("tlab/materialEditor/gui/matEdNonModalGroup.gui");
		exec("tlab/materialEditor/gui/MaterialEditorToolbar.gui");
		exec("tlab/materialEditor/gui/MaterialEditorTools.gui");
		exec("tlab/materialEditor/gui/MaterialEditorDialogs.gui");

	}

	// Load Client Scripts.
	exec("./MaterialEditorPlugin.cs");
	execPattern("tlab/materialEditor/scripts/*.cs");
	execPattern("tlab/materialEditor/scene/*.cs");
	execPattern("tlab/materialEditor/material/*.cs");
	execPattern("tlab/materialEditor/guiScripts/*.cs");
}
//==============================================================================
function destroyMaterialEditor() {
}
//------------------------------------------------------------------------------


text:
<?php
namespace Spot;

/**
 * Logging class for all query activity
 *
 * @package Spot
 * @link http://spot.os.ly
 */
class Log
{
	protected static $_queries = array();
	protected static $_queryCount = 0;

	/**
	 * Add query to log
	 *
	 * @param Spot_Adpater_Interface Instance of adapter used to generate the query
	 * @param mixed $query Query run
	 * @param mixed $data Data used in query - usually array, but can be scalar or null
	 */
	public static function addQuery($adapter, $query, $data = null)
	{
		self::$_queries[] = array(
			'adapter' => get_class($adapter),
			'query' => $query,
			'data' => $data
			);
		self::$_queryCount++;
	}

	/**
	 * Get full query log
	 *
	 * @return array Queries that have been executed and all data that has been passed with them
	 */
	public static function queries()
	{
		return self::$_queries;
	}

	/**
	 * Get last query run from log
	 *
	 * @return array Queries that have been executed and all data that has been passed with them
	 */
	public static function lastQuery()
	{
		return end(self::$_queries);
	}

	/**
	 * Get a count of how many queries have been run
	 *
	 * @return int Total number of queries that have been run
	 */
	public static function queryCount()
	{
		return self::$_queryCount;
	}
}


text:
<?php

namespace Magento\Shipping\Test\Unit\Model\Shipping;

use Magento\Framework\DataObject;
use Magento\Sales\Model\Order\Shipment;
use Magento\Store\Model\ScopeInterface;

/**
 * Class LabelGeneratorTest
 *
 * Test class for \Magento\Shipping\Model\Shipping\LabelGenerator
 */
class LabelGeneratorTest extends \PHPUnit_Framework_TestCase
{
    const CARRIER_CODE = 'fedex';

    const CARRIER_TITLE = 'Fedex carrier';

    /**
     * @var \Magento\Shipping\Model\CarrierFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    private $carrierFactory;

    /**
     * @var \Magento\Shipping\Model\Shipping\LabelsFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    private $labelsFactory;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private $scopeConfig;

    /**
     * @var \Magento\Sales\Model\Order\Shipment\TrackFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    private $trackFactory;

    /**
     * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject
     */
    private $filesystem;

    /**
     * @var \Magento\Shipping\Model\Shipping\LabelGenerator
     */
    private $labelGenerator;

    protected function setUp()
    {
        $this->carrierFactory = $this->getMockBuilder('Magento\Shipping\Model\CarrierFactory')
            ->disableOriginalConstructor()
            ->getMock();
        $this->labelsFactory = $this->getMockBuilder('Magento\Shipping\Model\Shipping\LabelsFactory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();
        $this->scopeConfig = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface');
        $this->trackFactory = $this->getMockBuilder('Magento\Sales\Model\Order\Shipment\TrackFactory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();
        $this->filesystem = $this->getMockBuilder('Magento\Framework\Filesystem')
            ->disableOriginalConstructor()
            ->getMock();

        $this->labelGenerator = new \Magento\Shipping\Model\Shipping\LabelGenerator(
            $this->carrierFactory,
            $this->labelsFactory,
            $this->scopeConfig,
            $this->trackFactory,
            $this->filesystem
        );
    }

    /**
     * @covers \Magento\Shipping\Model\Shipping\LabelGenerator
     * @param array $info
     * @dataProvider labelInfoDataProvider
     */
    public function testAddTrackingNumbersToShipment(array $info)
    {
        $order = $this->getMockBuilder('Magento\Sales\Model\Order')
            ->disableOriginalConstructor()
            ->getMock();
        $order->expects(static::once())
            ->method('getShippingMethod')
            ->with(true)
            ->willReturn($this->getShippingMethodMock());

        /**
         * @var $shipmentMock \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject
         */
        $shipmentMock = $this->getMockBuilder('Magento\Sales\Model\Order\Shipment')
            ->disableOriginalConstructor()
            ->getMock();
        $shipmentMock->expects(static::once())->method('getOrder')->willReturn($order);

        $this->carrierFactory->expects(static::once())
            ->method('create')
            ->with(self::CARRIER_CODE)
            ->willReturn($this->getCarrierMock());

        $labelsMock = $this->getMockBuilder('\Magento\Shipping\Model\Shipping\Labels')
            ->disableOriginalConstructor()
            ->getMock();
        $labelsMock->expects(static::once())
            ->method('requestToShipment')
            ->with($shipmentMock)
            ->willReturn($this->getResponseMock($info));

        $this->labelsFactory->expects(static::once())
            ->method('create')
            ->willReturn($labelsMock);

        $this->filesystem->expects(static::once())
            ->method('getDirectoryWrite')
            ->willReturn($this->getMock('Magento\Framework\Filesystem\Directory\WriteInterface'));

        $this->scopeConfig->expects(static::once())
            ->method('getValue')
            ->with(
                'carriers/' . self::CARRIER_CODE . '/title',
                ScopeInterface::SCOPE_STORE,
                null
            )->willReturn(self::CARRIER_TITLE);

        $this->labelsFactory->expects(static::once())
            ->method('create')
            ->willReturn($labelsMock);

        $trackMock = $this->getMockBuilder('Magento\Sales\Model\Order\Shipment\Track')
            ->setMethods(['setNumber', 'setCarrierCode', 'setTitle'])
            ->disableOriginalConstructor()
            ->getMock();

        $i = 0;
        $trackingNumbers = is_array($info['tracking_number']) ? $info['tracking_number'] : [$info['tracking_number']];
        foreach ($trackingNumbers as $trackingNumber) {
            $trackMock->expects(static::at($i++))
                ->method('setNumber')
                ->with($trackingNumber)
                ->willReturnSelf();
            $trackMock->expects(static::at($i++))
                ->method('setCarrierCode')
                ->with(self::CARRIER_CODE)
                ->willReturnSelf();
            $trackMock->expects(static::at($i++))
                ->method('setTitle')
                ->with(self::CARRIER_TITLE)
                ->willReturnSelf();
        }

        $this->trackFactory->expects(static::any())
            ->method('create')
            ->willReturn($trackMock);

        /**
         * @var $requestMock \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject
         */
        $requestMock = $this->getMock('Magento\Framework\App\RequestInterface');
        $this->labelGenerator->create($shipmentMock, $requestMock);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getShippingMethodMock()
    {
        $shippingMethod = $this->getMockBuilder('Magento\Framework\DataObject')
            ->disableOriginalConstructor()
            ->setMethods(['getCarrierCode'])
            ->getMock();
        $shippingMethod->expects(static::once())
            ->method('getCarrierCode')
            ->willReturn(self::CARRIER_CODE);

        return $shippingMethod;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getCarrierMock()
    {
        $carrierMock = $this->getMockBuilder('Magento\Shipping\Model\Carrier\AbstractCarrier')
            ->disableOriginalConstructor()
            ->setMethods(['isShippingLabelsAvailable', 'getCarrierCode'])
            ->getMockForAbstractClass();
        $carrierMock->expects(static::once())
            ->method('isShippingLabelsAvailable')
            ->willReturn(true);
        $carrierMock->expects(static::once())
            ->method('getCarrierCode')
            ->willReturn(self::CARRIER_CODE);

        return $carrierMock;
    }

    /**
     * @param array $info
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getResponseMock(array $info)
    {
        $responseMock = $this->getMockBuilder('\Magento\Framework\DataObject')
            ->setMethods(['hasErrors', 'hasInfo', 'getInfo'])
            ->disableOriginalConstructor()
            ->getMock();
        $responseMock->expects(static::once())
            ->method('hasErrors')
            ->willReturn(false);
        $responseMock->expects(static::once())
            ->method('hasInfo')
            ->willReturn(true);
        $responseMock->expects(static::once())
            ->method('getInfo')
            ->willReturn([$info]);

        return $responseMock;
    }

    /**
     * @return array
     */
    public function labelInfoDataProvider()
    {
        return [
            [['tracking_number' => ['111111', '222222', '333333'], 'label_content' => 'some']],
            [['tracking_number' => '111111', 'label_content' => 'some']],
        ];
    }
}


text:
package org.tolweb.hibernate;

import java.io.Serializable;
import java.util.Date;

/**
 *
 * @author lenards
 * @hibernate.class table="NodeRetirementLog"
 * @hibernate.cache usage="nonstrict-read-write"
 */
public class NodeRetirementRecord implements Serializable {
	/** */
	private static final long serialVersionUID = 8865059487484208448L;
	private Long id = Long.valueOf(-1);
	private Long nodeId;
	private String nodeName;
	private Long retiredFromClade;
	private String retiredBy;
	private Date timestamp;

	/**
	 * @return the id
	 * @hibernate.id generator-class="native" unsaved-value="-1"
	 */
	public Long getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the nodeId
	 * @hibernate.property
	 */
	public Long getNodeId() {
		return nodeId;
	}
	/**
	 * @param nodeId the nodeId to set
	 */
	public void setNodeId(Long nodeId) {
		this.nodeId = nodeId;
	}

	/**
	 * @return the nodeName
	 * @hibernate.property
	 */
	public String getNodeName() {
		return nodeName;
	}
	/**
	 * @param nodeName the nodeName to set
	 */
	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}

	/**
	 * @return the retiredFromClade
	 * @hibernate.property
	 */
	public Long getRetiredFromClade() {
		return retiredFromClade;
	}
	/**
	 * @param retiredFromClade the retiredFromClade to set
	 */
	public void setRetiredFromClade(Long retiredFromClade) {
		this.retiredFromClade = retiredFromClade;
	}

	/**
	 * @return the retiredBy
	 * @hibernate.property
	 */
	public String getRetiredBy() {
		return retiredBy;
	}
	/**
	 * @param retiredBy the retiredBy to set
	 */
	public void setRetiredBy(String retiredBy) {
		this.retiredBy = retiredBy;
	}

	/**
	 * @return the timestamp
	 * @hibernate.property
	 */
	public Date getTimestamp() {
		return timestamp;
	}
	/**
	 * @param timestamp the timestamp to set
	 */
	public void setTimestamp(Date timestamp) {
		this.timestamp = timestamp;
	}
}


text:
layout: default
title: Chattizen | A resource for Chattanoogans
page_class: home
no_heroshot: true
og:
    title: a resource for Chattanoogans
---

A Resource for Chattanoogans

Welcome to Chattizen.org

A citizens guide to local government in Chattanooga, Tenn.

{% comment %}

Use these tools to find helpful information about our city.

{% endcomment %}

What is Chattizen?

Chattizen helps you navigate local government. Find out how your tax dollars are spent with the tax receipt or learn how local government works with our guides to Chattanooga and Hamilton County.

The project is funded by the Benwood Foundation. To learn more, visit our about page or follow us on Twitter, Facebook or Tumblr.


text:
let jsonConfig;

try{
  jsonConfig = require('/run/config.json');
} catch(err) {
  // Mocking data in dev mode
  jsonConfig = {
    info: {
      limits: {
        cpu: 1
      }
    }
  };
}
/**
* Read number of CPUs from environment or fallback to the _private_ configuration property
* Useful for determining the number of processes to fork.
*/
function num_of_cpus() {
  try {
    if(process.env['OMP_NUM_THREADS']) {
      return process.env['OMP_NUM_THREADS'];
    }

    return Math.ceil(jsonConfig.info.limits.cpu);
  } catch (err) {
    throw new Error('Could not get number of cpus');
  }
};

function read_base64_json(varName) {
  try {
    return JSON.parse(new Buffer(process.env[varName], 'base64').toString());
  } catch (err) {
    throw new Error(`no ${varName} environment variable`);
  }
};

/**
* Reads Platform.sh configuration from environment and returns a single object
*/
function config() {
  if(!process.env.PLATFORM_PROJECT) {
    throw Error('This is not running on platform.sh');
  }

  return {
    application: read_base64_json('PLATFORM_APPLICATION'),
    relationships: read_base64_json('PLATFORM_RELATIONSHIPS'),
    variables: read_base64_json('PLATFORM_VARIABLES'),
    application_name: process.env.PLATFORM_APPLICATION_NAME,
    app_dir: process.env.PLATFORM_APP_DIR,
    environment: process.env.PLATFORM_ENVIRONMENT,
    project: process.env.PLATFORM_PROJECT,
    routes: read_base64_json('PLATFORM_ROUTES'),
    tree_id: process.env.PLATFORM_TREE_ID,
    project_entropy: process.env.PLATFORM_PROJECT_ENTROPY,
    branch: process.env.PLATFORM_BRANCH,
    document_root: process.env.PLATFORM_DOCUMENT_ROOT,
    port: process.env.PORT,
    omp_num_threads: num_of_cpus()
  };
};

module.exports = {
  config
};


text:
describe('Data update', function() {
  beforeEach(function() {
    browser.get('test/e2e/data_update.html');
  });
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Pflanzenfam. , 2b, no. 143-145, 5.

#### Original name
null

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using AddressBook.AddingForm;

namespace AddressBook.AddingForm
{
    public class AddFormController
    {
        private AddFormModel _model;
        private AddFormView _view;

        public AddFormModel Model
        {
            get { return _model; }
            set { _model = value; }
        }
        public AddFormView View
        {
            get { return _view; }
            set { _view = value; }
        }

        public AddFormController(AddFormModel model,AddFormView view)
        {
            _model = model;
            _view = view;

            _view.OkButtonListener(OkButtonClick);
            _view.CancelButtonListener(CancelButtonClick);
        }

        private void OkButtonClick(object o, EventArgs e)
        {
            var r =_view.GetRecord();
            var p = _model.SaveRecord(r);
        }

        private  void CancelButtonClick(object o, EventArgs e)
        {
            _view.Close();

        }

    }
}


text:
package org.glamey.training.jvm;

import lombok.Data;
import org.glamey.training.jvm.domain.BaseDomain;

@Data
public class ProductionVO extends BaseDomain {
    private String code;
    private String name;
}