text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.us.Common;

namespace OpenADK.Library.us.Food{

/// <summary>Reimbursing agency</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 1.5r1</para>
/// </remarks>
[Serializable]
public class Agency : SifKeyedElement
{
	/// <summary>
	/// Creates an instance of an Agency
	/// </summary>
	public Agency() : base ( FoodDTD.AGENCY ){}

	/// <summary>
	/// Constructor that accepts values for all mandatory fields
	/// </summary>
	///<param name="type">Type of the reimbursing agency. Values: Federal, State, Local, Other</param>
	///<param name="name">The name of the reimbursing agency. This element is to be used when the Type is set as Other.</param>
	///<param name="rates">A Rates</param>
	///
	public Agency( AgencyTypeCode type, string name, Rates rates ) : base( FoodDTD.AGENCY )
	{
		this.SetType( type );
		this.Name = name;
		this.Rates = rates;
	}

	/// <summary>
	/// Constructor used by the .Net Serialization formatter
	/// </summary>
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected Agency( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	/// <summary>
	/// Gets the metadata fields that make up the key of this object
	/// </summary>
	/// <value>
	/// an array of metadata fields that make up the object's key
	/// </value>
	public override IElementDef[] KeyFields {
		get { return new IElementDef[] { FoodDTD.AGENCY_TYPE }; }
	}

	/// <summary>
	/// Gets or sets the value of the <c>Type</c> attribute.
	/// </summary>
	/// <value> The <c>Type</c> attribute of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "Type of the reimbursing agency. Values: Federal, State, Local, Other"</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public string Type
	{
		get
		{
			return GetFieldValue( FoodDTD.AGENCY_TYPE );
		}
		set
		{
			SetField( FoodDTD.AGENCY_TYPE, value );
		}
	}

	/// <summary>
	/// Sets the value of the <c>Type</c> attribute.
	/// </summary>
	/// <param name="val">A AgencyTypeCode object</param>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "Type of the reimbursing agency. Values: Federal, State, Local, Other"</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public void SetType( AgencyTypeCode val )
	{
		SetField( FoodDTD.AGENCY_TYPE, val );
	}

	/// <summary>
	/// Gets or sets the value of the <c>Name</c> attribute.
	/// </summary>
	/// <value> The <c>Name</c> attribute of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "The name of the reimbursing agency. This element is to be used when the Type is set as Other."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public string Name
	{
		get
		{
			return (string) GetSifSimpleFieldValue( FoodDTD.AGENCY_NAME ) ;
		}
		set
		{
			SetFieldValue( FoodDTD.AGENCY_NAME, new SifString( value ), value );
		}
	}

	/// <summary>
	/// Gets or sets the value of the <c><Rates></c> element.
	/// </summary>
	/// <value> A Rates </value>
	/// <remarks>
	/// <para>To remove the <c>Rates</c>, set <c>Rates</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public Rates Rates
	{
		get
		{
			return (Rates)GetChild( FoodDTD.AGENCY_RATES);
		}
		set
		{
			RemoveChild( FoodDTD.AGENCY_RATES);
			if( value != null)
			{
				AddChild( FoodDTD.AGENCY_RATES, value );
			}
		}
	}

}}


text:
layout: page
title: Lee Scholar Research Dinner
date: 2016-05-24
author: Michael Hart
tags: weekly links, java
status: published
summary: Etiam vestibulum neque id sollicitudin pulvinar. Phasellus pretium.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/16/2016
  endDate: 10/19/2016
  ctyhocn: DALPPHX
  groupCode: LSRD
published: true
---
Ut ut neque ex. Fusce gravida placerat ipsum, quis consectetur eros venenatis a. Donec sit amet ante at sapien interdum tempus fermentum eu turpis. Cras mattis aliquam lacus, sit amet sagittis arcu. Vivamus ligula orci, porta eget sapien nec, consequat eleifend libero. Aenean vestibulum est vitae metus posuere, sed iaculis purus sollicitudin. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras eu augue finibus, vestibulum neque in, venenatis ante. Praesent fringilla placerat ex ut lacinia. Curabitur sollicitudin blandit turpis, nec tempus ligula maximus vel. Duis consectetur id lacus nec condimentum. Suspendisse fermentum neque enim. In imperdiet lectus nec tortor feugiat, eu tincidunt ligula imperdiet. Donec suscipit in nulla ac dictum. Sed ut felis libero.

* Morbi nec tellus vel orci pretium pharetra
* Donec cursus dolor at leo semper, sit amet vulputate ligula convallis
* Nunc pharetra ante eu erat sollicitudin maximus
* Pellentesque fringilla augue nec magna condimentum, eget varius nisl semper
* Donec suscipit justo hendrerit, tempus leo ac, eleifend nisl
* Maecenas eu nulla porttitor, aliquet ante at, sollicitudin lectus.

Nullam malesuada purus eu laoreet faucibus. Nullam ultrices faucibus felis nec vehicula. Curabitur tincidunt sollicitudin pretium. Sed vitae egestas risus, eu dapibus lectus. Suspendisse sit amet erat orci. Ut efficitur, diam eu pharetra vehicula, lorem ligula gravida dolor, in maximus ante metus eget ligula. Ut tincidunt ullamcorper magna ut mollis. Nullam feugiat vestibulum nulla, nec commodo tellus mattis quis. Pellentesque tincidunt blandit dui, ac eleifend nulla varius nec. Aliquam vestibulum tincidunt lacus eu varius. Proin velit ex, lobortis quis dolor at, pulvinar tincidunt eros. Vivamus sed metus nunc. Praesent ac justo quis quam vulputate luctus.

redpajama_set_name: RedPajamaGithub


text:
#include <types/Void.h>
#include "FunctionType.h"

std::string wasm_module::FunctionType::toString() const {
    std::string result;
    result += "((result";
    if (returnType() != Void::instance()) {
        result += returnType()->name();
    }
    result += ") ";

    for (const Type* type : parameters()) {
        result += "(param ";
        result += type->name();
        result += ") ";
    }
    result.resize(result.size() - 1);
    result += ")";
    return result;
}

wasm_module::FunctionType::FunctionType() {
    returnType_ = Void::instance();
}


text:
---
layout:     post
title:      "Java 8 CompletableFuture 详解"
date:       2017-07-30 14:10:00
author:     "Daniel"
header-img: "img/post-bg-java.jpg"
tags:
    - Java
    - CompletableFuture

---

Java 8引入了`CompletableFuture<T>`以及它的接口`CompletionStage<T>`作为对`Future<T>`的增强,它可以让你使用回调驱动的方式表达不同任务的信息流。`CompletableFuture`用来定义单个任务事件的计算。本文主要介绍其用法以及常见的工具方法。

###	`CompletableFuture<T>` API
1、 **异步操作**
1. `CompletableFuture.runAsync(() -> runnable.run())`,返回`CompletableFuture<Void>`;
2.  `CompletableFuture.supplyAsync(() -> supplier.get())`,返回`CompletableFuture<T>`

2、 **链式异步操作**
1. `cf.thenRun(() -> runnable.run())`,返回`CompletableFuture<Void>`;
2. `cf.thenAccept(t -> consumer.accept(t))`,返回`CompletableFuture<Void>`;
3. `cf.thenApply(t -> function.apply(t))`,返回`CompletableFuture<R>`

3、 **异步 vs. 同步**

|同步|异步|描述|
|:--|:--|:--|
|`allOf`|N/A|所有的`CompletableFuture`都执行完后执行计算|
|`anyOf`|N/A|当任意一个`CompletableFuture`执行完后就会执行计算|
|`completedFuture`|N/A|返回一个已经计算好的`CompletableFuture`|
|`exceptionally`|N/A|当原始的`CompletableFuture`抛出异常的时候,就会触发这个`CompletableFuture`的计算,调用fn计算值|
|`handle`|`handleAsync`|生成新的计算结果,有`whenComplete`和转换的两个功能|
|`runAfterBoth`|`runAfterBothAsync`|两个`CompletionStage`都完成计算之后,再执行一个`Runnable`,`Runnable`不使用这个计算结果。|
|`runAfterEither`|`runAfterEitherAsync`|等待第一个完成任务`CompletableFuture`|
|`acceptEither`|`acceptEitherAsync`|当任意一个`CompletionStage`完成的时候,消费者action就会被执行|
|`applyToEither`|`applyToEitherAsync`|当任意一个`CompletionStage`完成的时候,fn会被执行,返回值作为新的`CompletableFuture<U>`的计算结果|
|N/A|`runAsync`|以`Runnable`函数式接口类型为参数|
|N/A|`supplyAsync`|以`Supplier<U>`函数式接口类型为参数|
|`thenApply`|`thenApplyAsync`|生成新的计算结果,`CompletableFuture<T>`转换成`CompletableFuture<U>`|
|`thenRun`|`thenRunAsync`|纯消费,执行Action,不使用`CompletableFuture`计算的结果|
|`thenAccept`|`thenAcceptAsync`|纯消费,执行Action,不返回新的计算值,用于添加回调|
|`thenAcceptBoth`|`thenAcceptBothAsync`|组合另外一个异步的结果|
|`thenCombine`|`thenCombineAsync`|复合另外一个`CompletionStage`的结果|
|`thenCompose`|`thenComposeAsync`|新`CompletableFuture`组合原来的`CompletableFuture`和函数返回的`CompletableFuture`|
|`whenComplete`|`whenCompleteAsync`|计算结果完成时的处理|

- thenApply:等待并转化future
- thenAccept、thenRun:监听future完成
- thenCompose:相当于flatMap,避免CompletableFuture<CompletableFuture<String>>
- thenCombine:组合两个future,有返回值
- thenAcceptBoth:组合两个future,没有返回值
- applyToEither:取2个future中最先返回的,有返回值
- acceptEither:取2个future中最先返回的,无返回值

> `thenApply`与`handle`方法的区别:`handle`方法会处理正常计算值和异常,因此它可以屏蔽异常,避免异常继续抛出;`thenApply`方法只是用来处理正常值,因此一旦有异常就会抛出。

> `anyOf`返回值的计算结果是其中一个CompletableFuture的计算结果,`applyToEither`返回值的计算结果要经过fn处理。

提示:下图图片较大,右击图片,在新标签页打开查看图片。
![img](/img/in-post/java8-example/completable_future.png)

从上图API的分类来看,方法的命名有2点规律:

1、**什么东西触发了stage**
- `then`开头的方法:当一个单独的stage完成时,添加另一个要触发的stage;
- 包含`both`的方法:当前面两个stage同时完成时,添加另一个要触发的stage;
- 包含`either`的方法:当前面两个stage有一个完成,添加另一个要触发的stage;

2、**计算是否传入参数和返回结果**
- 包含`apply`的方法:接收一个Function,该Function一个参数(前一个stage的结果)和返回一个结果(下一个stage的参数);
- 包含`accpet`的方法:接收一个Consumer,该Consumer接受一个参数,不返回结果;
- 包含`run`的方法:接收一个Runnable,该Runnable不需要参数和返回结果;

#### 创建已经完成的CompletableFuture
``` java
CompletableFuture<String> cf = CompletableFuture.completedFuture("message");
assertTrue(cf.isDone());
assertEquals("message", cf.getNow(null));
```

#### 运行异步的Stage
``` java
CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> {
            assertTrue(Thread.currentThread().isDaemon());
            randomSleep();
        });
```

#### 在前一个stage上施加函数
``` java
// 同步
CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApply(s -> {
            assertFalse(Thread.currentThread().isDaemon());
            return s.toUpperCase();
        });
assertEquals("MESSAGE", cf.getNow(null));
// 异步
CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(s -> {
            assertTrue(Thread.currentThread().isDaemon());
            randomSleep();
            return s.toUpperCase();
        });
assertNull(cf.getNow(null));
assertEquals("MESSAGE", cf.join());
```

#### 消费前一个Stage的结果
``` java
StringBuilder result = new StringBuilder();
// 同步
CompletableFuture.completedFuture("thenAccept message")
                .thenAccept(s -> result.append(s));
assertTrue("Result was empty", result.length() > 0);
// 异步
CompletableFuture<Void> cf = CompletableFuture.completedFuture("thenAcceptAsync message")
                .thenAcceptAsync(s -> result.append(s));
cf.join();
assertTrue("Result was empty", result.length() > 0);
```

#### 在两个完成的stage中取任意一个stage结果施加函数
``` java
String original = "Message";
CompletableFuture<String> cf1 = CompletableFuture.completedFuture(original)
        .thenApplyAsync(s -> delayedUpperCase(s));
CompletableFuture<String> cf2 = cf1.applyToEither(
        CompletableFuture.completedFuture(original).thenApplyAsync(s -> delayedLowerCase(s)),
        s -> s + " from applyToEither");
assertTrue(cf2.join().endsWith(" from applyToEither"));
```

#### 在两个完成的stage中任意一个stage结果消费
``` java
String original = "Message";
StringBuilder result = new StringBuilder();
CompletableFuture<Void> cf = CompletableFuture.completedFuture(original)
        .thenApplyAsync(s -> delayedUpperCase(s))
        .acceptEither(CompletableFuture.completedFuture(original).thenApplyAsync(s -> delayedLowerCase(s)),
                s -> result.append(s).append("acceptEither"));
cf.join();
assertTrue("Result was empty", result.toString().endsWith("acceptEither"));
```

#### 在两个stage都完成后执行Runnable
``` java
String original = "Message";
StringBuilder result = new StringBuilder();
CompletableFuture.completedFuture(original).thenApply(String::toUpperCase).runAfterBoth(
        CompletableFuture.completedFuture(original).thenApply(String::toLowerCase),
        () -> result.append("done"));
assertTrue("Result was empty", result.length() > 0);
```
#### 在BiConsumer中接受两个stage的结果
``` java
String original = "Message";
StringBuilder result = new StringBuilder();
CompletableFuture.completedFuture(original).thenApply(String::toUpperCase).thenAcceptBoth(
        CompletableFuture.completedFuture(original).thenApply(String::toLowerCase),
        (s1, s2) -> result.append(s1 + s2));
assertEquals("MESSAGEmessage", result.toString());
```
#### 两个stage的结果施加BiFunction
``` java
String original = "Message";
// 同步
CompletableFuture<String> cf = CompletableFuture.completedFuture(original).thenApply(s -> delayedUpperCase(s))
        .thenCombine(CompletableFuture.completedFuture(original).thenApply(s -> delayedLowerCase(s)),
                (s1, s2) -> s1 + s2);
assertEquals("MESSAGEmessage", cf.getNow(null));
// 异步
CompletableFuture<String> cf = CompletableFuture.completedFuture(original)
                .thenApplyAsync(s -> delayedUpperCase(s))
                .thenCombine(CompletableFuture.completedFuture(original).thenApplyAsync(s -> delayedLowerCase(s)),
                        (s1, s2) -> s1 + s2);
assertEquals("MESSAGEmessage", cf.join());
```

#### 组合CompletableFutures
``` java
String original = "Message";
CompletableFuture<String> cf = CompletableFuture.completedFuture(original).thenApply(s -> delayedUpperCase(s))
        .thenCompose(upper -> CompletableFuture.completedFuture(original).thenApply(s -> delayedLowerCase(s))
                .thenApply(s -> upper + s));
assertEquals("MESSAGEmessage", cf.join());
```

### 错误处理

1、 **处理异常返回默认值**
``` java
CompletableFuture<Integer> x = CompletableFuture.supplyAsync(() -> {
    if (failure) {
        throw new RuntimeException("Oops, something went wrong");
    }
    return 42;
});
// Note that tryX and x are of same type.
CompletableFuture<Integer> tryX = x.exceptionally(ex -> -1);
```

2、 **处理异常并转换**
``` java
CompletableFuture<Integer> x = CompletableFuture.supplyAsync(() -> {
    if (failure) {
        throw new RuntimeException("Oops, something went wrong");
    }
    return 42;
});

CompletableFuture<HttpResponse> tryX = x.handle((value, ex) -> { // Note that tryX and x are of different type.
    if (value != null) {
        return new HttpResponse(200, format("{\"value\": %s}", value));
    } else {
        return new HttpResponse(500, format("{\"error\": \"%s\"}", ex.getMessage()));
    }
});
```

3、 **处理异常并传递**
``` java
CompletableFuture<Integer> x = CompletableFuture.supplyAsync(() -> {
    if (failure) {
        throw new RuntimeException("Oops, something went wrong");
    }
    return 42;
});
// Note that tryX and x are of same type. This CompletableFuture acts as an invisible "decorator".
CompletableFuture<Integer> tryX = x.whenComplete((value, ex) -> {
    if (value != null) {
        System.out.println("Result: " + value);
    } else {
        System.out.println("Error code: -1. Root cause: " + ex.getMessage());
    }
});
```

### 链式使用
> result = (x + 1) + y

``` java
CompletableFuture<Integer> x1 = CompletableFuture.supplyAsync(() -> compute(1));
CompletableFuture<Integer> x2 = x1.thenApply(x -> add(x, 1));
CompletableFuture<Integer> y = CompletableFuture.supplyAsync(() -> compute(2));
CompletableFuture<Integer> r = x2.thenCombine(y, (i, j) -> add(i, j));
try { println("Result: " + r.get()); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); }
```
`(i, j) -> add(i, j)`将来自`y`和`x2`的`Integer`作为输入并进行转换得到最终结果。

### 优化超时
`CompletableFuture.get()`阻塞主线程直到`CompletableFuture`计算完成。一般应该给`get`指定超时时间,如`r.get(1, TimeUnit.SECONDS)`。

1、 **回调**
使用`thenAccept`并在返回结果可用时提供回调计算,如:
``` java
r.thenAccept(result -> System.out.println("The result is: " + result));
```

2、 **非阻塞方法确定超时**
使用`acceptEither`或者`applyToEither`。
``` java
r.acceptEither(timeoutAfter(1, TimeUnit.SECONDS),
               result -> System.out.println("The result is: " + result));

public <T> CompletableFuture<T> timeoutAfter(long timeout, TimeUnit unit) {
    CompletableFuture<T> promise = new CompletableFuture<T>();
    delayer.schedule(() -> promise.completeExceptionally(new TimeoutException()), timeout, unit);
    return promise;
}
```
`delayer`的类型为`ScheduledThreadPoolExecutor`。

3、 **Java 9改进**
Java 9引入了`orTimeout`和`completeOnTimeOut`解决超时问题。
``` java
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)
```

``` java
r.orTimeout(1, TimeUnit.SECONDS)
 .whenComplete((result, error) -> {
                if (error == null) {
                    System.out.println("The result is: " + result);
                } else {
                    System.out.println("Sorry, we could not return you a result");
                }
 });

```

### CompletableFuture::join
``` java
/**
  * Returns a new {@link CompletableFuture} which completes to a list of all values of its input
  * stages, if all succeed.  The list of results is in the same order as the input stages.
  *
  * If any of the given stages complete exceptionally, then the returned future also does so,
  * with a {@link CompletionException} holding this exception as its cause.
  */
public static <T> CompletableFuture<List<T>> allAsList(
      Collection<? extends CompletionStage<? extends T>> stages) {
  @SuppressWarnings("unchecked")
  final CompletableFuture<? extends T>[] all = new CompletableFuture[stages.size()];
  // traditional for-loops instead of streams here for performance reasons
  for (int i = 0; i < stages.size(); i++) {
    all[i] = stages.get(i).toCompletableFuture();
  }
  return CompletableFuture.allOf(all)
      .thenApply(ignored -> {
        final List<T> result = new ArrayList<>(all.length);
        for (int i = 0; i < all.length; i++) {
          result.add(all[i].join());
        }
        return result;
      });
}
// example
List<String> values = asList("a", "b", "c");
List<CompletableFuture<String>> futures = values.stream().map(CompletableFuture::completedFuture).collect(toList());
CompletableFuture<List<String>> joined = allAsList(futures);

/**
  * Collect a stream of {@link CompletionStage}s into a single future holding a list of the
  * joined entities.
   * <pre>{@code
   * collection.stream()
   *     .map(this::someAsyncFunc)
   *     .collect(joinList())
   *     .thenApply(this::consumeList)
   * }</pre>
  */
public static <T, S extends CompletionStage<? extends T>>
  Collector<S, ?, CompletableFuture<List<T>>> joinList() {
    return Collectors.collectingAndThen(Collectors.toList(), CompletableFutures::allAsList);
}

/**
  * Returns a new {@link CompletableFuture} which completes to a list of values of those input
  * stages that succeeded. The list of results is in the same order as the input stages. For failed
  * stages, the defaultValueMapper will be called, and the value returned from that function will
  * be put in the resulting list.
  */
public static <T> CompletableFuture<List<T>> successfulAsList(
    List<? extends CompletionStage<T>> stages,
    Function<Throwable, ? extends T> defaultValueMapper) {
  return stages.stream()
      .map(f -> f.exceptionally(defaultValueMapper))
      .collect(joinList());
}
// example  遇到异常按默认值处理
List<CompletableFuture<String>> input = Arrays.asList(
    completedFuture("a"),
    exceptionallyCompletedFuture(new RuntimeException("boom")));
CompletableFuture<List<String>> joined = CompletableFutures.successfulAsList(input, t -> "default");
```

### CompletableFuture优雅处理异常
``` java
private static final ScheduledExecutorService scheduler =
        Executors.newScheduledThreadPool(1,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("failAfter-%d").build());

public static <T> CompletableFuture<T> failAfter(Duration duration) {
    final CompletableFuture<T> promise = new CompletableFuture<>();
    scheduler.schedule(() -> {
        final TimeoutException ex = new TimeoutException("Timeout after " + duration);
        return promise.completeExceptionally(ex);
    }, duration.toMillis(), MILLISECONDS);
    return promise;
}

public static <T> CompletableFuture<T> within(CompletableFuture<T> future, Duration duration) {
    final CompletableFuture<T> timeout = failAfter(duration);
    return future.applyToEither(timeout, Function.identity());
}

final CompletableFuture<Response> responseFuture = within(asyncCode(), Duration.ofSeconds(1));
responseFuture.thenAccept(this::send)
        .exceptionally(throwable -> {
            log.error("Unrecoverable error", throwable);
            return null;
        });
```

### 定时轮训外部资源
``` java
/**
 * Polls an external resource periodically until it returns a non-empty result.
 *
 * <p> The polling task should return {@code Optional.empty()} until it becomes available, and
 * then {@code Optional.of(result)}.  If the polling task throws an exception or returns null,
 * that will cause the result future to complete exceptionally.
 *
 * <p> Canceling the returned future will cancel the scheduled polling task as well.
 *
 * <p> Note that on a ScheduledThreadPoolExecutor the polling task might remain allocated for up
 * to {@code frequency} time after completing or being cancelled.  If you have lots of polling
 * operations or a long polling frequency, consider setting {@code removeOnCancelPolicy} to true.
 * See {@link java.util.concurrent.ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)}.
 *
 * @param pollingTask     the polling task
 * @param frequency       the frequency to run the polling task at
 * @param executorService the executor service to schedule the polling task on
 * @param <T>             the type of the result of the polling task, that will be returned when
 *                        the task succeeds.
 * @return a future completing to the result of the polling task once that becomes available
 */
public static <T> CompletableFuture<T> poll(
    final Supplier<Optional<T>> pollingTask,
    final Duration frequency,
    final ScheduledExecutorService executorService) {
  final CompletableFuture<T> result = new CompletableFuture<>();
  final ScheduledFuture<?> scheduled = executorService.scheduleAtFixedRate(
      () -> pollTask(pollingTask, result), 0, frequency.toMillis(), TimeUnit.MILLISECONDS);
  result.whenComplete((r, ex) -> scheduled.cancel(true));
  return result;
}

private static <T> void pollTask(
    final Supplier<Optional<T>> pollingTask,
    final CompletableFuture<T> resultFuture) {
  try {
    pollingTask.get().ifPresent(resultFuture::complete);
  } catch (Exception ex) {
    resultFuture.completeExceptionally(ex);
  }
}
```


text:
package org.apache.ignite.internal.processors.igfs;

import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.FileSystemConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.igfs.IgfsGroupDataBlocksKeyMapper;
import org.apache.ignite.igfs.IgfsIpcEndpointConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.cache.GridCacheDefaultAffinityKeyMapper;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.igfs.IgfsMode.DUAL_ASYNC;
import static org.apache.ignite.igfs.IgfsMode.DUAL_SYNC;
import static org.apache.ignite.igfs.IgfsMode.PROXY;

/**
 * Tests for node validation logic in {@link IgfsProcessor}.
 *

 * Tests starting with "testLocal" are checking
 * {@link IgfsUtils#validateLocalIgfsConfigurations(org.apache.ignite.configuration.IgniteConfiguration)}.
 *

 * Tests starting with "testRemote" are checking {@link IgfsProcessor#checkIgfsOnRemoteNode(org.apache.ignite.cluster.ClusterNode)}.
 */
public class IgfsProcessorValidationSelfTest extends IgfsCommonAbstractTest {
    /** IP finder. */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** Grid #1 config. */
    private IgniteConfiguration g1Cfg;

