text:
<ns0:metadata xmlns:ns0="http://purl.org/ornl/schema/mercury/terms/v1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://purl.org/ornl/schema/mercury/terms/v1.0 mercury-ornl-v1.xsd">
  <idinfo>
    <citation>
      <citeinfo>
        <origin>Socioeconomic Data and Applications Center (SEDAC), Center for International Earth Science Information Network (CIESIN)</origin>
        <title>Gridded Population of the World, version 3 (GPWv3)</title>
        <onlink>http://daac.ornl.gov/metadata/bluangel_harvest/RGED/QC/basic/human_dimensions/ciesin_world_gridded_pop.xml</onlink>
        <alt_onlink>http://daac.ornl.gov/metadata/bluangel_harvest/RGED/QC/basic/human_dimensions/ciesin_world_gridded_pop.xml</alt_onlink>
        <onlink />
        <onlink />
      </citeinfo>
    </citation>
    <descript>
      <abstract>The Gridded Population of the World, version 3 (GPWv3) depicts the distribution of human population across the globe. The data product renders global population data at the scale and extent required to demonstrate the spatial relationship of human populations and the environment across the globe. The purpose of GPWv3 is to provide a spatially disaggregated population layer that is compatible with data sets from social, economic, and Earth science fields. The gridded data set is constructed from national or subnational input units (usually administrative units) of varying resolutions. The native grid cell resolution is 2.5 arc-minutes, or ~5km at the equator, although aggregates at coarser resolutions are also provided. Separate grids are available for population count and density per grid cell. Population data estimates are provided for 1990, 1995, and 2000, and projected to 2005, 2010, and 2015.</abstract>
      <supplinf />
    </descript>
    <timeperd>
      <timeinfo>
        <rngdates>
          <begdate>19900101</begdate>
          <enddate>20151231</enddate>
        </rngdates>
      </timeinfo>
    </timeperd>
    <status>
      <progress>Final</progress>
      <update>As appropriate</update>
    </status>
    <spdom>
      <bounding>
        <westbc>-179.2</westbc>
        <eastbc>179.85</eastbc>
        <northbc>79.89</northbc>
        <southbc>-54.75</southbc>
      </bounding>
    </spdom>
    <keywords>
      <theme>
        <themekt>Parameter_Sensor_Source</themekt>
        <themekey>POPULATION DISTRIBUTION|ANALYSIS|COMPUTER MODEL</themekey>
        <themekey>POPULATION SIZE|ANALYSIS|COMPUTER MODEL</themekey>
      </theme>
      <theme>
        <themekt>Parameter</themekt>
        <themekey>POPULATION DISTRIBUTION</themekey>
      </theme>
      <theme>
        <themekt>Source</themekt>
        <themekey>COMPUTER MODEL</themekey>
      </theme>
      <theme>
        <themekt>Sensor</themekt>
        <themekey>ANALYSIS</themekey>
      </theme>
      <place>
        <placekt>Place Keywords</placekt>
        <placekey>Global (gridded)</placekey>
      </place>
    </keywords>
    <ptcontac>
      <cntinfo>
        <cntperp>
          <cntper>Socioeconomic Data and Applications Center (SEDAC), Center for International Earth Science Information Network (CIESIN)</cntper>
        </cntperp>
        <cntfax>6.1.10.8 Contact Electronic Mail: INTERNET &gt; CIESIN.Info@ciesin.org</cntfax>
      </cntinfo>
    </ptcontac>
  </idinfo>
  <distinfo>
    <distrib>
      <cntinfo>
        <cntperp>
          <cntorg>Socioeconomic Data and Applications Center (SEDAC), Center for International Earth Science Information Network (CIESIN), Columbia University/Lamont-Doherty Earth Observatory, Palisades, New York, USA</cntorg>
          <cntper>SEDAC User Services</cntper>
        </cntperp>
        <cntvoice>+1-517-797-2727</cntvoice>
        <cntfax>6.1.10.8 Contact Electronic Mail: INTERNET &gt; CIESIN.Info@ciesin.org</cntfax>
        <cntemail>CIESIN.Info@ciesin.org</cntemail>
      </cntinfo>
    </distrib>
    <stdorder>
      <digform>
        <digtopt>
          <onlinopt>
            <computer>http://sedac.ciesin.columbia.edu</computer>
            <accinstr>Public</accinstr>
          </onlinopt>
        </digtopt>
      </digform>
    </stdorder>
    <resdesc>Gridded Population of the World, version 3 (GPWv3). 2005. Available online at [http://sedac.ciesin.columbia.edu/gpw/index.jsp] from the Socioeconomic Data and Applications Center (SEDAC), Center for International Earth Science Information Network (CIESIN), Columbia University/Lamont-Doherty Earth Observatory, Palisades, New York, USA.</resdesc>
  </distinfo>
  <metainfo>
    <metd>20120418 162330</metd>
    <metc>
      <cntinfo>
        <cntorgp>
          <cntper>ORNL DAAC Staff</cntper>
        </cntorgp>
        <cntperp>
          <cntper>ORNL DAAC Staff</cntper>
        </cntperp>
        <cntvoice>+1(865)241-3952</cntvoice>
        <cntemail>ornldaac@ornl.gov</cntemail>
      </cntinfo>
    </metc>
    <metstdn>FGDC Content Standard for Digital Geospatial Metadata</metstdn>
  </metainfo>
  <mercury>
    <begdate>19900101</begdate>
    <enddate>20151231</enddate>
    <Site_Information>
      <Site>Global (gridded)</Site>
      <Westernmost_Longitude>-179.2</Westernmost_Longitude>
      <Easternmost_Longitude>179.85</Easternmost_Longitude>
      <Northernmost_Latitude>79.89</Northernmost_Latitude>
      <Southernmost_Latitude>-54.75</Southernmost_Latitude>
    </Site_Information>
    <Keywords>EOSDIS</Keywords>
    <Keywords>Global population</Keywords>
    <Keywords>GPW</Keywords>
    <Keywords>GPW v3</Keywords>
    <Keywords>Human Dimensions Collections</Keywords>
    <Keywords>Population count</Keywords>
    <Keywords>Population density</Keywords>
    <Keywords>Population estimates</Keywords>
    <Keywords>Population projections</Keywords>
    <Keywords>Population studies</Keywords>
    <Keywords>Rural population</Keywords>
    <Keywords>Urban population</Keywords>
    <Parameter_Description>
      <Parameter>POPULATION DISTRIBUTION</Parameter>
      <Sensor>ANALYSIS</Sensor>
      <Source>COMPUTER MODEL</Source>
      <Term>POPULATION</Term>
      <Topic>HUMAN DIMENSIONS</Topic>
    </Parameter_Description>
    <Parameter_Description>
      <Parameter>POPULATION SIZE</Parameter>
      <Sensor>ANALYSIS</Sensor>
      <Source>COMPUTER MODEL</Source>
      <Term>POPULATION</Term>
      <Topic>HUMAN DIMENSIONS</Topic>
    </Parameter_Description>
    <Project />
    <Navpath>COMPUTER MODEL|ANALYSIS|POPULATION DISTRIBUTION</Navpath>
    <Navpath>COMPUTER MODEL|ANALYSIS|POPULATION SIZE</Navpath>
    <Principal_Investigator>
      <Name>Socioeconomic Data and Applications Center (SEDAC), Center for International Earth Science Information Network (CIESIN)</Name>
      <Email>CIESIN.Info@ciesin.org</Email>
    </Principal_Investigator>
    <Data_Set_Link>
      <URL>http://sedac.ciesin.columbia.edu/gpw/global.jsp</URL>
      <Label>Gridded Population of the World, version 3 (GPWv3)</Label>
      <Link_Note>Follow instructions on this web page to download data.</Link_Note>
    </Data_Set_Link>
    <Documentation_Link>
      <URL />
      <Label />
      <Text />
    </Documentation_Link>
    <Documentation_Link>
      <URL />
      <Label />
    </Documentation_Link>
    <Alternate_Data_Access>
      <Data_Set_Status />
      <Data_Set_Restrictions />
      <Data_Set_Location />
      <Data_Contact_Person>
        <Email />
        <Name />
        <Phone />
        <Data_Center_URL />
      </Data_Contact_Person>
      <Data_Center_URL />
      <Data_Set_Citation />
      <Data_Set_Link>
        <URL />
        <Label />
        <Link_Note />
        <Data_Center_URL />
      </Data_Set_Link>
    </Alternate_Data_Access>
    <OME_Software_Version>Version 4.7.5, Revision Date: 04 Apr 2006</OME_Software_Version>
    <OME_DTD_Version>basic02.dtd</OME_DTD_Version>
    <Contact_Person>
      <Email>CIESIN.Info@ciesin.org</Email>
      <Name>SEDAC User Services</Name>
      <Phone>+1-517-797-2727</Phone>
    </Contact_Person>
    <Temporal_Resolution />
    <enddate_blank />
    <File_ID>Created 20120418 155757 by 66.82.162.37</File_ID>
    <Spatial_Reference_Method>Raster</Spatial_Reference_Method>
    <Spatial_Extent>48342.492</Spatial_Extent>
    <Search_Text_Link>
      <URL />
      <Label />
    </Search_Text_Link>
    <Other_Link>
      <URL />
      <Label />
    </Other_Link>
    <Granule_Details />
    <OGC_URL />
  </mercury>
  <sourceData>database</sourceData>
</ns0:metadata>


text:
package com.thoughtworks.go.server.messaging;

import com.thoughtworks.go.server.service.BackupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ServerBackupListener implements GoMessageListener<StartServerBackupMessage> {
    private BackupService backupService;

    @Autowired
    public ServerBackupListener(BackupService backupService, ServerBackupQueue queue) {
        this.backupService = backupService;
        queue.addListener(this);
    }

    @Override
    public void onMessage(StartServerBackupMessage message) {
        backupService.startBackupWithId(message.getId());
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Language.PureScript.Parser (module P) where

import Language.PureScript.Parser.Common as P
import Language.PureScript.Parser.Types as P
import Language.PureScript.Parser.State as P
import Language.PureScript.Parser.Kinds as P
import Language.PureScript.Parser.Declarations as P


text:
<?php

namespace MusicBrainz\Value\Page;

use MusicBrainz\Value\Release;
use MusicBrainz\Value\Page;

/**
 * A list of values
 */
class ReleaseListPage extends Page
{
    /**
     * Returns the class name of the list elements.
     *
     * @return string
     */
    public static function getType(): string
    {
        return Release::class;
    }
}


text:
package version_test

import (
	"fmt"
	"regexp"
	"testing"

	"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/commands/cmdrunner"
	"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/commands/cmdtest"
)

var (
	// TODO(kashomon): Use a real SemVer library to test this.
	numPattern     = `([1-9]\d*|0)`
	versionPattern = regexp.MustCompile(fmt.Sprintf(`^%s\.%s\.%s$`, numPattern, numPattern, numPattern))
)

func TestVersion(t *testing.T) {
	fakeio := cmdtest.NewFakeCmdIO()

	if err := cmdrunner.ExecuteCommand(fakeio, []string{
		"version",
	}); err != nil {
		t.Fatal(err)
	}

	version := string(fakeio.StdIO.WriteBytes)
	if !versionPattern.MatchString(version) {
		t.Errorf("Got version %s, but expected it to have the form X.Y.Z", version)
	}
}


text:
namespace CsIRC.Core.Events
{
    /// <summary>
    /// Event arguments for an event that applies to a user in a channel.
    /// </summary>
    public class ChannelUserCommandEventArgs : IRCMessageEventArgs, IChannelEvent, IUserEvent
    {
        /// <summary>
        /// The IRC channel the event applies to.
        /// </summary>
        public IRCChannel Channel { get; private set; }

        /// <summary>
        /// The IRC user the event applies to.
        /// </summary>
        public IRCUser User { get; private set; }

        /// <summary>
        /// Creates new event arguments for an event that applies to a user in a channel.
        /// </summary>
        /// <param name="message">The message that was received from the server.</param>
        /// <param name="channel">The channel the event applies to.</param>
        /// <param name="user">The user the event applies to.</param>
        public ChannelUserCommandEventArgs(IRCMessage message, IRCChannel channel, IRCUser user) : base(message)
        {
            Channel = channel;
            User = user;
        }
    }
}


text:
import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.SystemUtils;
import org.moeaframework.Executor;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.Solution;
import org.moeaframework.core.variable.RealVariable;
import org.moeaframework.problem.ExternalProblem;

/**
 * Similar to Example4, sockets can be used instead of standard I/O for
 * communicating with the external process.  Run the command 'make' in the
 * ./examples/ folder to compile the executable.  This example will only
 * work on POSIX (Unix-like) systems.
 */
public class Example6 {

	/**
	 * Notice that the only change is in the constructor, where the hostname and
	 * port are specified.
	 */
	public static class MyDTLZ2 extends ExternalProblem {

		public MyDTLZ2() throws IOException {
			super("localhost", ExternalProblem.DEFAULT_PORT);
		}

		@Override
		public String getName() {
			return "DTLZ2";
		}

		@Override
		public int getNumberOfVariables() {
			return 11;
		}

		@Override
		public int getNumberOfObjectives() {
			return 2;
		}

		@Override
		public int getNumberOfConstraints() {
			return 0;
		}

		@Override
		public Solution newSolution() {
			Solution solution = new Solution(getNumberOfVariables(),
					getNumberOfObjectives());

			for (int i = 0; i < getNumberOfVariables(); i++) {
				solution.setVariable(i, new RealVariable(0.0, 1.0));
			}

			return solution;
		}

	}

	public static void main(String[] args) throws IOException,
	InterruptedException {
		//check if the executable exists
		File file = new File("./examples/dtlz2_socket.exe");

		if (!file.exists()) {
			if (!SystemUtils.IS_OS_UNIX) {
				System.err.println("This example only works on POSIX-compliant systems; see the Makefile for details");
				return;
			}

			System.err.println("Please compile the executable by running make in the ./examples/ folder");
			return;
		}

		//run the executable and wait one second for the process to startup
		new ProcessBuilder(file.toString()).start();
		Thread.sleep(1000);

		//configure and run the DTLZ2 function
		NondominatedPopulation result = new Executor()
				.withProblemClass(MyDTLZ2.class)
				.withAlgorithm("NSGAII")
				.withMaxEvaluations(10000)
				.run();

		//display the results
		System.out.format("Objective1  Objective2%n");

		for (Solution solution : result) {
			System.out.format("%.4f      %.4f%n",
					solution.getObjective(0),
					solution.getObjective(1));
		}
	}

}


text:
package org.sagebionetworks.repo.model.dbo.dao;

import static junit.framework.Assert.assertNotNull;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sagebionetworks.ids.IdGenerator;
import org.sagebionetworks.ids.IdType;
import org.sagebionetworks.repo.model.CommentDAO;
import org.sagebionetworks.repo.model.MessageDAO;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.UserGroup;
import org.sagebionetworks.repo.model.UserGroupDAO;
import org.sagebionetworks.repo.model.dbo.file.FileHandleDao;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.message.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" })
public class DBOCommentDAOImplTest {

	@Autowired
	private CommentDAO commentDAO;

	@Autowired
	private MessageDAO messageDAO;

	@Autowired
	private UserGroupDAO userGroupDAO;

	@Autowired
	private FileHandleDao fileDAO;

	@Autowired
	private IdGenerator idGenerator;

	private String fileHandleId;
	private UserGroup maliciousUser;

	private List<String> cleanup;

	@Before
	public void setup() throws Exception {
		cleanup = new ArrayList<String>();

		maliciousUser = new UserGroup();
		maliciousUser.setIsIndividual(true);
		maliciousUser.setId(userGroupDAO.create(maliciousUser).toString());

		// We need a file handle to satisfy a foreign key constraint
		// But it doesn't need to point to an actual file
		// Also, it doesn't matter who the handle is tied to
		FileHandle handle = TestUtils.createS3FileHandle(maliciousUser.getId(), idGenerator.generateNewId(IdType.FILE_IDS).toString());
		handle = fileDAO.createFile(handle);
		fileHandleId = handle.getId();
	}

	@After
	public void cleanup() throws Exception {
		for (String id : cleanup) {
			messageDAO.deleteMessage(id);
		}
		fileDAO.delete(fileHandleId);
		userGroupDAO.delete(maliciousUser.getId());
	}

	@Test
	public void testCreate() throws Exception {
		Comment dto = new Comment();
		// Note: ID is auto generated
		dto.setCreatedBy(maliciousUser.getId());
		dto.setFileHandleId(fileHandleId);
		// Note: CreatedOn is set by the DAO
		dto.setTargetId("1337");
		dto.setTargetType(ObjectType.ENTITY);

		dto = commentDAO.createComment(dto);
		assertNotNull(dto.getId());
		cleanup.add(dto.getId());
		assertNotNull(dto.getCreatedOn());
	}
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = stripLow;

var _assertString = _interopRequireDefault(require("./util/assertString"));

var _blacklist = _interopRequireDefault(require("./blacklist"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function stripLow(str, keep_new_lines) {
  (0, _assertString.default)(str);
  var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F';
  return (0, _blacklist.default)(str, chars);
}

module.exports = exports.default;
module.exports.default = exports.default;


text:
/*===================================================================

Copyright (c) 2000-2014 Chih-Chung Chang and Chih-Jen Lin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither name of copyright holders nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

===================================================================*/

#ifndef _LIBSVM_H
#define _LIBSVM_H

#define LIBSVM_VERSION 318

#ifdef __cplusplus
extern "C" {
#endif

extern int libsvm_version;

struct svm_node
{
  int index;
  double value;
};

struct svm_problem
{
  int l;
  double *y;
  struct svm_node **x;
  double *W; /* instance weight */
};

enum { C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR }; /* svm_type */
enum { LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED }; /* kernel_type */

struct svm_parameter
{
  int svm_type;
  int kernel_type;
  int degree; /* for poly */
  double gamma; /* for poly/rbf/sigmoid */
  double coef0; /* for poly/sigmoid */

  /* these are for training only */
  double cache_size; /* in MB */
  double eps; /* stopping criteria */
  double C; /* for C_SVC, EPSILON_SVR and NU_SVR */
  int nr_weight;  /* for C_SVC */
  int *weight_label; /* for C_SVC */
  double* weight;  /* for C_SVC */
  double nu; /* for NU_SVC, ONE_CLASS, and NU_SVR */
  double p; /* for EPSILON_SVR */
  int shrinking; /* use the shrinking heuristics */
  int probability; /* do probability estimates */
};

//
// svm_model
//
struct svm_model
{
  struct svm_parameter param; /* parameter */
  int nr_class;  /* number of classes, = 2 in regression/one class svm */
  int l;   /* total #SV */
  struct svm_node **SV;  /* SVs (SV[l]) */
  double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */
  double *rho;  /* constants in decision functions (rho[k*(k-1)/2]) */
  double *probA;  /* pariwise probability information */
  double *probB;
  int *sv_indices;        /* sv_indices[0,...,nSV-1] are values in [1,...,num_traning_data] to indicate SVs in the training set */

  /* for classification only */

  int *label;  /* label of each class (label[k]) */
  int *nSV;  /* number of SVs for each class (nSV[k]) */
  /* nSV[0] + nSV[1] + ... + nSV[k-1] = l */
  /* XXX */
  int free_sv;  /* 1 if svm_model is created by svm_load_model*/
  /* 0 if svm_model is created by svm_train */
};

struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param);
void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target);

int svm_save_model(const char *model_file_name, const struct svm_model *model);
struct svm_model *svm_load_model(const char *model_file_name);

int svm_get_svm_type(const struct svm_model *model);
int svm_get_nr_class(const struct svm_model *model);
void svm_get_labels(const struct svm_model *model, int *label);
void svm_get_sv_indices(const struct svm_model *model, int *sv_indices);
int svm_get_nr_sv(const struct svm_model *model);
double svm_get_svr_probability(const struct svm_model *model);

double svm_predict_values(const struct svm_model *model, const struct svm_node *x, double* dec_values);
double svm_predict(const struct svm_model *model, const struct svm_node *x);
double svm_predict_probability(const struct svm_model *model, const struct svm_node *x, double* prob_estimates);

void svm_free_model_content(struct svm_model *model_ptr);
void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr);
void svm_destroy_param(struct svm_parameter *param);

const char *svm_check_parameter(const struct svm_problem *prob, const struct svm_parameter *param);
int svm_check_probability_model(const struct svm_model *model);

void svm_set_print_string_function(void (*print_func)(const char *));

#ifdef __cplusplus
}
#endif

#endif /* _LIBSVM_H */


text:
package space.pxls.server.packets.http;

public class SignInResponse {
    public String url;

    public SignInResponse(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }
}


text:
package support;

/**
 * Author:  Florian Wolf
 * Email:   florian.wolf@maibornwolff.de
 * on 21/12/15.
 */
public class ChartHelper {
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kellondebuggaus;

/**
 *
 * @author Jenni
 */
public class KellonDebuggaus {

  public static void main(String[] args) {

        YlhaaltaRajoitettuLaskuri sekunnit = new YlhaaltaRajoitettuLaskuri(59);
        YlhaaltaRajoitettuLaskuri minuutit = new YlhaaltaRajoitettuLaskuri(59);
        YlhaaltaRajoitettuLaskuri tunnit = new YlhaaltaRajoitettuLaskuri(23);

        tunnit.asetaArvo(23);
        minuutit.asetaArvo(50);

        int i = 0;
        while (i < 602) {
            System.out.println(tunnit + ":" + minuutit + ":" + sekunnit);
            sekunnit.seuraava();
            if (sekunnit.arvo() == 0) {
                minuutit.seuraava();
                if (minuutit.arvo()==0 ) {
                    tunnit.seuraava();
                }
            }

            i++;
        }
    }

}


text:
'use strict';

module.exports = {
	db: 'mongodb://localhost/timeline-test',
	port: 3001,
	app: {
		title: 'TimeLine - Test Environment'
	},
	facebook: {
		clientID: 'APP_ID',
		clientSecret: 'APP_SECRET',
		callbackURL: 'http://localhost:3000/auth/facebook/callback'
	},
	twitter: {
		clientID: 'CONSUMER_KEY',
		clientSecret: 'CONSUMER_SECRET',
		callbackURL: 'http://localhost:3000/auth/twitter/callback'
	},
	google: {
		clientID: 'APP_ID',
		clientSecret: 'APP_SECRET',
		callbackURL: 'http://localhost:3000/auth/google/callback'
	},
	linkedin: {
		clientID: 'APP_ID',
		clientSecret: 'APP_SECRET',
		callbackURL: 'http://localhost:3000/auth/linkedin/callback'
	}
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = false)]
namespace Framework.Log4NetImpl
{

    public class Log4NetHelper
    {
        #region Atributos

        protected ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        #endregion

        #region Métodos
        public static void Inicializacao()
        {
            log4net.Config.XmlConfigurator.Configure();
        }

        #endregion
    }
}


text:
<?php

namespace Symfony\Component\HttpKernel\Fragment;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\UriSigner;
use Twig\Environment;

/**
 * Implements the Hinclude rendering strategy.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class HIncludeFragmentRenderer extends RoutableFragmentRenderer
{
    private ?string $globalDefaultTemplate;
    private ?UriSigner $signer;
    private ?Environment $twig;
    private string $charset;

    /**
     * @param string $globalDefaultTemplate The global default content (it can be a template name or the content)
     */
    public function __construct(Environment $twig = null, UriSigner $signer = null, string $globalDefaultTemplate = null, string $charset = 'utf-8')
    {
        $this->twig = $twig;
        $this->globalDefaultTemplate = $globalDefaultTemplate;
        $this->signer = $signer;
        $this->charset = $charset;
    }

    /**
     * Checks if a templating engine has been set.
     */
    public function hasTemplating(): bool
    {
        return null !== $this->twig;
    }

    /**
     * {@inheritdoc}
     *
     * Additional available options:
     *
     *  * default:    The default content (it can be a template name or the content)
     *  * id:         An optional hx:include tag id attribute
     *  * attributes: An optional array of hx:include tag attributes
     */
    public function render(string|ControllerReference $uri, Request $request, array $options = []): Response
    {
        if ($uri instanceof ControllerReference) {
            $uri = (new FragmentUriGenerator($this->fragmentPath, $this->signer))->generate($uri, $request);
        }

        // We need to replace ampersands in the URI with the encoded form in order to return valid html/xml content.
        $uri = str_replace('&', '&', $uri);

        $template = $options['default'] ?? $this->globalDefaultTemplate;
        if (null !== $this->twig && $template && $this->twig->getLoader()->exists($template)) {
            $content = $this->twig->render($template);
        } else {
            $content = $template;
        }

        $attributes = isset($options['attributes']) && \is_array($options['attributes']) ? $options['attributes'] : [];
        if (isset($options['id']) && $options['id']) {
            $attributes['id'] = $options['id'];
        }
        $renderedAttributes = '';
        if (\count($attributes) > 0) {
            $flags = \ENT_QUOTES | \ENT_SUBSTITUTE;
            foreach ($attributes as $attribute => $value) {
                $renderedAttributes .= sprintf(
                    ' %s="%s"',
                    htmlspecialchars($attribute, $flags, $this->charset, false),
                    htmlspecialchars($value, $flags, $this->charset, false)
                );
            }
        }

        return new Response(sprintf('<hx:include src="%s"%s>%s</hx:include>', $uri, $renderedAttributes, $content));
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'hinclude';
    }
}


text:
template <class T>
class BinaryNode
{
	public:
		BinaryNode() {};
		BinaryNode(const T& nodeItem, BinaryNode *left=NULL, BinaryNode
				*right=NULL) :
			item(nodeItem), leftChild(left), rightChild(right) {}
		~BinaryNode() {};
		bool isLeaf() const {return (leftChild==NULL && rightChild==NULL);};
		T item;
		// The item
		BinaryNode<T> *leftChild; // The left child
		BinaryNode<T> *rightChild; // The right child
};

template <class T>
class BinaryTree
{
	public:
		BinaryTree() : root(NULL) {};
		BinaryTree(const T& rootItem) {root = new BinaryNode<T>(rootItem);};
		~BinaryTree() {delete root;};
		BinaryNode<T>* getRoot() const {return root;};
		bool isEmpty() const {return (root==NULL);};
		void attachLeft(const T& anItem); // Creates a left node with anItem as the root
		void attachRight(const T& anItem);// Creates a right node with anItem as the root
		void attachLeftTree(BinaryTree<T>* tree); // Attaches a left tree to the root
		void attachRightTree(BinaryTree<T>* tree);//Attaches a right tree to the root
		void flip(BinaryNode<T>* node); // After this operation the tree below this node is a mirror image of its original value
	private:
			BinaryNode<T> *root;
};


text:
<!doctype html>

	{{ theme:partial name="metadata" }}

			{{ theme:partial name="header" }}

			{{ theme:partial name="navigation" }}

		{{ theme:partial name="content" }}

			{{ theme:partial name="footer" }}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>uvijek odlicna hrana. pileci raznjici s povrcem su savrseni.</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/catering-andjeo</Source>
</CrawlItem>


text:
package jrd

import (
	"testing"
)

func TestParseJRD(t *testing.T) {

	// Adapted from spec http://tools.ietf.org/html/rfc6415#appendix-A
	blob := `
        {
              "subject":"http://blog.example.com/article/id/314",

              "aliases":[
                "http://blog.example.com/cool_new_thing",
                "http://blog.example.com/steve/article/7"],

              "properties":{
                "http://blgx.example.net/ns/version":"1.3",
                "http://blgx.example.net/ns/ext":null
              },

              "links":[
                {
                  "rel":"author",
                  "type":"text/html",
                  "href":"http://blog.example.com/author/steve",
                  "titles":{
                    "default":"About the Author",
                    "en-us":"Author Information"
                  },
                  "properties":{
                    "http://example.com/role":"editor"
                  }
                },
                {
                  "rel":"author",
                  "href":"http://example.com/author/john",
                  "titles":{
                    "default":"The other author"
                  }
                },
                {
                  "rel":"copyright"
                }
              ]
            }
        `
	obj, err := ParseJRD([]byte(blob))
	if err != nil {
		t.Fatal(err)
	}
	if got, want := obj.Subject, "http://blog.example.com/article/id/314"; got != want {
		t.Errorf("JRD.Subject is %q, want %q", got, want)
	}
	if got, want := obj.GetProperty("http://blgx.example.net/ns/version"), "1.3"; got != want {
		t.Errorf("obj.GetProperty('http://blgx.example.net/ns/version') returned %q, want %q", got, want)
	}
	if got, want := obj.GetProperty("http://blgx.example.net/ns/ext"), ""; got != want {
		t.Errorf("obj.GetProperty('http://blgx.example.net/ns/ext') returned %q, want %q", got, want)
	}
	if obj.GetLinkByRel("copyright") == nil {
		t.Error("obj.GetLinkByRel('copyright') returned nil, want non-nil value")
	}
	if got, want := obj.GetLinkByRel("author").Titles["default"], "About the Author"; got != want {
		t.Errorf("obj.GetLinkByRel('author').Titles['default'] returned %q, want %q", got, want)
	}
	if got, want := obj.GetLinkByRel("author").GetProperty("http://example.com/role"), "editor"; got != want {
		t.Errorf("obj.GetLinkByRel('author').GetProperty('http://example.com/role') returned %q, want %q", got, want)
	}
}


text:
package com.twistedplane.sealnote.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * A helper class to easily get dates and times for use in notes and views.
 * Appropriate conversions from current timezone to GMT is made behind the
 * scenes.
 */
public class EasyDate {
    public final static String TAG = "EasyDate";

    private final static String mDF_ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";

    final private Date mDate;

    /**
     * Return EasyDate object containing current timestamp.
     */
    public static EasyDate now() {
        return new EasyDate(new Date());
    }

    /**
     * Convert a date given in ISO format to EasyDate object
     *
     * @param date  String containing date in ISO format
     * @return      EasyDate object with given date
     * @throws      ParseException
     */
    public static EasyDate fromIsoString(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat(mDF_ISO_FORMAT);
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        return new EasyDate(df.parse(date));
    }

    /**
     * Create a EasyDate object using given java Date object
     */
    private EasyDate(Date date) {
        mDate = date;
    }

    /**
     * Convert current EasyDate object to ISO format string with UTC
     * as timezone.
     *
     * @return  String containing ISO format UTC time.
     */
    public String toString() {
        SimpleDateFormat df = new SimpleDateFormat(mDF_ISO_FORMAT);
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        return df.format(mDate);
    }

    /**
     * Return a string containing datetime in user friendly easy to read
     * form.
     *
     * + If the date equal to today, just show time. Eg "12:40 PM"
     * + If year is equal to current year. Eg. "24th July"
     * + Else show date. Eg. "24th July 2011"
     */
    public String friendly() {
        Calendar now = Calendar.getInstance();
        Calendar previous = Calendar.getInstance();
        SimpleDateFormat df;

        previous.setTime(mDate);

        if (previous.get(Calendar.DATE) == now.get(Calendar.DATE) &&
                previous.get(Calendar.MONTH) == now.get(Calendar.MONTH) &&
                previous.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
            df = new SimpleDateFormat("hh:mm aa");
        } else if (previous.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
            df = new SimpleDateFormat("MMM dd");

        } else {
            df = new SimpleDateFormat("MMM dd, yyyy");
        }
        df.setTimeZone(TimeZone.getDefault());
        return df.format(mDate);
    }
}


text:
try:
    from django.utils import timezone as datetime
except ImportError:
    from datetime import datetime

from django.contrib.auth.models import Group
from django.contrib.sites.models import Site
from django.db import models
from django.db.models.signals import post_save, post_delete, m2m_changed

from waffle.compat import AUTH_USER_MODEL, cache
from waffle.utils import get_setting, keyfmt

class Flag(models.Model):
    """A feature flag.

    Flags are active (or not) on a per-request basis.

    """
    name = models.CharField(max_length=100,
                            help_text='The human/computer readable name.')
    everyone = models.NullBooleanField(blank=True, help_text=(
        'Flip this flag on (Yes) or off (No) for everyone, overriding all '
        'other settings. Leave as Unknown to use normally.'))
    percent = models.DecimalField(max_digits=3, decimal_places=1, null=True,
                                  blank=True, help_text=(
        'A number between 0.0 and 99.9 to indicate a percentage of users for '
        'whom this flag will be active.'))
    testing = models.BooleanField(default=False, help_text=(
        'Allow this flag to be set for a session for user testing.'))
    superusers = models.BooleanField(default=True, help_text=(
        'Flag always active for superusers?'))
    staff = models.BooleanField(default=False, help_text=(
        'Flag always active for staff?'))
    authenticated = models.BooleanField(default=False, help_text=(
        'Flag always active for authenticate users?'))
    languages = models.TextField(blank=True, default='', help_text=(
        'Activate this flag for users with one of these languages (comma '
        'separated list)'))
    groups = models.ManyToManyField(Group, blank=True, help_text=(
        'Activate this flag for these user groups.'))
    users = models.ManyToManyField(AUTH_USER_MODEL, blank=True, help_text=(
        'Activate this flag for these users.'))
    rollout = models.BooleanField(default=False, help_text=(
        'Activate roll-out mode?'))
    note = models.TextField(blank=True, help_text=(
        'Note where this Flag is used.'))
    created = models.DateTimeField(default=datetime.now, db_index=True,
        help_text=('Date when this Flag was created.'))
    modified = models.DateTimeField(default=datetime.now, help_text=(
        'Date when this Flag was last modified.'))

    site = models.ForeignKey(Site, blank=True, null=True, related_name='waffle_flags')

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.modified = datetime.now()
        super(Flag, self).save(*args, **kwargs)

    class Meta:
        unique_together = ('name', 'site')

class Switch(models.Model):
    """A feature switch.

    Switches are active, or inactive, globally.

    """
    name = models.CharField(max_length=100,
                            help_text='The human/computer readable name.')
    active = models.BooleanField(default=False, help_text=(
        'Is this flag active?'))
    note = models.TextField(blank=True, help_text=(
        'Note where this Switch is used.'))
    created = models.DateTimeField(default=datetime.now, db_index=True,
        help_text=('Date when this Switch was created.'))
    modified = models.DateTimeField(default=datetime.now, help_text=(
        'Date when this Switch was last modified.'))

    site = models.ForeignKey(Site, blank=True, null=True, related_name='waffle_switches')

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.modified = datetime.now()
        super(Switch, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'Switches'
        unique_together = ('name', 'site')

class Sample(models.Model):
    """A sample is true some percentage of the time, but is not connected
    to users or requests.
    """
    name = models.CharField(max_length=100,
                            help_text='The human/computer readable name.')
    percent = models.DecimalField(max_digits=4, decimal_places=1, help_text=(
        'A number between 0.0 and 100.0 to indicate a percentage of the time '
        'this sample will be active.'))
    note = models.TextField(blank=True, help_text=(
        'Note where this Sample is used.'))
    created = models.DateTimeField(default=datetime.now, db_index=True,
        help_text=('Date when this Sample was created.'))
    modified = models.DateTimeField(default=datetime.now, help_text=(
        'Date when this Sample was last modified.'))

    site = models.ForeignKey(Site, blank=True, null=True, related_name='waffle_samples')

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.modified = datetime.now()
        super(Sample, self).save(*args, **kwargs)

    class Meta:
        unique_together = ('name', 'site')

def cache_flag(**kwargs):
    action = kwargs.get('action', None)
    # action is included for m2m_changed signal. Only cache on the post_*.
    if not action or action in ['post_add', 'post_remove', 'post_clear']:
        f = kwargs.get('instance')
        cache.add(keyfmt(get_setting('FLAG_CACHE_KEY'), f.name, f.site), f)
        cache.add(keyfmt(get_setting('FLAG_USERS_CACHE_KEY'), f.name, f.site),
                  f.users.all())
        cache.add(keyfmt(get_setting('FLAG_GROUPS_CACHE_KEY'), f.name, f.site),
                  f.groups.all())

def uncache_flag(**kwargs):
    flag = kwargs.get('instance')
    data = [
        keyfmt(get_setting('FLAG_CACHE_KEY'), flag.name, flag.site),
        keyfmt(get_setting('FLAG_USERS_CACHE_KEY'), flag.name, flag.site),
        keyfmt(get_setting('FLAG_GROUPS_CACHE_KEY'), flag.name, flag.site),
        keyfmt(get_setting('ALL_FLAGS_CACHE_KEY'))
    ]
    cache.delete_many(data)

post_save.connect(uncache_flag, sender=Flag, dispatch_uid='save_flag')
post_delete.connect(uncache_flag, sender=Flag, dispatch_uid='delete_flag')
m2m_changed.connect(uncache_flag, sender=Flag.users.through,
                    dispatch_uid='m2m_flag_users')
m2m_changed.connect(uncache_flag, sender=Flag.groups.through,
                    dispatch_uid='m2m_flag_groups')

def cache_sample(**kwargs):
    sample = kwargs.get('instance')
    cache.add(keyfmt(get_setting('SAMPLE_CACHE_KEY'), sample.name, sample.site), sample)

def uncache_sample(**kwargs):
    sample = kwargs.get('instance')
    cache.set(keyfmt(get_setting('SAMPLE_CACHE_KEY'), sample.name, sample.site), None, 5)
    cache.delete(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')))

post_save.connect(uncache_sample, sender=Sample, dispatch_uid='save_sample')
post_delete.connect(uncache_sample, sender=Sample,
                    dispatch_uid='delete_sample')

def cache_switch(**kwargs):
    switch = kwargs.get('instance')
    cache.add(keyfmt(get_setting('SWITCH_CACHE_KEY'), switch.name, switch.site), switch)

def uncache_switch(**kwargs):
    switch = kwargs.get('instance')
    cache.delete(keyfmt(get_setting('SWITCH_CACHE_KEY'), switch.name, switch.site))
    cache.delete(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')))

post_delete.connect(uncache_switch, sender=Switch,
                    dispatch_uid='delete_switch')
post_save.connect(uncache_switch, sender=Switch, dispatch_uid='save_switch')


text:
package hex.pca;

import hex.DataInfo;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import water.DKV;
import water.Key;
import water.TestUtil;
import water.fvec.Frame;
import water.util.FrameUtils;

import java.util.concurrent.TimeUnit;

import static hex.pca.JMHConfiguration.logLevel;
import static hex.pca.PCAModel.PCAParameters;
import static hex.pca.PCAModel.PCAParameters.Method.GramSVD;
import static water.TestUtil.parseTestFile;
import static water.TestUtil.stall_till_cloudsize;

/**
 * PCA benchmark micro-benchmark based on hex.pca.PCATest.testCatOnlyPUBDEV3988()
 * TODO migrate from PCATest!!!
 * - split train & score benchs
 * - create interface on top of it
 */
@Fork(1)
@Threads(1)
@State(Scope.Thread)
@Warmup(iterations = JMHConfiguration.WARM_UP_ITERATIONS)
@Measurement(iterations = JMHConfiguration.MEASUREMENT_ITERATIONS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Timeout(time = JMHConfiguration.TIMEOUT_MINUTES, timeUnit = TimeUnit.MINUTES)
public class PCACatOnlyPUBDEV3988Bench {

  @Param({"JAMA", "MTJ_SVD_DENSEMATRIX", "MTJ_EVD_DENSEMATRIX", "MTJ_EVD_SYMMMATRIX"})
  private PCAImplementation PCAImplementation;

  private PCAParameters paramsCatOnlyPUBDEV3988;
  private PCAModel pcaModel;
  private Frame trainingFrame;

  public static void main(String[] args) throws RunnerException {
    Options opt = new OptionsBuilder()
        .include(PCACatOnlyPUBDEV3988Bench.class.getSimpleName())
        .build();

    new Runner(opt).run();
  }

  @Setup(Level.Iteration)
  public void setup() {
    water.util.Log.setLogLevel(logLevel);
    stall_till_cloudsize(1);

    trainingFrame = null;
    double missing_fraction = 0.75;
    long seed = 12345;

    try {
      trainingFrame = parseTestFile(Key.make("arrests.hex"), "smalldata/pca_test/USArrests.csv");
      // Add missing values to the training data
      Frame frame = new Frame(Key.<Frame>make(), trainingFrame.names(), trainingFrame.vecs());
      DKV.put(frame._key, frame); // Need to put the frame (to be modified) into DKV for MissingInserter to pick up
      FrameUtils.MissingInserter j = new FrameUtils.MissingInserter(frame._key, seed, missing_fraction);
      j.execImpl().get(); // MissingInserter is non-blocking, must block here explicitly
      DKV.remove(frame._key); // Delete the frame header (not the data)

      paramsCatOnlyPUBDEV3988 = new PCAParameters();
      paramsCatOnlyPUBDEV3988._train = trainingFrame._key;
      paramsCatOnlyPUBDEV3988._k = 4;
      paramsCatOnlyPUBDEV3988._transform = DataInfo.TransformType.NONE;
      paramsCatOnlyPUBDEV3988._pca_method = GramSVD;
      paramsCatOnlyPUBDEV3988._pca_implementation = PCAImplementation;
      paramsCatOnlyPUBDEV3988._impute_missing = true;   // Don't skip rows with NA entries, but impute using mean of column
      paramsCatOnlyPUBDEV3988._seed = seed;

    } catch (RuntimeException e) {
      if (trainingFrame != null) {
        trainingFrame.delete();
      }
      throw e;
    }
  }

  @Setup(Level.Invocation)
  public void setupInvocation() {
    try {
      if (!train()) {                               // prepare the model for scoring
        throw new RuntimeException("PCA model failed to be trained.");
      }
    } catch (RuntimeException e) {
        if (trainingFrame != null) {
          trainingFrame.delete();
        }
      throw e;
    }
  }

  @Benchmark
  public boolean measureImputeMissingScoring() throws Exception {
    if (!score()) {
      throw new Exception("Model for PCAImputeMissing failed to be scored!");
    }
    return true;
  }

  @TearDown(Level.Iteration)
  public void tearDown() {
    if (trainingFrame != null) {
      trainingFrame.delete();
    }
  }

  @TearDown(Level.Invocation)
  public void tearDownInvocation() {
    if (pcaModel != null) {
      pcaModel.remove();
    }
  }

  private boolean train() {
    try {
      pcaModel = new PCA(paramsCatOnlyPUBDEV3988).trainModel().get();
    } catch (Exception exception) {
      return false;
    }
    return true;
  }

  private boolean score() {
    try {
      pcaModel.score(trainingFrame);
    } catch (Exception e) {
      return false;
    }
    return true;
  }

}


text:
package org.intellij.lang.annotations;

import org.jetbrains.annotations.NonNls;

import static java.lang.annotation.ElementType.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Specifies that an element of the program represents a string that is a regular expression text supported
 * by {@link java.util.regex.Pattern}.
 * Code editors may use this annotation to enable syntax highlighting, code completion and other features
 * inside the literals that assigned to the annotated variables, passed as arguments to the annotated parameters,
 * or returned from the annotated methods.
 *
 * @see Language
 */
@Retention(RetentionPolicy.CLASS)
@Target({METHOD, FIELD, PARAMETER, LOCAL_VARIABLE, ANNOTATION_TYPE})
@Language("RegExp")
public @interface RegExp {
    /**
     * A constant prefix that is assumed to be implicitly added before the regular expression.
     */
    @NonNls String prefix() default "";
    /**
     * A constant suffix that is assumed to be implicitly added after the regular expression.
     */
    @NonNls String suffix() default "";
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="50dd135c-7e61-4ec0-b775-4c4163eafe0c" name="Default" comment="">
      <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/favicon.ico" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/index.html" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/inline.bundle.js" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/inline.bundle.js.map" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/main.bundle.js" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/main.bundle.js.map" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/polyfills.bundle.js" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/polyfills.bundle.js.map" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/styles.bundle.js" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/styles.bundle.js.map" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/vendor.bundle.js" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/dist/vendor.bundle.js.map" beforeDir="false" />
      <change beforePath="$PROJECT_DIR$/package-lock.json" beforeDir="false" afterPath="$PROJECT_DIR$/package-lock.json" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/src/app/app.component.html" beforeDir="false" afterPath="$PROJECT_DIR$/src/app/app.component.html" afterDir="false" />
    </list>
    <ignored path="$PROJECT_DIR$/.tmp/" />
    <ignored path="$PROJECT_DIR$/temp/" />
    <ignored path="$PROJECT_DIR$/tmp/" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="FavoritesManager">
    <favorites_list name="bidmotion-email-signature" />
  </component>
  <component name="FileEditorManager">
    <leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
      <file pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/index.html">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="120">
              <caret line="8" column="52" selection-start-line="8" selection-start-column="51" selection-end-line="8" selection-end-column="52" />
            </state>
          </provider>
        </entry>
      </file>
      <file pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/src/app/app.component.html">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="196">
              <caret line="174" column="73" selection-start-line="174" selection-start-column="73" selection-end-line="174" selection-end-column="73" />
              <folding>
                <element signature="n#style#0;n#a#0;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#span#7;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#a#1;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#span#9;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#a#1;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#a#0;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#span#3;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
                <element signature="n#style#0;n#span#5;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/src/app/app.component.ts">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="269">
              <caret line="27" column="12" selection-start-line="27" selection-start-column="4" selection-end-line="27" selection-end-column="12" />
            </state>
          </provider>
        </entry>
      </file>
      <file pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/.angular-cli.json">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="195">
              <caret line="13" column="20" selection-start-line="13" selection-start-column="20" selection-end-line="13" selection-end-column="20" />
            </state>
          </provider>
        </entry>
      </file>
      <file pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/.gitignore">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="1035">
              <caret line="69" selection-start-line="69" selection-end-line="69" />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="FindInProjectRecents">
    <findStrings>
      <find>skypeURL</find>
      <find>form</find>
      <find>phone</find>
      <find>npmcdn</find>
      <find>_blank</find>
      <find>logoLink</find>
      <find>companyWebsite</find>
    </findStrings>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/src/app.ts" />
        <option value="$PROJECT_DIR$/.gitignore" />
        <option value="$PROJECT_DIR$/index.html" />
        <option value="$PROJECT_DIR$/src/app/app.component.html" />
      </list>
    </option>
  </component>
  <component name="ProjectFrameBounds" extendedState="6">
    <option name="y" value="23" />
    <option name="width" value="1280" />
    <option name="height" value="696" />
  </component>
  <component name="ProjectView">
    <navigator proportions="" version="1">
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="Scope" />
      <pane id="ProjectPane">
        <subPane>
          <expand>
            <path>
              <item name="bidmotion-email-signature" type="b2602c69:ProjectViewProjectNode" />
              <item name="bidmotion-email-signature" type="462c0819:PsiDirectoryNode" />
            </path>
            <path>
              <item name="bidmotion-email-signature" type="b2602c69:ProjectViewProjectNode" />
              <item name="bidmotion-email-signature" type="462c0819:PsiDirectoryNode" />
              <item name="src" type="462c0819:PsiDirectoryNode" />
            </path>
            <path>
              <item name="bidmotion-email-signature" type="b2602c69:ProjectViewProjectNode" />
              <item name="bidmotion-email-signature" type="462c0819:PsiDirectoryNode" />
              <item name="src" type="462c0819:PsiDirectoryNode" />
              <item name="app" type="462c0819:PsiDirectoryNode" />
            </path>
          </expand>
          <select />
        </subPane>
      </pane>
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="HbShouldOpenHtmlAsHb" value="" />
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="js-jscs-nodeInterpreter" value="/usr/local/bin/node" />
    <property name="js.eslint.eslintPackage" value="" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$" />
    <property name="nodejs_interpreter_path" value="/usr/local/bin/node" />
    <property name="ts.external.directory.path" value="$PROJECT_DIR$/node_modules/typescript/lib" />
  </component>
  <component name="RunDashboard">
    <option name="ruleStates">
      <list>
        <RuleState>
          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
          <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
      </list>
    </option>
  </component>
  <component name="RunManager">
    <configuration name="index.html" type="JavascriptDebugType" temporary="true" nameIsGenerated="true" uri="http://localhost:63342/bidmotion-email-signature/index.html">
      <method v="2" />
    </configuration>
    <configuration default="true" type="js.build_tools.gulp">
      <node-interpreter>project</node-interpreter>
      <node-options />
      <gulpfile />
      <tasks />
      <arguments />
      <envs />
      <method v="2" />
    </configuration>
    <recent_temporary>
      <list>
        <item itemvalue="JavaScript Debug.index.html" />
      </list>
    </recent_temporary>
  </component>
  <component name="SvnConfiguration">
    <configuration />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="50dd135c-7e61-4ec0-b775-4c4163eafe0c" name="Default" comment="" />
      <created>1485960332795</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1485960332795</updated>
      <workItem from="1485960334365" duration="3516000" />
      <workItem from="1485964375115" duration="1460000" />
      <workItem from="1491382378478" duration="4739000" />
      <workItem from="1557228406417" duration="1448000" />
    </task>
    <servers />
  </component>
  <component name="TimeTrackingManager">
    <option name="totallyTimeSpent" value="11163000" />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="23" width="1440" height="873" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info active="true" content_ui="combo" id="Project" order="0" sideWeight="0.49563047" visible="true" weight="0.118393235" />
      <window_info id="Structure" order="1" weight="0.2494043" />
      <window_info id="npm" order="2" side_tool="true" />
      <window_info id="Favorites" order="3" sideWeight="0.50436956" side_tool="true" weight="0.13526316" />
      <window_info anchor="bottom" id="Docker" show_stripe_button="false" />
      <window_info anchor="bottom" id="Message" order="0" />
      <window_info anchor="bottom" id="Find" order="1" weight="0.31011826" />
      <window_info anchor="bottom" id="Run" order="2" />
      <window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
      <window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
      <window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
      <window_info anchor="bottom" id="TODO" order="6" weight="0.32847896" />
      <window_info anchor="bottom" id="Event Log" order="7" sideWeight="0.50277996" side_tool="true" weight="0.32847896" />
      <window_info anchor="bottom" id="Terminal" order="8" weight="0.32781458" />
      <window_info anchor="bottom" id="Version Control" order="9" weight="0.32847896" />
      <window_info anchor="bottom" id="Floobits" order="10" sideWeight="0.49722" weight="0.32847896" />
      <window_info anchor="bottom" id="TypeScript" order="11" />
      <window_info anchor="right" id="Commander" order="0" weight="0.4" />
      <window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
      <window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
    </layout>
  </component>
  <component name="TypeScriptGeneratedFilesManager">
    <option name="version" value="1" />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/src/main.ts">
      <provider selected="true" editor-type-id="text-editor">
        <state>
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/config.js" />
    <entry file="file://$PROJECT_DIR$/src/app.ts" />
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="120">
          <caret line="8" column="52" selection-start-line="8" selection-start-column="51" selection-end-line="8" selection-end-column="52" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/.angular-cli.json">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="195">
          <caret line="13" column="20" selection-start-line="13" selection-start-column="20" selection-end-line="13" selection-end-column="20" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/.gitignore">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="1035">
          <caret line="69" selection-start-line="69" selection-end-line="69" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/app/app.component.ts">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="269">
          <caret line="27" column="12" selection-start-line="27" selection-start-column="4" selection-end-line="27" selection-end-column="12" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/app/app.component.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="196">
          <caret line="174" column="73" selection-start-line="174" selection-start-column="73" selection-end-line="174" selection-end-column="73" />
          <folding>
            <element signature="n#style#0;n#a#0;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#span#7;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#a#1;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#span#9;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#a#1;n#p#0;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#a#0;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#span#3;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
            <element signature="n#style#0;n#span#5;n#p#1;n#div#0;n#td#2;n#tr#0;n#tbody#0;n#table#0;n#div#14;n#form#0;n#div#0;n#div#0;n#div#0;n#!!top" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
[![Build Status](https://travis-ci.org/aaronwebb/aura-sql-debug.svg?branch=master)](https://travis-ci.org/aaronwebb/aura-sql-debug)

This library provides a decorated connection that logs profiles of PDO commands to a standard PSR-3 logger.

## Installation

Install the latest version with
```
require aaronwebb/aura-sql-debug
```

## Basic Usage

```
<?php
use Aura\Sql\ExtendedPdo;
use Aura\Sql\Profiler;
use Webb\Aura\Sql\ExtendedDebugPdo;

$logger = new Logger('database');
$logger->pushHandler(new ErrorLogHandler());

$pdo = new ExtendedDebugPdo(
  new ExtendedPdo(
    'mysql:host=localhost;dbname=test',
    'username',
    'password',
    array(), // driver options as key-value pairs
    array()  // attributes as key-value pairs
  ),
  $logger,
  new Profiler()
);
```


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
 */

Route::group(['middleware' => ['auth', 'minify']], function () {

    Route::get('/', 'DashboardController@index');
    Route::get('/timeline', 'DashboardController@timeline');

    Route::get('webhook/{projects}/refresh', 'WebhookController@refresh');

    Route::get('projects/{projects}', 'DeploymentController@project');

    Route::post('projects/{projects}/deploy', [
        'as'   => 'deploy',
        'uses' => 'DeploymentController@deploy',
    ]);

    // Deployment details
    Route::get('deployment/{deployments}', [
        'as'   => 'deployment',
        'uses' => 'DeploymentController@show',
    ]);

    Route::get('log/{log}', 'DeploymentController@log');

    // Resource management
    Route::group(['namespace' => 'Resources'], function () {

        Route::post('commands/reorder', 'CommandController@reorder');

        Route::get('projects/{projects}/commands/{step}', [
            'as'   => 'commands',
            'uses' => 'CommandController@listing',
        ]);

        Route::post('servers/reorder', 'ServerController@reorder');
        Route::get('servers/{servers}/test', 'ServerController@test');

        $actions = [
            'only' => ['store', 'update', 'destroy'],
        ];

        Route::resource('servers', 'ServerController', $actions);
        Route::resource('commands', 'CommandController', $actions);
        Route::resource('heartbeats', 'HeartbeatController', $actions);
        Route::resource('notifications', 'NotificationController', $actions);
        Route::resource('shared-files', 'SharedFilesController', $actions);
        Route::resource('project-file', 'ProjectFileController', $actions);
        Route::resource('notify-email', 'NotifyEmailController', $actions);
        Route::resource('check-url', 'CheckUrlController', $actions);

        Route::get('admin/templates/{projects}/commands/{step}', [
            'as'   => 'template.commands',
            'uses' => 'CommandController@listing',
        ]);
    });

    // Administration
    Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () {

        Route::resource('templates', 'TemplateController', [
            'only' => ['index', 'store', 'update', 'destroy', 'show'],
        ]);

        Route::resource('projects', 'ProjectController', [
            'only' => ['index', 'store', 'update', 'destroy'],
        ]);

        Route::resource('users', 'UserController', [
            'only' => ['index', 'store', 'update', 'destroy'],
        ]);

        Route::resource('groups', 'GroupController', [
            'only' => ['index', 'store', 'update'],
        ]);

    });

    // User profile managment

    Route::get('profile', [
        'as'   => 'profile.index',
        'uses' => 'ProfileController@index',
    ]);

    Route::post('profile/update', [
        'as'   => 'profile.update',
        'uses' => 'ProfileController@update',
    ]);

    Route::post('profile/email', [
        'as'   => 'profile.request_change_email',
        'uses' => 'ProfileController@requestEmail',
    ]);

    Route::post('profile/upload', [
        'as'   => 'profile.upload_avatar',
        'uses' => 'ProfileController@upload',
    ]);

    Route::post('profile/avatar', [
        'as'   => 'profile.avatar',
        'uses' => 'ProfileController@avatar',
    ]);

    Route::post('profile/gravatar', [
        'as'   => 'profile.gravatar',
        'uses' => 'ProfileController@gravatar',
    ]);
});

// Change the login email
Route::get('profile/email/{token}', 'ProfileController@email');
Route::post('profile/update-email', 'ProfileController@changeEmail');

// Webhooks
Route::post('deploy/{hash}', [
    'as'   => 'webhook',
    'uses' => 'WebhookController@webhook',
]);

Route::get('cctray.xml', 'DashboardController@cctray');

Route::group(['namespace' => 'Resources'], function () {
    Route::get('heartbeat/{hash}', [
        'as'   => 'heartbeat',
        'uses' => 'HeartbeatController@ping',
    ]);
});

Route::controllers([
    'auth'     => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);


text:
This is a PostgreSQL client, which uses [PostreSQL extension][sql-bricks-postgres]
of [sql-bricks][] as an interface to construct queries
and handles connections and transactions for you.

## Installation

```
npm install pg-bricks
```

## Usage

You can use `select`, `insert`, `update` and `delete` constructors of [sql-bricks][] and
construct your query by chaining their methods. You'll only need to finally call `.run()` or any data accessor to execute it:

```js
var db = require('pg-bricks').configure(process.env.DATABASE_URL);

// mind using db.sql to wrap now() function
db.update('user', {last_login: db.sql('now()')}).where('id', id).run(callback);

// db.sql contains various utilities to construct where conditions
db.delete('event').where(db.sql.lt('added', new Date('2005-01-01'))).run(...);

// .rows() access selected rows directly, not wrapped into result object
db.select().from('user').where('id', id).rows(callback);

// .row() will pass newly created user to a callback
db.insert('user', data).returning('*').row(callback);
```

As you can see, `db.sql` is a `sql-bricks` object, which you can use to escape raw sql
and construct where conditions. You can read about sql-bricks way of constructing
requests in [its documentation](http://csnw.github.io/sql-bricks) and
about PostgreSQL specific parts on [sql-bricks-postgres page][sql-bricks-postgres].

pg-bricks also exposes a reference to used [pg][] library via `db.pg`
in case you want to go low level.

Connections are handled automatically: a connection is withheld from a pool or created
for you when you need it and returned to the pool once you are done.
You can also manually get connection:

```js
db.run(function (client, callback) {
    // client is a node-postgres client object
    client.query("select * from user where id = $1", [id], callback);

    // it is however extended with sql-bricks query constructors
    client.select().from('user').where('id', id).run(callback);
});
```

You can also wrap your connection in a transaction:

```js
db.transaction(function (client, callback) {
    async.waterfall([
        // .run is a closure, so you can pass it to other function like this:
        client.insert('user', {name: 'Mike'}).returning('id').run,
        // res here is normal node-postgres result,
        // use .val accessor to get id directly
        function (res, callback) {
            var id = res.rows[0].id;
            client.insert('profile', {user_id: id, ...}).run(callback);
        },
    ], callback)
})
```

## Accessors

There are `.rows()`, `.row()`, `.col()` and `.val()` accessors on pg-bricks queries.
You can use them to extract corresponding part of result conveniently.
Also, `.row()` checks that result contains exactly one row and `.col()` checks that result
contains exactly one column. `.val()` does both:

```js
db.select('id,name').from('user').val(function (err) {
    // err is Error('Expected a single column, multiple found')
})
```

## Streaming

Query objects returned from `.query()` and `.run()` call emit `row`, `end` and `error` events.
This way you can process results without loading all of them into memory at once:

```js
var query = db.select('id,name').from('user').run();
query.on('row', ...)
query.on('end', ...)
query.on('error', ...)
```

It also provides stream-like piping. This way you can export to CSV:

```js
function (req, res) {
    var query = db.select('id,name').from('user').run();
    query.pipe(csv.stringify()).pipe(res);
}
```

## Debugging

`pg-bricks` uses [debug][] package, so you can use:

```bash
DEBUG=pg-bricks node your-app.js
```

to see all the queries on your screen.

## TODO:

- make queries with accessors capable of streaming?

[sql-bricks-postgres]: https://www.npmjs.org/package/sql-bricks-postgres
[sql-bricks]: https://www.npmjs.org/package/sql-bricks
[pg]: https://www.npmjs.org/package/pg
[debug]: https://www.npmjs.org/package/debug


text:
package org.uberfire.ext.widgets.common.client.common;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 *
 */
public abstract class Page {

    private final String label;
    private final PageView view;

    public Page(final IsWidget widget) {
        this(widget,
             "");
    }

    public Page(final IsWidget widget,
                final String label) {
        this.view = new PageView(this,
                                 widget);
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

    public abstract void onFocus();

    public abstract void onLostFocus();

    PageView getView() {
        return view;
    }

    public class PageView
            extends SimpleLayoutPanel
            implements RequiresResize {

        private final Page presenter;
        private final ScrollPanel sp = new ScrollPanel();

        public PageView(Page presenter,
                        IsWidget widget) {
            this.presenter = presenter;
            sp.setWidget(widget);
            setWidget(sp);
        }

        @Override
        public void onResize() {
            final Widget parent = getParent();
            if (parent != null) {
                final int width = parent.getOffsetWidth();
                final int height = parent.getOffsetHeight();
                sp.setPixelSize(width,
                                height);
            }
            super.onResize();
        }

        void onFocus() {
            presenter.onFocus();
        }

        public void onLostFocus() {
            presenter.onLostFocus();
        }

        public ScrollPanel getSp() {
            return sp;
        }
    }
}


text:
import { Database } from './../database';
import { Log } from './../log';
var _ = require("lodash");

export class PresenceChannel {
    /**
     * Database instance.
     */
    db: Database;

    /**
     * Create a new Presence channel instance.
     */
    constructor(private io, private options: any) {
        this.db = new Database(options);
    }

    /**
     * Get the members of a presence channel.
     */
    getMembers(channel: string): Promise<any> {
        return this.db.get(channel + ":members");
    }

    /**
     * Check if a user is on a presence channel.
     */
    isMember(channel: string, member: any): Promise<boolean> {
        return new Promise((resolve, reject) => {
            this.getMembers(channel).then(
                (members) => {
                    this.removeInactive(channel, members, member).then(
                        (members: any) => {
                            let search = members.filter(
                                (m) => m.user_id == member.user_id
                            );

                            if (search && search.length) {
                                resolve(true);
                            }

                            resolve(false);
                        }
                    );
                },
                (error) => Log.error(error)
            );
        });
    }

    /**
     * Remove inactive channel members from the presence channel.
     */
    removeInactive(channel: string, members: any[], member: any): Promise<any> {
        return new Promise((resolve, reject) => {
            this.io
                .of("/")
                .in(channel)
                .clients((error, clients) => {
                    members = members || [];
                    members = members.filter((member) => {
                        return clients.indexOf(member.socketId) >= 0;
                    });

                    this.db.set(channel + ":members", members);

                    resolve(members);
                });
        });
    }

    /**
     * Join a presence channel and emit that they have joined only if it is the
     * first instance of their presence.
     */
    join(socket: any, channel: string, member: any) {
        if (!member) {
            if (this.options.devMode) {
                Log.error(
                    "Unable to join channel. Member data for presence channel missing"
                );
            }

            return;
        }

        this.isMember(channel, member).then(
            (is_member) => {
                this.getMembers(channel).then(
                    (members) => {
                        members = members || [];
                        member.socketId = socket.id;
                        members.push(member);

                        this.db.set(channel + ":members", members);

                        members = _.uniqBy(members.reverse(), "user_id");

                        this.onSubscribed(socket, channel, members);

                        if (!is_member) {
                            this.onJoin(socket, channel, member);
                        }
                    },
                    (error) => Log.error(error)
                );
            },
            () => {
                Log.error("Error retrieving pressence channel members.");
            }
        );
    }

    /**
     * Remove a member from a presenece channel and broadcast they have left
     * only if not other presence channel instances exist.
     */
    leave(socket: any, channel: string): void {
        this.getMembers(channel).then(
            (members) => {
                members = members || [];
                let member = members.find(
                    (member) => member.socketId == socket.id
                );
                members = members.filter((m) => m.socketId != member.socketId);

                this.db.set(channel + ":members", members);

                this.isMember(channel, member).then((is_member) => {
                    if (!is_member) {
                        delete member.socketId;
                        this.onLeave(channel, member);
                    }
                });
            },
            (error) => Log.error(error)
        );
    }

    /**
     * On join event handler.
     */
    onJoin(socket: any, channel: string, member: any): void {
        this.io.sockets.connected[socket.id].broadcast
            .to(channel)
            .emit("presence:joining", channel, member);
    }

    /**
     * On leave emitter.
     */
    onLeave(channel: string, member: any): void {
        this.io.to(channel).emit("presence:leaving", channel, member);
    }

    /**
     * On subscribed event emitter.
     */
    onSubscribed(socket: any, channel: string, members: any[]) {
        this.io.to(socket.id).emit("presence:subscribed", channel, members);
    }
}


text:
package mil.nga.mapcache.preferences;

import android.content.Context;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import mil.nga.mapcache.R;

/**
 * Activity for the Preferences menu
 */
public class PreferencesActivity extends AppCompatActivity implements
        PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {

    /**
     * Create the activity and set to content_frame
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preferences);
        getSupportActionBar().setTitle("Settings");
        // Adds back arrow button to action bar
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new PreferencesFragment()).commit();
    }

    /**
     * Add back arrow button listener
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                NavUtils.navigateUpFromSameTask(this);
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onPreferenceStartFragment(PreferenceFragmentCompat preferenceFragmentCompat, Preference preference) {
        return false;
    }

    /**
     *  -------------------------------------------------------
     * Fragment to hold the preferences from xml/preferences.xml
     */
    public static class PreferencesFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {

        /**
         * Build from a preferences file instead of a layout
         * @param bundle
         * @param s
         */
        @Override
        public void onCreatePreferences(Bundle bundle, String s) {
            addPreferencesFromResource(R.xml.preferences);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.AppTheme);
            LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
            return super.onCreateView(localInflater, container, savedInstanceState);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {
            return false;
        }

    }

}


text:
.. _examples:
.. module:: marshmallow

********
Examples
********

The examples below will use `httpie <http://github.com/jkbr/httpie>`_ (a curl-like tool) for testing the APIs.

Text Analysis API (Bottle + TextBlob)
=====================================

Here is a very simple text analysis API using `Bottle <http://bottlepy.org>`_ and `TextBlob <http://textblob.readthedocs.io/>`_ that demonstrates how to declare an object serializer.

Assume that ``TextBlob`` objects have ``polarity``, ``subjectivity``, ``noun_phrase``, ``tags``, and ``words`` properties.

.. literalinclude:: ../examples/textblob_example.py
    :language: python

**Using The API**

First, run the app.

.. code-block:: bash

    $ python textblob_example.py

Then send a POST request with some text.

.. code-block:: bash

    $ http POST :5000/api/v1/analyze text="Simple is better"
    HTTP/1.0 200 OK
    Content-Length: 189
    Content-Type: application/json
    Date: Wed, 13 Nov 2013 08:58:40 GMT
    Server: WSGIServer/0.1 Python/2.7.5

    {
        "chunks": [
            "simple"
        ],
        "discrete_sentiment": "positive",
        "polarity": 0.25,
        "subjectivity": 0.4285714285714286,
        "tags": [
            [
                "Simple",
                "NN"
            ],
            [
                "is",
                "VBZ"
            ],
            [
                "better",
                "JJR"
            ]
        ],
        "word_count": 3
    }

Quotes API (Flask + SQLAlchemy)
================================

Below is a full example of a REST API for a quotes app using `Flask <http://flask.pocoo.org/>`_  and `SQLAlchemy <http://www.sqlalchemy.org/>`_  with marshmallow. It demonstrates a number of features, including:

    - Validation and deserialization using :meth:`Schema.load`.
    - Custom validation
    - Nesting fields
    - Using ``dump_only=True`` to specify read-only fields
    - Output filtering using the ``only`` parameter
    - Using `@pre_load <marshmallow.decorators.pre_load>` to preprocess input data.

.. literalinclude:: ../examples/flask_example.py
    :language: python

**Using The API**

Run the app.

.. code-block:: bash

    $ python flask_example.py

First we'll POST some quotes.

.. code-block:: bash

    $ http POST :5000/quotes/ author="Tim Peters" content="Beautiful is better than ugly."
    $ http POST :5000/quotes/ author="Tim Peters" content="Now is better than never."
    $ http POST :5000/quotes/ author="Peter Hintjens" content="Simplicity is always better than functionality."

If we provide invalid input data, we get 400 error response. Let's omit "author" from the input data.

.. code-block:: bash

    $ http POST :5000/quotes/ content="I have no author"
    {
        "author": [
            "Data not provided."
        ]
    }

Now we can GET a list of all the quotes.

.. code-block:: bash

    $ http :5000/quotes/
    {
        "quotes": [
            {
                "content": "Beautiful is better than ugly.",
                "id": 1
            },
            {
                "content": "Now is better than never.",
                "id": 2
            },
            {
                "content": "Simplicity is always better than functionality.",
                "id": 3
            }
        ]
    }

We can also GET the quotes for a single author.

.. code-block:: bash

    $ http :5000/authors/1
    {
        "author": {
            "first": "Tim",
            "formatted_name": "Peters, Tim",
            "id": 1,
            "last": "Peters"
        },
        "quotes": [
            {
                "content": "Beautiful is better than ugly.",
                "id": 1
            },
            {
                "content": "Now is better than never.",
                "id": 2
            }
        ]
    }

ToDo API (Flask + Peewee)
=========================

This example uses Flask and the `Peewee <http://peewee.readthedocs.io/en/latest/index.html>`_ ORM to create a basic Todo application.

Here, we use `Schema.load <marshmallow.Schema.load>` to validate and deserialize input data to model data. Also notice how `pre_load <marshmallow.decorators.pre_load>` is used to clean input data and `post_load <marshmallow.decorators.post_load>` is used to add an envelope to response data.

.. literalinclude:: ../examples/peewee_example.py
    :language: python

**Using the API**

After registering a user and creating some todo items in the database, here is an example response.

.. code-block:: bash

    $ http GET :5000/todos/
    {
        "todos": [
            {
                "content": "Install marshmallow",
                "done": false,
                "id": 1,
                "posted_on": "2015-05-05T01:51:12.832232+00:00",
                "user": {
                    "user": {
                        "email": "foo@bar.com",
                        "id": 1
                    }
                }
            },
            {
                "content": "Learn Python",
                "done": false,
                "id": 2,
                "posted_on": "2015-05-05T01:51:20.728052+00:00",
                "user": {
                    "user": {
                        "email": "foo@bar.com",
                        "id": 1
                    }
                }
            },
            {
                "content": "Refactor everything",
                "done": false,
                "id": 3,
                "posted_on": "2015-05-05T01:51:25.970153+00:00",
                "user": {
                    "user": {
                        "email": "foo@bar.com",
                        "id": 1
                    }
                }
            }
        ]
    }


text:
package com.amazonaws.services.sso.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.sso.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AccountInfoMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AccountInfoMarshaller {

    private static final MarshallingInfo<String> ACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("accountId").build();
    private static final MarshallingInfo<String> ACCOUNTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("accountName").build();
    private static final MarshallingInfo<String> EMAILADDRESS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("emailAddress").build();

    private static final AccountInfoMarshaller instance = new AccountInfoMarshaller();

    public static AccountInfoMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AccountInfo accountInfo, ProtocolMarshaller protocolMarshaller) {

        if (accountInfo == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(accountInfo.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(accountInfo.getAccountName(), ACCOUNTNAME_BINDING);
            protocolMarshaller.marshall(accountInfo.getEmailAddress(), EMAILADDRESS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}