text:
package com.spotify.sparkey;

import java.io.*;

final class Util {
  static int unsignedByte(byte b) {
    return ((int) b) & 0xFF;
  }

  static void writeLittleEndianInt(int value, InMemoryData data) throws IOException {
    data.writeUnsignedByte((value) & 0xFF);
    data.writeUnsignedByte((value >>> 8) & 0xFF);
    data.writeUnsignedByte((value >>> 16) & 0xFF);
    data.writeUnsignedByte((value >>> 24) & 0xFF);
  }

  static void writeLittleEndianInt(int value, RandomAccessFile rw) throws IOException {
    rw.write((value) & 0xFF);
    rw.write((value >>> 8) & 0xFF);
    rw.write((value >>> 16) & 0xFF);
    rw.write((value >>> 24) & 0xFF);
  }

  static void writeLittleEndianLong(long value, InMemoryData data) throws IOException {
    data.writeUnsignedByte((int) ((value) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 8) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 16) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 24) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 32) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 40) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 48) & 0xFF));
    data.writeUnsignedByte((int) ((value >>> 56) & 0xFF));
  }

  static void writeLittleEndianLong(long value, RandomAccessFile rw) throws IOException {
    writeLittleEndianInt((int) value, rw);
    writeLittleEndianInt((int) (value >>> 32), rw);
  }

  static long readLittleEndianLong(RandomAccessData data) throws IOException {
    long res = (long) data.readUnsignedByte();
    res |= ((long) data.readUnsignedByte()) << 8;
    res |= ((long) data.readUnsignedByte()) << 16;
    res |= ((long) data.readUnsignedByte()) << 24;
    res |= ((long) data.readUnsignedByte()) << 32;
    res |= ((long) data.readUnsignedByte()) << 40;
    res |= ((long) data.readUnsignedByte()) << 48;
    res |= ((long) data.readUnsignedByte()) << 56;
    return res;
  }

  static long readLittleEndianLong(InputStream input) throws IOException {
    return (long) readByte(input) | (long) readByte(input) << 8 | (long) readByte(
            input) << 16 | (long) readByte(input) << 24
            | (long) readByte(input) << 32 | (long) readByte(input) << 40 | (long) readByte(
            input) << 48 | (long) readByte(input) << 56;
  }

  static int readLittleEndianInt(RandomAccessData data) throws IOException {
    int a = data.readUnsignedByte();
    int b = data.readUnsignedByte();
    int c = data.readUnsignedByte();
    int d = data.readUnsignedByte();
    return a << 0 | b << 8 | c << 16 | d << 24;
  }

  static int readLittleEndianInt(InputStream input) throws IOException {
    int a = readByte(input);
    int b = readByte(input);
    int c = readByte(input);
    int d = readByte(input);
    return (a) | (b << 8) | (c << 16) | (d << 24);
  }

  static int unsignedVLQSize(int value) {
    if (value < 1 << 7) {
      return 1;
    }
    if (value < 1 << 14) {
      return 2;
    }
    if (value < 1 << 21) {
      return 3;
    }
    if (value < 1 << 28) {
      return 4;
    }
    return 5;
  }

  static int unsignedVLQSize(long value) {
      if (value < 1L << 7) {
          return 1;
      }
      if (value < 1L << 14) {
          return 2;
      }
      if (value < 1L << 21) {
          return 3;
      }
      if (value < 1L << 28) {
          return 4;
      }
      if (value < 1L << 35) {
          return 5;
      }
      if (value < 1L << 42) {
          return 6;
      }
      if (value < 1L << 49) {
          return 7;
      }
      if (value < 1L << 56) {
          return 8;
      }
      return 9;
  }

  static void writeUnsignedVLQ(long value, OutputStream output) throws IOException {
    while (value >= 1 << 7) {
      output.write((int) (value & 0x7f) | 0x80);
      value >>>= 7;
    }
    output.write((int) value);
  }

  static void writeUnsignedVLQ(int value, OutputStream output) throws IOException {
    while (value >= 1 << 7) {
      output.write(value & 0x7f | 0x80);
      value >>>= 7;
    }
    output.write(value);
  }

  static int readUnsignedVLQInt(BlockRandomInput input) throws IOException {
    int b = input.readUnsignedByte();
    int b2 = b & 0x7f;
    if (b2 == b) {
      return b;
    }
    int value = b2 & 0x7f;

    b = input.readUnsignedByte();
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 7;
    }
    value |= b2 << 7;

    b = input.readUnsignedByte();
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 14;
    }
    value |= b2 << 14;

    b = input.readUnsignedByte();
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 21;
    }
    value |= b2 << 21;

    b = input.readUnsignedByte();
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 28;
    }
    throw new RuntimeException("Too long VLQ value");
  }

  static int readUnsignedVLQInt(InputStream input) throws IOException {
    int b = readByte(input);
    int b2 = b & 0x7f;
    if (b2 == b) {
      return b;
    }
    int value = b2 & 0x7f;

    b = readByte(input);
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 7;
    }
    value |= b2 << 7;

    b = readByte(input);
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 14;
    }
    value |= b2 << 14;

    b = readByte(input);
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 21;
    }
    value |= b2 << 21;

    b = readByte(input);
    b2 = b & 0x7f;
    if (b2 == b) {
      return value | b << 28;
    }
    throw new RuntimeException("Too long VLQ value");
  }

  static int readByte(InputStream input) throws IOException {
    int read = input.read();
    if (read < 0) {
      throw new EOFException();
    }
    return read;
  }

  static void copy(long len, InputStream inputStream, OutputStream outputStream, byte[] buf) throws IOException {
    long full = len / buf.length;
    while (full > 0) {
      full--;
      readFully(inputStream, buf, buf.length);
      outputStream.write(buf, 0, buf.length);
    }
    int tail = (int) (len % buf.length);
    readFully(inputStream, buf, tail);
    outputStream.write(buf, 0, tail);
  }

  static void readFully(InputStream inputStream, byte[] buf, int len) throws IOException {
    int pos = 0;
    int remaining = len;
    while (pos < len) {
      int read = inputStream.read(buf, pos, remaining);
      if (read == -1) {
        throw new EOFException();
      }
      pos += read;
      remaining -= read;
    }
  }

  static boolean equals(int len, byte[] a, byte[] b) {
    while (--len >= 0) {
      if (a[len] != b[len]) {
        return false;
      }
    }
    return true;
  }

  static void nonThrowingClose(Closeable stream) {
    try {
      stream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


text:
layout: post
title: "Improved Heuristics for Solving the Pancake Problem"
author: "Danniel Yang"
supervisors: "Dr. Rick Valenzano and Professor Sheila McIlraith"
category: "Artificial Intelligence"
permalink: /artificial-intelligence/heuristics-for-solving-the-pancake-problem
---

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

The pancake problem is a well-known combinatorial optimization
problem first studied by Bill Gates and Christos Papadimitriou in 1979
[2]. The problem is described as follows: a chef has a stack of
pancakes, all of which have different sizes. Before serving the stack,
the chef must sort the pancakes so that they are in ascending order – in
size – from top to bottom. However, the chef can only reorder pancakes
by using a spatula to flip some number of pancakes on top of the stack.
Given an unsorted stack, the objective is to sort it using as few flips
as possible.

This problem, which has recently been shown to be NP-hard [1],
has seen continued interest due to its relation to a number of
applications. These include calculating genome similarity [3] and
physical stacking problems, such as using a forklift to stack a set of
differently sized boxes in a structurally sound way. The problem is also
a standard benchmark in the heuristic search community, as search
techniques have proven to be an effective way to optimally sort pancake
stacks. In this work, we increase our understanding of the behaviour of
such approaches on this problem by evaluating the accuracy of a
state-of-the-art heuristic function. We also propose three new heuristic
functions that greatly improve problem-solving time.

Background
==========

A stack of $n$ pancakes can be represented as a permutation of the
numbers from $1$ to $n + 1$, where the permutation maps each location in
the stack to the pancake at that location. In this representation, $n+1$
corresponds to the plate under the stack and can never be flipped. For
example, $(2~1~4~3~5)$ represents a stack of $4$ pancakes in which the
second smallest pancake is on top of the stack and is followed by the
smallest pancake.

Iterative Deepening A\ (IDA\*) [5] is a heuristic search
algorithm that is commonly used to solve state-space search
problems. This algorithm employs a heuristic function, which
estimates the optimal cost of reaching a goal from any given state.
In the pancake puzzle, this means that the heuristic function estimates
the minimum number of flips needed to sort a given stack. IDA\* is
guaranteed to only find optimal solutions if the heuristic function
never overestimates the cost of reaching the goal. Such heuristic
functions are said to be admissible.

The state-of-the-art heuristic function used for the pancake problem is
the gap heuristic function [4]. A gap occurs whenever two
adjacent pancakes in a stack are not adjacent in the sorted stack; this
computation includes the plate as a pancake. The gap heuristic function
then counts the number of gaps in the stack. For example, in stack
$(2~1~4~3~5)$, there is a gap between every pair of consecutive pancakes
except pancakes $4$ and $3$, and so the heuristic estimate for this
stack is $3$. Since each flip can remove at most one gap, this heuristic
function is admissible.

New Heuristic Functions
=======================

In this work, we introduce three new admissible heuristic functions for
this problem. All three functions use the inverse of a permutation,
which is a mapping from each pancake to its location in the stack. For
example, the inverse of $(2~4~1~3~5)$ is $(3~1~4~2~5)$.

The first new function uses the inverse to quickly identify stacks in
which no single flip will decrease the number of gaps. This top
heuristic function increases the gap heuristic estimate by one in such
cases. The top' heuristic function is then given by the maximum of
the values returned by the top heuristic function when applied to both a
stack and its inverse. Top' remains admissible since the number of flips
needed to sort a stack is the same number needed to sort its inverse
[6]. Finally, we have also developed a way to quickly look ahead
to the top heuristic estimates of all successors of a stack, and thereby
improve the estimate of the stack itself. The **L-top'** heuristic
function is then given by the maximum found using this lookahead on both
a stack and its inverse.

Experimental Analysis
=====================

To better understand the gap heuristic function, we analyzed its
accuracy on all $10!$ possible $10$-pancake stacks by calculating the
**heuristic error** on each. This metric is defined as the difference
between the heuristic estimate and the optimal cost of that problem. The
first column of Table 1 shows a count of the number of states
with each amount of heuristic error. The table shows that the gap
heuristic function is off by no more than one on the majority of
problems, though there are stacks where it is much more inaccurate.

These results suggest that it is highly likely that the gap heuristic
function will be very accurate on any randomly generated stack, and we
confirmed this holds on larger stacks by random sampling. This helps to
explain the success of IDA\*-based approaches seen in the literature, in
which random sampling is the standard way to generate test sets
[4, 6].

| Heuristic Error | Gap      | Top      | Top'     | L-Top'   |
|:---------------:|:--------:|:--------:|:--------:|:--------:|
|0                |1,717,763 |1,839,701 |1,924,425 |1,992,492 |
|1                |1,710,742 |1,644,853 |1,593,637 |1,547,761 |
|2                |194,280   |141,609   |109,304   |87,645    |
|3                |5,924     |2,620     |1,430     |898       |
|4                |91        |17        |4         |4         |

Table 1: Heuristic  accuracy  on  all  stacks  of  10  pancakes.   The  entries  are  thenumber of problems with the corresponding heuristic error.

Table 1 also displays heuristic error information for our new
heuristic functions. It shows that these functions are increasingly
accurate, so we tested them as part of an IDA\*-based solver to see if
the improved accuracy translated into better performance. We
experimented on two different test sets. The first, "random $50$",
consists of $1000$ randomly generated stacks of $50$ pancakes. The
second, "constructed $32$", consists of $1000$ stacks of $32$ pancakes
with a higher average heuristic error for the gap heuristic function.

Table 2 shows the performance of each heuristic function on
both test sets. For each function, the table shows the improvement seen
relative to the gap heuristic function, where a larger value indicates a
greater speedup. Clearly, the new heuristics lead to substantial
speedups on both test sets.

| Problem       | Gap | Top | Top' | L-Top'|
|:-------------:|:---:|:---:|:----:|:-----:|
|random 50      |1.0  |1.28 |1.74  |2.51   |
|constructed 32 |1.0  |1.95 |4.31  |6.94   |

Table 2: The relative performance of IDA* when using different heuristic functions on two problem sets. The table shows the speedup seen relative to the gap heuristic function.

Conclusion
==========

In this work, we identified that the gap heuristic function is very
accurate on randomly generated pancake problems, though there are stacks
for which it is inaccurate. We then introduced three new heuristic
functions that are more accurate and greatly improved search
performance. Our work both improves our ability to solve pancake
problems, and increases our understanding of this well-studied problem.

### References

1. Laurent Bulteau, Guillaume Fertin, and Irena Rusu.  Pancake flipping is hard.Journal of Computer and System Sciences, 81(8):1556–1574, 2015.

2. William Gates and Christos Papadimitriou. Bounds for sorting by prefix reversal.Discrete Math, 27:47–57, 1979

3. Brian Hayes. Sorting out the genome.American Scientist, 95:386–391, 2007.

4. Malte Helmert. Landmark heuristics for the pancake problem. InProceedings ofthe Third Annual Symposium on Combinatorial Search, SOCS 2010, in pages109-110, 2010, 2010.

5. Richard  E.  Korf.   Depth-first  iterative-deepening:  An  optimal  admissible  treesearch.Artificial Intelligence, 27(1):97–109, 1985.

6. Uzi Zahavi, Ariel Felner, Robert C. Holte, and Jonathan Schaeffer.  Duality inpermutation state spaces and the dual search algorithm.Artificial Intelligence,172(4-5):514–540, 2008.

redpajama_set_name: RedPajamaGithub


text:
package com.tangkuo.cn.pay.kmtk.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

import org.apache.commons.lang3.StringUtils;

public final class Calculator {

    /**
     * 方法说明:加法运算
     *
     * @param x
     * @param y
     * @return
     */
    public static double add(double x, double y) {
        BigDecimal bigX = new BigDecimal(x);
        BigDecimal bigY = new BigDecimal(y);
        return bigX.add(bigY).doubleValue();
    }

    /**
     * 方法说明:减法运算
     *
     * @param x
     * @param y
     * @return
     */
    public static double subtract(double x, double y) {
        BigDecimal bigX = new BigDecimal(x);
        BigDecimal bigY = new BigDecimal(y);
        return bigX.subtract(bigY).doubleValue();
    }

    /**
     * 方法说明: 乘法运算
     *
     * @param x
     * @param y
     * @return
     */
    public static double multiply(double x, double y) {
        BigDecimal bigX = new BigDecimal(String.valueOf(x));
        BigDecimal bigY = new BigDecimal(String.valueOf(y));
        return bigX.multiply(bigY).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
    }

    /**
     * 方法说明: 乘法运算
     *
     * @param x
     * @param y
     * @return
     */
    public static long multiply2(long x, double y) {
        BigDecimal bigX = new BigDecimal(String.valueOf(x));
        BigDecimal bigY = new BigDecimal(String.valueOf(y));
        return bigX.multiply(bigY).setScale(2, BigDecimal.ROUND_HALF_EVEN).longValue();
    }

    /**
     * 方法说明: 除法运算(两位小数,四舍五入)
     *
     * @param x
     * @param y 为0则返回0
     * @return
     */
    public static double divide(double x, double y) {
        if (y == 0) {
            return 0;
        }
        BigDecimal bigX = new BigDecimal(String.valueOf(x));
        BigDecimal bigY = new BigDecimal(String.valueOf(y));
        return bigX.divide(bigY, 2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
    }

    /**
     * 方法说明:减法运算
     *
     * @param x
     * @param y
     * @return
     */
    public static long subtractLong(long x, long y) {
        BigInteger bigX = new BigInteger(String.valueOf(x));
        BigInteger bigY = new BigInteger(String.valueOf(y));
        return bigX.subtract(bigY).longValue();
    }

    /**
     * 方法说明:金额元转为分

     *
     * @param amount
     * @return
     */
    public static long jmoney(String amount) {
        if (StringUtils.isEmpty(amount)) {
            return 0;
        }
        if (amount.indexOf(",") != -1) {
            amount = amount.replace(",", "");
        }
        BigDecimal decimal = new BigDecimal(amount);
        return decimal.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_EVEN).longValue();
    }

    /**
     * 方法说明:金额元转为分

     *
     * @param amount
     * @return
     */
    public static long jmoney(double amount) {
        if (amount <= 0) {
            return 0;
        }
        BigDecimal decimal = new BigDecimal(amount);
        return decimal.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_EVEN).longValue();
    }

    /**
     * 方法说明:金额分转为元 除法运算(两位小数,四舍五入)
     *
     * @param amount 金额(单位为分)
     * @param n 小数点位数
     * @return
     */
    public static String fmoney(long amount, int n) {
        BigDecimal decimal = new BigDecimal(amount);
        return String.valueOf(decimal.divide(new BigDecimal(100), n, RoundingMode.HALF_UP));
    }

    /**
     * 方法说明:金额分转为元, 2小数点位数 除法运算(两位小数,四舍五入)
     *
     * @param amount 金额(单位为分)
     * @return
     */
    public static double fmoney(long amount) {
        if (amount <= 0) {
            return 0D;
        }
        BigDecimal decimal = new BigDecimal(amount);
        return decimal.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * 方法说明:金额分转为元 除法运算(两位小数,四舍五入)
     *
     * @param amount 金额(单位为分)
     * @param n 小数点位数
     * @return
     */
    public static String fmoney(String amount, int n) {
        if (StringUtils.isEmpty(amount)) {
            return "0.00";
        }
        BigDecimal decimal = new BigDecimal(amount);
        return String.valueOf(decimal.divide(new BigDecimal(100), n, RoundingMode.HALF_UP));
    }

    /**
     * 方法说明:金额分转为万元 除法运算(两位小数,四舍五入)
     *
     * @param amount 金额(单位为分)
     * @param n 小数点位数
     * @return
     */
    public static String wmoney(String amount, int n) {
        if (StringUtils.isEmpty(amount)) {
            return "0.00";
        }
        BigDecimal decimal = new BigDecimal(amount);
        return String.valueOf(decimal.divide(new BigDecimal(1000000), n, RoundingMode.HALF_UP));
    }

    /**
     * 方法说明:金额万元转为分 乘法运算
     *
     * @param amount 金额(单位为万)
     * @return
     */
    public static long wmoney(String amount) {
        if (StringUtils.isEmpty(amount)) {
            return 0;
        }
        BigDecimal decimal = new BigDecimal(amount);
        return decimal.multiply(new BigDecimal(1000000)).setScale(0, BigDecimal.ROUND_HALF_EVEN).longValue();
    }

}


text:
import React from 'react'
import { Image, Reveal } from 'semantic-ui-react'

const RevealExampleActive = () => (
  <Reveal active animated='move'>
    <Reveal.Content visible>
      <Image src='/images/wireframe/square-image.png' size='small' />
    </Reveal.Content>
    <Reveal.Content hidden>
      <Image src='/images/avatar/large/nan.jpg' size='small' />
    </Reveal.Content>
  </Reveal>
)

export default RevealExampleActive


text:
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>

    </script>


text:
<?xml version="1.0"?>
<properties>
	<Edit>true</Edit>
	<Files>true</Files>
	<Properties>true</Properties>
	<RecentChanges>true</RecentChanges>
	<Refactor>true</Refactor>
	<Search>true</Search>
	<Versions>true</Versions>
	<WhereUsed>true</WhereUsed>
	<saveId>1204988968968</saveId>
	<ticketId>7175845390249155608</ticketId>
</properties>


text:
NS_ASSUME_NONNULL_BEGIN

@implementation SDLTemperature

- (instancetype)initWithFahrenheitValue:(float)value {
    return [self initWithUnit:SDLTemperatureUnitFahrenheit value:value];
}

- (instancetype)initWithCelsiusValue:(float)value {
    return [self initWithUnit:SDLTemperatureUnitCelsius value:value];
}

- (instancetype)initWithUnit:(SDLTemperatureUnit)unit value:(float)value {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.unit = unit;
    self.value = @(value);

    return self;
}

- (void)setUnit:(SDLTemperatureUnit)unit {
    [self.store sdl_setObject:unit forName:SDLRPCParameterNameUnit];
}

- (SDLTemperatureUnit)unit {
    NSError *error = nil;
    return [self.store sdl_enumForName:SDLRPCParameterNameUnit error:&error];
}

- (void)setValue:(NSNumber<SDLFloat> *)value {
    [self.store sdl_setObject:value forName:SDLRPCParameterNameValue];
}

- (NSNumber<SDLFloat> *)value {
    NSError *error = nil;
    return [self.store sdl_objectForName:SDLRPCParameterNameValue ofClass:NSNumber.class error:&error];
}

@end

NS_ASSUME_NONNULL_END


text:
package org.q3df.common.msg;

public interface BitStreamWriter {
    int getByte(int byteIdx);

    int getBitsSize();

    int getSize();

    int getWriteBitPos();

    boolean isEOWR();

    boolean writeBit(boolean isSet);

    boolean writeBit(int bit);

    boolean writeBits(int val, int bits);

    byte[] data();
}


text:
div.slogin-clear{
    clear: both;
}

#form-login-remember label {
    cursor: pointer;float:none;
}

#modlgn-remember {
    display: inline-block;
    height: auto;
    margin: 0;
    padding: 0;
    position: relative;
    width: auto;
}

