text:
package io.proleap.cobol.asg.metamodel.data.communication.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.proleap.cobol.CobolParser.CommunicationDescriptionEntryFormat1Context;
import io.proleap.cobol.CobolParser.EndKeyClauseContext;
import io.proleap.cobol.CobolParser.MessageCountClauseContext;
import io.proleap.cobol.CobolParser.MessageDateClauseContext;
import io.proleap.cobol.CobolParser.MessageTimeClauseContext;
import io.proleap.cobol.CobolParser.StatusKeyClauseContext;
import io.proleap.cobol.CobolParser.SymbolicQueueClauseContext;
import io.proleap.cobol.CobolParser.SymbolicSourceClauseContext;
import io.proleap.cobol.CobolParser.SymbolicSubQueueClauseContext;
import io.proleap.cobol.CobolParser.TextLengthClauseContext;
import io.proleap.cobol.asg.metamodel.ProgramUnit;
import io.proleap.cobol.asg.metamodel.call.Call;
import io.proleap.cobol.asg.metamodel.data.communication.CommunicationDescriptionEntryInput;
import io.proleap.cobol.asg.metamodel.data.communication.EndKeyClause;
import io.proleap.cobol.asg.metamodel.data.communication.MessageCountClause;
import io.proleap.cobol.asg.metamodel.data.communication.MessageDateClause;
import io.proleap.cobol.asg.metamodel.data.communication.MessageTimeClause;
import io.proleap.cobol.asg.metamodel.data.communication.StatusKeyClause;
import io.proleap.cobol.asg.metamodel.data.communication.SymbolicQueueClause;
import io.proleap.cobol.asg.metamodel.data.communication.SymbolicSourceClause;
import io.proleap.cobol.asg.metamodel.data.communication.SymbolicSubQueueClause;
import io.proleap.cobol.asg.metamodel.data.communication.TextLengthClause;

