text:
package sg.ncl.service.authentication.data.jpa;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

import javax.inject.Inject;

import static org.assertj.core.api.Assertions.assertThat;
import static sg.ncl.common.test.Checks.checkException;
import static sg.ncl.service.authentication.util.TestUtil.getPasswordResetRequestEntity;

/**
 * Created by dcszwang on 11/8/2016.
 */
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaAuditing
@ContextConfiguration(classes = PasswordResetRequestRepository.class)
@TestPropertySource(properties = "flyway.enabled=false")
public class PasswordResetRequestRepositoryTest {

    @Rule
    public final ExpectedException exception = ExpectedException.none();

    @Inject
    private PasswordResetRequestRepository repository;

    @Test
    public void testRepositoryExists() throws Exception {
        assertThat(repository).isNotNull();
    }

    @Test
    public void testGoodSave() throws Exception {
        final PasswordResetRequestEntity entity = getPasswordResetRequestEntity();

        final long count = repository.count();
        final PasswordResetRequestEntity saved = repository.saveAndFlush(entity);

        assertThat(repository.count()).isEqualTo(count + 1);
        assertThat(entity.getId()).isNotNull();
        assertThat(saved.getHash()).isEqualTo(entity.getHash());
        assertThat(saved.getUsername()).isEqualTo(entity.getUsername());
        assertThat(saved.getTime()).isEqualTo(entity.getTime());
    }

    @Test
    public void testSaveNullUsername() throws Exception {
        final PasswordResetRequestEntity entity = getPasswordResetRequestEntity();
        entity.setUsername(null);

        try {
            repository.saveAndFlush(entity);
            exception.expect(DataIntegrityViolationException.class);
        } catch (Exception e) {
            checkException(e, "NULL not allowed for column \"USERNAME\"");
        }
    }

    @Test
    public void testSaveNullHash() throws Exception {
        final PasswordResetRequestEntity entity = getPasswordResetRequestEntity();
        entity.setHash(null);

        try {
            repository.saveAndFlush(entity);
            exception.expect(DataIntegrityViolationException.class);
        } catch (Exception e) {
            checkException(e, "NULL not allowed for column \"HASH\"");
        }
    }

    @Test
    public void testSaveNullTime() throws Exception {
        final PasswordResetRequestEntity entity = getPasswordResetRequestEntity();
        entity.setTime(null);

        try {
            repository.saveAndFlush(entity);
            exception.expect(DataIntegrityViolationException.class);
        } catch (Exception e) {
            checkException(e, "NULL not allowed for column \"TIME\"");
        }
    }