.button
{
    background: #EEEEEE;
    border: medium none;
    color: #444444;
    display: inline-block;
    letter-spacing: normal;
    line-height: 30px;
    min-height: 30px;
    padding: 0 12px;
	background-color: #00A8E6;
    color: #FFFFFF
}
#modlgn-username
{
    background: #FFFFFF;
    border: 1px solid #DDDDDD;
    color: #444444;
    height: 30px;
	width: 100%;
    padding: 4px 6px;

}
.ul-jlslogin
{
	list-style: none outside none;
	padding: 5px 0 0;
	margin: 0;
}

#modlgn-passwd
{
    background: #FFFFFF;
    border: 1px solid #DDDDDD;
    color: #444444;
    height: 30px;
    width: 100%;
    padding: 4px 6px;
}

.login-greeting
{
    padding: 0 0 5px;
}
#login-form
{
	padding: 10px 0 0;
}

#form-login-remember label{cursor:pointer}

.userdata #form-login-password label
{
    display: block;
    float: left;
    margin-right: 10px;
    width: 20%;
}

.userdata #form-login-username label
{
    display: block;
    float: left;
    margin-right: 10px;
    width: 20%;
}

.slogin-buttons span {
    background: url(../../media/socials_sprite.png) no-repeat;
    height: 25px;
    width: 100px;
    display:block;
}
.slogin-buttons a, .slogin-buttons a:hover {
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    text-decoration:none;
    float: left;
}
.slogin-buttons a {
    display: block;
    width: 95px;
    padding:5px 10px 5px 10px;
    margin:5px 5px 0 0;
	text-decoration: none;
}

