text:
using namespace std;
using namespace mfem;

double p_exact(const Vector &x);
void gradp_exact(const Vector &, Vector &);
double div_gradp_exact(const Vector &x);
void v_exact(const Vector &x, Vector &v);
void curlv_exact(const Vector &x, Vector &cv);

int dim;
double freq = 1.0, kappa;

int main(int argc, char *argv[])
{
   // 1. Parse command-line options.
   const char *mesh_file = "../data/beam-hex.mesh";
   int order = 1;
   int prob = 0;
   bool static_cond = false;
   bool pa = false;
   const char *device_config = "cpu";
   bool visualization = 1;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree).");
   args.AddOption(&prob, "-p", "--problem-type",
                  "Choose between 0: grad, 1: curl, 2: div");
   args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
                  "--no-static-condensation", "Enable static condensation.");
   args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
                  "--no-partial-assembly", "Enable Partial Assembly.");
   args.AddOption(&device_config, "-d", "--device",
                  "Device configuration string, see Device::Configure().");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");

   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);
   kappa = freq * M_PI;

   // 2. Enable hardware devices such as GPUs, and programming models such as
   //    CUDA, OCCA, RAJA and OpenMP based on command line options.
   Device device(device_config);
   device.Print();

   // 3. Read the mesh from the given mesh file. We can handle triangular,
   //    quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
   //    the same code.
   Mesh *mesh = new Mesh(mesh_file, 1, 1);
   dim = mesh->Dimension();
   int sdim = mesh->SpaceDimension();

   // 4. Refine the mesh to increase the resolution. In this example we do
   //    'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
   //    largest number that gives a final mesh with no more than 50,000
   //    elements.
   {
      int ref_levels = (int)floor(log(50000./mesh->GetNE())/log(2.)/dim);
      for (int l = 0; l < ref_levels; l++)
      {
         mesh->UniformRefinement();
      }
   }

   // 5. Define a finite element space on the mesh. Here we use Nedelec or
   //    Raviart-Thomas finite elements of the specified order.
   FiniteElementCollection *trial_fec = NULL;
   FiniteElementCollection *test_fec = NULL;

   if (prob == 0)
   {
      trial_fec = new H1_FECollection(order, dim);
      test_fec = new ND_FECollection(order, dim);
   }
   else if (prob == 1)
   {
      trial_fec = new ND_FECollection(order, dim);
      test_fec = new RT_FECollection(order-1, dim);
   }
   else
   {
      trial_fec = new RT_FECollection(order-1, dim);
      test_fec = new L2_FECollection(order-1, dim);
   }

   FiniteElementSpace trial_fes(mesh, trial_fec);
   FiniteElementSpace test_fes(mesh, test_fec);

   int trial_size = trial_fes.GetTrueVSize();
   int test_size = test_fes.GetTrueVSize();

   if (prob == 0)
   {
      cout << "Number of Nedelec finite element unknowns: " << test_size << endl;
      cout << "Number of H1 finite element unknowns: " << trial_size << endl;
   }
   else if (prob == 1)
   {
      cout << "Number of Nedelec finite element unknowns: " << trial_size << endl;
      cout << "Number of Raviart-Thomas finite element unknowns: " << test_size <<
           endl;
   }
   else
   {
      cout << "Number of Raviart-Thomas finite element unknowns: "
           << trial_size << endl;
      cout << "Number of L2 finite element unknowns: " << test_size << endl;
   }

   // 6. Define the solution vector as a finite element grid function
   //    corresponding to the trial fespace.
   GridFunction gftest(&test_fes);
   GridFunction gftrial(&trial_fes);
   GridFunction x(&test_fes);
   FunctionCoefficient p_coef(p_exact);
   VectorFunctionCoefficient gradp_coef(sdim, gradp_exact);
   VectorFunctionCoefficient v_coef(sdim, v_exact);
   VectorFunctionCoefficient curlv_coef(sdim, curlv_exact);
   FunctionCoefficient divgradp_coef(div_gradp_exact);

   if (prob == 0)
   {
      gftrial.ProjectCoefficient(p_coef);
   }
   else if (prob == 1)
   {
      gftrial.ProjectCoefficient(v_coef);
   }
   else
   {
      gftrial.ProjectCoefficient(gradp_coef);
   }

   gftrial.SetTrueVector();
   gftrial.SetFromTrueVector();

   // 7. Set up the bilinear forms for L2 projection.
   ConstantCoefficient one(1.0);
   BilinearForm a(&test_fes);
   MixedBilinearForm a_mixed(&trial_fes, &test_fes);
   if (pa)
   {
      a.SetAssemblyLevel(AssemblyLevel::PARTIAL);
      a_mixed.SetAssemblyLevel(AssemblyLevel::PARTIAL);
   }

   if (prob == 0)
   {
      a.AddDomainIntegrator(new VectorFEMassIntegrator(one));
      a_mixed.AddDomainIntegrator(new MixedVectorGradientIntegrator(one));
   }
   else if (prob == 1)
   {
      a.AddDomainIntegrator(new VectorFEMassIntegrator(one));
      a_mixed.AddDomainIntegrator(new MixedVectorCurlIntegrator(one));
   }
   else
   {
      a.AddDomainIntegrator(new MassIntegrator(one));
      a_mixed.AddDomainIntegrator(new VectorFEDivergenceIntegrator(one));
   }

   // 8. Assemble the bilinear form and the corresponding linear system,
   //    applying any necessary transformations such as: eliminating boundary
   //    conditions, applying conforming constraints for non-conforming AMR,
   //    static condensation, etc.
   if (static_cond) { a.EnableStaticCondensation(); }

   a.Assemble();
   if (!pa) { a.Finalize(); }

   a_mixed.Assemble();
   if (!pa) { a_mixed.Finalize(); }

   if (pa)
   {
      a_mixed.Mult(gftrial, x);
   }
   else
   {
      SparseMatrix& mixed = a_mixed.SpMat();
      mixed.Mult(gftrial, x);
   }

   // 9. Define and apply a PCG solver for Ax = b with Jacobi preconditioner.
   {
      GridFunction rhs(&test_fes);
      rhs = x;
      x = 0.0;

      CGSolver cg;
      cg.SetRelTol(1e-12);
      cg.SetMaxIter(1000);
      cg.SetPrintLevel(1);
      if (pa)
      {
         Array<int> ess_tdof_list; // empty
         OperatorJacobiSmoother Jacobi(a, ess_tdof_list);

         cg.SetOperator(a);
         cg.SetPreconditioner(Jacobi);
         cg.Mult(rhs, x);
      }
      else
      {
         SparseMatrix& Amat = a.SpMat();
         DSmoother Jacobi(Amat);

         cg.SetOperator(Amat);
         cg.SetPreconditioner(Jacobi);
         cg.Mult(rhs, x);
      }
   }

   // 10. Compute the same field by applying a DiscreteInterpolator.
   GridFunction discreteInterpolant(&test_fes);
   DiscreteLinearOperator dlo(&trial_fes, &test_fes);
   if (prob == 0)
   {
      dlo.AddDomainInterpolator(new GradientInterpolator());
   }
   else if (prob == 1)
   {
      dlo.AddDomainInterpolator(new CurlInterpolator());
   }
   else
   {
      dlo.AddDomainInterpolator(new DivergenceInterpolator());
   }

   dlo.Assemble();
   dlo.Mult(gftrial, discreteInterpolant);

   // 11. Compute the projection of the exact field.
   GridFunction exact_proj(&test_fes);
   if (prob == 0)
   {
      exact_proj.ProjectCoefficient(gradp_coef);
   }
   else if (prob == 1)
   {
      exact_proj.ProjectCoefficient(curlv_coef);
   }
   else
   {
      exact_proj.ProjectCoefficient(divgradp_coef);
   }

   exact_proj.SetTrueVector();
   exact_proj.SetFromTrueVector();

   // 12. Compute and print the L_2 norm of the error.
   if (prob == 0)
   {
      double errSol = x.ComputeL2Error(gradp_coef);
      double errInterp = discreteInterpolant.ComputeL2Error(gradp_coef);
      double errProj = exact_proj.ComputeL2Error(gradp_coef);

      cout << "\n Solution of (E_h,v) = (grad p_h,v) for E_h and v in H(curl): "
           "|| E_h - grad p ||_{L_2} = " << errSol << '\n' << endl;
      cout << " Gradient interpolant E_h = grad p_h in H(curl): || E_h - grad p"
           " ||_{L_2} = " << errInterp << '\n' << endl;
      cout << " Projection E_h of exact grad p in H(curl): || E_h - grad p "
           "||_{L_2} = " << errProj << '\n' << endl;
   }
   else if (prob == 1)
   {
      double errSol = x.ComputeL2Error(curlv_coef);
      double errInterp = discreteInterpolant.ComputeL2Error(curlv_coef);
      double errProj = exact_proj.ComputeL2Error(curlv_coef);

      cout << "\n Solution of (E_h,w) = (curl v_h,w) for E_h and w in H(div): "
           "|| E_h - curl v ||_{L_2} = " << errSol << '\n' << endl;
      cout << " Curl interpolant E_h = curl v_h in H(div): || E_h - curl v "
           "||_{L_2} = " << errInterp << '\n' << endl;
      cout << " Projection E_h of exact curl v in H(div): || E_h - curl v "
           "||_{L_2} = " << errProj << '\n' << endl;
   }
   else
   {
      int order_quad = max(2, 2*order+1);
      const IntegrationRule *irs[Geometry::NumGeom];
      for (int i=0; i < Geometry::NumGeom; ++i)
      {
         irs[i] = &(IntRules.Get(i, order_quad));
      }

      double errSol = x.ComputeL2Error(divgradp_coef, irs);
      double errInterp = discreteInterpolant.ComputeL2Error(divgradp_coef, irs);
      double errProj = exact_proj.ComputeL2Error(divgradp_coef, irs);

      cout << "\n Solution of (f_h,q) = (div v_h,q) for f_h and q in L_2: "
           "|| f_h - div v ||_{L_2} = " << errSol << '\n' << endl;
      cout << " Divergence interpolant f_h = div v_h in L_2: || f_h - div v "
           "||_{L_2} = " << errInterp << '\n' << endl;
      cout << " Projection f_h of exact div v in L_2: || f_h - div v "
           "||_{L_2} = " << errProj << '\n' << endl;
   }

   // 13. Save the refined mesh and the solution. This output can be viewed
   //     later using GLVis: "glvis -m refined.mesh -g sol.gf".
   ofstream mesh_ofs("refined.mesh");
   mesh_ofs.precision(8);
   mesh->Print(mesh_ofs);
   ofstream sol_ofs("sol.gf");
   sol_ofs.precision(8);
   x.Save(sol_ofs);

   // 14. Send the solution by socket to a GLVis server.
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock.precision(8);
      sol_sock << "solution\n" << *mesh << x << flush;
   }

   // 15. Free the used memory.
   delete trial_fec;
   delete test_fec;
   delete mesh;

   return 0;
}

double p_exact(const Vector &x)
{
   if (dim == 3)
   {
      return sin(x(0)) * sin(x(1)) * sin(x(2));
   }
   else if (dim == 2)
   {
      return sin(x(0)) * sin(x(1));
   }

   return 0.0;
}

void gradp_exact(const Vector &x, Vector &f)
{
   if (dim == 3)
   {
      f(0) = cos(x(0)) * sin(x(1)) * sin(x(2));
      f(1) = sin(x(0)) * cos(x(1)) * sin(x(2));
      f(2) = sin(x(0)) * sin(x(1)) * cos(x(2));
   }
   else
   {
      f(0) = cos(x(0)) * sin(x(1));
      f(1) = sin(x(0)) * cos(x(1));
      if (x.Size() == 3) { f(2) = 0.0; }
   }
}

double div_gradp_exact(const Vector &x)
{
   if (dim == 3)
   {
      return -3.0 * sin(x(0)) * sin(x(1)) * sin(x(2));
   }
   else if (dim == 2)
   {
      return -2.0 * sin(x(0)) * sin(x(1));
   }

   return 0.0;
}

