text:
<?xml version="1.0" encoding="UTF-8"?>
<tns:loginConfiguration xmlns:tns="http://www.worklight.com/auth/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<!-- ***************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**************************************************************************** -->

	 <securityTests>
		<customSecurityTest name="AcmeairMobile-adapter-securityTest">
			<test isInternalUserID="true" realm="AcmeairMobileRealm" />
		</customSecurityTest>
	</securityTests>

	<realms>
		<realm name="WorklightConsole" loginModule="requireLogin">
			<className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
			<onLoginUrl>/console</onLoginUrl>
		</realm>

		<realm loginModule="AcmeairLoginModule" name="AcmeairMobileRealm">
			<className>com.worklight.integration.auth.AdapterAuthenticator</className>
			<parameter name="login-function" value="acmeairAdapter.onAuthRequired"/>
			<parameter name="logout-function" value="acmeairAdapter.onLogout"/>
		</realm>
	</realms>

	<loginModules>
		<loginModule name="requireLogin">
			<className>com.worklight.core.auth.ext.SingleIdentityLoginModule</className>
		</loginModule>

		<loginModule name="AcmeairLoginModule">
			<className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
		</loginModule>
	</loginModules>

</tns:loginConfiguration>


text:
package org.jboss.example.homeloan.clients;

import org.switchyard.component.test.mixins.http.HTTPMixIn;

public class PreQualSOAPClient {

	private static final String URL = "http://localhost:8080/homeloan/IntakeService";
    private static final String SUFFIX = "-soap.xml";
    private static final String PREFIX = "src/test/resources/";