    @Test
    public void testSaveDuplicateHash() throws Exception {
        final PasswordResetRequestEntity entity1 = getPasswordResetRequestEntity();
        final PasswordResetRequestEntity entity2 = getPasswordResetRequestEntity();
        entity2.setHash(entity1.getHash());

        repository.saveAndFlush(entity1);
        try {
            repository.saveAndFlush(entity2);
            exception.expect(DataIntegrityViolationException.class);
        } catch (Exception e) {
            checkException(e, "PUBLIC.PASSWORD_RESET_REQUESTS(HASH)");
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 36: 812 (1958)

#### Original name
Stilbospora chartarum Ehrenb., 1818

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package be.fluid_it.rµs.bundle.minimal.showcase.services;

import be.fluid_it.rµs.bundle.minimal.showcase.domain.CounterService;
import io.vertx.core.json.JsonObject;

public class SimpleCounterService implements CounterService{
    private int total = 0;

    @Override
    public void handleEvent(JsonObject event) {
        switch(event.getString("type")) {
            case "[Counter] Increment":
                total++;
                break;
            case "[Counter] Decrement":
                total--;
                break;
            case "[Counter] Reset":
                total = 0;
                break;
        }
    }

    @Override
    public int total() {
        return total;
    }
}


text:
<?php

namespace GetOptionKit\ValueType;

/**
 * An alias class for boolean type.
 */
class BoolType extends BooleanType
{
}


text:
'use strict';

/**
 * @ngdoc overview
 * @name fakeLunchHubApp
 * @description
 * # fakeLunchHubApp
 *
 * Main module of the application.
 */
var app = angular.module('fakeLunchHubApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ]);

app.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/main.html',
      controller: 'MainCtrl'
    })
    .when('/about', {
      templateUrl: 'views/about.html',
      controller: 'AboutCtrl'
    })
    .when('/groups', {
      templateUrl: 'views/groups.html',
      controller: 'GroupsCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
});

app.factory('Group', ['$resource', function($resource) {
  return $resource('/api/groups/:id.json', null, {
    'update': { method:'PUT' }
  });
}]);


text:
.. _dojox/form/manager/_NodeMixin:

=============================
dojox.form.manager._NodeMixin
=============================

:Project owner: Eugene Lazutkin
:since: 1.3

.. contents ::
   :depth: 3

Introduction
============

This class defines low-level primitives for form nodes. It is complimentary to and should be used together with :ref:`dojox.form.manager._Mixin <dojox/form/manager/_Mixin>`.

On startup this mixin inspects its body and registers all found form nodes (``<input>``, ``<select>``, ``<textarea>``, ``<button>``) unless they are part of some form widget.

Methods and properties
======================

This section describes all public methods and properties of the dojox.form.manager._NodeMixin class.

Value access
------------

Methods in this category provide primitives for low-level access to values of individual form elements. For high-level access to values use :ref:`_ValueMixin <dojox/form/manager/_ValueMixin>`.

formNodeValue
~~~~~~~~~~~~~

This method allows to get/set values of controlled form nodes. It is modeled after :ref:`dojox.form.manager._Mixin's formWidgetValue() <dojox/form/manager/_Mixin>`. It can be used two ways: with one parameter to get the value, and with two parameters to set the value:

.. js ::

  // reading the value
  var value = fm.formNodeValue("lastName");
  // writing the value
  fm.formNodeValue("lastName", "Smith");

The first parameter is a name of :ref:`a controlled form element <dojox/form/manager/index>` (a string). The optional second parameter is a value to be set. It is usually a string too.

The returned value is:

* A form element's value for the getter version.
* The form manager itself for the setter version providing easy chaining.

Inspection
----------

Methods in this category provide primitives to iterate over controlled elements. These methods are major building blocks for all other mixins. In most cases you should avoid using them directly relying on more high-level methods of other mixins. Do use them if you write your own mixins.

Note: this section is similar to
This method allows to get/set values of controlled form nodes. It is modeled after :ref:`dojox.form.manager._Mixin's inspectFormWidget() <dojox/form/manager/_Mixin>`.

inspectFormNodes
~~~~~~~~~~~~~~~~

This method iterates over controlled elements:

.. js ::

  var inspector = function(name, widget, value){
    var oldValue = this.formNodeValue(name);
    this.formNodeValue(name, value);
    return oldValue;
  };

  var state = ["firstName", "lastName"];

  var defaultValue = "X";

  fm.inspectFormNodes(inspector, state, defaultValue);

There are three ways to use this method:

1. ``state`` is an array of form names. In this case ``inspector`` is called with with the same 3rd parameter ``defaultValue`` for every node in the array. The above example uses this form of inspection: both ``lastName`` and ``firstName`` will be set to ``"X"``.

2. ``state`` is an object. In this case keys of the object are form names, while corresponding values are actual values to be passed to ``inspector`` as the 3rd parameter (in this case ``defaultValue`` is not used):

  .. js ::

    var state = {
      firstName: "Jill",
      lastName:  "Taylor"
    };
    fm.inspectFormNodes(inspector, state);

  The above example sets ``lastName`` to ``"Taylor"`` and ``firstName`` to ``"Jill"``.

3. ``state`` is ``null`` or missing. In this case the method will iterate over all controlled nodes passing ``defaultValue`` as the ``value`` parameter to ``inspector``.

  .. js ::

    fm.inspectFormNodes(inspector, null, "X");

  The above example sets all controlled widgets to ``"X"``.

While iterating the method collects all returned values of ``inspector`` in an object keyed by corresponding widget names, and returns it as the result.

.. js ::

  var state = {
    firstName: "Jill",
    lastName:  "Taylor"
  };
  var result = fm.inspectFormNodes(inspector, state);

  console.log(result.firstName);              // Jane
  console.log(result.lastName);               // Smith

  console.log(fm.formNodeValue("firstName")); // Jill
  console.log(fm.formNodeValue("lastName"));  // Taylor

``inspector`` function is called for every inspected node in the context of the form manager. It has following signature:

.. js ::

  var inspector = function(name, node, value){
    // ...
    return someValue;
  };

``name`` is the name of the inspected widget, ``node`` is the node itself, or an array of widgets for radio button nodes, ``value`` is the value passed to the function according to the above described rules. ``inspector``'s return value will be collected and returned as a part of the result object as described above.

What ``inspector`` does is up to you. It can modify or just read node values. It can return something meaningful or nothing at all. It is strongly suggested to use other form manager's methods to get/set node values rather than doing it manually.

Registration
------------

These functions can register/unregister form nodes. In most cases these methods are not used directly because dojox.form.manager._NodeMixin registers all children form nodes automatically. But if you create/delete nodes dynamically, you should register/unregister them manually.

Note: methods in this section are modeled on :ref:`dojox.form.manager._Mixin's registration <dojox/form/manager/_Mixin>`.

registerNode
~~~~~~~~~~~~

This method registers a form node with a form manager, and connects its observers. This node is not required to be a descendant of the form manager it is being registered with. This method is modeled on :ref:`dojox.form.manager._Mixin's registerWidget() <dojox/form/manager/_Mixin>`. Two signatures are recognized:

1. Register by node id:

  .. js ::

    fm.registerNode(id);

2. Register a DOM node:

  .. js ::

    fm.registerNode(node);

unregisterNode
~~~~~~~~~~~~~~

This method disconnects form node's observers, and removes it from internal structures of a form manager. This method is modeled on :ref:`dojox.form.manager._Mixin's unregisterWidget() <dojox/form/manager/_Mixin>`. The only way to unregister a form node is by its form name:

.. js ::

  fm.unregisterNode(name);

registerNodeDescendants
~~~~~~~~~~~~~~~~~~~~~~~

This method calls registerNode_ for every descendant form node of a given DOM node. This method is useful when you add several form nodes dynamically. These nodes do not need to be descendants of the form manager they are being registered with.

This method is modeled on :ref:`dojox.form.manager._Mixin's registerWidgetDescendants() <dojox/form/manager/_Mixin>`.

Like with registerNode_ two signatures are recognized:

1. Register by node id:

  .. js ::

    fm.registerNodeDescendants(id);

2. Register by specifying a DOM node:

  .. js ::

    fm.registerNodeDescendants(node);

unregisterNodeDescendants
~~~~~~~~~~~~~~~~~~~~~~~~~

This method calls unregisterNode_ for every descendant form node of a given DOM node. Its signature is the same as registerNodeDescendants_'s signature (both variants).

This method is modeled on :ref:`dojox.form.manager._Mixin's unregisterWidgetDescendants() <dojox/form/manager/_Mixin>`.

Lifecycle
---------

Lifecycle methods are part of every widget. They are used to initialize and destroy a widget. If you mix :ref:`dojox.form.manager._Mixin <dojox/form/manager/_Mixin>` in your own widget, make sure that these methods are not overwritten. If you overwrite them, make sure to call ``this.inherited(arguments)`` at the appropriate place, so they can initialize/destroy the widget properly.

destroy
~~~~~~~

This is the standard method of any widget. It is responsible for tearing up internal widget structures preparing the widget for the garbage collection. Usually it detaches event handlers, and kills references to DOM nodes. For more details, see :ref:`dijit._Widget <dijit/_Widget>`.

Additional functions
====================

dojox.form.manager.changeEvent
------------------------------

This is the low-level helper function, which returns an appropriate change event for a give DOM node.

.. js ::

  var button = dojo.doc.createElement("button"),
      select = dojo.doc.createElement("select");

  console.log(dojox.form.manager.changeEvent(button)); // onclick
  console.log(dojox.form.manager.changeEvent(select)); // onchange


text:
salt.states.pbm
===============

.. automodule:: salt.states.pbm
    :members:


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 339749 $ -->

<refentry xml:id="ds-map.capacity" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>Ds\Map::capacity</refname>
  <refpurpose>Returns the current capacity.</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>int</type><methodname>Ds\Map::capacity</methodname>
   <void />
  </methodsynopsis>
  <para>
    Returns the current capacity.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  &no.function.parameters;
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
    The current capacity.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <example>
   <title><function>Ds\Map::capacity</function> example</title>
   <programlisting role="php">
<![CDATA[
<?php
$map = new \Ds\Map();
var_dump($map->capacity());
?>
]]>
   </programlisting>
   &example.outputs.similar;
   <screen>
<![CDATA[
int(16)
]]>
   </screen>
  </example>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
'''
Custom filters for use in openshift-node
'''
from ansible import errors

class FilterModule(object):
    ''' Custom ansible filters for use by openshift_node role'''

    @staticmethod
    def get_dns_ip(openshift_dns_ip, hostvars):
        ''' Navigates the complicated logic of when to set dnsIP

            In all situations if they've set openshift_dns_ip use that
            For 1.0/3.0 installs we use the openshift_master_cluster_vip, openshift_node_first_master_ip, else None
            For 1.1/3.1 installs we use openshift_master_cluster_vip, else None (product will use kube svc ip)
            For 1.2/3.2+ installs we set to the node's default interface ip
        '''

        if not issubclass(type(hostvars), dict):
            raise errors.AnsibleFilterError("|failed expects hostvars is a dict")

        # We always use what they've specified if they've specified a value
        if openshift_dns_ip != None:
            return openshift_dns_ip

        if bool(hostvars['openshift']['common']['use_dnsmasq']):
            return hostvars['ansible_default_ipv4']['address']
        elif bool(hostvars['openshift']['common']['version_gte_3_1_or_1_1']):
            if 'openshift_master_cluster_vip' in hostvars:
                return hostvars['openshift_master_cluster_vip']
        else:
            if 'openshift_master_cluster_vip' in hostvars:
                return hostvars['openshift_master_cluster_vip']
            elif 'openshift_node_first_master_ip' in hostvars:
                return hostvars['openshift_node_first_master_ip']
        return None

    def filters(self):
        ''' returns a mapping of filters to methods '''
        return {'get_dns_ip': self.get_dns_ip}


text:
<?php

namespace PHPMentors\PageflowerBundle\Controller\Bundle\TestBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * @since Class available since Release 1.1.0
 */
class TestBundle extends Bundle
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="?colorPrimary"
                android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="DISCOVER MORE"

        android:textAlignment="center"
        android:textColor="@android:color/white"
        android:textSize="30dp"
        android:textStyle="bold"/>

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_below="@id/title"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:padding="10dp"
        android:src="@mipmap/intro_source"/>

    <TextView
        android:id="@+id/github"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/img"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="https://github.com/abertschi/flash-on-visit/"
        android:textAlignment="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/white"

        />

    <ch.abertschi.flashonvisit.view.TypewriterView
        android:id="@+id/tagline_typewriter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/github"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:editable="false"
        android:focusable="false"
        android:gravity="center"
        android:padding="30dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        android:windowSoftInputMode="stateHidden"/>

</RelativeLayout>


text:
var url = require('url');
var urlJoin = require('url-join');
var http = require('http');
var ServerResponse = http.ServerResponse;
var WebSocketServer = require('ws').Server;

var wsServers = {};

/**
 * @param {express.Application} app
 * @param {http.Server} [server]
 */
module.exports = function (app, server) {
  if(!server) {
    server = http.createServer(app);

    app.listen = function()
    {
      return server.listen.apply(server, arguments)
    }
  }

  function addSocketRoute(route, middleware, callback) {
    var args = [].splice.call(arguments, 0);
    var wsPath = urlJoin(app.mountpath, route);

    if (args.length < 2)
      throw new SyntaxError('Invalid number of arguments');

    if (args.length === 2) {
      middleware = [middleware];
    } else if (typeof middleware === 'object') {
      middleware.push(callback);
    } else {
      middleware = args.slice(1);
    }

    var wss = new WebSocketServer({
      server: server,
      path: wsPath
    });

    wsServers[wsPath] = wss;

    wss.on('connection', function(ws) {
      var response = new ServerResponse(ws.upgradeReq);
      response.writeHead = function (statusCode) {
        if (statusCode > 200) ws.close();
      };
      ws.upgradeReq.method = 'ws';

      app.handle(ws.upgradeReq, response, function(err) {
        var idx = 0;
        (function next (err) {
          if (err) return;
          var cur = middleware[idx++];
          if (!middleware[idx]) {
            cur(ws, ws.upgradeReq);
          } else {
            cur(ws.upgradeReq, response, next);
          }
        }(err));
      });
    });

    return app;
  };

  app.ws = addSocketRoute;

  return {
    app: app,
    getWss: function (route) {
      return wsServers[route];
    }
  };
};


text:
package org.jbehave.core.io.odf;

import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.InvalidStoryResource;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.LoadFromURL;
import org.jbehave.core.io.odf.OdfUtils.OdfDocumentLoadingFailed;
import org.jbehave.core.io.odf.OdfUtils.OdfDocumentParsingFailed;
import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class OdtLoaderBehaviour {

    @Test
    public void shouldLoadOdtResourceFromClasspath() {
        String resourceFromOdtWithTable = new LoadOdtFromClasspath(this.getClass())
                .loadResourceAsText("org/jbehave/core/io/odf/stories/a_story.odt");
        String resourceFromTxt = new LoadFromClasspath(this.getClass())
                .loadResourceAsText("org/jbehave/core/io/odf/stories/a_story.txt");
        assertThatOutputIs(resourceFromOdtWithTable.trim(), resourceFromTxt.trim());
    }

    @Test(expected = InvalidStoryResource.class)
    public void shouldNotLoadOdtResourceFromInexistingClasspathResource() {
        new LoadOdtFromClasspath(this.getClass())
                .loadResourceAsText("org/jbehave/core/io/odf/stories/an_inexisting_story.odt");
    }

    @Test
    public void shouldLoadOdtResourceFromURL() {
        String location = CodeLocations.codeLocationFromClass(this.getClass()).toString();
        String resourceFromOdtWithTable = new LoadOdtFromURL().loadResourceAsText(location
                + "org/jbehave/core/io/odf/stories/a_story.odt");
        String resourceFromTxt = new LoadFromURL().loadResourceAsText(location
                + "org/jbehave/core/io/odf/stories/a_story.txt");
        assertThatOutputIs(resourceFromOdtWithTable.trim(), resourceFromTxt.trim());
    }

    @Test(expected = InvalidStoryResource.class)
    public void shouldNotLoadOdtResourceFromInvalidURL() {
        // not a URL
        String location = CodeLocations.codeLocationFromClass(this.getClass()).getFile();
        new LoadOdtFromURL().loadResourceAsText(location + "org/jbehave/core/io/odf/stories/a_story.odt");
    }

    @Test(expected = InvalidStoryResource.class)
    public void shouldNotLoadOdtResourceFromInexistingURL() {
        String location = CodeLocations.codeLocationFromClass(this.getClass()).toString();
        new LoadOdtFromURL().loadResourceAsText(location + "org/jbehave/core/io/odf/stories/an_inexisting_story.odt");
    }

    @Test(expected = OdfDocumentLoadingFailed.class)
    public void shouldNotLoadInvalidOdfResources() {
        OdfUtils.loadOdt(null);
    }

    @Test(expected = OdfDocumentParsingFailed.class)
    public void shouldNotParseInvalidOdfResources() {
        OdfUtils.parseOdt(null);
    }

    @Test
    public void shouldKeepCoberturaHappy() {
        Assert.assertNotNull(new OdfUtils());
    }

    // copied from core/TemplatableOutputBehaviour
    private void assertThatOutputIs(String out, String expected) {
        assertEquals(dos2unix(expected), dos2unix(out));
    }

    private String dos2unix(String string) {
        return string.replace("\r\n", "\n");
    }

}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.itl_energy.webapi;

import java.util.Set;
import javax.ws.rs.core.MediaType;

/**
 * Defines the REST application programmatically to avoid more config files.
 *
 * @author Gordon
 */
@javax.ws.rs.ApplicationPath("api")
public class ItlEnergyApplication extends javax.ws.rs.core.Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
        // following code can be used to customize Jersey 2.0 JSON provider:
        try {
            Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
            // Class jsonProvider = Class.forName("org.glassfish.jersey.moxy.json.MoxyJsonFeature");
            // Class jsonProvider = Class.forName("org.glassfish.jersey.jettison.JettisonFeature");
            resources.add(jsonProvider);
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        addRestResourceClasses(resources);
        return resources;
    }

    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically re-generated by NetBeans REST support to populate
     * given list with all resources defined in the project.
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(com.itl_energy.webapi.ActuationsResource.class);
        resources.add(com.itl_energy.webapi.AuthenticationResource.class);
        resources.add(com.itl_energy.webapi.DeployedSensorResource.class);
        resources.add(com.itl_energy.webapi.ElectricalLoadForecastResource.class);
        resources.add(com.itl_energy.webapi.ElectricalLoadResource.class);
        resources.add(com.itl_energy.webapi.ForecastStatusResource.class);
        resources.add(com.itl_energy.webapi.GenerationResource.class);
        resources.add(com.itl_energy.webapi.HouseResource.class);
        resources.add(com.itl_energy.webapi.HubLogResource.class);
        resources.add(com.itl_energy.webapi.HubResource.class);
        resources.add(com.itl_energy.webapi.MeasurementResource.class);
        resources.add(com.itl_energy.webapi.ResourceBase.class);
        resources.add(com.itl_energy.webapi.SensorResource.class);
        resources.add(com.itl_energy.webapi.SiteResource.class);
        resources.add(com.itl_energy.webapi.StatusEventResource.class);
        resources.add(com.itl_energy.webapi.TariffBlockResource.class);
        resources.add(com.itl_energy.webapi.TariffResource.class);
        resources.add(com.itl_energy.webapi.UserResource.class);
        resources.add(com.itl_energy.webapi.WeatherForecastResource.class);
        resources.add(com.itl_energy.webapi.WeatherResource.class);
        resources.add(com.itl_energy.webcore.NotAuthorizedHandler.class);
    }

}