void v_exact(const Vector &x, Vector &v)
{
   if (dim == 3)
   {
      v(0) = sin(kappa * x(1));
      v(1) = sin(kappa * x(2));
      v(2) = sin(kappa * x(0));
   }
   else
   {
      v(0) = sin(kappa * x(1));
      v(1) = sin(kappa * x(0));
      if (x.Size() == 3) { v(2) = 0.0; }
   }
}

void curlv_exact(const Vector &x, Vector &cv)
{
   if (dim == 3)
   {
      cv(0) = -kappa * cos(kappa * x(2));
      cv(1) = -kappa * cos(kappa * x(0));
      cv(2) = -kappa * cos(kappa * x(1));
   }
   else
   {
      cv = 0.0;
   }
}


text:
Coffee clicker is a clicker game where you can buy programmers with coffee to make coffee for you!

Version 0.2
- Changed css to scss.
- Made the website more cross-browser.
- Put the js code inside function.

Version 0.1
- Added big coffee image to click.
- Added Shop.
- Added "people" inside shop that you can "hire".
- Added 3 upgrades per person.
- Added an upgrade: double/triple/quadruple points on click.
- Added auto comma every thousand.

redpajama_set_name: RedPajamaGithub


text:
package dto.FeaturedGames;

import java.io.Serializable;

public class Mastery implements Serializable {

	private static final long serialVersionUID = 5693570765958275483L;
	private int rank;
	private long masteryId;

	public int getRank() {
		return rank;
	}

	public long getMasteryId() {
		return masteryId;
	}
}


text:
package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;

import com.github.jknack.handlebars.Options;
import com.github.tomakehurst.wiremock.common.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;

import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;
import static javax.xml.xpath.XPathConstants.NODE;

/**
 * This class uses javax.xml.xpath.* for reading a xml via xPath so that the result can be used for response
 * templating.
 */
public class HandlebarsXPathHelper extends HandlebarsHelper<String> {

    @Override
    public Object apply(final String inputXml, final Options options) throws IOException {
        if (inputXml == null ) {
            return "";
        }

        if (options.param(0, null) == null) {
            return handleError("The XPath expression cannot be empty");
        }

        final String xPathInput = options.param(0);

        Document doc;
        try (final StringReader reader = new StringReader(inputXml)) {
            InputSource source = new InputSource(reader);
            final DocumentBuilderFactory factory = Xml.newDocumentBuilderFactory();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(source);
        } catch (SAXException se) {
            return handleError(inputXml + " is not valid XML");
        } catch (ParserConfigurationException e) {
            return throwUnchecked(e, Object.class);
        }

        try {
            final XPathFactory xPathfactory = XPathFactory.newInstance();
            final XPath xpath = xPathfactory.newXPath();

            Node node = (Node) xpath.evaluate(getXPathPrefix() + xPathInput, doc, NODE);

            if (node == null) {
                return "";
            }

            return Xml.toStringValue(node);
        } catch (XPathExpressionException e) {
            return handleError(xPathInput + " is not a valid XPath expression", e);
        }
    }

    /**
     * No prefix by default. It allows to extend this class with a specified prefix. Just overwrite this method to do
     * so.
     *
     * @return a prefix which will be applied before the specified xpath.
     */
    protected String getXPathPrefix() {
        return "";
    }
}


text:
import { URL_SIGN_IN_CALLBACK_REL } from './config'

// TODO replace the URLs in index.html dynamically
const URL_SIGN_IN = 'twitter-sign-in'

const URL_SIGN_IN_CALLBACK_ABS =
window.location.protocol + '//' + window.location.host + URL_SIGN_IN_CALLBACK_REL
const URL_SIGN_IN_CALLBACK = URL_SIGN_IN_CALLBACK_REL.replace(/^\//, '')

const URL_JUST_SIGNED_IN_REL = '/just-signed-in'
const URL_JUST_SIGNED_IN_ABS =
window.location.protocol + '//' + window.location.host + URL_JUST_SIGNED_IN_REL

// const URL_JUST_SIGNED_IN = URL_JUST_SIGNED_IN_REL.replace(/^\//, '')
export const URL_JUST_SIGNED_IN = 'just-signed-in' // TODO fix this
export const URL_NEW_STREET = 'new'
export const URL_NEW_STREET_COPY_LAST = 'copy-last'
export const URL_GLOBAL_GALLERY = 'gallery'
const URL_LOCALES = 'locales'
export const URL_ERROR = 'error'
export const URL_NO_USER = '-'
export const URL_HELP = 'help'

export const URL_ERROR_TWITTER_ACCESS_DENIED = 'twitter-access-denied'
export const URL_ERROR_NO_TWITTER_REQUEST_TOKEN = 'no-twitter-request-token'
export const URL_ERROR_NO_TWITTER_ACCESS_TOKEN = 'no-twitter-access-token'
export const URL_ERROR_AUTHENTICATION_API_PROBLEM = 'authentication-api-problem'

const URL_EXAMPLE_STREET = 'streetmix/7'

export const URL_SIGN_IN_REDIRECT = URL_SIGN_IN + '?callbackUri=' +
  URL_SIGN_IN_CALLBACK_ABS + '&redirectUri=' + URL_JUST_SIGNED_IN_ABS

// Since URLs like "streetmix.net/new" are reserved, but we still want
// @new to be able to use Streetmix, we prefix any reserved URLs with ~
export const RESERVED_URLS =
[URL_SIGN_IN, URL_SIGN_IN_CALLBACK,
  URL_NEW_STREET, URL_NEW_STREET_COPY_LAST,
  URL_JUST_SIGNED_IN,
  URL_LOCALES,
  URL_HELP, URL_GLOBAL_GALLERY, URL_ERROR, 'streets']
export const URL_RESERVED_PREFIX = '~'

export function goReload () {
  window.location.reload()
}

export function goHome () {
  window.location.href = '/'
}

export function goNewStreet (sameWindow) {
  if (sameWindow) {
    window.location.replace('/' + URL_NEW_STREET)
  } else {
    window.location.href = '/' + URL_NEW_STREET
  }
}

export function goExampleStreet () {
  window.location.href = '/' + URL_EXAMPLE_STREET
}

// NOTE: This does not seem to be used anywhere
export function goCopyLastStreet () {
  window.location.href = '/' + URL_NEW_STREET_COPY_LAST
}

export function goSignIn () {
  window.location.href = '/' + URL_SIGN_IN_REDIRECT
}


text:
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameInventorySystemEditor.h"
#include "GameInventorySystemEditorPrivatePCH.h"

class FGameInventorySystemEditor : public IGameInventorySystemEditor
{
	/** IModuleInterface implementation */
	virtual void StartupModule() override;
	virtual void ShutdownModule() override;
};

IMPLEMENT_MODULE(FGameInventorySystemEditor, GameInventorySystemEditor)

void FGameInventorySystemEditor::StartupModule()
{

}

void FGameInventorySystemEditor::ShutdownModule()
{

}


text:
import {createIframePromise} from '../../../../testing/iframe';
import '../amp-video';
import * as sinon from 'sinon';

const TAG = 'amp-video';

describe(TAG, () => {

  let sandbox;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
  });

  afterEach(() => {
    sandbox.restore();
  });

  function getFooVideoSrc(mediatype) {
    return '//someHost/foo.' + mediatype.slice(mediatype.indexOf('/') + 1); // assumes no optional params
  }

  function getVideo(attributes, children, opt_beforeLayoutCallback) {
    return createIframePromise(
        true, opt_beforeLayoutCallback).then(iframe => {
          const v = iframe.doc.createElement(TAG);
          for (const key in attributes) {
            v.setAttribute(key, attributes[key]);
          }
          if (children != null) {
            for (const key in children) {
              v.appendChild(children[key]);
            }
          }
          return iframe.addElement(v);
        });
  }

  it('should load a video', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
    }).then(v => {
      const preloadSpy = sandbox.spy(v.implementation_.preconnect, 'url');
      v.implementation_.preconnectCallback();
      preloadSpy.should.have.been.calledWithExactly('video.mp4', undefined);
      const video = v.querySelector('video');
      expect(video.tagName).to.equal('VIDEO');
      expect(video.getAttribute('src')).to.equal('video.mp4');
      expect(video.hasAttribute('controls')).to.be.false;
    });
  });

  it('should load a video', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'controls': '',
      'muted': '',
      'loop': '',
    }).then(v => {
      const preloadSpy = sandbox.spy(v.implementation_.preconnect, 'url');
      v.implementation_.preconnectCallback();
      preloadSpy.should.have.been.calledWithExactly('video.mp4', undefined);
      const video = v.querySelector('video');
      expect(video.tagName).to.equal('VIDEO');
      expect(video.hasAttribute('controls')).to.be.true;
      expect(video.hasAttribute('loop')).to.be.true;
      // autoplay is never propagated to the video element
      expect(video.hasAttribute('autoplay')).to.be.false;
      // muted is a deprecated attribute
      expect(video.hasAttribute('muted')).to.be.false;
    });
  });

  it('should load a video with source children', () => {
    const sources = [];
    const mediatypes = ['video/ogg', 'video/mp4', 'video/webm'];
    for (let i = 0; i < mediatypes.length; i++) {
      const mediatype = mediatypes[i];
      const source = document.createElement('source');
      source.setAttribute('src', getFooVideoSrc(mediatype));
      source.setAttribute('type', mediatype);
      sources.push(source);
    }
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'controls': '',
      'autoplay': '',
      'muted': '',
      'loop': '',
    }, sources).then(v => {
      const preloadSpy = sandbox.spy(v.implementation_.preconnect, 'url');
      v.implementation_.preconnectCallback();
      preloadSpy.should.have.been.calledWithExactly('video.mp4', undefined);
      const video = v.querySelector('video');
      // check that the source tags were propogated
      expect(video.children.length).to.equal(mediatypes.length);
      for (let i = 0; i < mediatypes.length; i++) {
        const mediatype = mediatypes[i];
        expect(video.children.item(i).tagName).to.equal('SOURCE');
        expect(video.children.item(i).hasAttribute('src')).to.be.true;
        expect(video.children.item(i).getAttribute('src'))
            .to.equal(getFooVideoSrc(mediatype));
        expect(video.children.item(i).getAttribute('type')).to.equal(mediatype);
      }
    });
  });

  it('should not load a video with http source children', () => {
    const sources = [];
    const mediatypes = ['video/ogg', 'video/mp4', 'video/webm'];
    for (let i = 0; i < mediatypes.length; i++) {
      const mediatype = mediatypes[i];
      const source = document.createElement('source');
      source.setAttribute('src', 'http:' + getFooVideoSrc(mediatype));
      source.setAttribute('type', mediatype);
      sources.push(source);
    }
    return expect(getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'controls': '',
      'autoplay': '',
      'muted': '',
      'loop': '',
    }, sources)).to.be.rejectedWith(/start with/);
  });

  it('should set poster and controls in prerender mode', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'poster': 'img.png',
      'controls': '',
    }, null, function(element) {
      // Should set appropriate attributes in buildCallback
      const video = element.querySelector('video');
      expect(video.getAttribute('poster')).to.equal('img.png');
      expect(video.getAttribute('controls')).to.exist;
      expect(video.getAttribute('playsinline')).to.exist;
      expect(video.getAttribute('webkit-playsinline')).to.exist;
    }).then(v => {
      // Same attributes should still be present in layoutCallback.
      const video = v.querySelector('video');
      expect(video.tagName).to.equal('VIDEO');
      expect(video.getAttribute('poster')).to.equal('img.png');
      expect(video.getAttribute('controls')).to.exist;
    });
  });

  it('should not set src or preload in prerender mode', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'preload': 'auto',
      'poster': 'img.png',
    }, null, function(element) {
      const video = element.querySelector('video');
      expect(video.getAttribute('preload')).to.equal('none');
      expect(video.hasAttribute('src')).to.be.false;
    }).then(v => {
      // Should set appropriate attributes in layoutCallback.
      const video = v.querySelector('video');
      expect(video.tagName).to.equal('VIDEO');
      expect(video.getAttribute('preload')).to.equal('auto');
    });
  });

  it('should remove preload attribute when not provided', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'poster': 'img.png',
    }, null, function(element) {
      const video = element.querySelector('video');
      expect(video.getAttribute('preload')).to.equal('none');
      expect(video.getAttribute('poster')).to.equal('img.png');
      expect(video.hasAttribute('src')).to.be.false;
    }).then(v => {
      // Should set appropriate attributes in layoutCallback.
      const video = v.querySelector('video');
      expect(video.tagName).to.equal('VIDEO');
      expect(video.hasAttribute('preload')).to.be.false;
      expect(video.getAttribute('poster')).to.equal('img.png');
    });
  });

  it('should not load a video with source children in prerender mode', () => {
    const sources = [];
    const mediatypes = ['video/ogg', 'video/mp4', 'video/webm'];
    for (let i = 0; i < mediatypes.length; i++) {
      const mediatype = mediatypes[i];
      const source = document.createElement('source');
      source.setAttribute('src', getFooVideoSrc(mediatype));
      source.setAttribute('type', mediatype);
      sources.push(source);
    }
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'controls': '',
      'autoplay': '',
      'muted': '',
      'loop': '',
    }, sources, function(element) {
      const video = element.querySelector('video');
      expect(video.children.length).to.equal(0);
    }).then(v => {
      // Should add attributes and source children in layoutCallback.
      const video = v.querySelector('video');
      // check that the source tags were propogated
      expect(video.children.length).to.equal(mediatypes.length);
      for (let i = 0; i < mediatypes.length; i++) {
        const mediatype = mediatypes[i];
        expect(video.children.item(i).tagName).to.equal('SOURCE');
        expect(video.children.item(i).hasAttribute('src')).to.be.true;
        expect(video.children.item(i).getAttribute('src'))
            .to.equal(getFooVideoSrc(mediatype));
        expect(video.children.item(i).getAttribute('type')).to.equal(mediatype);
      }
    });
  });

  it('should set src and preload in non-prerender mode', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'preload': 'auto',
      'poster': 'img.png',
    }, null, function(element) {
      const video = element.querySelector('video');
      expect(video.getAttribute('preload')).to.equal('none');
      expect(video.getAttribute('poster')).to.equal('img.png');
      expect(video.hasAttribute('src')).to.be.false;
    }).then(v => {
      const video = v.querySelector('video');
      expect(video.tagName).to.equal('VIDEO');
      expect(video.getAttribute('preload')).to.equal('auto');
      expect(video.getAttribute('poster')).to.equal('img.png');
    });
  });

  it('should pause the video when document inactive', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
    }).then(v => {
      const impl = v.implementation_;
      const video = v.querySelector('video');
      sandbox.spy(video, 'pause');
      impl.pauseCallback();
      expect(video.pause.called).to.be.true;
    });
  });

  it('should fallback if video element is not supported', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
    }, null, function(element) {
      const impl = element.implementation_;
      sandbox.stub(impl, 'isVideoSupported_').returns(false);
      sandbox.spy(impl, 'toggleFallback');
    }).then(v => {
      const impl = v.implementation_;
      expect(impl.toggleFallback.called).to.be.true;
      expect(impl.toggleFallback.calledWith(true)).to.be.true;
    });
  });

  it('play() should not log promise rejections', () => {
    const playPromise = Promise.reject('The play() request was interrupted');
    const catchSpy = sandbox.spy(playPromise, 'catch');
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
    }, null, function(element) {
      const impl = element.implementation_;
      sandbox.stub(impl.video_, 'play').returns(playPromise);
      impl.play();
    }).then(() => {
      expect(catchSpy.called).to.be.true;
    });
  });

  it('should propagate ARIA attributes', () => {
    return getVideo({
      src: 'video.mp4',
      width: 160,
      height: 90,
      'aria-label': 'Hello',
      'aria-labelledby': 'id2',
      'aria-describedby': 'id3',
    }).then(v => {
      const video = v.querySelector('video');
      expect(video.getAttribute('aria-label')).to.equal('Hello');
      expect(video.getAttribute('aria-labelledby')).to.equal('id2');
      expect(video.getAttribute('aria-describedby')).to.equal('id3');
    });
  });
});