    public static void main(final String[] args) throws Exception {

        HTTPMixIn soapMixIn = new HTTPMixIn();
        soapMixIn.initialize();

        String request = PREFIX + "Tina" + SUFFIX;
        if (args.length == 1) {
        	request = PREFIX + args[0] + SUFFIX;
        }

        try {
        	soapMixIn.setDumpMessages(true);
            soapMixIn.postFile(URL, request);
        } finally {
            soapMixIn.uninitialize();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _static_h
#define _static_h
#define DB_FILE "/tmp/bdhcpd-static.db"
/* stored for each mac in the db file */
struct lease {
	struct in_addr ip;
	struct in_addr subnet;
	struct in_addr dns[DNS_COUNT];
	struct in_addr gw;
	struct in_addr broadcast;
	u32 lease_time;
} __packed;
#endif


text:
import numpy as np
from scipy.interpolate import interp1d, RectBivariateSpline, UnivariateSpline
from delight.utils import approx_DL
# from specutils import extinction
from astropy import units as u

class PhotometricFilter:
    """Photometric filter response"""
    def __init__(self, bandName, tabulatedWavelength, tabulatedResponse):
        self.bandName = bandName
        self.wavelengthGrid = tabulatedWavelength
        self.tabulatedResponse = tabulatedResponse
        self.interp = interp1d(tabulatedWavelength, tabulatedResponse)
        self.norm = np.trapz(tabulatedResponse/tabulatedWavelength,
                             x=tabulatedWavelength)
        ind = np.where(
            tabulatedResponse > 0.001*np.max(tabulatedResponse)
                            )[0]
        self.lambdaMin = tabulatedWavelength[ind[0]]
        self.lambdaMax = tabulatedWavelength[ind[-1]]

    def __call__(self, wavelength):
        return self.interp(wavelength)

# class DustModel:
#     """
#     Extinction model from Cardelli, Clayton & Mathis (1988)
#     """
#     def __init__(self):
#         self.r_v = 3.1
#
#     def __call__(self, wave, a_v):
#         return extinction.extinction_d03(wave * u.Angstrom,
#                                          a_v, r_v=self.r_v)
#
#
# class SpectralTemplate_zd:
#     """
#     SED template, tabulated, to be interpolated  on aredshift and dust grid
#     """
#     def __init__(self,
#                  tabulatedWavelength, tabulatedSpectrum, photometricBands,
#                  redshiftGrid=None, dustGrid=None):
#         self.DL = approx_DL()
#         self.DustModel = DustModel()
#         self.photometricBands = photometricBands
#         self.numBands = len(photometricBands)
#         self.fbinterps = {}
#         self.sed_interp = interp1d(tabulatedWavelength, tabulatedSpectrum)
#         if redshiftGrid is None:
#             self.redshiftGrid = np.logspace(np.log10(1e-2),
#                                             np.log10(2.0),
#                                             50)
#         else:
#             self.redshiftGrid = redshiftGrid
#         if dustGrid is None:
#             self.dustGrid = np.logspace(np.log10(1e-2),
#                                         np.log10(100),
#                                         15)
#         else:
#             self.dustGrid = dustGrid
#
#         for filt in photometricBands:
#             fmodgrid = np.zeros((self.redshiftGrid.size, self.dustGrid.size))
#             for iz in range(self.redshiftGrid.size):
#                 opz = (self.redshiftGrid[iz] + 1)
#                 xf_z = filt.wavelengthGrid / opz
#                 yf_z = filt.tabulatedResponse
#                 ysed = self.sed_interp(xf_z)
#                 facz = opz**2. / (4*np.pi*self.DL(self.redshiftGrid[iz])**2.)
#                 for jd in range(self.dustGrid.size):
#                     ysedext = facz * ysed *\
#                         10**-0.4*self.DustModel(xf_z, self.dustGrid[jd])
#                     fmodgrid[iz, jd] =\
#                         np.trapz(ysedext * yf_z, x=xf_z) / filt.norm
#             self.fbinterps[filt.bandName] = RectBivariateSpline(
#                 self.redshiftGrid, self.dustGrid, fmodgrid)
#
#     def photometricFlux(self, redshifts, dusts, bandName, grid=False):
#         return self.fbinterps[bandName](redshifts, dusts, grid=grid).T
#
#     def flux(self, redshift, dust, wave):
#         opz = 1. + redshift
#         xf_z = wave / opz
#         facz = opz**2. / (4*np.pi*self.DL(redshift)**2.)
#         ysed = self.sed_interp(xf_z)
#         ysedext = facz * ysed *\
#             10**-0.4*self.DustModel(xf_z, dust)
#         return ysedext

class SpectralTemplate_z:
    """
    SED template, tabulated and to be interpolated  on a redshift grid
    """
    def __init__(self,
                 tabulatedWavelength, tabulatedSpectrum, photometricBands,
                 redshiftGrid=None, order=15):
        self.DL = approx_DL()
        self.photometricBands = photometricBands
        self.numBands = len(photometricBands)
        self.sed_interp = interp1d(tabulatedWavelength, tabulatedSpectrum,
                                   bounds_error=False,
                                   fill_value="extrapolate")
        if redshiftGrid is None:
            self.redshiftGrid = np.logspace(np.log10(1e-2),
                                            np.log10(2.0),
                                            350)
        else:
            self.redshiftGrid = redshiftGrid

        self.fbcoefs = {}
        self.fbinterps = {}
        self.logfbinterps = {}
        self.order = order
        self.fmodgrid = np.zeros((self.redshiftGrid.size,
                                  len(photometricBands)))
        self.bandNames = []
        for ib, filt in enumerate(photometricBands):
            self.bandNames.append(filt.bandName)
            for iz in range(self.redshiftGrid.size):
                opz = (self.redshiftGrid[iz] + 1)
                xf_z = filt.wavelengthGrid / opz
                yf_z = filt.tabulatedResponse
                ysed = self.sed_interp(xf_z)
                facz = opz**2. / (4*np.pi*self.DL(self.redshiftGrid[iz])**2.)
                ysedext = facz * ysed
                self.fmodgrid[iz, ib] =\
                    np.trapz(ysedext * yf_z, x=xf_z) / filt.norm
            self.fbinterps[filt.bandName] = UnivariateSpline(
                self.redshiftGrid, self.fmodgrid[:, ib], s=0)
            self.fbcoefs[filt.bandName] = np.polyfit(
                self.redshiftGrid, np.log(self.fmodgrid[:, ib]), self.order-1)
            self.logfbinterps[filt.bandName] =\
                np.poly1d(self.fbcoefs[filt.bandName])

    def photometricFlux_spline(self, redshifts, bandName):
        return self.fbinterps[bandName](redshifts)

    def photometricFlux(self, redshifts, bandName):
        return np.exp(self.logfbinterps[bandName](redshifts))

    def photometricFlux_bis(self, redshifts, bandName):
        xgg = redshifts[:, None] ** np.arange(self.order-1, -1, -1)[None, :]
        return np.exp(np.sum(xgg * self.fbcoefs[bandName][None, :], axis=1))

    def photometricFlux_gradz(self, redshifts, bandName):
        mod_der = np.poly1d(np.polyder(self.fbcoefs[bandName]))
        return mod_der(redshifts) * self.photometricFlux(redshifts, bandName)

    def photometricFlux_gradz_bis(self, redshifts, bandName):
        xgg = redshifts[:, None] ** np.arange(self.order-2, -1, -1)[None, :]
        der = np.arange(self.order-1, 0, -1)
        flux = self.photometricFlux_bis(redshifts, bandName)
        return np.sum(xgg * der * self.fbcoefs[bandName][None, :-1],
                      axis=1) * flux

    def flux(self, redshift, wave):
        opz = 1. + redshift
        xf_z = wave / opz
        facz = opz**2. / (4*np.pi*self.DL(redshift)**2.)
        ysed = self.sed_interp(xf_z)
        ysedext = facz * ysed
        return ysedext


text:
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.httpd.rpc.patch;

import com.google.gerrit.common.data.ReviewerResult;
import com.google.gerrit.common.data.ApprovalSummary;
import com.google.gerrit.common.data.ApprovalSummarySet;
import com.google.gerrit.common.data.ApprovalTypes;
import com.google.gerrit.common.data.PatchDetailService;
import com.google.gerrit.common.data.PatchScript;
import com.google.gerrit.common.errors.NoSuchEntityException;
import com.google.gerrit.httpd.rpc.BaseServiceImplementation;
import com.google.gerrit.httpd.rpc.Handler;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.AccountDiffPreference;
import com.google.gerrit.reviewdb.AccountPatchReview;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.Patch;
import com.google.gerrit.reviewdb.PatchLineComment;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gerrit.reviewdb.PatchSetApproval;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.reviewdb.Patch.Key;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.account.AccountInfoCacheFactory;
import com.google.gerrit.server.patch.PublishComments;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.workflow.FunctionState;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwtjsonrpc.client.VoidResult;
import com.google.gwtorm.client.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

class PatchDetailServiceImpl extends BaseServiceImplementation implements
    PatchDetailService {
  private final ApprovalTypes approvalTypes;

  private final AccountInfoCacheFactory.Factory accountInfoCacheFactory;
  private final AddReviewerHandler.Factory addReviewerHandlerFactory;
  private final ChangeControl.Factory changeControlFactory;
  private final RemoveReviewerHandler.Factory removeReviewerHandlerFactory;
  private final FunctionState.Factory functionStateFactory;
  private final PublishComments.Factory publishCommentsFactory;
  private final PatchScriptFactory.Factory patchScriptFactoryFactory;
  private final SaveDraft.Factory saveDraftFactory;

  @Inject
  PatchDetailServiceImpl(final Provider<ReviewDb> schema,
      final Provider<CurrentUser> currentUser,
      final ApprovalTypes approvalTypes,
      final AccountInfoCacheFactory.Factory accountInfoCacheFactory,
      final AddReviewerHandler.Factory addReviewerHandlerFactory,
      final RemoveReviewerHandler.Factory removeReviewerHandlerFactory,
      final ChangeControl.Factory changeControlFactory,
      final FunctionState.Factory functionStateFactory,
      final PatchScriptFactory.Factory patchScriptFactoryFactory,
      final PublishComments.Factory publishCommentsFactory,
      final SaveDraft.Factory saveDraftFactory) {
    super(schema, currentUser);
    this.approvalTypes = approvalTypes;

    this.accountInfoCacheFactory = accountInfoCacheFactory;
    this.addReviewerHandlerFactory = addReviewerHandlerFactory;
    this.removeReviewerHandlerFactory = removeReviewerHandlerFactory;
    this.changeControlFactory = changeControlFactory;
    this.functionStateFactory = functionStateFactory;
    this.patchScriptFactoryFactory = patchScriptFactoryFactory;
    this.publishCommentsFactory = publishCommentsFactory;
    this.saveDraftFactory = saveDraftFactory;
  }

  public void patchScript(final Patch.Key patchKey, final PatchSet.Id psa,
      final PatchSet.Id psb, final AccountDiffPreference dp,
      final AsyncCallback<PatchScript> callback) {
    if (psb == null) {
      callback.onFailure(new NoSuchEntityException());
      return;
    }
    patchScriptFactoryFactory.create(patchKey, psa, psb, dp).to(callback);
  }

  public void saveDraft(final PatchLineComment comment,
      final AsyncCallback<PatchLineComment> callback) {
    saveDraftFactory.create(comment).to(callback);
  }

  public void deleteDraft(final PatchLineComment.Key commentKey,
      final AsyncCallback<VoidResult> callback) {
    run(callback, new Action<VoidResult>() {
      public VoidResult run(ReviewDb db) throws OrmException, Failure {
        final PatchLineComment comment = db.patchComments().get(commentKey);
        if (comment == null) {
          throw new Failure(new NoSuchEntityException());
        }
        if (!getAccountId().equals(comment.getAuthor())) {
          throw new Failure(new NoSuchEntityException());
        }
        if (comment.getStatus() != PatchLineComment.Status.DRAFT) {
          throw new Failure(new IllegalStateException("Comment published"));
        }
        db.patchComments().delete(Collections.singleton(comment));
        return VoidResult.INSTANCE;
      }
    });
  }

  public void publishComments(final PatchSet.Id psid, final String msg,
      final Set<ApprovalCategoryValue.Id> tags,
      final AsyncCallback<VoidResult> cb) {
    Handler.wrap(publishCommentsFactory.create(psid, msg, tags)).to(cb);
  }

  /**
   * Update the reviewed status for the file by user @code{account}
   */
  public void setReviewedByCurrentUser(final Key patchKey,
      final boolean reviewed, AsyncCallback<VoidResult> callback) {
    run(callback, new Action<VoidResult>() {
      public VoidResult run(ReviewDb db) throws OrmException {
        Account.Id account = getAccountId();
        AccountPatchReview.Key key =
            new AccountPatchReview.Key(patchKey, account);
        AccountPatchReview apr = db.accountPatchReviews().get(key);
        if (apr == null && reviewed) {
          db.accountPatchReviews().insert(
              Collections.singleton(new AccountPatchReview(patchKey, account)));
        } else if (apr != null && !reviewed) {
          db.accountPatchReviews().delete(Collections.singleton(apr));
        }
        return VoidResult.INSTANCE;
      }
    });
  }

  public void addReviewers(final Change.Id id, final List<String> reviewers,
      final boolean confirmed, final AsyncCallback<ReviewerResult> callback) {
    addReviewerHandlerFactory.create(id, reviewers, confirmed).to(callback);
  }

  public void removeReviewer(final Change.Id id, final Account.Id reviewerId,
      final AsyncCallback<ReviewerResult> callback) {
    removeReviewerHandlerFactory.create(id, reviewerId).to(callback);
  }

  public void userApprovals(final Set<Change.Id> cids, final Account.Id aid,
      final AsyncCallback<ApprovalSummarySet> callback) {
    run(callback, new Action<ApprovalSummarySet>() {
      public ApprovalSummarySet run(ReviewDb db) throws OrmException {
        final Map<Change.Id, ApprovalSummary> approvals =
            new HashMap<Change.Id, ApprovalSummary>();
        final AccountInfoCacheFactory aicFactory =
            accountInfoCacheFactory.create();

        aicFactory.want(aid);
        for (final Change.Id id : cids) {
          try {
            final ChangeControl cc = changeControlFactory.validateFor(id);
            final Change change = cc.getChange();
            final PatchSet.Id ps_id = change.currentPatchSetId();
            final Map<ApprovalCategory.Id, PatchSetApproval> psas =
                new HashMap<ApprovalCategory.Id, PatchSetApproval>();
            final FunctionState fs =
                functionStateFactory.create(cc, ps_id, psas.values());

            for (final PatchSetApproval ca : db.patchSetApprovals()
                .byPatchSetUser(ps_id, aid)) {
              final ApprovalCategory.Id category = ca.getCategoryId();
              if (ApprovalCategory.SUBMIT.equals(category)) {
                continue;
              }
              if (change.getStatus().isOpen()) {
                fs.normalize(approvalTypes.byId(category), ca);
              }
              if (ca.getValue() == 0) {
                continue;
              }
              psas.put(category, ca);
            }

            approvals.put(id, new ApprovalSummary(psas.values()));
          } catch (NoSuchChangeException nsce) {
            /*
             * The user has no access to see this change, so we simply do not
             * provide any details about it.
             */
          }
        }
        return new ApprovalSummarySet(aicFactory.create(), approvals);
      }
    });
  }

  public void strongestApprovals(final Set<Change.Id> cids,
      final AsyncCallback<ApprovalSummarySet> callback) {
    run(callback, new Action<ApprovalSummarySet>() {
      public ApprovalSummarySet run(ReviewDb db) throws OrmException {
        final Map<Change.Id, ApprovalSummary> approvals =
            new HashMap<Change.Id, ApprovalSummary>();
        final AccountInfoCacheFactory aicFactory =
            accountInfoCacheFactory.create();

        for (final Change.Id id : cids) {
          try {
            final ChangeControl cc = changeControlFactory.validateFor(id);
            final Change change = cc.getChange();
            final PatchSet.Id ps_id = change.currentPatchSetId();
            final Map<ApprovalCategory.Id, PatchSetApproval> psas =
                new HashMap<ApprovalCategory.Id, PatchSetApproval>();
            final FunctionState fs =
                functionStateFactory.create(cc, ps_id, psas.values());

            for (PatchSetApproval ca : db.patchSetApprovals().byPatchSet(ps_id)) {
              final ApprovalCategory.Id category = ca.getCategoryId();
              if (ApprovalCategory.SUBMIT.equals(category)) {
                continue;
              }
              if (change.getStatus().isOpen()) {
                fs.normalize(approvalTypes.byId(category), ca);
              }
              if (ca.getValue() == 0) {
                continue;
              }
              boolean keep = true;
              if (psas.containsKey(category)) {
                final short oldValue = psas.get(category).getValue();
                final short newValue = ca.getValue();
                keep =
                    (Math.abs(oldValue) < Math.abs(newValue))
                        || ((Math.abs(oldValue) == Math.abs(newValue) && (newValue < oldValue)));
              }
              if (keep) {
                aicFactory.want(ca.getAccountId());
                psas.put(category, ca);
              }
            }

            approvals.put(id, new ApprovalSummary(psas.values()));
          } catch (NoSuchChangeException nsce) {
            /*
             * The user has no access to see this change, so we simply do not
             * provide any details about it.
             */
          }
        }

        return new ApprovalSummarySet(aicFactory.create(), approvals);
      }
    });
  }
}


text:
// ****************************************************************
// Copyright 2011, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************

using System;

namespace NUnit.ProjectEditor
{
    public delegate void ActionDelegate();

    public delegate void CommandDelegate();

    public delegate bool ActionStartingDelegate();
}


text:
process.chdir(__dirname);
require('should');

var gulp = require('gulp');
var watch = require('../lib/gulp-blueprint-watch');
var sinon = require('sinon');
var build = sinon.spy();

gulp.task('build', build);
watch({
  dependencies: ['build'],
  start: 'build'
});

describe('when running the watch task', function(){

  it('should complete without an error', function(){
    gulp.start('watch');
  });

  it('should have called build() exactly once', function(){
    build.calledOnce.should.be.exactly(true);
  });

});


text:
namespace cognon {

void AddSample(double v, Statistic* stat) {
  CHECK((!stat->has_count() && stat->values_size() == 0) ||
        (stat->has_count() &&
         (stat->values_size() == 0 || stat->count() == stat->values_size())));
  CHECK(!stat->has_count()
        || stat->count() == 0
        || (0 < stat->count() && stat->has_sum() && stat->has_ssum()));

  if (!stat->has_count()
      || stat->count() == 0
      || (stat->count() == stat->values_size()))
    stat->add_values(v);

  stat->set_count(stat->count() + 1);
  stat->set_sum(stat->sum() + v);
  stat->set_ssum(stat->ssum() + v * v);
}

double Mean(const Statistic& stat) {
  CHECK((!stat.has_count() && stat.values_size() == 0) ||
        (stat.has_count() &&
         (stat.values_size() == 0 || stat.count() == stat.values_size())));
  CHECK(!stat.has_count()
        || stat.count() == 0
        || (0 < stat.count() && stat.has_sum() && stat.has_ssum()));

  if (stat.has_count() && stat.has_sum() && 0 < stat.count())
    return stat.sum() / static_cast<double>(stat.count());
  return -1.0;
}

double Stddev(const Statistic& stat) {
  CHECK((!stat.has_count() && stat.values_size() == 0) ||
        (stat.has_count() &&
         (stat.values_size() == 0 || stat.count() == stat.values_size())));
  CHECK(!stat.has_count()
        || stat.count() == 0
        || (0 < stat.count() && stat.has_sum() && stat.has_ssum()));

  if (stat.has_count() && 1 < stat.count()
      && stat.has_sum() && stat.has_ssum()) {
    double v = stat.count() * stat.ssum() - stat.sum() * stat.sum();
    v /= static_cast<double>(stat.count() * (stat.count() - 1));
    return (0.0 <= v ? sqrt(v) : 0.0);
  }
  return -1.0;
}

Statistic operator+(const Statistic& a, const Statistic& b) {
  Statistic result(a);
  result += b;
  return result;
}

Statistic& operator+=(Statistic& a, const Statistic& b) {
  CHECK((!a.has_count() && a.values_size() == 0) ||
        (a.has_count() &&
         (a.values_size() == 0 || a.count() == a.values_size())));
  CHECK((!b.has_count() && b.values_size() == 0) ||
        (b.has_count() &&
         (b.values_size() == 0 || b.count() == b.values_size())));
  CHECK(!a.has_count()
        || a.count() == 0
        || (0 < a.count() && a.has_sum() && a.has_ssum()));
  CHECK(!b.has_count()
        || b.count() == 0
        || (0 < b.count() && b.has_sum() && b.has_ssum()));

  if (a.has_count() && 0 < a.count()
      && b.has_count() && 0 < b.count()
      && (a.count() != a.values_size() || b.count() != b.values_size())) {
    // Only one of a and b has values(), so result may not have values()
    a.clear_values();
  } else {
    for (int i = 0; i < b.values_size(); ++i) {
      a.add_values(b.values(i));
    }
  }

#define PB_OPERATOR_PLUS(param) \
  if (a.has_##param() && b.has_##param()) { \
    a.set_##param(a.param() + b.param()); \
  } else if (b.has_##param()) { \
    a.set_##param(b.param()); \
  }
  PB_OPERATOR_PLUS(count);
  PB_OPERATOR_PLUS(sum);
  PB_OPERATOR_PLUS(ssum);
#undef PB_OPERATOR_PLUS
  return a;
}

void AddSample(int32 bucket, double v, Histogram* hist) {
  // Add empty buckets, if necessary
  for (int32 i = hist->values_size(); i <= bucket; ++i) {
    hist->add_values();
  }
  AddSample(v, hist->mutable_values(bucket));
}

void SetHistogram(const vector<int32>& data, Histogram* result) {
  for (int32 i = data.size() - 1; 0 <= i; --i) {
    AddSample(i, static_cast<double>(data[i]), result);
  }
}

Histogram operator+(const Histogram& a, const Histogram& b) {
  Histogram result(a);
  result += b;
  return result;
}

Histogram& operator+=(Histogram& a, const Histogram& b) {
  int32 i;
  int32 a_count = (a.values_size() > 0 ? a.values(0).count() : 0);
  int32 b_count = (b.values_size() > 0 ? b.values(0).count() : 0);

  for (i = 0; i < b.values_size(); ++i) {
    if (i < a.values_size()) {
      *a.mutable_values(i) += b.values(i);
    } else {
      Statistic* s = a.add_values();
      for (int32 j = 0; j < a_count; ++j) {
        AddSample(0.0, s);
      }
      *a.mutable_values(i) += b.values(i);
    }
  }
  for (; i < a.values_size(); ++i) {
    for (int32 j = 0; j < b_count; ++j) {
      AddSample(0.0, a.mutable_values(i));
    }
  }
  return a;
}

NeuronStatistics operator+(const NeuronStatistics& a,
                           const NeuronStatistics& b) {
  NeuronStatistics result(a);
  result += b;
  return result;
}

NeuronStatistics& operator+=(NeuronStatistics& a,
                            const NeuronStatistics& b) {
#define PB_OPERATOR_PLUS(param) \
  if (a.has_##param() && b.has_##param()) { \
    *a.mutable_##param() += b.param();  \
  } else if (b.has_##param()) { \
    a.mutable_##param()->CopyFrom(b.param());      \
  }
  PB_OPERATOR_PLUS(false_false);
  PB_OPERATOR_PLUS(false_true);
  PB_OPERATOR_PLUS(false_count);
  PB_OPERATOR_PLUS(true_false);
  PB_OPERATOR_PLUS(true_true);
  PB_OPERATOR_PLUS(true_count);
  PB_OPERATOR_PLUS(q_after);
  PB_OPERATOR_PLUS(synapses_per_neuron);
  PB_OPERATOR_PLUS(bits_per_neuron);
  PB_OPERATOR_PLUS(bits_per_neuron_per_refractory_period);
  PB_OPERATOR_PLUS(mutual_information);
  PB_OPERATOR_PLUS(d_effective);
  PB_OPERATOR_PLUS(delay_histogram);
  PB_OPERATOR_PLUS(input_delay_histogram);
  PB_OPERATOR_PLUS(input_max_sum_delay_histogram);
  PB_OPERATOR_PLUS(h_histogram);
  PB_OPERATOR_PLUS(word_delay_histogram);
  PB_OPERATOR_PLUS(synapse_before_delay_histogram);
  PB_OPERATOR_PLUS(synapse_after_delay_histogram);
#undef PB_OPERATOR_PLUS

  return a;
}

void StatisticStripValues(Statistic* stat) {
  stat->clear_values();
}

void HistogramStripValues(Histogram* hist) {
  for (int32 i = 0; i < hist->values_size(); ++i) {
    StatisticStripValues(hist->mutable_values(i));
  }
}

void NeuronStatisticsStripValues(NeuronStatistics* stats) {
  StatisticStripValues(stats->mutable_false_false());
  StatisticStripValues(stats->mutable_false_true());
  StatisticStripValues(stats->mutable_false_count());
  StatisticStripValues(stats->mutable_true_false());
  StatisticStripValues(stats->mutable_true_true());
  StatisticStripValues(stats->mutable_true_count());
  StatisticStripValues(stats->mutable_q_after());
  StatisticStripValues(stats->mutable_synapses_per_neuron());
  StatisticStripValues(stats->mutable_bits_per_neuron());
  StatisticStripValues(stats->mutable_bits_per_neuron_per_refractory_period());
  StatisticStripValues(stats->mutable_mutual_information());
  StatisticStripValues(stats->mutable_d_effective());
  HistogramStripValues(stats->mutable_delay_histogram());
  HistogramStripValues(stats->mutable_input_delay_histogram());
  HistogramStripValues(stats->mutable_input_max_sum_delay_histogram());
  HistogramStripValues(stats->mutable_h_histogram());
  HistogramStripValues(stats->mutable_word_delay_histogram());
  HistogramStripValues(stats->mutable_synapse_before_delay_histogram());
  HistogramStripValues(stats->mutable_synapse_after_delay_histogram());
}

// Return "true" if a is "less" than b.
bool operator<(const TrainConfig&a, const TrainConfig& b) {
  const NeuronConfig& neuron_a = a.config();
  const NeuronConfig& neuron_b = b.config();

#define VALUE_COMPARE(a, b, v)                       \
  if (!a.has_##v() && b.has_##v()) return true;      \
  if (a.has_##v() && !b.has_##v()) return false;     \
  if (a.has_##v() && b.has_##v()) {                  \
    if (a.v() < b.v()) return true;                  \
    if (a.v() > b.v()) return false;                 \
  }

  VALUE_COMPARE(neuron_a, neuron_b, c);
  VALUE_COMPARE(neuron_a, neuron_b, d1);
  VALUE_COMPARE(neuron_a, neuron_b, d2);
  VALUE_COMPARE(neuron_a, neuron_b, h);
  VALUE_COMPARE(neuron_a, neuron_b, q);
  VALUE_COMPARE(neuron_a, neuron_b, r);
  VALUE_COMPARE(neuron_a, neuron_b, g_m);
  VALUE_COMPARE(neuron_a, neuron_b, h_m);

  VALUE_COMPARE(a, b, w);
  VALUE_COMPARE(a, b, num_active);
  VALUE_COMPARE(a, b, num_test_words);
#undef VALUE_COMPARE

  return false;
}

static double HistogramEntropy(const vector<int32>& hist) {
  // First calculate the entropy of the delay histogram
  double sum = 0.0;
  for (int32 i = 0; i < hist.size(); ++i) {
    sum += hist[i];
  }
  if (sum == 0.0) return 0.0;

  double entropy = 0.0;
  for (int32 i = 0; i < hist.size(); ++i) {
    if (0 < hist[i]) {
      double prob = hist[i] / sum;
      entropy -= prob * log(prob) / log(2.0);
    }
  }
  return pow(2.0, entropy);
}

void RunExperiment(const TrainConfig& config, NeuronStatistics* result) {
  Wordset words;
  Neuron neuron;

  // Must have either both or neither of g_m() and h_m()
  CHECK((config.config().has_g_m() && config.config().has_h_m())
        || (!config.config().has_g_m() && !config.config().has_h_m()));

  result->Clear();
  result->mutable_config()->CopyFrom(config);

  neuron.Init(config.config());
  if (config.has_num_active()) {
    words.ConfigFixed(config.w(), neuron.length(),
                      config.config().d1(), config.num_active());
  } else {
    words.Config(config.w(), neuron.length(),
                 config.config().d1(), config.config().r());
  }

  vector<int32> synapse_before_delay_histogram;
  neuron.GetSynapseDelayHistogram(&synapse_before_delay_histogram);

  Alice alice;
  vector<int32> delay_histogram;
  vector<int32> input_delay_histogram;
  vector<int32> input_max_sum_delay_histogram;
  vector<int32> H_histogram;
  alice.TrainHistogram(&words, &neuron,
                       &delay_histogram, &input_delay_histogram,
                       &input_max_sum_delay_histogram, &H_histogram);

  vector<int32> synapse_after_delay_histogram;
  neuron.GetSynapseDelayHistogram(&synapse_after_delay_histogram);

  // Collect various training-related statistics
  vector<int32> word_delay_histogram;
  SetHistogram(delay_histogram,
               result->mutable_delay_histogram());
  SetHistogram(input_delay_histogram,
               result->mutable_input_delay_histogram());
  SetHistogram(input_max_sum_delay_histogram,
               result->mutable_input_max_sum_delay_histogram());
  SetHistogram(H_histogram,
               result->mutable_h_histogram());
  SetHistogram(word_delay_histogram,
               result->mutable_word_delay_histogram());
  SetHistogram(synapse_before_delay_histogram,
               result->mutable_synapse_before_delay_histogram());
  SetHistogram(synapse_after_delay_histogram,
               result->mutable_synapse_after_delay_histogram());
  // Only add d_effective() if the neuron learned any words
  for (vector<int32>::const_iterator it = delay_histogram.begin();
       it != delay_histogram.end(); ++it) {
    if (0 < *it) {
      AddSample(HistogramEntropy(delay_histogram),
                result->mutable_d_effective());
      break;
    }
  }

  // Now start testing
  Bob bob;
  bob.Test((config.has_num_test_words() ? config.num_test_words() : 100000),
           words, neuron,
           result);

  // Collect statistics
  AddSample(neuron.Q_after(), result->mutable_q_after());
  AddSample(neuron.length(), result->mutable_synapses_per_neuron());
}

class JobRunConfiguration : public Job {
 public:
  JobRunConfiguration(TrainConfig* config, NeuronStatistics* result)
      : config_(config), result_(result), temp_() { }
  ~JobRunConfiguration() {
      (*result_) += temp_;
  }
  virtual void Run() {
    RunExperiment(*config_, &temp_);
  }
 private:
  TrainConfig* config_;
  NeuronStatistics* result_;
  NeuronStatistics temp_;
};

void RunConfiguration(int32 repetitions,
                      const TrainConfig& config, NeuronStatistics* result) {
  int32 N = repetitions;

  result->Clear();
  result->mutable_config()->CopyFrom(config);

  // Ensure that we try to learn at least 10,000 words in aggregate
  if (N * result->config().w() < 10000) {
    N = 10000 / result->config().w();
    if (10000 % result->config().w()) N++;
  }
  CHECK(repetitions <= N);
  CHECK_LT(0, N);

  if (config.has_num_test_words()) {
    result->mutable_config()->set_num_test_words(config.num_test_words());
  } else {
    // By default, ensure that we test on at least 1,000,000 random words
    const int32 kNumTestWords = 1000000;
    int32 num_test_words = kNumTestWords / N;
    if (kNumTestWords % N) num_test_words++;
    if (num_test_words < 1000) num_test_words = 1000;
    result->mutable_config()->set_num_test_words(num_test_words);
  }

  // printf("N = %d, num_test_words = %d\n",
  //        N, result->config().num_test_words());
  // fflush(stdout);
  vector<Job*> jobs(N);
  for (int32 i = 0; i < N; ++i) {
    jobs[i] = new JobRunConfiguration(result->mutable_config(), result);
  }
  RunParallel(&jobs);
}
}  // namespace cognon


text:
package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.Category.GUAVA;
import static com.google.errorprone.BugPattern.MaturityLevel.EXPERIMENTAL;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import static com.google.errorprone.matchers.Matchers.*;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.*;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree.JCExpression;

/**
 * Checks that the 1st argument to Preconditions.checkNotNull() isn't a primitive.
 * The primitive would be autoboxed to a non-null boxed type, and the check would trivially
 * pass.
 *
 * In our experience, most of these errors are from copied-and-pasted code and should
 * simply be removed.
 *
 * @author sjnickerson@google.com (Simon Nickerson)
 * @author eaftan@google.com (Eddie Aftandilian)
 */
@BugPattern(name = "PreconditionsCheckNotNullPrimitive",
    summary = "First argument to Preconditions.checkNotNull() is a primitive rather " +
    		"than an object reference",
    explanation =
        "Preconditions.checkNotNull() takes as an argument a reference that should be " +
        "non-null. Often a primitive is passed as the argument to check. The primitive " +
        "will be [http://docs.oracle.com/javase/7/docs/technotes/guides/language/autoboxing.html " +
        "autoboxed] into a boxed object, which is non-null, causing the check to " +
        "always pass without the condition being evaluated.\n" +
        "If the intent was to ensure that the primitive met some criterion (e.g., a boolean " +
        "that should be non-null), please use Precondtions.checkState() or " +
        "Preconditions.checkArgument() instead.",
    category = GUAVA, severity = ERROR, maturity = EXPERIMENTAL)
public class PreconditionsCheckNotNullPrimitive
    extends BugChecker implements MethodInvocationTreeMatcher {

  @SuppressWarnings("unchecked")
  @Override
  public Description matchMethodInvocation(MethodInvocationTree methodInvocationTree, VisitorState state) {
    if (allOf(
            methodSelect(staticMethod(
                "com.google.common.base.Preconditions", "checkNotNull")),
            argument(0, Matchers.<ExpressionTree>isPrimitiveType()))
            .matches(methodInvocationTree, state)) {
      return describe(methodInvocationTree, state);
    }
    return Description.NO_MATCH;
  }

  /**
   * If the call to Preconditions.checkNotNull is part of an expression (assignment, return, etc.),
   * we substitute the argument for the method call. E.g.:
   *   bar = Preconditions.checkNotNull(foo); ==> bar = foo;
   * If the argument to Preconditions.checkNotNull is a comparison using == or != and one of the
   * operands is null, we call checkNotNull on the non-null operand. E.g.:
   *   checkNotNull(a == null); ==> checkNotNull(a);
   * If the argument is a method call or binary tree and its return type is boolean, change it to a
   * checkArgument/checkState. E.g.:
   *   Preconditions.checkNotNull(foo.hasFoo()) ==> Preconditions.checkArgument(foo.hasFoo())
   * Otherwise, delete the checkNotNull call. E.g.:
   *   Preconditions.checkNotNull(foo); ==> [delete the line]
   */
  public Description describe(MethodInvocationTree methodInvocationTree, VisitorState state) {
    ExpressionTree arg1 = methodInvocationTree.getArguments().get(0);
    Tree parent = state.getPath().getParentPath().getLeaf();

    // Assignment, return, etc.
    if (parent.getKind() != Kind.EXPRESSION_STATEMENT) {
      return describeMatch(arg1,
          new SuggestedFix().replace(methodInvocationTree, arg1.toString()));
    }

    // Comparison to null
    if (arg1.getKind() == Kind.EQUAL_TO || arg1.getKind() == Kind.NOT_EQUAL_TO) {
      BinaryTree binaryExpr = (BinaryTree) arg1;
      if (binaryExpr.getLeftOperand().getKind() == Kind.NULL_LITERAL) {
        return describeMatch(arg1,
            new SuggestedFix().replace(arg1, binaryExpr.getRightOperand().toString()));
      }
      if (binaryExpr.getRightOperand().getKind() == Kind.NULL_LITERAL) {
        return describeMatch(arg1,
            new SuggestedFix().replace(arg1, binaryExpr.getLeftOperand().toString()));
      }
    }

    if ((arg1 instanceof BinaryTree || arg1.getKind() == Kind.METHOD_INVOCATION ||
         arg1.getKind() == Kind.LOGICAL_COMPLEMENT) &&
        ((JCExpression) arg1).type == state.getSymtab().booleanType) {
      return describeMatch(arg1,
          createCheckArgumentOrStateCall(methodInvocationTree, state, arg1));
    }

    return describeMatch(arg1, new SuggestedFix().delete(parent));
  }

  /**
   * Creates a SuggestedFix that replaces the checkNotNull call with a checkArgument or checkState
   * call.
   */
  private SuggestedFix createCheckArgumentOrStateCall(MethodInvocationTree methodInvocationTree,
      VisitorState state, ExpressionTree arg1) {
    SuggestedFix fix = new SuggestedFix();
    String replacementMethod = "checkState";
    if (arg1.getKind() == Kind.METHOD_INVOCATION && isMethodParameter(
        state.getPath(), (MethodInvocationTree) arg1)) {
      replacementMethod = "checkArgument";
    }

    StringBuilder replacement = new StringBuilder();

    // Was the original call to Preconditions.checkNotNull a static import or not?
    if (methodInvocationTree.getMethodSelect().getKind() == Kind.IDENTIFIER) {
      replacement.append(replacementMethod + "(");
      fix.addStaticImport("com.google.common.base.Preconditions." + replacementMethod);
    } else {
      replacement.append("Preconditions." + replacementMethod + "(");
    }

    // Create argument list.
    for (ExpressionTree arg : methodInvocationTree.getArguments()) {
      replacement.append(arg.toString());
      replacement.append(", ");
    }
    replacement.delete(replacement.length() - 2, replacement.length());
    replacement.append(")");
    fix.replace(methodInvocationTree, replacement.toString());
    return fix;
  }

  /**
   * Determines whether the root identifier of the tree node is a parameter to the enclosing
   * method.
   *
   * TODO(eaftan): Extract this to ASTHelpers.
   *
   * @param path the path to the current tree node
   * @param tree the node to compare against the parameters
   * @return whether the argument is a parameter to the enclosing method
   */
  private static boolean isMethodParameter(TreePath path, MethodInvocationTree tree) {
    ExpressionTree rootIdentifier = ASTHelpers.getRootIdentifier(tree);
    if (rootIdentifier == null || rootIdentifier.getKind() != Kind.IDENTIFIER) {
      throw new IllegalStateException("Could not find root identifier of expression " + tree);
    }
    Symbol sym = ASTHelpers.getSymbol(rootIdentifier);

    if (sym.isLocal()) {
      // Check against parameters of enclosing method declaration.
      while (path != null && !(path.getLeaf() instanceof MethodTree)) {
        path = path.getParentPath();
      }
      if (path == null) {
        throw new IllegalStateException("Should have an enclosing method declaration");
      }
      MethodTree methodDecl = (MethodTree) path.getLeaf();
      for (VariableTree param : methodDecl.getParameters()) {
        if (ASTHelpers.getSymbol(param) == sym) {
          return true;
        }
      }
    }
    return false;
  }
}


text:
/* $Id$ */

package org.apache.fop.afp.modca;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.output.ByteArrayOutputStream;

import org.apache.fop.afp.ptoca.PtocaBuilder;
import org.apache.fop.afp.ptoca.PtocaConstants;
import org.apache.fop.afp.util.BinaryUtils;

/**
 * Presentation text data contains the graphic characters and the control
 * sequences necessary to position the characters within the object space. The
 * data consists of: - graphic characters to be presented - control sequences
 * that position them - modal control sequences that adjust the positions by
 * small amounts - other functions causing text to be presented with differences
 * in appearance.
 *

 * The graphic characters are expected to conform to a coded font representation
 * so that they can be translated from the code point in the object data to the
 * character in the coded font. The units of measure for linear displacements
 * are derived from the PresentationTextDescriptor or from the hierarchical
 * defaults.
 *

 * In addition to graphic character code points, Presentation Text data can
 * contain embedded control sequences. These are strings of two or more bytes
 * which signal an alternate mode of processing for the content of the current
 * Presentation Text data.
 *

 * The content for this object can be created using {@link PtocaBuilder}.
 */
public class PresentationTextData extends AbstractAFPObject implements PtocaConstants {

    /** the maximum size of the presentation text data.*/
    private static final int MAX_SIZE = 8192;

    /** the AFP data relating to this presentation text data. */
    private final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /**
     * Default constructor for the PresentationTextData.
     */
    public PresentationTextData() {
        this(false);
    }

    private static final int HEADER_LENGTH = 9;

    /**
     * Constructor for the PresentationTextData, the boolean flag indicate
     * whether the control sequence prefix should be set to indicate the start
     * of a new control sequence.
     *
     * @param controlInd
     *            The control sequence indicator.
     */
    public PresentationTextData(boolean controlInd) {
        final byte[] data = {
                0x5A, // Structured field identifier
                0x00, // Record length byte 1
                0x00, // Record length byte 2
                SF_CLASS, // PresentationTextData identifier byte 1
                Type.DATA, // PresentationTextData identifier byte 2
                Category.PRESENTATION_TEXT, // PresentationTextData identifier byte 3
                0x00, // Flag
                0x00, // Reserved
                0x00, // Reserved
        };
        baos.write(data, 0, HEADER_LENGTH);

        if (controlInd) {
            baos.write(new byte[] {0x2B, (byte) 0xD3}, 0, 2);
        }
    }

    /**
     * Returns the number of data bytes still available in this object until it is full and a new
     * one has to be started.
     * @return the number of data bytes available
     */
    public int getBytesAvailable() {
        return MAX_SIZE - baos.size() + HEADER_LENGTH;
    }

    /**
     * Returns the output stream the content data is written to.
     * @return the output stream
     */
    protected OutputStream getOutputStream() {
        return this.baos;
    }

    /** {@inheritDoc} */
    public void writeToStream(OutputStream os) throws IOException {
        assert getBytesAvailable() >= 0;
        byte[] data = baos.toByteArray();
        byte[] size = BinaryUtils.convert(data.length - 1, 2);
        data[1] = size[0];
        data[2] = size[1];
        os.write(data);
    }

}


text:
#import <Foundation/Foundation.h>

@class UAInboxMessage;

/**
 * The UAInboxMessageListDelegate protocol declares methods that
 * are implemented by delegates of a UAInboxMessageList API calls.
 *
 * Delegates are notified when messages are modified, loaded or
 * fail to load or update.
 *
 * @deprecated As of 5.0.0. Use the block based message list callbacks instead.
 *
 */
 __attribute__((deprecated("As of version 5.0.0")))
@protocol UAInboxMessageListDelegate <NSObject>

@optional

/**
 * Tells the delegate that a request for inbox messages succeeded.
 */
- (void)messageListLoadSucceeded;
/**
 * Tells the delegate that a request for inbox messages failed.
 */
- (void)messageListLoadFailed;

/**
 * Tells the delegate that a message has been marked as read.
 *
 * @param message The message marked as read
 */
- (void)singleMessageMarkAsReadFinished:(UAInboxMessage *)message;

/**
 * Tells the delegate that a mark-as-read request failed.
 *
 * @param message The message that failed to update
 */
- (void)singleMessageMarkAsReadFailed:(UAInboxMessage *)message;

/**
 * Tells the delegate that a batch of messages has been marked as read.
 */
- (void)batchMarkAsReadFinished;

/**
 * Tells the delegate that a batch mark-as-read request failed.
 */
- (void)batchMarkAsReadFailed;

/**
 * Tells the delegate that a batch of messages has been deleted.
 */
- (void)batchDeleteFinished;

/**
 * Tells the delegate that a batch update of messages has failed.
 */
- (void)batchDeleteFailed;

@end


text:
<?php

// autoload.php generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitaa224ae752dfc5b990b2d5f1899d8aac::getLoader();


text:
package com.pivotal.gemfirexd.internal.iapi.tools.i18n;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import com.gemstone.gemfire.internal.shared.ClientSharedUtils;
import com.pivotal.gemfirexd.internal.shared.common.StopWatch;

/**
 * This {@link PrintWriter} implementation shows the output provided one page at
 * a time in interactive sessions waiting for user input to continue or allowing
 * the user to terminate the output at a particular point. The write and other
 * methods throw an {@link IllegalStateException} to indicate force quit by
 * user.
 *
 * @author swale
 * @since 7.0
 */
public class PagedLocalizedOutput extends LocalizedOutput {

  private final InputStream in;
  private final int terminalWidth;
  private final int terminalHeight;
  private final String continuePrompt;
  private final StopWatch timer;
  private char[] cbuf;
  private static final int BUFSIZE = 1024;

  private int currentWidth;
  private int currentLines;

  public PagedLocalizedOutput(OutputStream o, InputStream in,
      int terminalWidth, int terminalHeight, String continuePrompt,
      final StopWatch timer) {
    super(o);
    this.in = in;
    this.terminalWidth = terminalWidth - 1;
    // reduce by 1 to accomodate the continue prompt
    this.terminalHeight = terminalHeight - 1;
    this.continuePrompt = continuePrompt;
    this.timer = timer;
  }

  public PagedLocalizedOutput(OutputStream o, String enc, InputStream in,
      int terminalWidth, int terminalHeight, String continuePrompt,
      final StopWatch timer) throws UnsupportedEncodingException {
    super(o, enc);
    this.in = in;
    this.terminalWidth = terminalWidth - 1;
    // reduce by 1 to accomodate the continue prompt
    this.terminalHeight = terminalHeight - 1;
    this.continuePrompt = continuePrompt;
    this.timer = timer;
  }

  public PagedLocalizedOutput(Writer writer, InputStream in, int terminalWidth,
      int terminalHeight, String continuePrompt, final StopWatch timer) {
    super(writer);
    this.in = in;
    this.terminalWidth = terminalWidth - 1;
    // reduce by 1 to accomodate the continue prompt
    this.terminalHeight = terminalHeight - 1;
    this.continuePrompt = continuePrompt;
    this.timer = timer;
  }

  public void write(String s, int off, int len) {
    if (this.cbuf == null) {
      this.cbuf = new char[BUFSIZE > len ? BUFSIZE : len];
    }
    else if (this.cbuf.length < len) {
      this.cbuf = new char[len];
    }
    s.getChars(off, off + len, this.cbuf, 0);
    checkPage(this.cbuf, 0, len);
    super.write(this.cbuf, 0, len);
  }

  public void write(char[] buf, int off, int len) {
    checkPage(buf, off, len);
    super.write(buf, off, len);
  }

  public void println() {
    super.println();
    this.currentLines++;
    if (this.currentLines >= this.terminalHeight) {
      if (waitForPage()) {
        throw new IllegalStateException("user ending output");
      }
      this.currentLines = 0;
    }
    this.currentWidth = 0;
  }

  private void checkPage(final char[] buf, int off, int len)
      throws IllegalStateException {
    // check if string will cause the width to exceed the terminal width
    // TODO: ideally this should get the actual length after encoding etc.
    // that is being consumed on the screen, but it may be too late by then
    // if we first print it on screen so it will be an approximation either way;
    // probably can use some encoder API to get the actual width on screen
    int lineWidth = this.currentWidth;
    int newLines = 0;
    for (int index = off; index < (off + len); index++) {
      if (buf[index] == '\n' || ++lineWidth >= this.terminalWidth) {
        lineWidth = 0;
        newLines++;
        if ((this.currentLines + newLines) >= this.terminalHeight) {
          if (waitForPage()) {
            throw new IllegalStateException("user ending output");
          }
          this.currentLines = newLines;
          newLines = 0;
        }
      }
    }
    this.currentLines += newLines;
    this.currentWidth = lineWidth;
  }

  private boolean waitForPage() {
    if (this.timer != null) {
      this.timer.stop();
    }
    // wait for user input before further output
    super.write(this.continuePrompt, 0, this.continuePrompt.length());
    super.flush();
    String chars = ClientSharedUtils.getJdkHelper().readChars(this.in, false);
    super.println();
    if (chars != null && chars.length() > 0
        && (chars.charAt(0) == 'q' || chars.charAt(0) == 'Q')) {
      super.flush();
      if (this.timer != null) {
        this.timer.start();
      }
      return true;
    }
    if (this.timer != null) {
      this.timer.start();
    }
    return false;
  }
}


text:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Data;

namespace SilverlightUI.ViewModels
{
  public class MainMenu
  {
    private ObservableCollection<MenuItem> _menuItems;
    public ObservableCollection<MenuItem> MenuItems
    {
      get { return _menuItems; }
    }

    public MainMenu()
    {
      _menuItems = new ObservableCollection<MenuItem>
      {
        new MenuItem {
          Label = "Project List", MethodName = "ShowProjectList", Method = ShowProjectList,
          IsAuthorized = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ProjectList)) },
        new MenuItem {
          Label = "Resource List", MethodName = "ShowResourceList", Method = ShowResourceList,
          IsAuthorized = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ResourceList)) },
        new MenuItem {
          Label = "Edit roles", MethodName = "ShowRoleListEdit", Method = ShowRoleListEdit,
          IsAuthorized = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.Admin.RoleEditList)) },
      };
    }