text:
namespace Microsoft.TemplateEngine.Core.Operations
{
    // The commonly used conditional types. If more get added to ConditionalConfig.cs, they should be added here too.
    public enum ConditionalType
    {
        None,
        Xml,
        Razor,
        CNoComments,
        CLineComments,
        CBlockComments,
        HashSignLineComment,
        RemLineComment,
        MSBuild,
        HamlLineComment,
        JsxBlockComment
    }
}


text:
import {GraphResponse} from "./GraphResponse";
import {AttributesMapperFactory} from "../mappers/AttributesMapperFactory";

export class GraphResponseFactory {

    constructor(public attributesMapperFactory:AttributesMapperFactory) {}

    build(response:Promise<any>):GraphResponse {
        return GraphResponse.initWithAutoMapper(response, this.attributesMapperFactory);
    }
}


text:
package edu.towson.cis.cosc603.project2.monopoly;

import java.util.ArrayList;
import java.util.Iterator;

// TODO: Auto-generated Javadoc
/**
 * The Class GameMaster.
 */
public class GameMaster {

	/** The game master. */
	private static GameMaster gameMaster;

	/** The Constant MAX_PLAYER. */
	static final public int MAX_PLAYER = 8;

	/** The dice. */
	private Die[] dice;

	/** The game board. */
	private GameBoard gameBoard;

	/** The gui. */
	private MonopolyGUI gui;

	/** The init amount of money. */
	private int initAmountOfMoney;

	/** The players. */
	private ArrayList<Player> players = new ArrayList<Player>();

	/** The turn. */
	private int turn = 0;

	/** The util dice roll. */
	private int utilDiceRoll;

	/** The test mode. */
	private boolean testMode;

	/**
	 * Instance.
	 *
	 * @return the game master
	 */
	public static GameMaster instance() {
		if(gameMaster == null) {
			gameMaster = new GameMaster();
		}
		return gameMaster;
	}

	/**
	 * Instantiates a new game master.
	 */
	public GameMaster() {
		initAmountOfMoney = 1500;
		dice = new Die[]{new Die(), new Die()};
	}

    /**
     * Btn buy house clicked.
     */
    public void btnBuyHouseClicked() {
        gui.showBuyHouseDialog(getCurrentPlayer());
    }

    /**
     * Btn draw card clicked.
     *
     * @return the card
     */
    public Card btnDrawCardClicked() {
        gui.setDrawCardEnabled(false);
        CardCell cell = (CardCell)getCurrentPlayer().getPosition();
        Card card = null;
        if(cell.getType() == Card.TYPE_CC) {
            card = getGameBoard().drawCCCard();
            card.applyAction();
        } else {
            card = getGameBoard().drawChanceCard();
            card.applyAction();
        }
        gui.setEndTurnEnabled(true);
        return card;
    }

    /**
     * Btn end turn clicked.
     */
    public void btnEndTurnClicked() {
		setAllButtonEnabled(false);
		getCurrentPlayer().getPosition().playAction(null);
		if(getCurrentPlayer().isBankrupt()) {
			gui.setBuyHouseEnabled(false);
			gui.setDrawCardEnabled(false);
			gui.setEndTurnEnabled(false);
			gui.setGetOutOfJailEnabled(false);
			gui.setPurchasePropertyEnabled(false);
			gui.setRollDiceEnabled(false);
			gui.setTradeEnabled(getCurrentPlayerIndex(),false);
			updateGUI();
		}
		else {
			switchTurn();
			updateGUI();
		}
    }

    /**
     * Btn get out of jail clicked.
     */
    public void btnGetOutOfJailClicked() {
		getCurrentPlayer().getOutOfJail();
		if(getCurrentPlayer().isBankrupt()) {
			gui.setBuyHouseEnabled(false);
			gui.setDrawCardEnabled(false);
			gui.setEndTurnEnabled(false);
			gui.setGetOutOfJailEnabled(false);
			gui.setPurchasePropertyEnabled(false);
			gui.setRollDiceEnabled(false);
			gui.setTradeEnabled(getCurrentPlayerIndex(),false);
		}
		else {
			gui.setRollDiceEnabled(true);
			gui.setBuyHouseEnabled(getCurrentPlayer().canBuyHouse());
			gui.setGetOutOfJailEnabled(getCurrentPlayer().isInJail());
		}
    }

    /**
     * Btn purchase property clicked.
     */
    public void btnPurchasePropertyClicked() {
        Player player = getCurrentPlayer();
		player.purchase();
		gui.setPurchasePropertyEnabled(false);
		updateGUI();
    }

    /**
     * Btn roll dice clicked.
     */
    public void btnRollDiceClicked() {
		int[] rolls = rollDice();
		if((rolls[0]+rolls[1]) > 0) {
			Player player = getCurrentPlayer();
			gui.setRollDiceEnabled(false);
			StringBuffer msg = new StringBuffer();
			msg.append(player.getName())
					.append(", you rolled ")
					.append(rolls[0])
					.append(" and ")
					.append(rolls[1]);
			gui.showMessage(msg.toString());
			movePlayer(player, rolls[0] + rolls[1]);
			gui.setBuyHouseEnabled(false);
		}
    }

    /**
     * Btn trade clicked.
     */
    public void btnTradeClicked() {
        TradeDialog dialog = gui.openTradeDialog();
        TradeDeal deal = dialog.getTradeDeal();
        if(deal != null) {
            RespondDialog rDialog = gui.openRespondDialog(deal);
            if(rDialog.getResponse()) {
                completeTrade(deal);
                updateGUI();
            }
        }
    }