text:
/**
 * Toggle the specified class(es).
 * @method toggleClass
 * @memberof Grindstone
 * @param {string} cls className
 * @returns {NodeList} collection
 * @example
 * $('#selector').toggleClass('example');
 * $('#selector').toggleClass('one two');
 */

const toggleClass = function (cls) {
  const classes = cls.split(' ');
  this.each(function () {
    classes.forEach((clsName) => {
      this.classList.toggle(clsName);
    });
  });
  return this;
};

$.fn.toggleClass = toggleClass;

// @if !NODE_ENV='production'
module.exports = toggleClass;
// @endif


text:
<?php
namespace Modules;

use Phalcon\Loader;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View;

class Backend implements ModuleDefinitionInterface
{

    /**
     * Current module name
     * @var const
     */
    const MODULE = 'Backend';

    /**
     * Global config
     * @var bool | array
     */
    protected $_config = false;

    /**
     * Configuration init
     */
    public function __construct()
    {

        $this->_config = \Phalcon\DI::getDefault()->get('config');
    }

    /**
     * Register the autoloader specific to the current module
     * @access public
     * @return \Phalcon\Loader\Loader()
     */
    public function registerAutoloaders()
    {
        $loader = new Loader();

        $loader->registerNamespaces([
            'Modules\Backend\Controllers' => $this->_config['application']['controllersBack'],
            'Modules\Backend\Forms' => $this->_config['application']['formsBack'],
            'Models' => $this->_config['application']['modelsDir'],
            'Helpers' => $this->_config['application']['helpersDir'],
            'Libraries' => $this->_config['application']['libraryDir'],
            'Plugins' => $this->_config['application']['pluginsDir'],
        ]);

        $loader->register();
    }

