text:
package org.apache.ambari.server.api.services;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.ambari.annotations.ApiIgnore;
import org.apache.ambari.server.api.resources.ResourceInstance;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

/**
 * Service responsible for host_components resource requests.
 */
public class HostComponentService extends BaseService {
  /**
   * Parent cluster id.
   */
  private String m_clusterName;

  /**
   * Parent host id.
   */
  private String m_hostName;

  /**
   * Constructor.
   *
   * @param clusterName cluster id
   * @param hostName    host id
   */
  public HostComponentService(String clusterName, String hostName) {
    m_clusterName = clusterName;
    m_hostName = hostName;
  }

  /**
   * Handles GET /clusters/{clusterID}/hosts/{hostID}/host_components/{hostComponentID}
   * Get a specific host_component.
   *
   * @param headers           http headers
   * @param ui                uri info
   * @param hostComponentName host_component id
   * @return host_component resource representation
   */
  @GET @ApiIgnore // until documented
  @Path("{hostComponentName}")
  @Produces("text/plain")
  public Response getHostComponent(String body, @Context HttpHeaders headers, @Context UriInfo ui,
                                   @PathParam("hostComponentName") String hostComponentName, @QueryParam("format") String format) {

    //todo: needs to be refactored when properly handling exceptions
    if (m_hostName == null) {
      // don't allow case where host is not in url but a host_component instance resource is requested
      String s = "Invalid request. Must provide host information when requesting a host_resource instance resource.";
      return Response.status(400).entity(s).build();
    }

    if (format != null && format.equals("client_config_tar")) {
      return createClientConfigResource(body, headers, ui, hostComponentName);
    }

    return handleRequest(headers, body, ui, Request.Type.GET,
        createHostComponentResource(m_clusterName, m_hostName, hostComponentName));
  }

  /**
   * Handles GET /clusters/{clusterID}/hosts/{hostID}/host_components/
   * Get all host components for a host.
   *
   * @param headers http headers
   * @param ui      uri info
   * @return host_component collection resource representation
   */
  @GET @ApiIgnore // until documented
  @Produces("text/plain")
  public Response getHostComponents(String body, @Context HttpHeaders headers, @Context UriInfo ui, @QueryParam("format") String format) {
    if (format != null && format.equals("client_config_tar")) {
      return createClientConfigResource(body, headers, ui, null);
    }
    return handleRequest(headers, body, ui, Request.Type.GET,
        createHostComponentResource(m_clusterName, m_hostName, null));
  }

  /**
   * Handles POST /clusters/{clusterID}/hosts/{hostID}/host_components
   * Create host components by specifying an array of host components in the http body.
   * This is used to create multiple host components in a single request.
   *
   * @param body              http body
   * @param headers           http headers
   * @param ui                uri info
   *
   * @return status code only, 201 if successful
   */
  @POST @ApiIgnore // until documented
  @Produces("text/plain")
  public Response createHostComponents(String body, @Context HttpHeaders headers, @Context UriInfo ui) {

    return handleRequest(headers, body, ui, Request.Type.POST,
        createHostComponentResource(m_clusterName, m_hostName, null));
  }

  /**
   * Handles POST /clusters/{clusterID}/hosts/{hostID}/host_components/{hostComponentID}
   * Create a specific host_component.
   *
   * @param body              http body
   * @param headers           http headers
   * @param ui                uri info
   * @param hostComponentName host_component id
   *
   * @return host_component resource representation
   */
  @POST @ApiIgnore // until documented
  @Path("{hostComponentName}")
  @Produces("text/plain")
  public Response createHostComponent(String body, @Context HttpHeaders headers, @Context UriInfo ui,
                                   @PathParam("hostComponentName") String hostComponentName) {

    return handleRequest(headers, body, ui, Request.Type.POST,
        createHostComponentResource(m_clusterName, m_hostName, hostComponentName));
  }

  /**
   * Handles PUT /clusters/{clusterID}/hosts/{hostID}/host_components/{hostComponentID}
   * Updates a specific host_component.
   *
   * @param body              http body
   * @param headers           http headers
   * @param ui                uri info
   * @param hostComponentName host_component id
   *
   * @return information regarding updated host_component
   */
  @PUT @ApiIgnore // until documented
  @Path("{hostComponentName}")
  @Produces("text/plain")
  public Response updateHostComponent(String body, @Context HttpHeaders headers, @Context UriInfo ui,
                                      @PathParam("hostComponentName") String hostComponentName) {

    return handleRequest(headers, body, ui, Request.Type.PUT,
        createHostComponentResource(m_clusterName, m_hostName, hostComponentName));
  }

  /**
   * Handles PUT /clusters/{clusterID}/hosts/{hostID}/host_components
   * Updates multiple host_component resources.
   *
   * @param body              http body
   * @param headers           http headers
   * @param ui                uri info
   *
   * @return information regarding updated host_component resources
   */
  @PUT @ApiIgnore // until documented
  @Produces("text/plain")
  public Response updateHostComponents(String body, @Context HttpHeaders headers, @Context UriInfo ui) {

    return handleRequest(headers, body, ui, Request.Type.PUT,
        createHostComponentResource(m_clusterName, m_hostName, null));
  }

  /**
   * Handles DELETE /clusters/{clusterID}/hosts/{hostID}/host_components/{hostComponentID}
   * Delete a specific host_component.
   *
   * @param headers           http headers
   * @param ui                uri info
   * @param hostComponentName host_component id
   *
   * @return host_component resource representation
   */
  @DELETE @ApiIgnore // until documented
  @Path("{hostComponentName}")
  @Produces("text/plain")
  public Response deleteHostComponent(@Context HttpHeaders headers, @Context UriInfo ui,
                                   @PathParam("hostComponentName") String hostComponentName) {

    return handleRequest(headers, null, ui, Request.Type.DELETE,
        createHostComponentResource(m_clusterName, m_hostName, hostComponentName));
  }

  /**
   * Handles DELETE /clusters/{clusterID}/hosts/{hostID}/host_components
   * Deletes multiple host_component resources.
   *
   * @param headers           http headers
   * @param ui                uri info
   *
   * @return host_component resource representation
   */
  @DELETE @ApiIgnore // until documented
  @Produces("text/plain")
  public Response deleteHostComponents(String body, @Context HttpHeaders headers, @Context UriInfo ui) {

    return handleRequest(headers, body, ui, Request.Type.DELETE,
        createHostComponentResource(m_clusterName, m_hostName, null));
  }

  @GET @ApiIgnore // until documented
  @Path("{hostComponentName}/processes")
  @Produces("text/plain")
  public Response getProcesses(@Context HttpHeaders headers, @Context UriInfo ui,
      @PathParam("hostComponentName") String hostComponentName) {
    Map<Resource.Type,String> mapIds = new HashMap<>();
    mapIds.put(Resource.Type.Cluster, m_clusterName);
    mapIds.put(Resource.Type.Host, m_hostName);
    mapIds.put(Resource.Type.HostComponent, hostComponentName);

    ResourceInstance ri = createResource(Resource.Type.HostComponentProcess, mapIds);

    return handleRequest(headers, null, ui, Request.Type.GET, ri);
  }

  /**
   * Create a host_component resource instance.
   *
   * @param clusterName       cluster name
   * @param hostName          host name
   * @param hostComponentName host_component name
   *
   * @return a host resource instance
   */
  ResourceInstance createHostComponentResource(String clusterName, String hostName, String hostComponentName) {
    Map<Resource.Type,String> mapIds = new HashMap<>();
    mapIds.put(Resource.Type.Cluster, clusterName);
    mapIds.put(Resource.Type.Host, hostName);
    mapIds.put(Resource.Type.HostComponent, hostComponentName);

    return createResource(Resource.Type.HostComponent, mapIds);
  }

  private Response createClientConfigResource(String body, HttpHeaders headers, UriInfo ui,
                                              String hostComponentName) {
    Map<Resource.Type,String> mapIds = new HashMap<>();
    mapIds.put(Resource.Type.Cluster, m_clusterName);
    mapIds.put(Resource.Type.Host, m_hostName);
    mapIds.put(Resource.Type.Component, hostComponentName);

    Response response = handleRequest(headers, body, ui, Request.Type.GET,
            createResource(Resource.Type.ClientConfig, mapIds));

    //If response has errors return response
    if (response.getStatus() != 200) {
      return response;
    }

    String filePrefixName;

    if (StringUtils.isEmpty(hostComponentName)) {
      filePrefixName = m_hostName + "(" + Resource.InternalType.Host.toString().toUpperCase()+")";
    } else {
      filePrefixName = hostComponentName;
    }

    Validate.notNull(filePrefixName, "compressed config file name should not be null");
    String fileName =  filePrefixName + "-configs" + Configuration.DEF_ARCHIVE_EXTENSION;

    Response.ResponseBuilder rb = Response.status(Response.Status.OK);
    Configuration configs = new Configuration();
    String tmpDir = configs.getProperty(Configuration.SERVER_TMP_DIR.getKey());
    File file = new File(tmpDir,fileName);
    InputStream resultInputStream = null;
    try {
      resultInputStream = new FileInputStream(file);
    } catch (IOException e) {
      e.printStackTrace();
    }

    String contentType = Configuration.DEF_ARCHIVE_CONTENT_TYPE;
    rb.header("Content-Disposition",  "attachment; filename=\"" + fileName + "\"");
    rb.entity(resultInputStream);
    return rb.type(contentType).build();

  }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<title>jQuery custom scrollbar demo</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />

	<link rel="stylesheet" href="style.css">