    /**
     * Complete trade.
     *
     * @param deal the deal
     */
    public void completeTrade(TradeDeal deal) {
        Player seller = getPlayer(deal.getPlayerIndex());
        Cell property = gameBoard.queryCell(deal.getPropertyName());
        seller.sellProperty(property, deal.getAmount());
        getCurrentPlayer().buyProperty(property, deal.getAmount());
    }

    /**
     * Draw cc card.
     *
     * @return the card
     */
    public Card drawCCCard() {
        return gameBoard.drawCCCard();
    }

    /**
     * Draw chance card.
     *
     * @return the card
     */
    public Card drawChanceCard() {
        return gameBoard.drawChanceCard();
    }

	/**
	 * Gets the current player.
	 *
	 * @return the current player
	 */
	public Player getCurrentPlayer() {
		return getPlayer(turn);
	}

    /**
     * Gets the current player index.
     *
     * @return the current player index
     */
    public int getCurrentPlayerIndex() {
        return turn;
    }

	/**
	 * Gets the game board.
	 *
	 * @return the game board
	 */
	public GameBoard getGameBoard() {
		return gameBoard;
	}

    /**
     * Gets the gui.
     *
     * @return the gui
     */
    public MonopolyGUI getGUI() {
        return gui;
    }

	/**
	 * Gets the inits the amount of money.
	 *
	 * @return the inits the amount of money
	 */
	public int getInitAmountOfMoney() {
		return initAmountOfMoney;
	}

	/**
	 * Gets the number of players.
	 *
	 * @return the number of players
	 */
	public int getNumberOfPlayers() {
		return players.size();
	}

    /**
     * Gets the number of sellers.
     *
     * @return the number of sellers
     */
    public int getNumberOfSellers() {
        return players.size() - 1;
    }

	/**
	 * Gets the player.
	 *
	 * @param index the index
	 * @return the player
	 */
	public Player getPlayer(int index) {
		return (Player)players.get(index);
	}

	/**
	 * Gets the player index.
	 *
	 * @param player the player
	 * @return the player index
	 */
	public int getPlayerIndex(Player player) {
		return players.indexOf(player);
	}

    /**
     * Gets the seller list.
     *
     * @return the seller list
     */
    public ArrayList<Player> getSellerList() {
        ArrayList<Player> sellers = new ArrayList<Player>();
        for (Iterator<Player> iter = players.iterator(); iter.hasNext();) {
            Player player = (Player) iter.next();
            if(player != getCurrentPlayer()) sellers.add(player);
        }
        return sellers;
    }

	/**
	 * Gets the turn.
	 *
	 * @return the turn
	 */
	public int getTurn() {
		return turn;
	}

	/**
	 * Gets the util dice roll.
	 *
	 * @return the util dice roll
	 */
	public int getUtilDiceRoll() {
		return this.utilDiceRoll;
	}

	/**
	 * Move player.
	 *
	 * @param playerIndex the player index
	 * @param diceValue the dice value
	 */
	public void movePlayer(int playerIndex, int diceValue) {
		Player player = (Player)players.get(playerIndex);
		movePlayer(player, diceValue);
	}

	/**
	 * Move player.
	 *
	 * @param player the player
	 * @param diceValue the dice value
	 */
	public void movePlayer(Player player, int diceValue) {
		Cell currentPosition = player.getPosition();
		int positionIndex = gameBoard.queryCellIndex(currentPosition.getName());
		int newIndex = (positionIndex+diceValue)%gameBoard.getCellNumber();
		if(newIndex <= positionIndex || diceValue > gameBoard.getCellNumber()) {
			player.setMoney(player.getMoney() + 200);
		}
		player.setPosition(gameBoard.getCell(newIndex));
		gui.movePlayer(getPlayerIndex(player), positionIndex, newIndex);
		playerMoved(player);
		updateGUI();
	}

	/**
	 * Player moved.
	 *
	 * @param player the player
	 */
	public void playerMoved(Player player) {
		Cell cell = player.getPosition();
		int playerIndex = getPlayerIndex(player);
		cell.playerMoved(player, playerIndex, this);
        gui.setTradeEnabled(turn, false);
	}

	/**
	 * Reset.
	 */
	public void reset() {
		setPlayerPosition();
		turn = 0;
		if (gameBoard != null) {
			gameBoard.removeCards();
		}
	}

	/**
	 * Extracted setPlayerPosition() from reset();.
	 */
	private void setPlayerPosition() {
		for (int i = 0; i < getNumberOfPlayers(); i++) {
			Player player = (Player) players.get(i);
			player.setPosition(gameBoard.getCell(0));
		}

	}

	/**
	 * Roll dice.
	 *
	 * @return the int[]
	 */
	public int[] rollDice() {
		if(testMode) {
			return gui.getDiceRoll();
		}
		else {
			return new int[]{
					dice[0].getRoll(),
					dice[1].getRoll()
			};
		}
	}

	/**
	 * Send to jail.
	 *
	 * @param player the player
	 */
	public void sendToJail(Player player) {
	    int oldPosition = gameBoard.queryCellIndex(getCurrentPlayer().getPosition().getName());
		player.setPosition(gameBoard.queryCell("Jail"));
		player.setInJail(true);
		int jailIndex = gameBoard.queryCellIndex("Jail");
		gui.movePlayer(
		        getPlayerIndex(player),
		        oldPosition,
		        jailIndex);
	}

	/**
	 * Sets the all button enabled.
	 *
	 * @param enabled the new all button enabled
	 */
	private void setAllButtonEnabled(boolean enabled) {
		gui.setRollDiceEnabled(enabled);
		gui.setPurchasePropertyEnabled(enabled);
		gui.setEndTurnEnabled(enabled);
        gui.setTradeEnabled(turn, enabled);
        gui.setBuyHouseEnabled(enabled);
        gui.setDrawCardEnabled(enabled);
        gui.setGetOutOfJailEnabled(enabled);
	}

	/**
	 * Sets the game board.
	 *
	 * @param board the new game board
	 */
	public void setGameBoard(GameBoard board) {
		this.gameBoard = board;
	}

	/**
	 * Sets the gui.
	 *
	 * @param gui the new gui
	 */
	public void setGUI(MonopolyGUI gui) {
		this.gui = gui;
	}

	/**
	 * Sets the inits the amount of money.
	 *
	 * @param money the new inits the amount of money
	 */
	public void setInitAmountOfMoney(int money) {
		this.initAmountOfMoney = money;
	}

	/**
	 * Sets the number of players.
	 *
	 * @param number the new number of players
	 */
	public void setNumberOfPlayers(int number) {
		players.clear();
		for(int i =0;i<number;i++) {
			Player player = new Player();
			player.setMoney(initAmountOfMoney);
			players.add(player);
		}
	}

	/**
	 * Sets the util dice roll.
	 *
	 * @param diceRoll the new util dice roll
	 */
	public void setUtilDiceRoll(int diceRoll) {
		this.utilDiceRoll = diceRoll;
	}

	/**
	 * Start game.
	 */
	public void startGame() {
		gui.startGame();
		gui.enablePlayerTurn(0);
        gui.setTradeEnabled(0, true);
	}

	/**
	 * Switch turn.
	 */
	public void switchTurn() {
		turn = (turn + 1) % getNumberOfPlayers();
		if(!getCurrentPlayer().isInJail()) {
			gui.enablePlayerTurn(turn);
			gui.setBuyHouseEnabled(getCurrentPlayer().canBuyHouse());
            gui.setTradeEnabled(turn, true);
		}
		else {
			gui.setGetOutOfJailEnabled(true);
		}
	}

	/**
	 * Update gui.
	 */
	public void updateGUI() {
		gui.update();
	}

	/**
	 * Util roll dice.
	 */
	public void utilRollDice() {
		this.utilDiceRoll = gui.showUtilDiceRoll();
	}

	/**
	 * Sets the test mode.
	 *
	 * @param b the new test mode
	 */
	public void setTestMode(boolean b) {
		testMode = b;
	}
}


text:
package com.sunyj.pebbletodo.custom;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.widget.Toast;

import com.sunyj.pebbletodo.R;
import com.sunyj.pebbletodo.activity.AboutActivity;
import com.sunyj.pebbletodo.activity.FolderManageActivity;
import com.sunyj.pebbletodo.activity.LoginActivity;
import com.sunyj.pebbletodo.activity.MainActivity;
import com.sunyj.pebbletodo.activity.PebbleReceiverBaseActivity;
import com.sunyj.pebbletodo.activity.SituationManageActivity;
import com.sunyj.pebbletodo.util.AnalyticsApplication;