    public void MenuItemSelected(object sender, Bxf.Xaml.ExecuteEventArgs e)
    {
      var listbox = (ListBox)e.TriggerSource;
      var menuItem = (MenuItem)listbox.SelectedItem;
      if (menuItem.IsAuthorized)
        menuItem.Method();
      else
        Bxf.Shell.Instance.ShowError("You are not authorized to perform this action", "Authorization error");
    }

    public void ShowProjectList()
    {
      Bxf.Shell.Instance.ShowView(
        typeof(Views.ProjectList).AssemblyQualifiedName,
        "projectListViewSource",
        new ProjectList(),
        "Main");
    }

    public void ShowResourceList()
    {
      Bxf.Shell.Instance.ShowView(
        typeof(Views.ResourceList).AssemblyQualifiedName,
        "resourceListViewSource",
        new ResourceList(),
        "Main");
    }

    public void ShowRoleListEdit()
    {
      Bxf.Shell.Instance.ShowView(
        typeof(Views.RoleListEdit).AssemblyQualifiedName,
        "roleListEditViewSource",
        new RoleListEdit(),
        "Main");
    }

    public class MenuItem : INotifyPropertyChanged
    {
      private string _label;
      public string Label
      {
        get { return _label; }
        set { _label = value; OnPropertyChanged("Label"); }
      }