.slogin-buttons a:hover {
    background:#f4f3f2;
}

.slogin-buttons .googleslogin {
    background-position: 0 -100px;
}

.slogin-buttons .odnoklassnikislogin {
    background-position: 0 -140px;
}
.slogin-buttons .vkontakteslogin {
    background-position: 0 -180px;
}
.slogin-buttons .facebookslogin {
    background-position: 0 -220px;
}
.slogin-buttons .mailslogin {
    background-position: 0 -260px;
}
.slogin-buttons .twitterslogin {
    background-position: 0 -300px;
}

.slogin-buttons .yandexslogin {
    background-position: 0 -340px;
}

.slogin-buttons .linkedinslogin {
    background-position: 0 -380px;
}

.slogin-buttons .liveslogin {
    background-position: 0 -420px;
}

.slogin-buttons .uloginslogin {
    background-position: -100px -100px;
}

.slogin-buttons .yahooslogin {
    background-position: -100px -180px;
}

.slogin-buttons .wordpressslogin {
    background-position: -100px -220px;
}

.slogin-buttons .instagramslogin {
    background-position: -100px -260px;
}

.slogin-avatar{
    text-align: center;
}
.slogin-avatar img{
    border: 1px solid #c0c0c0;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    padding: 5px;
    margin: 10px;
}


text:
package com.hack23.cia.web.impl.ui.application.views.pageclicklistener;

import java.net.URI;
import java.net.URISyntaxException;

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

import com.hack23.cia.service.api.action.common.ServiceResponse.ServiceResult;
import com.hack23.cia.service.api.action.user.SetGoogleAuthenticatorCredentialRequest;
import com.hack23.cia.service.api.action.user.SetGoogleAuthenticatorCredentialResponse;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

import fi.jasoft.qrcode.QRCode;

/**
 * The Class SetGoogleAuthenticatorCredentialClickListener.
 */
public final class SetGoogleAuthenticatorCredentialClickListener extends AbstractClickListener implements ClickListener {

	/** The Constant ERROR_MESSAGE. */
	private static final String ERROR_MESSAGE = "Error message";

	/** The Constant GOOGLE_AUTHENTICATOR_QR_CODE. */
	private static final String GOOGLE_AUTHENTICATOR_QR_CODE = "Google Authenticator QR code";

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory.getLogger(SetGoogleAuthenticatorCredentialClickListener.class);

	/** The Constant MODAL_WINDOW_SIZE. */
	private static final String MODAL_WINDOW_SIZE = "400px";

	/** The Constant PROBLEM_DISPLAYING_QR_CODE. */
	private static final String PROBLEM_DISPLAYING_QR_CODE = "Problem displaying qr code";

	/** The Constant PROBLEM_ENABLE_GOOGLE_AUTHENTICATOR. */
	private static final String PROBLEM_ENABLE_GOOGLE_AUTHENTICATOR = "Problem enable google authenticator";

	/** The Constant PROBLEM_ENABLE_GOOGLE_AUTHENTICATOR_SESSIONID. */
	private static final String PROBLEM_ENABLE_GOOGLE_AUTHENTICATOR_SESSIONID = "Problem enable google authenticator, sessionid{}";

	/** The Constant QR_CODE. */
	private static final String QR_CODE = "QR code";

	/** The Constant QR_CODE_IMAGE_SIZE. */
	private static final String QR_CODE_IMAGE_SIZE = "175px";

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The Constant WINDOW_POSITION. */
	private static final int WINDOW_POSITION = 100;

	/** The google auth request. */
	private final SetGoogleAuthenticatorCredentialRequest googleAuthRequest;

	/**
	 * Instantiates a new sets the google authenticator credential click
	 * listener.
	 *
	 * @param googleAuthRequest
	 *            the google auth request
	 */
	public SetGoogleAuthenticatorCredentialClickListener(final SetGoogleAuthenticatorCredentialRequest googleAuthRequest) {
		this.googleAuthRequest = googleAuthRequest;
	}

	@Override
	public void buttonClick(final ClickEvent event) {
		final SetGoogleAuthenticatorCredentialResponse response = (SetGoogleAuthenticatorCredentialResponse) getApplicationManager().service(googleAuthRequest);

		if (ServiceResult.SUCCESS == response.getResult()) {

			try {
				final URI keyUri = new URI(response.getOtpAuthTotpURL());
				final QRCode qrCode = new QRCode(QR_CODE, keyUri.toASCIIString());
				qrCode.setHeight(QR_CODE_IMAGE_SIZE);
				qrCode.setWidth(QR_CODE_IMAGE_SIZE);

				final Window mywindow = new Window(GOOGLE_AUTHENTICATOR_QR_CODE);
				mywindow.setHeight(MODAL_WINDOW_SIZE);
				mywindow.setWidth(MODAL_WINDOW_SIZE);

				mywindow.setPositionX(WINDOW_POSITION);
				mywindow.setPositionY(WINDOW_POSITION);

				final VerticalLayout panelContent = new VerticalLayout();

				mywindow.setContent(panelContent);
				panelContent.addComponent(qrCode);

				mywindow.setModal(true);
				UI.getCurrent().addWindow(mywindow);

			} catch (final URISyntaxException e) {
				LOGGER.warn(PROBLEM_DISPLAYING_QR_CODE,e);
				showNotification(PROBLEM_DISPLAYING_QR_CODE,
		                  ERROR_MESSAGE,
		                  Notification.Type.WARNING_MESSAGE);
			}

		} else {
			showNotification(PROBLEM_ENABLE_GOOGLE_AUTHENTICATOR,
	                  ERROR_MESSAGE,
	                  Notification.Type.WARNING_MESSAGE);
			LOGGER.info(PROBLEM_ENABLE_GOOGLE_AUTHENTICATOR_SESSIONID,googleAuthRequest.getSessionId());
		}
	}
}


text:
/*
 *  duk_safe_call() reserve handling
 */

/*===
*** test_1 (duk_pcall)
top before: 8
top in dummy_func: 8
duk_safe_call() rc: 0
final top: 4101
==> rc=0, result='undefined'
*** test_2 (duk_pcall)
top before: 8
==> rc=1, result='TypeError: invalid args'
===*/

static duk_ret_t dummy_func(duk_context *ctx, void *udata) {
	(void) udata;
	printf("top in dummy_func: %ld\n", (long) duk_get_top(ctx));
	return 0;
}

static duk_ret_t test_1(duk_context *ctx) {
	duk_int_t rc;

	/* Some ignored values. */
	duk_push_null(ctx);
	duk_push_null(ctx);
	duk_push_null(ctx);
	duk_push_null(ctx);
	duk_push_null(ctx);

	duk_push_string(ctx, "foo");
	duk_push_string(ctx, "bar");
	duk_push_string(ctx, "quux");

	duk_require_stack(ctx, 4096 - 3);  /* 4096 nrets values */

	printf("top before: %ld\n", (long) duk_get_top(ctx));

	rc = duk_safe_call(ctx, dummy_func, NULL, 3 /*nargs*/, 4096 /*nrets*/);
	printf("duk_safe_call() rc: %ld\n", (long) rc);

	printf("final top: %ld\n", (long) duk_get_top(ctx));
	return 0;
}

static duk_ret_t test_2(duk_context *ctx) {
	duk_int_t rc;

	/* Some ignored values. */
	duk_push_null(ctx);
	duk_push_null(ctx);
	duk_push_null(ctx);
	duk_push_null(ctx);
	duk_push_null(ctx);

	duk_push_string(ctx, "foo");
	duk_push_string(ctx, "bar");
	duk_push_string(ctx, "quux");

	duk_require_stack(ctx, 4096 - 3);  /* 4096 nrets values */

	printf("top before: %ld\n", (long) duk_get_top(ctx));

	/* This safe call tries to use 'nrets' too large for the current
	 * value stack reserve.  The reserve check is not exact and doesn't
	 * differentiate internal and user reserve (managing the user reserve
	 * is always the responsibility of calling code).
	 *
	 * The call fails with a throw (at least currently) rather than an
	 * error return value and a value at stack top; it may not always be
	 * possible to push an error object if there's no reserve at all.
	 *
	 * Internal reserve in Duktape 2.2: 32 entries, public reserve on
	 * Duktape/C function entry (and empty call stack) is 64 entries.
	 */
	rc = duk_safe_call(ctx, dummy_func, NULL, 3 /*nargs*/, 4096 + 32 + 8 /*nrets*/);
	printf("duk_safe_call() rc: %ld\n", (long) rc);

	printf("final top: %ld\n", (long) duk_get_top(ctx));
	return 0;
}

void test(duk_context *ctx) {
	/* Use duk_pcall() so that value stack reserve is not extended
	 * for the top level activation.
	 */
	TEST_PCALL(test_1);
	TEST_PCALL(test_2);
}


text:
using System;

namespace Wox.Plugin.Program.ProgramSources
{
    [Serializable]
    [global::System.ComponentModel.Browsable(false)]
    public class UserStartMenuProgramSource : FileSystemProgramSource
    {
        public UserStartMenuProgramSource()
            : base(Environment.GetFolderPath(Environment.SpecialFolder.Programs))
        {
        }

        public UserStartMenuProgramSource(ProgramSource source)
            : this()
        {
            this.BonusPoints = source.BonusPoints;
        }

        public override string ToString()
        {
            return typeof(UserStartMenuProgramSource).Name;
        }
    }
}


text:
<!---
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-->
# Apache Hadoop Changelog

## Release 1.1.3 - Unreleased (as of 2016-03-04)

### INCOMPATIBLE CHANGES:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |

### IMPORTANT ISSUES:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |

### NEW FEATURES:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |

### IMPROVEMENTS:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |

### BUG FIXES:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |
| [HDFS-5028](https://issues.apache.org/jira/browse/HDFS-5028) | LeaseRenewer throw java.util.ConcurrentModificationException when timeout |  Major | . | zhaoyunjiong | zhaoyunjiong |

### TESTS:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |

### SUB-TASKS:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |

### OTHER:

| JIRA | Summary | Priority | Component | Reporter | Contributor |
|:---- |:---- | :--- |:---- |:---- |:---- |


text:
/* SiteDir.java */
package org.xlattice.httpd;

import java.io.File;
import java.io.IOException;

/**
 * @author Jim Dixon
 */

import org.xlattice.util.ArrayStack;

public class SiteDir                        implements RndDir {

    public  final String name;
    /** name including path and separator */
    public  final String dirName;
    private final ArrayStack subDirs;
    private final ArrayStack files;

    public SiteDir (String dirName)             throws Exception {
        if (dirName == null || dirName.equals(""))
            throw new IllegalArgumentException (
                    "null or empty directory name");
        name    = dirName;
        if (name.endsWith(File.separator))
            this.dirName = name;
        else
            this.dirName = new StringBuffer(name)
                                .append(File.separator)
                                .toString();
        subDirs = new ArrayStack();
        files   = new ArrayStack();
    }
    /**
     * Create the physical directory below the given base directory,
     * a path relative to the default directory and guaranteed to be
     * separator-terminated.
     */
    public boolean mkdir (String base)          throws Exception {
        if (base == null || base.equals(""))
            throw new IllegalArgumentException (
                    "null or empty base directory name");
        String s = new StringBuffer (base)
                    .append(dirName).toString();
        File dir = new File(s);
        if (dir.exists())
            dir.delete();
        return dir.mkdir();
    }
    // INTERFACE RndDir /////////////////////////////////////////////
    /** @return name of directory, including path and separator */
    public String dirName() {
        return dirName;
    }
    public SiteDir  addDir  (String s)      throws Exception {
        SiteDir dir = new SiteDir ( new StringBuffer(dirName)
                                    .append(s).toString() );
        subDirs.push(dir);
        return dir;
    }
    /**
     * Add a data file below this directory, prefixing a path.
     * @param s   name of the data file, excluding any path
     * @param ext extension excluding leading dot
     * @param b   contents of the file
     */
    public SiteFile addFile (String s, String ext, byte[] b)
                                            throws Exception {
        String name = new StringBuffer(dirName).append(s).toString();
        SiteFile file = new SiteFile (name, ext, b);
        files.push(file);
        return file;
    }
    public int dirCount () {
        return subDirs.size();
    }
    public int fileCount () {
        return files.size();
    }
}


text:
module Storytime
  module Concerns
    module StorytimeUser
      extend ActiveSupport::Concern

      module ClassMethods
        def storytime_user
          belongs_to :storytime_role, class_name: "Storytime::Role"

          has_many :storytime_posts, class_name: "Storytime::Post"
          has_many :storytime_pages, class_name: "Storytime::Page"
          has_many :storytime_media, class_name: "Storytime::Media"
          has_many :storytime_versions, class_name: "Storytime::Version"
          has_many :storytime_comments, class_name: "Storytime::Comment"

          class_eval <<-EOS
            def self.policy_class
              UserPolicy
            end

            def storytime_user?
              !storytime_role.nil?
            end
          EOS

          %w{admin editor writer}.each do |role_name|
            class_eval <<-EOS
              def storytime_#{role_name}?
                storytime_role && storytime_role.name == "#{role_name}"
              end
            EOS
          end
        end
      end

    end
  end
end

ActiveRecord::Base.send :include, Storytime::Concerns::StorytimeUser


text:
package io.grpc.netty;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.netty.buffer.Unpooled.EMPTY_BUFFER;

import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.internal.ClientStreamListener;
import io.grpc.internal.Http2ClientStream;
import io.grpc.internal.WritableBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.util.AsciiString;

import javax.annotation.Nullable;

/**
 * Client stream for a Netty transport.
 */
abstract class NettyClientStream extends Http2ClientStream {
  private final MethodDescriptor<?, ?> method;
  /** {@code null} after start. */
  private Metadata headers;
  private final Channel channel;
  private final NettyClientHandler handler;
  private AsciiString authority;
  private final AsciiString scheme;
  private Http2Stream http2Stream;
  private Integer id;
  private WriteQueue writeQueue;

  NettyClientStream(MethodDescriptor<?, ?> method, Metadata headers, Channel channel,
      NettyClientHandler handler, int maxMessageSize, AsciiString authority, AsciiString scheme) {
    super(new NettyWritableBufferAllocator(channel.alloc()), maxMessageSize);
    this.method = checkNotNull(method, "method");
    this.headers = checkNotNull(headers, "headers");
    this.writeQueue = handler.getWriteQueue();
    this.channel = checkNotNull(channel, "channel");
    this.handler = checkNotNull(handler, "handler");
    this.authority = checkNotNull(authority, "authority");
    this.scheme = checkNotNull(scheme, "scheme");
  }

  @Override
  public void setAuthority(String authority) {
    checkState(listener() == null, "must be call before start");
    this.authority = AsciiString.of(checkNotNull(authority, "authority"));
  }

  @Override
  public void start(ClientStreamListener listener) {
    super.start(listener);

    // Convert the headers into Netty HTTP/2 headers.
    AsciiString defaultPath = new AsciiString("/" + method.getFullMethodName());
    Http2Headers http2Headers
        = Utils.convertClientHeaders(headers, scheme, defaultPath, authority);
    headers = null;

    ChannelFutureListener failureListener = new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (!future.isSuccess()) {
          // Stream creation failed. Close the stream if not already closed.
          Status s = statusFromFailedFuture(future);
          transportReportStatus(s, true, new Metadata());
        }
      }
    };

    // Write the command requesting the creation of the stream.
    writeQueue.enqueue(new CreateStreamCommand(http2Headers, this),
        !method.getType().clientSendsOneMessage()).addListener(failureListener);
  }

  /**
   * Intended to be overriden by NettyClientTransport, which has more information about failures.
   * May only be called from event loop.
   */
  protected abstract Status statusFromFailedFuture(ChannelFuture f);

  @Override
  public void request(int numMessages) {
    if (channel.eventLoop().inEventLoop()) {
      // Processing data read in the event loop so can call into the deframer immediately
      requestMessagesFromDeframer(numMessages);
    } else {
      writeQueue.enqueue(new RequestMessagesCommand(this, numMessages), true);
    }
  }

  @Override
  public Integer id() {
    return id;
  }

  public void id(int id) {
    this.id = id;
  }

  /**
   * Sets the underlying Netty {@link Http2Stream} for this stream. This must be called in the
   * context of the transport thread.
   */
  public void setHttp2Stream(Http2Stream http2Stream) {
    checkNotNull(http2Stream, "http2Stream");
    checkState(this.http2Stream == null, "Can only set http2Stream once");
    this.http2Stream = http2Stream;

    // Now that the stream has actually been initialized, call the listener's onReady callback if
    // appropriate.
    onStreamAllocated();
  }

  /**
   * Gets the underlying Netty {@link Http2Stream} for this stream.
   */
  @Nullable
  public Http2Stream http2Stream() {
    return http2Stream;
  }

  void transportHeadersReceived(Http2Headers headers, boolean endOfStream) {
    if (endOfStream) {
      transportTrailersReceived(Utils.convertTrailers(headers));
    } else {
      transportHeadersReceived(Utils.convertHeaders(headers));
    }
  }

  void transportDataReceived(ByteBuf frame, boolean endOfStream) {
    transportDataReceived(new NettyReadableBuffer(frame.retain()), endOfStream);
  }

  @Override
  protected void sendCancel(Status reason) {
    // Send the cancel command to the handler.
    writeQueue.enqueue(new CancelClientStreamCommand(this, reason), true);
  }

  @Override
  protected void sendFrame(WritableBuffer frame, boolean endOfStream, boolean flush) {
    ByteBuf bytebuf = frame == null ? EMPTY_BUFFER : ((NettyWritableBuffer) frame).bytebuf();
    final int numBytes = bytebuf.readableBytes();
    if (numBytes > 0) {
      // Add the bytes to outbound flow control.
      onSendingBytes(numBytes);
      writeQueue.enqueue(
          new SendGrpcFrameCommand(this, bytebuf, endOfStream),
          channel.newPromise().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
              // Remove the bytes from outbound flow control, optionally notifying
              // the client that they can send more bytes.
              onSentBytes(numBytes);
            }
          }), flush);
    } else {
      // The frame is empty and will not impact outbound flow control. Just send it.
      writeQueue.enqueue(new SendGrpcFrameCommand(this, bytebuf, endOfStream), flush);
    }
  }

  @Override
  protected void returnProcessedBytes(int processedBytes) {
    handler.returnProcessedBytes(http2Stream, processedBytes);
    writeQueue.scheduleFlush();
  }
}


text:
    #set($i=0)
    #set($_565405093a6a4c781faecacf = $!data.ads['565405093a6a4c781faecacf'])
    #foreach($doc in $!_565405093a6a4c781faecacf.ads)

#end

    #set($_565405093a6a4c781faecacf = $!data.ads['565405093a6a4c781faecacf'])
    #foreach($doc in $!_565405093a6a4c781faecacf.ads)

#end

    Previous

    Next


text:
<?php declare(strict_types=1);

namespace WyriMaps\Tests\BattleNet\Resource\Sync\WorldOfWarcraft;

use ApiClients\Tools\ResourceTestUtilities\AbstractResourceTest;
use WyriMaps\BattleNet\ApiSettings;
use WyriMaps\BattleNet\Resource\WorldOfWarcraft\Realm;

class RealmTest extends AbstractResourceTest
{
    public function getSyncAsync(): string
    {
        return 'Sync';
    }

    public function getClass(): string
    {
        return Realm::class;
    }

    public function getNamespace(): string
    {
        return ApiSettings::NAMESPACE;
    }
}


text:
<?php

namespace Bitbucket\Tests\API\Repositories\Commits\Statuses;

use Bitbucket\Tests\API as Tests;
use Bitbucket\API;

class BuildStatusesTest extends Tests\TestCase
{
    public function testGet()
    {
        $endpoint = 'repositories/gentle/eof/commit/SHA1/statuses/build/KEY';
        $expectedResult = $this->fakeResponse(array('dummy'));

        $client = $this->getHttpClientMock();
        $client->expects($this->once())
            ->method('get')
            ->with($endpoint)
            ->will($this->returnValue($expectedResult));

        /** @var \Bitbucket\API\Repositories\Commits\BuildStatuses $buildStatus */
        $buildStatus = $this->getClassMock('Bitbucket\API\Repositories\Commits\BuildStatuses', $client);
        $actual = $buildStatus->get('gentle', 'eof', 'SHA1', 'KEY');

        $this->assertEquals($expectedResult, $actual);
    }

    public function testCreate()
    {
        $endpoint = 'repositories/gentle/eof/commit/SHA1/statuses/build';
        $params = json_encode(array(
            'state' => 'SUCCESSFUL'
        ));

        $client = $this->getHttpClientMock();
        $client->expects($this->once())
            ->method('post')
            ->with($endpoint);

        /** @var \Bitbucket\API\Repositories\Commits\BuildStatuses $buildStatus */
        $buildStatus = $this->getClassMock('Bitbucket\API\Repositories\Commits\BuildStatuses', $client);

        $buildStatus->create('gentle', 'eof', 'SHA1', $params);
    }