public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
    AnalyticsApplication app;

    private Preference accountPreference;
    private Preference folderPreference;
    private Preference situationPreference;
    private Preference aboutPreference;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences_layout);
        app = (AnalyticsApplication) getActivity().getApplication();

        accountPreference = findPreference(getString(R.string.account_key));
        updateAccountPreference();
        accountPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                Log.i(PebbleReceiverBaseActivity.LOG_TAG, "click.. " + preference.getKey());
                final SharedPreferences sharedPreferences = getActivity().getSharedPreferences(LoginActivity.SHARED_PREF_LOGIN_DATA, Context.MODE_PRIVATE);
                String mEmail = sharedPreferences.getString(LoginActivity.SHARED_PREF_KEY_EMAIL, "");
                if (mEmail.equals("")) {
                    Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
                    startActivityForResult(intent, MainActivity.REQUEST_ID_LOGIN);
                } else {
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
                    alertDialogBuilder.setTitle(getString(R.string.be_sure_log_out));
                    alertDialogBuilder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.remove(LoginActivity.SHARED_PREF_KEY_EMAIL);
                            editor.putBoolean(LoginActivity.SHARED_PREF_KEY_DATA_CHANGED, true);
                            editor.apply();
                            Toast.makeText(getActivity().getApplicationContext(), "Log out successful!", Toast.LENGTH_SHORT).show();
                            updateAccountPreference();
                        }
                    });
                    alertDialogBuilder.setNegativeButton(getString(R.string.cancel), null);
                    alertDialogBuilder.show();
                }
                return true;
            }
        });

        folderPreference = findPreference(getString(R.string.folder_key));
        folderPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                Intent intent = new Intent(getActivity(), FolderManageActivity.class);
                startActivity(intent);
                return true;
            }
        });

        situationPreference = findPreference(getString(R.string.situation_key));
        situationPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(new Intent(getActivity(), SituationManageActivity.class));
                return false;
            }
        });

        aboutPreference = findPreference(getString(R.string.about_key));
        aboutPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                Intent intent = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent);
                return true;
            }
        });
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Log.i(PebbleReceiverBaseActivity.LOG_TAG, "pref.. " + key);
        PreferenceKeys preferenceKeys = new PreferenceKeys(getResources());
        if (key.equals(preferenceKeys.night_mode_pref_key)) {
            SharedPreferences themePreferences = getActivity().getSharedPreferences(MainActivity.THEME_PREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor themeEditor = themePreferences.edit();
            //We tell our MainLayout to recreate itself because mode has changed
            themeEditor.putBoolean(MainActivity.RECREATE_ACTIVITY, true);

            CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference(preferenceKeys.night_mode_pref_key);
            if (checkBoxPreference.isChecked()) {
                //Comment out this line if not using Google Analytics
                app.send(this, "Settings", "Night Mode used");
                themeEditor.putString(MainActivity.THEME_SAVED, MainActivity.DARKTHEME);
            } else {
                themeEditor.putString(MainActivity.THEME_SAVED, MainActivity.LIGHTTHEME);
            }
            themeEditor.apply();

            getActivity().recreate();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MainActivity.REQUEST_ID_LOGIN) {
            updateAccountPreference();
        }
    }

    public void updateAccountPreference() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(LoginActivity.SHARED_PREF_LOGIN_DATA, Context.MODE_PRIVATE);
        String mEmail = sharedPreferences.getString(LoginActivity.SHARED_PREF_KEY_EMAIL, "");
        if (mEmail.equals("")) {
            accountPreference.setTitle(getString(R.string.no_account));
            accountPreference.setSummary(getString(R.string.title_activity_login));
        } else {
            accountPreference.setTitle(mEmail);
            accountPreference.setSummary(getString(R.string.log_out));
        }
    }
}


text:
namespace llvm {
  class BasicBlock;
  class Instruction;
  class LoadInst;
  template<typename T> class SmallVectorImpl;
  template<typename T> class SSAUpdaterTraits;
  class PHINode;
  class Type;
  class Use;
  class Value;

/// \brief Helper class for SSA formation on a set of values defined in
/// multiple blocks.
///
/// This is used when code duplication or another unstructured
/// transformation wants to rewrite a set of uses of one value with uses of a
/// set of values.
class SSAUpdater {
  friend class SSAUpdaterTraits<SSAUpdater>;

private:
  /// This keeps track of which value to use on a per-block basis. When we
  /// insert PHI nodes, we keep track of them here.
  //typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
  void *AV;

  /// ProtoType holds the type of the values being rewritten.
  Type *ProtoType;

  /// PHI nodes are given a name based on ProtoName.
  std::string ProtoName;

  /// If this is non-null, the SSAUpdater adds all PHI nodes that it creates to
  /// the vector.
  SmallVectorImpl<PHINode*> *InsertedPHIs;

public:
  /// If InsertedPHIs is specified, it will be filled
  /// in with all PHI Nodes created by rewriting.
  explicit SSAUpdater(SmallVectorImpl<PHINode*> *InsertedPHIs = nullptr);
  ~SSAUpdater();

  /// \brief Reset this object to get ready for a new set of SSA updates with
  /// type 'Ty'.
  ///
  /// PHI nodes get a name based on 'Name'.
  void Initialize(Type *Ty, StringRef Name);

  /// \brief Indicate that a rewritten value is available in the specified block
  /// with the specified value.
  void AddAvailableValue(BasicBlock *BB, Value *V);

  /// \brief Return true if the SSAUpdater already has a value for the specified
  /// block.
  bool HasValueForBlock(BasicBlock *BB) const;

  /// \brief Construct SSA form, materializing a value that is live at the end
  /// of the specified block.
  Value *GetValueAtEndOfBlock(BasicBlock *BB);

  /// \brief Construct SSA form, materializing a value that is live in the
  /// middle of the specified block.
  ///
  /// \c GetValueInMiddleOfBlock is the same as \c GetValueAtEndOfBlock except
  /// in one important case: if there is a definition of the rewritten value
  /// after the 'use' in BB.  Consider code like this:
  ///
  /// \code
  ///      X1 = ...
  ///   SomeBB:
  ///      use(X)
  ///      X2 = ...
  ///      br Cond, SomeBB, OutBB
  /// \endcode
  ///
  /// In this case, there are two values (X1 and X2) added to the AvailableVals
  /// set by the client of the rewriter, and those values are both live out of
  /// their respective blocks.  However, the use of X happens in the *middle* of
  /// a block.  Because of this, we need to insert a new PHI node in SomeBB to
  /// merge the appropriate values, and this value isn't live out of the block.
  Value *GetValueInMiddleOfBlock(BasicBlock *BB);

  /// \brief Rewrite a use of the symbolic value.
  ///
  /// This handles PHI nodes, which use their value in the corresponding
  /// predecessor. Note that this will not work if the use is supposed to be
  /// rewritten to a value defined in the same block as the use, but above it.
  /// Any 'AddAvailableValue's added for the use's block will be considered to
  /// be below it.
  void RewriteUse(Use &U);

  /// \brief Rewrite a use like \c RewriteUse but handling in-block definitions.
  ///
  /// This version of the method can rewrite uses in the same block as
  /// a definition, because it assumes that all uses of a value are below any
  /// inserted values.
  void RewriteUseAfterInsertions(Use &U);

private:
  Value *GetValueAtEndOfBlockInternal(BasicBlock *BB);

  void operator=(const SSAUpdater&) = delete;
  SSAUpdater(const SSAUpdater&) = delete;
};

/// \brief Helper class for promoting a collection of loads and stores into SSA
/// Form using the SSAUpdater.
///
/// This handles complexities that SSAUpdater doesn't, such as multiple loads
/// and stores in one block.
///
/// Clients of this class are expected to subclass this and implement the
/// virtual methods.
class LoadAndStorePromoter {
protected:
  SSAUpdater &SSA;

public:
  LoadAndStorePromoter(ArrayRef<const Instruction*> Insts,
                       SSAUpdater &S, StringRef Name = StringRef());
  virtual ~LoadAndStorePromoter() {}

  /// \brief This does the promotion.
  ///
  /// Insts is a list of loads and stores to promote, and Name is the basename
  /// for the PHIs to insert. After this is complete, the loads and stores are
  /// removed from the code.
  void run(const SmallVectorImpl<Instruction*> &Insts) const;

  /// \brief Return true if the specified instruction is in the Inst list.
  ///
  /// The Insts list is the one passed into the constructor. Clients should
  /// implement this with a more efficient version if possible.
  virtual bool isInstInList(Instruction *I,
                            const SmallVectorImpl<Instruction*> &Insts) const;

  /// \brief This hook is invoked after all the stores are found and inserted as
  /// available values.
  virtual void doExtraRewritesBeforeFinalDeletion() const {
  }

  /// \brief Clients can choose to implement this to get notified right before
  /// a load is RAUW'd another value.
  virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const {
  }

  /// \brief Called before each instruction is deleted.
  virtual void instructionDeleted(Instruction *I) const {
  }

  /// \brief Called to update debug info associated with the instruction.
  virtual void updateDebugInfo(Instruction *I) const {
  }
};

} // End llvm namespace

#endif


text:
<?php

namespace Contentful;

use Contentful\Log\NullLogger;
use Contentful\Log\StandardTimer;
use Contentful\Exception\NotFoundException;
use Contentful\Exception\RateLimitExceededException;
use Contentful\Exception\InvalidQueryException;
use Contentful\Exception\AccessTokenInvalidException;
use GuzzleHttp\ClientInterface as GuzzleClientInterface;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\ClientException;
use Contentful\Log\LoggerInterface;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;

/**
 * Abstract client for common code for the different clients.
 */
abstract class Client
{
    /**
     * @var GuzzleClientInterface
     */
    private $httpClient;

    /**
     * @var Psr7\Uri
     */
    private $baseUri;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var string
     */
    private $api;

    /**
     * @var string
     */
    private $token;

    /**
     * @var string
     */
    private $applicationName;

    /**
     * @var string
     */
    private $applicationVersion;

    /**
     * @var string
     */
    private $integrationName;

    /**
     * @var string
     */
    private $integrationVersion;

    /*
     * @var string|null
     */
    private $contentfulUserAgent;