	<link rel="stylesheet" href="../jquery.mCustomScrollbar.css">

Add image

Remove image

Plugin home Project on Github MIT License

redpajama_set_name: RedPajamaGithub


text:
package blobstoretest;

import blobstoretest.shared.FileData;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.Entity;
import com.google.common.base.Function;

/**
 * Utility class for {@link FileData} conversions.
 *
 * @author Andrés Testi
 */
public class FileDataConverters {

  private static final Function<Entity, FileData> ENTITY_TO_FILE_DATA =
      new Function<Entity, FileData>() {
        @Override
        public FileData apply(Entity entity) {
          return entityToFileData(entity);
        }
      };

  private static final Function<FileData, Entity> FILE_DATA_TO_ENTITY =
      new Function<FileData, Entity>() {
        public Entity apply(FileData fileData) {
          return fileDataToEntity(fileData);
        }
      };

  private static final Function<BlobInfo, FileData> BLOB_INFO_TO_FILE_DATA =
      new Function<BlobInfo, FileData>() {
        @Override
        public FileData apply(BlobInfo blobInfo) {
          return blobInfoToFileData(blobInfo);
        }
      };

  public static Function<Entity, FileData> entityToFileData() {
    return ENTITY_TO_FILE_DATA;
  }

  public static Function<FileData, Entity> fileDataToEntity() {
    return FILE_DATA_TO_ENTITY;
  }

  public static Function<BlobInfo, FileData> blobInfoToEntity() {
    return BLOB_INFO_TO_FILE_DATA;
  }

  public static FileData entityToFileData(Entity entity) {
    FileData fileData = new FileData();
    fileData.setBlobKey((BlobKey) entity.getProperty("blobKey"));
    fileData.setFilename((String) entity.getProperty("filename"));
    return fileData;
  }

  public static Entity fileDataToEntity(FileData fileData) {
    Entity entity = new Entity(Constants.ENTITY_NAME);
    entity.setProperty("filename", fileData.getFilename());
    entity.setProperty("blobKey", fileData.getBlobKey());
    return entity;
  }

  public static FileData blobInfoToFileData(BlobInfo blobInfo) {
    return new FileData(blobInfo.getFilename(), blobInfo.getBlobKey());
  }
}


text:
// Licensed under the Apache License. See footer for details.

fs   = require("fs")
path = require("path")

_    = require("underscore")
nopt = require("nopt")

utils = require("./utils")

getOpts = exports

//------------------------------------------------------------------------------
getOpts.parse = function parse(args, optsSpec) {
  if (args[0] == "?") return getOpts.printHelp()

  optsSpec = optsSpec || {}
  optsSpec.verbose = [ "v", Boolean ],
  optsSpec.help    = [ "h", Boolean ]

  var longOpts   = {}
  var shortOpts  = {}
  var defValues  = {}

  for (var name in optsSpec) {
    var opt = optsSpec[name]

    var shortName = opt[0]
    var type      = opt[1]
    var defValue  = opt[2]

    if (type == Boolean) defValue = false

    shortOpts[shortName] = "--#{name}"
    longOpts[name]       = type

    if (defValue != null) {
      defValues[name] = defValue
    }
  }

  var parsed = nopt(longOpts, shortOpts, args, 0)

  if (parsed.help) getOpts.printHelp()

  var opts

  args = parsed.argv.remain
  opts = _.pick(parsed, _.keys(longOpts))
  opts = _.defaults(opts, defValues)

  utils.verbose(opts.verbose)

  return [args, opts]
}

//------------------------------------------------------------------------------
getOpts.printHelp = function printHelp() {
  var helpFile = path.join(__dirname, utils.PROGRAM + "-help.txt" )
  var content  = fs.readFileSync(helpFile, "utf8")

  content = content.replace(/%PROGRAM%/g,     utils.PROGRAM    )
  content = content.replace(/%PACKAGE%/g,     utils.PACKAGE    )
  content = content.replace(/%VERSION%/g,     utils.VERSION    )
  content = content.replace(/%DESCRIPTION%/g, utils.DESCRIPTION)
  content = content.replace(/%HOMEPAGE%/g,    utils.HOMEPAGE   )

  console.log(content)
  process.exit(1)
}


text:
<app-navbar></app-navbar>

<div class="container main-container">
    <router-outlet></router-outlet>
</div>


text:
/*
191 Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3.

*/

/* ****
1. n = n >>> 1, 可提前终止循环.
*****/

public static int hammingWeight(int n) {
	int ones = 0;
	while(n!=0) {
		ones += (n & 1);
		n >>>= 1;
	}
	return ones;
}
/*
An Integer in Java has 32 bits, e.g. 00101000011110010100001000011010.
To count the 1s in the Integer representation with put the input int n in bit
AND with 1 (that is represented as 00000000000000000000000000000001,
and if this operation result is 1, that means that the last bit of the input integer
is 1. Thus we add it to the 1s count.
ones = ones + (n & 1);
Then we shift the input Integer by one on the right, to check for the next bit.
n = n>>>1;
We need to use bit shifting unsigned operation >>> (while >> depends on sign
extension)
We keep doing this until the input Integer is 0.
In Java we need to put attention on the fact that the maximum integer is
2147483647. Integer type in Java is signed and there is no unsigned int. So the input
2147483648 is represented in Java as -2147483648 (in java int type has a cyclic
representation, that means Integer.MAXVALUE+1==Integer.MINVALUE).
This force us to use
n!=0
in the while condition and we cannot use
n>0
because the input 2147483648 would correspond to -2147483648 in java and the
code would not enter the while if the condition is n>0 for n=2147483648.*/


text:
import { Injectable } from '@angular/core'
import { HotkeyDescription, HotkeyProvider, TranslateService } from 'tabby-core'

/** @hidden */
@Injectable()
export class ElectronHotkeyProvider extends HotkeyProvider {
    hotkeys: HotkeyDescription[] = [
        {
            id: 'new-window',
            name: this.translate.instant('New window'),
        },
        {
            id: 'toggle-window',
            name: this.translate.instant('Toggle terminal window'),
        },
    ]

    constructor (private translate: TranslateService) { super() }