      private string _methodName;
      public string MethodName
      {
        get { return _methodName; }
        set { _methodName = value; OnPropertyChanged("MethodName"); }
      }

      private Action _method;
      public Action Method
      {
        get { return _method; }
        set { _method = value; OnPropertyChanged("Method"); }
      }

      private bool _isAuthorized;
      public bool IsAuthorized
      {
        get { return _isAuthorized; }
        set { _isAuthorized = value; OnPropertyChanged("IsAuthorized"); }
      }

      public event PropertyChangedEventHandler PropertyChanged;

      protected virtual void OnPropertyChanged(string propertyName)
      {
        if (PropertyChanged != null)
          PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }
  }
}


text:
Simple example, showing how to wrap ajax-driven jstree to angularjs directive.

## Usage

```shell
groovy server.groovy
```

open in browser:

http://localhost:5050

and you see jstree like this:

![screenshot](doc/screenshot_2014-02-08_22_07_02.png "angularjs-jstree screenshot")

Of course, concrete content of the tree will be different on different systems.

**WARNING:**

Please DO NOT make this program accessible via external IP.
The program shows the content of your file system in the browser,
which should be considered a significant security risk in such circumstances.

If you use only internal IP address, you are safe - no security risk involved.

## Copyright and License

Copyright 2013-2014 (c) Andrey Hihlovskiy