    /**
     * Client constructor.
     *
     * @param string                $token
     * @param string                $baseUri
     * @param string                $api
     * @param LoggerInterface       $logger
     * @param GuzzleClientInterface $guzzle
     */
    public function __construct($token, $baseUri, $api, LoggerInterface $logger = null, GuzzleClientInterface $guzzle = null)
    {
        $this->token = $token;
        $this->logger = $logger ?: new NullLogger();

        $this->api = $api;
        $this->baseUri = new Psr7\Uri($baseUri);
        $this->httpClient = $guzzle ?: new GuzzleClient();
        $this->contentfulUserAgent = $this->getContentfulUserAgent();
    }

    /**
     * Set the application name and version. The values are used as part of the X-Contentful-User-Agent header.
     *
     * @param string|null $name
     * @param string|null $version
     *
     * @return $this
     */
    public function setApplication($name, $version = null)
    {
        $this->applicationName = $name;
        $this->applicationVersion = $version;

        // Update the cached value
        $this->contentfulUserAgent = $this->getContentfulUserAgent();

        return $this;
    }

    /**
     * Set the application name and version. The values are used as part of the X-Contentful-User-Agent header.
     *
     * @param string|null $name
     * @param string|null $version
     *
     * @return $this
     */
    public function setIntegration($name, $version = null)
    {
        $this->integrationName = $name;
        $this->integrationVersion = $version;

        // Update the cached value
        $this->contentfulUserAgent = $this->getContentfulUserAgent();

        return $this;
    }

    /**
     * @param string $method
     * @param string $path
     * @param array  $options
     *
     * @return array
     */
    protected function request($method, $path, array $options = [])
    {
        $timer = new StandardTimer;
        $timer->start();

        $query = isset($options['query']) ? $options['query'] : null;
        if ($query) {
            unset($options['query']);
        }
        $request = $this->buildRequest($method, $path, $query);

        // We define this variable so it's also available in the catch block.
        $response = null;
        try {
            $response = $this->doRequest($request, $options);
            $result = self::decodeJson($response->getBody());
        } catch (\Exception $e) {
            $timer->stop();
            $this->logger->log($this->api, $request, $timer, $response, $e);

            throw $e;
        }

        $timer->stop();
        $this->logger->log($this->api, $request, $timer, $response);

        return $result;
    }

    /**
     * @param  RequestInterface $request
     * @param  array            $options
     *
     * @return \Psr\Http\Message\ResponseInterface|null
     */
    private function doRequest(RequestInterface $request, array $options)
    {
        try {
            return $this->httpClient->send($request, $options);
        } catch (ClientException $e) {
            $response = $e->getResponse();
            if ($response->getStatusCode() === 404) {
                $result = self::decodeJson($response->getBody());
                throw new NotFoundException($result['message'], 0, $e);
            }
            if ($response->getStatusCode() === 429) {
                $result = self::decodeJson($response->getBody());
                $rateLimitReset = (int) $response->getHeader('X-Contentful-RateLimit-Reset')[0];
                throw new RateLimitExceededException($result['message'], 0, $e, $rateLimitReset);
            }
            if ($response->getStatusCode() === 400) {
                $result = self::decodeJson($response->getBody());
                if ($result['sys']['id'] === 'InvalidQuery') {
                    throw new InvalidQueryException($result['message'], 0, $e);
                }
            }
            if ($response->getStatusCode() === 401) {
                $result = self::decodeJson($response->getBody());
                if ($result['sys']['id'] === 'AccessTokenInvalid') {
                    throw new AccessTokenInvalidException($result['message'], 0, $e);
                }
            }

            throw $e;
        }
    }

    /**
     * @param  string            $method
     * @param  string            $path
     * @param  array|string|null $query
     *
     * @return Psr7\Request
     *
     * @throws \InvalidArgumentException If $query is not a valid type
     */
    private function buildRequest($method, $path, $query = null)
    {
        $contentTypes = [
            'DELIVERY' => 'application/vnd.contentful.delivery.v1+json',
            'PREVIEW' => 'application/vnd.contentful.delivery.v1+json',
            'MANAGEMENT' => 'application/vnd.contentful.management.v1+json'
        ];

        $uri = Psr7\UriResolver::resolve($this->baseUri, new Psr7\Uri($path));

        if ($query) {
            if (is_array($query)) {
                $query = http_build_query($query, null, '&', PHP_QUERY_RFC3986);
            }
            if (!is_string($query)) {
                throw new \InvalidArgumentException('query must be a string or array');
            }
            $uri = $uri->withQuery($query);
        }

        return new Psr7\Request($method, $uri, [
            'X-Contentful-User-Agent' => $this->contentfulUserAgent,
            'Accept' => $contentTypes[$this->api],
            'Accept-Encoding' => 'gzip',
            'Authorization' => 'Bearer ' . $this->token,
        ], null);
    }

    /**
     * The name of the library to be used in the User-Agent header.
     *
     * @return string
     */
    abstract protected function getSdkNameAndVersion();

    /**
     * Returns the value of the User-Agent header for any requests made to Contentful
     *
     * @return string
     */
    protected function getContentfulUserAgent()
    {
        $possibleOperatingSystems = [
            'WINNT' => 'Windows',
            'Darwin' => 'macOS'
        ];

        $parts = [
            'app' => '',
            'integration' => '',
            'sdk' => $this->getSdkNameAndVersion(),
            'platform' => 'PHP/' . \PHP_VERSION,
            'os' => isset($possibleOperatingSystems[PHP_OS]) ? $possibleOperatingSystems[PHP_OS] : 'Linux'
        ];

        if ($this->applicationName !== null) {
            $parts['app'] = $this->applicationName;
            if ($this->applicationVersion !== null) {
                $parts['app'] .= '/' . $this->applicationVersion;
            }
        }

        if ($this->integrationName !== null) {
            $parts['integration'] = $this->integrationName;
            if ($this->integrationVersion !== null) {
                $parts['integration'] .= '/' . $this->integrationVersion;
            }
        }

        $agent = '';
        foreach ($parts as $key => $value) {
            if ($value === '') {
                continue;
            }
            $agent .= $key . ' ' . $value . '; ';
        }

        return trim($agent);
    }

    /**
     * @param  string $json JSON encoded object or array
     *
     * @return array
     *
     * @throws \RuntimeException On invalid JSON
     *
     * @internal
     */
    public static function decodeJson($json)
    {
        $result = json_decode($json, true);
        if ($result === null) {
            throw new \RuntimeException(json_last_error_msg(), json_last_error());
        }

        return $result;
    }
}


text:
To run integration tests faster you can set the following system properties...

```
-DtestServer=lumify-dev -Drepository.ontology=io.lumify.core.model.ontology.InMemoryOntologyRepository
```


text:
#pragma once

namespace graphite2 {

class Position
{
public:
    Position() : x(0), y(0) { }
    Position(const float inx, const float iny) : x(inx), y(iny) {}
    Position operator + (const Position& a) const { return Position(x + a.x, y + a.y); }
    Position operator - (const Position& a) const { return Position(x - a.x, y - a.y); }
    Position operator * (const float m) const { return Position(x * m, y * m); }
    Position &operator += (const Position &a) { x += a.x; y += a.y; return *this; }
    Position &operator *= (const float m) { x *= m; y *= m; return *this; }

    float x;
    float y;
};

class Rect
{
public :
    Rect() {}
    Rect(const Position& botLeft, const Position& topRight): bl(botLeft), tr(topRight) {}
    Rect widen(const Rect& other) { return Rect(Position(bl.x > other.bl.x ? other.bl.x : bl.x, bl.y > other.bl.y ? other.bl.y : bl.y), Position(tr.x > other.tr.x ? tr.x : other.tr.x, tr.y > other.tr.y ? tr.y : other.tr.y)); }
    Rect operator + (const Position &a) const { return Rect(Position(bl.x + a.x, bl.y + a.y), Position(tr.x + a.x, tr.y + a.y)); }
    Rect operator - (const Position &a) const { return Rect(Position(bl.x - a.x, bl.y - a.y), Position(tr.x - a.x, tr.y - a.y)); }
    Rect operator * (float m) const { return Rect(Position(bl.x, bl.y) * m, Position(tr.x, tr.y) * m); }
    float width() const { return tr.x - bl.x; }
    float height() const { return tr.y - bl.y; }

    bool hitTest(Rect &other);

    // returns Position(overlapx, overlapy) where overlap<0 if overlapping else positive)
    Position overlap(Position &offset, Rect &other, Position &otherOffset);
    //Position constrainedAvoid(Position &offset, Rect &box, Rect &sdbox, Position &other, Rect &obox, Rect &osdbox);

    Position bl;
    Position tr;
};

} // namespace graphite2


text:
package ru.job4j.h3list.t3simplestackandqueue;
import java.util.NoSuchElementException;

/**
 * @param <E> is the name of type parameter.
 */
public class LinkList<E> {
    /**
     * The ref to the first element in the list.
     */
    private Link<E> first;
    /**
     * The ref to the last element in the list.
     */
    private Link<E> last;

    /**
     * @param value to be added to the list on the first position.
     */
    public void addFirst(E value) {
        Link<E> newLink = new Link<>(value);
        if (isEmpty()) {
            last = newLink;
        }
        newLink.next = first;
        first = newLink;
    }

    /**
     * @param value to be added to the list on the last position.
     */
    public void addLast(E value) {
        Link<E> newLink = new Link<>(value);
        if (isEmpty()) {
            first = newLink;
        } else {
            last.next = newLink;
        }
        last = newLink;
    }