    /** First IGFS config in grid #1. */
    private FileSystemConfiguration g1IgfsCfg1 = new FileSystemConfiguration();

    /** Second IGFS config in grid#1. */
    private FileSystemConfiguration g1IgfsCfg2 = new FileSystemConfiguration();

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        g1Cfg = getConfiguration("g1");
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();

        discoSpi.setIpFinder(IP_FINDER);

        cfg.setDiscoverySpi(discoSpi);

        g1IgfsCfg1.setName("g1IgfsCfg1");

        g1IgfsCfg2.setName("g1IgfsCfg2");

        cfg.setFileSystemConfiguration(g1IgfsCfg1, g1IgfsCfg2);

        cfg.setLocalHost("127.0.0.1");

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        stopAllGrids();
    }

    /**
     * Returns a new array that contains the concatenated contents of two arrays.
     *
     * @param first the first array of elements to concatenate.
     * @param second the second array of elements to concatenate.
     * @param cls Class of elements.
     * @return Concatenated array.
     */
    private <T> T[] concat(T[] first, T[] second, Class<?> cls) {
        Collection<T> res = new ArrayList<>();

        res.addAll(Arrays.asList(first));
        res.addAll(Arrays.asList(second));

        return res.toArray((T[]) Array.newInstance(cls, res.size()));
    }