All versions, present and past, of angularjs-jstree are licensed under [MIT license](license.txt).


text: Rails.application.config.session_store :cookie_store, key: '_cleanup-social_session'


text:
package cloud::aws::cloudwatch::mode::getmetrics;

use base qw(centreon::plugins::templates::counter);

use strict;
use warnings;

sub custom_metric_perfdata {
    my ($self, %options) = @_;

    $self->{output}->perfdata_add(
        label => $self->{result_values}->{perf_label},
        value => $self->{result_values}->{value},
        warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-metric'),
        critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-metric'),
    );
}

sub custom_metric_threshold {
    my ($self, %options) = @_;

    my $exit = $self->{perfdata}->threshold_check(
        value => $self->{result_values}->{value},
        threshold => [
            { label => 'critical-metric', exit_litteral => 'critical' },
            { label => 'warning-metric', exit_litteral => 'warning' }
        ]
    );
    return $exit;
}

sub custom_metric_output {
    my ($self, %options) = @_;

    my $msg = "Metric '" . $self->{result_values}->{display}  . "' value is " . $self->{result_values}->{value};
    return $msg;
}

sub custom_metric_calc {
    my ($self, %options) = @_;

    $self->{result_values}->{value} = $options{new_datas}->{$self->{instance} . '_value'};
    $self->{result_values}->{perf_label} = $options{new_datas}->{$self->{instance} . '_perf_label'};
    $self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
    return 0;
}