    /**
     * @return the value that is deleted from the first position in the list.
     */
    public E removeFirst() {
        if (!isEmpty()) {
            Link<E> newLink = first;
            first = first.next;
            return newLink.data;
        } else {
            throw new NoSuchElementException();
        }
    }

    /**
     * @param position which value should be found.
     * @return the value according to the found position.
     */
    public E get(int position) {
        int val = 1;
        Link<E> curr = first;
        while ((curr != null) && (val < position)) {
            curr = curr.next;
            val++;
        }
        if ((curr == null) || (position < val)) {
            throw new IndexOutOfBoundsException();
        }
        return curr.data;
    }

    /**
     * @return true or false.
     */
    private boolean isEmpty() {
        return first == null;
    }
//-----------------------------------------
    /**
     * @param <E> is the name of type parameter.
     */
    private class Link<E> {
        /**
         * Data for storing.
         */
        private E data;
        /**
         * The ref to the next element.
         */
        private Link<E> next;
        /**
         * @param data is the value for the constructor.
         */
        private Link(E data) {
            this.data = data;
        }
    }
}


text:
package de.rwth_aachen.roboterclub.serial.ui;

import java.util.Enumeration;
import java.awt.*;
import javax.swing.*;
import de.rwth_aachen.roboterclub.serial.io.Connection;
import de.rwth_aachen.roboterclub.serial.io.ConnectionSupervisor;
import de.rwth_aachen.roboterclub.serial.io.PortIdentifier;

import java.awt.event.*;

@SuppressWarnings("serial")
public class PnlConnection extends JPanel implements ConnectionSupervisor {
	private String preferredPort;
	private Connection connection;
	JComboBox jComboBox1 = new JComboBox();
	FlowLayout flowLayout1 = new FlowLayout();
	JButton cmbConnect = new JButton();
	JButton cmbDisconnect = new JButton();
	JButton cmbEnumPorts = new JButton();

	public void setConnection(Connection connection) {
		this.connection = connection;
		connection.setPnlConnection(this);
	}

	public PnlConnection() {
		try {
			jbInit();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	void jbInit() throws Exception {
		this.setLayout(flowLayout1);
		jComboBox1.setMinimumSize(new Dimension(150, 19));
		jComboBox1.setPreferredSize(new Dimension(150, 19));
		cmbConnect.setText("Connect");
		cmbConnect.addActionListener(new PnlConnection_cmbConnect_actionAdapter(this));
		cmbDisconnect.setText("Disconnect");
		cmbDisconnect.addActionListener(new PnlConnection_cmbDisconnect_actionAdapter(this));
		cmbEnumPorts.setText("EnumPorts");
		cmbEnumPorts.addActionListener(new PnlConnection_cmbEnumPorts_actionAdapter(this));
		this.add(cmbEnumPorts, null);
		this.add(jComboBox1, null);
		this.add(cmbConnect, null);
		this.add(cmbDisconnect, null);
	}

	public void closeAll() {
		connection.disconnect();
	}
	void cmbConnect_actionPerformed(ActionEvent e) {
		if(connection.isConnected())
			connection.disconnect();
		Object o = jComboBox1.getSelectedItem();
		preferredPort = o.toString();
		connection.connect(o);
	}

	void cmbEnumPorts_actionPerformed(ActionEvent e) {
		if (!connection.isConnected()) {
			setShowState(STATE_DISCONNECTED);
			jComboBox1.removeAllItems();
			Enumeration<PortIdentifier> enu = connection.enumPorts();
			while (enu.hasMoreElements()){
				PortIdentifier p = enu.nextElement();
				jComboBox1.addItem(p);
				if (preferredPort != null && p.toString().equals(preferredPort))
					jComboBox1.setSelectedItem(p);
			}
		}
		else{
			setShowState(STATE_CONNECTED);
		}
	}

	void cmbDisconnect_actionPerformed(ActionEvent e) {
		connection.disconnect();
	}

	@Override
	public void setShowState(int state){
		cmbConnect.setEnabled(state!=STATE_CONNECTED);
		cmbDisconnect.setEnabled(state==STATE_CONNECTED);
		jComboBox1.setEnabled(state!=STATE_CONNECTED);
		/*    switch(state){
      case STATE_CONNECTED:
        cmbConnect.setEnabled(false);
        cmbDisconnect.setEnabled(true);
        jComboBox1.setEnabled(false);
        break;
      case STATE_DISCONNECTED:
        cmbConnect.setEnabled(true);
        cmbDisconnect.setEnabled(false);
        jComboBox1.setEnabled(true);
        break;
    }*/
	}

	public String getPreferredPort() {
		return preferredPort;
	}
	public void setPreferredPort(String preferredPort) {
		this.preferredPort = preferredPort;
	}

	public void populatePortList() {
		cmbEnumPorts.doClick();
	}
}

class PnlConnection_cmbConnect_actionAdapter implements java.awt.event.ActionListener {
	PnlConnection adaptee;

	PnlConnection_cmbConnect_actionAdapter(PnlConnection adaptee) {
		this.adaptee = adaptee;
	}
	public void actionPerformed(ActionEvent e) {
		adaptee.cmbConnect_actionPerformed(e);
	}
}

class PnlConnection_cmbEnumPorts_actionAdapter implements java.awt.event.ActionListener {
	PnlConnection adaptee;

	PnlConnection_cmbEnumPorts_actionAdapter(PnlConnection adaptee) {
		this.adaptee = adaptee;
	}
	public void actionPerformed(ActionEvent e) {
		adaptee.cmbEnumPorts_actionPerformed(e);
	}
}

class PnlConnection_cmbDisconnect_actionAdapter implements java.awt.event.ActionListener {
	PnlConnection adaptee;

	PnlConnection_cmbDisconnect_actionAdapter(PnlConnection adaptee) {
		this.adaptee = adaptee;
	}
	public void actionPerformed(ActionEvent e) {
		adaptee.cmbDisconnect_actionPerformed(e);
	}
}


text:
Cover

Home

Features

Cover your page.

Cover is a one-page template for building simple and beautiful home pages. Download, edit the text, and add your own fullscreen background photo to make it your own.

          Learn more

Cover template for Bootstrap, by @mdo.


text:
var Checker = require('../../lib/checker');
var assert = require('assert');

describe('rules/disallow-anonymous-functions', function() {
    var checker;

    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();

        checker.configure({
            disallowAnonymousFunctions: true
        });
    });

    it('should report on anonymous function declarations', function() {
        assert(checker.checkString('$("hi").click(function(){});').getErrorCount() === 1);
    });

    it('should report on anonymous function expressions', function() {
        assert(checker.checkString('var x = function(){};').getErrorCount() === 1);
        assert(checker.checkString('var foo = {bar: function() {}};').getErrorCount() === 1);
    });

    it('should not report on named function declarations', function() {
        assert(checker.checkString('function named(){};').isEmpty());
    });

    it('should not report on named function expressions', function() {
        assert(checker.checkString('$("hi").click(function named(){});').isEmpty());
        assert(checker.checkString('var x = function named(){};').isEmpty());
    });
});


text:
import unittest

import tempfile
from pathlib import Path

from g1.bases import collections as g1_collections
from g1.files import caches