    async provide (): Promise<HotkeyDescription[]> {
        return this.hotkeys
    }
}


text:
'use strict';

var factory = require('../octicon.js');

// This is an auto-generated ES2015 icon from the modularize script. Please do not modify this file.
var dash = factory('dash', 8, 16, {"fill-rule":"evenodd","d":"M0 7v2h8V7H0z"}, ["hyphen","range"]);

module.exports = dash;


text:
 * git
 * docker (>=v1.12)
 * kvm (if building host images)

## Builds / Release

To build the images in this repo requires docker to be listening on 172.17.0.1, this allows the post-process scripts for Mandracchio to run and also for some build-scripts to in turn run 'sub-builds' to reduce the final image size and remove the requirement for development tools like gcc et al. to be installed within the containers. SELinux should be set to a maximum enforcement level of 'Permissive' as otherwise some things can freak out (notably SElinux labeling inside a container)

The built images from this repository may be found at the Port.direct [docker hub](https://hub.docker.com/u/port/). Releases are split into two streams: 'latest' and 'stable'. 'Latest' builds for the Port.direct continuous release, while stable tracks the upstream OpenStack Release schedule and will only receive critical security updates following a release. It is strongly recommend that unless you have very specific requirements to use the the 'latest' release stream for the best experience.

### OpenvSwitch

Building containers that provide OpenvSwitch support require that a local OVS repo is running on the build host, this can be started with the following command:

```bash
docker run -d --name openvswitch-repo -p 172.17.0.1:80:80/tcp port/openvswitch-rpm:latest
```

### FreeIPA Server && Ipsilon-API

Building containers that provide the FreeIPA Server or Ipsilon API a local repo is running on the build host, this can be started with the following command:

```bash
docker run -d --name freeipa-repo -p 172.17.0.1:83:80/tcp port/freeipa-rpm:latest
```

### Ipsilon-API

Building containers that provide the Ipsilon API a local repo is running on the build host, this can be started with the following command:

```bash
docker run -d --name ipsilon-repo -p 172.17.0.1:82:80/tcp port/ipsilon-rpm:latest
```

### Quickstart
```bash
docker run -d --name openvswitch-repo -p 172.17.0.1:80:80/tcp port/openvswitch-rpm:latest
docker run -d --name freeipa-repo -p 172.17.0.1:83:80/tcp port/freeipa-rpm:latest
docker run -d --name ipsilon-repo -p 172.17.0.1:82:80/tcp port/ipsilon-rpm:latest
./tools/update-build-links
./tools/make-scripts-exec.sh
./tools/build-all-docker-images --release
```

### Cleaning up
```bash
docker rm -f freeipa-repo
docker rm -f ipsilon-repo
docker rm -f openvswitch-repo
```


text:
module.exports = HoverLine

/// A line that tracks the mouse position on the chart.
///
/// chart   - ChartView
/// options -
///
function HoverLine(chart, options) {
  this.chart              = chart
  this.line               = document.createElement("div")
  this.line.className     = "hover-track-x"
  this.line.style.top     = chart.tpadding + "px"
  this.line.style.display = "none"
  this.isVisible          = false

  this.onResize()
  this.chart.container.appendChild(this.line)
}

HoverLine.prototype.destroy = function() {
  this.chart = this.line = this._onHoverX = null
}

// Rendering is done in response to mouse events.
HoverLine.prototype.render = function() { }

////////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////////

HoverLine.prototype.onResize = function() {
  this.line.style.height = this.chart.height + "px"
}

// left - Integer pixels or null.
HoverLine.prototype.moveTo = function(left) {
  if (!left || left < 0) return this.setVisible(false)
  this.setVisible(true)
  this.line.style.left = left + "px"
}

HoverLine.prototype.setVisible = function(isVisible) {
  if (this.isVisible === isVisible) return
  this.isVisible          = isVisible
  this.line.style.display = isVisible ? null : "none"
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                          http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Doctrine\Tests\Models\DDC869\DDC869ChequePayment">
        <field name="serialNumber" column="serialNumber" type="string"/>
    </entity>

</doctrine-mapping>


text:
package io.quarkus.grpc.server.interceptors;

import io.grpc.examples.helloworld.Greeter;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.quarkus.grpc.GrpcService;
import io.smallrye.common.annotation.Blocking;
import io.smallrye.mutiny.Uni;

@GrpcService
public class MyInterceptedGreeting implements Greeter {
    @Override
    @Blocking
    public Uni<HelloReply> sayHello(HelloRequest request) {
        return Uni.createFrom().item(() -> HelloReply.newBuilder()
                .setMessage("hello " + MyFirstInterceptor.KEY_1.get() + " - " + MyFirstInterceptor.KEY_2.get()).build());
    }

    @Override
    @Blocking
    public Uni<HelloReply> wEIRD(HelloRequest request) {
        return sayHello(request);
    }
}


text:
exports.Async = Async;

/**
 * provides save mixin method for Box instances for asynchronous state saving
 * @constructor Async
 */
function Async() {}

/**
 * method gets merged to the implementor class
 * @returns {*}
 */
Async.prototype.save = function (url, callback, format, method) {
    return Async.saveBox(this, url, method, callback, format);
};

/**
 * serializes and saves the given Box instance
 * @param box {boxxer.Box}
 * @param url {String}
 * @param [method] {String} GET/POST
 * @param [callback] {Function}
 * @param [format] {String}
 */
Async.saveBox = function (box, url, method, callback, format) {
    if (!format) {
        format = Serializer.JSON;
    }

    new Connection(box, url, method, format, callback).save();
};

/**
 * PUT request
 * @type {string}
 */
Async.POST = "PUT";

/**
 * DELETE request
 * @type {string}
 */
Async.POST = "DELETE";

/**
 * POST request
 * @type {string}
 */
Async.POST = "POST";

/**
 * GET request
 * @type {string}
 */
Async.GET = "GET";


text:
'use strict'

import SKAction from './SKAction'
//import SKActionTimingMode from './SKActionTimingMode'
//import SKNode from './SKNode'

export default class SKRepeat extends SKAction {
  /**
   * constructor
   * @access public
   * @constructor
   */
  constructor() {
    super()

    this._timesToRepeat = 0
    this._repeatedAtion = null
    this._forever = false
    this._timesRepeated = 0
  }

  /**
   * Creates an action that repeats another action a specified number of times.
   * @access public
   * @param {SKAction} action - The action to execute.
   * @param {number} count - The number of times to execute the action.
   * @returns {SKAction} -
   * @desc When the action executes, the associated action runs to completion and then repeats, until the count is reached.This action is reversible; it creates a new action that is the reverse of the specified action and then repeats it the same number of times.
   * @see https://developer.apple.com/documentation/spritekit/skaction/1417750-repeat
   */
  static repeat(action, count) {
    const _action = new SKRepeat()
    _action._repeatedAction = action
    _action._duration = action.duration
    _action._timesToRepeat = count
    _action._forever = (count === Infinity)
    return _action
  }

  /**
   * Creates an action that repeats another action forever.
   * @access public
   * @param {SKAction} action - The action to execute.
   * @returns {SKAction} -
   * @desc When the action executes, the associated action runs to completion and then repeats.This action is reversible; it creates a new action that is the reverse of the specified action and then repeats it forever.NoteThe action to be repeated must have a non-instantaneous duration.
   * @see https://developer.apple.com/documentation/spritekit/skaction/1417676-repeatforever
   */
  static repeatForever(action) {
    return this.repeat(action, Infinity)
  }

  /**
   * @access public
   * @returns {SCNActionFade} -
   */
  copy() {
    const action = super.copy()

    action._timesToRepeat = this._timesToRepeat
    action._repeatedAction = this._repeatedAction
    action._forever = this._forever
    action._timesRepeated = this._timesRepeated

    return action
  }

  _getTime(time, needTimeConversion) {
    if(!needTimeConversion){
      return time
    }

    const baseTime = this._basetimeFromTime(time)
    if(this.timingFunction === null){
      return baseTime
    }

    const n = Math.floor(baseTime)
    const t = this.timingFunction._getValueAtTime(baseTime - n)
    return n + t
  }

  /**
   * apply action to the given node.
   * @access private
   * @param {Object} obj - target object to apply this action.
   * @param {number} time - active time
   * @param {boolean} [needTimeConversion = true] -
   * @returns {void}
   */
  _applyAction(obj, time, needTimeConversion = true) {
    const dt = this._getTime(time, needTimeConversion)
    const timesRepeated = Math.floor(dt)
    while(timesRepeated > this._timesRepeated){
      this._timesRepeated += 1
      this._repeatedAction._applyAction(obj, 1.0, false)
      if(!this._forever && this._timesRepeated >= this._timesToRepeat){
        this._finished = true
        return
      }
      this._repeatedAction._resetFinished()
    }
    const t = dt - this._timesRepeated
    this._repeatedAction._applyAction(obj, t, false)
    this._finished = false
  }

  get duration() {
    if(this._forever){
      return Infinity
    }
    return this._repeatedAction.duration * this._timesToRepeat
  }

  _resetFinished() {
    this._repeatedAction._resetFinished()
    this._timesRepeated = 0
    this._finished = false
  }

}

SKAction.repeat = SKRepeat.repeat
SKAction.repeatForever = SKRepeat.repeatForever


text:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneLoadingLayer : OsuTestScene
    {
        private Drawable dimContent;
        private LoadingLayer overlay;

        public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(LoadingSpinner) };

        private Container content;

        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            Children = new[]
            {
                content = new Container
                {
                    Size = new Vector2(300),
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Children = new[]
                    {
                        new Box
                        {
                            Colour = Color4.SlateGray,
                            RelativeSizeAxes = Axes.Both,
                        },
                        dimContent = new FillFlowContainer
                        {
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                            Direction = FillDirection.Vertical,
                            Spacing = new Vector2(10),
                            RelativeSizeAxes = Axes.Both,
                            Size = new Vector2(0.9f),
                            Children = new Drawable[]
                            {
                                new OsuSpriteText { Text = "Sample content" },
                                new TriangleButton { Text = "can't puush me", Width = 200, },
                                new TriangleButton { Text = "puush me", Width = 200, Action = () => { } },
                            }
                        },
                        overlay = new LoadingLayer(dimContent),
                    }
                },
            };
        });

        [Test]
        public void TestShowHide()
        {
            AddAssert("not visible", () => !overlay.IsPresent);

            AddStep("show", () => overlay.Show());

            AddUntilStep("wait for content dim", () => dimContent.Colour != Color4.White);

            AddStep("hide", () => overlay.Hide());

            AddUntilStep("wait for content restore", () => dimContent.Colour == Color4.White);
        }

        [Test]
        public void TestContentRestoreOnDispose()
        {
            AddAssert("not visible", () => !overlay.IsPresent);

            AddStep("show", () => overlay.Show());

            AddUntilStep("wait for content dim", () => dimContent.Colour != Color4.White);

            AddStep("expire", () => overlay.Expire());

            AddUntilStep("wait for content restore", () => dimContent.Colour == Color4.White);
        }