    /**
     * Registration services for specific module
     * @param \Phalcon\DI $di
     * @access public
     * @return mixed
     */
    public function registerServices($di)
    {
        // Dispatch register
        $di->set('dispatcher', function () use ($di) {

            // Creating an event manager
            $eventsManager = $di->getShared('eventsManager');

            $dispatcher = new \Phalcon\Mvc\Dispatcher();
            $dispatcher->setEventsManager($eventsManager);
            $dispatcher->setDefaultNamespace('Modules\\' . self::MODULE . '\Controllers');
            return $dispatcher;

        }, true);

        // Database connection is created based in the parameters defined in the configuration file

        $di->set('db', function () {

            try {
                $connect = new \Phalcon\Db\Adapter\Pdo\Mysql([
                    "host" => $this->_config->database->host,
                    "username" => $this->_config->database->username,
                    "password" => $this->_config->database->password,
                    "dbname" => $this->_config->database->dbname,
                    "persistent" => $this->_config->database->persistent,
                    "options" => [
                        \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '{$this->_config->database->charset}'",
                        \PDO::ATTR_CASE => \PDO::CASE_LOWER,
                        \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
                    ]
                ]);
                return $connect;
            }
            catch (\PDOException $e) {
                echo $e->getMessage();
            }

        }, true);

        // Registration of component representations (Views)

        $di->set('view', function () {
            $view = new View();
            $view->setViewsDir($this->_config['application']['viewsBack'])
                ->setMainView('auth-layout')
                ->setPartialsDir('partials');
            return $view;
        });

        require_once APP_PATH . '/Modules/' . self::MODULE . '/config/services.php';

        if (APPLICATION_ENV === 'development') {

            // share develop sidebar
            (new \Plugins\Debugger\Develop($di));

            // share Fabfuel topbar
            $profiler = new \Fabfuel\Prophiler\Profiler();
            $di->setShared('profiler', $profiler);

            $pluginManager = new \Fabfuel\Prophiler\Plugin\Manager\Phalcon($profiler);
            $pluginManager->register();

        }

        return;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using URSA.Security;
using URSA.Web.Http;

namespace URSA.Web
{
    /// Describes a request.
    public interface IRequestInfo
    {
        /// Gets a value indicating whether the output can be provided by any of the converters available.
        bool OutputNeutral { get; }

        /// Gets the request headers.
        IDictionary<string, string> Headers { get; }

        /// Gets the body of the request.
        Stream Body { get; }

        /// Gets the URL of the request.
        Url Url { get; }

        /// Gets or sets the identity of this request.
        /// <exception cref="ArgumentNullException">Thrown when setting a null value.</exception>
        IClaimBasedIdentity Identity { get; set; }
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/mysite.com/public/application/libraries/swiftmailer/classes/Swift/Plugins/Decorator</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../../../../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../../../../../css/style.css" rel="stylesheet">

/var/www/mysite.com/public/application

libraries

swiftmailer

classes

Swift

Plugins

Decorator

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

           100.00% covered (success)

100.00%

0 / 0

           100.00% covered (success)

100.00%

0 / 0

           100.00% covered (success)

0 / 0

       Replacements.php

           100.00% covered (success)

100.00%

0 / 0

           100.00% covered (success)

100.00%

0 / 0

           100.00% covered (success)

0 / 0

Legend

     Low: 0% to 50%
     Medium: 50% to 90%
     High: 90% to 100%

     Generated by PHP_CodeCoverage 3.3.1 using PHP 5.6.21-1+donate.sury.org~trusty+1 and PHPUnit 5.3.2 at Thu May 12 13:04:40 EEST 2016.


text:
package com.cinchapi.concourse.shell;

/**
 * An exception that indicates that the evaluation of some input has caused the
 * program to crash.
 *
 * @author Jeff Nelson
 */
@SuppressWarnings("serial")
class ProgramCrash extends IrregularEvaluationResult {

    /**
     * Construct a new instance.
     *
     * @param message
     */
    public ProgramCrash(String message) {
        super(message);
    }

}


text:
it("should resolve aliased loader module with query", function() {
	var foo = require('./a');

	expect(foo).toBe("someMessage");
});

it("should favor explicit loader query over aliased query (options in rule)", function() {
	var foo = require('./b');

	expect(foo).toBe("someOtherMessage");
});

it("should favor explicit loader query over aliased query (inline query in rule)", function() {
	var foo = require('./b2');

	expect(foo).toBe("someOtherMessage");
});

it("should favor explicit loader query over aliased query (inline query in rule.use)", function() {
	var foo = require('./b3');

	expect(foo).toBe("someOtherMessage");
});


text:
using System;

namespace Tau.Core
{
	public class DoubleCriticalSpringDamperCurve : ITimeCurve
	{
		public double Interpolate (double time)
		{
			if (time <= 0.5) {
				var adjusted = time * 2;
				return (2.0 / (ExponentialDecay (adjusted, 3) + 1)) - 1;
			} else {
				var adjusted = (time - 0.5) * 2;
				return ExponentialDecay (adjusted, 2);
			}
		}

		double ExponentialDecay (double input, double ratio)
		{
			return (1 - input) * Math.Exp (-ratio * input);
		}
	}
}


text:
package cluster // import "github.com/docker/docker/daemon/cluster"

import (
	"context"
	"fmt"
	"path/filepath"
	"strings"
	"sync"
	"time"

	types "github.com/docker/docker/api/types/swarm"
	"github.com/docker/docker/daemon/cluster/executor/container"
	lncluster "github.com/docker/libnetwork/cluster"
	swarmapi "github.com/docker/swarmkit/api"
	swarmallocator "github.com/docker/swarmkit/manager/allocator/cnmallocator"
	swarmnode "github.com/docker/swarmkit/node"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// nodeRunner implements a manager for continuously running swarmkit node, restarting them with backoff delays if needed.
type nodeRunner struct {
	nodeState
	mu             sync.RWMutex
	done           chan struct{} // closed when swarmNode exits
	ready          chan struct{} // closed when swarmNode becomes active
	reconnectDelay time.Duration
	config         nodeStartConfig

	repeatedRun     bool
	cancelReconnect func()
	stopping        bool
	cluster         *Cluster // only for accessing config helpers, never call any methods. TODO: change to config struct
}

// nodeStartConfig holds configuration needed to start a new node. Exported
// fields of this structure are saved to disk in json. Unexported fields
// contain data that shouldn't be persisted between daemon reloads.
type nodeStartConfig struct {
	// LocalAddr is this machine's local IP or hostname, if specified.
	LocalAddr string
	// RemoteAddr is the address that was given to "swarm join". It is used
	// to find LocalAddr if necessary.
	RemoteAddr string
	// ListenAddr is the address we bind to, including a port.
	ListenAddr string
	// AdvertiseAddr is the address other nodes should connect to,
	// including a port.
	AdvertiseAddr string
	// DataPathAddr is the address that has to be used for the data path
	DataPathAddr string
	// DefaultAddressPool contains list of subnets
	DefaultAddressPool []string
	// SubnetSize contains subnet size of DefaultAddressPool
	SubnetSize uint32
	// DataPathPort contains Data path port (VXLAN UDP port) number that is used for data traffic.
	DataPathPort uint32
	// JoinInProgress is set to true if a join operation has started, but
	// not completed yet.
	JoinInProgress bool

	joinAddr        string
	forceNewCluster bool
	joinToken       string
	lockKey         []byte
	autolock        bool
	availability    types.NodeAvailability
}

func (n *nodeRunner) Ready() chan error {
	c := make(chan error, 1)
	n.mu.RLock()
	ready, done := n.ready, n.done
	n.mu.RUnlock()
	go func() {
		select {
		case <-ready:
		case <-done:
		}
		select {
		case <-ready:
		default:
			n.mu.RLock()
			c <- n.err
			n.mu.RUnlock()
		}
		close(c)
	}()
	return c
}

func (n *nodeRunner) Start(conf nodeStartConfig) error {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.reconnectDelay = initialReconnectDelay

	return n.start(conf)
}

func (n *nodeRunner) start(conf nodeStartConfig) error {
	var control string
	if isWindows {
		control = `\\.\pipe\` + controlSocket
	} else {
		control = filepath.Join(n.cluster.runtimeRoot, controlSocket)
	}

	joinAddr := conf.joinAddr
	if joinAddr == "" && conf.JoinInProgress {
		// We must have been restarted while trying to join a cluster.
		// Continue trying to join instead of forming our own cluster.
		joinAddr = conf.RemoteAddr
	}

	// Hostname is not set here. Instead, it is obtained from
	// the node description that is reported periodically
	swarmnodeConfig := swarmnode.Config{
		ForceNewCluster:    conf.forceNewCluster,
		ListenControlAPI:   control,
		ListenRemoteAPI:    conf.ListenAddr,
		AdvertiseRemoteAPI: conf.AdvertiseAddr,
		NetworkConfig: &swarmallocator.NetworkConfig{
			DefaultAddrPool: conf.DefaultAddressPool,
			SubnetSize:      conf.SubnetSize,
			VXLANUDPPort:    conf.DataPathPort,
		},
		JoinAddr:  joinAddr,
		StateDir:  n.cluster.root,
		JoinToken: conf.joinToken,
		Executor: container.NewExecutor(
			n.cluster.config.Backend,
			n.cluster.config.PluginBackend,
			n.cluster.config.ImageBackend,
			n.cluster.config.VolumeBackend,
		),
		HeartbeatTick: n.cluster.config.RaftHeartbeatTick,
		// Recommended value in etcd/raft is 10 x (HeartbeatTick).
		// Lower values were seen to have caused instability because of
		// frequent leader elections when running on flakey networks.
		ElectionTick:     n.cluster.config.RaftElectionTick,
		UnlockKey:        conf.lockKey,
		AutoLockManagers: conf.autolock,
		PluginGetter:     n.cluster.config.Backend.PluginGetter(),
	}
	if conf.availability != "" {
		avail, ok := swarmapi.NodeSpec_Availability_value[strings.ToUpper(string(conf.availability))]
		if !ok {
			return fmt.Errorf("invalid Availability: %q", conf.availability)
		}
		swarmnodeConfig.Availability = swarmapi.NodeSpec_Availability(avail)
	}
	node, err := swarmnode.New(&swarmnodeConfig)
	if err != nil {
		return err
	}
	if err := node.Start(context.Background()); err != nil {
		return err
	}

	n.done = make(chan struct{})
	n.ready = make(chan struct{})
	n.swarmNode = node
	if conf.joinAddr != "" {
		conf.JoinInProgress = true
	}
	n.config = conf
	savePersistentState(n.cluster.root, conf)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		n.handleNodeExit(node)
		cancel()
	}()

	go n.handleReadyEvent(ctx, node, n.ready)
	go n.handleControlSocketChange(ctx, node)

	return nil
}

func (n *nodeRunner) handleControlSocketChange(ctx context.Context, node *swarmnode.Node) {
	for conn := range node.ListenControlSocket(ctx) {
		n.mu.Lock()
		if n.grpcConn != conn {
			if conn == nil {
				n.controlClient = nil
				n.logsClient = nil
			} else {
				n.controlClient = swarmapi.NewControlClient(conn)
				n.logsClient = swarmapi.NewLogsClient(conn)
				// push store changes to daemon
				go n.watchClusterEvents(ctx, conn)
			}
		}
		n.grpcConn = conn
		n.mu.Unlock()
		n.cluster.SendClusterEvent(lncluster.EventSocketChange)
	}
}

func (n *nodeRunner) watchClusterEvents(ctx context.Context, conn *grpc.ClientConn) {
	client := swarmapi.NewWatchClient(conn)
	watch, err := client.Watch(ctx, &swarmapi.WatchRequest{
		Entries: []*swarmapi.WatchRequest_WatchEntry{
			{
				Kind:   "node",
				Action: swarmapi.WatchActionKindCreate | swarmapi.WatchActionKindUpdate | swarmapi.WatchActionKindRemove,
			},
			{
				Kind:   "service",
				Action: swarmapi.WatchActionKindCreate | swarmapi.WatchActionKindUpdate | swarmapi.WatchActionKindRemove,
			},
			{
				Kind:   "network",
				Action: swarmapi.WatchActionKindCreate | swarmapi.WatchActionKindUpdate | swarmapi.WatchActionKindRemove,
			},
			{
				Kind:   "secret",
				Action: swarmapi.WatchActionKindCreate | swarmapi.WatchActionKindUpdate | swarmapi.WatchActionKindRemove,
			},
			{
				Kind:   "config",
				Action: swarmapi.WatchActionKindCreate | swarmapi.WatchActionKindUpdate | swarmapi.WatchActionKindRemove,
			},
		},
		IncludeOldObject: true,
	})
	if err != nil {
		logrus.WithError(err).Error("failed to watch cluster store")
		return
	}
	for {
		msg, err := watch.Recv()
		if err != nil {
			// store watch is broken
			errStatus, ok := status.FromError(err)
			if !ok || errStatus.Code() != codes.Canceled {
				logrus.WithError(err).Error("failed to receive changes from store watch API")
			}
			return
		}
		select {
		case <-ctx.Done():
			return
		case n.cluster.watchStream <- msg:
		}
	}
}

func (n *nodeRunner) handleReadyEvent(ctx context.Context, node *swarmnode.Node, ready chan struct{}) {
	select {
	case <-node.Ready():
		n.mu.Lock()
		n.err = nil
		if n.config.JoinInProgress {
			n.config.JoinInProgress = false
			savePersistentState(n.cluster.root, n.config)
		}
		n.mu.Unlock()
		close(ready)
	case <-ctx.Done():
	}
	n.cluster.SendClusterEvent(lncluster.EventNodeReady)
}

func (n *nodeRunner) handleNodeExit(node *swarmnode.Node) {
	err := detectLockedError(node.Err(context.Background()))
	if err != nil {
		logrus.Errorf("cluster exited with error: %v", err)
	}
	n.mu.Lock()
	n.swarmNode = nil
	n.err = err
	close(n.done)
	select {
	case <-n.ready:
		n.enableReconnectWatcher()
	default:
		if n.repeatedRun {
			n.enableReconnectWatcher()
		}
	}
	n.repeatedRun = true
	n.mu.Unlock()
}

// Stop stops the current swarm node if it is running.
func (n *nodeRunner) Stop() error {
	n.mu.Lock()
	if n.cancelReconnect != nil { // between restarts
		n.cancelReconnect()
		n.cancelReconnect = nil
	}
	if n.swarmNode == nil {
		// even though the swarm node is nil we still may need
		// to send a node leave event to perform any cleanup required.
		if n.cluster != nil {
			n.cluster.SendClusterEvent(lncluster.EventNodeLeave)
		}
		n.mu.Unlock()
		return nil
	}
	n.stopping = true
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	n.mu.Unlock()
	if err := n.swarmNode.Stop(ctx); err != nil && !strings.Contains(err.Error(), "context canceled") {
		return err
	}
	n.cluster.SendClusterEvent(lncluster.EventNodeLeave)
	<-n.done
	return nil
}

func (n *nodeRunner) State() nodeState {
	if n == nil {
		return nodeState{status: types.LocalNodeStateInactive}
	}
	n.mu.RLock()
	defer n.mu.RUnlock()

	ns := n.nodeState

	if ns.err != nil || n.cancelReconnect != nil {
		if errors.Cause(ns.err) == errSwarmLocked {
			ns.status = types.LocalNodeStateLocked
		} else {
			ns.status = types.LocalNodeStateError
		}
	} else {
		select {
		case <-n.ready:
			ns.status = types.LocalNodeStateActive
		default:
			ns.status = types.LocalNodeStatePending
		}
	}

	return ns
}

func (n *nodeRunner) enableReconnectWatcher() {
	if n.stopping {
		return
	}
	n.reconnectDelay *= 2
	if n.reconnectDelay > maxReconnectDelay {
		n.reconnectDelay = maxReconnectDelay
	}
	logrus.Warnf("Restarting swarm in %.2f seconds", n.reconnectDelay.Seconds())
	delayCtx, cancel := context.WithTimeout(context.Background(), n.reconnectDelay)
	n.cancelReconnect = cancel

	go func() {
		<-delayCtx.Done()
		if delayCtx.Err() != context.DeadlineExceeded {
			return
		}
		n.mu.Lock()
		defer n.mu.Unlock()
		if n.stopping {
			return
		}

		if err := n.start(n.config); err != nil {
			n.err = err
		}
	}()
}

// nodeState represents information about the current state of the cluster and
// provides access to the grpc clients.
type nodeState struct {
	swarmNode       *swarmnode.Node
	grpcConn        *grpc.ClientConn
	controlClient   swarmapi.ControlClient
	logsClient      swarmapi.LogsClient
	status          types.LocalNodeState
	actualLocalAddr string
	err             error
}

// IsActiveManager returns true if node is a manager ready to accept control requests. It is safe to access the client properties if this returns true.
func (ns nodeState) IsActiveManager() bool {
	return ns.controlClient != nil
}

// IsManager returns true if node is a manager.
func (ns nodeState) IsManager() bool {
	return ns.swarmNode != nil && ns.swarmNode.Manager() != nil
}

// NodeID returns node's ID or empty string if node is inactive.
func (ns nodeState) NodeID() string {
	if ns.swarmNode != nil {
		return ns.swarmNode.NodeID()
	}
	return ""
}


text:
package org.cloudfoundry.community.servicebroker.model;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
 * A service plan available for a ServiceDefinition
 *
 * @author sgreenberg@gopivotal.com
 */
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Plan {

	@NotEmpty
	@JsonSerialize
	@JsonProperty("id")
	private String id;

	@NotEmpty
	@JsonSerialize
	@JsonProperty("name")
	private String name;

	@NotEmpty
	@JsonSerialize
	@JsonProperty("description")
	private String description;

	@JsonSerialize
	@JsonProperty("metadata")
	private Map<String,Object> metadata = new HashMap<String,Object>();

	@JsonSerialize
	@JsonProperty("free")
	private boolean free;

	public Plan() {
	}

	public Plan(String id, String name, String description) {
		this.id = id;
		this.name = name;
		this.description = description;
	}

	public Plan(String id, String name, String description, Map<String,Object> metadata) {
		this(id, name, description);
		setMetadata(metadata);
	}

	public Plan(String id, String name, String description, Map<String,Object> metadata, boolean free) {
		this(id, name, description, metadata);
		this.free = free;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getDescription() {
		return description;
	}

	public Map<String, Object> getMetadata() {
		return metadata;
	}

	private void setMetadata(Map<String, Object> metadata) {
		if (metadata == null) {
			this.metadata = new HashMap<String,Object>();
		} else {
			this.metadata = metadata;
		}
	}

	public boolean isFree() {
		return free;
	}

}


text:
import datetime

from neutron.common import rpc as proxy
from neutron.openstack.common import log as logging

LOG = logging.getLogger(__name__)

class HeloAgentNotifyAPI(proxy.RpcProxy):
    """API for plugin to ping agent."""
    BASE_RPC_API_VERSION = '1.0'

    def __init__(self, topic=None, version=None):
        if version:
            super(HeloAgentNotifyAPI, self).__init__(
                topic=topic, default_version=version)
        else:
            super(HeloAgentNotifyAPI, self).__init__(
                topic=topic, default_version=self.BASE_RPC_API_VERSION)

    def helo_agent_host(self, context, host, topic):
        """Notify the agent on host."""
        data = 0
        try:
            data = self.call(
                context, self.make_msg('helo',
                                       time=datetime.datetime.utcnow()),
                timeout = 3,
                topic='%s.%s' % (topic, host))
        except Exception:
            LOG.exception(_("Failed to helo %(topic)s on %(host)s"),
                          {"topic": topic, "host": host})
        return data

class HeloRpcCallbackMixin(object):

    def helo(self, context, time):
        LOG.debug(time)
        return 1


text:
package ru.job4j.tracker.dbconnector;

 import org.w3c.dom.Document;
 import org.xml.sax.SAXException;

 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import java.io.File;
 import java.io.IOException;

 /**
  * Class for getting document to parse.
  *
  * @author Ayuzyak
  * @version 1.0
  * @since 13.10.2017
  */
 public class DocParser {
     /**
      * Document for parsing.
      */
     private Document document;

     /**
      * Constructor for DocParser.
      *
      * @param path to file.
      * @throws ParserConfigurationException when has serious configuration error.
      * @throws IOException                  Signals that an I/O exception of some sort has occurred.
      * @throws SAXException                 Encapsulate a general SAX error or warning.
      */
     public DocParser(String path) throws ParserConfigurationException, IOException, SAXException {
         DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = builderFactory.newDocumentBuilder();
         File file = new File(path);
         this.document = builder.parse(file);
     }

     /**
      * Getter for document.
      *
      * @return document.
      */
     public Document getDocument() {
         return document;
     }
 }


text:
package org.gradle.nativeplatform.tasks;

import com.google.common.collect.Lists;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Incubating;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.nativeplatform.toolchain.internal.PCHUtils;
import org.gradle.work.DisableCachingByDefault;
import org.gradle.workers.WorkAction;
import org.gradle.workers.WorkParameters;
import org.gradle.workers.WorkQueue;
import org.gradle.workers.WorkerExecutor;

import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.io.File;

/**
 * Generates a prefix header file from a list of headers to be precompiled.
 */
@Incubating
@DisableCachingByDefault(because = "Not made cacheable, yet")
public abstract class PrefixHeaderFileGenerateTask extends DefaultTask {
    private String header;
    private File prefixHeaderFile;
    private final WorkerExecutor workerExecutor;

    /**
     * Injects a {@link WorkerExecutor} instance.
     *
     * @since 4.2
     */
    @Inject
    public PrefixHeaderFileGenerateTask(WorkerExecutor workerExecutor) {
        this.workerExecutor = workerExecutor;
    }

    @TaskAction
    void generatePrefixHeaderFile() {
        WorkQueue workQueue = workerExecutor.noIsolation();

        workQueue.submit(GeneratePrefixHeaderFile.class, new Action<PrefixHeaderFileParameters>() {
            @Override
            public void execute(@Nonnull PrefixHeaderFileParameters parameters) {
                parameters.getHeader().set(header);
                parameters.getPrefixHeaderFile().set(prefixHeaderFile);
            }
        });
    }

    @Input
    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    @OutputFile
    public File getPrefixHeaderFile() {
        return prefixHeaderFile;
    }

    public void setPrefixHeaderFile(File prefixHeaderFile) {
        this.prefixHeaderFile = prefixHeaderFile;
    }

    interface PrefixHeaderFileParameters extends WorkParameters {
        Property<String> getHeader();
        RegularFileProperty getPrefixHeaderFile();
    }

    static abstract class GeneratePrefixHeaderFile implements WorkAction<PrefixHeaderFileParameters> {
        @Inject
        public GeneratePrefixHeaderFile() { }

        @Override
        public void execute() {
            PCHUtils.generatePrefixHeaderFile(Lists.newArrayList(getParameters().getHeader().get()), getParameters().getPrefixHeaderFile().getAsFile().get());
        }
    }
}


text:
/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file BlockChain.h
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#pragma once

#include <deque>
#include <chrono>
#include <unordered_map>
#include <unordered_set>
#include <libdevcore/db.h>
#include <libdevcore/Log.h>
#include <libdevcore/Exceptions.h>
#include <libdevcore/Guards.h>
#include <libethcore/Common.h>
#include <libethcore/BlockInfo.h>
#include <libevm/ExtVMFace.h>
#include "BlockDetails.h"
#include "Account.h"
#include "Transaction.h"
#include "BlockQueue.h"
#include "VerifiedBlock.h"
#include "State.h"

namespace std
{
template <> struct hash<pair<dev::h256, unsigned>>
{
	size_t operator()(pair<dev::h256, unsigned> const& _x) const { return hash<dev::h256>()(_x.first) ^ hash<unsigned>()(_x.second); }
};
}

namespace dev
{

class OverlayDB;

namespace eth
{

static const h256s NullH256s;

class State;
class Block;

struct AlreadyHaveBlock: virtual Exception {};
struct UnknownParent: virtual Exception {};
struct FutureTime: virtual Exception {};
struct TransientError: virtual Exception {};

struct BlockChainChat: public LogChannel { static const char* name(); static const int verbosity = 5; };
struct BlockChainNote: public LogChannel { static const char* name(); static const int verbosity = 3; };
struct BlockChainWarn: public LogChannel { static const char* name(); static const int verbosity = 1; };
struct BlockChainDebug: public LogChannel { static const char* name(); static const int verbosity = 0; };

// TODO: Move all this Genesis stuff into Genesis.h/.cpp
std::unordered_map<Address, Account> const& genesisState();

ldb::Slice toSlice(h256 const& _h, unsigned _sub = 0);
ldb::Slice toSlice(uint64_t _n, unsigned _sub = 0);

using BlocksHash = std::unordered_map<h256, bytes>;
using TransactionHashes = h256s;
using UncleHashes = h256s;

enum {
	ExtraDetails = 0,
	ExtraBlockHash,
	ExtraTransactionAddress,
	ExtraLogBlooms,
	ExtraReceipts,
	ExtraBlocksBlooms
};

using ProgressCallback = std::function<void(unsigned, unsigned)>;

class VersionChecker
{
public:
	VersionChecker(std::string const& _dbPath, h256 const& _genesisHash);
};

/**
 * @brief Implements the blockchain database. All data this gives is disk-backed.
 * @threadsafe
 */
class BlockChain
{
public:
	/// Doesn't open the database - if you want it open it's up to you to subclass this and open it
	/// in the constructor there.
	BlockChain(bytes const& _genesisBlock, AccountMap const& _genesisState, std::string const& _path);
	~BlockChain();

	/// Reopen everything.
	virtual void reopen(WithExisting _we = WithExisting::Trust, ProgressCallback const& _pc = ProgressCallback()) { close(); open(m_genesisBlock, m_genesisState, m_dbPath); openDatabase(m_dbPath, _we, _pc); }

	/// (Potentially) renders invalid existing bytesConstRef returned by lastBlock.
	/// To be called from main loop every 100ms or so.
	void process();

	/// Sync the chain with any incoming blocks. All blocks should, if processed in order.
	/// @returns fresh blocks, dead blocks and true iff there are additional blocks to be processed waiting.
	std::tuple<ImportRoute, bool, unsigned> sync(BlockQueue& _bq, OverlayDB const& _stateDB, unsigned _max);

	/// Attempt to import the given block directly into the CanonBlockChain and sync with the state DB.
	/// @returns the block hashes of any blocks that came into/went out of the canonical block chain.
	std::pair<ImportResult, ImportRoute> attemptImport(bytes const& _block, OverlayDB const& _stateDB, bool _mutBeNew = true) noexcept;

	/// Import block into disk-backed DB
	/// @returns the block hashes of any blocks that came into/went out of the canonical block chain.
	ImportRoute import(bytes const& _block, OverlayDB const& _stateDB, bool _mustBeNew = true);
	ImportRoute import(VerifiedBlockRef const& _block, OverlayDB const& _db, bool _mustBeNew = true);

	/// Returns true if the given block is known (though not necessarily a part of the canon chain).
	bool isKnown(h256 const& _hash) const;

	/// Get the partial-header of a block (or the most recent mined if none given). Thread-safe.
	BlockInfo info(h256 const& _hash) const { return BlockInfo(headerData(_hash), CheckNothing, _hash, HeaderData); }
	BlockInfo info() const { return info(currentHash()); }

	/// Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
	bytes block(h256 const& _hash) const;
	bytes block() const { return block(currentHash()); }

	/// Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
	bytes headerData(h256 const& _hash) const;
	bytes headerData() const { return headerData(currentHash()); }

	/// Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
	BlockDetails details(h256 const& _hash) const { return queryExtras<BlockDetails, ExtraDetails>(_hash, m_details, x_details, NullBlockDetails); }
	BlockDetails details() const { return details(currentHash()); }

	/// Get the transactions' log blooms of a block (or the most recent mined if none given). Thread-safe.
	BlockLogBlooms logBlooms(h256 const& _hash) const { return queryExtras<BlockLogBlooms, ExtraLogBlooms>(_hash, m_logBlooms, x_logBlooms, NullBlockLogBlooms); }
	BlockLogBlooms logBlooms() const { return logBlooms(currentHash()); }

	/// Get the transactions' receipts of a block (or the most recent mined if none given). Thread-safe.
	/// receipts are given in the same order are in the same order as the transactions
	BlockReceipts receipts(h256 const& _hash) const { return queryExtras<BlockReceipts, ExtraReceipts>(_hash, m_receipts, x_receipts, NullBlockReceipts); }
	BlockReceipts receipts() const { return receipts(currentHash()); }

	/// Get the transaction by block hash and index;
	TransactionReceipt transactionReceipt(h256 const& _blockHash, unsigned _i) const { return receipts(_blockHash).receipts[_i]; }

	/// Get the transaction receipt by transaction hash. Thread-safe.
	TransactionReceipt transactionReceipt(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return bytesConstRef(); return transactionReceipt(ta.blockHash, ta.index); }

	/// Get a list of transaction hashes for a given block. Thread-safe.
	TransactionHashes transactionHashes(h256 const& _hash) const { auto b = block(_hash); RLP rlp(b); h256s ret; for (auto t: rlp[1]) ret.push_back(sha3(t.data())); return ret; }
	TransactionHashes transactionHashes() const { return transactionHashes(currentHash()); }

	/// Get a list of uncle hashes for a given block. Thread-safe.
	UncleHashes uncleHashes(h256 const& _hash) const { auto b = block(_hash); RLP rlp(b); h256s ret; for (auto t: rlp[2]) ret.push_back(sha3(t.data())); return ret; }
	UncleHashes uncleHashes() const { return uncleHashes(currentHash()); }

	/// Get the hash for a given block's number.
	h256 numberHash(unsigned _i) const { if (!_i) return genesisHash(); return queryExtras<BlockHash, uint64_t, ExtraBlockHash>(_i, m_blockHashes, x_blockHashes, NullBlockHash).value; }

	/// Get the last N hashes for a given block. (N is determined by the LastHashes type.)
	LastHashes lastHashes() const { return lastHashes(number()); }
	LastHashes lastHashes(unsigned _i) const;

	/** Get the block blooms for a number of blocks. Thread-safe.
	 * @returns the object pertaining to the blocks:
	 * level 0:
	 * 0x, 0x + 1, .. (1x - 1)
	 * 1x, 1x + 1, .. (2x - 1)
	 * ...
	 * (255x .. (256x - 1))
	 * level 1:
	 * 0x .. (1x - 1), 1x .. (2x - 1), ..., (255x .. (256x - 1))
	 * 256x .. (257x - 1), 257x .. (258x - 1), ..., (511x .. (512x - 1))
	 * ...
	 * level n, index i, offset o:
	 * i * (x ^ n) + o * x ^ (n - 1)
	 */
	BlocksBlooms blocksBlooms(unsigned _level, unsigned _index) const { return blocksBlooms(chunkId(_level, _index)); }
	BlocksBlooms blocksBlooms(h256 const& _chunkId) const { return queryExtras<BlocksBlooms, ExtraBlocksBlooms>(_chunkId, m_blocksBlooms, x_blocksBlooms, NullBlocksBlooms); }
	void clearBlockBlooms(unsigned _begin, unsigned _end);
	LogBloom blockBloom(unsigned _number) const { return blocksBlooms(chunkId(0, _number / c_bloomIndexSize)).blooms[_number % c_bloomIndexSize]; }
	std::vector<unsigned> withBlockBloom(LogBloom const& _b, unsigned _earliest, unsigned _latest) const;
	std::vector<unsigned> withBlockBloom(LogBloom const& _b, unsigned _earliest, unsigned _latest, unsigned _topLevel, unsigned _index) const;

	/// Returns true if transaction is known. Thread-safe
	bool isKnownTransaction(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); return !!ta; }

	/// Get a transaction from its hash. Thread-safe.
	bytes transaction(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return bytes(); return transaction(ta.blockHash, ta.index); }
	std::pair<h256, unsigned> transactionLocation(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return std::pair<h256, unsigned>(h256(), 0); return std::make_pair(ta.blockHash, ta.index); }

	/// Get a block's transaction (RLP format) for the given block hash (or the most recent mined if none given) & index. Thread-safe.
	bytes transaction(h256 const& _blockHash, unsigned _i) const { bytes b = block(_blockHash); return RLP(b)[1][_i].data().toBytes(); }
	bytes transaction(unsigned _i) const { return transaction(currentHash(), _i); }

	/// Get all transactions from a block.
	std::vector<bytes> transactions(h256 const& _blockHash) const { bytes b = block(_blockHash); std::vector<bytes> ret; for (auto const& i: RLP(b)[1]) ret.push_back(i.data().toBytes()); return ret; }
	std::vector<bytes> transactions() const { return transactions(currentHash()); }

	/// Get a number for the given hash (or the most recent mined if none given). Thread-safe.
	unsigned number(h256 const& _hash) const { return details(_hash).number; }
	unsigned number() const { return m_lastBlockNumber; }

	/// Get a given block (RLP format). Thread-safe.
	h256 currentHash() const { ReadGuard l(x_lastBlockHash); return m_lastBlockHash; }

	/// Get the hash of the genesis block. Thread-safe.
	h256 genesisHash() const { return m_genesisHash; }

	/// Get all blocks not allowed as uncles given a parent (i.e. featured as uncles/main in parent, parent + 1, ... parent + @a _generations).
	/// @returns set including the header-hash of every parent (including @a _parent) up to and including generation + @a _generations
	/// togther with all their quoted uncles.
	h256Hash allKinFrom(h256 const& _parent, unsigned _generations) const;

	/// Run through database and verify all blocks by reevaluating.
	/// Will call _progress with the progress in this operation first param done, second total.
	void rebuild(std::string const& _path, ProgressCallback const& _progress = std::function<void(unsigned, unsigned)>(), bool _prepPoW = false);

	/// Alter the head of the chain to some prior block along it.
	void rewind(unsigned _newHead);

	/// Rescue the database.
	void rescue(OverlayDB& _db);

	/** @returns a tuple of:
	 * - an vector of hashes of all blocks between @a _from and @a _to, all blocks are ordered first by a number of
	 * blocks that are parent-to-child, then two sibling blocks, then a number of blocks that are child-to-parent;
	 * - the block hash of the latest common ancestor of both blocks;
	 * - the index where the latest common ancestor of both blocks would either be found or inserted, depending
	 * on whether it is included.
	 *
	 * @param _common if true, include the common ancestor in the returned vector.
	 * @param _pre if true, include all block hashes running from @a _from until the common ancestor in the returned vector.
	 * @param _post if true, include all block hashes running from the common ancestor until @a _to in the returned vector.
	 *
	 * e.g. if the block tree is 3a -> 2a -> 1a -> g and 2b -> 1b -> g (g is genesis, *a, *b are competing chains),
	 * then:
	 * @code
	 * treeRoute(3a, 2b, false) == make_tuple({ 3a, 2a, 1a, 1b, 2b }, g, 3);
	 * treeRoute(2a, 1a, false) == make_tuple({ 2a, 1a }, 1a, 1)
	 * treeRoute(1a, 2a, false) == make_tuple({ 1a, 2a }, 1a, 0)
	 * treeRoute(1b, 2a, false) == make_tuple({ 1b, 1a, 2a }, g, 1)
	 * treeRoute(3a, 2b, true) == make_tuple({ 3a, 2a, 1a, g, 1b, 2b }, g, 3);
	 * treeRoute(2a, 1a, true) == make_tuple({ 2a, 1a }, 1a, 1)
	 * treeRoute(1a, 2a, true) == make_tuple({ 1a, 2a }, 1a, 0)
	 * treeRoute(1b, 2a, true) == make_tuple({ 1b, g, 1a, 2a }, g, 1)
	 * @endcode
	 */
	std::tuple<h256s, h256, unsigned> treeRoute(h256 const& _from, h256 const& _to, bool _common = true, bool _pre = true, bool _post = true) const;

	struct Statistics
	{
		unsigned memBlocks;
		unsigned memDetails;
		unsigned memLogBlooms;
		unsigned memReceipts;
		unsigned memTransactionAddresses;
		unsigned memBlockHashes;
		unsigned memTotal() const { return memBlocks + memDetails + memLogBlooms + memReceipts + memTransactionAddresses + memBlockHashes; }
	};

	/// @returns statistics about memory usage.
	Statistics usage(bool _freshen = false) const { if (_freshen) updateStats(); return m_lastStats; }

	/// Deallocate unused data.
	void garbageCollect(bool _force = false);

	/// Change the function that is called with a bad block.
	template <class T> void setOnBad(T const& _t) { m_onBad = _t; }

	/// Get a pre-made genesis State object.
	Block genesisBlock(OverlayDB const& _db) const;

	/// Verify block and prepare it for enactment
	virtual VerifiedBlockRef verifyBlock(bytesConstRef _block, std::function<void(Exception&)> const& _onBad, ImportRequirements::value _ir = ImportRequirements::OutOfOrderChecks) const = 0;

protected:
	static h256 chunkId(unsigned _level, unsigned _index) { return h256(_index * 0xff + _level); }

	/// Initialise everything and ready for openning the database.
	// TODO: rename to init
	void open(bytes const& _genesisBlock, AccountMap const& _genesisState, std::string const& _path);
	/// Open the database.
	// TODO: rename to open.
	unsigned openDatabase(std::string const& _path, WithExisting _we);
	/// Finalise everything and close the database.
	void close();

	/// Open the database, rebuilding if necessary.
	void openDatabase(std::string const& _path, WithExisting _we, ProgressCallback const& _pc)
	{
		if (openDatabase(_path, _we) != c_minorProtocolVersion || _we == WithExisting::Verify)
			rebuild(_path, _pc);
	}

	template<class T, class K, unsigned N> T queryExtras(K const& _h, std::unordered_map<K, T>& _m, boost::shared_mutex& _x, T const& _n, ldb::DB* _extrasDB = nullptr) const
	{
		{
			ReadGuard l(_x);
			auto it = _m.find(_h);
			if (it != _m.end())
				return it->second;
		}

		std::string s;
		(_extrasDB ? _extrasDB : m_extrasDB)->Get(m_readOptions, toSlice(_h, N), &s);
		if (s.empty())
			return _n;

		noteUsed(_h, N);

		WriteGuard l(_x);
		auto ret = _m.insert(std::make_pair(_h, T(RLP(s))));
		return ret.first->second;
	}

	template<class T, unsigned N> T queryExtras(h256 const& _h, std::unordered_map<h256, T>& _m, boost::shared_mutex& _x, T const& _n, ldb::DB* _extrasDB = nullptr) const
	{
		return queryExtras<T, h256, N>(_h, _m, _x, _n, _extrasDB);
	}

	void checkConsistency();

	/// The caches of the disk DB and their locks.
	mutable SharedMutex x_blocks;
	mutable BlocksHash m_blocks;
	mutable SharedMutex x_details;
	mutable BlockDetailsHash m_details;
	mutable SharedMutex x_logBlooms;
	mutable BlockLogBloomsHash m_logBlooms;
	mutable SharedMutex x_receipts;
	mutable BlockReceiptsHash m_receipts;
	mutable SharedMutex x_transactionAddresses;
	mutable TransactionAddressHash m_transactionAddresses;
	mutable SharedMutex x_blockHashes;
	mutable BlockHashHash m_blockHashes;
	mutable SharedMutex x_blocksBlooms;
	mutable BlocksBloomsHash m_blocksBlooms;

	using CacheID = std::pair<h256, unsigned>;
	mutable Mutex x_cacheUsage;
	mutable std::deque<std::unordered_set<CacheID>> m_cacheUsage;
	mutable std::unordered_set<CacheID> m_inUse;
	void noteUsed(h256 const& _h, unsigned _extra = (unsigned)-1) const;
	void noteUsed(uint64_t const& _h, unsigned _extra = (unsigned)-1) const { (void)_h; (void)_extra; } // don't note non-hash types
	std::chrono::system_clock::time_point m_lastCollection;

	void noteCanonChanged() const { Guard l(x_lastLastHashes); m_lastLastHashes.clear(); }
	mutable Mutex x_lastLastHashes;
	mutable LastHashes m_lastLastHashes;
	mutable unsigned m_lastLastHashesNumber = (unsigned)-1;

	void updateStats() const;
	mutable Statistics m_lastStats;

	/// The disk DBs. Thread-safe, so no need for locks.
	ldb::DB* m_blocksDB;
	ldb::DB* m_extrasDB;

	/// Hash of the last (valid) block on the longest chain.
	mutable boost::shared_mutex x_lastBlockHash;
	h256 m_lastBlockHash;
	unsigned m_lastBlockNumber = 0;

	/// Genesis block info.
	h256 m_genesisHash;
	bytes m_genesisBlock;
	std::unordered_map<Address, Account> m_genesisState;

	ldb::ReadOptions m_readOptions;
	ldb::WriteOptions m_writeOptions;

	std::function<void(Exception&)> m_onBad;									///< Called if we have a block that doesn't verify.

	std::string m_dbPath;

	friend std::ostream& operator<<(std::ostream& _out, BlockChain const& _bc);
};

template <class Sealer>
class FullBlockChain: public BlockChain
{
public:
	using BlockHeader = typename Sealer::BlockHeader;

	FullBlockChain(bytes const& _genesisBlock, AccountMap const& _genesisState, std::string const& _path, WithExisting _we, ProgressCallback const& _pc = ProgressCallback()):
		BlockChain(_genesisBlock, _genesisState, _path)
	{
		openDatabase(_path, _we, _pc);
	}

	/// Get the header of a block (or the most recent mined if none given). Thread-safe.
	typename Sealer::BlockHeader header(h256 const& _hash) const { return typename Sealer::BlockHeader(headerData(_hash), IgnoreSeal, _hash, HeaderData); }
	typename Sealer::BlockHeader header() const { return header(currentHash()); }

	virtual VerifiedBlockRef verifyBlock(bytesConstRef _block, std::function<void(Exception&)> const& _onBad, ImportRequirements::value _ir = ImportRequirements::OutOfOrderChecks) const override
	{
		VerifiedBlockRef res;
		BlockHeader h;
		try
		{
			h = BlockHeader(_block, (_ir & ImportRequirements::ValidSeal) ? Strictness::CheckEverything : Strictness::QuickNonce);
			h.verifyInternals(_block);
			if (!!(_ir & ImportRequirements::Parent))
			{
				bytes parentHeader(headerData(h.parentHash()));
				if (parentHeader.empty())
					BOOST_THROW_EXCEPTION(InvalidParentHash() << errinfo_required_h256(h.parentHash()) << errinfo_currentNumber(h.number()));
				h.verifyParent(typename Sealer::BlockHeader(parentHeader, IgnoreSeal, h.parentHash(), HeaderData));
			}
			res.info = static_cast<BlockInfo&>(h);
		}
		catch (Exception& ex)
		{
			ex << errinfo_phase(1);
			ex << errinfo_now(time(0));
			ex << errinfo_block(_block.toBytes());
			// only populate extraData if we actually managed to extract it. otherwise,
			// we might be clobbering the existing one.
			if (!h.extraData().empty())
				ex << errinfo_extraData(h.extraData());
			if (_onBad)
				_onBad(ex);
			throw;
		}

		RLP r(_block);
		unsigned i = 0;
		if (_ir && !!(ImportRequirements::UncleBasic | ImportRequirements::UncleParent | ImportRequirements::UncleSeals))
			for (auto const& uncle: r[2])
			{
				BlockHeader uh;
				try
				{
					uh.populateFromHeader(RLP(uncle.data()), (_ir & ImportRequirements::UncleSeals) ? Strictness::CheckEverything : Strictness::IgnoreSeal);
					if (!!(_ir & ImportRequirements::UncleParent))
					{
						bytes parentHeader(headerData(uh.parentHash()));
						if (parentHeader.empty())
							BOOST_THROW_EXCEPTION(InvalidUncleParentHash() << errinfo_required_h256(uh.parentHash()) << errinfo_currentNumber(h.number()) << errinfo_uncleNumber(uh.number()));
						uh.verifyParent(typename Sealer::BlockHeader(parentHeader, IgnoreSeal, uh.parentHash(), HeaderData));
					}
				}
				catch (Exception& ex)
				{
					ex << errinfo_phase(1);
					ex << errinfo_uncleIndex(i);
					ex << errinfo_now(time(0));
					ex << errinfo_block(_block.toBytes());
					// only populate extraData if we actually managed to extract it. otherwise,
					// we might be clobbering the existing one.
					if (!uh.extraData().empty())
						ex << errinfo_extraData(uh.extraData());
					if (_onBad)
						_onBad(ex);
					throw;
				}
				++i;
			}
		i = 0;
		if (_ir && !!(ImportRequirements::TransactionBasic | ImportRequirements::TransactionSignatures))
			for (RLP const& tr: r[1])
			{
				bytesConstRef d = tr.data();
				try
				{
					res.transactions.push_back(Transaction(d, (_ir & ImportRequirements::TransactionSignatures) ? CheckTransaction::Everything : CheckTransaction::None));
				}
				catch (Exception& ex)
				{
					ex << errinfo_phase(1);
					ex << errinfo_transactionIndex(i);
					ex << errinfo_transaction(d.toBytes());
					ex << errinfo_block(_block.toBytes());
					// only populate extraData if we actually managed to extract it. otherwise,
					// we might be clobbering the existing one.
					if (!h.extraData().empty())
						ex << errinfo_extraData(h.extraData());
					if (_onBad)
						_onBad(ex);
					throw;
				}
				++i;
			}
		res.block = bytesConstRef(_block);
		return res;
	}

protected:
	/// Constructor for derived classes to use when they'll open the chain db afterwards.
	FullBlockChain(bytes const& _genesisBlock, AccountMap const& _genesisState, std::string const& _path):
		BlockChain(_genesisBlock, _genesisState, _path)
	{}
};

std::ostream& operator<<(std::ostream& _out, BlockChain const& _bc);

}
}


text:
  " id,url,visit_time,from_visit,transition,segment_id,is_indexed "

namespace history {

VisitDatabase::VisitDatabase() {
}

VisitDatabase::~VisitDatabase() {
}

bool VisitDatabase::InitVisitTable() {
  if (!GetDB().DoesTableExist("visits")) {
    if (!GetDB().Execute("CREATE TABLE visits("
        "id INTEGER PRIMARY KEY,"
        "url INTEGER NOT NULL," // key of the URL this corresponds to
        "visit_time INTEGER NOT NULL,"
        "from_visit INTEGER,"
        "transition INTEGER DEFAULT 0 NOT NULL,"
        "segment_id INTEGER,"
        // True when we have indexed data for this visit.
        "is_indexed BOOLEAN)"))
      return false;
  } else if (!GetDB().DoesColumnExist("visits", "is_indexed")) {
    // Old versions don't have the is_indexed column, we can just add that and
    // not worry about different database revisions, since old ones will
    // continue to work.
    //
    // TODO(brettw) this should be removed once we think everybody has been
    // updated (added early Mar 2008).
    if (!GetDB().Execute("ALTER TABLE visits ADD COLUMN is_indexed BOOLEAN"))
      return false;
  }

  // Visit source table contains the source information for all the visits. To
  // save space, we do not record those user browsed visits which would be the
  // majority in this table. Only other sources are recorded.
  // Due to the tight relationship between visit_source and visits table, they
  // should be created and dropped at the same time.
  if (!GetDB().DoesTableExist("visit_source")) {
    if (!GetDB().Execute("CREATE TABLE visit_source("
                         "id INTEGER PRIMARY KEY,source INTEGER NOT NULL)"))
        return false;
  }

  // Index over url so we can quickly find visits for a page. This will just
  // fail if it already exists and we'll ignore it.
  GetDB().Execute("CREATE INDEX visits_url_index ON visits (url)");

  // Create an index over from visits so that we can efficiently find
  // referrers and redirects. Ignore failures because it likely already exists.
  GetDB().Execute("CREATE INDEX visits_from_index ON visits (from_visit)");

  // Create an index over time so that we can efficiently find the visits in a
  // given time range (most history views are time-based). Ignore failures
  // because it likely already exists.
  GetDB().Execute("CREATE INDEX visits_time_index ON visits (visit_time)");

  return true;
}

bool VisitDatabase::DropVisitTable() {
  GetDB().Execute("DROP TABLE visit_source");
  // This will also drop the indices over the table.
  return GetDB().Execute("DROP TABLE visits");
}

// Must be in sync with HISTORY_VISIT_ROW_FIELDS.
// static
void VisitDatabase::FillVisitRow(sql::Statement& statement, VisitRow* visit) {
  visit->visit_id = statement.ColumnInt64(0);
  visit->url_id = statement.ColumnInt64(1);
  visit->visit_time = base::Time::FromInternalValue(statement.ColumnInt64(2));
  visit->referring_visit = statement.ColumnInt64(3);
  visit->transition = PageTransition::FromInt(statement.ColumnInt(4));
  visit->segment_id = statement.ColumnInt64(5);
  visit->is_indexed = !!statement.ColumnInt(6);
}

// static
void VisitDatabase::FillVisitVector(sql::Statement& statement,
                                    VisitVector* visits) {
  while (statement.Step()) {
    history::VisitRow visit;
    FillVisitRow(statement, &visit);
    visits->push_back(visit);
  }
}

VisitID VisitDatabase::AddVisit(VisitRow* visit, VisitSource source) {
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "INSERT INTO visits "
      "(url, visit_time, from_visit, transition, segment_id, is_indexed) "
      "VALUES (?,?,?,?,?,?)"));
  if (!statement) {
    VLOG(0) << "Failed to build visit insert statement:  "
            << "url_id = " << visit->url_id;
    return 0;
  }

  statement.BindInt64(0, visit->url_id);
  statement.BindInt64(1, visit->visit_time.ToInternalValue());
  statement.BindInt64(2, visit->referring_visit);
  statement.BindInt64(3, visit->transition);
  statement.BindInt64(4, visit->segment_id);
  statement.BindInt64(5, visit->is_indexed);

  if (!statement.Run()) {
    VLOG(0) << "Failed to execute visit insert statement:  "
            << "url_id = " << visit->url_id;
    return 0;
  }

  visit->visit_id = GetDB().GetLastInsertRowId();

  if (source != SOURCE_BROWSED) {
    // Record the source of this visit when it is not browsed.
    sql::Statement statement1(GetDB().GetCachedStatement(SQL_FROM_HERE,
        "INSERT INTO visit_source (id, source) VALUES (?,?)"));
    if (!statement1.is_valid()) {
      VLOG(0) << "Failed to build visit_source insert statement:  "
              << "url_id = " << visit->visit_id;
      return 0;
    }

    statement1.BindInt64(0, visit->visit_id);
    statement1.BindInt64(1, source);
    if (!statement1.Run()) {
      VLOG(0) << "Failed to execute visit_source insert statement:  "
              << "url_id = " << visit->visit_id;
      return 0;
    }
  }

  return visit->visit_id;
}

void VisitDatabase::DeleteVisit(const VisitRow& visit) {
  // Patch around this visit. Any visits that this went to will now have their
  // "source" be the deleted visit's source.
  sql::Statement update_chain(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "UPDATE visits SET from_visit=? WHERE from_visit=?"));
  if (!update_chain)
    return;
  update_chain.BindInt64(0, visit.referring_visit);
  update_chain.BindInt64(1, visit.visit_id);
  update_chain.Run();

  // Now delete the actual visit.
  sql::Statement del(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "DELETE FROM visits WHERE id=?"));
  if (!del)
    return;
  del.BindInt64(0, visit.visit_id);
  del.Run();

  // Try to delete the entry in visit_source table as well.
  // If the visit was browsed, there is no corresponding entry in visit_source
  // table, and nothing will be deleted.
  del.Assign(GetDB().GetCachedStatement(SQL_FROM_HERE,
             "DELETE FROM visit_source WHERE id=?"));
  if (!del.is_valid())
    return;
  del.BindInt64(0, visit.visit_id);
  del.Run();
}

bool VisitDatabase::GetRowForVisit(VisitID visit_id, VisitRow* out_visit) {
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS "FROM visits WHERE id=?"));
  if (!statement)
    return false;

  statement.BindInt64(0, visit_id);
  if (!statement.Step())
    return false;

  FillVisitRow(statement, out_visit);

  // We got a different visit than we asked for, something is wrong.
  DCHECK_EQ(visit_id, out_visit->visit_id);
  if (visit_id != out_visit->visit_id)
    return false;

  return true;
}

bool VisitDatabase::UpdateVisitRow(const VisitRow& visit) {
  // Don't store inconsistent data to the database.
  DCHECK_NE(visit.visit_id, visit.referring_visit);
  if (visit.visit_id == visit.referring_visit)
    return false;

  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "UPDATE visits SET "
      "url=?,visit_time=?,from_visit=?,transition=?,segment_id=?,is_indexed=? "
      "WHERE id=?"));
  if (!statement)
    return false;

  statement.BindInt64(0, visit.url_id);
  statement.BindInt64(1, visit.visit_time.ToInternalValue());
  statement.BindInt64(2, visit.referring_visit);
  statement.BindInt64(3, visit.transition);
  statement.BindInt64(4, visit.segment_id);
  statement.BindInt64(5, visit.is_indexed);
  statement.BindInt64(6, visit.visit_id);
  return statement.Run();
}

bool VisitDatabase::GetVisitsForURL(URLID url_id, VisitVector* visits) {
  visits->clear();

  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS
      "FROM visits "
      "WHERE url=? "
      "ORDER BY visit_time ASC"));
  if (!statement)
    return false;

  statement.BindInt64(0, url_id);
  FillVisitVector(statement, visits);
  return true;
}

void VisitDatabase::GetAllVisitsInRange(base::Time begin_time,
                                        base::Time end_time,
                                        int max_results,
                                        VisitVector* visits) {
  visits->clear();

  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS "FROM visits "
      "WHERE visit_time >= ? AND visit_time < ?"
      "ORDER BY visit_time LIMIT ?"));
  if (!statement)
    return;

  // See GetVisibleVisitsInRange for more info on how these times are bound.
  int64 end = end_time.ToInternalValue();
  statement.BindInt64(0, begin_time.ToInternalValue());
  statement.BindInt64(1, end ? end : std::numeric_limits<int64>::max());
  statement.BindInt64(2,
      max_results ? max_results : std::numeric_limits<int64>::max());

  FillVisitVector(statement, visits);
}

void VisitDatabase::GetVisitsInRangeForTransition(
    base::Time begin_time,
    base::Time end_time,
    int max_results,
    PageTransition::Type transition,
    VisitVector* visits) {
  DCHECK(visits);
  visits->clear();

  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS "FROM visits "
      "WHERE visit_time >= ? AND visit_time < ? "
      "AND (transition & ?) == ?"
      "ORDER BY visit_time LIMIT ?"));
  if (!statement)
    return;

  // See GetVisibleVisitsInRange for more info on how these times are bound.
  int64 end = end_time.ToInternalValue();
  statement.BindInt64(0, begin_time.ToInternalValue());
  statement.BindInt64(1, end ? end : std::numeric_limits<int64>::max());
  statement.BindInt(2, PageTransition::CORE_MASK);
  statement.BindInt(3, transition);
  statement.BindInt64(4,
      max_results ? max_results : std::numeric_limits<int64>::max());

  FillVisitVector(statement, visits);
}

void VisitDatabase::GetVisibleVisitsInRange(base::Time begin_time,
                                            base::Time end_time,
                                            int max_count,
                                            VisitVector* visits) {
  visits->clear();
  // The visit_time values can be duplicated in a redirect chain, so we sort
  // by id too, to ensure a consistent ordering just in case.
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS "FROM visits "
      "WHERE visit_time >= ? AND visit_time < ? "
      "AND (transition & ?) != 0 "  // CHAIN_END
      "AND (transition & ?) NOT IN (?, ?, ?) "  // NO SUBFRAME or
                                                // KEYWORD_GENERATED
      "ORDER BY visit_time DESC, id DESC"));
  if (!statement)
    return;

  // Note that we use min/max values for querying unlimited ranges of time using
  // the same statement. Since the time has an index, this will be about the
  // same amount of work as just doing a query for everything with no qualifier.
  int64 end = end_time.ToInternalValue();
  statement.BindInt64(0, begin_time.ToInternalValue());
  statement.BindInt64(1, end ? end : std::numeric_limits<int64>::max());
  statement.BindInt(2, PageTransition::CHAIN_END);
  statement.BindInt(3, PageTransition::CORE_MASK);
  statement.BindInt(4, PageTransition::AUTO_SUBFRAME);
  statement.BindInt(5, PageTransition::MANUAL_SUBFRAME);
  statement.BindInt(6, PageTransition::KEYWORD_GENERATED);

  std::set<URLID> found_urls;
  while (statement.Step()) {
    VisitRow visit;
    FillVisitRow(statement, &visit);
    // Make sure the URL this visit corresponds to is unique.
    if (found_urls.find(visit.url_id) != found_urls.end())
      continue;
    found_urls.insert(visit.url_id);
    visits->push_back(visit);

    if (max_count > 0 && static_cast<int>(visits->size()) >= max_count)
      break;
  }
}

VisitID VisitDatabase::GetMostRecentVisitForURL(URLID url_id,
                                                VisitRow* visit_row) {
  // The visit_time values can be duplicated in a redirect chain, so we sort
  // by id too, to ensure a consistent ordering just in case.
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS "FROM visits "
      "WHERE url=? "
      "ORDER BY visit_time DESC, id DESC "
      "LIMIT 1"));
  if (!statement)
    return 0;

  statement.BindInt64(0, url_id);
  if (!statement.Step())
    return 0;  // No visits for this URL.

  if (visit_row) {
    FillVisitRow(statement, visit_row);
    return visit_row->visit_id;
  }
  return statement.ColumnInt64(0);
}

bool VisitDatabase::GetMostRecentVisitsForURL(URLID url_id,
                                              int max_results,
                                              VisitVector* visits) {
  visits->clear();

  // The visit_time values can be duplicated in a redirect chain, so we sort
  // by id too, to ensure a consistent ordering just in case.
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT" HISTORY_VISIT_ROW_FIELDS
      "FROM visits "
      "WHERE url=? "
      "ORDER BY visit_time DESC, id DESC "
      "LIMIT ?"));
  if (!statement)
    return false;

  statement.BindInt64(0, url_id);
  statement.BindInt(1, max_results);
  FillVisitVector(statement, visits);
  return true;
}

bool VisitDatabase::GetRedirectFromVisit(VisitID from_visit,
                                         VisitID* to_visit,
                                         GURL* to_url) {
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT v.id,u.url "
      "FROM visits v JOIN urls u ON v.url = u.id "
      "WHERE v.from_visit = ? "
      "AND (v.transition & ?) != 0"));  // IS_REDIRECT_MASK
  if (!statement)
    return false;

  statement.BindInt64(0, from_visit);
  statement.BindInt(1, PageTransition::IS_REDIRECT_MASK);

  if (!statement.Step())
    return false;  // No redirect from this visit.
  if (to_visit)
    *to_visit = statement.ColumnInt64(0);
  if (to_url)
    *to_url = GURL(statement.ColumnString(1));
  return true;
}

bool VisitDatabase::GetRedirectToVisit(VisitID to_visit,
                                       VisitID* from_visit,
                                       GURL* from_url) {
  VisitRow row;
  if (!GetRowForVisit(to_visit, &row))
    return false;

  if (from_visit)
    *from_visit = row.referring_visit;

  if (from_url) {
    sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
        "SELECT u.url "
        "FROM visits v JOIN urls u ON v.url = u.id "
        "WHERE v.id = ?"));
    statement.BindInt64(0, row.referring_visit);

    if (!statement.Step())
      return false;

    *from_url = GURL(statement.ColumnString(0));
  }
  return true;
}

bool VisitDatabase::GetVisitCountToHost(const GURL& url,
                                        int* count,
                                        base::Time* first_visit) {
  if (!url.SchemeIs(chrome::kHttpScheme) && !url.SchemeIs(chrome::kHttpsScheme))
    return false;

  // We need to search for URLs with a matching host/port. One way to query for
  // this is to use the LIKE operator, eg 'url LIKE http://google.com/%'. This
  // is inefficient though in that it doesn't use the index and each entry must
  // be visited. The same query can be executed by using >= and < operator.
  // The query becomes:
  // 'url >= http://google.com/' and url < http://google.com0'.
  // 0 is used as it is one character greater than '/'.
  GURL search_url(url);
  const std::string host_query_min = search_url.GetOrigin().spec();

  if (host_query_min.empty())
    return false;

  std::string host_query_max = host_query_min;
  host_query_max[host_query_max.size() - 1] = '0';

  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT MIN(v.visit_time), COUNT(*) "
      "FROM visits v INNER JOIN urls u ON v.url = u.id "
      "WHERE (u.url >= ? AND u.url < ?)"));
  if (!statement)
    return false;

  statement.BindString(0, host_query_min);
  statement.BindString(1, host_query_max);

  if (!statement.Step()) {
    // We've never been to this page before.
    *count = 0;
    return true;
  }

  *first_visit = base::Time::FromInternalValue(statement.ColumnInt64(0));
  *count = statement.ColumnInt(1);
  return true;
}

bool VisitDatabase::GetStartDate(base::Time* first_visit) {
  sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE,
      "SELECT MIN(visit_time) FROM visits WHERE visit_time != 0"));
  if (!statement || !statement.Step() || statement.ColumnInt64(0) == 0) {
    *first_visit = base::Time::Now();
    return false;
  }
  *first_visit = base::Time::FromInternalValue(statement.ColumnInt64(0));
  return true;
}

void VisitDatabase::GetVisitsSource(const VisitVector& visits,
                                    VisitSourceMap* sources) {
  DCHECK(sources);
  sources->clear();

  // We query the source in batch. Here defines the batch size.
  const size_t batch_size = 500;
  size_t visits_size = visits.size();

  size_t start_index = 0, end_index = 0;
  while (end_index < visits_size) {
    start_index = end_index;
    end_index = end_index + batch_size < visits_size ? end_index + batch_size
                                                     : visits_size;

    // Compose the sql statement with a list of ids.
    std::string sql = "SELECT id,source FROM visit_source ";
    sql.append("WHERE id IN (");
    // Append all the ids in the statement.
    for (size_t j = start_index; j < end_index; j++) {
      if (j != start_index)
        sql.push_back(',');
      sql.append(base::Int64ToString(visits[j].visit_id));
    }
    sql.append(") ORDER BY id");
    sql::Statement statement(GetDB().GetUniqueStatement(sql.c_str()));
    if (!statement)
      return;

    // Get the source entries out of the query result.
    while (statement.Step()) {
      std::pair<VisitID, VisitSource> source_entry(statement.ColumnInt64(0),
          static_cast<VisitSource>(statement.ColumnInt(1)));
      sources->insert(source_entry);
    }
  }
}

}  // namespace history


text:
http://gregtatum.com/poems/raymarch

## Running

Make sure npm is install, then in the directory run `npm install` to get the dependencies.

To run and prototype with live-reload:

	npm run dev

To build:

	npm run build

Project copyright (c) 2014 Greg Tatum under The MIT License (MIT)


text:
package com.github.ndrlslz.utils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateUtils {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * Get date string with given year, month and day
     *
     * @param year  year
     * @param month month
     * @param day   day
     * @return date string
     */
    public static String getStringWith(int year, int month, int day) {
        return LocalDate.of(year, month, day).format(formatter);
    }

    /**
     * Get date string of today
     *
     * @return date string
     */
    public static String getStringOfNow() {
        return LocalDate.now().format(formatter);
    }

    /**
     * Get the day before given day.
     *
     * @param date date string
     * @return the day before given date
     */
    public static String getDayBefore(String date) {
        LocalDate yesterday = LocalDate.parse(date, formatter);
        return yesterday.minus(1, ChronoUnit.DAYS).format(formatter);
    }

}


text:
require({cache:{"url:gridx/templates/FilterConfirmDialog.html":"
${clearFilterMsg}

<input type=\"button\" data-dojo-type=\"dijit.form.Button\" label=\"${clearButton}\"\n\t/><input type=\"button\" data-dojo-type=\"dijit.form.Button\" label=\"${cancelButton}\"\n/>
\n"}});
define("gridx/modules/filter/FilterConfirmDialog",["dojo/_base/declare","dojo/string","dijit/Dialog","dojo/text!../../templates/FilterConfirmDialog.html","dojo/i18n!../../nls/FilterBar"],function(_1,_2,_3,_4,_5){
return _1(_3,{title:_5.clearFilterDialogTitle,cssClass:"gridxFilterConfirmDialog",autofocus:false,postCreate:function(){
this.inherited(arguments);
this.set("content",_2.substitute(_4,_5));
var _6=dijit.findWidgets(this.domNode);
this.btnClear=_6[0];
this.btnCancel=_6[1];
this.connect(this.btnCancel,"onClick","hide");
this.connect(this.btnClear,"onClick","onExecute");
this.connect(this,"show",function(){
this.btnCancel.focus();
});
},onExecute:function(){
this.execute();
},execute:function(){
}});
});


text:
from urllib.parse import urlparse

from zerver.lib.url_preview.types import UrlEmbedData

from .base import BaseParser

class OpenGraphParser(BaseParser):
    def extract_data(self) -> UrlEmbedData:
        meta = self._soup.findAll("meta")

        data = UrlEmbedData()

        for tag in meta:
            if not tag.has_attr("property"):
                continue
            if not tag.has_attr("content"):
                continue

            if tag["property"] == "og:title":
                data.title = tag["content"]
            elif tag["property"] == "og:description":
                data.description = tag["content"]
            elif tag["property"] == "og:image":
                try:
                    # We use urlparse and not URLValidator because we
                    # need to support relative URLs.
                    urlparse(tag["content"])
                except ValueError:
                    continue
                data.image = tag["content"]

        return data