class CacheTest(unittest.TestCase):

    def setUp(self):
        super().setUp()
        self._test_dir_tempdir = tempfile.TemporaryDirectory()
        self.test_dir_path = Path(self._test_dir_tempdir.name)

    def tearDown(self):
        self._test_dir_tempdir.cleanup()
        super().tearDown()

    def assert_cache_dir(self, entries):
        self.assertEqual(
            {
                path.relative_to(self.test_dir_path): path.read_bytes()
                for dir_path in self.test_dir_path.iterdir()
                for path in dir_path.iterdir()
            },
            {
                caches.Cache._get_relpath(key): value
                for key, value in entries.items()
            },
        )

    def assert_access_log(self, cache, access_log):
        self.assertEqual(
            list(cache._access_log.items()),
            [(cache._get_path(key), count) for key, count in access_log],
        )
        get_recency = cache._make_get_recency()
        for recency, (key, _) in enumerate(access_log):
            self.assertEqual(get_recency(cache._get_path(key)), recency)
        self.assertEqual(get_recency(Path('no-such-key')), len(access_log))

    def assert_active_paths(self, cache, active_paths):
        self.assertEqual(
            cache._active_paths,
            g1_collections.Multiset(active_paths),
        )

    def test_init(self):
        dir_path = self.test_dir_path / '00'
        dir_path.mkdir()
        for i in range(10):
            path = self.test_dir_path / ('00/%030d' % i)
            path.touch()
            with self.subTest(i):
                cache = caches.Cache(self.test_dir_path, 10)
                # No eviction yet.
                self.assertEqual(cache._eviction_countdown, 10 - i - 1)
                self.assertEqual(len(list(dir_path.iterdir())), i + 1)

    def test_init_with_eviction(self):
        dir_path = self.test_dir_path / '00'
        dir_path.mkdir()
        for i in range(20):
            path = self.test_dir_path / ('00/%030d' % i)
            path.touch()
        cache = caches.Cache(self.test_dir_path, 10)
        # __init__ evicts.
        self.assertEqual(cache._eviction_countdown, 2)
        self.assertEqual(len(list(dir_path.iterdir())), 8)

    def test_init_invalid_args(self):
        with self.assertRaisesRegex(AssertionError, r'expect.*is_dir'):
            caches.Cache(self.test_dir_path / 'foo', 100)
        with self.assertRaisesRegex(AssertionError, r'expect x > 0, not -1'):
            caches.Cache(self.test_dir_path, -1)
        with self.assertRaisesRegex(
            AssertionError, r'expect 0 <= post_eviction_size <= 1, not 2'
        ):
            caches.Cache(self.test_dir_path, 1, post_eviction_size=2)
        with self.assertRaisesRegex(
            AssertionError, r'expect 0 <= post_eviction_size <= 1, not -1'
        ):
            caches.Cache(self.test_dir_path, 1, post_eviction_size=-1)

    def test_access_log(self):
        cache = caches.Cache(self.test_dir_path, 100)
        self.assert_access_log(cache, [])

        cache.set(b'0', b'0')
        self.assert_access_log(cache, [(b'0', 1)])
        cache.set(b'1', b'1')
        self.assert_access_log(cache, [(b'1', 1), (b'0', 1)])
        cache.set(b'2', b'2')
        self.assert_access_log(cache, [(b'2', 1), (b'1', 1), (b'0', 1)])

        cache.set(b'0', b'4')
        self.assert_access_log(cache, [(b'0', 2), (b'2', 1), (b'1', 1)])
        self.assertEqual(cache.get(b'0'), b'4')
        self.assert_access_log(cache, [(b'0', 3), (b'2', 1), (b'1', 1)])
        self.assertEqual(cache.get(b'1'), b'1')
        self.assert_access_log(cache, [(b'1', 2), (b'0', 3), (b'2', 1)])
        self.assertEqual(cache.get(b'1'), b'1')
        self.assert_access_log(cache, [(b'1', 3), (b'0', 3), (b'2', 1)])

        self.assertIsNone(cache.get(b'4'))
        self.assert_access_log(cache, [(b'1', 3), (b'0', 3), (b'2', 1)])

    def test_estimate_size(self):
        cache = caches.Cache(self.test_dir_path, 100)
        self.assertEqual(cache.estimate_size(), 0)
        self.assert_cache_dir({})
        cache.set(b'0', b'')
        self.assertEqual(cache.estimate_size(), 1)
        self.assert_cache_dir({b'0': b''})
        cache.set(b'1', b'')
        self.assertEqual(cache.estimate_size(), 2)
        self.assert_cache_dir({b'0': b'', b'1': b''})
        cache.set(b'2', b'')
        self.assertEqual(cache.estimate_size(), 3)
        self.assert_cache_dir({b'0': b'', b'1': b'', b'2': b''})

    def test_evict(self):
        cache = caches.Cache(self.test_dir_path, 10)
        dir_path = self.test_dir_path / '00'
        dir_path.mkdir()
        for i in range(10):
            path = self.test_dir_path / ('00/%030d' % i)
            path.touch()
            cache._access_log[path] = 1
        self.assertEqual(len(list(dir_path.iterdir())), 10)
        self.assertEqual(len(cache._access_log), 10)

        self.assertEqual(cache.evict(), 2)
        self.assertEqual(len(list(dir_path.iterdir())), 8)
        self.assertEqual(len(cache._access_log), 8)
        self.assertEqual(cache._eviction_countdown, 2)

        for i in range(10, 20):
            path = self.test_dir_path / ('00/%030d' % i)
            path.touch()
            cache._access_log[path] = 1
        self.assertEqual(len(list(dir_path.iterdir())), 18)
        self.assertEqual(len(cache._access_log), 18)

        self.assertEqual(cache.evict(), 10)
        self.assertEqual(len(list(dir_path.iterdir())), 8)
        self.assertEqual(len(cache._access_log), 8)
        self.assertEqual(cache._eviction_countdown, 2)

    def test_evict_full(self):
        cache = caches.Cache(self.test_dir_path, 10, post_eviction_size=0)
        dir_path = self.test_dir_path / '00'
        dir_path.mkdir()
        for i in range(10):
            path = self.test_dir_path / ('00/%030d' % i)
            path.touch()
            cache._access_log[path] = 1
        self.assertEqual(len(list(dir_path.iterdir())), 10)
        self.assertEqual(len(cache._access_log), 10)

        self.assertEqual(cache.evict(), 10)
        self.assertFalse(dir_path.exists())
        self.assertEqual(len(cache._access_log), 0)
        self.assertEqual(cache._eviction_countdown, 10)

    def test_evict_order(self):
        cache = caches.Cache(self.test_dir_path, 10)
        dir_path = self.test_dir_path / '00'
        dir_path.mkdir()
        for i in range(10):
            path = self.test_dir_path / ('00/%030d' % i)
            path.touch()
            cache._log_access(path)
        self.assertEqual(len(list(dir_path.iterdir())), 10)
        self.assertEqual(len(cache._access_log), 10)

        get_recency = cache._make_get_recency()
        self.assertEqual(cache._evict_dir(dir_path, 8, get_recency), 2)
        self.assertEqual(
            sorted(dir_path.iterdir()),
            [self.test_dir_path / ('00/%030d' % i) for i in range(2, 10)],
        )
        self.assertEqual(
            sorted(cache._access_log),
            [self.test_dir_path / ('00/%030d' % i) for i in range(2, 10)],
        )

        get_recency = cache._make_get_recency()
        self.assertEqual(cache._evict_dir(dir_path, 0, get_recency), 8)
        self.assertFalse(dir_path.exists())
        self.assertEqual(cache._access_log, {})

    def test_get_file(self):
        cache = caches.Cache(self.test_dir_path, 10)
        cache.set(b'some key', b'some value')

        f, size = cache.get_file(b'some key')
        with f:
            self.assertTrue(Path(f.name).exists())
            self.assertEqual(f.read(), b'some value')
        self.assertEqual(size, 10)

        f, size = cache.get_file(b'some key')
        with f:
            cache.pop(b'some key')
            self.assertFalse(Path(f.name).exists())
            self.assertEqual(f.read(), b'some value')
        self.assertEqual(size, 10)

        self.assertIsNone(cache.get_file(b'some key'))

    def test_getting_path(self):
        cache = caches.Cache(self.test_dir_path, 10, post_eviction_size=0)
        cache.set(b'some key', b'some value')
        self.assert_active_paths(cache, [])

        with cache.getting_path(b'some key') as p1:
            self.assertIsNotNone(p1)
            self.assert_active_paths(cache, [p1])
            with cache.getting_path(b'some key') as p2:
                self.assertIsNotNone(p2)
                self.assertEqual(p1, p2)
                self.assert_active_paths(cache, [p1, p2])
                self.assertEqual(cache.evict(), 0)
            self.assert_active_paths(cache, [p1])
            self.assertEqual(cache.evict(), 0)

        self.assert_active_paths(cache, [])
        self.assertEqual(cache.evict(), 1)

        with cache.getting_path(b'no such key') as path:
            self.assertIsNone(path)
            self.assert_active_paths(cache, [])
        self.assert_active_paths(cache, [])

    def test_set(self):
        cache = caches.Cache(self.test_dir_path, 10)
        self.assert_access_log(cache, [])
        self.assertEqual(cache._eviction_countdown, 10)

        for i in range(10):
            cache.set(b'%d' % i, b'%d' % i)
            self.assert_cache_dir({b'%d' % j: b'%d' % j for j in range(i + 1)})
            self.assert_access_log(
                cache,
                [(b'%d' % j, 1) for j in reversed(range(i + 1))],
            )
            self.assertEqual(cache._eviction_countdown, 10 - i - 1)

        self.assert_cache_dir({b'%d' % i: b'%d' % i for i in range(10)})
        self.assert_access_log(
            cache,
            [(b'%d' % i, 1) for i in reversed(range(10))],
        )
        self.assertEqual(cache._eviction_countdown, 0)

        cache.set(b'10', b'10')
        # Cache over-evicted because post_eviction_size is much less
        # than 256.
        self.assert_access_log(cache, [])
        self.assertEqual(cache._eviction_countdown, 10)
        self.assertEqual(len(list(self.test_dir_path.iterdir())), 0)

    def test_setting_file(self):
        cache = caches.Cache(self.test_dir_path, 10)

        with cache.setting_file(b'some key') as value_file:
            self.assertFalse(cache._lock.locked())
            value_file.write(b'some value')

        self.assertEqual(cache.get(b'some key'), b'some value')
        self.assert_cache_dir({b'some key': b'some value'})

    def test_setting_file_error(self):
        cache = caches.Cache(self.test_dir_path, 10)
        self.assert_cache_dir({})

        with self.assertRaisesRegex(Exception, r'expected'):
            with cache.setting_file(b'some other key'):
                self.assert_cache_dir({})
                raise Exception('expected')

        self.assertIsNone(cache.get(b'some other key'))
        self.assert_cache_dir({})

    def test_pop(self):
        cache = caches.Cache(self.test_dir_path, 10)
        with self.assertRaises(KeyError):
            cache.pop(b'0')
        self.assertIsNone(cache.pop(b'0', None))

        cache.set(b'0', b'0')
        self.assert_access_log(cache, [(b'0', 1)])
        self.assertEqual(cache._eviction_countdown, 9)
        self.assertEqual(len(list(self.test_dir_path.iterdir())), 1)

        self.assertEqual(cache.pop(b'0'), b'0')
        self.assert_access_log(cache, [])
        self.assertEqual(cache._eviction_countdown, 10)
        self.assertEqual(len(list(self.test_dir_path.iterdir())), 0)

if __name__ == '__main__':
    unittest.main()