        [Test]
        public void TestLargeArea()
        {
            AddStep("show", () =>
            {
                content.RelativeSizeAxes = Axes.Both;
                content.Size = new Vector2(1);

                overlay.Show();
            });

            AddStep("hide", () => overlay.Hide());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="viewModel"
            type="com.mooveit.fakeit.viewmodels.PokemonViewModel"/>
    </data>

    <RelativeLayout
        android:id="@+id/activity_main"
        style="@style/Base.ContainerFullWidth.FullPadded">

        <TextView
            android:id="@+id/pokemon_name_label"
            style="@style/Base.Wrapper.Bold"
            android:text="@string/pokemon_name"/>

        <TextView
            android:id="@+id/pokemon_name"
            style="@style/Base.Wrapper.MarginLeft"
            android:layout_toRightOf="@+id/pokemon_name_label"
            android:text="@{viewModel.data.pokemonName}"/>

        <TextView
            android:id="@+id/locations_label"
            style="@style/Base.Wrapper.Bold"
            android:layout_below="@+id/pokemon_name"
            android:text="@string/pokemon_locations"/>

        <TextView
            android:id="@+id/locations"
            style="@style/Base.Wrapper.MarginLeft"
            android:layout_below="@+id/pokemon_name"
            android:layout_toRightOf="@+id/locations_label"
            android:text="@{viewModel.data.pokemonLocation}"/>

        <Button
            android:id="@+id/refresh"
            style="@style/Base.RefreshButton"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:onClick="@{() -> viewModel.refresh()}"/>
    </RelativeLayout>
</layout>


text:
**Given the challenges of external SIG coordinating with internal roadmaps, a new
process has been put in place for the core TF and Keras teams to handle migration
and deprecation of Addons components. If you believe there is a strong candidate for
migration please post an issue and we'll escalate it to the respective team members.**

### Criteria for Migration
* The addition is widely used throughout the community
* The addition is unlikely to have API changes as time progresses
* The addition is well written / tested


text:
package org.apache.polygene.library.constraints;

import java.util.regex.Pattern;
import org.apache.polygene.api.constraint.Constraint;
import org.apache.polygene.library.constraints.annotation.Matches;

/**
 * Implement @Matches constraint.
 */
public class MatchesConstraint
    implements Constraint<Matches, String>
{
    @Override
    public boolean isValid( Matches annotation, String argument )
    {
        if( argument != null )
        {
            Pattern pattern = Pattern.compile( annotation.value() );
            return pattern.matcher( argument ).matches();
        }

        return false;
    }

}


text:
from django.db import IntegrityError
from django.db.models import Q
from django.db import connection
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist

# permissions imports
from permissions.exceptions import Unauthorized
from permissions.models import ObjectPermission
from permissions.models import ObjectPermissionInheritanceBlock
from permissions.models import Permission
from permissions.models import PrincipalRoleRelation
from permissions.models import Role

# Roles ######################################################################

def add_role(principal, role):
    """Adds a global role to a principal.

    **Parameters:**

    principal
        The principal (user or group) which gets the role added.

    role
        The role which is assigned.
    """
    if isinstance(principal, User):
        try:
            ppr = PrincipalRoleRelation.objects.get(user=principal, role=role, content_id=None, content_type=None)
        except PrincipalRoleRelation.DoesNotExist:
            PrincipalRoleRelation.objects.create(user=principal, role=role)
            return True
    else:
        try:
            ppr = PrincipalRoleRelation.objects.get(group=principal, role=role, content_id=None, content_type=None)
        except PrincipalRoleRelation.DoesNotExist:
            PrincipalRoleRelation.objects.create(group=principal, role=role)
            return True

    return False

def add_local_role(obj, principal, role):
    """Adds a local role to a principal.

    **Parameters:**

    obj
        The object for which the principal gets the role.

    principal
        The principal (user or group) which gets the role.

    role
        The role which is assigned.
    """
    ctype = ContentType.objects.get_for_model(obj)
    if isinstance(principal, User):
        try:
            ppr = PrincipalRoleRelation.objects.get(user=principal, role=role, content_id=obj.pk, content_type=ctype)
        except PrincipalRoleRelation.DoesNotExist:
            PrincipalRoleRelation.objects.create(user=principal, role=role, content=obj)
            return True
    else:
        try:
            ppr = PrincipalRoleRelation.objects.get(group=principal, role=role, content_id=obj.pk, content_type=ctype)
        except PrincipalRoleRelation.DoesNotExist:
            PrincipalRoleRelation.objects.create(group=principal, role=role, content=obj)
            return True

    return False

def remove_role(principal, role):
    """Removes role from passed principal.

    **Parameters:**

    principal
        The principal (user or group) from which the role is removed.

    role
        The role which is removed.
    """
    try:
        if isinstance(principal, User):
            ppr = PrincipalRoleRelation.objects.get(
                    user=principal, role=role, content_id=None, content_type=None)
        else:
            ppr = PrincipalRoleRelation.objects.get(
                    group=principal, role=role, content_id=None, content_type=None)

    except PrincipalRoleRelation.DoesNotExist:
        return False
    else:
        ppr.delete()

    return True

def remove_local_role(obj, principal, role):
    """Removes role from passed object and principle.

    **Parameters:**

    obj
        The object from which the role is removed.

    principal
        The principal (user or group) from which the role is removed.

    role
        The role which is removed.
    """
    try:
        ctype = ContentType.objects.get_for_model(obj)

        if isinstance(principal, User):
            ppr = PrincipalRoleRelation.objects.get(
                user=principal, role=role, content_id=obj.pk, content_type=ctype)
        else:
            ppr = PrincipalRoleRelation.objects.get(
                group=principal, role=role, content_id=obj.pk, content_type=ctype)

    except PrincipalRoleRelation.DoesNotExist:
        return False
    else:
        ppr.delete()

    return True

def remove_roles(principal):
    """Removes all roles passed principal (user or group).

    **Parameters:**

    principal
        The principal (user or group) from which all roles are removed.
    """
    if isinstance(principal, User):
        ppr = PrincipalRoleRelation.objects.filter(
            user=principal, content_id=None, content_type=None)
    else:
        ppr = PrincipalRoleRelation.objects.filter(
            group=principal, content_id=None, content_type=None)

    if ppr:
        ppr.delete()
        return True
    else:
        return False

def remove_local_roles(obj, principal):
    """Removes all local roles from passed object and principal (user or
    group).

    **Parameters:**

    obj
        The object from which the roles are removed.

    principal
        The principal (user or group) from which the roles are removed.
    """
    ctype = ContentType.objects.get_for_model(obj)

    if isinstance(principal, User):
        ppr = PrincipalRoleRelation.objects.filter(
            user=principal, content_id=obj.pk, content_type=ctype)
    else:
        ppr = PrincipalRoleRelation.objects.filter(
            group=principal, content_id=obj.pk, content_type=ctype)

    if ppr:
        ppr.delete()
        return True
    else:
        return False

def get_roles(user, obj=None):
    """Returns *all* roles of the passed user.

    This takes direct roles and roles via the user's groups into account.

    If an object is passed local roles will also added. Then all local roles
    from all ancestors and all user's groups are also taken into account.

    This is the method to use if one want to know whether the passed user
    has a role in general (for the passed object).

    **Parameters:**

    user
        The user for which the roles are returned.

    obj
        The object for which local roles will returned.

    """
    roles = []
    groups = user.groups.all()
    groups_ids_str = ", ".join([str(g.id) for g in groups])

    # Gobal roles for user and the user's groups
    cursor = connection.cursor()
    cursor.execute("""SELECT role_id
                      FROM permissions_principalrolerelation
                      WHERE (user_id=%s OR group_id IN (%s))
                      AND content_id is Null""" % (user.id, groups_ids_str))

    for row in cursor.fetchall():
        roles.append(row[0])

    # Local roles for user and the user's groups and all ancestors of the
    # passed object.
    while obj:
        ctype = ContentType.objects.get_for_model(obj)
        cursor.execute("""SELECT role_id
                          FROM permissions_principalrolerelation
                          WHERE (user_id='%s' OR group_id IN (%s))
                          AND content_id='%s'
                          AND content_type_id='%s'""" % (user.id, groups_ids_str, obj.pk, ctype.id))

        for row in cursor.fetchall():
            roles.append(row[0])

        try:
            obj = obj.get_parent_for_permissions()
        except AttributeError:
            obj = None

    return roles

def get_global_roles(principal):
    """Returns *direct* global roles of passed principal (user or group).
    """
    if isinstance(principal, User):
        return [prr.role for prr in PrincipalRoleRelation.objects.filter(
            user=principal, content_id=None, content_type=None)]
    else:
        if isinstance(principal, Group):
            principal = (principal,)
        return [prr.role for prr in PrincipalRoleRelation.objects.filter(
            group__in=principal, content_id=None, content_type=None)]

def get_local_roles(obj, principal):
    """Returns *direct* local roles for passed principal and content object.
    """
    ctype = ContentType.objects.get_for_model(obj)

    if isinstance(principal, User):
        return [prr.role for prr in PrincipalRoleRelation.objects.filter(
            user=principal, content_id=obj.pk, content_type=ctype)]
    else:
        return [prr.role for prr in PrincipalRoleRelation.objects.filter(
            group=principal, content_id=obj.pk, content_type=ctype)]

# Permissions ################################################################

def check_permission(obj, user, codename, roles=None):
    """Checks whether passed user has passed permission for passed obj.

    **Parameters:**

    obj
        The object for which the permission should be checked.

    codename
        The permission's codename which should be checked.

    user
        The user for which the permission should be checked.

    roles
        If given these roles will be assigned to the user temporarily before
        the permissions are checked.
    """
    if not has_permission(obj, user, codename):
        raise Unauthorized("User '%s' doesn't have permission '%s' for object '%s' (%s)"
            % (user, codename, obj.slug, obj.__class__.__name__))

def grant_permission(obj, role, permission):
    """Grants passed permission to passed role. Returns True if the permission
    was able to be added, otherwise False.

    **Parameters:**

    obj
        The content object for which the permission should be granted.

    role
        The role for which the permission should be granted.

    permission
        The permission which should be granted. Either a permission
        object or the codename of a permission.
    """
    if not isinstance(permission, Permission):
        try:
            permission = Permission.objects.get(codename = permission)
        except Permission.DoesNotExist:
            return False

    ct = ContentType.objects.get_for_model(obj)
    try:
        ObjectPermission.objects.get(role=role, content_type = ct, content_id=obj.pk, permission=permission)
    except ObjectPermission.DoesNotExist:
        ObjectPermission.objects.create(role=role, content=obj, permission=permission)

    return True

def remove_permission(obj, role, permission):
    """Removes passed permission from passed role and object. Returns True if
    the permission has been removed.

    **Parameters:**

    obj
        The content object for which a permission should be removed.

    role
        The role for which a permission should be removed.

    permission
        The permission which should be removed. Either a permission object
        or the codename of a permission.
    """
    if not isinstance(permission, Permission):
        try:
            permission = Permission.objects.get(codename = permission)
        except Permission.DoesNotExist:
            return False

    ct = ContentType.objects.get_for_model(obj)

    try:
        op = ObjectPermission.objects.get(role=role, content_type = ct, content_id=obj.pk, permission = permission)
    except ObjectPermission.DoesNotExist:
        return False

    op.delete()
    return True

def has_permission(obj, user, codename, roles=None):
    """Checks whether the passed user has passed permission for passed object.

    **Parameters:**

    obj
        The object for which the permission should be checked.

    codename
        The permission's codename which should be checked.

    request
        The current request.

    roles
        If given these roles will be assigned to the user temporarily before
        the permissions are checked.
    """
    cache_key = "%s-%s-%s" % (obj.content_type, obj.pk, codename)
    result = _get_cached_permission(user, cache_key)
    if result is not None:
        return result

    if roles is None:
        roles = []

    if user.is_superuser:
        return True

    if not user.is_anonymous():
        roles.extend(get_roles(user, obj))

    ct = ContentType.objects.get_for_model(obj)

    result = False
    while obj is not None:
        p = ObjectPermission.objects.filter(
            content_type=ct, content_id=obj.pk, role__in=roles, permission__codename = codename).values("id")

        if len(p) > 0:
            result = True
            break

        if is_inherited(obj, codename) == False:
            result = False
            break

        try:
            obj = obj.get_parent_for_permissions()
            ct = ContentType.objects.get_for_model(obj)
        except AttributeError:
            result = False
            break

    _cache_permission(user, cache_key, result)
    return result

# Inheritance ################################################################

def add_inheritance_block(obj, permission):
    """Adds an inheritance for the passed permission on the passed obj.

    **Parameters:**

        permission
            The permission for which an inheritance block should be added.
            Either a permission object or the codename of a permission.
        obj
            The content object for which an inheritance block should be added.
    """
    if not isinstance(permission, Permission):
        try:
            permission = Permission.objects.get(codename = permission)
        except Permission.DoesNotExist:
            return False

    ct = ContentType.objects.get_for_model(obj)
    try:
        ObjectPermissionInheritanceBlock.objects.get(content_type = ct, content_id=obj.pk, permission=permission)
    except ObjectPermissionInheritanceBlock.DoesNotExist:
        try:
            result = ObjectPermissionInheritanceBlock.objects.create(content=obj, permission=permission)
        except IntegrityError:
            return False
    return True

def remove_inheritance_block(obj, permission):
    """Removes a inheritance block for the passed permission from the passed
    object.

    **Parameters:**

        obj
            The content object for which an inheritance block should be added.

        permission
            The permission for which an inheritance block should be removed.
            Either a permission object or the codename of a permission.
    """
    if not isinstance(permission, Permission):
        try:
            permission = Permission.objects.get(codename = permission)
        except Permission.DoesNotExist:
            return False

    ct = ContentType.objects.get_for_model(obj)
    try:
        opi = ObjectPermissionInheritanceBlock.objects.get(content_type = ct, content_id=obj.pk, permission=permission)
    except ObjectPermissionInheritanceBlock.DoesNotExist:
        return False

    opi.delete()
    return True

def is_inherited(obj, codename):
    """Returns True if the passed permission is inherited for passed object.

    **Parameters:**

        obj
            The content object for which the permission should be checked.

        codename
            The permission which should be checked. Must be the codename of
            the permission.
    """
    ct = ContentType.objects.get_for_model(obj)
    try:
        ObjectPermissionInheritanceBlock.objects.get(
            content_type=ct, content_id=obj.pk, permission__codename = codename)
    except ObjectDoesNotExist:
        return True
    else:
        return False

def get_group(id):
    """Returns the group with passed id or None.
    """
    try:
        return Group.objects.get(pk=id)
    except Group.DoesNotExist:
        return None

def get_role(id):
    """Returns the role with passed id or None.
    """
    try:
        return Role.objects.get(pk=id)
    except Role.DoesNotExist:
        return None

def get_user(id):
    """Returns the user with passed id or None.
    """
    try:
        return User.objects.get(pk=id)
    except User.DoesNotExist:
        return None

def has_group(user, group):
    """Returns True if passed user has passed group.
    """
    if isinstance(group, str):
        group = Group.objects.get(name=group)

    return group in user.groups.all()

def reset(obj):
    """Resets all permissions and inheritance blocks of passed object.
    """
    ctype = ContentType.objects.get_for_model(obj)
    ObjectPermissionInheritanceBlock.objects.filter(content_id=obj.pk, content_type=ctype).delete()
    ObjectPermission.objects.filter(content_id=obj.pk, content_type=ctype).delete()

# Registering ################################################################

def register_permission(name, codename, ctypes=[]):
    """Registers a permission to the framework. Returns the permission if the
    registration was successfully, otherwise False.

    **Parameters:**

        name
            The unique name of the permission. This is displayed to the
            customer.
        codename
            The unique codename of the permission. This is used internally to
            identify the permission.
        content_types
            The content type for which the permission is active. This can be
            used to display only reasonable permissions for an object. This
            must be a Django ContentType
    """
    try:
        p = Permission.objects.create(name=name, codename=codename)

        ctypes = [ContentType.objects.get_for_model(ctype) for ctype in ctypes]
        if ctypes:
            p.content_types = ctypes
            p.save()
    except IntegrityError:
        return False
    return p

def unregister_permission(codename):
    """Unregisters a permission from the framework

    **Parameters:**

        codename
            The unique codename of the permission.
    """
    try:
        permission = Permission.objects.get(codename=codename)
    except Permission.DoesNotExist:
        return False
    permission.delete()
    return True

def register_role(name):
    """Registers a role with passed name to the framework. Returns the new
    role if the registration was successfully, otherwise False.

    **Parameters:**

    name
        The unique role name.
    """
    try:
        role = Role.objects.create(name=name)
    except IntegrityError:
        return False
    return role

def unregister_role(name):
    """Unregisters the role with passed name.

    **Parameters:**

    name
        The unique role name.
    """
    try:
        role = Role.objects.get(name=name)
    except Role.DoesNotExist:
        return False

    role.delete()
    return True

def register_group(name):
    """Registers a group with passed name to the framework. Returns the new
    group if the registration was successfully, otherwise False.

    Actually this creates just a default Django Group.

    **Parameters:**

    name
        The unique group name.
    """
    try:
        group = Group.objects.create(name=name)
    except IntegrityError:
        return False
    return group

def unregister_group(name):
    """Unregisters the group with passed name. Returns True if the
    unregistration was succesfull otherwise False.

    Actually this deletes just a default Django Group.

    **Parameters:**

    name
        The unique role name.
    """
    try:
        group = Group.objects.get(name=name)
    except Group.DoesNotExist:
        return False

    group.delete()
    return True

def _cache_permission(user, cache_key, data):
    """Stores the passed data on the passed user object.

    **Parameters:**

    user
        The user on which the data is stored.

    cache_key
        The key under which the data is stored.

    data
        The data which is stored.
    """
    if not getattr(user, "permissions", None):
        user.permissions = {}
    user.permissions[cache_key] = data

def _get_cached_permission(user, cache_key):
    """Returns the stored data from passed user object for passed cache_key.

    **Parameters:**

    user
        The user from which the data is retrieved.

    cache_key
        The key under which the data is stored.

    """
    permissions = getattr(user, "permissions", None)
    if permissions:
        return user.permissions.get(cache_key, None)


text:
var res = require("../src/response.js");
var response = res.response;
var json = res.json;
var status = res.status;
var text = res.text;
var time = res.time;
var otherwise = res.otherwise;

describe("Response", function () {

  var mockRequest = function () {
      return {};
  };

  var mockResponse = function () {
    var testResponse = {
      setHeader : function () { },
      end : function () { },
      write : function () { }
    };

    spyOn(testResponse, "setHeader");
    spyOn(testResponse, "end");
    spyOn(testResponse, "write");

    return testResponse;
  };

  it("handles with text", function () {
    var testResponse = mockResponse();
    text("Hello there!").handle(mockRequest(), testResponse);

    expect(testResponse.setHeader)
      .toHaveBeenCalledWith("Content-Type", "text/plain");
  });

  it("handles with a text response", function () {
    var testResponse = mockResponse();
    response(text("Hello there!")).handle(mockRequest(), testResponse);

    expect(testResponse.setHeader)
      .toHaveBeenCalledWith("Content-Type", "text/plain");
  });

  it("sets the status code", function () {
    var testResponse = mockResponse();
    response(text("text gives a status code of 200"))
      .handle(mockRequest(), testResponse);

    expect(testResponse.statusCode).toEqual(200);
  });

  it("handles with a status code", function () {
    var testResponse = mockResponse();
    response(status(422)).handle(mockRequest(), testResponse);

    expect(testResponse.statusCode).toEqual(422);
  });

  it("writes text", function () {
    var testResponse = mockResponse();
    response(text("pete campbell")).handle(mockRequest(), testResponse);

    expect(testResponse.write).toHaveBeenCalledWith("pete campbell");
  });

  it("writes an object as json", function () {
    var testResponse = mockResponse();
    var jsonObject = { success : true };
    response(json(jsonObject)).handle(mockRequest(), testResponse);
    expect(testResponse.setHeader)
      .toHaveBeenCalledWith("Content-Type", "application/json");
    expect(testResponse.write)
      .toHaveBeenCalledWith(JSON.stringify(jsonObject));
  });

  it("writes a string as json", function () {
    var testResponse = mockResponse();
    response(json('{"success" : true}')).handle(mockRequest(), testResponse);
    expect(testResponse.setHeader)
      .toHaveBeenCalledWith("Content-Type", "application/json");
    expect(testResponse.write)
      .toHaveBeenCalledWith('{"success" : true}');
  });

  it("calls end", function () {
    var testResponse = mockResponse();
    response(text('should call end')).handle(mockRequest(), testResponse);
    expect(testResponse.end)
      .toHaveBeenCalled();
  });

  it("writes different results the first and second time", function () {
    var testResponse1 = mockResponse();
    var testResponse2 = mockResponse();
    var r = response(time(1, text('Kittens')),
                     time(2, text('Puppies')));

    r.handle(mockRequest(), testResponse1);
    r.handle(mockRequest(), testResponse2);

    expect(testResponse1.write).toHaveBeenCalledWith('Kittens');
    expect(testResponse1.write).wasNotCalledWith('Puppies');

    expect(testResponse2.write).wasNotCalledWith('Kittens');
    expect(testResponse2.write).toHaveBeenCalledWith('Puppies');
  });

  it("does not write a default if time matches", function () {
    var testResponse = mockResponse();
    var r = response(time(1, text('Charmander')),
                     otherwise(text('Abra')));

    r.handle(mockRequest(), testResponse);

    expect(testResponse.write).wasNotCalledWith('Abra');
  });

  it("writes a default if a time does not match", function () {
    var testResponse = mockResponse();

    var r = response(time(1, text('Pikachu')),
                     otherwise(text('Bulbasaur')));

    r.handle(mockRequest(), mockResponse());
    r.handle(mockRequest(), testResponse);

    expect(testResponse.write).toHaveBeenCalledWith('Bulbasaur');
    expect(testResponse.write).wasNotCalledWith('Pikachu');
  });
});


text:
package gov.va.escreening.repository;

import gov.va.escreening.entity.SurveySection;

import java.util.List;

public interface SurveySectionRepository extends RepositoryInterface<SurveySection> {

    /**
     * Finds all SurveySections for the given assessment
     * @param veteranAssessmentId
     * @return List of SurveySection in display order
     */
    public List<SurveySection> findForVeteranAssessmentId(int veteranAssessmentId);

    /**
     * Retrieves all the SurveySections in the system.
     * @return
     */
    List<SurveySection> getSurveySectionList();

}


text: Helper class used by a lot of angular projects on the web


text:
  Wannehain est
       un village
       situé dans le département de Nord en Nord-Pas-de-Calais. Elle comptait 913 habitants en 2008.

Wannehain est situé à seulement 11 km de Villeneuve-d'Ascq, les étudiants qui voudrons se loger à moindre coût pourront envisager de louer un appartement à Wannehain. Wannehain est aussi un bon investissement locatif a cause de sa proximité de Villeneuve-d'Ascq et de ses Universités. Il sera aisé de trouver un logement à vendre.

La commune compte quelques  équipements, elle propose entre autres un terrain de sport.

Le parc de logements, à Wannehain, était réparti en 2011 en quatre appartements et 407 maisons soit
 un marché plutôt équilibré.

Si vous pensez venir habiter à Wannehain, vous pourrez facilement trouver une maison à vendre.

À coté de Wannehain sont localisées les communes de
Camphin-en-Pévèle localisée à 3 km, 1 620 habitants,
Louvil localisée à 5 km, 840 habitants,
Bachy localisée à 1 km, 1 399 habitants,
Bouvines à 5 km, 723 habitants,
Genech à 5 km, 2 587 habitants,
Mouchin située à 5 km, 1 351 habitants,
 entre autres. De plus, Wannehain est située à seulement 16 km de Lille.

À Wannehain, la valorisation moyenne à la vente d'un appartement se situe à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 476 € du m². À la location la valeur moyenne se situe à 0 € du m² par mois.


text:
.class public final Lcom/google/zxing/common/reedsolomon/GenericGF;
.super Ljava/lang/Object;

# static fields
.field public static final AZTEC_DATA_10:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final AZTEC_DATA_12:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final AZTEC_DATA_6:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final AZTEC_DATA_8:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final AZTEC_PARAM:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final DATA_MATRIX_FIELD_256:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final MAXICODE_FIELD_64:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field public static final QR_CODE_FIELD_256:Lcom/google/zxing/common/reedsolomon/GenericGF;

.field private static final a:I

# instance fields
.field private b:[I

.field private c:[I

.field private d:Lcom/google/zxing/common/reedsolomon/a;

.field private e:Lcom/google/zxing/common/reedsolomon/a;

.field private final f:I

.field private final g:I

.field private h:Z

# direct methods
.method static constructor <clinit>()V
    .locals 4

    const/16 v3, 0x100

    new-instance v0, Lcom/google/zxing/common/reedsolomon/GenericGF;

    const/16 v1, 0x1069

    const/16 v2, 0x1000

    invoke-direct {v0, v1, v2}, Lcom/google/zxing/common/reedsolomon/GenericGF;-><init>(II)V

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->AZTEC_DATA_12:Lcom/google/zxing/common/reedsolomon/GenericGF;

    new-instance v0, Lcom/google/zxing/common/reedsolomon/GenericGF;

    const/16 v1, 0x409

    const/16 v2, 0x400

    invoke-direct {v0, v1, v2}, Lcom/google/zxing/common/reedsolomon/GenericGF;-><init>(II)V

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->AZTEC_DATA_10:Lcom/google/zxing/common/reedsolomon/GenericGF;

    new-instance v0, Lcom/google/zxing/common/reedsolomon/GenericGF;

    const/16 v1, 0x43

    const/16 v2, 0x40

    invoke-direct {v0, v1, v2}, Lcom/google/zxing/common/reedsolomon/GenericGF;-><init>(II)V

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->AZTEC_DATA_6:Lcom/google/zxing/common/reedsolomon/GenericGF;

    new-instance v0, Lcom/google/zxing/common/reedsolomon/GenericGF;

    const/16 v1, 0x13

    const/16 v2, 0x10

    invoke-direct {v0, v1, v2}, Lcom/google/zxing/common/reedsolomon/GenericGF;-><init>(II)V

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->AZTEC_PARAM:Lcom/google/zxing/common/reedsolomon/GenericGF;

    new-instance v0, Lcom/google/zxing/common/reedsolomon/GenericGF;

    const/16 v1, 0x11d

    invoke-direct {v0, v1, v3}, Lcom/google/zxing/common/reedsolomon/GenericGF;-><init>(II)V

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->QR_CODE_FIELD_256:Lcom/google/zxing/common/reedsolomon/GenericGF;

    new-instance v0, Lcom/google/zxing/common/reedsolomon/GenericGF;

    const/16 v1, 0x12d

    invoke-direct {v0, v1, v3}, Lcom/google/zxing/common/reedsolomon/GenericGF;-><init>(II)V

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->DATA_MATRIX_FIELD_256:Lcom/google/zxing/common/reedsolomon/GenericGF;

    sget-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->DATA_MATRIX_FIELD_256:Lcom/google/zxing/common/reedsolomon/GenericGF;

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->AZTEC_DATA_8:Lcom/google/zxing/common/reedsolomon/GenericGF;

    sget-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->AZTEC_DATA_6:Lcom/google/zxing/common/reedsolomon/GenericGF;

    sput-object v0, Lcom/google/zxing/common/reedsolomon/GenericGF;->MAXICODE_FIELD_64:Lcom/google/zxing/common/reedsolomon/GenericGF;

    return-void
.end method

.method public constructor <init>(II)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-boolean v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->h:Z

    iput p1, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->g:I

    iput p2, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    if-gtz p2, :cond_0

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->c()V

    :cond_0
    return-void
.end method

.method static b(II)I
    .locals 1

    xor-int v0, p0, p1

    return v0
.end method

.method private c()V
    .locals 5

    const/4 v3, 0x1

    const/4 v1, 0x0

    iget v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    new-array v0, v0, [I

    iput-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->b:[I

    iget v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    new-array v0, v0, [I

    iput-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->c:[I

    move v0, v1

    move v2, v3

    :goto_0
    iget v4, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    if-ge v0, v4, :cond_1

    iget-object v4, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->b:[I

    aput v2, v4, v0

    shl-int/lit8 v2, v2, 0x1

    iget v4, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    if-lt v2, v4, :cond_0

    iget v4, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->g:I

    xor-int/2addr v2, v4

    iget v4, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    add-int/lit8 v4, v4, -0x1

    and-int/2addr v2, v4

    :cond_0
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    :cond_1
    move v0, v1

    :goto_1
    iget v2, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    add-int/lit8 v2, v2, -0x1

    if-ge v0, v2, :cond_2

    iget-object v2, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->c:[I

    iget-object v4, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->b:[I

    aget v4, v4, v0

    aput v0, v2, v4

    add-int/lit8 v0, v0, 0x1

    goto :goto_1

    :cond_2
    new-instance v0, Lcom/google/zxing/common/reedsolomon/a;

    new-array v2, v3, [I

    aput v1, v2, v1

    invoke-direct {v0, p0, v2}, Lcom/google/zxing/common/reedsolomon/a;-><init>(Lcom/google/zxing/common/reedsolomon/GenericGF;[I)V

    iput-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->d:Lcom/google/zxing/common/reedsolomon/a;

    new-instance v0, Lcom/google/zxing/common/reedsolomon/a;

    new-array v2, v3, [I

    aput v3, v2, v1

    invoke-direct {v0, p0, v2}, Lcom/google/zxing/common/reedsolomon/a;-><init>(Lcom/google/zxing/common/reedsolomon/GenericGF;[I)V

    iput-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->e:Lcom/google/zxing/common/reedsolomon/a;

    iput-boolean v3, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->h:Z

    return-void
.end method

.method private d()V
    .locals 1

    iget-boolean v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->h:Z

    if-nez v0, :cond_0

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->c()V

    :cond_0
    return-void
.end method

# virtual methods
.method a(I)I
    .locals 1

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->b:[I

    aget v0, v0, p1

    return v0
.end method

.method a()Lcom/google/zxing/common/reedsolomon/a;
    .locals 1

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->d:Lcom/google/zxing/common/reedsolomon/a;

    return-object v0
.end method

.method a(II)Lcom/google/zxing/common/reedsolomon/a;
    .locals 2

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    if-gez p1, :cond_0

    new-instance v0, Ljava/lang/IllegalArgumentException;

    invoke-direct {v0}, Ljava/lang/IllegalArgumentException;-><init>()V

    throw v0

    :cond_0
    if-nez p2, :cond_1

    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->d:Lcom/google/zxing/common/reedsolomon/a;

    :goto_0
    return-object v0

    :cond_1
    add-int/lit8 v0, p1, 0x1

    new-array v1, v0, [I

    const/4 v0, 0x0

    aput p2, v1, v0

    new-instance v0, Lcom/google/zxing/common/reedsolomon/a;

    invoke-direct {v0, p0, v1}, Lcom/google/zxing/common/reedsolomon/a;-><init>(Lcom/google/zxing/common/reedsolomon/GenericGF;[I)V

    goto :goto_0
.end method

.method b(I)I
    .locals 1

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    if-nez p1, :cond_0

    new-instance v0, Ljava/lang/IllegalArgumentException;

    invoke-direct {v0}, Ljava/lang/IllegalArgumentException;-><init>()V

    throw v0

    :cond_0
    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->c:[I

    aget v0, v0, p1

    return v0
.end method

.method b()Lcom/google/zxing/common/reedsolomon/a;
    .locals 1

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->e:Lcom/google/zxing/common/reedsolomon/a;

    return-object v0
.end method

.method c(I)I
    .locals 3

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    if-nez p1, :cond_0

    new-instance v0, Ljava/lang/ArithmeticException;

    invoke-direct {v0}, Ljava/lang/ArithmeticException;-><init>()V

    throw v0

    :cond_0
    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->b:[I

    iget v1, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    iget-object v2, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->c:[I

    aget v2, v2, p1

    sub-int/2addr v1, v2

    add-int/lit8 v1, v1, -0x1

    aget v0, v0, v1

    return v0
.end method

.method c(II)I
    .locals 4

    invoke-direct {p0}, Lcom/google/zxing/common/reedsolomon/GenericGF;->d()V

    if-eqz p1, :cond_0

    if-nez p2, :cond_1

    :cond_0
    const/4 v0, 0x0

    :goto_0
    return v0

    :cond_1
    if-ltz p1, :cond_2

    if-ltz p2, :cond_2

    iget v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    if-ge p1, v0, :cond_2

    iget v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    if-lt p2, v0, :cond_3

    :cond_2
    add-int/lit8 p1, p1, 0x1

    :cond_3
    iget-object v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->c:[I

    aget v0, v0, p1

    iget-object v1, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->c:[I

    aget v1, v1, p2

    add-int/2addr v0, v1

    iget-object v1, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->b:[I

    iget v2, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    rem-int v2, v0, v2

    iget v3, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    div-int/2addr v0, v3

    add-int/2addr v0, v2

    aget v0, v1, v0

    goto :goto_0
.end method

.method public getSize()I
    .locals 1

    iget v0, p0, Lcom/google/zxing/common/reedsolomon/GenericGF;->f:I

    return v0
.end method


text:
require 'test_helper'
require 'generators/c4_module/c4_module_generator'

module C4
  class C4ModuleGeneratorTest < Rails::Generators::TestCase
    tests C4ModuleGenerator
    destination Rails.root.join('tmp/generators')
    setup :prepare_destination

    # test "generator runs without errors" do
    #   assert_nothing_raised do
    #     run_generator ["arguments"]
    #   end
    # end
  end
end


text:
import './../../constants/keycodes';
//import {BunnyElement} from "../../BunnyElement";

/**
 * Adds event listener to element and stores a function in this element's custom property
 * and returns unique ID which can be used to remove event listener later
 * even anonymous functions, component methods, functions with arguments
 *
 * Simple example:
 *
 * const Component = {
 *      docBodyClickEventId: null,
 *      anonymousEventId: null,
 *
 *      init(param1, param2) {
 *          this.docBodyClickEventId = addEvent(document.body, 'click', this.bodyClicked.bind(this, param1, param2));
 *
 *          this.anonymousEventId = addEvent(document.body, 'click', e => {
 *              console.log(e)
 *          });
 *      },
 *
 *      destroy() {
 *          this.docBodyClickEventId = removeEvent(document.body, 'click', this.docBodyClickEventId);
 *
 *          this.anonymousEventId = removeEvent(document.body, 'click', this.anonymousEventId)'
 *      },
 *
 *      bodyClicked(param1, param2) {
 *          console.log(this.internalAction(param1, param2));
 *      },
 *
 *      internalAction(param1, param2) {
 *          return param1 + param2;
 *      }
 * }
 *
 * @param {HTMLElement} element
 * @param {String} eventName
 * @param {Function} eventListener
 *
 * @returns {Number}
 */
export function addEvent(element, eventName, eventListener) {
  if (element.__bunny_event_handlers === undefined) {
    element.__bunny_event_handlers = {
      handlers: {},
      counter: 0
    }
  }
  element.__bunny_event_handlers.handlers[element.__bunny_event_handlers.counter] = eventListener;
  element.addEventListener(
    eventName,
    element.__bunny_event_handlers.handlers[element.__bunny_event_handlers.counter]
  );
  element.__bunny_event_handlers.counter++;
  return element.__bunny_event_handlers.counter - 1;
}

/**
 * Remove event listener
 *
 * @param {HTMLElement} element
 * @param {String} eventName
 * @param {Number} eventIndex
 *
 * @returns {null}
 */
export function removeEvent(element, eventName, eventIndex) {
  if (element.__bunny_event_handlers !== undefined &&
    element.__bunny_event_handlers.handlers[eventIndex] !== undefined
  ) {
    element.removeEventListener(eventName, element.__bunny_event_handlers.handlers[eventIndex]);
    delete element.__bunny_event_handlers.handlers[eventIndex];
    // do not decrement counter, each new event handler should have next unique index
  }
  return null;
}

/**
 * Call event listener only once after "delay" ms
 * Useful for scroll, keydown and other events
 * when the actions must be done only once
 * when user stopped typing or scrolling for example
 *
 * @param {HTMLElement} element
 * @param {String} eventName
 * @param {Function} eventListener
 * @param {Number} delay
 * @returns {Number}
 */
export function addEventOnce(element, eventName, eventListener, delay = 500) {
  let timeout = 0;
  return addEvent(element, eventName, (e) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      eventListener(e);
    }, delay)
  });
}

export function isEventCursorInside(e, element) {
  const bounds = element.getBoundingClientRect();
  return (e.clientX > bounds.left && e.clientX < bounds.right
    && e.clientY > bounds.top && e.clientY < bounds.bottom
  );
}

export function onClickOutside(element, callback) {
  if (document.__bunny_core_outside_callbacks === undefined) {
    document.__bunny_core_outside_callbacks = [];
  }
  const handler = (event) => {
    const target = event.target;
    const bTargetExists = document.contains(target) !== false;
    const bTargetIsElOrChild = event.target === element || element.contains(event.target);
    if (bTargetExists && !bTargetIsElOrChild) {
      callback(event);
    }
  };

  if (element.__bunny_core_outside_callbacks === undefined) {
    element.__bunny_core_outside_callbacks = [];
  }
  element.__bunny_core_outside_callbacks.push(handler);
  document.__bunny_core_outside_callbacks.push(handler);

  if (document.__bunny_core_outside_handler === undefined) {
    document.__bunny_core_outside_handler = (event) => {
      document.__bunny_core_outside_callbacks.forEach(callback => {
        callback(event);
      })
    };
    document.addEventListener('click', document.__bunny_core_outside_handler);
    document.addEventListener('touchstart', document.__bunny_core_outside_handler);
  }

  return handler;
}

export function removeClickOutside(element, callback) {
  if (document.__bunny_core_outside_callbacks !== undefined) {
    const index = document.__bunny_core_outside_callbacks.indexOf(callback);
    if (index !== -1) {
      document.__bunny_core_outside_callbacks.splice(index, 1);
      if (document.__bunny_core_outside_callbacks.length === 0) {
        document.removeEventListener('click', document.__bunny_core_outside_handler);
        document.removeEventListener('touchstart', document.__bunny_core_outside_handler);
        delete document.__bunny_core_outside_handler;
      }
    }
  }

  if (element.__bunny_core_outside_callbacks !== undefined) {
    const index = element.__bunny_core_outside_callbacks.indexOf(callback);
    if (index !== -1) {
      element.__bunny_core_outside_callbacks.splice(index, 1);
    }
  }
}

/**
 * Adds up, down, esc, enter keypress event on 'element' to traverse though 'items'
 *
 * @param {HTMLElement} element
 * @param {HTMLCollection|NodeList} items
 * @param {function} itemSelectCallback
 *   callback(null) if Enter was pressed and no item was selected (for example custom value entered)
 *   callback(false) if Esc was pressed (canceled)
 *   callback({HTMLElement} item) - selected item on Enter
 * @param {function} itemSwitchCallback = null
 *   callback({HTMLElement} item) - new item on arrow up/down
 *
 * @returns {function(*)}
 */
export function addEventKeyNavigation(element, items, itemSelectCallback, itemSwitchCallback = null) {

  let currentItemIndex = null;
  for (let k = 0; k < items.length; k++) {
    if (items[k].hasAttribute('aria-selected')) {
      currentItemIndex = k;
      break;
    }
  }

  /*let currentActiveItems = [];
  for (let k = 0; k < items.length; k++) {
    if (items[k].classList.contains(activeClass)) {
      currentActiveItems.push(items[k]);
    }
  }*/

  const _itemAdd = () => {
    items[currentItemIndex].focus();
    //items[currentItemIndex].classList.add(activeClass);
    //items[currentItemIndex].setAttribute('aria-selected', 'true');
    /*if (!BunnyElement.isInViewport(items[currentItemIndex])) {
      BunnyElement.scrollTo(items[currentItemIndex], 400, -200);
    }*/
    //items[currentItemIndex].scrollIntoView(false);
    if (itemSwitchCallback !== null) {
      itemSwitchCallback(items[currentItemIndex]);
    }
  };

  const _itemRemove = () => {
    //items[currentItemIndex].classList.remove(activeClass);
    //items[currentItemIndex].removeAttribute('aria-selected');
  };

  const handler = (e) => {
    const c = e.keyCode;

    const maxItemIndex = items.length - 1;

    if (c === KEY_ENTER || c === KEY_SPACE) {
      e.preventDefault();
      if (currentItemIndex !== null) {
        items[currentItemIndex].click();
        itemSelectCallback(items[currentItemIndex]);
      } else {
        itemSelectCallback(null);
      }

    } else if (c === KEY_ESCAPE) {
      e.preventDefault();
      /*for (let k = 0; k < items.length; k++) {
        if (currentActiveItems.indexOf(items[k]) === -1) {
          // remove active state
          items[k].classList.remove(activeClass);
          items[k].removeAttribute('aria-selected');
        } else {
          // set active state
          items[k].classList.add(activeClass);
          items[k].setAttribute('aria-selected', 'true');
        }
      }*/
      itemSelectCallback(false);

    } else if (c === KEY_ARROW_UP || c === KEY_ARROW_LEFT) {
      e.preventDefault();
      if (currentItemIndex !== null && currentItemIndex > 0) {
        _itemRemove();
        currentItemIndex -= 1;
        _itemAdd();
      }

    } else if (c === KEY_ARROW_DOWN || c === KEY_ARROW_RIGHT) {
      e.preventDefault();
      if (currentItemIndex === null) {
        currentItemIndex = 0;
        _itemAdd();
      } else if (currentItemIndex < maxItemIndex) {
        _itemRemove();
        currentItemIndex += 1;
        _itemAdd();
      }
    }
  };

  if (items.length > 0) {
    element.addEventListener('keydown', handler);
  }

  return handler;
}

export function removeEventKeyNavigation(element, handler) {
  element.removeEventListener('keydown', handler);
}


text:
package com.thoughtworks.cruise.context.configuration;

import com.thoughtworks.cruise.context.Configuration;
import com.thoughtworks.cruise.state.RepositoryState;
import com.thoughtworks.cruise.state.ScenarioState;
import com.thoughtworks.cruise.utils.ScenarioHelper;
import net.sf.sahi.client.Browser;

public class MultipleAgentsConfiguration extends AbstractConfiguration {

	public MultipleAgentsConfiguration(Configuration config, ScenarioState state, RepositoryState repositoryState, ScenarioHelper scenarioHelper, Browser browser) throws Exception {
		super("/config/multiple-agents-cruise-config.xml", config, state, repositoryState, scenarioHelper, browser);
	}

	// setUp and tearDown is needed because Twist scenarios need their contexts to support these otherwise they show compile errors!
	@com.thoughtworks.gauge.Step("Multiple agents configuration - setup")
	public void setUp() throws Exception {
		super.setUp();
	}

	@com.thoughtworks.gauge.Step("Multiple agents configuration - teardown")
	public void tearDown() throws Exception {
		super.tearDown();
	}
}


text:
package me.suisui.framework.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

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

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.Maps;
/**
 * 系统的Cache都是从这里创建的, 包括GuavaCacheManager 和 CacheableDao 和spring自定义Cache Annotation
 * @author swaron
 *
 */
public class AppCache {
	public static final String DEFAULT_SPEC_NAME = "default";
	public static Logger logger = LoggerFactory.getLogger(AppCache.class);
	public static Map<String, String> cacheBuilderSpecs = new HashMap<String, String>(0);
	public static Map<String, CacheLoader<Object, Object>> cacheLoaders = Maps.newHashMap();
	private static ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);

	public static Cache getCache(String name){
		return cacheMap.get(name);
	}
	public static <K1 , V1> Cache<K1, V1>  createCache(String name,String spec){
		return createCache(name, spec, null);
	}
	public static <K1 , V1> Cache<K1, V1> createCache(String name,String spec,CacheLoader<Object, Object> cacheLoader){
		synchronized (cacheMap) {
			Cache cache = cacheMap.get(name);
			if(cache != null){
				logger.warn("duplicately create cache with same name.");
				return cache;
			}
			CacheBuilder<Object, Object> builder = CacheBuilder.from(spec);
			if (cacheLoader != null) {
				cache = builder.build(cacheLoader);
			} else {
				cache = builder.build();
			}
			cacheMap.put(name, cache);
			return cache;
		}
	}
	public static Set<String> getCacheNames() {
		return Collections.unmodifiableSet(cacheMap.keySet());
	}
}


text:
package SNMP::Info::Layer3::Mikrotik;

use strict;
use Exporter;
use SNMP::Info::Layer3;

@SNMP::Info::Layer3::Mikrotik::ISA       = qw/SNMP::Info::Layer3 Exporter/;
@SNMP::Info::Layer3::Mikrotik::EXPORT_OK = qw//;

use vars qw/$VERSION %GLOBALS %MIBS %FUNCS %MUNGE/;

$VERSION = '3.29';

%MIBS = (
    %SNMP::Info::Layer3::MIBS,
    'HOST-RESOURCES-MIB'       => 'hrSystem',
    'MIKROTIK-MIB'             => 'mtxrLicVersion',
);

%GLOBALS = (
    %SNMP::Info::Layer3::GLOBALS,
    'hrSystemUptime' => 'hrSystemUptime',
    'os_level'       => 'mtxrLicLevel',
    'os_ver'         => 'mtxrLicVersion',
    'serial1'        => 'mtxrSystem.3.0',
    'firmware'       => 'mtxrSystem.4.0',
    'fan_type'       => 'mtxrHlActiveFan',
);

%FUNCS = (
    %SNMP::Info::Layer3::FUNCS,
);

%MUNGE = (
    %SNMP::Info::Layer3::MUNGE,
);

sub vendor {
    return 'mikrotik';
}

sub serial {
    my $mikrotik = shift;
    return $mikrotik->serial1;
}

sub model {
    my $mikrotik = shift;
    my $descr = $mikrotik->description() || '';
    my $model = undef;
    $model = $1 if ( $descr =~ /^RouterOS\s+(\S+)$/i );
    return $model;
}

sub os {
    return 'routeros';
}

sub board_temp {
    my $mikrotik = shift;
    my $temp = $mikrotik->mtxrHlTemperature;
    return $temp / 10.0;
}

sub cpu_temp {
    my $mikrotik = shift;
    my $temp = $mikrotik->mtxrHlProcessorTemperature;
    return $temp / 10.0;
}

1;
__END__

=head1 NAME

SNMP::Info::Layer3::Mikrotik - SNMP Interface to Mikrotik devices

=head1 AUTHORS

Jeroen van Ingen
initial version based on SNMP::Info::Layer3::NetSNMP by Bradley Baetz and Bill Fenner

=head1 SYNOPSIS

 # Let SNMP::Info determine the correct subclass for you.
 my $mikrotik = new SNMP::Info(
                          AutoSpecify => 1,
                          Debug       => 1,
                          DestHost    => 'myrouter',
                          Community   => 'public',
                          Version     => 2
                        )
    or die "Can't connect to DestHost.\n";

 my $class      = $mikrotik->class();
 print "SNMP::Info determined this device to fall under subclass : $class\n";

=head1 DESCRIPTION

Subclass for Mikrotik devices

=head2 Inherited Classes

=over

=item SNMP::Info::Layer3

=back

=head2 Required MIBs

=over

=item F<HOST-RESOURCES-MIB>

=item F<MIKROTIK-MIB>

=item Inherited Classes' MIBs

See L<SNMP::Info::Layer3> for its own MIB requirements.

=back

=head1 GLOBALS

These are methods that return scalar value from SNMP

=over

=item $mikrotik->vendor()

Returns C<'mikrotik'>.

=item $mikrotik->os()

Returns C<'routeros'>.

=item $mikrotik->model()

Tries to extract the device model from C<sysDescr>.

=item $mikrotik->os_ver()

Returns the value of C<mtxrLicVersion>.

=item $mikrotik->os_level()

Returns the value of RouterOS level C<mtxrLicLevel>

=item $mikrotik->board_temp()
=item $mikrotik->cpu_temp()

Returns the appropriate temperature values

=item $mikrotik->serial()

Returns the device serial.

=item $mikrotik->firmware()

Returns the firmware version of hardware.

=back

=head2 Globals imported from SNMP::Info::Layer3

See documentation in L<SNMP::Info::Layer3> for details.

=head1 TABLE ENTRIES

These are methods that return tables of information in the form of a reference
to a hash.

=head2 Overrides

None.

=over

=back

=head2 Table Methods imported from SNMP::Info::Layer3

See documentation in L<SNMP::Info::Layer3> for details.

=cut


text:
SYNONYM

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

#### Published in
Revis. gen. pl. (Leipzig) 3: 470 (1898)

#### Original name
Aecidium prenanthis Pers., 1801

### Remarks
null