    public function testUpdate()
    {
        $endpoint = 'repositories/gentle/eof/commit/SHA1/statuses/build/KEY';
        $params = json_encode(array(
            'state' => 'SUCCESSFUL'
        ));

        $client = $this->getHttpClientMock();
        $client->expects($this->once())
            ->method('put')
            ->with($endpoint);

        /** @var \Bitbucket\API\Repositories\Commits\BuildStatuses $buildStatus */
        $buildStatus = $this->getClassMock('Bitbucket\API\Repositories\Commits\BuildStatuses', $client);

        $buildStatus->update('gentle', 'eof', 'SHA1', 'KEY', $params);
    }
}


text:
// Copyright (c) 2019, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "randomx.h"
#include "c_threads.h"
#include "hash-ops.h"
#include "misc_log_ex.h"

#define RX_LOGCAT	"randomx"

#if defined(_MSC_VER)
#define THREADV __declspec(thread)
#else
#define THREADV __thread
#endif

typedef struct rx_state {
  CTHR_MUTEX_TYPE rs_mutex;
  char rs_hash[32];
  uint64_t  rs_height;
  randomx_cache *rs_cache;
} rx_state;

static CTHR_MUTEX_TYPE rx_mutex = CTHR_MUTEX_INIT;
static CTHR_MUTEX_TYPE rx_dataset_mutex = CTHR_MUTEX_INIT;

static rx_state rx_s[2] = {{CTHR_MUTEX_INIT,{0},0,0},{CTHR_MUTEX_INIT,{0},0,0}};

static randomx_dataset *rx_dataset;
static uint64_t rx_dataset_height;
static THREADV randomx_vm *rx_vm = NULL;
static THREADV int rx_toggle;

static void local_abort(const char *msg)
{
  fprintf(stderr, "%s\n", msg);
#ifdef NDEBUG
  _exit(1);
#else
  abort();
#endif
}

/**
 * @brief uses cpuid to determine if the CPU supports the AES instructions
 * @return true if the CPU supports AES, false otherwise
 */

static inline int force_software_aes(void)
{
  static int use = -1;

  if (use != -1)
    return use;

  const char *env = getenv("MONERO_USE_SOFTWARE_AES");
  if (!env) {
    use = 0;
  }
  else if (!strcmp(env, "0") || !strcmp(env, "no")) {
    use = 0;
  }
  else {
    use = 1;
  }
  return use;
}

static void cpuid(int CPUInfo[4], int InfoType)
{
#if defined(__x86_64__)
    __asm __volatile__
    (
    "cpuid":
        "=a" (CPUInfo[0]),
        "=b" (CPUInfo[1]),
        "=c" (CPUInfo[2]),
        "=d" (CPUInfo[3]) :
            "a" (InfoType), "c" (0)
        );
#endif
}
static inline int check_aes_hw(void)
{
#if defined(__x86_64__)
    int cpuid_results[4];
    static int supported = -1;

    if(supported >= 0)
        return supported;

    cpuid(cpuid_results,1);
    return supported = cpuid_results[2] & (1 << 25);
#else
    return 0;
#endif
}

static volatile int use_rx_jit_flag = -1;

static inline int use_rx_jit(void)
{
#if defined(__x86_64__)

  if (use_rx_jit_flag != -1)
    return use_rx_jit_flag;

  const char *env = getenv("MONERO_USE_RX_JIT");
  if (!env) {
    use_rx_jit_flag = 1;
  }
  else if (!strcmp(env, "0") || !strcmp(env, "no")) {
    use_rx_jit_flag = 0;
  }
  else {
    use_rx_jit_flag = 1;
  }
  return use_rx_jit_flag;
#else
  return 0;
#endif
}

#define SEEDHASH_EPOCH_BLOCKS	2048	/* Must be same as BLOCKS_SYNCHRONIZING_MAX_COUNT in cryptonote_config.h */
#define SEEDHASH_EPOCH_LAG		64

void rx_reorg(const uint64_t split_height) {
  int i;
  CTHR_MUTEX_LOCK(rx_mutex);
  for (i=0; i<2; i++) {
    if (split_height < rx_s[i].rs_height)
      rx_s[i].rs_height = 1;	/* set to an invalid seed height */
  }
  CTHR_MUTEX_UNLOCK(rx_mutex);
}

uint64_t rx_seedheight(const uint64_t height) {
  uint64_t s_height =  (height <= SEEDHASH_EPOCH_BLOCKS+SEEDHASH_EPOCH_LAG) ? 0 :
                       (height - SEEDHASH_EPOCH_LAG - 1) & ~(SEEDHASH_EPOCH_BLOCKS-1);
  return s_height;
}

void rx_seedheights(const uint64_t height, uint64_t *seedheight, uint64_t *nextheight) {
  *seedheight = rx_seedheight(height);
  *nextheight = rx_seedheight(height + SEEDHASH_EPOCH_LAG);
}

typedef struct seedinfo {
  randomx_cache *si_cache;
  unsigned long si_start;
  unsigned long si_count;
} seedinfo;

static CTHR_THREAD_RTYPE rx_seedthread(void *arg) {
  seedinfo *si = arg;
  randomx_init_dataset(rx_dataset, si->si_cache, si->si_start, si->si_count);
  CTHR_THREAD_RETURN;
}

static void rx_initdata(randomx_cache *rs_cache, const int miners, const uint64_t seedheight) {
  if (miners > 1) {
    unsigned long delta = randomx_dataset_item_count() / miners;
    unsigned long start = 0;
    int i;
    seedinfo *si;
    CTHR_THREAD_TYPE *st;
    si = malloc(miners * sizeof(seedinfo));
    if (si == NULL)
      local_abort("Couldn't allocate RandomX mining threadinfo");
    st = malloc(miners * sizeof(CTHR_THREAD_TYPE));
    if (st == NULL) {
      free(si);
      local_abort("Couldn't allocate RandomX mining threadlist");
    }
    for (i=0; i<miners-1; i++) {
      si[i].si_cache = rs_cache;
      si[i].si_start = start;
      si[i].si_count = delta;
      start += delta;
    }
    si[i].si_cache = rs_cache;
    si[i].si_start = start;
    si[i].si_count = randomx_dataset_item_count() - start;
    for (i=1; i<miners; i++) {
      CTHR_THREAD_CREATE(st[i], rx_seedthread, &si[i]);
    }
    randomx_init_dataset(rx_dataset, rs_cache, 0, si[0].si_count);
    for (i=1; i<miners; i++) {
      CTHR_THREAD_JOIN(st[i]);
    }
    free(st);
    free(si);
  } else {
    randomx_init_dataset(rx_dataset, rs_cache, 0, randomx_dataset_item_count());
  }
  rx_dataset_height = seedheight;
}

void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const char *seedhash, const void *data, size_t length,
  char *hash, int miners, int is_alt) {
  uint64_t s_height = rx_seedheight(mainheight);
  int changed = 0;
  int toggle = is_alt ? s_height : seedheight;
  randomx_flags flags = RANDOMX_FLAG_DEFAULT;
  rx_state *rx_sp;
  randomx_cache *cache;

  toggle = (toggle & SEEDHASH_EPOCH_BLOCKS) != 0;
  CTHR_MUTEX_LOCK(rx_mutex);

  /* if alt block but with same seed as mainchain, no need for alt cache */
  if (is_alt && s_height == seedheight && !memcmp(rx_s[toggle].rs_hash, seedhash, sizeof(rx_s[toggle].rs_hash)))
    is_alt = 0;

  /* RPC could request an earlier block on mainchain */
  if (!is_alt && s_height > seedheight)
    is_alt = 1;

  toggle ^= (is_alt != 0);
  if (toggle != rx_toggle)
    changed = 1;
  rx_toggle = toggle;

  rx_sp = &rx_s[toggle];
  CTHR_MUTEX_LOCK(rx_sp->rs_mutex);
  CTHR_MUTEX_UNLOCK(rx_mutex);

  cache = rx_sp->rs_cache;
  if (cache == NULL) {
    if (use_rx_jit())
      flags |= RANDOMX_FLAG_JIT;
    if (cache == NULL) {
      cache = randomx_alloc_cache(flags | RANDOMX_FLAG_LARGE_PAGES);
      if (cache == NULL) {
        mdebug(RX_LOGCAT, "Couldn't use largePages for RandomX cache");
        cache = randomx_alloc_cache(flags);
      }
      if (cache == NULL)
        local_abort("Couldn't allocate RandomX cache");
    }
  }
  if (rx_sp->rs_height != seedheight || rx_sp->rs_cache == NULL || memcmp(seedhash, rx_sp->rs_hash, sizeof(rx_sp->rs_hash))) {
    randomx_init_cache(cache, seedhash, 32);
    rx_sp->rs_cache = cache;
    rx_sp->rs_height = seedheight;
    memcpy(rx_sp->rs_hash, seedhash, sizeof(rx_sp->rs_hash));
    changed = 1;
  }
  if (rx_vm == NULL) {
    randomx_flags flags = RANDOMX_FLAG_DEFAULT;
    if (use_rx_jit()) {
      flags |= RANDOMX_FLAG_JIT;
      if (!miners)
          flags |= RANDOMX_FLAG_SECURE;
    }
    if(!force_software_aes() && check_aes_hw())
      flags |= RANDOMX_FLAG_HARD_AES;
    if (miners) {
      CTHR_MUTEX_LOCK(rx_dataset_mutex);
      if (rx_dataset == NULL) {
        rx_dataset = randomx_alloc_dataset(RANDOMX_FLAG_LARGE_PAGES);
        if (rx_dataset == NULL) {
          mdebug(RX_LOGCAT, "Couldn't use largePages for RandomX dataset");
          rx_dataset = randomx_alloc_dataset(RANDOMX_FLAG_DEFAULT);
        }
        if (rx_dataset != NULL)
          rx_initdata(rx_sp->rs_cache, miners, seedheight);
      }
      if (rx_dataset != NULL)
        flags |= RANDOMX_FLAG_FULL_MEM;
      else {
        miners = 0;
        mwarning(RX_LOGCAT, "Couldn't allocate RandomX dataset for miner");
      }
      CTHR_MUTEX_UNLOCK(rx_dataset_mutex);
    }
    rx_vm = randomx_create_vm(flags | RANDOMX_FLAG_LARGE_PAGES, rx_sp->rs_cache, rx_dataset);
    if(rx_vm == NULL) { //large pages failed
      mdebug(RX_LOGCAT, "Couldn't use largePages for RandomX VM");
      rx_vm = randomx_create_vm(flags, rx_sp->rs_cache, rx_dataset);
    }
    if(rx_vm == NULL) {//fallback if everything fails
      flags = RANDOMX_FLAG_DEFAULT | (miners ? RANDOMX_FLAG_FULL_MEM : 0);
      rx_vm = randomx_create_vm(flags, rx_sp->rs_cache, rx_dataset);
    }
    if (rx_vm == NULL)
      local_abort("Couldn't allocate RandomX VM");
  } else if (miners) {
    CTHR_MUTEX_LOCK(rx_dataset_mutex);
    if (rx_dataset != NULL && rx_dataset_height != seedheight)
      rx_initdata(cache, miners, seedheight);
    CTHR_MUTEX_UNLOCK(rx_dataset_mutex);
  } else if (changed) {
    randomx_vm_set_cache(rx_vm, rx_sp->rs_cache);
  }
  /* mainchain users can run in parallel */
  if (!is_alt)
    CTHR_MUTEX_UNLOCK(rx_sp->rs_mutex);
  randomx_calculate_hash(rx_vm, data, length, hash);
  /* altchain slot users always get fully serialized */
  if (is_alt)
    CTHR_MUTEX_UNLOCK(rx_sp->rs_mutex);
}