sub set_counters {
    my ($self, %options) = @_;

    $self->{maps_counters_type} = [
        { name => 'metrics', type => 1, message_multiple => 'All metrics are ok' },
    ];

    $self->{maps_counters}->{metrics} = [
        { label => 'metric', set => {
                key_values => [ { name => 'value' }, { name => 'perf_label' }, { name => 'display' } ],
                closure_custom_calc => $self->can('custom_metric_calc'),
                closure_custom_output => $self->can('custom_metric_output'),
                closure_custom_perfdata => $self->can('custom_metric_perfdata'),
                closure_custom_threshold_check => $self->can('custom_metric_threshold'),
            }
        }
    ];
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'namespace:s'  => { name => 'namespace' },
        'dimension:s%' => { name => 'dimension' },
        'metric:s@'    => { name => 'metric' },
    });

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::check_options(%options);

    if (!defined($self->{option_results}->{namespace}) || $self->{option_results}->{namespace} eq '') {
        $self->{output}->add_option_msg(short_msg => "Need to specify --namespace option.");
        $self->{output}->option_exit();
    }

    $self->{aws_metrics} = [];
    if (defined($self->{option_results}->{metric})) {
        $self->{aws_metrics} = [@{$self->{option_results}->{metric}}];
    }
    if (scalar(@{$self->{aws_metrics}}) <= 0) {
        $self->{output}->add_option_msg(short_msg => "Need to specify --metric option.");
        $self->{output}->option_exit();
    }

    $self->{dimension_name} = '';
    my $append = '';
    $self->{aws_dimensions} = [];
    if (defined($self->{option_results}->{dimension})) {
        foreach (keys %{$self->{option_results}->{dimension}}) {
            push @{$self->{aws_dimensions}}, { Name => $_, Value => $self->{option_results}->{dimension}->{$_} };
            $self->{dimension_name} .= $append . $_ . '.' . $self->{option_results}->{dimension}->{$_};
            $append = '-';
        }
    }

    $self->{aws_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 600;
    $self->{aws_period} = defined($self->{option_results}->{period}) ? $self->{option_results}->{period} : 60;

    $self->{aws_statistics} = ['Average'];
    if (defined($self->{option_results}->{statistic})) {
        $self->{aws_statistics} = [];
        foreach my $stat (@{$self->{option_results}->{statistic}}) {
            if ($stat ne '') {
                push @{$self->{aws_statistics}}, ucfirst(lc($stat));
            }
        }
    }

    foreach my $metric_name ($self->{aws_metrics}) {
        foreach my $statistic ($self->{aws_statistics}) {
            my $entry = { label => lc($metric_name) . '-' . $statistic, set => {
                    key_values => [ { name => $metric_name . '_' . $statistic }, { name => 'display' } ],
                    output_template => $metric_name . ' ' . ucfirst($statistic) . ' : %s',
                    perfdatas => [
                        { label => lc($metric_name) . '_' . $statistic, value => $metric_name . '_' . $statistic , template => '%s',
                          label_extra_instance => 1, instance_use => 'display' },
                    ],
                }
            };
            push @{$self->{maps_counters}->{dimensions}}, $entry;
        }
    }
}

sub manage_selection {
    my ($self, %options) = @_;

    my $metric_results = $options{custom}->cloudwatch_get_metrics(
        namespace => $self->{option_results}->{namespace},
        dimensions => $self->{aws_dimensions},
        metrics => $self->{aws_metrics},
        statistics => $self->{aws_statistics},
        timeframe => $self->{aws_timeframe},
        period => $self->{aws_period},
    );

    $self->{metrics} = {};
    foreach my $label (keys %{$metric_results}) {
        foreach my $stat (('minimum', 'maximum', 'average', 'sum')) {
            next if (!defined($metric_results->{$label}->{$stat}));

            my $name = $label . '_' . $stat;
            $name = $self->{dimension_name} . '_' . $name if ($self->{dimension_name} ne '');
            $self->{metrics}->{$name} = {
                display => $name,
                value => $metric_results->{$label}->{$stat},
                perf_label => $label . '_' . $stat,
            };
        }
    }
}

1;

__END__

=head1 MODE

Check cloudwatch metrics (same dimension and namespace).

Example:
perl centreon_plugins.pl --plugin=cloud::aws::plugin --custommode=paws --mode=cloudwatch-get-metrics --region=eu-west-1
--namespace=AWS/EC2 --dimension=InstanceId=i-01622936185e32a45 --metric=CPUUtilization --metric=CPUCreditUsage
--statistic=average --statistic=max –-period=60 --timeframe=600 --warning-metric= --critical-metric=

=over 8

=item B<--namespace>

Set cloudwatch namespace (Required).

=item B<--dimension>

Set cloudwatch dimensions.

=item B<--metric>

Set cloudwatch metrics (Required).

=item B<--warning-metric>

Threshold warning.

=item B<--critical-metric>

Threshold critical.

=back

=cut


text:
from random import randrange, choice
from collections import defaultdict

import data.tools as tools

actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']

class Run(tools._State):

    def __init__(self):
        super(Run, self).__init__()
        self.need_event = False
        self.stop = False

    # 对角线翻转
    def transpose(self, field):
        return [list(row) for row in zip(*field)]

    # 垂直镜面翻转
    def invert(self, field):
        return [row[::-1] for row in field]

    # 判断是否能够移动
    def move_is_possible(self, direction):
        def row_is_left_movable(row):
            def change(i):
                if row[i] == 0 and row[i + 1] != 0:
                    return True
                if row[i] != 0 and row[i + 1] == row[i]:
                    return True
                return False

            return any(change(i) for i in range(len(row) - 1))

        check = {}
        check['Left'] = lambda field: any(row_is_left_movable(row) for row in field)

        check['Right'] = lambda field: check['Left'](self.invert(field))

        check['Up'] = lambda field: check['Left'](self.transpose(field))

        check['Down'] = lambda field: check['Right'](self.transpose(field))

        if direction in check:
            return check[direction](self.field)
        else:
            return False

    def move(self, direction):

        # 接受用户行为, 取得移动方向
        def move_row_left(row):

            # 移动后补空
            def tighten(row):
                new_row = [i for i in row if i != 0]
                new_row += [0 for i in range(len(row) - len(new_row))]
                return new_row

            # 合并相同数字
            def merge(row):
                pair = False
                new_row = []
                for i in range(len(row)):
                    if pair:
                        new_row.append(2 * row[i])
                        self.score += 2 * row[i]
                        pair = False
                    else:
                        if i + 1 < len(row) and row[i] == row[i + 1]:
                            pair = True
                            new_row.append(0)
                        else:
                            new_row.append(row[i])
                assert len(new_row) == len(row)
                return new_row

            return tighten(merge(tighten(row)))

        moves = {}

        moves['Left'] = lambda field: [move_row_left(row) for row in field]
        moves['Right'] = lambda field: self.invert(moves['Left'](self.invert(field)))
        moves['Up'] = lambda field: self.transpose(moves['Left'](self.transpose(field)))
        moves['Down'] = lambda field: self.transpose(moves['Right'](self.transpose(field)))

        # 测试各个方向是否可以移动
        if direction in moves:
            if self.move_is_possible(direction):
                self.field = moves[direction](self.field)
                self.spawn()
                self.need_event = False
                return True
            else:
                self.need_event = False
                return False

    def is_win(self):
        return any(any(i >= self.win_value for i in row) for row in self.field)

    def is_gameover(self):
        return not any(self.move_is_possible(move) for move in actions)

    def draw(self, screen):
        help_string1 = '(W)Up (S)Down (A)Left (D)Right'
        help_string2 = '      (R)Restart (Q)Exit'
        gameover_string = '           GAME OVER'
        win_string = '           YOU WIN!'

        def cast(string):
            screen.addstr(string + '\n')

        def draw_hor_separator():
            line = '+' + ('+------' * self.width + '+')[1:]
            separator = defaultdict(lambda: line)
            if not hasattr(draw_hor_separator, "counter"):
                draw_hor_separator.counter = 0
            cast(separator[draw_hor_separator.counter])
            draw_hor_separator.counter += 1

        def draw_row(row):
            cast(''.join('|{: ^5} '.format(num) if num > 0 else '|      ' for num in row) + '|')

        screen.clear()
        cast('SCORE: ' + str(self.score))

        if 0 != self.highscore:
            cast('HIGHSCORE: ' + str(self.highscore))

        for row in self.field:
            draw_hor_separator()
            draw_row(row)

        draw_hor_separator()

        if self.is_win():
            cast(win_string)
            cast(help_string2)
            return True
        else:
            if self.is_gameover():
                cast(gameover_string)
                cast(help_string2)
                return True
            else:
                cast(help_string1)

        cast(help_string2)

    def spawn(self):
        new_element = 4 if randrange(100) > 89 else 2
        (i, j) = choice([(i, j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0])
        self.field[i][j] = new_element

    def startup(self, game_data):
        self.next = 'Halt'
        self.previous = 'Init'
        self.score = game_data['score']
        self.highscore = game_data['highscore']
        self.win_value = game_data['win_score']
        self.width = game_data['width']
        self.height = game_data['height']
        self.game_data = game_data
        self.field = [[0 for i in range(self.width)] for j in range(self.height)]
        self.spawn()

    def cleanup(self):
        self.done = False
        return self.game_data

    def update(self, screen, event):
        self.move(direction = event)
        self.stop = self.draw(screen)
        if event is 'Restart':
            self.done = True
            self.next = 'Init'
        if not self.stop:
            self.need_event = True
        else:
            self.done = True

    def get_event(self, event):
        self.event = event


text:
@import QuartzCore;

@interface ComboViewController () <
    CAAnimationDelegate,
    ComboProtocol,
    UICollectionViewDataSource,
    UICollectionViewDelegate,
    UICollectionViewDelegateFlowLayout
>

@property (nonatomic, strong) Combo *game;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) BOOL showHint;
@property (nonatomic, readonly) UIEdgeInsets insets;
@property (nonatomic, readonly) CGSize itemSize;

@end

@implementation ComboViewController

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (UIEdgeInsets)insets {
    return [self collectionView:self.collectionView
                         layout:self.collectionView.collectionViewLayout
         insetForSectionAtIndex:0];
}