    /**
     * @throws Exception If failed.
     */
    public void testLocalIfAffinityMapperIsWrongClass() throws Exception {

        for (FileSystemConfiguration igfsCfg : g1Cfg.getFileSystemConfiguration()) {
            igfsCfg.setDataCacheConfiguration(dataCache(1024));
            igfsCfg.setMetaCacheConfiguration(metaCache());

            igfsCfg.getMetaCacheConfiguration().setAffinityMapper(new GridCacheDefaultAffinityKeyMapper());
            igfsCfg.getDataCacheConfiguration().setAffinityMapper(new GridCacheDefaultAffinityKeyMapper());
        }

        checkGridStartFails(g1Cfg, "Invalid IGFS data cache configuration (key affinity mapper class should be", true);
    }

    /**
     * @throws Exception If failed.
     */
    public void testLocalIfIgfsConfigsHaveDuplicatedNames() throws Exception {
        String igfsCfgName = "igfs-cfg";

        g1IgfsCfg1.setName(igfsCfgName);
        g1IgfsCfg2.setName(igfsCfgName);

        checkGridStartFails(g1Cfg, "Duplicate IGFS name found (check configuration and assign unique name", true);
    }

    /**
     * @throws Exception If failed.
     */
    public void testLocalIfQueryIndexingEnabledForDataCache() throws Exception {
        g1IgfsCfg1.setDataCacheConfiguration(dataCache(1024));
        g1IgfsCfg1.getDataCacheConfiguration().setIndexedTypes(Integer.class, String.class);

        checkGridStartFails(g1Cfg, "IGFS data cache cannot start with enabled query indexing", true);
    }

