text:
<?php

namespace Blogger\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Blogger\BlogBundle\Controller\BaseController;
use Blogger\BlogBundle\Entity\Post;
use Blogger\BlogBundle\Entity\PostCategories;

class PostsController extends BaseController {

	public function getAction()
	{
		if(self::is_auth() && self::is_admin())
		{
			$posts = $this->get('doctrine')->getEntityManager()
				->createQuery('SELECT p FROM BloggerBlogBundle:Post p')
				->getResult()
			;
			$this->data["posts"] = $posts;
			return $this->render('BloggerBlogBundle:posts:index.html.twig', $this->data);
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function addAction()
	{
		if(self::is_auth() && self::is_admin())
		{
			return $this->render('BloggerBlogBundle:posts:add.html.twig', $this->data);
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function saveAction(Request $request)
	{
		if(self::is_auth() && self::is_admin())
		{
			if($request->getMethod() == 'POST' && $request->isXmlHttpRequest())
			{
				$params = $request->request->all();
				$post = new Post();
				$post->setTitle($params["title"]);
				$post->setContent($params["content"]);
				$post->setStatus($params["status"]);
				$post->setAuthor("admin");
				$em = $this->getDoctrine()->getManager();
				$em->persist($post);
				$em->flush();
				$this->data["status"] = "OK";
				$this->data["added_id"] = $post->getId();
				return new response(json_encode($this->data));
			}
			else
			{
				echo 'Access Denied';
				exit();
			}
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function editAction($PostId)
	{
		if(self::is_auth() && self::is_admin())
		{
			$em = $this->getDoctrine()->getManager();
			$posts = $em->getRepository('BloggerBlogBundle:Post')->find($PostId);

			if (!$posts) {
				return $this->redirect($this->generateUrl("admin_posts"));
			}
			$this->data["posts"] = $posts;
			return $this->render('BloggerBlogBundle:posts:edit.html.twig', $this->data);
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function updateAction(Request $request)
	{
		if(self::is_auth() && self::is_admin())
		{
			if($request->getMethod() == 'POST' && $request->isXmlHttpRequest())
			{
				$params = $request->request->all();
				$em = $this->getDoctrine()->getManager();
				$post = $em->getRepository('BloggerBlogBundle:Post')->find($params["id"]);

				if (!$post) {
					$this->data["status"] = "Failed";
					$this->data["error_msg"] = "Post Does't exist";
				}
				else
				{
					$post->setTitle($params["title"]);
					$post->setContent($params["content"]);
					$post->setStatus($params["status"]);
					$post->setAuthor("admin");
					$em = $this->getDoctrine()->getManager();
					$em->persist($post);
					$em->flush();
					$this->data["status"] = "OK";
				}
				return new response(json_encode($this->data));
			}
			else
			{
				echo 'Access Denied';
				exit();
			}
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function deleteAction(Request $request , $PostId)
	{
		if(self::is_auth() && self::is_admin())
		{
			$em = $this->getDoctrine()->getManager();
			$post = $em->getRepository('BloggerBlogBundle:Post')->find($PostId);

			if (!$post) {
				if($request->getMethod() == 'GET' && $request->isXmlHttpRequest())
				{
					$this->data["status"] = "Failed";
					$this->data["error_msg"] = "Post Does't exist";
					return new response(json_encode($this->data));
				}
				else
				{
					return $this->redirect($this->generateUrl("admin_posts"));
				}
			}
			else
			{
				$em->remove($post);
				$em->flush();

			}

			if($request->getMethod() == 'GET' && $request->isXmlHttpRequest())
			{
				$this->data["status"] = "OK";
				return new response(json_encode($this->data));
			}
			else
			{
				return $this->redirect($this->generateUrl("admin_posts"));
			}
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function categoriesAction($PostId)
	{
		if(self::is_auth() && self::is_admin())
		{
			$this->data["Post_id"] = $PostId;
			$categories = $this->get('doctrine')->getEntityManager()
				->createQuery('SELECT p FROM BloggerBlogBundle:Category p')
				->getResult()
			;
			$this->data["categories"] = $categories;

			$post_categories = $this->get('doctrine')->getEntityManager()
				->createQuery('SELECT p FROM BloggerBlogBundle:PostCategories p where p.Post_id = ' . $PostId)
				->getResult()
			;

			$this->data["post_categories"] = $post_categories;
			return $this->render('BloggerBlogBundle:posts:categories.html.twig', $this->data);
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

	public function assignCategoriesAction(Request $request)
	{
		if(self::is_auth() && self::is_admin())
		{
			if($request->getMethod() == 'POST' && $request->isXmlHttpRequest())
			{
				$params = $request->request->all();
				if(!empty($params["Post_id"]) && isset($params["categories"]))
				{
					$result = $this->get('doctrine')->getEntityManager()
						->createQuery("DELETE FROM BloggerBlogBundle:PostCategories p where p.Post_id = " . $params["Post_id"])
						->getResult()
					;

					$arr_categories = explode(',', $params["categories"]);
					for($i = 0 ; $i<count($arr_categories) ; $i++)
					{
						$post_category = new PostCategories();
						$post_category->setPostId($params["Post_id"]);
						$post_category->setCategoryId($arr_categories[$i]);
						$em = $this->getDoctrine()->getManager();
						$em->persist($post_category);
						$em->flush();
					}

					$this->data["status"] = "OK";
				}
				else
				{
					$this->data["status"] = "Failed";
					$this->data["error_msg"] = "Post id must provide , and check some categories";
				}
				return new response(json_encode($this->data));
			}
			else
			{
				echo 'Access Denied';
				exit();
			}
		}
		else
		{
			return $this->redirect($this->generateUrl("logout"));
		}
	}

}


text:
package org.tiogasolutions.identity.client.domain;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.tiogasolutions.identity.client.core.PubItem;
import org.tiogasolutions.identity.client.core.PubLink;
import org.tiogasolutions.identity.client.core.PubLinks;
import org.tiogasolutions.identity.client.core.PubStatus;

import java.util.ArrayList;
import java.util.List;

import static java.util.Collections.unmodifiableList;

public class IdentityPolicies extends PubItem {

    private final int total;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final List<IdentityPolicy> items = new ArrayList<>();

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final List<PubLink> links = new ArrayList<>();

    public IdentityPolicies(@JsonProperty("_status") PubStatus _status,
                            @JsonProperty("_links") PubLinks _links,
                            @JsonProperty("total") int total,
                            @JsonProperty("items") List<IdentityPolicy> items,
                            @JsonProperty("links") List<PubLink> links) {

        super(_status, _links);

        this.total = total;

        if (items != null) this.items.addAll(items);
        if (links != null) this.links.addAll(links);
    }

    public List<IdentityPolicy> getItems() {
        return unmodifiableList(items);
    }

    public List<PubLink> getLinks() {
        return unmodifiableList(links);
    }

    public int getTotal() {
        return total;
    }
}

redpajama_set_name: RedPajamaGithub


text:
if (vueContentObject) getVueObject().$destroy();

[vuePageSize, loadPageableDataUrl, tableColumnsName, tableColumnsKey, tableButtonsOnEachRow] = [
	10,
	'departmentsByPage',
	['','ID','部门编码','部门名称','部门描述','排序','所属机构','上级部门','可用状态','注册日期','最后修改日期','操作'],
	['selection','id','code','name','descirption','sort','organization','parent','available','createDate','modifyDate','operation'],
	['rowUpdateButton#修改','rowDeleteButton#删除']
];

parseValuesOnTableEachRow = obj => ({
	id: obj.id,
	code: obj.code,
	name: obj.name,
	descirption: obj.descirption,
	sort: obj.sort,
	organization: obj.organization ? obj.organization.name : '无',
	parent: obj.parent ? obj.parent.name : '无',
	available: obj.available ? '启用' : '弃用',
	createDate:formatDate(obj.createDate),
	modifyDate:formatDate(obj.modifyDate)
});

const [departmentsUrl, departmentsLabel, organizationsUrl, organizationsLabel] = [
	(currentRequestMappingRootPath + '/getAllAvailableDepartments'),'请选择上级部门',
	'organization/getAllAvailableOrganizations','请选择所属机构'
];

vueContentBeforeCreate = () => {
	[customVueContentData, parentDataSelect, organizationDataSelect, availableDataSelect] = [
		{treeData: [{id: null, expand: false, title: '<i class="ivu-icon ivu-icon-ios-circle-filled" style="font-size: 16px;">', children: vueContentObject.vueRecordTotal != 0 ? [{}] : null}]},
		getDataList(departmentsUrl,departmentsLabel),
		getDataList(organizationsUrl,organizationsLabel),
		[{value: 'true', label: '启用'},{value: 'false', label: '弃用'}]
	];
};

setFormDataObject({id: -1, code: '', name: '', descirption: '', sort: 1, organization_id: nullAsNumber, parent_id: nullAsNumber, available: 'true'});

[queryFormItemName, queryFormItemKey, queryFormItemType] = [
	['ID','部门编码','部门名称','所属机构','上级部门','可用状态'],
	['id','code','name','organization','parent','available'],
	['string','string','string','string','string','select#availableDataSelect']
];

setFormRulesObject({
	'code': [{trigger: 'blur',type: 'string', required: true, min:4,max :10,message: '部门编码为长度4至10位之间字符串!'}, {validator: this.validateFormRules, trigger: 'blur',unique:'checkDepartmentCodeUnique',message: '部门编码已被使用'}],
	'name': [{trigger: 'blur',type: 'string', required: true, min:2,max :12,message: '部门名称为长度2至12位之间字符串!'}],
	'sort': [{trigger: 'blur',type: 'number', required: true, pattern: /^[0-9]*$/, message: '排序必须为正整数!'}]
});

//////////////////////////////// tree //////////////////////////////////

loadTreeNodeUrl = 'department/children';
vueContentMethods.selectChange = () => {};

parseNode = data => {
	let node = {id: data.id, expand: data.expand, title: data.name, children: data.countOfChildren != 0 ? [{}] : null};
	if (data.hasOwnProperty('available')) {
		node.disabled = !data.available;
		if (node.disabled)
			node.title = `${node.title}  <i class="ivu-icon ivu-icon-eye-disabled" style="font-size: 16px;">`;
	}
	return node;
}

vueContentObject = new Vue(initializeContentOptions());
(() => {
	//初始化树根节点下级子节点数据,并展开根节点下级子节点
	getVueRefObject('tree').$children[0].handleExpand();
})();

//////////////////////////////// tree //////////////////////////////////

submitAddAfter = submitUpdateAfter = submitDeleteAfter = (data) => {
	vueContentObject.parentDataSelect = getDataList(departmentsUrl,departmentsLabel);
	vueContentObject.organizationDataSelect = getDataList(organizationsUrl,organizationsLabel);
	handleNodeMovement(data);
}

function handleNodeMovement(data) {

	const treeDataStr = JSON.stringify(vueContentObject.treeData); //字符串类型树数据对象
	const rootNode = vueContentObject.treeData[0]; //树数据对象根节点对象
	const parent = data.parent; //存储移动后新父节点内容的对象
	const parentId = parent == null ? null : parent.id; //存储移动后新父节点ID的对象
	const isParentOnTree = treeDataStr.includes(`{"id":${parentId},`); //树数据对象中新父节点的位置
	const isChildOnTree = treeDataStr.includes(`{"id":${data.id},`); //树数据对象中移动后节点的位置
	let child = {}; //存储移动后节点内容的对象

	if (currentAction == actions.update) {
		if (isChildOnTree) {
			//移动的子节点在当前树中,扫描并获取当前节点,并移至新父节点下
			child = getChildFromNode(data.id, rootNode);
			child.title = data.name;
			//判断是否当前新父节点在当前树中
			if (isParentOnTree) {
				//新父节点在当前树中,在新父节点下插入
				setChildToNode(child,parentId,rootNode);
			} else {
				//新父节点不在当前树中,暂时不做任何操作
			}
		} else {
			//移动的子节点不在当前树中,判断是否新父节点在当前树中
			if (isParentOnTree) {
				parseChild(child, data, true);
				child = parseNode(child);
				child.title = data.name;
				//寻找新父节点并为其插入移动过来的子节点
				setChildToNode(child,parentId,rootNode);
			} else {
				//新父节点不在当前树中,暂时不做任何操作
			}
		}
	} else if (currentAction == actions.del && data.count > 0) {
		for(let r of data.ids) getChildFromNode(data.ids[r], rootNode);
	} else if (currentAction == actions.add) {
		if (isParentOnTree) {
			parseChild(child, data);
			child = parseNode(child);
			//寻找新父节点并为其插入移动过来的子节点
			setChildToNode(child,parentId,rootNode);
		} else {
			//新父节点不在当前树中,暂时不做任何操作
		}
	}
}

showUpdateFormBefore = (form) => {
	//动态设置上级部门下拉菜单中哪些项目是不可选的
	const id = vueUpdateForm.id;
	$.iposty('getChildrenIds', {id: id}, (data) => {
		let ids = data.ids;
		ids.push(id);
		let options = getVueRefObject('updateFormParentSelection').$children[0].$children[2].$children;
		options.forEach(option => option.disabled = ids.includes(option.value));
	});
}

function getDataList(url,label) {
	//Iview解决resetFields不能清空Select选中项问题之前
	//https://github.com/iview/iview/issues/970
	//暂且用Javascript中数字类型最小值在clearNullStructureObject4JSON方法中表示null值进行处理
	let content = [{value: nullAsNumber, label: label}];
	$.posty(url, null, ({parents}) => parents.map(node => content.push({value: node.id, label: node.name})));
	return content;
}

function parseChild(child, data, checkChildren) {
	child.id = data.id;
	child.expand = false;
	child.name = data.name;
	child.available = data.available;
	child.countOfChildren = checkChildren ? data.countOfChildren : 0;
}


text:
package org.apache.metron.hbase;

/**
 * A simple POJO used for testing.
 */
public class Widget {

  /**
   * The name of the widget.
   */
  private String name;

  /**
   * The cost of the widget.
   */
  private int cost;

  public Widget(String name, int cost) {
    this.name = name;
    this.cost = cost;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getCost() {
    return cost;
  }

  public void setCost(int cost) {
    this.cost = cost;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Widget widget = (Widget) o;
    if (cost != widget.cost) return false;
    return name != null ? name.equals(widget.name) : widget.name == null;

  }

  @Override
  public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + cost;
    return result;
  }

  @Override
  public String toString() {
    return "Widget{" +
            "name='" + name + '\'' +
            ", cost=" + cost +
            '}';
  }
}


text:
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';
import '@angular/forms';

import 'rxjs';

window["jwplayer"] = require("../libs/jwplayer");
window["jwplayer"].key = "RQ+gASdSAzcEhqeSCgQ7M7hHOXdBC1Jdsl+PWg==";


text:
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');
const expect = require('expect');

const expectedFiles = {
  eurekaregistry: ['./registry-k8s/jhipster-registry.yml', './registry-k8s/application-configmap.yml'],
  consulregistry: ['./registry-k8s/consul.yml', './registry-k8s/consul-config-loader.yml', './registry-k8s/application-configmap.yml'],
  jhgate: ['./jhgate-k8s/jhgate-deployment.yml', './jhgate-k8s/jhgate-mysql.yml', './jhgate-k8s/jhgate-service.yml'],
  jhgateingress: ['./jhgate-k8s/jhgate-ingress.yml'],
  customnamespace: ['./namespace.yml'],
  msmysql: ['./msmysql-k8s/msmysql-deployment.yml', './msmysql-k8s/msmysql-mysql.yml', './msmysql-k8s/msmysql-service.yml'],
  mspsql: [
    './mspsql-k8s/mspsql-deployment.yml',
    './mspsql-k8s/mspsql-postgresql.yml',
    './mspsql-k8s/mspsql-service.yml',
    './mspsql-k8s/mspsql-elasticsearch.yml',
  ],
  msmongodb: ['./msmongodb-k8s/msmongodb-deployment.yml', './msmongodb-k8s/msmongodb-mongodb.yml', './msmongodb-k8s/msmongodb-service.yml'],
  msmariadb: ['./msmariadb-k8s/msmariadb-deployment.yml', './msmariadb-k8s/msmariadb-mariadb.yml', './msmariadb-k8s/msmariadb-service.yml'],
  msmssqldb: ['./msmssqldb-k8s/msmssqldb-deployment.yml', './msmssqldb-k8s/msmssqldb-mssql.yml', './msmssqldb-k8s/msmssqldb-service.yml'],
  monolith: [
    './samplemysql-k8s/samplemysql-deployment.yml',
    './samplemysql-k8s/samplemysql-mysql.yml',
    './samplemysql-k8s/samplemysql-service.yml',
    './samplemysql-k8s/samplemysql-elasticsearch.yml',
  ],
  kafka: [
    './samplekafka-k8s/samplekafka-deployment.yml',
    './samplekafka-k8s/samplekafka-mysql.yml',
    './samplekafka-k8s/samplekafka-service.yml',
    './messagebroker-k8s/kafka.yml',
  ],
  prometheusmonit: [
    './monitoring-k8s/jhipster-prometheus-crd.yml',
    './monitoring-k8s/jhipster-prometheus-cr.yml',
    './monitoring-k8s/jhipster-grafana.yml',
    './monitoring-k8s/jhipster-grafana-dashboard.yml',
  ],
  jhgategateway: ['./jhgate-k8s/jhgate-gateway.yml', './jhgate-k8s/jhgate-destination-rule.yml', './jhgate-k8s/jhgate-virtual-service.yml'],
  applyScript: ['./kubectl-apply.sh'],
};

describe('JHipster Kubernetes Sub Generator', () => {
  describe('only gateway', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/01-gateway'), path.join(dir, './01-gateway'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['01-gateway'],
          adminPassword: 'meetup',
          dockerRepositoryName: 'jhipsterrepository',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'jhipsternamespace',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files and content', () => {
      assert.file(expectedFiles.eurekaregistry);
      assert.fileContent('./registry-k8s/jhipster-registry.yml', /# base64 encoded "meetup"/);
    });
    it('creates expected gateway files and content', () => {
      assert.file(expectedFiles.jhgate);
      assert.fileContent('./jhgate-k8s/jhgate-deployment.yml', /image: jhipsterrepository\/jhgate/);
      assert.fileContent('./jhgate-k8s/jhgate-deployment.yml', /jhipsternamespace.svc.cluster/);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('gateway and mysql microservice', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/01-gateway'), path.join(dir, './01-gateway'));
          fse.copySync(path.join(__dirname, './templates/compose/02-mysql'), path.join(dir, './02-mysql'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['01-gateway', '02-mysql'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected gateway files', () => {
      assert.file(expectedFiles.jhgate);
    });
    it('creates expected mysql files', () => {
      assert.file(expectedFiles.msmysql);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('mysql microservice with custom namespace', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/02-mysql'), path.join(dir, './02-mysql'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['02-mysql'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'mynamespace',
          jhipsterConsole: true,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected mysql files', () => {
      assert.file(expectedFiles.msmysql);
    });
    it('creates expected namespace file', () => {
      assert.file(expectedFiles.customnamespace);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('gateway and ingress', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/01-gateway'), path.join(dir, './01-gateway'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['01-gateway'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          kubernetesServiceType: 'Ingress',
          ingressDomain: 'example.com',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected gateway files', () => {
      assert.file(expectedFiles.jhgate);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('MySQL and PostgreSQL microservices without gateway', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/02-mysql'), path.join(dir, './02-mysql'));
          fse.copySync(path.join(__dirname, './templates/compose/03-psql'), path.join(dir, './03-psql'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['02-mysql', '03-psql'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it("doesn't creates gateway files", () => {
      assert.noFile(expectedFiles.jhgate);
    });
    it('creates expected mysql files', () => {
      assert.file(expectedFiles.msmysql);
    });
    it('creates expected psql files', () => {
      assert.file(expectedFiles.mspsql);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('gateway, mysql, psql, mongodb, mariadb, mssql microservices', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/01-gateway'), path.join(dir, './01-gateway'));
          fse.copySync(path.join(__dirname, './templates/compose/02-mysql'), path.join(dir, './02-mysql'));
          fse.copySync(path.join(__dirname, './templates/compose/03-psql'), path.join(dir, './03-psql'));
          fse.copySync(path.join(__dirname, './templates/compose/04-mongo'), path.join(dir, './04-mongo'));
          fse.copySync(path.join(__dirname, './templates/compose/07-mariadb'), path.join(dir, './07-mariadb'));
          fse.copySync(path.join(__dirname, './templates/compose/11-mssql'), path.join(dir, './11-mssql'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['01-gateway', '02-mysql', '03-psql', '04-mongo', '07-mariadb', '11-mssql'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected gateway files', () => {
      assert.file(expectedFiles.jhgate);
    });
    it('creates expected mysql files', () => {
      assert.file(expectedFiles.msmysql);
    });
    it('creates expected psql files', () => {
      assert.file(expectedFiles.mspsql);
    });
    it('creates expected mongodb files', () => {
      assert.file(expectedFiles.msmongodb);
    });
    it('creates expected mariadb files', () => {
      assert.file(expectedFiles.msmariadb);
    });
    it('creates expected mssql files', () => {
      assert.file(expectedFiles.msmssqldb);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('monolith application', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/08-monolith'), path.join(dir, './08-monolith'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'monolith',
          directoryPath: './',
          chosenApps: ['08-monolith'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it("doesn't creates registry files", () => {
      assert.noFile(expectedFiles.eurekaregistry);
    });
    it('creates expected default files', () => {
      assert.file(expectedFiles.monolith);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('Kafka application', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/09-kafka'), path.join(dir, './09-kafka'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'monolith',
          directoryPath: './',
          chosenApps: ['09-kafka'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it("doesn't creates registry files", () => {
      assert.noFile(expectedFiles.eurekaregistry);
    });
    it('creates expected default files', () => {
      assert.file(expectedFiles.kafka);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('mysql microservice with custom namespace and jhipster prometheus monitoring', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/02-mysql'), path.join(dir, './02-mysql'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['02-mysql'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'mynamespace',
          monitoring: 'prometheus',
          kubernetesServiceType: 'LoadBalancer',
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected mysql files', () => {
      assert.file(expectedFiles.msmysql);
    });
    it('creates expected prometheus files', () => {
      assert.file(expectedFiles.prometheusmonit);
    });
    it('creates expected namespace file', () => {
      assert.file(expectedFiles.customnamespace);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('gateway with istio routing', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/01-gateway'), path.join(dir, './01-gateway'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['01-gateway'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          ingressDomain: 'example.com',
          clusteredDbApps: [],
          istio: true,
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected service gateway files', () => {
      assert.file(expectedFiles.jhgate);
    });
    it('creates expected routing gateway and istio files', () => {
      assert.file(expectedFiles.jhgategateway);
    });
    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });

  describe('mysql, psql, mongodb, mariadb, mssql microservices with dynamic storage provisioning', () => {
    let runResult;
    before(async () => {
      runResult = await helpers
        .create(require.resolve('../generators/kubernetes'))
        .doInDir(dir => {
          fse.copySync(path.join(__dirname, './templates/compose/01-gateway'), path.join(dir, './01-gateway'));
          fse.copySync(path.join(__dirname, './templates/compose/02-mysql'), path.join(dir, './02-mysql'));
          fse.copySync(path.join(__dirname, './templates/compose/03-psql'), path.join(dir, './03-psql'));
          fse.copySync(path.join(__dirname, './templates/compose/04-mongo'), path.join(dir, './04-mongo'));
          fse.copySync(path.join(__dirname, './templates/compose/07-mariadb'), path.join(dir, './07-mariadb'));
          fse.copySync(path.join(__dirname, './templates/compose/11-mssql'), path.join(dir, './11-mssql'));
        })
        .withOptions({ skipChecks: true, reproducibleTests: true })
        .withPrompts({
          deploymentApplicationType: 'microservice',
          directoryPath: './',
          chosenApps: ['01-gateway', '02-mysql', '03-psql', '04-mongo', '07-mariadb', '11-mssql'],
          dockerRepositoryName: 'jhipster',
          dockerPushCommand: 'docker push',
          kubernetesNamespace: 'default',
          jhipsterConsole: false,
          kubernetesServiceType: 'LoadBalancer',
          clusteredDbApps: [],
          kubernetesUseDynamicStorage: true,
          kubernetesStorageClassName: '',
        })
        .run();
    });
    it('should match files snapshot', function () {
      expect(runResult.getSnapshot()).toMatchSnapshot();
    });
    it('creates expected registry files', () => {
      assert.file(expectedFiles.eurekaregistry);
    });
    it('creates expected gateway files', () => {
      assert.file(expectedFiles.jhgate);
    });
    it('creates expected mysql files', () => {
      assert.file(expectedFiles.msmysql);
      assert.fileContent(expectedFiles.msmysql[1], /PersistentVolumeClaim/);
      assert.fileContent(expectedFiles.msmysql[1], /claimName:/);
    });

    it('creates expected psql files', () => {
      assert.file(expectedFiles.mspsql);
      assert.fileContent(expectedFiles.mspsql[1], /PersistentVolumeClaim/);
      assert.fileContent(expectedFiles.mspsql[1], /claimName:/);
    });
    it('creates expected mongodb files', () => {
      assert.file(expectedFiles.msmongodb);
      assert.fileContent(expectedFiles.msmongodb[1], /volumeClaimTemplates:/);
    });
    it('creates expected mariadb files', () => {
      assert.file(expectedFiles.msmariadb);
      assert.fileContent(expectedFiles.msmariadb[1], /PersistentVolumeClaim/);
      assert.fileContent(expectedFiles.msmariadb[1], /claimName:/);
    });
    it('creates expected mssql files', () => {
      assert.file(expectedFiles.msmssqldb);
      assert.fileContent(expectedFiles.msmssqldb[1], /PersistentVolumeClaim/);
      assert.fileContent(expectedFiles.msmssqldb[1], /claimName:/);
    });

    it('create the apply script', () => {
      assert.file(expectedFiles.applyScript);
    });
  });
});


text:
/**
 * Utility Package for common code for Turmeric handler.
 */
package org.ebayopensource.turmeric.runtime.common.handler;


text:
class HomeController < ApplicationController

	def index

		if session[:usuario]
			aluno = Aluno.find_by(matricula: session[:usuario])
			turma = Turma.find(aluno.turma_id)
			@professor = Professor.find(turma.professor_id)
			@posts = Post.where("professor_id=#{@professor.id}").limit(5).order('created_at DESC')
			@arquivos = Arquivo.joins('JOIN posts ON posts.id = arquivos.post_id').where("tipo = 'Video'").order('nome')
		else
			redirect_to action:'login'
		end

	end

  	def login

  		if not session[:usuario]
			@aluno = Aluno.new
		else
			redirect_to root_path
		end

	end

	def log

		if not session[:usuario]

			if session[:prof]
				reset_session
			end

		@aluno = Aluno.find_by_matricula_and_senha(params[:matricula],Digest::MD5.hexdigest(params[:senha]))

			if !@aluno.nil?
				if @aluno.confirmado
					session[:usuario] = @aluno.matricula
					redirect_to :home
			  	else
			  		flash.now[:alert] = "Ainda em espera de aprovação de cadastro"
	        		render :login
			  	end
			else
				@aluno = Aluno.new
				flash.now[:alert] = 'Matrícula ou senha incorretas'
	        	render :login
			end

		else

			redirect_to root_path

		end

	end

	def logout

		if session[:usuario]
		    reset_session
		    redirect_to root_path
		else
			redirect_to action: 'login'
		end

  	end

end


text:
package net.fortytwo.ripple.cli.ast;

import net.fortytwo.flow.Sink;
import net.fortytwo.ripple.RippleException;
import net.fortytwo.ripple.libs.control.ControlLibrary;
import net.fortytwo.ripple.model.ModelConnection;
import net.fortytwo.ripple.model.Operator;
import net.fortytwo.ripple.model.RippleList;
import net.fortytwo.ripple.query.QueryEngine;

/**
 * @author Joshua Shinavier (http://fortytwo.net)
 */
public class OperatorAST implements AST<RippleList> {
    public enum Type {
        Apply,
        Inverse,
        Option,
        Plus,
        Range,
        Star,
        Times,
    }

    private final Type type;
    private NumberAST min, max;

    public OperatorAST(final Type type) {
        this.type = type;
    }

    public OperatorAST() {
        this(Type.Apply);
    }

    public OperatorAST(final NumberAST times) {
        type = Type.Times;
        min = times;
    }

    public OperatorAST(final NumberAST min, final NumberAST max) {
        type = Type.Range;
        this.min = min;
        this.max = max;
    }

    public void evaluate(final Sink<RippleList> sink,
                         final QueryEngine qe,
                         final ModelConnection mc)
            throws RippleException {
        RippleList l;

        switch (type) {
            case Apply:
                l = mc.list().push(Operator.OP);
                break;
            case Inverse:
                // Note: only one "op" here.  This merely finds the inverse; it doesn't automatically apply the inverse.
                l = mc.list().push(Operator.OP)
                        .push(ControlLibrary.getInverseValue());
                break;
            case Option:
                l = mc.list().push(Operator.OP)
                        .push(Operator.OP)
                        .push(ControlLibrary.getOptionApplyValue());
                break;
            case Plus:
                l = mc.list().push(Operator.OP)
                        .push(Operator.OP)
                        .push(ControlLibrary.getPlusApplyValue());
                break;
            case Range:
                l = mc.list().push(Operator.OP)
                        .push(Operator.OP)
                        .push(ControlLibrary.getRangeApplyValue())
                        .push(max.getValue())
                        .push(min.getValue());
                break;
            case Star:
                l = mc.list().push(Operator.OP)
                        .push(Operator.OP)
                        .push(ControlLibrary.getStarApplyValue());
                break;
            case Times:
                l = mc.list().push(Operator.OP)
                        .push(Operator.OP)
                        .push(ControlLibrary.getTimesApplyValue())
                        .push(min.getValue());
                break;
            default:
                throw new RippleException("unhandled operator type: " + type);
        }

        sink.accept(l);
    }

    public String toString() {
        switch (type) {
            case Apply:
                return ".";
            case Inverse:
                return "~";
            case Option:
                return "?";
            case Plus:
                return "+";
            case Range:
                return "{" + min + "," + max + "}";
            case Star:
                return "*";
            case Times:
                return "{" + min + "}";
            default:
                return "error";
        }
    }
}


text:
package org.elasticsearch.action.admin.indices.template.put;

import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.master.AcknowledgedResponse;

public class PutIndexTemplateAction extends ActionType<AcknowledgedResponse> {

    public static final PutIndexTemplateAction INSTANCE = new PutIndexTemplateAction();
    public static final String NAME = "indices:admin/template/put";

    private PutIndexTemplateAction() {
        super(NAME, AcknowledgedResponse::readFrom);
    }

}


text:
#ifndef __MD5CHECKIMPL_H__
#define __MD5CHECKIMPL_H__

#include "md5check.h"

class MD5Check;
class MD5CheckImpl
{
public:
    MD5CheckImpl(MD5Check *md5Check) : m_md5Check(md5Check){};
    virtual ~MD5CheckImpl(){};

    virtual const string& getStringMD5(const string& str){return m_md5;}
    virtual const string& getFileMD5(const string& path){return m_md5;}
    virtual const string& getLocalMD5(){return m_md5;}

protected:
    MD5Check* m_md5Check;
    string m_md5;
};
extern MD5CheckImpl* __createMD5Check(MD5Check* md5Check);

#endif /* __MD5CHECKIMPL_H__ */


text:
package com.qiuqp.mybill.bean;

/**
 * 实体类
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public abstract class Entity extends Base {

	protected long id;

	public long getId() {
		return id;
	}
	public void setId(long _id)
	{
	this.id=_id;
	}
	protected String cacheKey;

	public String getCacheKey() {
		return cacheKey;
	}

	public void setCacheKey(String cacheKey) {
		this.cacheKey = cacheKey;
	}
}


text:
jQuery(function($) {

	$('#simple-colorpicker-1').ace_colorpicker({pull_right:true}).on('change', function(){
		var color_class = $(this).find('option:selected').data('class');
		var new_class = 'widget-box';
		if(color_class != 'default')  new_class += ' widget-color-'+color_class;
		$(this).closest('.widget-box').attr('class', new_class);
	});

	// scrollables
	$('.scrollable').each(function () {
		var $this = $(this);
		$(this).ace_scroll({
			size: $this.attr('data-size') || 100,
			//styleClass: 'scroll-left scroll-margin scroll-thin scroll-dark scroll-light no-track scroll-visible'
		});
	});
	$('.scrollable-horizontal').each(function () {
		var $this = $(this);
		$(this).ace_scroll(
		  {
			horizontal: true,
			styleClass: 'scroll-top',//show the scrollbars on top(default is bottom)
			size: $this.attr('data-size') || 500,
			mouseWheelLock: true
		  }
		).css({'padding-top': 12});
	});

	$(window).on('resize.scroll_reset', function() {
		$('.scrollable-horizontal').ace_scroll('reset');
	});

	$('#id-checkbox-vertical').prop('checked', false).on('click', function() {
		$('#widget-toolbox-1').toggleClass('toolbox-vertical')
		.find('.btn-group').toggleClass('btn-group-vertical')
		.filter(':first').toggleClass('hidden')
		.parent().toggleClass('btn-toolbar')
	});

	/**
	//or use slimScroll plugin
	$('.slim-scrollable').each(function () {
		var $this = $(this);
		$this.slimScroll({
			height: $this.data('height') || 100,
			railVisible:true
		});
	});
	*/

	/**$('.widget-box').on('setting.ace.widget' , function(e) {
		e.preventDefault();
	});*/

	/**
	$('.widget-box').on('show.ace.widget', function(e) {
		//e.preventDefault();
		//this = the widget-box
	});
	$('.widget-box').on('reload.ace.widget', function(e) {
		//this = the widget-box
	});
	*/

	//$('#my-widget-box').widget_box('hide');

	// widget boxes
	// widget box drag & drop example
    $('.widget-container-col').sortable({
        connectWith: '.widget-container-col',
		items:'> .widget-box',
		handle: ace.vars['touch'] ? '.widget-header' : false,
		cancel: '.fullscreen',
		opacity:0.8,
		revert:true,
		forceHelperSize:true,
		placeholder: 'widget-placeholder',
		forcePlaceholderSize:true,
		tolerance:'pointer',
		start: function(event, ui) {
			//when an element is moved, it's parent becomes empty with almost zero height.
			//we set a min-height for it to be large enough so that later we can easily drop elements back onto it
			ui.item.parent().css({'min-height':ui.item.height()})
			//ui.sender.css({'min-height':ui.item.height() , 'background-color' : '#F5F5F5'})
		},
		update: function(event, ui) {
			ui.item.parent({'min-height':''})
			//p.style.removeProperty('background-color');
		}
    });

});


text:
package com.google.code.arm.sql;

import java.sql.NClob;

public class DelegatingNClob<S extends NClob> extends DelegatingClob<S> implements NClob {

    protected DelegatingNClob(S delegate) {
        super(delegate);
    }

}


text:
package org.newdawn.swingle;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JPanel;
import javax.swing.Popup;

/**
 * A popup implemenation that uses a software mode (Swing) panel to
 * display the popup contents. On OSX popups are always heavyweight
 * and this doesn't work when rendering to a image.
 *
 * @author kevin
 */
public class SoftPopup extends Popup {
	/** The frame that is repsonsible for this popup */
	private final HeadlessFrame frame;
	/** The panel on which the contents is shown */
	private JComponent panel = new JPanel();

	/**
	 * Create a new popup
	 *
	 * @param frame The frame owning the popup
	 * @param component The component to be display
	 * @param x The x coordinate at which to display the popup
	 * @param y The y coordinate at which to display the popup
	 */
	public SoftPopup(HeadlessFrame frame, Component component, int x, int y) {
		this.frame = frame;
		Dimension size = component.getPreferredSize();
		panel.setBounds(x,y,size.width,size.height);
		panel.setLayout(null);
		component.setBounds(0,0,size.width,size.height);
		panel.add(component);

		frame.getContentPane().add(panel);
		if (frame.getContentPane() instanceof JDesktopPane) {
			((JDesktopPane) frame.getContentPane()).moveToFront(panel);
		}
		component.invalidate();
		panel.validate();
	}

	/**
	 * @see javax.swing.Popup#hide()
	 */
	public void hide() {
		panel.setVisible(false);
	}

	/**
	 * @see javax.swing.Popup#show()
	 */
	public void show() {
		panel.setVisible(true);
	}
}


text:
package ovfimporttestsuite

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"reflect"
	"sort"
	"strings"
	"time"

	daisyCompute "github.com/GoogleCloudPlatform/compute-daisy/compute"

	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/utils/path"
	ovfimporter "github.com/GoogleCloudPlatform/compute-image-import/cli_tools/gce_ovf_import/ovf_importer"
	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools_tests/e2e"
	"github.com/GoogleCloudPlatform/compute-image-import/common/gcp"
	"github.com/GoogleCloudPlatform/compute-image-import/go/e2e_test_utils/junitxml"
	testconfig "github.com/GoogleCloudPlatform/compute-image-import/go/e2e_test_utils/test_config"
)

// OvfImportTestProperties hold common OVF import properties shared between
// instance and machine image imports.
type OvfImportTestProperties struct {
	IsWindows                 bool
	ExpectedStartupOutput     string
	FailureMatches            []string
	VerificationStartupScript string
	AllowFallbackToPDStandard bool
	BuildID                   string
	Zone                      string
	SourceURI                 string
	Os                        string
	MachineType               string
	Network                   string
	Subnet                    string
	Project                   string
	Tags                      []string
	ComputeServiceAccount     string
	InstanceServiceAccount    string
	NoInstanceServiceAccount  bool
	InstanceAccessScopes      string
	NoInstanceAccessScopes    bool
	InstanceMetadata          map[string]string
}

// BuildArgsMap builds CLI args map for all OVF import CLIs being tested
// (wrapper, gcloud). Specific args are provided as args to this func to allow
// customization for different tools (instance import, machine image import)
func BuildArgsMap(props *OvfImportTestProperties, testProjectConfig *testconfig.Project,
	gcloudBetaArgs, gcloudArgs, wrapperArgs []string) map[e2e.CLITestType][]string {

	project := GetProject(props, testProjectConfig)
	buildID := props.BuildID
	if buildID == "" {
		buildID = path.RandString(10)
	}
	gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--project=%v", project))
	gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--source-uri=%v", props.SourceURI))
	gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--zone=%v", props.Zone))

	gcloudArgs = append(gcloudArgs, fmt.Sprintf("--project=%v", project))
	gcloudArgs = append(gcloudArgs, fmt.Sprintf("--source-uri=%v", props.SourceURI))
	gcloudArgs = append(gcloudArgs, fmt.Sprintf("--zone=%v", props.Zone))

	wrapperArgs = append(wrapperArgs, fmt.Sprintf("-project=%v", project))
	wrapperArgs = append(wrapperArgs, fmt.Sprintf("-ovf-gcs-path=%v", props.SourceURI))
	wrapperArgs = append(wrapperArgs, fmt.Sprintf("-zone=%v", props.Zone))
	wrapperArgs = append(wrapperArgs, fmt.Sprintf("-build-id=%v", buildID))

	if len(props.Tags) > 0 {
		tags := strings.Join(props.Tags, ",")
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--tags=%v", tags))
		gcloudArgs = append(gcloudBetaArgs, fmt.Sprintf("--tags=%v", tags))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-tags=%v", tags))
	}
	if props.Os != "" {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--os=%v", props.Os))
		gcloudArgs = append(gcloudBetaArgs, fmt.Sprintf("--os=%v", props.Os))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-os=%v", props.Os))
	}
	if props.MachineType != "" {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--machine-type=%v", props.MachineType))
		gcloudArgs = append(gcloudArgs, fmt.Sprintf("--machine-type=%v", props.MachineType))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-machine-type=%v", props.MachineType))
	}
	if props.Network != "" {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--network=%v", props.Network))
		gcloudArgs = append(gcloudArgs, fmt.Sprintf("--network=%v", props.Network))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-network=%v", props.Network))
	}
	if props.Subnet != "" {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--subnet=%v", props.Subnet))
		gcloudArgs = append(gcloudArgs, fmt.Sprintf("--subnet=%v", props.Subnet))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-subnet=%v", props.Subnet))
	}
	if props.ComputeServiceAccount != "" {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--compute-service-account=%v", props.ComputeServiceAccount))
		gcloudArgs = append(gcloudArgs, fmt.Sprintf("--compute-service-account=%v", props.ComputeServiceAccount))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-compute-service-account=%v", props.ComputeServiceAccount))
	}
	if props.InstanceServiceAccount != "" && !props.NoInstanceServiceAccount {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--service-account=%v", props.InstanceServiceAccount))
		gcloudArgs = append(gcloudArgs, fmt.Sprintf("--service-account=%v", props.InstanceServiceAccount))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-service-account=%v", props.InstanceServiceAccount))
	}
	if props.NoInstanceServiceAccount {
		gcloudBetaArgs = append(gcloudBetaArgs, "--service-account=")
		gcloudArgs = append(gcloudArgs, "--service-account=")
		wrapperArgs = append(wrapperArgs, "-service-account=")
	}
	if props.InstanceAccessScopes != "" && !props.NoInstanceAccessScopes {
		gcloudBetaArgs = append(gcloudBetaArgs, fmt.Sprintf("--scopes=%v", props.InstanceAccessScopes))
		gcloudArgs = append(gcloudArgs, fmt.Sprintf("--scopes=%v", props.InstanceAccessScopes))
		wrapperArgs = append(wrapperArgs, fmt.Sprintf("-scopes=%v", props.InstanceAccessScopes))
	}
	if props.NoInstanceAccessScopes {
		gcloudBetaArgs = append(gcloudBetaArgs, "--scopes=")
		gcloudArgs = append(gcloudArgs, "--scopes=")
		wrapperArgs = append(wrapperArgs, "-scopes=")
	}

	argsMap := map[e2e.CLITestType][]string{
		e2e.Wrapper:                       wrapperArgs,
		e2e.GcloudBetaProdWrapperLatest:   gcloudBetaArgs,
		e2e.GcloudBetaLatestWrapperLatest: gcloudBetaArgs,
		e2e.GcloudGaLatestWrapperRelease:  gcloudArgs,
	}
	return argsMap
}

// GetProject returns project ID by prioritizing the value from OvfImportTestProperties.
// If not set, the value from testconfig.Project is used
func GetProject(props *OvfImportTestProperties, testProjectConfig *testconfig.Project) string {
	if props.Project != "" {
		return props.Project
	}
	return testProjectConfig.TestProjectID
}

// LoadScriptContent loads script content from local file system. If it fails,
// the whole program will exit with an error.
func LoadScriptContent(scriptPath string, args map[string]string, logger *log.Logger) string {
	scriptContentBytes, err := ioutil.ReadFile(scriptPath)
	if err != nil {
		logger.Printf("Error loading script `%v`: %v", scriptPath, err)
		os.Exit(1)
	}

	scriptContent := string(scriptContentBytes)

	for key, value := range args {
		scriptContent = strings.ReplaceAll(scriptContent, key, value)
	}

	return scriptContent
}

// VerifyInstance verifies that imported instance is matching OvfImportTestProperties.
func VerifyInstance(instance *gcp.InstanceBeta, client daisyCompute.Client,
	testCase *junitxml.TestCase, project string, logger *log.Logger, props *OvfImportTestProperties) {

	for attachedDiskIndex, attachedDisk := range instance.Disks {
		//Try to use device name to retrieve a PD. This works well for instance import
		disk, diskErr := client.GetDisk(project, props.Zone, attachedDisk.DeviceName)
		if diskErr != nil {
			// If device name didn't return a disk, try to use instance name as the
			// base for disk name. This should work for GMI import.

			diskNameSuffix := ""
			if attachedDiskIndex > 0 {
				// first/boot disk has the same name as instance. Data disks have suffix
				// based on their position
				diskNameSuffix = fmt.Sprintf("-%v", attachedDiskIndex)
			}
			disk, diskErr = client.GetDisk(project, props.Zone, instance.Name+diskNameSuffix)
			if diskErr != nil {
				e2e.Failure(testCase, logger,
					fmt.Sprintf("Can't retrieve disk `%v` for instance `%v`: %v",
						attachedDisk.DeviceName, instance.Name, diskErr))
				return
			}
		}

		// Verify disk type (SSD vs Standard)
		expectedDiskType := "pd-ssd"
		if !strings.Contains(disk.Type, expectedDiskType) && !props.AllowFallbackToPDStandard {
			e2e.Failure(testCase, logger, fmt.Sprintf(
				"Disk should be of `%v` type, but is `%v`", expectedDiskType, disk.Type))
			return
		}

		if attachedDisk.Boot {
			// The boot disk for a Windows instance must have the WINDOWS GuestOSFeature,
			// while the boot disk for other operating systems shouldn't have it.
			hasWindowsFeature := false
			for _, feature := range attachedDisk.GuestOsFeatures {
				if feature.Type == "WINDOWS" {
					hasWindowsFeature = true
					break
				}
			}
			if props.IsWindows && !hasWindowsFeature {
				testCase.WriteFailure(
					"Windows boot disk missing WINDOWS GuestOsFeature. Features found=%v",
					attachedDisk.GuestOsFeatures)
			} else if !props.IsWindows && hasWindowsFeature {
				testCase.WriteFailure(
					"Non-Windows boot disk includes WINDOWS GuestOsFeature. Features found=%v",
					attachedDisk.GuestOsFeatures)
			}
		}
	}

	if props.MachineType != "" && !strings.HasSuffix(instance.MachineType, props.MachineType) {
		testCase.WriteFailure(
			"Instance machine type `%v` doesn't match the expected machine type `%v`",
			instance.MachineType, props.MachineType)
		return
	}

	if !strings.HasSuffix(instance.Zone, props.Zone) {
		e2e.Failure(testCase, logger, fmt.Sprintf("Instance zone `%v` doesn't match requested zone `%v`",
			instance.Zone, props.Zone))
		return
	}

	//Verify networks
	if (props.Network != "" || props.Subnet != "") && len(instance.NetworkInterfaces) == 0 {
		e2e.Failure(testCase, logger,
			fmt.Sprintf("Instance does not have network interface when `%v` network flag is provided", props.Network))
		return
	}
	for _, networkInterface := range instance.NetworkInterfaces {
		if props.Network != "" && !strings.Contains(networkInterface.Network, props.Network) {
			e2e.Failure(testCase, logger,
				fmt.Sprintf("Instance network (%v) does not match network flag value: %v", networkInterface.Network, props.Network))
			return
		}
		if props.Subnet != "" && !strings.Contains(networkInterface.Subnetwork, props.Subnet) {
			e2e.Failure(testCase, logger,
				fmt.Sprintf("Instance subnetwork (%v) does not match subnetwork flag value: %v", networkInterface.Subnetwork, props.Subnet))
			return
		}
	}

	// Verify that the instance's tags match the user's request (regardless of order).
	expectedTags := map[string]struct{}{}
	for _, tag := range props.Tags {
		expectedTags[tag] = struct{}{}
	}
	actualTags := map[string]struct{}{}
	for _, tag := range instance.Tags.Items {
		actualTags[tag] = struct{}{}
	}
	if !reflect.DeepEqual(expectedTags, actualTags) {
		e2e.Failure(testCase, logger,
			fmt.Sprintf("Instance's tags don't match import request. Expected=`%v`, Actual=`%v`",
				props.Tags, instance.Tags.Items))
		return
	}

	// Verify instance service account
	if props.NoInstanceServiceAccount {
		if len(instance.ServiceAccounts) > 0 {
			e2e.Failure(testCase, logger,
				fmt.Sprintf("Instance service accounts should be empty but is `%v`", instance.ServiceAccounts[0].Email))
			return
		}
	} else {
		if len(instance.ServiceAccounts) == 0 {
			e2e.Failure(testCase, logger, "No service account on the instance when one should be set")
			return
		}
		if props.InstanceServiceAccount != "" {
			serviceAccountMatch := false
			var instanceServiceAccountEmails []string
			for _, instanceServiceAccount := range instance.ServiceAccounts {
				instanceServiceAccountEmails = append(instanceServiceAccountEmails, instanceServiceAccount.Email)
				if instanceServiceAccount.Email == props.InstanceServiceAccount {
					serviceAccountMatch = true
				}
			}
			if !serviceAccountMatch {
				e2e.Failure(testCase, logger, fmt.Sprintf("Instance service accounts (`%v`) don't contain custom service account `%v`",
					strings.Join(instanceServiceAccountEmails, ","), props.InstanceServiceAccount))
				return
			}
		}
	}

	// Verify instance access scopes
	expectedScopes := []string{}
	if props.InstanceAccessScopes != "" {
		expectedScopes = strings.Split(props.InstanceAccessScopes, ",")
	} else if !props.NoInstanceAccessScopes {
		expectedScopes = ovfimporter.DefaultInstanceAccessScopes
	}
	sort.Strings(expectedScopes)

	for _, instanceServiceAccount := range instance.ServiceAccounts {
		if props.NoInstanceAccessScopes && len(instanceServiceAccount.Scopes) > 0 {
			e2e.Failure(testCase, logger, fmt.Sprintf(
				"Instance access scopes for service account `%v` should be empty but are: %v",
				instanceServiceAccount.Email, strings.Join(instanceServiceAccount.Scopes, ",")))
			return
		}
		sort.Strings(instanceServiceAccount.Scopes)
		if len(instanceServiceAccount.Scopes) == 0 && len(expectedScopes) == 0 {
			continue
		}
		if !reflect.DeepEqual(expectedScopes, instanceServiceAccount.Scopes) {
			e2e.Failure(testCase, logger, fmt.Sprintf(
				"Instance access scopes (%v) for service account `%v` do not match expected scopes: `%v`. NoInstanceAccessScopes %v, len %v",
				strings.Join(instanceServiceAccount.Scopes, ","), instanceServiceAccount.Email, strings.Join(expectedScopes, ","), props.NoInstanceAccessScopes, len(instanceServiceAccount.Scopes)))
			return
		}
	}

	logger.Printf("[%v] Stopping instance before restarting with test startup script", instance.Name)
	err := client.StopInstance(project, props.Zone, instance.Name)

	if err != nil {
		testCase.WriteFailure("Error stopping imported instance: %v", err)
		return
	}

	if props.VerificationStartupScript == "" {
		logger.Printf("[%v] Will not set test startup script to instance metadata as it's not defined", instance.Name)
		return
	}

	// Store serial logs from test instance in Cloud Logging.
	if props.InstanceMetadata == nil {
		props.InstanceMetadata = make(map[string]string)
	}
	props.InstanceMetadata["serial-port-enable"] = "true"

	err = instance.StartWithScriptCode(props.VerificationStartupScript, props.InstanceMetadata)
	if err != nil {
		testCase.WriteFailure("Error starting instance `%v` with script: %v", instance.Name, err)
		return
	}
	logger.Printf("[%v] Waiting for `%v` in instance serial console.", instance.Name,
		props.ExpectedStartupOutput)
	if err := instance.WaitForSerialOutput(
		props.ExpectedStartupOutput, props.FailureMatches, 1, 5*time.Second, 15*time.Minute); err != nil {
		testCase.WriteFailure("Error during VM validation: %v", err)
	}
}


text:
package smarthouse.ejb.service;

import java.io.Serializable;

import org.jinouts.xml.bind.annotation.XmlAccessType;
import org.jinouts.xml.bind.annotation.XmlAccessorType;
import org.jinouts.xml.bind.annotation.XmlType;

/**
 *
Classe Java pour equipment complex type.
 *
 *
Le fragment de sch�ma suivant indique le contenu attendu figurant dans cette classe.
 *
 *

 * <complexType name="equipment">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="driverIdentifier" type="{http://service.ejb.smarthouse/}driverIdentifier" minOccurs="0"/>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="properties" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "equipment", propOrder = {
    "driverIdentifier",
    "id",
    "name",
    "properties"
})
public class Equipment implements Serializable{

    protected DriverIdentifier driverIdentifier;
    protected int id;
    protected String name;
    protected String properties;

    /**
     * Obtient la valeur de la propri�t� driverIdentifier.
     *
     * @return
     *     possible object is
     *     {@link DriverIdentifier }
     *
     */
    public DriverIdentifier getDriverIdentifier() {
        return driverIdentifier;
    }

    /**
     * D�finit la valeur de la propri�t� driverIdentifier.
     *
     * @param value
     *     allowed object is
     *     {@link DriverIdentifier }
     *
     */
    public void setDriverIdentifier(DriverIdentifier value) {
        this.driverIdentifier = value;
    }

    /**
     * Obtient la valeur de la propri�t� id.
     *
     */
    public int getId() {
        return id;
    }

    /**
     * D�finit la valeur de la propri�t� id.
     *
     */
    public void setId(int value) {
        this.id = value;
    }

    /**
     * Obtient la valeur de la propri�t� name.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * D�finit la valeur de la propri�t� name.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Obtient la valeur de la propri�t� properties.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getProperties() {
        return properties;
    }

    /**
     * D�finit la valeur de la propri�t� properties.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setProperties(String value) {
        this.properties = value;
    }

}


text:
MemScan
=======

Android app that allocates a lot of memory and continuously scans it for changes.


text:
package mundosk_libraries.java_websocket.exceptions;

/**
 * exception which indicates the frame payload is not sendable
 */
public class NotSendableException extends RuntimeException {

    /**
     * Serializable
     */
    private static final long serialVersionUID = -6468967874576651628L;

    /**
     * constructor for a NotSendableException
     */
    public NotSendableException() {
        super();
    }

    /**
     * constructor for a NotSendableException
     *
     * @param s the detail message.
     */
    public NotSendableException(String s) {
        super(s);
    }

    /**
     * constructor for a NotSendableException
     *
     * @param t the throwable causing this exception.
     */
    public NotSendableException(Throwable t) {
        super(t);
    }

    /**
     * constructor for a NotSendableException
     *
     * @param s the detail message.
     * @param t the throwable causing this exception.
     */
    public NotSendableException(String s, Throwable t) {
        super(s, t);
    }

}


text:
package org.hive2hive.core.network.data.futures;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import net.tomp2p.dht.FuturePut;
import net.tomp2p.dht.FutureRemove;
import net.tomp2p.dht.StorageLayer.PutStatus;
import net.tomp2p.futures.BaseFutureAdapter;
import net.tomp2p.peers.Number640;
import net.tomp2p.peers.PeerAddress;

import org.hive2hive.core.H2HConstants;
import org.hive2hive.core.model.BaseNetworkContent;
import org.hive2hive.core.network.data.DataManager;
import org.hive2hive.core.network.data.DataManager.H2HPutStatus;
import org.hive2hive.core.network.data.parameters.IParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A put future adapter for verifying a put of a {@link BaseNetworkContent} object. Provides failure handling
 * and a blocking wait.

 *
 * Failure Handling

 * Putting can fail when the future object failed, when the future object contains wrong data or the
 * responding node detected a failure. See {@link PutStatus} for possible failures. If putting fails the
 * adapter retries it to a certain threshold (see {@link H2HConstants#PUT_RETRIES}). All puts are
 * asynchronous. That's why the future listener attaches himself to the new future objects so that the adapter
 * can finally notify his/her listener about a success or failure.
 *
 * @author Seppi, Nico
 */
public class FuturePutListener extends BaseFutureAdapter<FuturePut> {

	private static final Logger logger = LoggerFactory.getLogger(FuturePutListener.class);

	private final IParameters parameters;
	private final DataManager dataManager;
	private final CountDownLatch latch;

	// used to count put retries
	private int putTries = 0;
	// used as return value
	private H2HPutStatus status;

	public FuturePutListener(IParameters parameters, DataManager dataManager) {
		this.parameters = parameters;
		this.dataManager = dataManager;
		this.latch = new CountDownLatch(1);
	}

	/**
	 * Wait (blocking) until the put is done
	 *
	 * @return true if successful, false if not successful
	 */
	public H2HPutStatus await() {
		try {
			latch.await(H2HConstants.AWAIT_NETWORK_OPERATION_MS * H2HConstants.PUT_RETRIES, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			logger.error("Could not wait until put has finished.", e);
		}

		return status;
	}

	@Override
	public void operationComplete(FuturePut future) throws Exception {
		if (future.isFailed()) {
			logger.warn("Put future was not successful. '{}'. Reason: {}", parameters.toString(), future.failedReason());
			retryPut();
			return;
		} else if (future.rawResult().isEmpty()) {
			logger.warn("Returned raw results are empty. '{}'", parameters.toString());
			retryPut();
			return;
		}

		// analyze returned put status
		List<PeerAddress> fail = new ArrayList<PeerAddress>();
		List<PeerAddress> versionFork = new ArrayList<PeerAddress>();
		for (PeerAddress peeradress : future.rawResult().keySet()) {
			Map<Number640, Byte> map = future.rawResult().get(peeradress);
			if (map == null) {
				logger.warn("A node gave no status (null) back. '{}'", parameters.toString());
				fail.add(peeradress);
			} else {
				for (Number640 key : map.keySet()) {
					byte putStatus = map.get(key);
					if (putStatus == -1) {
						logger.warn("Got an invalid status: {}", putStatus);
						fail.add(peeradress);
					} else {
						switch (PutStatus.values()[putStatus]) {
							case OK:
							case OK_PREPARED:
							case OK_UNCHANGED:
								break;
							case FAILED:
							case FAILED_SECURITY:
								logger.warn("A node denied putting data. reason = '{}'. '{}'",
										PutStatus.values()[putStatus], parameters.toString());
								fail.add(peeradress);
								break;
							case VERSION_FORK:
								logger.warn("A node responded with a version fork. '{}'", parameters.toString());
								versionFork.add(peeradress);
								break;
							default:
								logger.warn("Got an unknown status: {}", PutStatus.values()[putStatus]);
						}
					}
				}
			}
		}

		// check if majority of the contacted nodes responded with ok
		if ((double) fail.size() < ((double) future.rawResult().size()) / 2.0) {
			if (versionFork.isEmpty()) {
				if (parameters.hasPrepareFlag()) {
					// confirm put
					dataManager.confirmUnblocked(parameters).addListener(new BaseFutureAdapter<FuturePut>() {

						// used to count confirm retries
						private int confirmTries = 0;

						@Override
						public void operationComplete(FuturePut future) throws Exception {
							if (future.isFailed()) {
								logger.warn("Confirm future was not successful. Reason = '{}' {}", future.failedReason(),
										parameters.toString());
								retryConfirm();
								return;
							} else if (future.rawResult().isEmpty()) {
								logger.warn("Returned raw results are empty. {}", parameters.toString());
								retryConfirm();
								return;
							}

							// analyze returned status
							List<PeerAddress> fail = new ArrayList<PeerAddress>();
							for (PeerAddress peeradress : future.rawResult().keySet()) {
								Map<Number640, Byte> map = future.rawResult().get(peeradress);
								if (map == null) {
									logger.warn("A node gave no status (null) back. {}", parameters.toString());
									fail.add(peeradress);
								} else {
									for (Number640 key : future.rawResult().get(peeradress).keySet()) {
										byte putStatus = future.rawResult().get(peeradress).get(key);
										switch (PutStatus.values()[putStatus]) {
											case OK:
												break;
											case FAILED:
											case FAILED_SECURITY:
											case NOT_FOUND:
												logger.warn("A node could not confirm data. Reason = '{}'. {}",
														PutStatus.values()[putStatus], parameters.toString());
												fail.add(peeradress);
												break;
											default:
												logger.warn("Got an unknown status = '{}' {}",
														PutStatus.values()[putStatus], parameters.toString());
										}
									}
								}
							}

							// check if majority of the contacted nodes responded with ok
							if ((double) fail.size() < ((double) future.rawResult().size()) / 2.0) {
								status = H2HPutStatus.OK;
								latch.countDown();
							} else {
								logger.warn("{} of {} contacted nodes failed. {}", fail.size(), future.rawResult().size(),
										parameters.toString());
								retryConfirm();
							}
						}

						/**
						 * Retries a confirm till a certain threshold is reached (see
						 * {@link H2HConstants.CONFIRM_RETRIES}). A {@link RetryPutListener} tries to confirm
						 * again.
						 */
						private void retryConfirm() {
							if (confirmTries++ < H2HConstants.CONFIRM_RETRIES) {
								logger.warn("Confirm retry #{}. {}", confirmTries, parameters.toString());
								// retry confirmation, attach itself as listener
								dataManager.confirmUnblocked(parameters).addListener(this);
							} else {
								logger.error("Could not confirm put after {} tries. {}", confirmTries, parameters.toString());
								status = H2HPutStatus.FAILED;
								latch.countDown();
							}
						}
					});
				} else {
					status = H2HPutStatus.OK;
					latch.countDown();
				}
			} else {
				logger.warn("Version fork after put detected. Rejecting put.");
				// reject put
				dataManager.removeVersionUnblocked(parameters).addListener(new BaseFutureAdapter<FutureRemove>() {
					@Override
					public void operationComplete(FutureRemove future) {
						if (future.isFailed()) {
							logger.warn("Could not delete the prepared put. '{}'", parameters.toString());
						}
						status = H2HPutStatus.VERSION_FORK;
						latch.countDown();
					}
				});
			}
		} else {
			logger.warn("{} of {} contacted nodes failed.", fail.size(), future.rawResult().size());
			retryPut();
		}
	}

	/**
	 * Retries a put till a certain threshold is reached (see {@link H2HConstants.PUT_RETRIES}). Removes first
	 * the possibly succeeded puts. A {@link RetryPutListener} tries to put again the given content.
	 */
	private void retryPut() {
		if (putTries++ < H2HConstants.PUT_RETRIES) {
			logger.warn("Put retry #{}. '{}'", putTries, parameters.toString());
			// remove prior put
			dataManager.removeVersionUnblocked(parameters).addListener(new BaseFutureAdapter<FutureRemove>() {
				@Override
				public void operationComplete(FutureRemove future) {
					if (future.isFailed()) {
						logger.warn("Could not delete the newly put content. '{}'", parameters.toString());
					}
					// retry put, attach itself as listener
					dataManager.putUnblocked(parameters).addListener(FuturePutListener.this);
				}
			});
		} else {
			logger.error("Could not put data after {} tries. '{}'", putTries, parameters.toString());
			// remove prior put
			dataManager.removeVersionUnblocked(parameters).addListener(new BaseFutureAdapter<FutureRemove>() {
				@Override
				public void operationComplete(FutureRemove future) {
					if (future.isFailed()) {
						logger.warn("Could not delete the newly put content. '{}'", parameters.toString());
					}
					status = H2HPutStatus.FAILED;
					latch.countDown();
				}
			});
		}
	}

}


text:
coc2015
=======

LC Madrid Congress 2015 website


text:
package com.futureprocessing.documentjuggler;

import com.futureprocessing.documentjuggler.example.cars.CarsRepository;
import com.futureprocessing.documentjuggler.example.cars.model.Car;
import com.futureprocessing.documentjuggler.exception.FieldNotLoadedException;
import com.futureprocessing.documentjuggler.exception.LimitAlreadyPresentException;
import com.futureprocessing.documentjuggler.exception.SkipAlreadyPresentException;
import com.mongodb.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;

import static com.futureprocessing.documentjuggler.example.cars.CarsDBModel.Car.BRAND;
import static com.futureprocessing.documentjuggler.example.cars.CarsDBModel.Car.MODEL;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class ReadListTest {

    private CarsRepository carsRepository;

    @Mock
    private DB db;
    @Mock
    private DBCollection collection;
    @Mock
    private DBCursor cursor;

    @Before
    public void before() {
        given(db.getCollection(any())).willReturn(collection);
        given(collection.find(any(), any())).willReturn(cursor);

        carsRepository = new CarsRepository(db);
    }

    @Test
    public void shouldReadListOfDocuments() {
        // given
        String brand = "Ford";
        String model1 = "Mondeo";
        String model2 = "Focus";

        BasicDBObject car1 = new BasicDBObject(BRAND, brand).append(MODEL, model1);
        BasicDBObject car2 = new BasicDBObject(BRAND, brand).append(MODEL, model2);

        given(cursor.hasNext()).willReturn(true, true, false);
        given(cursor.next()).willReturn(car1, car2);

        // when
        List<Car> carReaders = carsRepository.find(car -> car.withBrand(brand)).all();

        // then
        assertThat(extractProperty("model").from(carReaders)).containsExactly(model1, model2);
    }

    @Test
    public void shouldReturnEmptyListIfNoMatchingDocuments() {
        // given
        given(cursor.hasNext()).willReturn(false);

        // when
        List<Car> carReaders = carsRepository.find(car -> car.withBrand("Fiat")).all();

        // then
        assertThat(carReaders).isEmpty();
    }

    @Test
    public void shouldNotPassQueryWhenTryingToFindAll() {
        // given

        // when
        carsRepository.find().all(MODEL);

        // then
        verify(collection).find(isNull(DBObject.class), any(DBObject.class));
    }

    @Test
    public void shouldPassSkipAndLimitWhenTryingToGetOnePageOfResults() {
        // given

        // when
        carsRepository.find().skip(1).limit(10).all();

        // then
        verify(cursor).limit(eq(10));
        verify(cursor).skip(eq(1));
    }

    @Test
    public void shouldThrowSkipAlreadyPresentExceptionWhenSkipIsPassedTwice() {
        // given

        // when
        try {
            carsRepository.find().skip(1).skip(10).all();
        } catch (SkipAlreadyPresentException e) {
            //then
            return;
        }

        // then
        fail("Should throw SkipAlreadyPresentException exception");
    }

    @Test
    public void shouldThrowLimitAlreadyPresentExceptionWhenLimitIsPassedTwice() {
        // given

        // when
        try {
            carsRepository.find().limit(1).limit(10).all();
        } catch (LimitAlreadyPresentException e) {
            //then
            return;
        }

        // then
        fail("Should throw LimitAlreadyPresentException exception");
    }

    @Test
    public void shouldThrowFieldNotLoadedExceptionWhenAccessingNotLoadedField() {
        // given
        BasicDBObject dbObject = new BasicDBObject();
        given(cursor.hasNext()).willReturn(true, false);
        given(cursor.next()).willReturn(dbObject);

        List<Car> carReaders = carsRepository.find(car -> car.withBrand("fiat")).all(MODEL);

        // when
        try {
            carReaders.get(0).getBrand();
        } catch (FieldNotLoadedException e) {
            // then
            return;
        }

        fail("Should thrown exception");
    }
}


text:
import pygame

class dino():
    def __init__(self, position, type, lives=1, smoothness_rate=0.3):
        self.actual_type = type
        self.__image = pygame.image.load('../resources/' + self.actual_type + '.png')
        self.__size = (self.__image.get_width(), self.__image.get_height())
        self.__position = position
        self.__movement = 1
        self.__smoothness_rate = smoothness_rate
        self.__jumping = False
        self.__lives = lives
        self.__coins = 0
        self.__total_coins = 0
        self.__initial_position = position
        self.__initial_lives = lives

    def get_image(self):
        return self.__image

    def get_position(self):
        return self.__position

    def get_movement(self):
        return self.__movement

    def get_size(self):
        return self.__size

    def get_lives(self):
        return self.__lives

    def get_coins(self):
        return self.__coins

    def get_type(self):
        return self.actual_type

    def get_total_coins(self):
        return self.__total_coins

    def is_jumping(self):
        return self.__jumping

    def set_position(self, value):
        self.__position = value

    def set_movement(self, value):
        self.__movement = value

    def set_jumping(self, value):
        self.__jumping = value

    def set_lives(self, value, type='default'):
        if (type is 'default'):
            self.__lives = value
        if (type is 'decrement'):
            self.__lives -= value

    def set_coins(self, value, type='default'):
        if (type is 'default'):
            self.__coins = value
        if (type is 'increment'):
            self.__coins += value

    def reset(self):
        self.__position = self.__initial_position
        self.__lives = self.__initial_lives
        self.__total_coins += self.__coins
        self.__coins = 0
        self.__movement = 1

    def jump(self, threshold):
        if (self.__movement):
            self.set_movement(self.__movement - self.__smoothness_rate)
        if (self.get_position()[1] + self.get_size()[1] >= threshold):
            self.set_movement(0)
            self.set_jumping(False)
            self.set_position((self.get_position()[0],
                               threshold - self.get_size()[1] - 1))
        else:
            self.set_position((self.get_position()[0],
                               self.get_position()[1] - self.get_movement()))


text:
import sys
import os
import numpy as np

import theano
import theano.tensor as T
import lasagne as nn

sys.path.append("..")
import utils as u
import config as c
from batch_norm_layer import batch_norm as bn
from lasagne.layers import InputLayer, Conv2DLayer, MaxPool2DLayer
from lasagne.layers import GlobalPoolLayer, NonlinearityLayer, InverseLayer

def build_fcae(input_var, channels=1):
    ret = {}
    ret['input'] = layer = InputLayer(shape=(None, channels, None, None), input_var=input_var)
    ret['conv1'] = layer = bn(Conv2DLayer(layer, num_filters=128, filter_size=5, pad='full'))
    ret['pool1'] = layer =  MaxPool2DLayer(layer, pool_size=2)
    ret['conv2'] = layer = bn(Conv2DLayer(layer, num_filters=256, filter_size=3, pad='full'))
    ret['pool2'] = layer = MaxPool2DLayer(layer, pool_size=2)
    ret['conv3'] = layer = bn(Conv2DLayer(layer, num_filters=32, filter_size=3, pad='full'))
    ret['enc'] = layer = GlobalPoolLayer(layer)
    ret['ph1'] = layer = NonlinearityLayer(layer, nonlinearity=None)
    ret['ph2'] = layer = NonlinearityLayer(layer, nonlinearity=None)
    ret['unenc'] = layer = bn(InverseLayer(layer, ret['enc']))
    ret['deconv3'] = layer = bn(Conv2DLayer(layer, num_filters=256, filter_size=3))
    ret['depool2'] = layer = InverseLayer(layer, ret['pool2'])
    ret['deconv2'] = layer = bn(Conv2DLayer(layer, num_filters=128, filter_size=3))
    ret['depool1'] = layer = InverseLayer(layer, ret['pool1'])
    ret['output'] = layer = Conv2DLayer(layer, num_filters=1, filter_size=5,
                                     nonlinearity=nn.nonlinearities.sigmoid)
    return ret

def main(num_epochs = 20):

    print("Building model and compiling functions...")
    input_var = T.tensor4('inputs')
    fcae = build_fcae(input_var)

    output = nn.layers.get_output(fcae['output'])
    output_det = nn.layers.get_output(fcae['output'], deterministic=True)
    loss = nn.objectives.binary_crossentropy(output, input_var).mean()
    test_loss = nn.objectives.binary_crossentropy(output_det, input_var).mean()

    # ADAM updates
    params = nn.layers.get_all_params(fcae['output'], trainable=True)
    updates = nn.updates.adam(loss, params, learning_rate=1e-3)
    train_fn = theano.function([input_var], loss, updates=updates)
    val_fn = theano.function([input_var], test_loss)
    ae_fn = theano.function([input_var], nn.layers.get_output(fcae['output']))

    data = u.DataH5PyStreamer(os.path.join(c.external_data, 'mnist.hdf5'), batch_size=128)
    hist = u.train_with_hdf5(data, num_epochs=num_epochs,
            train_fn = train_fn, test_fn = val_fn,
            max_per_epoch=40,
            tr_transform = lambda x: u.raw_to_floatX(x[0], pixel_shift=0.),
            te_transform = lambda x: u.raw_to_floatX(x[0], pixel_shift=0.))

    u.save_params(fcae['output'], 'fcae_params_{}.npz'.format(np.asarray(hist)[-1,-1]))

    from PIL import Image
    from matplotlib import pyplot as plt

    streamer = data.streamer()
    imb = next(streamer.get_epoch_iterator())
    batch = u.raw_to_floatX(imb[0], pixel_shift=0.).transpose((0,1,3,2))

    orig_dim = 28
    im = Image.new("RGB", (orig_dim*20, orig_dim*20))
    for j in xrange(10):
        dim = orig_dim
        orig_im = Image.fromarray(u.get_picture_array(batch,
            np.random.randint(batch.shape[0]), shift=0.0))
        im.paste(orig_im.resize((2*orig_dim, 2*orig_dim), Image.ANTIALIAS),
                box=(0,j*orig_dim*2))
        new_im = {}
        for i in xrange(9):
            new_im = orig_im.resize((dim, dim), Image.ANTIALIAS)
            new_im = ae_fn(u.arr_from_img(new_im, shift=0.).reshape(1,-1,dim,dim))
            new_im = Image.fromarray(u.get_picture_array(new_im, 0, shift=0.))\
                    .resize((orig_dim*2, orig_dim*2), Image.ANTIALIAS)
            im.paste(new_im, box=((i+1)*orig_dim*2, j*orig_dim*2))
            dim = int(dim * 1.2)
    im.save('increasing_size_autoencoded.jpg')

if __name__ == '__main__':
    # make all arguments of main(...) command line arguments (with type inferred from
    # the default value) - this doesn't work on bools so those are strings when
    # passed into main.
    import argparse, inspect
    parser = argparse.ArgumentParser(description='Command line options')
    ma = inspect.getargspec(main)
    for arg_name,arg_type in zip(ma.args[-len(ma.defaults):],[type(de) for de in ma.defaults]):
        parser.add_argument('--{}'.format(arg_name), type=arg_type, dest=arg_name)
    args = parser.parse_args(sys.argv[1:])
    main(**{k:v for (k,v) in vars(args).items() if v is not None})


text:
var _ = require('./vendor/lodash-custom.js');
var Template = require('../templates/section.html');
var CommentTemplate = require('../templates/comment.html');
var FormTemplate = require('../templates/form.html');
var mobileCheck = require('./helpers/mobile-check.js');
var $ = jQuery;

/**
 * Creates a new Section object, which is responsible for managing a
 * single comment section.
 * @param {Object} eventPipe The Emitter object used for passing around events.
 * @param {Array} comments   The array of comments for this section. Optional.
 */
function Section( eventPipe, $el, currentUser, comments ) {
	this.eventPipe = eventPipe;
	this.$el = $el;
	this.comments = comments ? comments.comments : [];
	this.currentUser = currentUser || null;
	this.clickEventName = mobileCheck() ? 'touchstart' : 'click';

	this.id = $el.data('section-id');

	this.$el.on(this.clickEventName, '.side-comment .marker', _.bind(this.markerClick, this));
	this.$el.on(this.clickEventName, '.side-comment .add-comment', _.bind(this.addCommentClick, this));
	this.$el.on(this.clickEventName, '.side-comment .reply-comment', _.bind(this.replyCommentClick, this));
	this.$el.on(this.clickEventName, '.side-comment .post', _.bind(this.postCommentClick, this));
	this.$el.on(this.clickEventName, '.side-comment .cancel', _.bind(this.cancelCommentClick, this));
	this.$el.on(this.clickEventName, '.side-comment .delete', _.bind(this.deleteCommentClick, this));
	this.render();
}

/**
 * Click callback event on markers.
 * @param  {Object} event The event object.
 */
Section.prototype.markerClick = function( event ) {
	event.preventDefault();
	this.select();
};

/**
 * Callback for the comment button click event.
 * @param {Object} event The event object.
 */
Section.prototype.addCommentClick = function( event ) {
  event.preventDefault();
  if (this.currentUser) {
  	this.showCommentForm();
  } else {
  	this.eventPipe.emit('addCommentAttempted');
  }
};

/**
 * Show the comment form for this section.
 */
Section.prototype.showCommentForm = function() {
  if (this.comments.length > 0) {
  	this.hideCommentForm();
    this.$el.find('.add-comment').addClass('hide');
    this.$el.find('.comment-form').addClass('active');
  }

  this.focusCommentBox();
};

/**
 * Callback for the reply button click event.
 * @param {Object} event The event object.
 */
Section.prototype.replyCommentClick = function( event ) {
  event.preventDefault();
  if (this.currentUser) {
  	this.showReplyForm(event.currentTarget);
  } else {
  	this.eventPipe.emit('addCommentAttempted');
  }
};

/**
 * Show the reply form for this section.
 */
Section.prototype.showReplyForm = function( replyButton ) {
  if (this.comments.length > 0) {
    this.hideCommentForm();
    this.$el.find(replyButton).addClass('hide');
    $form = $(_.find($.makeArray(this.$el.find('.reply-form')), function (el) {return el.dataset.parent === replyButton.dataset.comment}));
    $form.addClass('active');
  }

  this.focusCommentBox();
};

/**
 * Hides the comment form for this section.
 */
Section.prototype.hideCommentForm = function() {
  if (this.comments.length > 0) {
    this.$el.find('a[class*="-comment"]').removeClass('hide');
    this.$el.find('div[class*="-form"]').removeClass('active');
  }

  this.$el.find('.comment-box').empty();
};

/**
 * Focus on the comment box in the comment form.
 */
Section.prototype.focusCommentBox = function() {
	// NOTE: !!HACK!! Using a timeout here because the autofocus causes a weird
	// "jump" in the form. It renders wider than it should be on screens under 768px
	// and then jumps to a smaller size.
	setTimeout(_.bind(function(){
		this.$el.find('.comment-box').get(0).focus();
	}, this), 300);
};

/**
 * Cancel comment callback.
 * @param  {Object} event The event object.
 */
Section.prototype.cancelCommentClick = function( event ) {
  event.preventDefault();
  this.cancelComment();
};

/**
 * Cancel adding of a comment.
 */
Section.prototype.cancelComment = function() {
  if (this.comments.length > 0) {
    this.hideCommentForm();
  } else {
  	this.deselect();
    this.eventPipe.emit('hideComments');
  }
};

/**
 * Post comment callback.
 * @param  {Object} event The event object.
 */
Section.prototype.postCommentClick = function( event ) {
  event.preventDefault();
  this.postComment();
};

/**
 * Post a comment to this section.
 */
Section.prototype.postComment = function() {
  if ( this.$el.find('.comments > li').length > 0 ){
  	var $commentForm = this.$el.find('div[class*="-form"].active');
  } else {
  	var $commentForm = this.$el.find('div[class*="-form"]');
  }

  var $commentBox = $commentForm.find('.comment-box'),
  	  commentBody = $commentBox.val(),
  	  comment = {
	  	sectionId: this.id,
	  	comment: commentBody,
	  	authorAvatarUrl: this.currentUser.avatarUrl,
	  	authorName: this.currentUser.name,
	  	authorId: this.currentUser.id,
	  	authorUrl: this.currentUser.authorUrl || null,
	  	replies: []
	  };

  if ( Number($commentForm.data('parent')) ) {
  	comment.parentId = Number($commentForm.data('parent'));
  }

  $commentBox.val(''); // Clear the comment.
  this.eventPipe.emit('commentPosted', comment);
};

/**
 * Insert a comment into this sections comment list.
 * @param  {Object} comment A comment object.
 */
Section.prototype.insertComment = function( comment ) {

	var newCommentHtml = _.template(CommentTemplate, {
		comment: comment,
		currentUser: this.currentUser,
		formTemplate: FormTemplate,
		self: CommentTemplate
	});

	if ( comment.parentId !== undefined ) {
		_.find(this.comments, { id: comment.parentId }).replies.push(comment);
		$parent = $(_.find($.makeArray(this.$el.find('.comments > li')), function ( el ) { return el.dataset.commentId == comment.parentId }));
		$parent.find('.replies').append(newCommentHtml);
	} else {
		this.comments.push(comment);
		this.$el.find('.comments').append(newCommentHtml);
	}

	this.$el.find('.side-comment').addClass('has-comments');
	this.updateCommentCount();
	this.hideCommentForm();
};

/**
 * Increments the comment count for a given section.
 */
Section.prototype.updateCommentCount = function() {
	this.$el.find('.marker span').text(this.comments.length);
};

/**
 * Event handler for delete comment clicks.
 * @param  {Object} event The event object.
 */
Section.prototype.deleteCommentClick = function( event ) {
	event.preventDefault();
	var commentId = $(event.target).closest('li').data('comment-id'),
		parentId = $(event.target).data('parent-id');

	if (window.confirm("Are you sure you want to delete this comment?")) {
		this.deleteComment(commentId, parentId);
	}
};

/**
 * Finds the comment and emits an event with the comment to be deleted.
 * @param commentId ID of the comment to be deleted
 * @param parentId ID of the parent comment of the reply to be deleted. Optional
 */
Section.prototype.deleteComment = function( commentId, parentId ) {
	if ( parentId != null ) {
		var parent = _.find(this.comments, { id: parentId }),
			comment = _.find(parent.replies, { id: commentId });
	} else {
		var comment = _.find(this.comments, { id: commentId });
	}

	comment.sectionId = this.id;
	this.eventPipe.emit('commentDeleted', comment);
};

/**
 * Removes the comment from the list of comments and the comment array.
 * @param commentId ID of the comment to be removed from this section
 * @param parentId ID of the parent comment of the reply to be removed from this section. Optional
 */
Section.prototype.removeComment = function( commentId, parentId ) {

	if ( parentId != null ) {
		var comment = _.find(this.comments, { id: parentId });
		comment.replies = _.reject( comment.replies, { id: commentId });
		this.$el.find('.side-comment .comments > li[data-comment-id="'+parentId+'"] .replies li[data-comment-id="'+commentId+'"]').remove();
	} else {
		var comment = _.find(this.comments, { id: commentId });

		if ( comment.replies.length > 0 ) {
			this.replaceCommentWithReplies( comment );
		} else {
			this.comments = _.reject(this.comments, { id: commentId });
			this.$el.find('.side-comment .comments li[data-comment-id="'+commentId+'"]').remove();
			this.updateCommentCount();
		}
	}

	if (this.comments.length < 1) {
		this.$el.find('.side-comment').removeClass('has-comments');
	}
};

/**
 * Replace a comment with replies
 *
 *
*/
Section.prototype.replaceCommentWithReplies = function ( comment ) {
	var $commentEl = this.$el.find('.side-comment .comments > li[data-comment-id="'+ comment.id +'"] > .comment');

	comment.deleted = true;
	$commentEl.html('Comment deleted by the author');
}

/**
 * Mark this section as selected. Delsect if this section is already selected.
 */
Section.prototype.select = function() {
	if (this.isSelected()) {
		this.deselect();
		this.eventPipe.emit('sectionDeselected', this);
	} else {
		this.$el.find('.side-comment').addClass('active');

		if (this.comments.length === 0 && this.currentUser) {
		  this.focusCommentBox();
		}

		this.eventPipe.emit('sectionSelected', this);
	}
};

/**
 * Deselect this section.
 */
Section.prototype.deselect = function() {
	this.$el.find('.side-comment').removeClass('active');
	this.hideCommentForm();
};

Section.prototype.isSelected = function() {
	return this.$el.find('.side-comment').hasClass('active');
};

/**
 * Get the class to be used on the side comment section wrapper.
 * @return {String} The class names to use.
 */
Section.prototype.sectionClasses = function() {
	var classes = '';

	if (this.comments.length > 0) {
		classes = classes + ' has-comments';
	}
	if (!this.currentUser) {
		classes = classes + ' no-current-user'
	}

	return classes;
};

/**
 * Render this section into the DOM.
 */
Section.prototype.render = function() {
	this.$el.find('.side-comment').remove();
	$(_.template(Template, {
	  commentTemplate: CommentTemplate,
	  comments: this.comments,
	  sectionClasses: this.sectionClasses(),
	  formTemplate: FormTemplate,
	  currentUser: this.currentUser
	})).appendTo(this.$el);
};

/**
 * Desttroy this Section object. Generally meaning unbind events.
 */
Section.prototype.destroy = function() {
	this.$el.off();
}

module.exports = Section;