void rx_slow_hash_allocate_state(void) {
}

void rx_slow_hash_free_state(void) {
  if (rx_vm != NULL) {
    randomx_destroy_vm(rx_vm);
    rx_vm = NULL;
  }
}

void rx_stop_mining(void) {
  CTHR_MUTEX_LOCK(rx_dataset_mutex);
  if (rx_dataset != NULL) {
    randomx_dataset *rd = rx_dataset;
    rx_dataset = NULL;
    randomx_release_dataset(rd);
  }
  CTHR_MUTEX_UNLOCK(rx_dataset_mutex);
}


text:
package gov.nasa.ensemble.core.activityDictionary.view.transfer;

import gov.nasa.ensemble.dictionary.EStateResourceDef;

import java.util.Collection;

public class StateResourceDefTransferable extends NamedDefTransferable<EStateResourceDef> {

	public StateResourceDefTransferable() {
		super(EStateResourceDef.class);
	}

	public StateResourceDefTransferable(Collection<EStateResourceDef> defs) {
		super(EStateResourceDef.class, defs);
	}

}


text:
import React from 'react'
import { sparqlConnect } from 'sparql-connect';
import NotFound from 'components/not-found'
import Spinner from 'components/shared/spinner'
import CodeList from 'components/code-list'
import { getRangeLabel } from 'utils/range'
import D, { getLang } from 'i18n'
/**
  * Builds the query that retrieves the details on a given mas.
  */
const queryBuilder = masId => `
  PREFIX sdmx-mm: <http://www.w3.org/ns/sdmx-mm#>
  PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
  PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
  PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
  SELECT ?masLabelFr ?masLabelEn ?range ?isPresentational ?codeListCS
  FROM <http://rdf.insee.fr/graphes/def/simsv2fr>
  FROM <http://rdf.insee.fr/graphes/codes>
  WHERE {
    ?mas rdfs:label ?masLabelFr ;
      rdfs:label ?masLabelEn ;
      sdmx-mm:metadataAttributeProperty ?map .
    FILTER(STRENDS(STR(?mas), '/${masId}'))
    FILTER(lang(?masLabelFr) = 'fr')
    FILTER(lang(?masLabelEn) = 'en')
    OPTIONAL {?mas sdmx-mm:isPresentational ?isPresentational }
    OPTIONAL {?map rdfs:range ?range }
    OPTIONAL {?range rdfs:seeAlso ?codeListCS .
      ?codeListCS rdf:type skos:ConceptScheme}
  }
  ORDER BY ?mas
`;

const connector = sparqlConnect(queryBuilder, {
  queryName: 'masDetails',
  params: ['masId'],
  singleResult: true
});

const MasDetails = ({ masLabelFr, masLabelEn, range, isPresentational, codeListCS })  =>
    (

          {getLang() === 'fr' ? masLabelFr : masLabelEn}

          {getLang() === 'en' &&
{`${D.labelFr} : ${masLabelFr}`}
}
          {getLang() === 'fr' &&
{`${D.labelEn} : ${masLabelEn}`}
}

{`${D.presentational} : ${isPresentational ? D.yes : D.no}`}

{`${D.range} : ${getRangeLabel(range, codeListCS)}`}

          {codeListCS && <CodeList codeList={range} />}

  );

export default connector(MasDetails, {
  error: ({ masId }) => <NotFound
    message={D.masIdNotFound(masId)} />,
  loading: () => <Spinner text={D.loadingMas}/>
});


text:
package ninja.egg82.bukkit.processors;

import java.io.Closeable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import org.bukkit.event.EventException;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.EventExecutor;
import org.bukkit.plugin.PluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ninja.egg82.bukkit.BasePlugin;
import ninja.egg82.bukkit.core.CoreEventHandler;
import ninja.egg82.concurrent.DynamicConcurrentSet;
import ninja.egg82.concurrent.IConcurrentSet;
import ninja.egg82.patterns.DoubleBuffer;
import ninja.egg82.patterns.ServiceLocator;
import ninja.egg82.patterns.tuples.pair.Pair;
import ninja.egg82.plugin.handlers.events.EventHandler;
import ninja.egg82.plugin.handlers.events.HighEventHandler;
import ninja.egg82.plugin.handlers.events.HighestEventHandler;
import ninja.egg82.plugin.handlers.events.IEventHandler;
import ninja.egg82.plugin.handlers.events.LowEventHandler;
import ninja.egg82.plugin.handlers.events.LowestEventHandler;
import ninja.egg82.plugin.handlers.events.MonitorEventHandler;
import ninja.egg82.utils.ReflectUtil;

public class EventProcessor implements Listener, Closeable {
    // vars
    private static final Logger logger = LoggerFactory.getLogger(EventProcessor.class);

    private CoreEventHandler highestEventHandler = new CoreEventHandler();
    private CoreEventHandler highEventHandler = new CoreEventHandler();
    private CoreEventHandler normalEventHandler = new CoreEventHandler();
    private CoreEventHandler lowEventHandler = new CoreEventHandler();
    private CoreEventHandler lowestEventHandler = new CoreEventHandler();
    private CoreEventHandler monitorEventHandler = new CoreEventHandler();

    private IConcurrentSet<String> events = new DynamicConcurrentSet<String>();
    private DoubleBuffer<Pair<Event, EventPriority>> lastEvents = new DoubleBuffer<Pair<Event, EventPriority>>();

    private BasePlugin plugin = ServiceLocator.getService(BasePlugin.class);
    private PluginManager manager = Bukkit.getServer().getPluginManager();