    /**
     * @throws Exception If failed.
     */
    public void testLocalIfQueryIndexingEnabledForMetaCache() throws Exception {
        g1IgfsCfg1.setMetaCacheConfiguration(metaCache());

        g1IgfsCfg1.getMetaCacheConfiguration().setIndexedTypes(Integer.class, String.class);

        checkGridStartFails(g1Cfg, "IGFS metadata cache cannot start with enabled query indexing", true);
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings("NullableProblems")
    public void testLocalNullIgfsNameIsSupported() throws Exception {
        g1IgfsCfg1.setName(null);

        assertFalse(G.start(g1Cfg).cluster().nodes().isEmpty());
    }

    /**
     * @throws Exception If failed.
     */
    public void testLocalIfNonPrimaryModeAndHadoopFileSystemUriIsNull() throws Exception {
        g1IgfsCfg2.setDefaultMode(PROXY);

        checkGridStartFails(g1Cfg, "secondaryFileSystem cannot be null when mode is not PRIMARY", true);
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemoteIfDataBlockSizeDiffers() throws Exception {
        IgniteConfiguration g2Cfg = getConfiguration("g2");

        FileSystemConfiguration g2IgfsCfg1 = new FileSystemConfiguration(g1IgfsCfg1);

        g2IgfsCfg1.setBlockSize(g2IgfsCfg1.getBlockSize() + 100);

        g2Cfg.setFileSystemConfiguration(g2IgfsCfg1, g1IgfsCfg2);

        G.start(g1Cfg);

        checkGridStartFails(g2Cfg, "Data block size should be the same on all nodes in grid for IGFS", false);
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemoteIfAffinityMapperGroupSizeDiffers() throws Exception {
        IgniteConfiguration g2Cfg = getConfiguration("g2");

        G.start(g1Cfg);

        for (FileSystemConfiguration igfsCfg : g2Cfg.getFileSystemConfiguration())
            igfsCfg.setDataCacheConfiguration(dataCache(1000));

        checkGridStartFails(g2Cfg, "Affinity mapper group size should be the same on all nodes in grid for IGFS",
            false);
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemoteIfDefaultModeDiffers() throws Exception {
        IgniteConfiguration g2Cfg = getConfiguration("g2");

        FileSystemConfiguration g2IgfsCfg1 = new FileSystemConfiguration(g1IgfsCfg1);
        FileSystemConfiguration g2IgfsCfg2 = new FileSystemConfiguration(g1IgfsCfg2);

        g1IgfsCfg1.setDefaultMode(DUAL_ASYNC);
        g1IgfsCfg2.setDefaultMode(DUAL_ASYNC);

        g2IgfsCfg1.setDefaultMode(DUAL_SYNC);
        g2IgfsCfg2.setDefaultMode(DUAL_SYNC);

        g2Cfg.setFileSystemConfiguration(g2IgfsCfg1, g2IgfsCfg2);

        G.start(g1Cfg);

        checkGridStartFails(g2Cfg, "Default mode should be the same on all nodes in grid for IGFS", false);
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemoteIfPathModeDiffers() throws Exception {
        IgniteConfiguration g2Cfg = getConfiguration("g2");

        FileSystemConfiguration g2IgfsCfg1 = new FileSystemConfiguration(g1IgfsCfg1);
        FileSystemConfiguration g2IgfsCfg2 = new FileSystemConfiguration(g1IgfsCfg2);

        g2IgfsCfg1.setPathModes(Collections.singletonMap("/somePath", DUAL_SYNC));
        g2IgfsCfg2.setPathModes(Collections.singletonMap("/somePath", DUAL_SYNC));

        g2Cfg.setFileSystemConfiguration(g2IgfsCfg1, g2IgfsCfg2);

        G.start(g1Cfg);

        checkGridStartFails(g2Cfg, "Path modes should be the same on all nodes in grid for IGFS", false);
    }

    /**
     * @throws Exception If failed.
     */
    public void testZeroEndpointTcpPort() throws Exception {
        checkInvalidPort(0);
    }

    /**
     * @throws Exception If failed.
     */
    public void testNegativeEndpointTcpPort() throws Exception {
        checkInvalidPort(-1);
    }

    /**
     * @throws Exception If failed.
     */
    public void testTooBigEndpointTcpPort() throws Exception {
        checkInvalidPort(65536);
    }

    /**
     * @throws Exception If failed.
     */
    public void testPreConfiguredCache() throws Exception {
        FileSystemConfiguration igfsCfg1 = new FileSystemConfiguration(g1IgfsCfg1);
        igfsCfg1.setName("igfs");

        g1Cfg.setFileSystemConfiguration(igfsCfg1);

        CacheConfiguration ccfgData = dataCache(1024);
        ccfgData.setRebalanceTimeout(10001);

        CacheConfiguration ccfgMeta = metaCache();
        ccfgMeta.setRebalanceTimeout(10002);

        igfsCfg1.setDataCacheConfiguration(ccfgData);
        igfsCfg1.setMetaCacheConfiguration(ccfgMeta);

        IgniteEx g = (IgniteEx)G.start(g1Cfg);

        assertEquals(10001,
            g.cachex(g.igfsx("igfs").configuration().getDataCacheConfiguration().getName())
                .configuration().getRebalanceTimeout());
        assertEquals(10002,
            g.cachex(g.igfsx("igfs").configuration().getMetaCacheConfiguration().getName())
                .configuration().getRebalanceTimeout());
    }

    /**
     * Check invalid port handling.
     *
     * @param port Port.
     * @throws Exception If failed.
     */
    private void checkInvalidPort(int port) throws Exception {
        final String failMsg = "IGFS endpoint TCP port is out of range";

        final String igfsCfgName = "igfs-cfg";
        final IgfsIpcEndpointConfiguration igfsEndpointCfg = new IgfsIpcEndpointConfiguration();
        igfsEndpointCfg.setPort(port);
        g1IgfsCfg1.setName(igfsCfgName);
        g1IgfsCfg1.setIpcEndpointConfiguration(igfsEndpointCfg);

        checkGridStartFails(g1Cfg, failMsg, true);
    }

    /**
     * @throws Exception If failed.
     */
    public void testInvalidEndpointThreadCount() throws Exception {
        final String failMsg = "IGFS endpoint thread count must be positive";

        final String igfsCfgName = "igfs-cfg";
        final IgfsIpcEndpointConfiguration igfsEndpointCfg = new IgfsIpcEndpointConfiguration();
        igfsEndpointCfg.setThreadCount(0);
        g1IgfsCfg1.setName(igfsCfgName);
        g1IgfsCfg1.setIpcEndpointConfiguration(igfsEndpointCfg);

        checkGridStartFails(g1Cfg, failMsg, true);
    }

    /**
     * Checks that the given grid configuration will lead to {@link IgniteCheckedException} upon grid startup.
     *
     * @param cfg Grid configuration to check.
     * @param excMsgSnippet Root cause (assertion) exception message snippet.
     * @param testLoc {@code True} if checking is done for "testLocal" tests.
     */
    private void checkGridStartFails(IgniteConfiguration cfg, CharSequence excMsgSnippet, boolean testLoc) {
        assertNotNull(cfg);
        assertNotNull(excMsgSnippet);

        try {
            G.start(cfg);

            fail("No exception has been thrown.");
        }
        catch (IgniteException e) {
            if (testLoc) {
                if (e.getMessage().contains(excMsgSnippet)
                    || ("Failed to start processor: GridProcessorAdapter []".equals(e.getMessage()) &&
                    (e.getCause().getMessage().contains(excMsgSnippet) ||
                     e.getCause().getCause().getMessage().contains(excMsgSnippet))))
                    return; // Expected exception.
            }
            else if (e.getMessage().contains(excMsgSnippet))
                return; // Expected exception.

            error("Caught unexpected exception.", e);

            fail();
        }
    }

    /**
     * @param grpSize Group size to use in {@link org.apache.ignite.igfs.IgfsGroupDataBlocksKeyMapper}.
     * @return 2 preconfigured data cache.
     */
    private CacheConfiguration dataCache(int grpSize) {

        CacheConfiguration dataCache = defaultCacheConfiguration();

        dataCache.setAffinityMapper(new IgfsGroupDataBlocksKeyMapper(grpSize));
        dataCache.setAtomicityMode(TRANSACTIONAL);

        return dataCache;
    }

    /**
     * @return preconfigured meta cache.
     */
    private CacheConfiguration metaCache() {
        CacheConfiguration metaCache = defaultCacheConfiguration();

        metaCache.setAtomicityMode(TRANSACTIONAL);

        return metaCache;
    }
}


text:
package org.statmantis.stat.common;

import java.math.BigDecimal;

import org.statmantis.stat.AbstractStatistic;
import org.statmantis.stat.StatisticInfo;
import org.statmantis.stat.StatisticType;

@StatisticInfo(
        name = "On-base Percentage",
        abbreviations = { "OBP", "OBA" },
        types = { StatisticType.BATTING, StatisticType.PITCHING },
        dependencies = {
                Hits.class,
                BasesOnBalls.class,
                HitByPitches.class,
                AtBats.class,
                SacrificeFlies.class
        })
public class OnBasePercentage extends AbstractStatistic<BigDecimal> {

    @Override
    public BigDecimal getCurrentValue() {
        int h = getDependency(Hits.class);
        int bb = getDependency(BasesOnBalls.class);
        int hbp = getDependency(HitByPitches.class);
        int ab = getDependency(AtBats.class);
        int sf = getDependency(SacrificeFlies.class);
        int denom = ab + bb + hbp + sf;
        if (denom == 0) {
            return BigDecimal.ZERO;
        }
        return new BigDecimal(h + bb + hbp).divide(
                new BigDecimal(denom));
    }

}


text:
class BroadcastsController < ApplicationController
  before_filter :except => [:index, :show] { authenticate_admin(broadcasts_url) }

  def index
    @broadcasts = Broadcast.push_to_all.order('created_at DESC').page(params[:page]).per(5)

    respond_to do |format|
      format.html
    end
  end

  def show
    @broadcast = Broadcast.find(params[:id])

    respond_to do |format|
      format.html
    end
  end

  def new
    @broadcast = Broadcast.new

    respond_to do |format|
      format.html
    end
  end

  def create
    @attr = params[:broadcast]
    @attr.merge!(:author => current_user.id)
    @broadcast = Broadcast.new(params[:broadcast])

    respond_to do |format|
      if @broadcast.save
        format.html { redirect_to @broadcast }
      else
        format.html { render action: 'new' }
      end
    end
  end

  def edit
    @broadcast = Broadcast.find(params[:id])
  end

  def update
    @attr = params[:broadcast]
    @broadcast = Broadcast.find(params[:id])

    respond_to do |format|
      if @broadcast.update_attributes(@attr)
        format.html { redirect_to @broadcast }
      else
        flash.now[:alert] = @broadcast.errors.full_messages
        format.html { render action: 'edit' }
      end
    end
  end

  def destroy
    @broadcast = Broadcast.find(params[:id])
    @broadcast.destroy

    respond_to do |format|
      format.html { redirect_to broadcasts_url }
    end
  end

  def blogs
    @broadcasts = Broadcast.order('created_at DESC').page(params[:page]).per(5)

    respond_to do |format|
      format.html { render :index }
    end
  end
end


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

import com.facebook.airlift.configuration.AbstractConfigurationAwareModule;
import com.facebook.presto.plugin.jdbc.BaseJdbcConfig;
import com.facebook.presto.plugin.jdbc.JdbcClient;
import com.google.inject.Binder;
import com.google.inject.Scopes;
import com.mysql.jdbc.Driver;

import java.sql.SQLException;
import java.util.Properties;

import static com.facebook.airlift.configuration.ConfigBinder.configBinder;
import static com.google.common.base.Preconditions.checkArgument;

public class MySqlClientModule
        extends AbstractConfigurationAwareModule
{
    @Override
    protected void setup(Binder binder)
    {
        binder.bind(JdbcClient.class).to(MySqlClient.class).in(Scopes.SINGLETON);
        ensureCatalogIsEmpty(buildConfigObject(BaseJdbcConfig.class).getConnectionUrl());
        configBinder(binder).bindConfig(MySqlConfig.class);
    }

    private static void ensureCatalogIsEmpty(String connectionUrl)
    {
        try {
            Driver driver = new Driver();
            Properties urlProperties = driver.parseURL(connectionUrl, null);
            checkArgument(urlProperties != null, "Invalid JDBC URL for MySQL connector");
            checkArgument(driver.database(urlProperties) == null, "Database (catalog) must not be specified in JDBC URL for MySQL connector");
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#ifndef _PWL_BUTTON_H_
#define _PWL_BUTTON_H_

class PWL_CLASS CPWL_Button : public CPWL_Wnd
{
public:
	CPWL_Button();
	virtual ~CPWL_Button();

public:
	virtual CFX_ByteString		GetClassName() const;
	virtual void				OnCreate(PWL_CREATEPARAM & cp);

	virtual FX_BOOL				OnLButtonDown(const CPDF_Point & point, FX_DWORD nFlag);
	virtual FX_BOOL				OnLButtonUp(const CPDF_Point & point, FX_DWORD nFlag);

protected:
	FX_BOOL						m_bMouseDown;
};

#endif // !defined(AFX_PWL_BUTTON_H__5A6080AA_33C5_4FC9_91FC_D9644C41120A__INCLUDED_)


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

@import uk.gov.hmrc.helptosavefrontend.config.FrontendAppConfig
@import uk.gov.hmrc.helptosavefrontend.models.HtsContext
@import uk.gov.hmrc.helptosavefrontend.controllers.routes

@import uk.gov.hmrc.helptosavefrontend.util.Email

@this(main: uk.gov.hmrc.helptosavefrontend.views.html.main_template)

@(returningUser: Boolean, accountEmail: Option[Email])(implicit htsContext: HtsContext, request: Request[_], messages: Messages, appConfig: FrontendAppConfig)

@title = @{
  Messages("hts.cannot-change-email-try-later.title.h1")
}

@main(
title = title,
sidebarLinks = None,
bodyClasses = None) {
  @if(returningUser){

    @accountEmail match {
        case None => {

@title

@Html(Messages("hts.cannot-change-email-try-later.p1"))

            @messages("hts.cannot-change-email-try-later.try_later_button")

                @Messages("hts.cannot-change-email-try-later.back_button")

        }

        case _ => {

@title

@Messages("hts.cannot-change-email-try-later.returning.p1")

@Html(Messages("hts.cannot-change-email-try-later.returning.p2"))

@Messages("hts.cannot-change-email-try-later.returning.button")

        }
    }

  } else {

@title

@Html(Messages("hts.cannot-change-email-try-later.p1"))

    @messages("hts.cannot-change-email-try-later.try_later_button")

      @Messages("hts.cannot-change-email-try-later.back_button")

  }
}


text:
<!DOCTYPE html>
<html>
<body>
<script>
console.log('Loaded pagehide-timeout-go-back.html, going back');
setTimeout(function() { history.back(); }, 200);
</script>
</body>
</html>


text:
<?php

namespace SandraPokemonBundle\Admin;

use Doctrine\ORM\EntityRepository;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class BadgesAdmin extends AbstractAdmin
{
    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('nom')
            ->add('idBadges')
        ;
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('nom')
            ->add('idBadges')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('nom')
            ->add('idDresseurMaitre', EntityType::class, array(
                'class' => 'SandraPokemonBundle\Entity\Dresseurs',
                'query_builder' => function (EntityRepository $er) {
                    $qb = $er->createQueryBuilder('d');

                    return $qb;
                },
                'choice_label' => function ($dresseurs) {
                    return $dresseurs->getNom();
                },
                'required'          => false,
            ))
            ->add('idZones', EntityType::class, array(
            'class' => 'SandraPokemonBundle\Entity\Zones',
            'query_builder' => function (EntityRepository $er) {
                $qb = $er->createQueryBuilder('z');

                return $qb;
            },
            'choice_label' => function ($zones) {
                return $zones->getNom();
            },
            'required'          => false,
        ))
        ;
    }

    /**
     * @param ShowMapper $showMapper
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('nom')
            ->add('idBadges')
        ;
    }
}


text:
require_dependency 'stash_api/application_controller'

module StashApi
  class GeneralController < ApplicationController

    before_action :doorkeeper_authorize!, only: :test
    before_action :require_api_user, only: :test

    # get /datasets
    def index
      respond_to do |format|
        format.json { render json: output }
        format.html {}
      end
    end

    # post /test
    # see if you can do a post request and connect with the key you've obtained
    def test
      respond_to do |format|
        format.json { render json: { message: "Welcome application owner #{@user.name}", user_id: @user.id } }
        format.html {}
      end
    end

    private

    def output
      {
        '_links': {
          'self': root_self,
          'stash:datasets': {
            href: datasets_path
          },
          curies: curies
        }
      }
    end

    def root_self
      {
        href: root_path
      }
    end

    def curies
      [
        {
          name: 'stash',
          href: 'https://github.com/CDLUC3/stash/blob/development/stash_api/link-relations.md#{rel}', # rubocop:disable Lint/InterpolationCheck
          templated: 'true'
        }
      ]
    end

  end
end


text:
function loadChildChoices(parentField, child) {
    var valueField = child;
    var ajaxUrl = valueField.getAttribute("ajax_url");
    var emptyLabel = valueField.getAttribute('empty_label') || '--------';

    var headers = new Headers();
    headers.append("Accept", "application/json");

    var request = new Request(
        ajaxUrl + "?field=" + valueField.getAttribute("name") + "&parent_field=" + parentField.getAttribute("name") + "&parent_value=" + parentField.value,
        {
            method: "GET",
            headers: headers,
            credentials: 'same-origin'
        }
    );

    fetch(request).then(function(response) {
        return response.json();
    }).then(function(options) {
        var optionsHTML = "";

        if (!child[0].hasAttribute("multiple")) {
            optionsHTML += '<option value="">' + emptyLabel + '</option>';
        }

        options.forEach(function(option) {
            optionsHTML += '<option value="' + option[0] + '">' + option[1] + '</option>';
        });

        valueField.innerHTML = optionsHTML;
        valueField.dispatchEvent(new Event("change"));
        valueField.dispatchEvent(new Event("load"));
        valueField.dispatchEvent(new Event("liszt:updated")); // support for chosen versions < 1.0.0
        valueField.dispatchEvent(new Event("chosen:updated")); // support for chosen versions >= 1.0.0
    });
};

function loadAllChainedChoices(parentField) {
    var chained_ids = parentField.getAttribute('chained_ids').split(",");

    chained_ids.forEach(function(chained_id) {
        var child = document.getElementById(chained_id);
        loadChildChoices(parentField, child);
    });
};

document.addEventListener("DOMContentLoaded", function() {
    var parentFields = document.querySelectorAll(".chained-parent-field");

    parentFields.forEach(function(parentField) {
        if ( parentField.classList.contains('chzn-done') ) {
            $(parentField).change(function() {
                loadAllChainedChoices(this);
            });
        } else {
            parentField.addEventListener("change", function() { loadAllChainedChoices(this); });
        }
    });
});


text:
Application::Application(RenderingConfig & config) :
	_config(config) {
	_startTime = System::time();
	_timer = _startTime;
	for(uint fid = 0; fid < _frameTimes.size(); ++fid){
		_frameTimes[fid] = 0.0f;
	}

	if(_config.trackDebug) {
		_debug.reset(new DebugViewer());
		DebugViewer::setDefault(_debug.get());
	} else {
		// No viewer
		_debug = nullptr;
	}
}

Application::~Application(){
	if(_config.trackDebug){
		DebugViewer::setDefault(nullptr);
	}
}

void Application::update() {
	// Handle window resize.
	if(Input::manager().resized()) {
		const uint width = uint(Input::manager().size()[0]);
		const uint height = uint(Input::manager().size()[1]);
		_config.screenResolution[0] = float(width > 0 ? width : 1);
		_config.screenResolution[1] = float(height > 0 ? height : 1);
		resize();
	}

	// Reload resources.
	if(Input::manager().triggered(Input::Key::P)) {
		Resources::manager().reload();
	}

	if(_showDebug && _debug) {
		_debug->interface();
	}

	// Compute the time elapsed since last frame
	const double currentTime = System::time();
	_frameTime		 = currentTime - _timer;
	_timer			 = currentTime;

	// Keep accumulating smoothed time.
	_smoothTime -= _frameTimes[_currFrame];
	_frameTimes[_currFrame] = _frameTime;
	_smoothTime += _frameTimes[_currFrame];
	_currFrame = (_currFrame + 1) % _framesCount;
}

void Application::finish() {
	// This will be executed before the GUI is drawn.

	// Perform screenshot capture in the current working directory.
	if(Input::manager().triggered(Input::Key::O) || (Input::manager().controllerAvailable() && Input::manager().controller()->triggered(Controller::ButtonView))) {
		const std::string filename = System::timestamp();
		GPU::saveFramebuffer(*Framebuffer::backbuffer(), "./" + filename, Image::Save::IGNORE_ALPHA);
	}

	// Display debug informations.
	if((Input::manager().pressed(Input::Key::LeftControl) || Input::manager().pressed(Input::Key::LeftAlt)) && Input::manager().triggered(Input::Key::Tab)) {
		_showDebug = !_showDebug;
	}
}

double Application::timeElapsed(){
	return _timer - _startTime;
}

double Application::frameTime(){
	return _frameTime;
}

double Application::frameRate(){
	return double(_framesCount) / _smoothTime;
}

CameraApp::CameraApp(RenderingConfig & config) : Application(config) {
	_userCamera.ratio(config.screenResolution[0] / config.screenResolution[1]);
}

void CameraApp::update(){
	Application::update();
	_userCamera.update();

	// We separate punctual events from the main physics/movement update loop.
	// Physics simulation
	// First avoid super high frametime by clamping.
	const double frameTimeUpdate = std::min(frameTime(), 0.2);
	// Accumulate new frame time.
	_remainingTime += frameTimeUpdate;
	// Instead of bounding at dt, we lower our requirement (1 order of magnitude).
	while(_remainingTime > 0.2 * _dt) {
		const double deltaTime = std::min(_remainingTime, _dt);
		if(!_freezeCamera){
			_userCamera.physics(deltaTime);
		}
		// Update physics.
		physics(_fullTime, deltaTime);
		// Update timers.
		_fullTime += deltaTime;
		_remainingTime -= deltaTime;
	}
}

void CameraApp::physics(double, double){

}

void CameraApp::freezeCamera(bool shouldFreeze){
	_freezeCamera = shouldFreeze;
}


text:
.class Lcom/android/server/content/SyncManager$4;
.super Landroid/content/BroadcastReceiver;
.source "SyncManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/content/SyncManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/content/SyncManager;

# direct methods
.method constructor <init>(Lcom/android/server/content/SyncManager;)V
    .locals 0

    .prologue
    .line 239
    iput-object p1, p0, Lcom/android/server/content/SyncManager$4;->this$0:Lcom/android/server/content/SyncManager;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 11
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "intent"    # Landroid/content/Intent;

    .prologue
    const-wide/16 v6, 0x0

    const/4 v1, 0x0

    .line 242
    iget-object v0, p0, Lcom/android/server/content/SyncManager$4;->this$0:Lcom/android/server/content/SyncManager;

    invoke-virtual {v0}, Lcom/android/server/content/SyncManager;->updateRunningAccounts()V

    .line 245
    iget-object v0, p0, Lcom/android/server/content/SyncManager$4;->this$0:Lcom/android/server/content/SyncManager;

    const/4 v2, -0x1

    const/4 v3, -0x2

    const/4 v10, 0x0

    move-object v4, v1

    move-object v5, v1

    move-wide v8, v6

    invoke-virtual/range {v0 .. v10}, Lcom/android/server/content/SyncManager;->scheduleSync(Landroid/accounts/Account;IILjava/lang/String;Landroid/os/Bundle;JJZ)V

    .line 247
    return-void
.end method


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.False.html">

Redirecting to type.False.html...


text:
package org.spongepowered.common.data.manipulator.immutable.entity;

import static com.google.common.base.Preconditions.checkArgument;

import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.entity.ImmutableIgniteableData;
import org.spongepowered.api.data.manipulator.mutable.entity.IgniteableData;
import org.spongepowered.api.data.value.immutable.ImmutableBoundedValue;
import org.spongepowered.common.data.manipulator.immutable.common.AbstractImmutableData;
import org.spongepowered.common.data.manipulator.mutable.entity.SpongeIgniteableData;
import org.spongepowered.common.data.util.DataConstants;
import org.spongepowered.common.data.value.SpongeValueFactory;

public class ImmutableSpongeIgniteableData extends AbstractImmutableData<ImmutableIgniteableData, IgniteableData> implements ImmutableIgniteableData {

    private final int fireTicks;
    private final int fireDelay;

    private final ImmutableBoundedValue<Integer> fireTicksValue;
    private final ImmutableBoundedValue<Integer> fireDelayValue;

    public ImmutableSpongeIgniteableData(int fireTicks, int fireDelay) {
        super(ImmutableIgniteableData.class);
        checkArgument(fireTicks > 0);
        this.fireTicks = fireTicks;
        this.fireDelay = fireDelay;

        this.fireTicksValue = SpongeValueFactory.boundedBuilder(Keys.FIRE_TICKS)
                .actualValue(this.fireTicks)
                .defaultValue(DataConstants.DEFAULT_FIRE_TICKSVALUE)
                .minimum(1)
                .maximum(Integer.MAX_VALUE)
                .build()
                .asImmutable();

        this.fireDelayValue = SpongeValueFactory.boundedBuilder(Keys.FIRE_DAMAGE_DELAY)
                .actualValue(this.fireDelay)
                .defaultValue(DataConstants.DEFAULT_FIRE_DAMAGE_DELAY)
                .minimum(0)
                .maximum(Integer.MAX_VALUE)
                .build()
                .asImmutable();

        registerGetters();
    }

    @Override
    public ImmutableBoundedValue<Integer> fireTicks() {
        return this.fireTicksValue;
    }

    @Override
    public ImmutableBoundedValue<Integer> fireDelay() {
        return this.fireDelayValue;
    }

    @Override
    public IgniteableData asMutable() {
        return new SpongeIgniteableData(this.fireTicks, this.fireDelay);
    }

    @Override
    public DataContainer toContainer() {
        return super.toContainer()
            .set(Keys.FIRE_TICKS.getQuery(), this.fireTicks)
            .set(Keys.FIRE_DAMAGE_DELAY.getQuery(), this.fireDelay);
    }

    public int getFireTicks() {
        return this.fireTicks;
    }

    public int getFireDelay() {
        return this.fireDelay;
    }

    @Override
    protected void registerGetters() {
        registerFieldGetter(Keys.FIRE_TICKS, ImmutableSpongeIgniteableData.this::getFireTicks);
        registerKeyValue(Keys.FIRE_TICKS, ImmutableSpongeIgniteableData.this::fireTicks);

        registerFieldGetter(Keys.FIRE_DAMAGE_DELAY, ImmutableSpongeIgniteableData.this::getFireDelay);
        registerKeyValue(Keys.FIRE_DAMAGE_DELAY, ImmutableSpongeIgniteableData.this::fireDelay);
    }

}


text:
package org.jetbrains.jps.builders.java.dependencyView;

import com.intellij.util.io.DataInputOutputUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.storage.BuildDataCorruptedException;
import org.jetbrains.org.objectweb.asm.Type;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.util.Set;

/**
 * @author: db
 * Date: 07.03.11
 */
abstract class ProtoMember extends Proto {

  @NotNull
  public final TypeRepr.AbstractType myType;
  public final Object myValue;

  private static abstract class DataDescriptor<T> {
    public static final DataDescriptor NONE = new DataDescriptor(0, null) {
      @Override
      public Object load(DataInput out) {
        return null;
      }
      @Override
      public void save(DataOutput out, Object value) throws IOException {
      }
    };
    public static final DataDescriptor<String> STRING = new DataDescriptor<String>(1, String.class) {
      @Override
      public String load(DataInput in) throws IOException {
        return RW.readUTF(in);
      }
      @Override
      public void save(DataOutput out, String value) throws IOException {
        RW.writeUTF(out, value);
      }
    };
    public static final DataDescriptor<Integer> INTEGER = new DataDescriptor<Integer>(2, Integer.class) {
      @Override
      public Integer load(DataInput in) throws IOException {
        return DataInputOutputUtil.readINT(in);
      }

      @Override
      public void save(DataOutput out, Integer value) throws IOException {
        DataInputOutputUtil.writeINT(out, value.intValue());
      }
    };
    public static final DataDescriptor<Long> LONG = new DataDescriptor<Long>(3, Long.class) {
      @Override
      public Long load(DataInput in) throws IOException {
        return in.readLong();
      }

      @Override
      public void save(DataOutput out, Long value) throws IOException {
        out.writeLong(value.longValue());
      }
    };
    public static final DataDescriptor<Float> FLOAT = new DataDescriptor<Float>(4, Float.class) {
      @Override
      public Float load(DataInput in) throws IOException {
        return in.readFloat();
      }

      @Override
      public void save(DataOutput out, Float value) throws IOException {
        out.writeFloat(value.floatValue());
      }
    };
    public static final DataDescriptor<Double> DOUBLE = new DataDescriptor<Double>(5, Double.class) {
      @Override
      public Double load(DataInput in) throws IOException {
        return in.readDouble();
      }

      @Override
      public void save(DataOutput out, Double value) throws IOException {
        out.writeDouble(value.doubleValue());
      }
    };
    public static final DataDescriptor<Type> TYPE = new DataDescriptor<Type>(6, Type.class) {
      @Override
      public Type load(DataInput in) throws IOException {
        return Type.getType(RW.readUTF(in));
      }

      @Override
      public void save(DataOutput out, Type value) throws IOException {
        RW.writeUTF(out, value.getDescriptor());
      }
    };

    private final byte myId;
    @Nullable
    private final Class<T> myDataType;

    private DataDescriptor(int id, Class<T> dataType) {
      myId = (byte)id;
      myDataType = dataType;
    }

    public byte getId() {
      return myId;
    }

    @Nullable
    public Class<T> getDataType() {
      return myDataType;
    }

    public abstract void save(DataOutput out, T value) throws IOException;
    public abstract T load(DataInput in) throws IOException;

    @NotNull
    public static DataDescriptor findById(byte tag) {
      if (STRING.getId() == tag) {
        return STRING;
      }
      if (INTEGER.getId() == tag) {
        return INTEGER;
      }
      if (LONG.getId() == tag) {
        return LONG;
      }
      if (FLOAT.getId() == tag) {
        return FLOAT;
      }
      if (DOUBLE.getId() == tag) {
        return DOUBLE;
      }
      if (TYPE.getId() == tag) {
        return TYPE;
      }
      if (NONE.getId() == tag) {
        return NONE;
      }
      assert false : "Unknown descriptor tag: " + tag;
      return NONE;
    }

    public static DataDescriptor findByValueType(@Nullable Class<?> dataType) {
      if (dataType != null) {
        if (dataType.equals(STRING.getDataType())) {
          return STRING;
        }
        if (dataType.equals(INTEGER.getDataType())) {
          return INTEGER;
        }
        if (dataType.equals(LONG.getDataType())) {
          return LONG;
        }
        if (dataType.equals(FLOAT.getDataType())) {
          return FLOAT;
        }
        if (dataType.equals(DOUBLE.getDataType())) {
          return DOUBLE;
        }
        //noinspection ConstantConditions
        if (TYPE.getDataType().isAssignableFrom(dataType)) {
          return TYPE;
        }
      }
      return NONE;
    }
  }

  public boolean hasValue() {
    return myValue != null;
  }

  protected ProtoMember(final int access,
                        final int signature,
                        final int name,
                        @NotNull
                        final TypeRepr.AbstractType t,
                        @NotNull
                        Set<TypeRepr.ClassType> annotations,
                        final Object value) {
    super(access, signature, name, annotations);
    myType = t;
    myValue = value;
  }

  protected ProtoMember(final DependencyContext context, final DataInput in) {
    super(context, in);
    try {
      myType = TypeRepr.externalizer(context).read(in);
      myValue = loadTyped(in);
    }
    catch (IOException e) {
      throw new BuildDataCorruptedException(e);
    }
  }

  private static Object loadTyped(final DataInput in) {
    try {
      final byte tag = in.readByte();
      if (tag < 0) {
        // is array
        final int length = DataInputOutputUtil.readINT(in);
        final DataDescriptor descriptor = DataDescriptor.findById((byte)-tag);
        final Object array = Array.newInstance(descriptor.getDataType(), length);
        for (int idx = 0; idx < length; idx++) {
          Array.set(array, idx, descriptor.load(in));
        }
        return array;
      }
      return DataDescriptor.findById(tag).load(in);
    }
    catch (IOException e) {
      throw new BuildDataCorruptedException(e);
    }
  }

  public void save(final DataOutput out) {
    super.save(out);
    myType.save(out);

    try {
      final Object val = myValue;
      final Class valueType = val != null? val.getClass() : null;
      if (valueType != null && valueType.isArray()) {
        final int length = Array.getLength(val);
        final Class dataType = length > 0? Array.get(val, 0).getClass() : valueType.getComponentType();
        final DataDescriptor descriptor = DataDescriptor.findByValueType(dataType);
        out.writeByte(-descriptor.getId());
        if (descriptor != DataDescriptor.NONE) {
          DataInputOutputUtil.writeINT(out, length);
          for (int idx = 0; idx < length; idx++) {
            final Object element = Array.get(val, idx);
            //noinspection unchecked
            descriptor.save(out, element);
          }
        }
      }
      else {
        final DataDescriptor descriptor = DataDescriptor.findByValueType(valueType);
        out.writeByte(descriptor.getId());
        //noinspection unchecked
        descriptor.save(out, val);
      }
    }
    catch (IOException e) {
      throw new BuildDataCorruptedException(e);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public Difference difference(final Proto past) {
    final ProtoMember m = (ProtoMember)past;
    final Difference diff = super.difference(past);
    int base = diff.base();

    if (!m.myType.equals(myType)) {
      base |= Difference.TYPE;
    }

    switch ((myValue == null ? 0 : 1) + (m.myValue == null ? 0 : 2)) {
      case 3:
        if (!myValue.equals(m.myValue)) {
          base |= Difference.VALUE;
        }
        break;

      case 2:
        base |= Difference.VALUE;
        break;

      case 1:
        base |= Difference.VALUE;
        break;

      case 0:
        break;
    }

    final int newBase = base;

    return new DifferenceImpl(diff) {
      @Override
      public int base() {
        return newBase;
      }

      @Override
      public boolean no() {
        return newBase == NONE && super.no();
      }

      @Override
      public boolean hadValue() {
        return ((ProtoMember)past).hasValue();
      }
    };
  }

  public void toStream(final DependencyContext context, final PrintStream stream) {
    super.toStream(context, stream);
    stream.print("          Type       : ");
    stream.println(myType.getDescr(context));

    stream.print("          Value      : ");
    stream.println(myValue == null ? "<null>" : myValue.toString());
  }
}


text:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;
using Sifteo;

namespace Siftables.ViewModel
{
    public class MainWindowViewModel : ViewModelNotifier
    {
        public const int NumInitialCubes = 6;
        public String ReadyStatus { get { return Strings.ReadyStatus; } }

        public ObservableCollection<CubeViewModel> CubeViewModels { get; private set; }
        public ObservableCollection<SoundViewModel> ActiveSounds { get; private set; }
        public Collection<SoundViewModel> InactiveSounds { get; private set; }

        public RelayCommand SnapToGridCommand { get; private set; }
        public RelayCommand LoadAFileCommand { get; private set; }
        public RelayCommand PauseOrResumeCommand { get; private set; }
        public RelayCommand<EventArgs> ChangeNumberOfCubesCommand { get; private set; }

        private String _status;
        public String Status
        {
            get { return _status; }

            set
            {
                _status = value;
                NotifyPropertyChanged("Status");
            }
        }

        public AppRunner AppRunner { get; private set; }

        private MediaSources _imageSources;
        public MediaSources SoundSources;

        public string SnapToGridText
        {
            get { return Strings.SnapToGrid; }
        }
        public string LoadAProgramText
        {
            get { return Strings.LoadAProgram; }
        }
        public string NumOfCubesText { get { return Strings.NumOfCubes; } }

        public string PauseOrResumeText
        {
            get
            {
                return AppRunner.IsRunning ? Strings.Pause : Strings.Resume;
            }
        }
        public bool CanPauseOrResume
        {
            get { return AppRunner.IsRunning; }
        }

        public MainWindowViewModel()
        {
            #region ChangeNumberOfCubesCommand
            ChangeNumberOfCubesCommand = new RelayCommand<EventArgs>(e =>
                {
                    Status = Strings.ChangingNumberStatus;
                    var args = e as RoutedPropertyChangedEventArgs<double>;
                    if (args != null)
                    {
                        var numToChange = Math.Abs(Convert.ToInt32(CubeViewModels.Count - args.NewValue));
                        if (args.NewValue < CubeViewModels.Count) // removing cubes
                        {
                            for (var i = 0; i < numToChange; i++)
                            {
                                CubeViewModels.RemoveAt(CubeViewModels.Count - 1);
                            }
                            NeighborCalculator.CalculateNeighbors(CubeViewModels);
                        }
                        else if (args.NewValue > CubeViewModels.Count) // adding cubes
                        {
                            AddNewCubes(numToChange);
                            Status = ReadyStatus;
                            SnapToGridCommand.Execute(null);
                            if (AppRunner.IsRunning)
                            {
                                AppRunner.App.AssociateCubes(CubeSet);
                            }
                        }
                    }
                    Status = ReadyStatus;
                });
            #endregion
            #region SnapToGridCommand
            SnapToGridCommand = new RelayCommand(() =>
                {
                    Status = Strings.SnappingStatus;
                    for (var i = 0; i < Math.Ceiling(CubeViewModels.Count / 4.0); i++)
                    {
                        for (var j = 0; j < 4; j++)
                        {
                            if ((i * 4) + j > CubeViewModels.Count - 1)
                            {
                                NeighborCalculator.CalculateNeighbors(CubeViewModels);
                                Status = ReadyStatus;
                                return;
                            }
                            CubeViewModels[(i * 4) + j].PositionX = 200 * j;
                            CubeViewModels[(i * 4) + j].PositionY = 200 * i;
                        }
                    }
                    NeighborCalculator.CalculateNeighbors(CubeViewModels);
                    Status = ReadyStatus;
                });
            #endregion
            #region LoadAFileCommand
            LoadAFileCommand = new RelayCommand(() =>
                {
                    if (AppRunner.IsRunning)
                    {
                        AppRunner.StopExecution();
                    }

                    Status = Strings.SelectAppStatus;

                    var openFileDialog = new OpenFileDialog
                                             {
                                                 Filter = "C# Library (*.dll)|*.dll|All Files (*.*)|*.*",
                                                 FilterIndex = 1,
                                                 Multiselect = false
                                             };
                    if (openFileDialog.ShowDialog() == true)
                    {
                        Status = Strings.LoadingStatus;
                        using (var fileStream = openFileDialog.File.OpenRead())
                        {
                            try
                            {
                                AppRunner.LoadApplication(fileStream);
                            }
                            catch (TypeLoadException e)
                            {
                                Status = String.Format(Strings.LoadingError + ": {0}", e.Message);
                            }
                        }
                        if (AppRunner.IsLoaded)
                        {
                            Status = Strings.LoadingImagesStatus;
                            if (openFileDialog.File.Directory != null)
                            {
                                _imageSources =
                                    new ImageSources(openFileDialog.File.Directory.FullName + "\\assets\\images");
                                SoundSources =
                                    new SoundSources(openFileDialog.File.Directory.FullName + "\\assets\\sounds", ActiveSounds, InactiveSounds);

                                AppRunner.App.Images = (ImageSet) _imageSources.GetMediaSet();

                                foreach (var cubeViewModel in CubeViewModels)
                                {
                                    cubeViewModel.ImageSources = _imageSources;
                                }

                                Status = openFileDialog.File.Name + " " + Strings.LoadingSuccess;
                                AppRunner.StartExecution(CubeSet, Application.Current.MainWindow.Dispatcher, (SoundSet) SoundSources.GetMediaSet());
                                AppRunner.NotifyApplicationException += DisplayException;
                                NotifyPropertyChanged("PauseOrResumeText");
                                NotifyPropertyChanged("CanPauseOrResume");
                            }
                            else
                            {
                                Status = Strings.LoadingFail;
                            }
                        }
                    }
                    else
                    {
                        Status = Strings.LoaderClosed;
                    }
                });
            #endregion
            #region PauseOrResumeCommand

            PauseOrResumeCommand = new RelayCommand(() =>
            {
                if (AppRunner.IsRunning)
                {
                    AppRunner.PauseExecution();
                    foreach (var sound in ActiveSounds)
                    {
                        sound.SetResumeSpot();
                        InactiveSounds.Add(sound);
                    }
                    ActiveSounds.Clear();
                }
                else
                {
                    AppRunner.ResumeExecution();
                    foreach (var sound in InactiveSounds)
                    {
                        ActiveSounds.Add(sound);
                        sound.RestoreResumeSpot();
                    }
                    InactiveSounds.Clear();
                }
                NotifyPropertyChanged("PauseOrResumeText");
            });
            #endregion

            AppRunner = AppRunner.GetInstance();

            CubeViewModels = new ObservableCollection<CubeViewModel>();
            AddNewCubes(NumInitialCubes);
            SnapToGridCommand.Execute(null);
            ActiveSounds = new ObservableCollection<SoundViewModel>();
            InactiveSounds = new Collection<SoundViewModel>();
            Status = ReadyStatus;
        }

        public void DisplayException(Exception e)
        {
            Status = String.Format(Strings.AppAbortedStatus + " ({0}: {1})", e.GetType(), e.Message);
            AppRunner.StopExecution();
            NotifyPropertyChanged("CanPauseOrResume");
            NotifyPropertyChanged("PauseOrResumeText");
            MessageBox.Show(String.Format(Strings.AppAbortedMessage + ":\n{0}", e), Strings.AppAbortedCaption, MessageBoxButton.OK);
        }

        private void AddNewCubes(int n)
        {
            for (var i = 0; i < n; i++)
            {
                AddNewCube();
            }
        }

        private void AddNewCube()
        {
            var cubeViewModel = new CubeViewModel();
            cubeViewModel.CubeModel.NotifyCubeMoved += (sender, arguments) => NeighborCalculator.CalculateNeighbors(CubeViewModels);
            if (AppRunner.IsRunning)
            {
                cubeViewModel.ImageSources = _imageSources;
            }
            CubeViewModels.Add(cubeViewModel);
        }

        public CubeSet CubeSet
        {
            get
            {
                var cubeSet = new CubeSet();
                foreach (var cube in CubeViewModels)
                {
                    cubeSet.Add(cube.CubeModel);
                }

                return cubeSet;
            }
        }

    }
}


text:
'use strict';

describe('Service: Toast', function () {

  beforeEach(module('<%= appPrefix %>App'));

  // ---  --- //

  it('should contain a Toast service', function () {
    inject(function (Toast) {
      expect(Toast).toBeDefined();
    });
  });

  it('should have exposed properties', function () {
    inject(function (Toast) {
      expect(Toast.toast).toBeDefined();
      expect(Toast.notYetImplemented).toBeDefined();
    });
  });

  // TODO: test the actual DOM manipulation logic
});


text:
layout: api
title: toTimeString
permalink: toTimeString/index.html
filename: api/toTimeString.md
---


text:
package io.github.astrapi69.bundle.app.panels.start;

public enum BundleStart
{
	CONNECT, CREATE, NONE

}


text:
<?php
/**
 * @package WordPress
 * @subpackage ShopBox Theme
 */

require_once(dirname(__FILE__) . "lib/php/class-nimbus-theme.php");
require_once(dirname(__FILE__) . "lib/php/class-nimbus-utilities.php");

//////////////////////////////
//  Theme Utility Functions //
//////////////////////////////

class Theme extends NimbusTheme{
	//Make theme functions here
}
class ToolKit extends NimbusUtilities{

}
$Tools = new ToolKit();

$Theme = new Theme('Nimbus');

//$Theme->add_script('name', '../path/something');

//$Theme->add_style('name', '../path/something');

//$Theme->add_post_type('Products');


text:
prepare_recipe

include_recipe 'opsworks_ruby::configure'

every_enabled_application do |application, deploy|
  databases = []
  every_enabled_rds(self, application) do |rds|
    databases.push(Drivers::Db::Factory.build(self, application, rds: rds))
  end

  scm = Drivers::Scm::Factory.build(self, application)
  framework = Drivers::Framework::Factory.build(self, application, databases: databases)
  appserver = Drivers::Appserver::Factory.build(self, application)
  worker = Drivers::Worker::Factory.build(self, application, databases: databases)
  webserver = Drivers::Webserver::Factory.build(self, application)
  bundle_env = scm.class.adapter.to_s == 'Chef::Provider::Git' ? { 'GIT_SSH' => scm.out[:ssh_wrapper] } : {}

  fire_hook(:before_deploy, items: databases + [scm, framework, appserver, worker, webserver])

  deploy application['shortname'] do
    deploy_to deploy_dir(application)
    user node['deployer']['user'] || 'root'
    group www_group
    rollback_on_error true
    environment application['environment'].merge(framework.out[:deploy_environment] || {})

    keep_releases deploy[:keep_releases]
    create_dirs_before_symlink(
      (node['defaults']['deploy']['create_dirs_before_symlink'] + Array.wrap(deploy[:create_dirs_before_symlink])).uniq
    )
    purge_before_symlink(
      (node['defaults']['deploy']['purge_before_symlink'] + Array.wrap(deploy[:purge_before_symlink])).uniq
    )
    symlink_before_migrate deploy[:symlink_before_migrate]
    symlinks(node['defaults']['deploy']['symlinks'].merge(deploy[:symlinks] || {}))

    scm.out.each do |scm_key, scm_value|
      send(scm_key, scm_value) if respond_to?(scm_key)
    end

    [appserver, webserver].each do |server|
      server.notifies[:deploy].each do |config|
        notifies config[:action],
                 config[:resource].respond_to?(:call) ? config[:resource].call(application) : config[:resource],
                 config[:timer]
      end
    end

    migration_command(framework.out[:migration_command]) if framework.out[:migration_command]
    migrate framework.out[:migrate]
    before_migrate do
      perform_bundle_install(shared_path, bundle_env)

      fire_hook(:deploy_before_migrate, items: databases + [scm, framework, appserver, worker, webserver])

      run_callback_from_file(File.join(release_path, 'deploy', 'before_migrate.rb'))
    end

    before_symlink do
      perform_bundle_install(shared_path, bundle_env) unless framework.out[:migrate]

      fire_hook(:deploy_before_symlink, items: databases + [scm, framework, appserver, worker, webserver])

      run_callback_from_file(File.join(release_path, 'deploy', 'before_symlink.rb'))
    end

    before_restart do
      directory File.join(release_path, '.git') do
        recursive true
        action :delete
      end if scm.out[:remove_scm_files]

      fire_hook(:deploy_before_restart, items: databases + [scm, framework, appserver, worker, webserver])

      run_callback_from_file(File.join(release_path, 'deploy', 'before_restart.rb'))
    end

    after_restart do
      fire_hook(:deploy_after_restart, items: databases + [scm, framework, appserver, worker, webserver])

      run_callback_from_file(File.join(release_path, 'deploy', 'after_restart.rb'))
    end
  end

  fire_hook(:after_deploy, items: databases + [scm, framework, appserver, worker, webserver])
end


text:
    /* jshint ignore:start */
(function() {
    'use strict';

    angular
        .module('medicamentos')
        .factory('MedicamentosForm', factory);

    function factory() {

      var getFormFields = function(disabled) {

        var fields = [
  				{
  					key: 'nombre_medicamento',
  					type: 'input',
  					templateOptions: {
              label: 'Nombre del medicamento:',
              placeholder: 'Nombre',
  						disabled: disabled
  			    }
  				},
          {
            key: 'nombre_laboratorio',
            type: 'input',
            templateOptions: {
              label: 'Nombre del laboratorio:',
              placeholder: 'Laboratorio',
              disabled: disabled
            }
          }
  			];

        return fields;

      };

      var service = {
        getFormFields: getFormFields
      };

      return service;

  }

})();
  /* jshint ignore:end */


text:
package com.jersey.service;

import com.jersey.dto.request.UserProfileIn;
import com.jersey.dto.response.GenericResponse;

public interface CommonService {

	GenericResponse saveUserProfile(UserProfileIn req);

}


text:
CREATE TABLE customer_broad_parts (
  c_nationkey INT4,
  c_name    TEXT,
  c_address    TEXT,
  c_phone    TEXT,
  c_acctbal    FLOAT8,
  c_mktsegment    TEXT,
  c_comment    TEXT
) PARTITION BY COLUMN (c_custkey    INT4);