- (CGSize)itemSize {
    return [self collectionView:self.collectionView
                         layout:self.collectionView.collectionViewLayout
         sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
}

#pragma mark - View Management

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Combo needs to support all iPhone screen sizes. The user inferface is simple,
    // so we decided to layout the views programmatically instead of using a storyboard.

    // Make sure the main view exists
    NSAssert(self.view, @"main view undefined");
    // NSLog(@"%@", self.view);

    self.view.backgroundColor = [UIColor blackColor];

    // Combo displays 12 cards face-up using a standard collection view. The collection view
    // fills most of the screen, and a small amount of space at the bottom is reserved for a
    // progress bar and an info button.

    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height * 0.95;

    // We always want to display the cards in a 4 x 3 grid. Given that constraint, we
    // compute the size of each cell ("span" is the standard distance between cells).
    // General formula: cellWidth = (screenWidth – (n + 1) * span) / n

    CGFloat span = 15.0;
    CGSize cellSize = CGSizeMake((width - (4.0 * span)) / 3.0, (height - (5.0 * span)) / 4.0);

    // Create the flow layout. The 4 x 3 grid is a consequence of using the standard flow layout
    // with the computed values for span and cell size.

    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = cellSize;
    // self.flowLayout.estimatedItemSize = cellSize;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(span, span, span, span);
    self.flowLayout.minimumInteritemSpacing = self.flowLayout.minimumLineSpacing = span;

    // Create the collection view and add it to the main view

    CGRect frame = CGRectMake(0.0, 0.0, width, height);
    self.collectionView =
        [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:self.flowLayout];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];
    [self.collectionView registerClass:[ComboViewCell class] forCellWithReuseIdentifier:@"ComboCell"];
    [self.view addSubview:self.collectionView];

    // Add gestures to the collection view

    // single tap to choose a card
    UITapGestureRecognizer *tap =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    tap.numberOfTapsRequired = 1;
    [self.collectionView addGestureRecognizer:tap];

    // right swipe to ask for a hint
    UISwipeGestureRecognizer *swipe =
        [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe:)];
    [swipe setDirection:(UISwipeGestureRecognizerDirectionRight)];
    swipe.numberOfTouchesRequired = 1;
    [self.collectionView addGestureRecognizer:swipe];

    // Create a progress bar and add it to the main view

    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    self.progressView.userInteractionEnabled = NO;

    self.progressView.frame = CGRectMake(self.collectionView.bounds.origin.x + 16.0,
                                         self.collectionView.bounds.size.height + 10.0,
                                         self.collectionView.bounds.size.width - 32.0,
                                         3.0);

    self.progressView.progress = 0.5f;
    self.progressView.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:self.progressView];

    // Create an info button to display usage information, and add it to the Main View.

    // Create the first game.
    [self createGame];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
    [super viewWillDisappear:animated];
}

#pragma mark - UICollectionViewDelegateFlowLayout

#if 0

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    CGFloat spacing = (collectionView.frame.size.width - (self.itemSize.width * 3.0) - (self.insets.top * 2.0)) / 2.0;

    return spacing;
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //static CGSize itemSize;

    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat numColumns = 3;

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let collectionViewSize = collectionView.frame.size
        let cellSpan = traitCollection.horizontalSizeClass == .Compact ?
    kReadyCategoryCollectionViewCellSpanCompact: kReadyCategoryCollectionViewCellSpanRegular
        let sideSize: Double = sqrt(Double(collectionViewSize.width * collectionViewSize.height) / (Double(entries.count))) - cellSpan
        return CGSize(width: sideSize * kResponsiveCollectionSizeProportion, height: sideSize)
    }

    return itemSize;
}

#endif

#pragma mark - Game Control

- (void)createGame
{
    self.game = [[Combo alloc] initWithCardCount:12 usingCardDeck:[self createDeck]];
    self.game.delegate = self;
    [self updateUI];
}

- (ComboDeck *)createDeck
{
    return [[ComboDeck alloc] init];
}

- (void)updateUI
{
    for (ComboViewCell *cell in [self.collectionView visibleCells]) {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
        ComboCard *card = [self.game cardAtIndex:indexPath.item];
        [self updateCell:cell usingCard:card];
    }

    CGFloat progress = [self.game gameProgress];
    [self.progressView setProgress:progress animated:YES];
}

- (void)gameDidFinish
{
    NSArray *messages = @[@"Awesome!", @"Great Job!", @"Whew!", @"Nice Work!"];
    unsigned index = arc4random() % [messages count];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Game Over"
                                                                   message:messages[index]
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) { [self createGame]; }];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

}

- (void)singleTap:(UITapGestureRecognizer *)gesture
{
    CGPoint tapLocation = [gesture locationInView:self.collectionView];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:tapLocation];
    if (indexPath) {
        self.showHint = NO;
        BOOL success = [self.game chooseCardAtIndex:indexPath.item];
        [self updateUI];
        if (!success) {
            // match failed
            [self shake];
        }
    }
}

- (void)rightSwipe:(UISwipeGestureRecognizer *)gesture
{
    self.showHint = YES;
    [self updateUI];
}

#pragma mark - QuickLook

- (IBAction)info:(id)sender
{
    [self present];
}

- (void)present
{
    PreviewController *controller = [[PreviewController alloc] init];
    [self presentViewController:controller animated:YES completion:nil];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 12;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ComboViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ComboCell" forIndexPath:indexPath];
    ComboCard *card = [self.game cardAtIndex:indexPath.item];
    [self updateCell:cell usingCard:card];

    return cell;
}

- (void)updateCell:(ComboViewCell *)cell usingCard:(ComboCard *)card
{
    cell.rank = card.rank;
    cell.shape = card.shape;
    cell.color = card.color;
    cell.shading = card.shading;
    cell.hidden = card.isMatched;

    if (card.isNew) {
        CATransition *transition = [CATransition animation];
        transition.type = kCATransitionMoveIn;
        transition.subtype = kCATransitionFromBottom;
        transition.duration = 0.3;
        [cell.layer addAnimation:transition forKey:nil];
        card.new = NO;
    }

    if (self.showHint) {
        if (card.canMatch) {
            [self startAnimatingCell:cell];
        }
    }
    else if (card.isChosen) {
        [self startAnimatingCell:cell];
    }
    else {
        [self stopAnimatingCell:cell];
    }
}

- (void)startAnimatingCell:(ComboViewCell *)cell
{
    if (cell.animating) return;
    cell.animating = YES;

    UIViewAnimationOptions options = UIViewAnimationOptionCurveEaseInOut |
                                     UIViewAnimationOptionAutoreverse |
                                     UIViewAnimationOptionRepeat |
                                     UIViewAnimationOptionAllowUserInteraction;

    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.95, 0.95);

    [UIView animateWithDuration:0.25
                          delay:0
                        options:options
                     animations:^{ cell.transform = transform; }
                     completion:NULL];
}

- (void)stopAnimatingCell:(ComboViewCell *)cell
{
    if (!cell.animating) return;
    cell.animating = NO;

    UIViewAnimationOptions options = UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState;

    CGAffineTransform transform = CGAffineTransformIdentity;

    [UIView animateWithDuration:0.1
                          delay:0
                        options:options
                     animations:^{ cell.transform = transform; }
                     completion:NULL];
}

- (void)shake
{
    static CAKeyframeAnimation *animation;

    if (!animation) {

        animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        animation.duration = 0.25;
        animation.delegate = self;
        animation.fillMode = kCAFillModeForwards;
        animation.removedOnCompletion = YES;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

        NSMutableArray* values = [[NSMutableArray alloc] init];

        int steps = 100;
        double position = 0;
        float e = 2.71;

        for (int t = 0; t < steps; t++) {
            position = 10 * pow(e, -0.022 * t) * sin(0.12 * t);
            NSValue* value = [NSValue valueWithCGPoint:CGPointMake([self.collectionView center].x - position, [self.collectionView center].y)];
            [values addObject:value];
        }

        animation.values = values;
    }

    [[self.collectionView layer] addAnimation:animation forKey:@"position"];
}

@end


text:
from gym_torcs import TorcsEnv
import numpy as np
import random
import argparse
from keras.models import model_from_json, Model
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
import tensorflow as tf
from keras.engine.training import collect_trainable_weights
import json
from collections import deque

import math
from keras.initializations import normal, identity
from keras.models import model_from_json
from keras.models import Sequential, Model
from keras.engine.training import collect_trainable_weights
from keras.layers import Dense, Flatten, Input, merge, Lambda
from keras.optimizers import Adam
import tensorflow as tf
import keras.backend as K

from keras.models import load_model
from keras.layers import Activation
from keras.models import Sequential, Model

import timeit

# In[21]:

#Ornstein-Uhlenbeck process

def Ornstein_Uhlenbeck(self, x, mu, theta, sigma):
    return theta * (mu - x) + sigma * np.random.randn(1)

# In[22]:

class ReplayBuffer(object):

    def __init__(self, buffer_size):
        self.buffer_size = buffer_size
        self.num_experiences = 0
        self.buffer = deque()

    def getBatch(self, batch_size):
        # Randomly sample batch_size examples
        if self.num_experiences < batch_size:
            return random.sample(self.buffer, self.num_experiences)
        else:
            return random.sample(self.buffer, batch_size)

    def size(self):
        return self.buffer_size

    def add(self, state, action, reward, new_state, done):
        experience = (state, action, reward, new_state, done)
        if self.num_experiences < self.buffer_size:
            self.buffer.append(experience)
            self.num_experiences += 1
        else:
            self.buffer.popleft()
            self.buffer.append(experience)

    def count(self):
        # if buffer is full, return buffer size
        # otherwise, return experience counter
        return self.num_experiences

    def erase(self):
        self.buffer = deque()
        self.num_experiences = 0

# In[23]:

HIDDEN1_UNITS = 300
HIDDEN2_UNITS = 600

class ActorNetwork(object):
    def __init__(self, sess, state_size, action_size, BATCH_SIZE, TAU, LEARNING_RATE):
        self.sess = sess
        self.BATCH_SIZE = BATCH_SIZE
        self.TAU = TAU
        self.LEARNING_RATE = LEARNING_RATE

        K.set_session(sess)

        #Now create the model
        self.model , self.weights, self.state = self.create_actor_network(state_size, action_size)
        self.target_model, self.target_weights, self.target_state = self.create_actor_network(state_size, action_size)
        self.action_gradient = tf.placeholder(tf.float32,[None, action_size])
        self.params_grad = tf.gradients(self.model.output, self.weights, -self.action_gradient)
        grads = zip(self.params_grad, self.weights)
        self.optimize = tf.train.AdamOptimizer(LEARNING_RATE).apply_gradients(grads)
        self.sess.run(tf.initialize_all_variables())

    def train(self, states, action_grads):
        self.sess.run(self.optimize, feed_dict={
            self.state: states,
            self.action_gradient: action_grads
        })

    def target_train(self):
        actor_weights = self.model.get_weights()
        actor_target_weights = self.target_model.get_weights()
        for i in xrange(len(actor_weights)):
            actor_target_weights[i] = self.TAU * actor_weights[i] + (1 - self.TAU)* actor_target_weights[i]
        self.target_model.set_weights(actor_target_weights)

    def create_actor_network(self, state_size,action_dim):
        print("building Actor model")
        S = Input(shape=[state_size])
        h0 = Dense(HIDDEN1_UNITS, activation='relu')(S)
        h1 = Dense(HIDDEN2_UNITS, activation='relu')(h0)
        Steering = Dense(1,activation='tanh',init=lambda shape, name: normal(shape, scale=1e-4, name=name))(h1)
        Acceleration = Dense(1,activation='sigmoid',init=lambda shape, name: normal(shape, scale=1e-4, name=name))(h1)
        Brake = Dense(1,activation='sigmoid',init=lambda shape, name: normal(shape, scale=1e-4, name=name))(h1)
        V = merge([Steering,Acceleration,Brake],mode='concat')
        model = Model(input=S,output=V)
        return model, model.trainable_weights, S

# In[24]:

class CriticNetwork(object):
    def __init__(self, sess, state_size, action_size, BATCH_SIZE, TAU, LEARNING_RATE):
        self.sess = sess
        self.BATCH_SIZE = BATCH_SIZE
        self.TAU = TAU
        self.LEARNING_RATE = LEARNING_RATE
        self.action_size = action_size

        K.set_session(sess)

        #Now create the model
        self.model, self.action, self.state = self.create_critic_network(state_size, action_size)
        self.target_model, self.target_action, self.target_state = self.create_critic_network(state_size, action_size)
        self.action_grads = tf.gradients(self.model.output, self.action)  #GRADIENTS for policy update
        self.sess.run(tf.initialize_all_variables())

    def gradients(self, states, actions):
        return self.sess.run(self.action_grads, feed_dict={
            self.state: states,
            self.action: actions
        })[0]

    def target_train(self):
        critic_weights = self.model.get_weights()
        critic_target_weights = self.target_model.get_weights()
        for i in xrange(len(critic_weights)):
            critic_target_weights[i] = self.TAU * critic_weights[i] + (1 - self.TAU)* critic_target_weights[i]
        self.target_model.set_weights(critic_target_weights)

    def create_critic_network(self, state_size,action_dim):
        print("building critic model")
        S = Input(shape=[state_size])
        A = Input(shape=[action_dim],name='action2')
        w1 = Dense(HIDDEN1_UNITS, activation='relu')(S)
        a1 = Dense(HIDDEN2_UNITS, activation='linear')(A)
        h1 = Dense(HIDDEN2_UNITS, activation='linear')(w1)
        h2 = merge([h1,a1],mode='sum')
        h3 = Dense(HIDDEN2_UNITS, activation='relu')(h2)
        V = Dense(action_dim,activation='linear')(h3)
        model = Model(input=[S,A],output=V)
        adam = Adam(lr=self.LEARNING_RATE)
        model.compile(loss='mse', optimizer=adam)
        return model, A, S

# In[25]:

def playGame(train_indicator=1):    #1 means Train, 0 means simply Run
    BUFFER_SIZE = 100000
    BATCH_SIZE = 32
    GAMMA = 0.99
    TAU = 0.001     #Target Network HyperParameters
    LRA = 0.0001    #Learning rate for Actor
    LRC = 0.001     #Lerning rate for Critic

    action_dim = 3  #Steering/Acceleration/Brake
    state_dim = 29  #of sensors input

    np.random.seed(1337)

    vision = False

    EXPLORE = 100000.
    episode_count = 20
    max_steps = 10
    reward = 0
    done = False
    step = 0
    epsilon = 1
    indicator = 0

    #Tensorflow GPU optimization
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    from keras import backend as K
    K.set_session(sess)

    actor = ActorNetwork(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRA)
    critic = CriticNetwork(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRC)
    buff = ReplayBuffer(BUFFER_SIZE)    #Create replay buffer

    # Generate a Torcs environment
    env = TorcsEnv(vision=vision, throttle=True,gear_change=False)

    #Now load the weight
    print("load the weight")
    try:
        actor.model.load_weights("Myactormodel.h5")
        critic.model.load_weights("Mycriticmodel.h5")
        actor.target_model.load_weights("Myactormodel.h5")
        critic.target_model.load_weights("Mycriticmodel.h5")
        print("Weight load successfully")
    except:
        print("Cannot find the model weight")

    print("TORCS RL Start...")
    for i in range(episode_count):

        print("Episode : " + str(i) + " Replay Buffer " + str(buff.count()))

        if np.mod(i, 3) == 0:
            ob = env.reset(relaunch=True)   #relaunch TORCS every 3 episode because of the memory leak error
        else:
            ob = env.reset()

        s_t = np.hstack((ob.angle, ob.track, ob.trackPos, ob.speedX, ob.speedY,  ob.speedZ, ob.wheelSpinVel/100.0, ob.rpm))

        total_reward = 0.
        for j in range(max_steps):
            loss = 0
            epsilon -= 1.0 / EXPLORE
            a_t = np.zeros([1,action_dim])
            noise_t = np.zeros([1,action_dim])

            a_t_original = actor.model.predict(s_t.reshape(1, s_t.shape[0]))
            noise_t[0][0] = train_indicator * max(epsilon, 0) * Ornstein_Uhlenbeck(a_t_original[0][0],  0.0 , 0.60, 0.30)
            noise_t[0][1] = train_indicator * max(epsilon, 0) * Ornstein_Uhlenbeck(a_t_original[0][1],  0.5 , 1.00, 0.10)
            noise_t[0][2] = train_indicator * max(epsilon, 0) * Ornstein_Uhlenbeck(a_t_original[0][2], -0.1 , 1.00, 0.05)

            #The following code do the stochastic brake
            if random.random() <= 0.1:
                print("we apply the brakes here...")
                noise_t[0][2] = train_indicator * max(epsilon, 0) * Ornstein_Uhlenbeck(a_t_original[0][2],  0.2 , 1.00, 0.10)

            a_t[0][0] = a_t_original[0][0] + noise_t[0][0]
            a_t[0][1] = a_t_original[0][1] + noise_t[0][1]
            a_t[0][2] = a_t_original[0][2] + noise_t[0][2]

            ob, r_t, done, info = env.step(a_t[0])

            s_t1 = np.hstack((ob.angle, ob.track, ob.trackPos, ob.speedX, ob.speedY, ob.speedZ, ob.wheelSpinVel/100.0, ob.rpm))

            buff.add(s_t, a_t[0], r_t, s_t1, done)      #Add replay buffer

            #Do the batch update
            batch = buff.getBatch(BATCH_SIZE)
            states = np.asarray([e[0] for e in batch])
            actions = np.asarray([e[1] for e in batch])
            rewards = np.asarray([e[2] for e in batch])
            new_states = np.asarray([e[3] for e in batch])
            dones = np.asarray([e[4] for e in batch])
            y_t = np.asarray([e[1] for e in batch])

            target_q_values = critic.target_model.predict([new_states, actor.target_model.predict(new_states)])

            for k in range(len(batch)):
                if dones[k]:
                    y_t[k] = rewards[k]
                else:
                    y_t[k] = rewards[k] + GAMMA*target_q_values[k]

            if (train_indicator):
                loss += critic.model.train_on_batch([states,actions], y_t)
                a_for_grad = actor.model.predict(states)
                grads = critic.gradients(states, a_for_grad)
                actor.train(states, grads)
                actor.target_train()
                critic.target_train()

            total_reward += r_t
            s_t = s_t1

            print("Episode", i, "Step", step, "Action", a_t, "Reward", r_t, "Loss", loss)

            step += 1
            if done:
                break

        if np.mod(i, 3) == 0:
            if (train_indicator):
                print("Now we save model")
                actor.model.save_weights("Myactormodel.h5", overwrite=True)
                with open("Myactormodel.json", "w") as outfile:
                    json.dump(actor.model.to_json(), outfile)

                critic.model.save_weights("Mycriticmodel.h5", overwrite=True)
                with open("Mycriticmodel.json", "w") as outfile:
                    json.dump(critic.model.to_json(), outfile)

        print("TOTAL REWARD @ " + str(i) +"-th Episode  : Reward " + str(total_reward))
        print("Total Step: " + str(step))
        print("")

    env.end()  # This is for shutting down TORCS
    print("Finish.")

if __name__ == "__main__":
    playGame()


text:
<Configuration>
    <View>
        <Page name="PAGE-LoggedIn" document="CATALOG" title="Logged In">
            <Panel type="LIST">
                <Panel type="ROW" outcome="OUTCOME-GetFreshPlants">
                    <Field type="LABEL" label="Show Fresh Plants" />
                    <Field type="SUBLABEL" label="Needs the network" />
                </Panel>
                <Panel type="ROW" outcome="OUTCOME-Catalog">
                    <Field type="LABEL" label="Show Stale Plants" />
                    <Field type="SUBLABEL" label="Cached data (60s)" />
                </Panel>
                <Panel type="ROW" >
                    <Field type="BUTTON" label="Log off" outcome="OUTCOME-LogOff"/>
                </Panel>
            </Panel>
        </Page>
    </View>
</Configuration>


text:
namespace MPSig {
    namespace detail {
        class SearchPatternHexMatcher final : public SearchPatternBase {
        private:
            std::vector<std::pair<char, bool>> m_compiledPattern;
        public:
            SearchPatternHexMatcher(gsl::cstring_span<-1> hexPattern);

            virtual SearchPatternBase::ExecFirstResult<gsl_span_cit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const override;
            virtual SearchPatternBase::ExecFirstResult<gsl_span_crit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const override;

            virtual SearchPatternBase::ExecFirstResult<gsl_span_cit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const override;
            virtual SearchPatternBase::ExecFirstResult<gsl_span_crit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const override;

            virtual std::unique_ptr<SearchPatternBase> Clone() const override;
        };

    }
}

#endif


text:
'use strict';

var path = require('path');
var _ = require('lodash');

function requiredProcessEnv(name) {
  if(!process.env[name]) {
    throw new Error('You must set the ' + name + ' environment variable');
  }
  return process.env[name];
}

// All configurations will extend these options
// ============================================
var all = {
  env: process.env.NODE_ENV,

  // Root path of server
  root: path.normalize(__dirname + '/../../..'),

  // Server port
  port: process.env.PORT || 9000,

  // Server IP
  ip: process.env.IP || '0.0.0.0',

  // Should we populate the DB with sample data?
  seedDB: false,

  // Secret for session, you will want to change this and make it an environment variable
  secrets: {
    session: 'web-rtc-secret'
  },

  // List of user roles
  userRoles: ['guest', 'user', 'admin'],

  // MongoDB connection options
  mongo: {
    options: {
      db: {
        safe: true
      }
    }
  },

};

// Export the config object based on the NODE_ENV
// ==============================================
module.exports = _.merge(
  all,
  require('./' + process.env.NODE_ENV + '.js') || {});


text:
import sublime, sublime_plugin
import subprocess
import tempfile
import os
import sys

from PhpSimpleRefactor.PhpSimpleRefactorCommand import PhpSimpleRefactorBaseCommand

class PhpSimpleRefactorExtractMethodCommand(PhpSimpleRefactorBaseCommand):
	function_name = ''

	def process(self):
		sublime.active_window().show_input_panel('Function name', '', self.obtain_function_name, None, None)

	def obtain_function_name(self, functionName):
		self.function_name = functionName;
		self.on_filled_info()

	def get_command(self):
		settings = sublime.load_settings('PHPSimpleRefactor.sublime-settings')
		self.php_path = settings.get('php_path')
		self.refactor_path = settings.get('refactor_path')
		rows = ''.join([str(self.rowBegin), "-", str(self.rowEnd)])
		cmd = ''.join([self.php_path, ' "', self.refactor_path,'" ',  'extract-method', ' "', self.file_name, '" ', rows, ' ', self.function_name])
		print(cmd)
		return subprocess.Popen(cmd, shell=True, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)


text:
package net.lightbody.bmp.exception;

/**
 * Indicates that an error occurred while decompressing content.
 */
public class DecompressionException extends RuntimeException {
    private static final long serialVersionUID = 8666473793514307564L;

    public DecompressionException() {
    }

    public DecompressionException(String message) {
        super(message);
    }

    public DecompressionException(String message, Throwable cause) {
        super(message, cause);
    }

    public DecompressionException(Throwable cause) {
        super(cause);
    }
}