    // constructor
    @SuppressWarnings("deprecation")
    public EventProcessor() {
        Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
            public void run() {
                lastEvents.swapBuffers();
                lastEvents.getBackBuffer().clear();
            }
        }, 20L, 20L);
    }

    // public
    public boolean addHandler(Class<? extends Event> event, Class<? extends IEventHandler<? extends Event>> clazz) {
        if (event == null) {
            throw new IllegalArgumentException("event cannot be null.");
        }
        if (clazz == null) {
            throw new IllegalArgumentException("clazz cannot be null.");
        }

        registerEvent(event);

        if (ReflectUtil.doesExtend(EventHandler.class, clazz)) {
            return normalEventHandler.addEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(MonitorEventHandler.class, clazz)) {
            return monitorEventHandler.addEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(HighestEventHandler.class, clazz)) {
            return highestEventHandler.addEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(HighEventHandler.class, clazz)) {
            return highEventHandler.addEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(LowestEventHandler.class, clazz)) {
            return lowestEventHandler.addEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(LowEventHandler.class, clazz)) {
            return lowEventHandler.addEventHandler(event, clazz);
        }

        return false;
    }

    public boolean removeHandler(Class<? extends IEventHandler<? extends Event>> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("clazz cannot be null.");
        }

        if (ReflectUtil.doesExtend(EventHandler.class, clazz)) {
            return normalEventHandler.removeEventHandler(clazz);
        } else if (ReflectUtil.doesExtend(MonitorEventHandler.class, clazz)) {
            return monitorEventHandler.removeEventHandler(clazz);
        } else if (ReflectUtil.doesExtend(HighestEventHandler.class, clazz)) {
            return highestEventHandler.removeEventHandler(clazz);
        } else if (ReflectUtil.doesExtend(HighEventHandler.class, clazz)) {
            return highEventHandler.removeEventHandler(clazz);
        } else if (ReflectUtil.doesExtend(LowestEventHandler.class, clazz)) {
            return lowestEventHandler.removeEventHandler(clazz);
        } else if (ReflectUtil.doesExtend(LowEventHandler.class, clazz)) {
            return lowEventHandler.removeEventHandler(clazz);
        }

        return false;
    }

    public boolean removeHandler(Class<? extends Event> event, Class<? extends IEventHandler<? extends Event>> clazz) {
        if (event == null) {
            throw new IllegalArgumentException("event cannot be null.");
        }
        if (clazz == null) {
            throw new IllegalArgumentException("clazz cannot be null.");
        }

        if (ReflectUtil.doesExtend(EventHandler.class, clazz)) {
            return normalEventHandler.removeEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(MonitorEventHandler.class, clazz)) {
            return monitorEventHandler.removeEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(HighestEventHandler.class, clazz)) {
            return highestEventHandler.removeEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(HighEventHandler.class, clazz)) {
            return highEventHandler.removeEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(LowestEventHandler.class, clazz)) {
            return lowestEventHandler.removeEventHandler(event, clazz);
        } else if (ReflectUtil.doesExtend(LowEventHandler.class, clazz)) {
            return lowEventHandler.removeEventHandler(event, clazz);
        }

        return false;
    }

    public boolean hasHandler(Class<? extends Event> event) {
        if (event == null) {
            return false;
        }

        if (normalEventHandler.hasEventHandler(event)) {
            return true;
        } else if (monitorEventHandler.hasEventHandler(event)) {
            return true;
        } else if (highestEventHandler.hasEventHandler(event)) {
            return true;
        } else if (highEventHandler.hasEventHandler(event)) {
            return true;
        } else if (lowestEventHandler.hasEventHandler(event)) {
            return true;
        } else if (lowEventHandler.hasEventHandler(event)) {
            return true;
        }

        return false;
    }

    public void clear() {
        highestEventHandler.clear();
        highEventHandler.clear();
        normalEventHandler.clear();
        lowEventHandler.clear();
        lowestEventHandler.clear();
        monitorEventHandler.clear();
    }

    public void close() {
        clear();

        List<Class<Event>> events = ReflectUtil.getClasses(Event.class, "org.bukkit.event", true, false, false);
        for (Class<Event> e : events) {
            unregisterEvent(e);
        }
    }

    public void registerEvent(Class<? extends Event> e) {
        if (!events.add(e.getName())) {
            return;
        }

        manager.registerEvent(e, this, EventPriority.HIGHEST, highestEventExecutor, plugin, false);
        manager.registerEvent(e, this, EventPriority.HIGH, highEventExecutor, plugin, false);
        manager.registerEvent(e, this, EventPriority.NORMAL, normalEventExecutor, plugin, false);
        manager.registerEvent(e, this, EventPriority.LOW, lowEventExecutor, plugin, false);
        manager.registerEvent(e, this, EventPriority.LOWEST, lowestEventExecutor, plugin, false);
        manager.registerEvent(e, this, EventPriority.MONITOR, monitorEventExecutor, plugin, false);
    }

    public void unregisterEvent(Class<? extends Event> e) {
        if (!events.remove(e.getName())) {
            return;
        }

        Method m = ReflectUtil.getMethod("getHandlerList", e);

        if (m == null) {
            return;
        }

        HandlerList list = null;
        try {
            list = (HandlerList) m.invoke(null, new Object[0]);
        } catch (Exception ex) {
            logger.warn("Could not unregister event.", ex);
            return;
        }

        list.unregister(this);
    }

    public int addHandlersFromPackage(String packageName) {
        return addHandlersFromPackage(packageName, true);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public int addHandlersFromPackage(String packageName, boolean recursive) {
        if (packageName == null) {
            throw new IllegalArgumentException("packageName cannot be null.");
        }

        int numEvents = 0;

        List<Class<? extends IEventHandler>> enums = ReflectUtil.getClassesParameterized(IEventHandler.class, packageName, recursive, false, false);
        for (Class<? extends IEventHandler> c : enums) {
            Class<? extends Event> eventType = null;
            try {
                eventType = (Class<? extends Event>) ((ParameterizedType) c.getGenericSuperclass()).getActualTypeArguments()[0];
            } catch (Exception ex) {
                continue;
            }

            if (addHandler(eventType, (Class<IEventHandler<? extends Event>>) c)) {
                numEvents++;
            }
        }

        return numEvents;
    }

    // private
    private EventExecutor highestEventExecutor = new EventExecutor() {
        public void execute(Listener listener, Event event) throws EventException {
            onAnyEvent(EventPriority.HIGHEST, event, event.getClass());
        }
    };
    private EventExecutor highEventExecutor = new EventExecutor() {
        public void execute(Listener listener, Event event) throws EventException {
            onAnyEvent(EventPriority.HIGH, event, event.getClass());
        }
    };
    private EventExecutor normalEventExecutor = new EventExecutor() {
        public void execute(Listener listener, Event event) throws EventException {
            onAnyEvent(EventPriority.NORMAL, event, event.getClass());
        }
    };
    private EventExecutor lowEventExecutor = new EventExecutor() {
        public void execute(Listener listener, Event event) throws EventException {
            onAnyEvent(EventPriority.LOW, event, event.getClass());
        }
    };
    private EventExecutor lowestEventExecutor = new EventExecutor() {
        public void execute(Listener listener, Event event) throws EventException {
            onAnyEvent(EventPriority.LOWEST, event, event.getClass());
        }
    };
    private EventExecutor monitorEventExecutor = new EventExecutor() {
        public void execute(Listener listener, Event event) throws EventException {
            onAnyEvent(EventPriority.MONITOR, event, event.getClass());
        }
    };

    private <T extends Event> void onAnyEvent(EventPriority priority, T event, Class<? extends Event> clazz) {
        if (isDuplicate(event, priority)) {
            return;
        }

        if (priority == EventPriority.NORMAL) {
            normalEventHandler.onAnyEvent(event, clazz);
        } else if (priority == EventPriority.MONITOR) {
            monitorEventHandler.onAnyEvent(event, clazz);
        } else if (priority == EventPriority.HIGHEST) {
            highestEventHandler.onAnyEvent(event, clazz);
        } else if (priority == EventPriority.HIGH) {
            highEventHandler.onAnyEvent(event, clazz);
        } else if (priority == EventPriority.LOWEST) {
            lowestEventHandler.onAnyEvent(event, clazz);
        } else if (priority == EventPriority.LOW) {
            lowEventHandler.onAnyEvent(event, clazz);
        }
    }

    private boolean isDuplicate(Event event, EventPriority priority) {
        if (!lastEvents.getCurrentBuffer().add(new Pair<Event, EventPriority>(event, priority))) {
            return true;
        }
        return false;
    }
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tests.Formula
{
	using ISSE.SafetyChecking.Formula;

	public static class TestFormulaGenerator
	{
		public static Formula CreateBinaryFormula()
		{
			var ap1 = new AtomarPropositionFormula();
			var ap2 = new AtomarPropositionFormula();
			var bexp = new BinaryFormula(ap1, BinaryOperator.And, ap2);
			return bexp;
		}

		public static Formula CreateNestedOnceFormula()
		{
			var bexp = CreateBinaryFormula();
			var once = new UnaryFormula(bexp, UnaryOperator.Once);
			return once;
		}

		public static Formula CreateConnectedNestedOnceFormula()
		{
			var once1 = CreateNestedOnceFormula();
			var once2 = CreateNestedOnceFormula();
			var conOnce = new BinaryFormula(once1, BinaryOperator.Or, once2);
			return conOnce;
		}

		public static Formula CreateFinallyNestedFormula()
		{
			var once = CreateNestedOnceFormula();
			var fin = new UnaryFormula(once, UnaryOperator.Finally);
			return fin;
		}

		public static Formula CreateFinallyConnectedNestedFormula()
		{
			var conOnce = CreateConnectedNestedOnceFormula();
			var fin = new UnaryFormula(conOnce, UnaryOperator.Finally);
			return fin;
		}

		public static Formula CreateNestedTwice()
		{
			var once = CreateNestedOnceFormula();
			var twice = new UnaryFormula(once, UnaryOperator.Once);
			return twice;
		}
	}
}


text:
package org.sealoflove.zero.five;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.sealoflove.Task;
import org.sealoflove.zero.zero.Task003;

public class Task050_alt implements Task {

	int limit = 1000000;

	List<Integer> primes = Task003.getPrimeNumbers(limit);
	Set<Integer> primesSet = new HashSet<>(primes);

	List<Integer> sums = getPartialSums();

	private List<Integer> getPartialSums() {
//		System.out.println(primes);
		List<Integer> res = new ArrayList<>();
		int sum = 0;
		for (int i = 0; i < primes.size(); i++) {
			res.add(sum);
			sum += primes.get(i);
		}
		return res;
	}

	private int findLongestSum() {
		int maxDistance = 0;
		int maxPrime = 0;
//		System.out.println(sums);
//		System.out.println(primes);
		for (int i = 0; i < sums.size(); i++) {

			for (int j = i + 1; j < sums.size(); j++) {
				//cursor sum = sums.get(i) - sums.get(j)
				int sum = sums.get(j) - sums.get(i);
				if (sum > limit)
					break;
//				System.out.println(sum);
				if (primesSet.contains(sum)) {
					if (maxDistance < j - i) {
						maxDistance = j-i;
						maxPrime = sum;
					}
				}

			}
		}
		System.out.println(maxDistance);
		return maxPrime;
	}

	@Override
	public String getResult() {

		return String.format("%d", findLongestSum());
	}

}


text:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="theme.css">
<title>Typing Instructor </title>

 Welcome to Typing Instructor! This website will teach you how to type properly!

The home row keys are: a, s, d, f, (left hand) ;, l, k, j (right hand).


text:
{% extends 'radioportal/episodes/episode_list_base.html' %}{% load i18n hosts%}
{% comment %}
Copyright © 2012 Robert Weidlich. All Rights Reserved.

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

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

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

3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE LICENSOR "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
{% endcomment %}
{% block title %} · {{ object_list.0.show.name }} {% endblock %}
{% block breadcrumb %}{{ block.super }} » {% trans "Recent episodes" %}{% endblock %}

{% block head %}
{% if show %}
	<link href="{% host_url "show-feed" status="recent" show_name=show.slug on "feeds" %}" type="application/atom+xml" rel="alternate" title="ATOM Feed" />
{% else %}
	<link href="{% host_url "all-feed" status="recent" on "feeds" %}" type="application/atom+xml" rel="alternate" title="ATOM Feed" />
{% endif %}

{% endblock %}
{% block feed_footer %}
{% if show %}

{% trans "atom" %}

{% else %}

{% trans "atom" %}

{% endif %}

{% endblock %}
{% block collapsed_shows %}{% endblock %}
{% block collapsed_upcoming %}un{% endblock %}
{% block navi_upcoming %}
{% if future %}

{% for episode in future %}

			{{ episode.slug|upper }}

{% endfor %}

{% endif %}
{% endblock %}
{% block navi_shows %}{% endblock %}
{% block no_episodes %}

{% trans "There are no episodes upcoming currently" %}

{% endblock %}


text:
import { Types } from 'mongoose'
import { Item } from 'models'
import { formatItemsResponse } from 'utils'
import { statusTypes } from 'constants/itemConstants/statusTypes'

// todo: сделать верификацию если юзер фильтрует по статусам
export default (req, res) => {
  const { status, statuses, noStatus, ids } = req.body;
  let query = {
    status: status || statusTypes.types[1].id
  };

  if (ids) {
    query = {
      '_id': {
        $in: req.body.ids.map(item =>
          Types.ObjectId(item)
        )
      },
      ...query
    };
  }

  if (statuses) {
    query = {
      ...query,
      status: { $in: statuses },
    };
  }

  if (noStatus) {
    delete query.status;
  }

  Item.find(query)
    .then(data => {
      res.status(200).json(formatItemsResponse(data, undefined, req.body))
    })
    .catch(err => {
      res.status(500).json({
        message: err.toString()
      })
    })
};


text:
package org.numixproject.blush;

/**
 * A color transformation.
 *NOTE: The Implementation of Transform should have a public constructor with no parameters.
 */
public interface Transform<T> {
    /**
     * Transforms Color
     * @param color Input Color
     * @return Transformed Color
     */
    public Color transform(Color color, T value);
}


text:
package MySQLProtocol

type Packet_COM_TIME struct {
	Packet
}

func (packet Packet_COM_TIME) GetPacketSize(context Context) (size uint64) {
	size += 1
	return size
}

func (packet Packet_COM_TIME) ToPacket(context Context) (data []byte) {
	size := packet.GetPacketSize(context)

	data = make([]byte, 0, size+4)
	data = append(data, BuildFixedLengthInteger3(uint32(size))...)
	data = append(data, BuildFixedLengthInteger1(packet.sequence_id)...)
	data = append(data, COM_TIME)

	return data
}

func (packet *Packet_COM_TIME) FromPacket(context Context, data Proto) {
	data.GetFixedLengthInteger3()
	packet.sequence_id = data.GetFixedLengthInteger1()
	data.GetFixedLengthInteger1()
}


text:
@interface LoLStaticMasteryTreeList : LoLBaseDTO

@property (nonatomic, strong) NSArray *masteryTreeItems; // List[MasteryTreeItemDto]

@end


text:
Not a registered file.

	<col cond="$allow_multiple" style="width:25px" />
	<col style="width:250px" />
	<col />
	<col cond="!$allow_multiple" style="width:50px; white-space:nowrap" />

 $key, $val">

					<object height="100" width="100" flashvars="" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" xmlns="http://www.w3.org/1999/xhtml">
						<param value="{getUrl('')}{$val->filename}" name="movie" xmlns="http://www.w3.org/1999/xhtml" />
						<param value="transparent" name="wmode" xmlns="http://www.w3.org/1999/xhtml" />
						<param value="sameDomain" name="allowScriptAccess" xmlns="http://www.w3.org/1999/xhtml" />
						<param value="high" name="quality" xmlns="http://www.w3.org/1999/xhtml" />
						<embed height="100" width="100" wmode="transparent" flashvars="" autostart="false" src="{getUrl('')}{$val->filename}" xmlns="http://www.w3.org/1999/xhtml" />
					</object>

					filename}" class="filebox_item" />

attributes => $name, $value">
					{htmlspecialchars($name, ENT_COMPAT | ENT_HTML401, 'UTF-8', false)} : {$value}

				<button type="button" class="x_btn select" style="white-space:nowrap">{$lang->cmd_select}</button>

		<button class="x_btn select">{$lang->cmd_select}</button>

	<input type="hidden" name="module" value="{$module}" />
	<input type="hidden" name="act" value="{$act}" />