public class CommunicationDescriptionEntryInputImpl extends CommunicationDescriptionEntryImpl
		implements CommunicationDescriptionEntryInput {

	private final static Logger LOG = LoggerFactory.getLogger(CommunicationDescriptionEntryInputImpl.class);

	protected final CommunicationDescriptionEntryFormat1Context ctx;

	protected EndKeyClause endKeyClause;

	protected EndKeyClauseContext endKeyClauseContext;

	protected MessageCountClause messageCountClause;

	protected MessageDateClause messageDateClause;

	protected MessageTimeClause messageTimeClause;

	protected StatusKeyClause statusKeyClause;

	protected SymbolicQueueClause symbolicQueueClause;

	protected SymbolicSourceClause symbolicSourceClause;

	protected SymbolicSubQueueClause symbolicSubQueueClause;

	protected TextLengthClause textLengthClause;

	public CommunicationDescriptionEntryInputImpl(final String name, final ProgramUnit programUnit,
			final CommunicationDescriptionEntryFormat1Context ctx) {
		super(name, programUnit, ctx);

		this.ctx = ctx;
	}

	@Override
	public EndKeyClause addEndKeyClause(final EndKeyClauseContext ctx) {
		EndKeyClause result = (EndKeyClause) getASGElement(ctx);

		if (result == null) {
			result = new EndKeyClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			endKeyClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public MessageCountClause addMessageCountClause(final MessageCountClauseContext ctx) {
		MessageCountClause result = (MessageCountClause) getASGElement(ctx);

		if (result == null) {
			result = new MessageCountClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			messageCountClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public MessageDateClause addMessageDateClause(final MessageDateClauseContext ctx) {
		MessageDateClause result = (MessageDateClause) getASGElement(ctx);

		if (result == null) {
			result = new MessageDateClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			messageDateClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public MessageTimeClause addMessageTimeClause(final MessageTimeClauseContext ctx) {
		MessageTimeClause result = (MessageTimeClause) getASGElement(ctx);

		if (result == null) {
			result = new MessageTimeClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			messageTimeClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public StatusKeyClause addStatusKeyClause(final StatusKeyClauseContext ctx) {
		StatusKeyClause result = (StatusKeyClause) getASGElement(ctx);

		if (result == null) {
			result = new StatusKeyClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			statusKeyClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public SymbolicQueueClause addSymbolicQueueClause(final SymbolicQueueClauseContext ctx) {
		SymbolicQueueClause result = (SymbolicQueueClause) getASGElement(ctx);

		if (result == null) {
			result = new SymbolicQueueClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			symbolicQueueClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public SymbolicSourceClause addSymbolicSourceClause(final SymbolicSourceClauseContext ctx) {
		SymbolicSourceClause result = (SymbolicSourceClause) getASGElement(ctx);

		if (result == null) {
			result = new SymbolicSourceClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			symbolicSourceClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public SymbolicSubQueueClause addSymbolicSubQueueClause(final SymbolicSubQueueClauseContext ctx) {
		SymbolicSubQueueClause result = (SymbolicSubQueueClause) getASGElement(ctx);

		if (result == null) {
			result = new SymbolicSubQueueClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			/*
			 * sub queue
			 */
			final SymbolicSubQueueClause.SymbolicSubQueueClauseType type;

			if (ctx.SUB_QUEUE_1() != null) {
				type = SymbolicSubQueueClause.SymbolicSubQueueClauseType.SUB_QUEUE_1;
			} else if (ctx.SUB_QUEUE_2() != null) {
				type = SymbolicSubQueueClause.SymbolicSubQueueClauseType.SUB_QUEUE_2;
			} else if (ctx.SUB_QUEUE_3() != null) {
				type = SymbolicSubQueueClause.SymbolicSubQueueClauseType.SUB_QUEUE_3;
			} else {
				LOG.warn("unknown type at {}", ctx);
				type = null;
			}

			result.setSymbolicSubQueueClauseType(type);

			symbolicSubQueueClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public TextLengthClause addTextLengthClause(final TextLengthClauseContext ctx) {
		TextLengthClause result = (TextLengthClause) getASGElement(ctx);

		if (result == null) {
			result = new TextLengthClauseImpl(programUnit, ctx);

			final Call dataDescCall = createCall(ctx.dataDescName());
			result.setDataDescCall(dataDescCall);

			textLengthClause = result;
			registerASGElement(result);
		}

		return result;
	}

	@Override
	public CommunicationDescriptionEntryType getCommunicationDescriptionEntryType() {
		return CommunicationDescriptionEntryType.INPUT;
	}

	@Override
	public EndKeyClause getEndKeyClause() {
		return endKeyClause;
	}

	@Override
	public MessageCountClause getMessageCountClause() {
		return messageCountClause;
	}

	@Override
	public MessageDateClause getMessageDateClause() {
		return messageDateClause;
	}

	@Override
	public MessageTimeClause getMessageTimeClause() {
		return messageTimeClause;
	}

	@Override
	public StatusKeyClause getStatusKeyClause() {
		return statusKeyClause;
	}

	@Override
	public SymbolicQueueClause getSymbolicQueueClause() {
		return symbolicQueueClause;
	}

	@Override
	public SymbolicSourceClause getSymbolicSourceClause() {
		return symbolicSourceClause;
	}

	@Override
	public SymbolicSubQueueClause getSymbolicSubQueueClause() {
		return symbolicSubQueueClause;
	}

	@Override
	public TextLengthClause getTextLengthClause() {
		return textLengthClause;
	}

}


text: search_result['4501']=["topic_0000000000000AD0.html","CompanyService.GetAreas Method",""];

redpajama_set_name: RedPajamaGithub


text:
owncloud-news-app
=================

A MacOS RSS Reader that gets news from your owncloud news plugin

**WARNING!!!** This software is not even alpha ready and could therefore contain bugs that may screw up your owncloud news. Use at your own risk.

![image](https://raw.githubusercontent.com/phpwutz/owncloud-news-app/master/screenshot.png)


text:
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[Route("values")]
[Produces("application/json")]
public class ValuesController : Controller
{
    private readonly IRepository _repository;
    public ValuesController(IRepository repository){
        _repository = repository;
    }

    /// <summary>
    /// Returns a collection of MyModel items
    /// </summary>
    /// <returns>Returns a collection of MyModel items</returns>
    /// <response code="200">Returns a collection of MyModel items</response>
    [Authorize]
    [HttpGet("")]
    [Produces("application/json", Type = typeof(IEnumerable<MyModel>))]
    [ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]
    public IActionResult GetAll()
    {
        return new ObjectResult(_repository.GetAll());
    }

    /// <summary>
    /// Returns a specific MyModel item
    /// </summary>
    /// <param name="id"></param>
    /// <returns>Returns specific MyModel item</returns>
    /// <response code="200">Returns specific MyModel item</response>
    /// <response code="404">If the MyModel item is null</response>
    [HttpGet("{id}", Name = "GetModel")]
    [Produces(typeof(MyModel))]
    [ProducesResponseType(typeof(MyModel), 200)]
    [ProducesResponseType(typeof(MyModel), 404)]
    public IActionResult  Get(string id)
    {
        return new ObjectResult(_repository.Get(id));
    }

    /// <summary>
    /// Creates a MyModel item
    /// </summary>
    /// <param name="item">An item to create</param>
    /// <returns>new created MyModel item</returns>
    /// <response code="201">Returns the newly created item</response>
    /// <response code="400">If the item is null</response>
    [Authorize]
    [HttpPost]
    [Produces(typeof(MyModel))]
    [ProducesResponseType(typeof(MyModel), 201)]
    [ProducesResponseType(typeof(MyModel), 400)]
    public IActionResult Create([FromBody] MyModel item)
    {
        if (item == null)
        {
            return BadRequest();
        }
        _repository.Add(item);
        return CreatedAtRoute("GetModel", new { id = item.Id }, item);
    }

    /// <summary>
    /// Updates a specific MyModel item
    /// </summary>
    /// <param name="id">The id of the instance</param>
    /// <param name="item">An instance of MyModel</param>
    /// <returns></returns>
    /// <response code="204">Returns when item was updated</response>
    [Authorize]
    [HttpPut("{id}")]
    [ProducesResponseType(typeof(MyModel), 204)]
    public IActionResult Update(string id, [FromBody] MyModel item)
    {
        _repository.Edit(id, item);
        return NoContent();
    }

    /// <summary>
    /// Updates a specific MyModel item
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    /// <response code="204">Returns when item was updated</response>
    [Authorize]
    [HttpDelete("{id}")]
    [ProducesResponseType(typeof(MyModel), 204)]
    public IActionResult Delete(string id)
    {
        _repository.Delete(id);
        return NoContent();
    }
}


text:
package org.apache.helix.model.builder;

import java.util.ArrayList;

import org.apache.helix.model.IdealState.RebalanceMode;

/**
 * IS Builder for resource in Full-Auto rebalance mode.
 */
public class FullAutoModeISBuilder extends IdealStateBuilder {
  public FullAutoModeISBuilder(String resourceName) {
    super(resourceName);
    setRebalancerMode(RebalanceMode.FULL_AUTO);
  }

  /**
   * Add a partition, Helix will automatically assign the placement and state
   * for this partition at runtime.
   * @param partitionName
   */
  public FullAutoModeISBuilder add(String partitionName) {
    if (_record.getListField(partitionName) == null) {
      _record.setListField(partitionName, new ArrayList<String>());
    }

    return this;
  }
}


text:
#ifndef SUBSTREAM_H
#define SUBSTREAM_H

#include <QtGlobal>

class Bitmap;
class FileBuffer;
class Palette;
class QImage;
class SubPicture;
class SubPictureDVD;
class SubtitleProcessor;

class Substream
{
public:
    virtual ~Substream() { }

    virtual void decode(int index) = 0;

    virtual int primaryColorIndex() = 0;
    virtual int numFrames() = 0;
    virtual int numForcedFrames() = 0;

    virtual qint64 endTime(int index) = 0;
    virtual qint64 startTime(int index) = 0;
    virtual qint64 startOffset(int index) = 0;

    virtual bool isForced(int index) = 0;

    virtual Bitmap &bitmap() = 0;

    virtual Palette &palette() = 0;

    virtual SubPicture *subPicture(int index) = 0;

    virtual QImage image() = 0;
    virtual QImage image(Bitmap &bitmap) = 0;

protected:
    int _numForcedFrames = 0;
};

#endif // SUBSTREAM_H


text:
package io.apicurio.hub.core.editing.ops;

/**
 * @author Marc Savy {@literal <marc@rhymewithgravy.com>}
 */
public class JoinLeaveOperation extends BaseOperation {

    private String user;
    private String id;

    public JoinLeaveOperation() {}

    public String getUser() {
        return user;
    }

    public JoinLeaveOperation setUser(String user) {
        this.user = user;
        return this;
    }

    public String getId() {
        return id;
    }

    public JoinLeaveOperation setId(String id) {
        this.id = id;
        return this;
    }

}


text:
package evaluator;
import java.util.ArrayList;

public class Node {
	private Operand mainFunc;
	private ArrayList<Node> children;

	public Node(ArrayList<Func> function){
	while(stripLeadTail(function));
	if(function.size()==1 && function.get(0).isANumber()){
		mainFunc = (Operand) function.get(0);
	}
	else{
			children = new ArrayList<Node>();
			int index = findHighestOp(function);
			mainFunc = (Operand)function.get(index);
			if(mainFunc.getNumVals()==1) {
				children.add(new Node(subList(index + 1, function.size(), function)));
			}
			else if (mainFunc.getNumVals()==2) {
				children.add(new Node(subList(0, index, function)));
				children.add(new Node(subList(index + 1, function.size(), function)));
			}
	}
	}

	private static ArrayList<Func> subList(int start, int end, ArrayList<Func> function) {

		ArrayList<Func> subList = new ArrayList<Func>();
		for(int i = start; i < end; i++){
			subList.add(function.get(i));
		}
		return subList;
	}

	private boolean stripLeadTail(ArrayList<Func> function) {
		int currParenLevel = 1;
		if(!(function.get(0).isAParen()&& function.get(function.size() - 1).isAParen())) return false; 	//If the func does not start+end with ( and ), exit
		for(int i = 1; i < function.size() - 1; i++){	//If the paren depth is ever ==0 before the end, exit
			if(function.get(i).isAParen()){
				if(((Paren)function.get(i)).isOpening()) currParenLevel++;
				else currParenLevel--;
			}
			if(currParenLevel==0) return false;
		}
		function.remove(function.size()-1);
		function.remove(0);
		return true;
	}

	private int findHighestOp(ArrayList<Func> function) {
		int highestOp = -1;
		int index = -1;
		int parenNum=0;
		for(int i = 0; i < function.size(); i++){
			Func temp = function.get(i);
			if(temp.isAParen()){
				if(((Paren) temp).isOpening()) parenNum++;
				else parenNum--;
			}
			if(parenNum == 0 && temp.getOrderOps()>highestOp){
				highestOp = temp.getOrderOps();
				index = i;
			}
		}
		return index;
	}

	public double eval() throws Exception {
		return eval(null);
	}

	public double eval(ArrayList<KeyPair> keys) throws Exception{
		if(mainFunc.isAVar()){
			String thisKey = ((Var)mainFunc).getKey();
			if(keys==null) throw new Exception();
			for(KeyPair key: keys){
				if(key.getKey().equals(thisKey)){
					ArrayList<Double> val = new ArrayList<Double>();
					val.add(key.getVal());
					 return mainFunc.eval(val);
				}
			}
			throw new Exception();
		}
		if(mainFunc.isANumber()) return mainFunc.eval(null);

		ArrayList<Double> subEval = new ArrayList<Double>();
		for(Node child: children){
			subEval.add(child.eval(keys));
		}
		return mainFunc.eval(subEval);
	}

	public ArrayList<KeyPair> getKeys() {
		if(children == null || children.size() == 0){
			ArrayList<KeyPair> keys = new ArrayList<KeyPair>();
			if(mainFunc.isAVar()){
				keys.add(new KeyPair(((Var) mainFunc).getKey()));
			}
			return keys;
		}
		if(children.size()==1){
			return children.get(0).getKeys();
		}
		ArrayList<KeyPair> child1 = children.get(0).getKeys();
		ArrayList<KeyPair> child2 = children.get(1).getKeys();
		int i = 0;
		while(i < child1.size()){	//Delete duplicate keys
			int j = 0;
			while(j < child2.size()){
				if(child1.get(i).getKey().equals(child2.get(j).getKey()))
					child2.remove(j);
				else
					j++;
			}
			i++;
		}
		for(KeyPair key: child2){	//Add the remaining second list on to the first
			child1.add(key);
		}
		return child1;
	}
}


text:
<?php
namespace Elton\CoreBundle\ORM;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class TrimestreEnumType extends Type
{
    const ENUM_NAME = 'trimestreType';
    const UN = 'Premier trimestre';
    const DEUX = 'Second trimestre';
    const TROIS = 'Troisième trimestre';

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return "ENUM('Premier trimestre', 'Second trimestre', 'Troisième trimestre')";
    }

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

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if($value == 0) $value = 'Premier trimestre';
        else if($value == 1) $value = 'Second trimestre';
        else if($value == 2) $value = 'Troisième trimestre';
        if (!in_array($value, array(self::UN, self::DEUX, self::TROIS))) {
            throw new \InvalidArgumentException("Invalid status");
        }
        return $value;
    }

    public static function get_enum_values()
    {
        return array('Premier trimestre', 'Second trimestre', 'Troisième trimestre');
    }

    public function getName()
    {
        return self::ENUM_NAME;
    }
}


text:
package com.dmdirc.events;

import com.dmdirc.events.eventbus.BaseEvent;

/**
 * Fired when the list of available plugins may have updated.
 */
public class PluginRefreshEvent extends BaseEvent {

}


text:
from __future__ import annotations

from datetime import timedelta as td

from django.conf import settings
from django.utils.timezone import now

from hc.api.models import Channel, Check
from hc.test import BaseTestCase

class ListChecksTestCase(BaseTestCase):
    def setUp(self):
        super().setUp()

        self.now = now().replace(microsecond=0)

        self.a1 = Check(project=self.project, name="Alice 1")
        self.a1.timeout = td(seconds=3600)
        self.a1.grace = td(seconds=900)
        self.a1.n_pings = 0
        self.a1.status = "new"
        self.a1.tags = "a1-tag a1-additional-tag"
        self.a1.desc = "This is description"
        self.a1.save()

        self.a2 = Check(project=self.project, name="Alice 2")
        self.a2.timeout = td(seconds=86400)
        self.a2.grace = td(seconds=3600)
        self.a2.last_ping = self.now
        self.a2.status = "up"
        self.a2.tags = "a2-tag"
        self.a2.save()

        self.c1 = Channel.objects.create(project=self.project)
        self.a1.channel_set.add(self.c1)

    def get(self):
        return self.client.get("/api/v1/checks/", HTTP_X_API_KEY="X" * 32)

    def test_it_works(self):
        # Expect 3 queries:
        # * check API key
        # * retrieve checks
        # * retrieve  channel codes
        with self.assertNumQueries(3):
            r = self.get()

        self.assertEqual(r.status_code, 200)
        self.assertEqual(r["Access-Control-Allow-Origin"], "*")

        doc = r.json()
        self.assertEqual(len(doc["checks"]), 2)

        by_name = {}
        for check in doc["checks"]:
            by_name[check["name"]] = check

        a1 = by_name["Alice 1"]
        self.assertEqual(a1["timeout"], 3600)
        self.assertEqual(a1["grace"], 900)
        self.assertEqual(a1["ping_url"], self.a1.url())
        self.assertEqual(a1["last_ping"], None)
        self.assertEqual(a1["n_pings"], 0)
        self.assertEqual(a1["status"], "new")
        self.assertEqual(a1["channels"], str(self.c1.code))
        self.assertEqual(a1["desc"], "This is description")

        update_url = settings.SITE_ROOT + "/api/v1/checks/%s" % self.a1.code
        pause_url = update_url + "/pause"
        self.assertEqual(a1["update_url"], update_url)
        self.assertEqual(a1["pause_url"], pause_url)

        self.assertEqual(a1["next_ping"], None)

        a2 = by_name["Alice 2"]
        self.assertEqual(a2["timeout"], 86400)
        self.assertEqual(a2["grace"], 3600)
        self.assertEqual(a2["ping_url"], self.a2.url())
        self.assertEqual(a2["status"], "up")
        next_ping = self.now + td(seconds=86400)
        self.assertEqual(a2["last_ping"], self.now.isoformat())
        self.assertEqual(a2["next_ping"], next_ping.isoformat())

    def test_it_handles_options(self):
        r = self.client.options("/api/v1/checks/")
        self.assertEqual(r.status_code, 204)
        self.assertIn("GET", r["Access-Control-Allow-Methods"])

    def test_it_shows_only_users_checks(self):
        Check.objects.create(project=self.bobs_project, name="Bob 1")

        r = self.get()
        data = r.json()
        self.assertEqual(len(data["checks"]), 2)
        for check in data["checks"]:
            self.assertNotEqual(check["name"], "Bob 1")

    def test_it_works_with_tags_param(self):
        r = self.client.get("/api/v1/checks/?tag=a2-tag", HTTP_X_API_KEY="X" * 32)
        self.assertEqual(r.status_code, 200)

        doc = r.json()
        self.assertTrue("checks" in doc)
        self.assertEqual(len(doc["checks"]), 1)

        check = doc["checks"][0]

        self.assertEqual(check["name"], "Alice 2")
        self.assertEqual(check["tags"], "a2-tag")

    def test_it_filters_with_multiple_tags_param(self):
        r = self.client.get(
            "/api/v1/checks/?tag=a1-tag&tag=a1-additional-tag", HTTP_X_API_KEY="X" * 32
        )
        self.assertEqual(r.status_code, 200)

        doc = r.json()
        self.assertTrue("checks" in doc)
        self.assertEqual(len(doc["checks"]), 1)

        check = doc["checks"][0]

        self.assertEqual(check["name"], "Alice 1")
        self.assertEqual(check["tags"], "a1-tag a1-additional-tag")

    def test_it_does_not_match_tag_partially(self):
        r = self.client.get("/api/v1/checks/?tag=tag", HTTP_X_API_KEY="X" * 32)
        self.assertEqual(r.status_code, 200)

        doc = r.json()
        self.assertTrue("checks" in doc)
        self.assertEqual(len(doc["checks"]), 0)

    def test_non_existing_tags_filter_returns_empty_result(self):
        r = self.client.get(
            "/api/v1/checks/?tag=non_existing_tag_with_no_checks",
            HTTP_X_API_KEY="X" * 32,
        )
        self.assertEqual(r.status_code, 200)

        doc = r.json()
        self.assertTrue("checks" in doc)
        self.assertEqual(len(doc["checks"]), 0)

    def test_readonly_key_works(self):
        self.project.api_key_readonly = "R" * 32
        self.project.save()

        # Expect a query to check the API key, and a query to retrieve checks
        with self.assertNumQueries(2):
            r = self.client.get("/api/v1/checks/", HTTP_X_API_KEY="R" * 32)

        self.assertEqual(r.status_code, 200)

        # When using readonly keys, the ping URLs should not be exposed:
        self.assertNotContains(r, self.a1.url())


text:
#ifndef DSRDTITN_H
#define DSRDTITN_H

#include "dcmtk/config/osconfig.h"   /* make sure OS specific configuration is included first */

#include "dcmtk/dcmsr/dsrdoctn.h"
#include "dcmtk/dcmsr/dsrstrvl.h"

/*---------------------*
 *  class declaration  *
 *---------------------*/

/** Class for content item DATETIME
 */
class DCMTK_DCMSR_EXPORT DSRDateTimeTreeNode
  : public DSRDocumentTreeNode,
    public DSRStringValue
{

  public:

    /** constructor
     ** @param  relationshipType  type of relationship to the parent tree node.
     *                            Should not be RT_invalid or RT_isRoot.
     */
    DSRDateTimeTreeNode(const E_RelationshipType relationshipType);

    /** constructor
     ** @param  relationshipType  type of relationship to the parent tree node.
     *                            Should not be RT_invalid or RT_isRoot.
     *  @param  dateTimeValue     initial value to be set (VR=DT, mandatory)
     *  @param  check             if enabled, check 'dateTimeValue' for validity before setting
     *                            it.  See checkValue() for details.  An empty value is never
     *                            accepted.
     */
    DSRDateTimeTreeNode(const E_RelationshipType relationshipType,
                        const OFString &dateTimeValue,
                        const OFBool check = OFTrue);

    /** destructor
     */
    virtual ~DSRDateTimeTreeNode();

    /** clear all member variables.
     *  Please note that the content item might become invalid afterwards.
     */
    virtual void clear();

    /** check whether the content item is valid.
     *  The content item is valid if the base classes, the concept name and the currently
     *  stored date/time value are valid.
     ** @return OFTrue if tree node is valid, OFFalse otherwise
     */
    virtual OFBool isValid() const;

    /** print content item.
     *  A typical output looks like this: contains DATETIME:(,,"Code")="2000101012000000"
     ** @param  stream  output stream to which the content item should be printed
     *  @param  flags   flag used to customize the output (see DSRTypes::PF_xxx)
     ** @return status, EC_Normal if successful, an error code otherwise
     */
    virtual OFCondition print(STD_NAMESPACE ostream &stream,
                              const size_t flags) const;

    /** write content item in XML format. Uses ISO formatted date/time value.
     ** @param  stream  output stream to which the XML document is written
     *  @param  flags   flag used to customize the output (see DSRTypes::XF_xxx)
     ** @return status, EC_Normal if successful, an error code otherwise
     */
    virtual OFCondition writeXML(STD_NAMESPACE ostream &stream,
                                 const size_t flags) const;

    // --- static helper function ---

    /** get DICOM date/time value from given XML element.
     *  The DICOM DateTime (DT) value is expected to be stored in ISO format as created by
     *  writeXML().
     ** @param  doc            document containing the XML file content
     *  @param  cursor         cursor pointing to the corresponding node
     *  @param  dateTimeValue  reference to string object in which the value should be stored
     *  @param  clearString    flag specifying whether to clear the 'dateTimeValue' or not
     ** @return reference to string object (might be empty)
     */
    static OFString &getValueFromXMLNodeContent(const DSRXMLDocument &doc,
                                                DSRXMLCursor cursor,
                                                OFString &dateTimeValue,
                                                const OFBool clearString = OFTrue);

  protected:

    /** read content item (value) from dataset
     ** @param  dataset  DICOM dataset from which the content item should be read
     ** @return status, EC_Normal if successful, an error code otherwise
     */
    virtual OFCondition readContentItem(DcmItem &dataset);

    /** write content item (value) to dataset
     ** @param  dataset  DICOM dataset to which the content item should be written
     ** @return status, EC_Normal if successful, an error code otherwise
     */
    virtual OFCondition writeContentItem(DcmItem &dataset) const;

    /** read content item specific XML data
     ** @param  doc     document containing the XML file content
     *  @param  cursor  cursor pointing to the starting node
     ** @return status, EC_Normal if successful, an error code otherwise
     */
    virtual OFCondition readXMLContentItem(const DSRXMLDocument &doc,
                                           DSRXMLCursor cursor);

    /** render content item (value) in HTML/XHTML format
     ** @param  docStream     output stream to which the main HTML/XHTML document is written
     *  @param  annexStream   output stream to which the HTML/XHTML document annex is written
     *  @param  nestingLevel  current nesting level.  Used to render section headings.
     *  @param  annexNumber   reference to the variable where the current annex number is stored.
     *                        Value is increased automatically by 1 after a new entry has been added.
     *  @param  flags         flag used to customize the output (see DSRTypes::HF_xxx)
     ** @return status, EC_Normal if successful, an error code otherwise
     */
    virtual OFCondition renderHTMLContentItem(STD_NAMESPACE ostream &docStream,
                                              STD_NAMESPACE ostream &annexStream,
                                              const size_t nestingLevel,
                                              size_t &annexNumber,
                                              const size_t flags) const;

    /** check the specified date/time value for validity.
     *  In addition to the base class check for a non-empty value, this method also checks
     *  whether the given value conforms to the corresponding VR (DT) and VM (1).
     ** @param  dateTimeValue  value to be checked
     ** @return status, EC_Normal if value is valid, an error code otherwise
     */
    virtual OFCondition checkValue(const OFString &dateTimeValue) const;

  private:

 // --- declaration of default/copy constructor and assignment operator

    DSRDateTimeTreeNode();
    DSRDateTimeTreeNode(const DSRDateTimeTreeNode &);
    DSRDateTimeTreeNode &operator=(const DSRDateTimeTreeNode &);
};

#endif


text:
var async     = require("async"),
    Settings  = require("pn-common").Settings,
    trace     = Settings.tracer("pn:disp:apis"),
    messenger = require("../lib/messenger");

exports.register = function (app) {
    app.post("/send", function (req, res) {
        trace("/send %j", req.body);
        if (Array.isArray(req.body.info)) {
            async.map(req.body.info, function (parcel, done) {
                if (typeof(parcel.message) == "string" && Array.isArray(parcel.regIds)) {
                    if (parcel.regIds.length <= Settings.MAX_REGIDS_INREQ) {
                        messenger.get().post(parcel.message, parcel.regIds, function (err, message, failedRegIds) {
                            if (err) {
                                done(null, { error: err.message });
                            } else if (failedRegIds.length > 0) {
                                done(null, { msgId: message.id, failedRegIds: failedRegIds });
                            } else {
                                done(null, message.id);
                            }
                        });
                    } else {
                        done(null, { error: "TooManyRegIds" });
                    }
                } else {
                    done(null, { error: "BadFormat" });
                }
            }, function (err, msgIds) {
                trace("messageIds: %j", msgIds);
                res.json({ messageIds: msgIds });
            });
        } else {
            res.json(400, { error: "BadParameter" });
        }
    });
};


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../刊/index.html">
<meta http-equiv=refresh content="0; url='../刊/index.html'">

Redirecting...

Click here if you are not redirected.


text:
'use strict'
const moment = require('moment')
const mongoose = require('mongoose')

const Venue = require('./venue.js')

const eventSchema = mongoose.Schema({
  _start: { type: Number, required: true },
  _end: { type: Number, required: true },
  name: { type: String },
  numberOfPeople: { type: Number, required: true },
  venue: { type: mongoose.Schema.Types.ObjectId, default: null },
  owner: { type: mongoose.Schema.Types.ObjectId, required: false },
  // TODO: change to "true"
})

// "virtual" fields are ones that are not stored to MongoDB,
// but that can be queried and set as if they were part of the model.
// we store the start and end times of an Event as integer (Unix timestamp)
// and use these virtual fields to provide get and set for these times as Moment.js moments
// which are much more convenient.
//
// So any time we read or manipulate times, we should do so with Moment.js.

eventSchema.virtual('start').get(function() {
  return moment(this._start)
})

eventSchema.virtual('end').get(function() {
  return moment(this._end)
})

eventSchema.virtual('start').set(function(time) {
  this._start = time.valueOf()
})

eventSchema.virtual('end').set(function(time) {
  this._end = time.valueOf()
})

eventSchema.pre('save', function(next) {
  if(!this.venue)
    return next()
  Venue.findById(this.venue)
    .then(venue => {
      if(!venue.events.includes(this._id))
        venue.events.push(this._id)
      return venue.save()
    })
    .then(() => next())
    .catch(err => next(err))
})

eventSchema.post('remove', function(removedEvent, next) {
  // if(!removedEvent.venue)
  //   return next()
  Venue.findById(removedEvent.venue)
    .then(venue => {
      venue.events = venue.events.filter(event => event._id !== removedEvent._id)
      return venue && venue.save()
    })
    .then(() => next())
    .catch(err => next(err))
})

const Event = mongoose.model('event', eventSchema)

module.exports = Event


text:
package com.evanzeimet.hystrixinterceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Interceptor
@HystrixIntercept
public class HystrixInterceptor {

	@AroundInvoke
	public Object intercept(InvocationContext invocationContext) {
		return new HystrixInterceptorCommand(invocationContext).execute();
	}

}


text:
export interface ICommandParser{
	parseCommand(): void;
}


text: export { default } from './AlertTitle';


text:
require 'resolv-replace'

#parse xml/html
require 'nokogiri'

#open url
require 'open-uri'

@encoding = "ISO-8859-1"

#helper to generate REGEX for currency symbol before and after the value
def preorpost(str)
  value = "\\d+([\\,\\.]\\d+){0,2}"
  "(#{value}\\s*#{str})|(#{str}\\s*#{value})"
end

#all supported currencies in format [isostring] => regex
def getAllCurrencies
  {
  "EUR" => preorpost("\\€"),
  "USD" => preorpost("\\$"),
  "GBP" => preorpost("\\£"),
  "CHF" => preorpost("CHF"),
  "TWD" => preorpost("NT\\$"),
  "SGD" => preorpost("S\\$"),
  "HKD" => preorpost("HK\\$"),
  "CNY" => preorpost("(\\¥|RNB)")
  }
end

#generate regex for all supported currencies
def regexAllCurrencies
  currencies = getAllCurrencies
  cs = currencies.values

  cs_regex = "("
  cs.each do |s|
    cs_regex += s
    unless s == cs.last
      cs_regex += "|"
    end
  end
  cs_regex += ")"
  return cs_regex.force_encoding(@encoding)
end

#filter out number of string str
def getNumber(str)
  numberexp = "\\d+([\\,\\.]\\d+){0,2}".force_encoding(@encoding)
  numberstr = str.match(/#{numberexp}/).to_s
  lastsep = numberstr.rindex(/(\.\d+$)|(\,\d{2}$)/)
  if(lastsep)
    numberstr[lastsep] = 'X'
  end

  newsep = numberstr.rindex(/[\.\,]/)
  while(newsep)
    numberstr.slice! newsep
    newsep = numberstr.rindex(/[\.\,]/)
  end

  if(lastsep)
    numberstr[lastsep] = '.'
  end

  return numberstr.to_f
end

#filter out iso code of string str
def getISOCode(str)
  currencies = getAllCurrencies
  currencies.each_pair do |k, v|
    if str.match(/#{v.force_encoding(@encoding)}/)
      return k
    end
  end
  return nil
end

#convert currency String str to dollar
def convertToDollar(str, debug)
  isocode = getISOCode(str)
  value = getNumber(str)
  if(isocode == 'USD')
    if debug
      puts "Value in USD: #{value}"
    end
    return value
  else
    link = "http://www.xe.com/currencyconverter/convert/?Amount=" + value.to_s + "&From=#{isocode}&To=USD"
    convertpage = Nokogiri::HTML(open(URI.escape(link)))
    answer = convertpage.css('.uccRes .rightCol')[0].text.force_encoding(@encoding)
    newVal = getNumber(answer)
    if debug
      puts "Converted Value: #{str} to #{newVal.to_s}$"
    end
    return newVal
  end
end


text:
{% extends "page-base.html" %}

{% block title %}Search Results - SciPy Central{% endblock %}

{% block pageContent %}

Search Results

	{% if query %}
		{% with page as entries %}
		{% include 'submission/entries_list.html' %}
		{% endwith %}

	{% else %}
		{# Show some example queries to run, maybe advanced query syntax #}
	{% endif %}
{% endblock %}


text:
/*
 * HomeConstants
 * Each action has a corresponding type, which the reducer knows and picks up on.
 * To avoid weird typos between the reducer and the actions, we save them as
 * constants here. We prefix them with 'yourproject/YourComponent' so we avoid
 * reducers accidentally picking up actions they shouldn't.
 *
 * Follow this format:
 * export const YOUR_ACTION_CONSTANT = 'yourproject/YourContainer/YOUR_ACTION_CONSTANT';
 */

export const RESPOND = 'borderbot/Home/RESPOND';
export const PRINT = 'borderbot/Home/PRINT';
export const SCRIPT_FETCH_REQUESTED = 'borderbot/Home/SCRIPT_FETCH_REQUESTED';


text:
 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         mfc_example.cpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: examples of using Boost.Regex with MFC and ATL string types.
  */

#include <boost/regex/config.hpp>

#ifdef BOOST_HAS_ICU

#include <boost/regex/icu.hpp>
#include <iostream>
#include <assert.h>

//
// Find out if *password* meets our password requirements,
// as defined by the regular expression *requirements*.
//
bool is_valid_password(const U_NAMESPACE_QUALIFIER UnicodeString& password, const U_NAMESPACE_QUALIFIER UnicodeString& requirements)
{
   return boost::u32regex_match(password, boost::make_u32regex(requirements));
}

//
// Extract filename part of a path from a UTF-8 encoded std::string and return the result
// as another std::string:
//
std::string get_filename(const std::string& path)
{
   boost::u32regex r = boost::make_u32regex("(?:\\A|.*\\\\)([^\\\\]+)");
   boost::smatch what;
   if(boost::u32regex_match(path, what, r))
   {
      // extract $1 as a std::string:
      return what.str(1);
   }
   else
   {
      throw std::runtime_error("Invalid pathname");
   }
}

U_NAMESPACE_QUALIFIER UnicodeString extract_greek(const U_NAMESPACE_QUALIFIER UnicodeString& text)
{
   // searches through some UTF-16 encoded text for a block encoded in Greek,
   // this expression is imperfect, but the best we can do for now - searching
   // for specific scripts is actually pretty hard to do right.
   boost::u32regex r = boost::make_u32regex(L"[\\x{370}-\\x{3FF}](?:[^[:L*:]]|[\\x{370}-\\x{3FF}])*");
   boost::u16match what;
   if(boost::u32regex_search(text, what, r))
   {
      // extract $0 as a UnicodeString:
      return U_NAMESPACE_QUALIFIER UnicodeString(what[0].first, what.length(0));
   }
   else
   {
      throw std::runtime_error("No Greek found!");
   }
}

void enumerate_currencies(const std::string& text)
{
   // enumerate and print all the currency symbols, along
   // with any associated numeric values:
   const char* re =
      "([[:Sc:]][[:Cf:][:Cc:][:Z*:]]*)?"
      "([[:Nd:]]+(?:[[:Po:]][[:Nd:]]+)?)?"
      "(?(1)"
         "|(?(2)"
            "[[:Cf:][:Cc:][:Z*:]]*"
         ")"
         "[[:Sc:]]"
      ")";
   boost::u32regex r = boost::make_u32regex(re);
   boost::u32regex_iterator<std::string::const_iterator> i(boost::make_u32regex_iterator(text, r)), j;
   while(i != j)
   {
      std::cout << (*i)[0] << std::endl;
      ++i;
   }
}

void enumerate_currencies2(const std::string& text)
{
   // enumerate and print all the currency symbols, along
   // with any associated numeric values:
   const char* re =
      "([[:Sc:]][[:Cf:][:Cc:][:Z*:]]*)?"
      "([[:Nd:]]+(?:[[:Po:]][[:Nd:]]+)?)?"
      "(?(1)"
         "|(?(2)"
            "[[:Cf:][:Cc:][:Z*:]]*"
         ")"
         "[[:Sc:]]"
      ")";
   boost::u32regex r = boost::make_u32regex(re);
   boost::u32regex_token_iterator<std::string::const_iterator>
      i(boost::make_u32regex_token_iterator(text, r, 1)), j;
   while(i != j)
   {
      std::cout << *i << std::endl;
      ++i;
   }
}

//
// Take a credit card number as a string of digits,
// and reformat it as a human readable string with "-"
// separating each group of four digit;,
// note that we're mixing a UTF-32 regex, with a UTF-16
// string and a UTF-8 format specifier, and it still all
// just works:
//
const boost::u32regex e = boost::make_u32regex("\\A(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})\\z");
const char* human_format = "$1-$2-$3-$4";

U_NAMESPACE_QUALIFIER UnicodeString human_readable_card_number(const U_NAMESPACE_QUALIFIER UnicodeString& s)
{
   return boost::u32regex_replace(s, e, human_format);
}

int main()
{
   // password checks using u32regex_match:
   U_NAMESPACE_QUALIFIER UnicodeString pwd = "abcDEF---";
   U_NAMESPACE_QUALIFIER UnicodeString pwd_check = "(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]]).{6,}";
   bool b = is_valid_password(pwd, pwd_check);
   assert(b);
   pwd = "abcD-";
   b = is_valid_password(pwd, pwd_check);
   assert(!b);
   // filename extraction with u32regex_match:
   std::string file = "abc.hpp";
   file = get_filename(file);
   assert(file == "abc.hpp");
   file = "c:\\a\\b\\c\\d.h";
   file = get_filename(file);
   assert(file == "d.h");

   // Greek text extraction with u32regex_search:
   const UChar t[] = {
      'S', 'o', 'm', 'e', ' ', 'w', 'h', 'e', 'r', 'e', ' ', 'i', 'n', 0x0391, 0x039D, 0x0395, 0x0398, 0x0391, 0
   };
   const UChar g[] = {
      0x0391, 0x039D, 0x0395, 0x0398, 0x0391, 0
   };
   U_NAMESPACE_QUALIFIER UnicodeString text = t;
   U_NAMESPACE_QUALIFIER UnicodeString greek = extract_greek(text);
   assert(greek == g);

   // extract currency symbols with associated value, use iterator interface:
   std::string text2 = " $100.23 or \xC2\xA3""198.12 "; // \xC2\xA3 is the pound sign encoded in UTF-8
   enumerate_currencies(text2);
   enumerate_currencies2(text2);

   U_NAMESPACE_QUALIFIER UnicodeString credit_card_number = "1234567887654321";
   credit_card_number = human_readable_card_number(credit_card_number);
   assert(credit_card_number == "1234-5678-8765-4321");
   return 0;
}

#else

#include <iostream>

int main()
{
   std::cout << "<NOTE>ICU support not enabled, feature unavailable</NOTE>";
   return 0;
}

#endif


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.cn;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class id {
        public static final int Button01=0x7f060001;
        public static final int myEditText=0x7f060000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class raw {
        public static final int sound=0x7f040000;
    }
    public static final class string {
        public static final int app_name=0x7f050000;
        public static final int call=0x7f050001;
        public static final int tel=0x7f050002;
    }
}


text:
package main

import (
	"encoding/xml"
	"errors"
	"fmt"
	"sync"
)

var (
	ErrAlreadyExists = errors.New("album already exists")
)

// The DB interface defines methods to manipulate the albums.
type DB interface {
	Get(id int) *Album
	GetAll() []*Album
	Find(band, title string, year int) []*Album
	Add(a *Album) (int, error)
	Update(a *Album) error
	Delete(id int)
}

// Thread-safe in-memory map of albums.
type albumsDB struct {
	sync.RWMutex
	m   map[int]*Album
	seq int
}

// The one and only database instance.
var db DB

func init() {
	db = &albumsDB{
		m: make(map[int]*Album),
	}
	// Fill the database
	db.Add(&Album{Id: 1, Band: "Slayer", Title: "Reign In Blood", Year: 1986})
	db.Add(&Album{Id: 2, Band: "Slayer", Title: "Seasons In The Abyss", Year: 1990})
	db.Add(&Album{Id: 3, Band: "Bruce Springsteen", Title: "Born To Run", Year: 1975})
}

// GetAll returns all albums from the database.
func (db *albumsDB) GetAll() []*Album {
	db.RLock()
	defer db.RUnlock()
	if len(db.m) == 0 {
		return nil
	}
	ar := make([]*Album, len(db.m))
	i := 0
	for _, v := range db.m {
		ar[i] = v
		i++
	}
	return ar
}

// Find returns albums that match the search criteria.
func (db *albumsDB) Find(band, title string, year int) []*Album {
	db.RLock()
	defer db.RUnlock()
	var res []*Album
	for _, v := range db.m {
		if v.Band == band || band == "" {
			if v.Title == title || title == "" {
				if v.Year == year || year == 0 {
					res = append(res, v)
				}
			}
		}
	}
	return res
}

// Get returns the album identified by the id, or nil.
func (db *albumsDB) Get(id int) *Album {
	db.RLock()
	defer db.RUnlock()
	return db.m[id]
}

// Add creates a new album and returns its id, or an error.
func (db *albumsDB) Add(a *Album) (int, error) {
	db.Lock()
	defer db.Unlock()
	// Return an error if band-title already exists
	if !db.isUnique(a) {
		return 0, ErrAlreadyExists
	}
	// Get the unique ID
	db.seq++
	a.Id = db.seq
	// Store
	db.m[a.Id] = a
	return a.Id, nil
}

// Update changes the album identified by the id. It returns an error if the
// updated album is a duplicate.
func (db *albumsDB) Update(a *Album) error {
	db.Lock()
	defer db.Unlock()
	if !db.isUnique(a) {
		return ErrAlreadyExists
	}
	db.m[a.Id] = a
	return nil
}

// Delete removes the album identified by the id from the database. It is a no-op
// if the id does not exist.
func (db *albumsDB) Delete(id int) {
	db.Lock()
	defer db.Unlock()
	delete(db.m, id)
}

// Checks if the album already exists in the database, based on the Band and Title
// fields.
func (db *albumsDB) isUnique(a *Album) bool {
	for _, v := range db.m {
		if v.Band == a.Band && v.Title == a.Title && v.Id != a.Id {
			return false
		}
	}
	return true
}

// The Album data structure, serializable in JSON, XML and text using the Stringer interface.
type Album struct {
	XMLName xml.Name `json:"-" xml:"album"`
	Id      int      `json:"id" xml:"id,attr"`
	Band    string   `json:"band" xml:"band"`
	Title   string   `json:"title" xml:"title"`
	Year    int      `json:"year" xml:"year"`
}

func (a *Album) String() string {
	return fmt.Sprintf("%s - %s (%d)", a.Band, a.Title, a.Year)
}


text:
$(function() {
	var msgs_controller = new MessagesController();
	$("#btnSendMessage").click(function() {
		var message_body = $("#txtMessage").val();
		var nick = $("#txtNick").val();
		if(message_body != "" && nick != "") {
			if(msgs_controller.createNewMessage(nick, message_body, new Date().getTime())) {
				$("#loading-div").show();
				$("#txtMessage").val("");
			}
		}
	});

	$("#txtMessage").keyup(function(e) {
		if(e.keyCode == 13) { //enter daba dia. :O
			$("#btnSendMessage").click();
			$("#txtMessage").val("");
		}
	});
});


text:
var http = require('http'),
    router = require('./router'),
    connect = require('connect');

var requestHandler = function(req, res) {
    // sending request to router
    router.match(req, res);
};

requestHandler.startServer = function() {
    // Sessions
    var sessionOptions = {
        secret: (process.env.SESSIONS_SECRET) ? process.env.SESSIONS_SECRET : 'hello world'
    };

    if (process.env.STORE_SESSIONS_IN_MONGODB) {
        var MongoStore = require('connect-mongodb');

        var mongoStoreOptions = {
            safe: true,
            url: 'mongodb://' + process.env.MONGODB_USER + ':' + process.env.MONGODB_PASSWORD + '@' + process.env.MONGODB_HOST + ':' + process.env.MONGODB_PORT + '/' + process.env.MONGODB_DATABASE
        };

        sessionOptions.store = new MongoStore(mongoStoreOptions, function(err) {
            if (err) console.log('err', err);
        });
    }

    // if ran from c9, use its port
    process.env.PORT = (process.env.C9_PORT != undefined) ? process.env.C9_PORT : process.env.PORT;

    // starts the server
    var server = connect()
        .use(connect.favicon())
        .use(connect.cookieParser())
        .use(connect.session(sessionOptions))
        .use(requestHandler)
        .listen(process.env.PORT, function() {
            console.log('ThinAir server is started and listening on port ' + process.env.PORT);
        });

    return server;
};

module.exports = requestHandler;


text:
/**
 * Package contains the step actions for the GCSDelete features.
 */
package io.cdap.plugin.gcsdelete.actions;


text:
package edu.wustl.dao.test;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import test.Address;
import test.Order;
import test.Person;
import test.User;
import edu.wustl.common.exception.ApplicationException;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.dao.DAO;
import edu.wustl.dao.QueryWhereClause;
import edu.wustl.dao.condition.EqualClause;
import edu.wustl.dao.condition.GreaterThenClause;
import edu.wustl.dao.condition.INClause;
import edu.wustl.dao.condition.LessThenClause;
import edu.wustl.dao.condition.NotEqualClause;
import edu.wustl.dao.condition.NotNullClause;
import edu.wustl.dao.condition.NullClause;
import edu.wustl.dao.daofactory.IDAOFactory;
import edu.wustl.dao.exception.DAOException;
import edu.wustl.dao.formatmessage.ConstraintViolationFormatter;
import edu.wustl.dao.util.DAOConstants;
import edu.wustl.dao.util.HibernateMetaData;

/**
 * @author kalpana_thakur
 *
 */
public class HibernateTestCaseForCatissue extends BaseTestCase
{

	/**
	 * Logger.
	 */
	private static org.apache.log4j.Logger logger = Logger.getLogger(HibernateTestCaseForCatissue.class);
	/**
	 * DAO instance.
	 */
	private DAO dao;

	{
		setDAO();
	}

	/**
	 * This method will be called to set the Default DAO.
	 */
	public void setDAO()
	{
		IDAOFactory daoFactory = daoConfigFactory.getInstance().getDAOFactory("caTissuecore");
		try
		{
			dao = daoFactory.getDAO();
		}
		catch (DAOException e)
		{
			logger.fatal("Problem while retrieving DAO object", e);
		}
	}

	/**
	 * This test will assert that DAO instance is not null.
	 */
	@Test
	public void testDAOInstance()
	{
		assertNotNull("DAO Object is null",dao);
	}

	/**
	 * This test will assert that Object inserted successfully.
	 */
	@Test
	public void testInsertPerson()
	{
		try
		{
			dao.openSession(null);
			Person person = new Person();

			Address address = new Address();
			address.setStreet("Street unknown");
			dao.insert(address,false);
			person.setAddress(address);

			Collection<Object> orderCol = new HashSet<Object>();
			Order order = new Order();
			order.setPerson(person);

			person.setName("Kalpana");
			orderCol.add(order);
			person.setOrderCollection(orderCol);
			dao.insert(person,false);
			dao.commit();
			//dao.closeSession();

		}
		catch(Exception exp)
		{
			ApplicationException appExp = (ApplicationException)exp;
			logger.fatal(appExp.getLogMessage());
			assertFalse("Failed while inserting object :", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

/**
	 * This test will assert that Object inserted successfully.
	 */
	@Test
	public void testCaseInsertObject()
	{
		try
		{
		  User user = (User)createUserObject();
		  dao.openSession(null);
		  dao.insert(user, false);
		//  dao.commit();
		 // dao.closeSession();

		  	User user2 = new User();
		  	user2.setFirstName("sachin");
		  	user2.setLastName("Lale");
		  	user2.setEmailAddress("sach@lale.co.in");
		//  dao.openSession(null);
		  dao.insert(user2, false);
		  dao.commit();
		//  dao.closeSession();
		}
		catch(Exception exp)
		{
			assertFalse("Failed while inserting object :", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

		/**
	 * This test will assert that Object updated successfully.
	 */
	@Test
	public void testCaseUpdateObject()
	{
		try
		{

		  User user = new User();
		  user.setIdentifier(Long.valueOf(1));
		  user.setFirstName("Srikanth");
		  user.setLastName("Adiga");
		  user.setEmailAddress("sri.adiga@persistent.co.in");

		  dao.openSession(null);
		  	  dao.update(user,null);
		  	  dao.commit();
		//  dao.closeSession();
		}
		catch(Exception exp)
		{
			assertFalse("Failed while updating object :", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	  }

	/**
	 * This test will assert  the retrieve used by catissuecore.
	 */
	@Test
	 public void testRetrieveForCatissue()
	{
		List<Object> list = null;
		try
		{
			dao.openSession(null);
			String[] selectColumnName = null;
			String sourceObjectName = "test.User";
			Object [] colValues = {Long.valueOf(1),Long.valueOf(2)};
			String[] whereColNames = {"lastName" , "identifier"};
			String[] whereColConditions = {DAOConstants.EQUAL,
					DAOConstants.IN_CONDITION};
			Object[] whereColValues = {"Naik",colValues};
			String joinCondition = DAOConstants.OR_JOIN_CONDITION;
			QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName);
			queryWhereClause.getWhereCondition(whereColNames, whereColConditions,
					whereColValues, joinCondition);
			list = dao.retrieve(sourceObjectName, selectColumnName,queryWhereClause,false);
			assertNotNull("Object retrieved is null ",list);

			String[] whereColNamesNew = {"identifier","lastName" };
			String[] whereColConditionsNew = {DAOConstants.EQUAL,
					DAOConstants.NOT_NULL_CONDITION};
			Object[] whereColValuesNew = {Long.valueOf(1)};

			queryWhereClause = new QueryWhereClause(sourceObjectName);
			queryWhereClause.getWhereCondition(whereColNamesNew, whereColConditionsNew,
					whereColValuesNew, joinCondition);
			list = dao.retrieve(sourceObjectName, selectColumnName,queryWhereClause,false);
			assertNotNull("Object retrieved is null ",list);
		//	dao.closeSession();
		}
		catch(Exception exp)
		{
			assertFalse("Problem while retrieving :", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that all the objects are retrieved successfully.
	 */
	@Test
	public void testCaseRetriveAllObjects()
	{
	  try
	  {
		  dao.openSession(null);
	  	  List<Object> list = dao.retrieve("test.User",null,null,false);
	  	//  dao.closeSession();

	  	  assertNotNull("No objects retrieved :",list);
	  	//  assertTrue("No object retrieved ::", !list.isEmpty());
	   }
	  catch(Exception exp)
	  {
		  assertFalse("Failed while retrieving object :", true);
	  }
	  finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that the object with requested
	 * column will be retrieved successfully.
	 */
	@Test
	public void testCaseRetriveObject()
	{
	  try
	  {
	    dao.openSession(null);
	    QueryWhereClause queryWhereClause = new QueryWhereClause("test.User");
	    queryWhereClause.addCondition(new EqualClause("identifier" , Long.valueOf(1)));
	    List<Object> list = dao.retrieve("test.User",null , queryWhereClause,false);

	  //	dao.closeSession();
	  	assertNotNull("No objects retrieved",list);
		//assertTrue("No object retrieved ::",!list.isEmpty());
	  }
	  catch(Exception exp)
	  {
		  assertFalse("Failed while retrieving object ::", true);
	  }
	  finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that requested columns of the objects are
	 * retrieved successfully.
	 */
	@Test
	public void testCaseRetrieveObjectColumns()
	{
	  try
	  {
		String[] selectColumnName = {"identifier","firstName","lastName","emailAddress"};
		dao.openSession(null);
	    List<Object> list = dao.retrieve("test.User", selectColumnName,null,false);
	   // dao.closeSession();

	    assertNotNull("No object retrieved ::",list);
		//assertTrue("No object retrieved ::",!list.isEmpty());
	  }
	  catch(Exception exp)
	  {
		  assertFalse("Failed while retrieving object ::", true);
	  }
	  finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that object will given identifier
	 * retrieved successfully.
	 */
	@Test
	public void testCaseRetrieveObjectAsPerID()
	{
		try
		{
			dao.openSession(null);
			User user  = (User)dao.retrieveById("test.User", Long.valueOf(1));
			//dao.closeSession();
			assertNotNull("Object is null ",user);
		}
		catch(Exception exp)
		{
			assertFalse("Failed while retrieving object ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that object will given identifier
	 * retrieved successfully.
	 *//*
	@Test
	public void testCaseLoadCleanObject()
	{
		try
		{
			dao.openSession(null);
			HibernateDAOImpl hiberDao = (HibernateDAOImpl)dao;
			User user  = (User)hiberDao.loadCleanObj("test.User", Long.valueOf(1));
		//	dao.closeSession();

			assertNotNull("No object retieved ::",user);

		}
		catch(Exception exp)
		{
			assertFalse("Failed while retrieving object ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}*/

	/**
	 * This test will assert that requested objects deleted successfully.
	 */
	@Test
	public void testCaseDeleteObject()
	{
	  try
	  {
		  User user = new User();
		  user.setIdentifier(Long.valueOf(2));
		  dao.openSession(null);
	  	  dao.delete(user);
	  	  dao.commit();
	  	//  dao.closeSession();
	  	assertTrue("Object deleted :", true);
	  }
	  catch(Exception exp)
	  {
		  exp.printStackTrace();
		  assertFalse("Failed while deleting object :", true);
	  }
	  finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that objects retrieved successfully
	 * when where clause holds in condition.
	 */
	@Test
	public void testRetriveInCondition()
	{
		try
		{
			String sourceObjectName = "test.User";
			String[] selectColumnName = null;

			Object[] object = {"naik"};
			QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName);
			queryWhereClause.addCondition(new INClause("firstName","JOHN,abhijit")).andOpr().
			addCondition(new INClause("lastName",object,sourceObjectName)).orOpr().
			addCondition(new NotEqualClause("identifier",Long.valueOf(1)));

			dao.openSession(null);
			List<Object> list = dao.retrieve(sourceObjectName, selectColumnName,
					queryWhereClause,false);
			//dao.closeSession();

			assertNotNull("No object retrieved ::",list);
			//assertTrue("No object retrieved ::",!list.isEmpty());
		}
		catch(Exception exp)
		{
			assertFalse("Failed while retrieving object ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that objects retrieved successfully
	 * when where clause holds not null condition.
	 */
	@Test
	public void testRetriveIsNotNullCondition()
	{
		try
		{
			String sourceObjectName = "test.User";
			String[] selectColumnName = null;

			QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName);
			queryWhereClause.addCondition(new NotNullClause("identifier"))
			.orOpr().addCondition(new NotNullClause("lastName",sourceObjectName));

			dao.openSession(null);
			List<Object> list = dao.retrieve(sourceObjectName, selectColumnName,
					queryWhereClause,false);
		//	dao.closeSession();

			assertNotNull(list);
		//	assertTrue("No object retrieved ::",!list.isEmpty());

		}
		catch(Exception exp)
		{
			assertFalse("Failed while retrieving object ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that objects retrieved successfully
	 * when where clause holds is null condition.
	 */
	@Test
	public void testRetriveIsNullCondition()
	{
		try
		{
			String sourceObjectName = "test.User";

			String[] selectColumnName = null;

			QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName);
			queryWhereClause.addCondition(new NullClause("lastName"));

			dao.openSession(null);
			List<Object> list = dao.retrieve(sourceObjectName, selectColumnName,
					queryWhereClause,false);
			//dao.closeSession();

			assertNotNull(list);

		}
		catch(Exception exp)
		{
			assertFalse("Failed while retrieving object ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that query will be executed successfully.
	 */
	@Test
	public void testCaseExecuteQuery()
	{
		try
		{
			dao.openSession(null);
			String sql = "select count(*) from test.User";
			List<Object> list = dao.executeQuery(sql);
			//dao.closeSession();
			assertNotNull(list);
		//	assertTrue("No object retrieved ::",!list.isEmpty());

		}
		catch(Exception exp)
		{
			assertFalse("Problem while executing query ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert that requested objects disabled successfully.
	 */
	/*@Test
	public void testDisableRelatedObjects()
	{
		String tableName = "test_user";
		String whereColumnName = "IDENTIFIER";
		Long[] whereColumnValues = {Long.valueOf(1),Long.valueOf(2)};
		try
		{
			dao.openSession(null);
			dao.disableRelatedObjects(tableName,whereColumnName,whereColumnValues);
			dao.commit();
			//dao.closeSession();
		}
		catch(Exception exp)
		{
			assertFalse("Problem in disabling object : :", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}*/

	/**
	 * This test will assert that attribute retrieved successfully.
	 */
	@Test
	public void testRetrieveAttribute()
	{
		try
		{/*
			dao.openSession(null);
			Object obj = (Object)dao.retrieveAttribute(User.class,
					Long.valueOf(1),"emailAddress","identifier");
		//	dao.closeSession();

			assertNotNull("Object retrieved is null",obj);
			List<String> list = (List<String>)obj;
			assertNotNull("Object retrieved is null",list);
			//assertTrue("Problem in retrieving attribute :", !list.isEmpty());
		*/}
		catch(Exception exp)
		{
			assertFalse("Problem in retrieving attribute ::", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This method will use session.load to retrieve the object with the given identifier.
	 *//*
	@Test
	public void testLoadCleanObjects()
	{
		HibernateDAO hibernateDAO = null;
		try
		{
			//dao.openSession(null);
			hibernateDAO = (HibernateDAO)dao;
			hibernateDAO.openSession(null);

			Object obj = (Object)hibernateDAO.loadCleanObj(User.class,
					Long.valueOf(1));
			//dao.closeSession();
			assertNotNull("Object retrieved is null",obj);
		}
		catch(Exception exp)
		{
			assertFalse("Problem in retrieving attribute ::", true);
		}
		finally
		{
			try
			{
				hibernateDAO.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}
*/

	/**
	 * This test will assert that clean session retrieved.
	 */
	@Test
	public void testCleanSession()
	{
		Session session = null;
		try
		{
		//	session = dao.getCleanSession();
			assertNotNull("session Object is null",session);
		}
		catch(Exception exp)
		{
			assertFalse("Failed while obtaining new session :", true);
		}
		finally
		{
			session.close();
		}

	}

	/**
	 * This test will open clean session with in a session.
	 * insert one object and in second session update the same object.
	 */
	@Test
	public void testCleanSessionWithinaSession()
	{/*
		try
		{
			dao.openSession(null);

			Session session = dao.getCleanSession();
				User user = (User)createUserObject();
				Transaction transaction = session.beginTransaction();
				session.save(user);
				transaction.commit();
			session.close();

			user.setEmailAddress("cruise_tom@persistent.co.in");
			dao.update(user,null);
			dao.commit();
			//dao.closeSession();
		}
		catch(Exception exp)
		{
			assertFalse("Problem occurred while opening clean session within a session:", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	*/}

	/**
	 * This test will ensure that second application can open session
	 * when first application session is not closed that means
	 * opening and closing of session by one application do not affect other application session.
	 * In this test application 'App1' and 'App2'insert object to their respective databases.
	 * Pointing to same database type either MySQL , Oracle or any third type.
	 */
	/*@Test
	public void testMultAppInsertPointngRespectiveDBSameDBType()
	{
		try
		{
			User user = (User)createUserObject();
			dao.openSession(null);
			insertObjectByApp2(user);
			user.setEmailAddress("cruise_tom@persistent.co.in");
			dao.insert(user, null, false, false);
			dao.commit();
			//dao.closeSession();
		}
		catch(Exception exp)
		{
			assertFalse("Problem occurred while opening second session within a session:", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}*/

	/**
	 * This test will create a complex retrieve query having multiple clause(IN,NOT NULL,IS NULL)
	 * It will ensure that objects retrieved successfully.
	 */
	@Test
	public void testRetriveComplexQuery()
	{
		try
		{
			String sourceObjectName = "test.User";
			Object [] colValues = {Long.valueOf(1),Long.valueOf(2)};
			String[] selectColumnName = null;

			QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName);
			queryWhereClause.addCondition(new INClause("identifier",colValues))
			.orOpr().addCondition(new NotNullClause("firstName")).orOpr()
			.addCondition(new EqualClause("firstName","Washu")).orOpr().
			addCondition(new LessThenClause("identifier",Long.valueOf(100))).orOpr().
			addCondition(new LessThenClause("identifier",Long.valueOf(100),sourceObjectName)).orOpr()
			.addCondition(new GreaterThenClause("identifier",Long.valueOf(100),sourceObjectName)).orOpr().
			addCondition(new GreaterThenClause("identifier",Long.valueOf(1)));

			dao.openSession(null);
			List<Object> list = dao.retrieve(sourceObjectName, selectColumnName,queryWhereClause,false);
			//dao.closeSession();
			assertNotNull("No data retrieved :",list);
			//assertTrue("No data retrieved :",!list.isEmpty());
		}
		catch(Exception exp)
		{
			assertFalse("Problem occurred while retrieving object:", true);
		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will various factory members.
	 * 	 */
	@Test
	public void testDAOFactoryMembers()
	{
		IDAOFactory daoFactory = daoConfigFactory.getInstance().getDAOFactory("caTissuecore");
		assertNotNull("No configuration file exist", daoFactory.getConfigurationFile());
		assertNotNull("Default class name Name does not exists", daoFactory.getDefaultDAOClassName());
		assertNotNull("Connection Manager Name not exists", daoFactory.getDefaultConnMangrName());
		assertNotNull("JDBC class name Name does not exists", daoFactory.getJdbcDAOClassName());
		assertNotNull("JDBC Connection Manager Name not exists", daoFactory.getJdbcConnMangrName());
		//assertNotNull("Data source not exists", daoFactory.getDataSource());

	}

	/**
	 * This test will test various methods of HibernateMetaData class.
	 */
	@Test
	public void testDifferentMethodsOfHibernateMetaData()
	{
		try
		{
			dao.openSession(null);
			User user  = (User)dao.retrieveById("test.User", Long.valueOf(1));
			Object object = HibernateMetaData.getProxyObjectImpl(user);
				assertNotNull("Proxy Object retrieved is null :"+object);

			String tableName = HibernateMetaData.getTableName(object.getClass());
				assertTrue("Table name is empty",
						!tableName.equals(DAOConstants.TAILING_SPACES));

			String rootTableName = HibernateMetaData.getRootTableName(object.getClass());
			assertTrue("Root Table name is empty",
						!rootTableName.equals(DAOConstants.TAILING_SPACES));

			String columnName = HibernateMetaData.getColumnName(object.getClass(),"lastName");
				assertTrue("Column Name is empty",
						!columnName.equals(DAOConstants.TAILING_SPACES));

			int colWidth = HibernateMetaData.getColumnWidth(object.getClass(),"lastName");
			assertTrue("colWidth  is 0",colWidth > 0);

			String className = HibernateMetaData.getClassName("Test_user");
				assertTrue("NO class name obtained ",
						!className.equals(DAOConstants.TAILING_SPACES));

			//dao.closeSession();
			assertNotNull("Object is null ",object);
		}
		catch(Exception exp)
		{
			logger.fatal(exp);
			assertFalse("Failed in HibernateMetaData ::", true);

		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	}

	/**
	 * This test will assert on constraint violation proper message is thrown.
	 */
	@Test
	public void testConstraintViolation()
	{
		try
		{
			dao.openSession(null);
			Address address = new Address();
			address.setStreet("Street unknown");
			dao.insert(address, false);
			dao.commit();
			//dao.closeSession();
		}
		catch(Exception exp)
		{
			System.out.println("------------------------------------------------------------------------");
			exp.printStackTrace();
			ConstraintViolationFormatter formatter = new ConstraintViolationFormatter();
			try
			{
				ApplicationException appExp = (ApplicationException)exp;
				String messagethrown = formatter.formatMessage(appExp.getWrapException());
				assertTrue("Message thrown is not correct!! ",
						messagethrown.contains("Submission failed since"));

			}
			catch (DAOException e)
			{
				logger.fatal(e);
			}
			finally
			{
				try
				{
					dao.closeSession();
				}
				catch (DAOException e)
				{
					e.printStackTrace();
				}
			}

		}
		finally
		{
			try
			{
				dao.closeSession();
			}
			catch (DAOException e)
			{
				e.printStackTrace();
			}
		}

	  }

	/**
	 * @param user : user object
	 * @throws DAOException : DAOExp
	 */
	private void insertObjectByApp2(User user) throws DAOException

	{
		IDAOFactory daoFactory = daoConfigFactory.getInstance().getDAOFactory("DynamicExtensions");
		DAO deDAO = daoFactory.getDAO();
		deDAO.openSession(null);
		deDAO.insert(user, false);
		deDAO.commit();
		deDAO.closeSession();
	}

	/**
	 * This method will be called to create user object.
	 * @return : It will returns the user object.
	 */
	User createUserObject()
	{
	  User user = new User();
	  user.setFirstName("abhijit");
	  user.setLastName("naik");
	  user.setEmailAddress("abhijit_naik@persistent.co.in");
	  return user;
	}

}


text:
package org.apache.wicket.markup.parser;

import org.apache.wicket.WicketTestCase;

/**
 *
 */
public class TestHomePage extends WicketTestCase
{
	/**
	 * Wicket-2105
	 */
	public void testRenderMyPage()
	{
		// start and render the test page
		tester.startPage(HomePage.class);

		// assert rendered page class
		tester.assertRenderedPage(HomePage.class);

		// assert rendered label component
		tester.assertLabel("version", "1.0");
	}
}


text:
import logger from "../../utils/logger";

let errors = {
    "400": "Oops, we screwed up the SQL code. Or you did?",
    "404": "We're sorry, there's nothing here.",
    "500": "Oops, we couldn't reach the database machine."
};

function handleEmptyResult(result, response) {
    if (result.rowCount !== 0) {
        return false;
    }

    return response
        .status(404)
        .json({success: false, data: errors["404"]});

}

function handleEmptyGeoJSONResult(result, response) {
    if (result.rows[0].fc.features) {
        return false;
    }

    return response
        .status(404)
        .json({success: false, data: errors["404"]});
}

function handleError(err, response) {
    if (!err) {
        return false;
    }

    logger.error(err);

    return response
        .status(err.message)
        .json({success: false, data: errors[err.message]});
}

export {handleError, handleEmptyResult, handleEmptyGeoJSONResult};


text:
/* global Promise */
'use strict';

var debug = require('debug')('Example:ModalAction');
var createFluxibleRouteTransformer = require('../utils').createFluxibleRouteTransformer;

/**
 * Execute an optional custom action that may be defined for the dialog.
 *
 * @param {Object} context - The fluxible action context.
 * @param {Object} payload - The MODAL action payload.
 * @param {Object} [payload.action] - A custom action for the modal.
 * @param {String} [payload.split] - A code split handler.
 * @returns {Promise} A promise result.
 */
function executeCustomAction (context, payload) {
  var splits = require('../utils/splits');

  if (payload.action) {
    debug('executing custom action ', payload.action);

    // If the payload also indicates a code split, resolve that first.
    var codeResolver = payload.split ? splits[payload.split]
      : function () {
        return Promise.resolve();
      };

    return codeResolver(context, payload, updateComponent).then(function () {
      var transformer = createFluxibleRouteTransformer({
        actions: require('./interface')
      }).jsonToFluxible;

      // Make the action executable
      payload = transformer({
        payload: payload
      }).payload;

      return context.executeAction(payload.action);
    });
  }

  return Promise.resolve();
}

/**
 * Open a modal dialog.
 * Try to get the dialog content from the contentStore first.
 * After content, execute a custom action if one is specified.
 *
 * @param {Object} context - The fluxible action context.
 * @param {Object} payload - The MODAL action payload.
 * @param {Function} done - The callback to execute on completion.
 */
function openModal (context, payload, done) {
  var data = context.getStore('ContentStore').get(payload.resource);

  debug(payload.resource + (data ? ' found ' : ' not found ') + ' in cache');

  context.dispatch('MODAL_START', {
    component: payload.component,
    props: data
  });

  if (!data) {
    context.service.read('page', payload, {}, function (err, data) {
      debug('Page service request complete');

      if (err) {
        context.dispatch('MODAL_FAILURE', err);
        return done(err);
      }

      if (!data) {
        err = new Error('No data found for '+payload.resource);
        context.dispatch('MODAL_FAILURE', err);
        return done(err);
      }

      context.dispatch('RECEIVE_PAGE_CONTENT', {
        resource: payload.resource,
        data: data
      });

      executeCustomAction(context, payload)
      .then(function () {
        done();
      })
      .catch(function (error) {
        context.dispatch('MODAL_FAILURE', error);
        done(error);
      });
    });
  } else {
    executeCustomAction(context, payload)
    .then(function () {
      done();
    })
    .catch(function (error) {
      context.dispatch('MODAL_FAILURE', error);
      done(error);
    });
  }
}

/**
 * Close the modal dialog.
 *
 * @param {Object} context - The fluxible action context.
 * @param {Object} payload - Ignored.
 * @param {Function} done - The callback to execute on completion.
 */
function closeModal (context, payload, done) {
  context.dispatch('MODAL_STOP');
  done();
}

/**
 * Update the modal UI component.
 *
 * @param {Object} context - The fluxible action context.
 * @param {Object} payload - The MODAL_COMPONENT action payload.
 * @param {String} payload.resource - The name of the component resource.
 * @param {Object} payload.component - The UI component reference.
 * @param {Function} done - The callback to execute on completion.
 */
function updateComponent (context, payload, done) {
  context.dispatch('MODAL_COMPONENT', payload);
  done();
}

module.exports = {
  openModal: openModal,
  closeModal: closeModal,
  updateComponent: updateComponent
};


text:
VPATH = ../tools:equations

# Compiler
FC = gfortran

# Flags
FFLAGS  = -o3 -fexternal-blas
LDFLAGS = -L /usr/local/lib/ -lfftw3 -llapack -lblas

# Objects
EQNS = quasigeostrophic_mod.o nikolaevskiy_mod.o kuramoto_mod.o kdv_mod.o nls_mod.o
METHODS = etdrk4_mod.o etdsdc_mod.o imexsdc_mod.o
PHI = phi_mod.o
TOOLS = tools_mod.o

PROGRAMS = singlerun experimentrun

all: $(PROGRAMS)

$(EQNS): $(TOOLS)
$(METHODS): $(TOOLS) $(PHI)

singlerun.o: $(TOOLS) $(METHODS) $(EQNS)
singlerun: $(TOOLS) $(PHI) $(METHODS) $(EQNS)

experimentrun.o: $(TOOLS) $(METHODS) $(EQNS)
experimentrun: $(TOOLS) $(PHI) $(METHODS) $(EQNS)

# ======================================================================
# General rules. Taken From
# (http://www.webalice.it/o.drofa/davide/makefile-fortran/makefile-fortran.html)
# ======================================================================

# General rule for building prog from prog.o; $^ (GNU extension) is
# used in order to list additional object files on which the
# executable depends
%: %.o
	$(FC) $(FCFLAGS) -o $@.exe $^ $(LDFLAGS)

# General rules for building prog.o from prog.f90 or prog.F90; $< is
# used in order to list only the first prerequisite (the source file)
# and not the additional prerequisites such as module or include files
%.o: %.f90
	$(FC) $(FCFLAGS) -c $<

%.o: %.F90
	$(FC) $(FCFLAGS) -c $<

# Utility targets
.PHONY: clean

clean:
	rm -f *.o *.mod *.MOD


text:
if (!Object.getOwnPropertyDescriptor) {

    Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
        if (Object(object) !== object) {
            throw new TypeError('Object.getOwnPropertyDescriptor can only be called on Objects.');
        }

        var descriptor;
        if (!Object.prototype.hasOwnProperty.call(object, property)) {
            return descriptor;
        }

        descriptor = {
            enumerable: Object.prototype.propertyIsEnumerable.call(object, property),
            configurable: true
        };

        descriptor.value = object[property];

        var psPropertyType = object.reflect.find(property).type;
        descriptor.writable = !(psPropertyType === "readonly");

        return descriptor;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.ObjectMetadataList.html">

Redirecting to type.ObjectMetadataList.html...


text:
#ifndef FREELISTALLOCATOR_H
#define FREELISTALLOCATOR_H

#include "Allocator.h"
#include "SinglyLinkedList.h"

class FreeListAllocator : public Allocator {
public:
    enum PlacementPolicy {
        FIND_FIRST,
        FIND_BEST
    };

private:
    struct FreeHeader {
        std::size_t blockSize;
    };
    struct AllocationHeader {
        std::size_t blockSize;
        char padding;
    };

    typedef SinglyLinkedList<FreeHeader>::Node Node;

    void* m_start_ptr = nullptr;
    PlacementPolicy m_pPolicy;
    SinglyLinkedList<FreeHeader> m_freeList;

public:
    FreeListAllocator(const std::size_t totalSize, const PlacementPolicy pPolicy);

    virtual ~FreeListAllocator();

    virtual void* Allocate(const std::size_t size, const std::size_t alignment = 0) override;

    virtual void Free(void* ptr) override;

    virtual void Init() override;

    virtual void Reset();
private:
    FreeListAllocator(FreeListAllocator &freeListAllocator);

    void Coalescence(Node* prevBlock, Node * freeBlock);

    void Find(const std::size_t size, const std::size_t alignment, std::size_t& padding, Node*& previousNode, Node*& foundNode);
    void FindBest(const std::size_t size, const std::size_t alignment, std::size_t& padding, Node*& previousNode, Node*& foundNode);
    void FindFirst(const std::size_t size, const std::size_t alignment, std::size_t& padding, Node*& previousNode, Node*& foundNode);
};

#endif /* FREELISTALLOCATOR_H */


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.Containers;
using osu.Game.Input.Bindings;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays.Changelog;

namespace osu.Game.Overlays
{
    public class ChangelogOverlay : FullscreenOverlay
    {
        public readonly Bindable<APIChangelogBuild> Current = new Bindable<APIChangelogBuild>();

        protected ChangelogHeader Header;

        private Container<ChangelogContent> content;

        private SampleChannel sampleBack;

        private List<APIChangelogBuild> builds;

        protected List<APIUpdateStream> Streams;

        public ChangelogOverlay()
            : base(OverlayColourScheme.Purple)
        {
        }

        [BackgroundDependencyLoader]
        private void load(AudioManager audio)
        {
            Children = new Drawable[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = ColourProvider.Background4,
                },
                new OverlayScrollContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    ScrollbarVisible = false,
                    Child = new ReverseChildIDFillFlowContainer<Drawable>
                    {
                        RelativeSizeAxes = Axes.X,
                        AutoSizeAxes = Axes.Y,
                        Direction = FillDirection.Vertical,
                        Children = new Drawable[]
                        {
                            Header = new ChangelogHeader
                            {
                                ListingSelected = ShowListing,
                            },
                            content = new Container<ChangelogContent>
                            {
                                RelativeSizeAxes = Axes.X,
                                AutoSizeAxes = Axes.Y,
                            }
                        },
                    },
                },
            };

            sampleBack = audio.Samples.Get(@"UI/generic-select-soft");

            Header.Build.BindTo(Current);

            Current.BindValueChanged(e =>
            {
                if (e.NewValue != null)
                    loadContent(new ChangelogSingleBuild(e.NewValue));
                else
                    loadContent(new ChangelogListing(builds));
            });
        }

        public void ShowListing()
        {
            Current.Value = null;
            Show();
        }

        /// <summary>
        /// Fetches and shows a specific build from a specific update stream.
        /// </summary>
        /// <param name="build">Must contain at least <see cref="APIUpdateStream.Name"/> and
        /// <see cref="APIChangelogBuild.Version"/>. If <see cref="APIUpdateStream.DisplayName"/> and
        /// <see cref="APIChangelogBuild.DisplayVersion"/> are specified, the header will instantly display them.</param>
        public void ShowBuild([NotNull] APIChangelogBuild build)
        {
            if (build == null) throw new ArgumentNullException(nameof(build));

            Current.Value = build;
            Show();
        }

        public void ShowBuild([NotNull] string updateStream, [NotNull] string version)
        {
            if (updateStream == null) throw new ArgumentNullException(nameof(updateStream));
            if (version == null) throw new ArgumentNullException(nameof(version));

            performAfterFetch(() =>
            {
                var build = builds.Find(b => b.Version == version && b.UpdateStream.Name == updateStream)
                            ?? Streams.Find(s => s.Name == updateStream)?.LatestBuild;

                if (build != null)
                    ShowBuild(build);
            });

            Show();
        }

        public override bool OnPressed(GlobalAction action)
        {
            switch (action)
            {
                case GlobalAction.Back:
                    if (Current.Value == null)
                    {
                        Hide();
                    }
                    else
                    {
                        Current.Value = null;
                        sampleBack?.Play();
                    }

                    return true;
            }

            return false;
        }

        protected override void PopIn()
        {
            base.PopIn();

            if (initialFetchTask == null)
                // fetch and refresh to show listing, if no other request was made via Show methods
                performAfterFetch(() => Current.TriggerChange());
        }

        private Task initialFetchTask;

        private void performAfterFetch(Action action) => fetchListing()?.ContinueWith(_ =>
            Schedule(action), TaskContinuationOptions.OnlyOnRanToCompletion);

        private Task fetchListing()
        {
            if (initialFetchTask != null)
                return initialFetchTask;

            return initialFetchTask = Task.Run(async () =>
            {
                var tcs = new TaskCompletionSource<bool>();

                var req = new GetChangelogRequest();

                req.Success += res => Schedule(() =>
                {
                    // remap streams to builds to ensure model equality
                    res.Builds.ForEach(b => b.UpdateStream = res.Streams.Find(s => s.Id == b.UpdateStream.Id));
                    res.Streams.ForEach(s => s.LatestBuild.UpdateStream = res.Streams.Find(s2 => s2.Id == s.LatestBuild.UpdateStream.Id));

                    builds = res.Builds;
                    Streams = res.Streams;

                    Header.Populate(res.Streams);

                    tcs.SetResult(true);
                });

                req.Failure += e =>
                {
                    initialFetchTask = null;
                    tcs.SetException(e);
                };

                await API.PerformAsync(req);

                await tcs.Task;
            });
        }

        private CancellationTokenSource loadContentCancellation;

        private void loadContent(ChangelogContent newContent)
        {
            content.FadeTo(0.2f, 300, Easing.OutQuint);

            loadContentCancellation?.Cancel();

            LoadComponentAsync(newContent, c =>
            {
                content.FadeIn(300, Easing.OutQuint);

                c.BuildSelected = ShowBuild;
                content.Child = c;
            }, (loadContentCancellation = new CancellationTokenSource()).Token);
        }
    }
}


text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Hina.Linq;

// csharp: hina/methodfactory.cs [snipped]
namespace Hina
{
    // thread-safe.
    static class MethodFactory
    {
        public delegate object ConstructorCall(object[] args);
        public delegate object MethodCall(object instance, object[] args);

        static readonly ConcurrentDictionary<object, ConstructorCall> ConstructorCache = new ConcurrentDictionary<object, ConstructorCall>();
        static readonly ConcurrentDictionary<object, MethodCall> MethodCache           = new ConcurrentDictionary<object, MethodCall>();

        struct ExpressionArgsPair
        {
            public Expression Expression;
            public ParameterExpression[] Parameters;
        }

        static ExpressionArgsPair GetObjectCreatorExpressions(ConstructorInfo constructor)
        {
            Check.NotNull(constructor);

            // create a single param of type object[]
            var parameters = Expression.Parameter(typeof(object[]), "args");
            var arguments  = GetMethodCallArgsExpressions(constructor.GetParameters(), parameters);

            return new ExpressionArgsPair()
            {
                Expression = Expression.New(constructor, arguments),
                Parameters = new[] { parameters }
            };
        }

        public static ConstructorCall CompileConstructor(ConstructorInfo constructor)
        {
            Check.NotNull(constructor);

            var expressions = GetObjectCreatorExpressions(constructor);
            var lambda      = Expression.Lambda<ConstructorCall>(expressions.Expression, expressions.Parameters);

            return lambda.Compile();
        }

        // does the same as `CompileObjectConstructor`, but with an extra boxing expression
        static ConstructorCall CompileBoxedConstructor(ConstructorInfo constructor)
        {
            Check.NotNull(constructor);

            var expressions = GetObjectCreatorExpressions(constructor);
            var conversion  = Expression.Convert(expressions.Expression, typeof(object));
            var lambda      = Expression.Lambda<ConstructorCall>(conversion, expressions.Parameters);

            return lambda.Compile();
        }

        public static T CreateInstance<T>(Type type)
        {
            Check.NotNull(type);

            return (T)CreateInstance(type);
        }

        public static object CreateInstance(Type type)
        {
            Check.NotNull(type);

            var creator = ConstructorCache.GetOrAdd(type, (object _) =>
            {
                var constructor = type.GetConstructors().FirstOrDefault(x => x.GetParameters().Length == 0);
                if (constructor == null)
                    throw new ArgumentException("Type does not have any accessible parameterless constructors.");

                return CompileConstructor(constructor);
            });

            return creator(new object[0]);
        }

        static ExpressionArgsPair GetMethodCallExpressions(MethodInfo method)
        {
            Check.NotNull(method);

            // create a single param of type object[]
            var instanceParameter = Expression.Parameter(typeof(object), "instance");
            var instance          = Expression.Convert(instanceParameter, method.DeclaringType);

            var parameters   = Expression.Parameter(typeof(object[]), "args");
            var arguments    = GetMethodCallArgsExpressions(method.GetParameters(), parameters);

            // call method with args
            var callInstance = method.IsStatic ? null : instance;
            var caller       = (Expression)Expression.Call(callInstance, method, arguments);

            // the lambda compilation won't work without this - `void` cannot be coerced into an `object`
            if (method.ReturnType == typeof(void))
                caller = Expression.Block(caller, Expression.Default(typeof(object)));

            return new ExpressionArgsPair()
            {
                Expression = caller,
                Parameters = new[] { instanceParameter, parameters }
            };
        }

        static Expression[] GetMethodCallArgsExpressions(ParameterInfo[] parameters, ParameterExpression args)
        {
            Check.NotNull(parameters, args);

            return Enumerable.Range(0, parameters.Length).MapArray(i =>
            {
                // create a type cast expression for each argument
                var index           = Expression.Constant(i);
                var parameterType   = parameters[i].ParameterType;
                var parameterAccess = Expression.ArrayIndex(args, index);
                return (Expression)Expression.Convert(parameterAccess, parameterType);
            });
        }

        static MethodCall CompileMethodCall(MethodInfo method)
        {
            Check.NotNull(method);

            var expressions = GetMethodCallExpressions(method);
            var lambda      = Expression.Lambda<MethodCall>(expressions.Expression, expressions.Parameters);

            return lambda.Compile();
        }

        // does the same as `CompileObjectConstructor`, but with an extra boxing expression
        static MethodCall CompileBoxedMethodCall(MethodInfo method)
        {
            Check.NotNull(method);

            var expressions = GetMethodCallExpressions(method);
            var conversion  = Expression.Convert(expressions.Expression, typeof(object));
            var lambda      = Expression.Lambda<MethodCall>(conversion, expressions.Parameters);

            return lambda.Compile();
        }

        // `instance` may be null if the method is a static method, and `arguments` may be null if the method takes no
        // arguments
        public static T CallMethod<T>(MethodInfo method, object instance, object[] arguments)
        {
            return (T)CallMethod(method, instance, arguments);
        }

        // `instance` may be null if the method is a static method, and `arguments` may be null if the method takes no
        // arguments
        public static object CallMethod(MethodInfo method, object instance, object[] arguments)
        {
            Check.NotNull(method);

            return MethodCache.GetOrAdd(method, _ => CompileMethodCall(method))(instance, arguments);
        }
    }
}


text:
package org.estatio.module.invoicegroup.fixtures;

import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.fixturescripts.PersonaWithBuilderScript;
import org.apache.isis.applib.fixturescripts.PersonaWithFinder;
import org.apache.isis.applib.services.registry.ServiceRegistry2;

import org.estatio.module.asset.dom.Property;
import org.estatio.module.asset.fixtures.property.enums.Property_enum;
import org.estatio.module.invoicegroup.dom.InvoiceGroup;
import org.estatio.module.invoicegroup.dom.InvoiceGroupRepository;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Accessors;

@AllArgsConstructor
@Getter
@Accessors(chain = true)
public enum InvoiceGroup_enum implements PersonaWithBuilderScript<InvoiceGroup, InvoiceGroupBuilder>,
        PersonaWithFinder<InvoiceGroup> {

    BudNl   ("BUD", new Property_enum[] {Property_enum.BudNl}),
    RonIt   ("RON", new Property_enum[] {Property_enum.RonIt}),
    GraIt   ("GRA", new Property_enum[] {Property_enum.GraIt}),
    HanSe   ("HAN", new Property_enum[] {Property_enum.HanSe}),
    KalNl   ("KAL", new Property_enum[] {Property_enum.KalNl}),
    MacFr   ("MAC", new Property_enum[] {Property_enum.MacFr}),
    MnsFr   ("MNS", new Property_enum[] {Property_enum.MnsFr}),
    OxfGb   ("OXF", new Property_enum[] {Property_enum.OxfGb}),
    VivFr   ("VIV", new Property_enum[] {Property_enum.VivFr, Property_enum.BvvFr});

    private final String ref;
    private final Property_enum[] properties_d;

    @Override
    public InvoiceGroup findUsing(final ServiceRegistry2 serviceRegistry) {
        final InvoiceGroupRepository repository =
                serviceRegistry.lookupService(InvoiceGroupRepository.class);
        return repository.findByReference(ref).orElseThrow(() -> new IllegalStateException(
                String.format("Invoice group '%s' not setup", ref)));
    }

    public InvoiceGroupBuilder builder() {
        return new InvoiceGroupBuilder()
                        .setRef(ref)
                        .setPrereq((f, ec) -> {
                            for (final Property_enum property_d : properties_d) {
                                final Property property = f.objectFor(property_d, ec);
                                f.getProperties().add(property);
                            }
                        });
    }

    @Programmatic
    public static class PersistAll extends FixtureScript {

        @Override
        protected void execute(final ExecutionContext executionContext) {
            for (final InvoiceGroup_enum datum : values()) {
                executionContext.executeChild(this, datum.builder());
            }
        }
    }
}