« {$lang->first_page}

		<block cond="$page_navigation->first_page != 1 && $page_navigation->first_page + $page_navigation->page_count > $page_navigation->last_page - 1 && $page_navigation->page_count != $page_navigation->total_page">
			{@$isGoTo = true}

				cmd_go_to_page}">…

					<input type="number" min="1" max="{$page_navigation->last_page}" required name="page" title="{$lang->cmd_go_to_page}" />
					<button type="submit" class="x_add-on">Go</button>

		</block>

			{@$last_page = $page_no}

{$page_no}

		<block cond="$last_page != $page_navigation->last_page && $last_page + 1 != $page_navigation->last_page">
			{@$isGoTo = true}

				cmd_go_to_page}">…

					<input type="number" min="1" max="{$page_navigation->last_page}" required name="page" title="{$lang->cmd_go_to_page}" />
					<button type="submit" class="x_add-on">Go</button>

		</block>

last_page">last_page}" title="{$page_navigation->last_page}">{$lang->last_page} »


text:
namespace GitMind.Utils.Git.Private.CredentialsHandling
{
	internal interface ICredentialService
	{
		bool TryGetCredential(string url, string username, out IGitCredential gitCredential);

		bool TryGetPassword(string username, out IGitCredential gitCredential);

		bool TryGetPassphrase(string username, out IGitCredential gitCredential);

		void SetDialogConfirm(IGitCredential dialog, bool isConfirmed);
	}
}


text:
title: "{}"
layout: "function"
isPage: "true"
link: "/warpscript/functions"
desc: "Push an empty MAP on top of the stack"
categoryTree: ["reference","functions"]
oldPath: ["30-functions","20-lists-and-maps","02-function_EMPTYMAP.html.md"]
category: "reference"
---

The `{}` function creates an empty MAP on the top of the stack.

## Example ##

WarpScript commands:

    {}

Stack:

    TOP: {}

{% raw %}
<warp10-warpscript-widget backend="{{backend}}"  exec-endpoint="{{execEndpoint}}">{}
</warp10-warpscript-widget>
{% endraw %}

## Unit test ##

{% raw %}
<warp10-warpscript-widget backend="{{backend}}"  exec-endpoint="{{execEndpoint}}">{}
MAP->
0 == ASSERT
'unit test successful'
</warp10-warpscript-widget>
{% endraw %}


text:
GreenUp WebClient  - v0.01
=========
Powered by XenonApps

GreenUp Repository for Client and Administration
------------------------------------------------------------------------

A mobile-web client for GreenUp-VT

 - Tabbed menus
 - Interactive Maps
 - Discussion forum

###Dev Notes

#####Use of the proxy script:

For development: In order to bypass the browser's origin-based security measures, it is necessary to run a php script locally that proxies
all HTTP requests to the live web-server.

Using the proxy is simple.
Instead of making requests to http://199.195.248.180:31337/api,
I make a request to http://localhost/proxy.php?url=http://199.195.248.180:31337/api.

Whereas the live server would return: `{ "heartbeat": 1389547522 }`

the proxied response looks like: `{ "status":  "http_code": 200 }, "contents": { "heartbeat": 138954752 } }`

Note:  There will be a line in the ApiConnectors that identifies the origin and switches the proxy script in and out accordingly.

####Problems with SSL and Google OAuth:

 The Admin dashboard uses Google Analytics data to feed some of the usage graphs, so when a user enters the admin dash he is prompted to login
 with google credentials. The dash uses these credentials to authenticate into google analytics, all over HTTPS. If you log in as you... you won't see analytics data,
 as the site will be looking for an anlytics profile for YOUR account.
 I am working on fixing this, but until I do, you have to log in as xenonapplab@gmai.com

 Furthermore, you have to connect to your localhost using https://127.0.0.1 meaning you'll have to configure Apache to listen for ssl traffic,
 and generate a certificate.

 Mac users, see this tutorial

License
--

GPLv


text:
package com.asakusafw.lang.compiler.extension.iterative.mock;

import com.asakusafw.lang.compiler.api.testing.MockExporterDescription;
import com.asakusafw.vocabulary.external.ExporterDescription;

/**
 * Mock {@link ExporterDescription}.
 */
public class MockOutput extends MockExporterDescription.Basic {

    /**
     * Creates a new instance.
     */
    public MockOutput() {
        super(String.class);
    }
}


text:
package com.sequenceiq.authorization.service;

import java.util.Collection;
import java.util.Optional;

import javax.inject.Inject;

import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.base.Joiner;
import com.sequenceiq.authorization.annotation.CheckPermissionByResourceCrnList;
import com.sequenceiq.authorization.annotation.ResourceCrnList;
import com.sequenceiq.authorization.resource.AuthorizationResourceAction;
import com.sequenceiq.authorization.service.model.AuthorizationRule;
import com.sequenceiq.authorization.utils.CrnAccountValidator;

@Component
public class ResourceCrnListAuthorizationFactory extends TypedAuthorizationFactory<CheckPermissionByResourceCrnList> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceCrnListAuthorizationFactory.class);

    @Inject
    private CommonPermissionCheckingUtils commonPermissionCheckingUtils;

    @Inject
    private DefaultResourceAuthorizationProvider defaultResourceAuthorizationProvider;

    @Inject
    private EnvironmentBasedAuthorizationProvider environmentBasedAuthorizationProvider;

    @Inject
    private CrnAccountValidator crnAccountValidator;

    @Override
    public Optional<AuthorizationRule> doGetAuthorization(CheckPermissionByResourceCrnList methodAnnotation, String userCrn,
            ProceedingJoinPoint proceedingJoinPoint, MethodSignature methodSignature) {
        AuthorizationResourceAction action = methodAnnotation.action();
        Collection<String> resourceCrns = commonPermissionCheckingUtils
                .getParameter(proceedingJoinPoint, methodSignature, ResourceCrnList.class, Collection.class);
        crnAccountValidator.validateSameAccount(userCrn, resourceCrns);
        LOGGER.debug("Getting authorization rule to authorize user [{}] for action [{}] over resources [{}]", userCrn, action,
                Joiner.on(",").join(resourceCrns));
        return calcAuthorization(resourceCrns, action);
    }

    public Optional<AuthorizationRule> calcAuthorization(Collection<String> resourceCrns, AuthorizationResourceAction action) {
        if (CollectionUtils.isEmpty(resourceCrns)) {
            return Optional.empty();
        }
        return defaultResourceAuthorizationProvider.authorizeDefaultOrElseCompute(resourceCrns, action,
                filteredResourceCrns -> environmentBasedAuthorizationProvider.getAuthorizations(filteredResourceCrns, action));
    }

    @Override
    public Class<CheckPermissionByResourceCrnList> supportedAnnotation() {
        return CheckPermissionByResourceCrnList.class;
    }
}


text:
'use strict';

var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
var setupTestHooks = blueprintHelpers.setupTestHooks;
var emberNew = blueprintHelpers.emberNew;
var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;
var modifyPackages = blueprintHelpers.modifyPackages;
var setupPodConfig = blueprintHelpers.setupPodConfig;

var chai = require('ember-cli-blueprint-test-helpers/chai');
var expect = chai.expect;

describe('Acceptance: ember generate and destroy util', function() {
  setupTestHooks(this);

  it('util foo-bar', function() {
    var args = ['util', 'foo-bar'];

    return emberNew()
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('app/utils/foo-bar.js'))
          .to.contain('export default function fooBar() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import fooBar from 'my-app/utils/foo-bar';");
      }));
  });

  it('util foo-bar/baz', function() {
    var args = ['util', 'foo/bar-baz'];

    return emberNew()
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('app/utils/foo/bar-baz.js'))
          .to.contain('export default function fooBarBaz() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('tests/unit/utils/foo/bar-baz-test.js'))
          .to.contain("import fooBarBaz from 'my-app/utils/foo/bar-baz';");
      }));
  });

  it('in-addon util foo-bar', function() {
    var args = ['util', 'foo-bar'];

    return emberNew({ target: 'addon' })
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('addon/utils/foo-bar.js'))
          .to.contain('export default function fooBar() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('app/utils/foo-bar.js'))
          .to.contain("export { default } from 'my-addon/utils/foo-bar';");

        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import fooBar from 'dummy/utils/foo-bar';");
      }));
  });

  it('in-addon util foo-bar/baz', function() {
    var args = ['util', 'foo/bar-baz'];

    return emberNew({ target: 'addon' })
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('addon/utils/foo/bar-baz.js'))
          .to.contain('export default function fooBarBaz() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('app/utils/foo/bar-baz.js'))
          .to.contain("export { default } from 'my-addon/utils/foo/bar-baz';");

        expect(_file('tests/unit/utils/foo/bar-baz-test.js'))
          .to.contain("import fooBarBaz from 'dummy/utils/foo/bar-baz';");
      }));
  });

  it('util foo-bar --pod', function() {
    var args = ['util', 'foo-bar', '--pod'];

    return emberNew()
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('app/utils/foo-bar.js'))
          .to.contain('export default function fooBar() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import fooBar from 'my-app/utils/foo-bar';");
      }));
  });

  it('util foo-bar --pod podModulePrefix', function() {
    var args = ['util', 'foo-bar', '--pod'];

    return emberNew()
      .then(() => setupPodConfig({ podModulePrefix: true }))
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('app/utils/foo-bar.js'))
          .to.contain('export default function fooBar() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import fooBar from 'my-app/utils/foo-bar';");
      }));
  });

  it('util foo-bar/baz --pod', function() {
    var args = ['util', 'foo/bar-baz', '--pod'];

    return emberNew()
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('app/utils/foo/bar-baz.js'))
          .to.contain('export default function fooBarBaz() {\n' +
                      '  return true;\n' +
                      '}');

        expect(_file('tests/unit/utils/foo/bar-baz-test.js'))
          .to.contain("import fooBarBaz from 'my-app/utils/foo/bar-baz';");
      }));
  });

  it('util-test foo-bar', function() {
    var args = ['util-test', 'foo-bar'];

    return emberNew()
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import fooBar from 'my-app/utils/foo-bar';");
      }));
  });

  it('in-addon util-test foo-bar', function() {
    var args = ['util-test', 'foo-bar'];

    return emberNew({ target: 'addon' })
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import fooBar from 'dummy/utils/foo-bar';");
      }));
  });

  it('util-test foo-bar for mocha', function() {
    var args = ['util-test', 'foo-bar'];

    return emberNew()
      .then(() => modifyPackages([
        { name: 'ember-cli-qunit', delete: true },
        { name: 'ember-cli-mocha', dev: true }
      ]))
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('tests/unit/utils/foo-bar-test.js'))
          .to.contain("import { describe, it } from 'mocha';")
          .to.contain("import fooBar from 'my-app/utils/foo-bar';")
          .to.contain("describe('Unit | Utility | foo bar', function() {");
      }));
  });
});


text:
package com.sequenceiq.cloudbreak.reactor.api.event.stack.loadbalancer;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent;

public class UpdateServiceConfigRequest extends StackEvent {

    @JsonCreator
    public UpdateServiceConfigRequest(
            @JsonProperty("resourceId") Long stackId) {
        super(stackId);
    }
}